lbundle
Version:
Small zero-configuration bundler build on top of Rollup.js and SWC for NPM libraries
99 lines (96 loc) • 2.7 kB
JavaScript
import resolver from 'resolve';
import { resolve, legacy } from 'resolve.exports';
import { arrayFmt } from './array-fmt.mjs';
import path from 'path';
import { fileURLToPath } from 'url';
const baseDir = path.dirname(fileURLToPath(import.meta.url));
const packageFilterBuilder = function() {
let path = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : '.', opts = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
const conditions = opts.conditions ?? [
'style',
'import',
'require'
];
const fields = opts.fields ?? [
'style',
'module',
'main'
];
return (pkg)=>{
// Check `exports` fields
try {
const resolvedExport = resolve(pkg, path, {
conditions,
unsafe: true
});
if (typeof resolvedExport === 'string') {
pkg.main = resolvedExport;
return pkg;
}
} catch {
/* noop */ }
// Check independent fields
try {
const resolvedField = legacy(pkg, {
fields,
browser: false
});
if (typeof resolvedField === 'string') {
pkg.main = resolvedField;
return pkg;
}
} catch {
/* noop */ }
return pkg;
};
};
const defaultOpts = {
caller: 'Resolver',
basedirs: [
baseDir
],
extensions: [
'.mjs',
'.js',
'.cjs',
'.json'
],
preserveSymlinks: true,
packageFilter: packageFilterBuilder()
};
const resolverSync = function(id) {
let options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
try {
return resolver.sync(id, {
...options,
pathFilter: (pkg, _path, relativePath)=>{
const result = resolve(pkg, relativePath);
if (result) return result[0];
return '';
}
});
} catch {
return;
}
};
function resolveSync(ids, userOpts) {
const options = {
...defaultOpts,
...userOpts
};
for (const basedir of options.basedirs){
const opts = {
...options,
basedir,
basedirs: undefined,
caller: undefined
};
for (const id of ids){
const resolved = resolverSync(id, opts);
if (resolved) return resolved;
}
}
throw new Error(`${options.caller} could not resolve ${arrayFmt(ids)}`);
}
export { packageFilterBuilder, resolveSync };
//# sourceMappingURL=resolve.mjs.map