From cdbf4d80d4b0633ff3c0e0efb9267c02354e399c Mon Sep 17 00:00:00 2001 From: Sebastian Landwehr Date: Tue, 9 Jan 2024 00:15:56 +0000 Subject: [PATCH] fix: fix module-root.js package.json in subpath --- src/utils/module-root.js | 16 +++++++++------- .../esm-packagejson-subpath/package.json | 7 +++++++ test/special/bin.js | 6 ++++++ 3 files changed, 22 insertions(+), 7 deletions(-) create mode 100644 test/node_modules/esm-packagejson-subpath/package.json diff --git a/src/utils/module-root.js b/src/utils/module-root.js index d990568b..5fde89c0 100644 --- a/src/utils/module-root.js +++ b/src/utils/module-root.js @@ -7,14 +7,16 @@ export default (...args) => { const name = args.find((arg) => typeof arg === 'string'); const options = args.find((arg) => typeof arg === 'object') || {}; options.cwd = options.cwd || process.cwd(); - let pkg; try { - const fullpath = name - ? resolveFrom(options.cwd, name) - : callsite()[1].getFileName(); - pkg = findup('package.json', { cwd: path.dirname(fullpath) }); + if (name) { + const fullpath = resolveFrom(options.cwd, name); + const index = fullpath.indexOf(name.replace(/\//g, path.sep)) + return fullpath.substring(0, index + name.length) + } else { + return path.dirname(findup('package.json', { cwd: path.dirname(callsite()[1].getFileName()) })) + } } catch { - pkg = resolveFrom(options.cwd, `${args[0]}/package.json`); + const pkg = resolveFrom(options.cwd, `${name}/package.json`); + return path.resolve(path.dirname(pkg)); } - return path.resolve(path.dirname(pkg)); }; diff --git a/test/node_modules/esm-packagejson-subpath/package.json b/test/node_modules/esm-packagejson-subpath/package.json new file mode 100644 index 00000000..5263064d --- /dev/null +++ b/test/node_modules/esm-packagejson-subpath/package.json @@ -0,0 +1,7 @@ +{ + "bin": { + "esm-packagejson-subpath": "bin" + }, + "exports": "./dist/index.js", + "type": "module" +} diff --git a/test/special/bin.js b/test/special/bin.js index 1e2e7f06..715a7467 100644 --- a/test/special/bin.js +++ b/test/special/bin.js @@ -125,6 +125,12 @@ const testCases = [ dependencies: ['@scoped/scoped-binary-package'], expected: ['@scoped/scoped-binary-package'], }, + { + name: 'esm package.json in subpath', + script: 'esm-packagejson-subpath', + dependencies: ['esm-packagejson-subpath'], + expected: ['esm-packagejson-subpath'], + }, { name: 'esm', script: 'esm',