module: package "exports" error refinements

Backport-PR-URL: https://github.com/nodejs/node/pull/32610
PR-URL: https://github.com/nodejs/node/pull/31625
Reviewed-By: Jan Krems <jan.krems@gmail.com>
This commit is contained in:
Guy Bedford authored and Myles Borins committed 2020-04-03 15:56:41 -04:00
1 parent 05091d48e3
commit c537afb18c
10 files changed
+331 -219

No files matched your search

+20
View File
@@ -1301,6 +1301,12 @@ An invalid HTTP token was supplied.
An IP address is not valid.
<a id="ERR_INVALID_MODULE_SPECIFIER"></a>
### `ERR_INVALID_MODULE_SPECIFIER`
The imported module string is an invalid URL, package name, or package subpath
specifier.
<a id="ERR_INVALID_OPT_VALUE"></a>
### `ERR_INVALID_OPT_VALUE`
@@ -1316,6 +1322,12 @@ An invalid or unknown file encoding was passed.
An invalid `package.json` file was found which failed parsing.
<a id="ERR_INVALID_PACKAGE_TARGET"></a>
### `ERR_INVALID_PACKAGE_TARGET`
The `package.json` [exports][] field contains an invalid target mapping value
for the attempted module resolution.
<a id="ERR_INVALID_PERFORMANCE_MARK"></a>
### `ERR_INVALID_PERFORMANCE_MARK`
@@ -1616,6 +1628,13 @@ A non-context-aware native addon was loaded in a process that disallows them.
A given value is out of the accepted range.
<a id="ERR_PACKAGE_PATH_NOT_EXPORTED"></a>
### `ERR_PACKAGE_PATH_NOT_EXPORTED`
The `package.json` [exports][] field does not export the requested subpath.
Because exports are encapsulated, private internal modules that are not exported
cannot be imported through the package resolution, unless using an absolute URL.
<a id="ERR_REQUIRE_ESM"></a>
### `ERR_REQUIRE_ESM`
@@ -2457,6 +2476,7 @@ such as `process.stdout.on('data')`.
[crypto digest algorithm]: crypto.html#crypto_crypto_gethashes
[domains]: domain.html
[event emitter-based]: events.html#events_class_eventemitter
[exports]: esm.html#esm_package_exports
[file descriptors]: https://en.wikipedia.org/wiki/File_descriptor
[policy]: policy.html
[stream-based]: stream.html
+44 -31
View File
@@ -1446,6 +1446,17 @@ of these top-level routines unless stated otherwise.
_defaultEnv_ is the conditional environment name priority array,
`["node", "import"]`.
The resolver can throw the following errors:
* _Invalid Module Specifier_: Module specifier is an invalid URL, package name
or package subpath specifier.
* _Invalid Package Configuration_: package.json configuration is invalid or
contains an invalid configuration.
* _Invalid Package Target_: Package exports define a target module within the
package that is an invalid type or string target.
* _Package Path Not Exported_: Package exports do not define or permit a target
subpath in the package for the given module.
* _Module Not Found_: The package or module requested does not exist.
<details>
<summary>Resolver algorithm specification</summary>
@@ -1456,7 +1467,7 @@ _defaultEnv_ is the conditional environment name priority array,
> 1. Set _resolvedURL_ to the result of parsing and reserializing
> _specifier_ as a URL.
> 1. Otherwise, if _specifier_ starts with _"/"_, then
> 1. Throw an _Invalid Specifier_ error.
> 1. Throw an _Invalid Module Specifier_ error.
> 1. Otherwise, if _specifier_ starts with _"./"_ or _"../"_, then
> 1. Set _resolvedURL_ to the URL resolution of _specifier_ relative to
> _parentURL_.
@@ -1466,7 +1477,7 @@ _defaultEnv_ is the conditional environment name priority array,
> **PACKAGE_RESOLVE**(_specifier_, _parentURL_).
> 1. If _resolvedURL_ contains any percent encodings of _"/"_ or _"\\"_ (_"%2f"_
> and _"%5C"_ respectively), then
> 1. Throw an _Invalid Specifier_ error.
> 1. Throw an _Invalid Module Specifier_ error.
> 1. If _resolvedURL_ does not end with a trailing _"/"_ and the file at
> _resolvedURL_ does not exist, then
> 1. Throw a _Module Not Found_ error.
@@ -1480,14 +1491,14 @@ _defaultEnv_ is the conditional environment name priority array,
> 1. Let _packageName_ be *undefined*.
> 1. Let _packageSubpath_ be *undefined*.
> 1. If _packageSpecifier_ is an empty string, then
> 1. Throw an _Invalid Specifier_ error.
> 1. Throw an _Invalid Module Specifier_ error.
> 1. Otherwise,
> 1. If _packageSpecifier_ does not contain a _"/"_ separator, then
> 1. Throw an _Invalid Specifier_ error.
> 1. Throw an _Invalid Module Specifier_ error.
> 1. Set _packageName_ to the substring of _packageSpecifier_
> until the second _"/"_ separator or the end of the string.
> 1. If _packageName_ starts with _"."_ or contains _"\\"_ or _"%"_, then
> 1. Throw an _Invalid Specifier_ error.
> 1. Throw an _Invalid Module Specifier_ error.
> 1. Let _packageSubpath_ be _undefined_.
> 1. If the length of _packageSpecifier_ is greater than the length of
> _packageName_, then
@@ -1495,7 +1506,7 @@ _defaultEnv_ is the conditional environment name priority array,
> _packageSpecifier_ from the position at the length of _packageName_.
> 1. If _packageSubpath_ contains any _"."_ or _".."_ segments or percent
> encoded strings for _"/"_ or _"\\"_, then
> 1. Throw an _Invalid Specifier_ error.
> 1. Throw an _Invalid Module Specifier_ error.
> 1. Set _selfUrl_ to the result of
> **SELF_REFERENCE_RESOLVE**(_packageName_, _packageSubpath_, _parentURL_).
> 1. If _selfUrl_ isn't empty, return _selfUrl_.
@@ -1552,7 +1563,7 @@ _defaultEnv_ is the conditional environment name priority array,
> 1. Throw a _Module Not Found_ error.
> 1. If _pjson.exports_ is not **null** or **undefined**, then
> 1. If _exports_ is an Object with both a key starting with _"."_ and a key
> not starting with _"."_, throw an "Invalid Package Configuration" error.
> not starting with _"."_, throw an _Invalid Package Configuration_ error.
> 1. If _pjson.exports_ is a String or Array, or an Object containing no
> keys starting with _"."_, then
> 1. Return **PACKAGE_EXPORTS_TARGET_RESOLVE**(_packageURL_,
@@ -1561,6 +1572,7 @@ _defaultEnv_ is the conditional environment name priority array,
> 1. Let _mainExport_ be the _"."_ property in _pjson.exports_.
> 1. Return **PACKAGE_EXPORTS_TARGET_RESOLVE**(_packageURL_,
> _mainExport_, _""_).
> 1. Throw a _Package Path Not Exported_ error.
> 1. If _pjson.main_ is a String, then
> 1. Let _resolvedMain_ be the URL resolution of _packageURL_, "/", and
> _pjson.main_.
@@ -1575,7 +1587,7 @@ _defaultEnv_ is the conditional environment name priority array,
**PACKAGE_EXPORTS_RESOLVE**(_packageURL_, _packagePath_, _exports_)
> 1. If _exports_ is an Object with both a key starting with _"."_ and a key not
> starting with _"."_, throw an "Invalid Package Configuration" error.
> starting with _"."_, throw an _Invalid Package Configuration_ error.
> 1. If _exports_ is an Object and all keys of _exports_ start with _"."_, then
> 1. Set _packagePath_ to _"./"_ concatenated with _packagePath_.
> 1. If _packagePath_ is a key of _exports_, then
@@ -1591,43 +1603,44 @@ _defaultEnv_ is the conditional environment name priority array,
> of the length of _directory_.
> 1. Return **PACKAGE_EXPORTS_TARGET_RESOLVE**(_packageURL_, _target_,
> _subpath_, _defaultEnv_).
> 1. Throw a _Module Not Found_ error.
> 1. Throw a _Package Path Not Exported_ error.
**PACKAGE_EXPORTS_TARGET_RESOLVE**(_packageURL_, _target_, _subpath_, _env_)
> 1. If _target_ is a String, then
> 1. If _target_ does not start with _"./"_, throw a _Module Not Found_
> error.
> 1. If _subpath_ has non-zero length and _target_ does not end with _"/"_,
> throw a _Module Not Found_ error.
> 1. If _target_ or _subpath_ contain any _"node_modules"_ segments including
> _"node_modules"_ percent-encoding, throw a _Module Not Found_ error.
> 1.If _target_ is a String, then
> 1. If _target_ does not start with _"./"_ or contains any _"node_modules"_
> segments including _"node_modules"_ percent-encoding, throw an
> _Invalid Package Target_ error.
> 1. Let _resolvedTarget_ be the URL resolution of the concatenation of
> _packageURL_ and _target_.
> 1. If _resolvedTarget_ is contained in _packageURL_, then
> 1. Let _resolved_ be the URL resolution of the concatenation of
> _subpath_ and _resolvedTarget_.
> 1. If _resolved_ is contained in _resolvedTarget_, then
> 1. Return _resolved_.
> 1. If _resolvedTarget_ is not contained in _packageURL_, throw an
> _Invalid Package Target_ error.
> 1. If _subpath_ has non-zero length and _target_ does not end with _"/"_,
> throw an _Invalid Module Specifier_ error.
> 1. Let _resolved_ be the URL resolution of the concatenation of
> _subpath_ and _resolvedTarget_.
> 1. If _resolved_ is not contained in _resolvedTarget_, throw an
> _Invalid Module Specifier_ error.
> 1. Return _resolved_.
> 1. Otherwise, if _target_ is a non-null Object, then
> 1. If _exports_ contains any index property keys, as defined in ECMA-262
> [6.1.7 Array Index][], throw an _Invalid Package Configuration_ error.
> 1. For each property _p_ of _target_, in object insertion order as,
> 1. If _env_ contains an entry for _p_, then
> 1. Let _targetValue_ be the value of the _p_ property in _target_.
> 1. Let _resolved_ be the result of **PACKAGE_EXPORTS_TARGET_RESOLVE**
> (_packageURL_, _targetValue_, _subpath_, _env_).
> 1. Assert: _resolved_ is a String.
> 1. Return _resolved_.
> 1. Return the result of **PACKAGE_EXPORTS_TARGET_RESOLVE**(
> _packageURL_, _targetValue_, _subpath_, _env_), continuing the
> loop on any _Package Path Not Exported_ error.
> 1. Throw a _Package Path Not Exported_ error.
> 1. Otherwise, if _target_ is an Array, then
> 1. If _target.length is zero, throw an _Invalid Package Target_ error.
> 1. For each item _targetValue_ in _target_, do
> 1. If _targetValue_ is an Array, continue the loop.
> 1. Let _resolved_ be the result of
> **PACKAGE_EXPORTS_TARGET_RESOLVE**(_packageURL_, _targetValue_,
> _subpath_, _env_), continuing the loop on abrupt completion.
> 1. Assert: _resolved_ is a String.
> 1. Return _resolved_.
> 1. Throw a _Module Not Found_ error.
> 1. Return the result of **PACKAGE_EXPORTS_TARGET_RESOLVE**(_packageURL_,
> _targetValue_, _subpath_, _env_), continuing the loop on any
> _Package Path Not Exported_ or _Invalid Package Target_ error.
> 1. Throw the last fallback resolution error.
> 1. Otherwise throw an _Invalid Package Target_ error.
**ESM_FORMAT**(_url_)
+28 -1
View File
@@ -13,16 +13,20 @@
const {
ArrayIsArray,
Error,
JSONStringify,
Map,
MathAbs,
NumberIsInteger,
ObjectDefineProperty,
ObjectKeys,
StringPrototypeSlice,
Symbol,
SymbolFor,
WeakMap,
} = primordials;
const sep = process.platform === 'win32' ? '\\' : '/';
const messages = new Map();
const codes = {};
@@ -1065,6 +1069,11 @@ E('ERR_INVALID_FILE_URL_PATH', 'File URL path %s', TypeError);
E('ERR_INVALID_HANDLE_TYPE', 'This handle type cannot be sent', TypeError);
E('ERR_INVALID_HTTP_TOKEN', '%s must be a valid HTTP token ["%s"]', TypeError);
E('ERR_INVALID_IP_ADDRESS', 'Invalid IP address: %s', TypeError);
E('ERR_INVALID_MODULE_SPECIFIER', (pkgPath, subpath) => {
assert(subpath !== '.');
return `Package subpath '${subpath}' is not a valid module request for the ` +
`"exports" resolution of ${pkgPath}${sep}package.json`;
}, TypeError);
E('ERR_INVALID_OPT_VALUE', (name, value) =>
`The value "${String(value)}" is invalid for option "${name}"`,
TypeError,
@@ -1072,7 +1081,17 @@ E('ERR_INVALID_OPT_VALUE', (name, value) =>
E('ERR_INVALID_OPT_VALUE_ENCODING',
'The value "%s" is invalid for option "encoding"', TypeError);
E('ERR_INVALID_PACKAGE_CONFIG',
'Invalid package config for \'%s\', %s', Error);
`Invalid package config %s${sep}package.json, %s`, Error);
E('ERR_INVALID_PACKAGE_TARGET', (pkgPath, key, subpath, target) => {
if (key === '.') {
return `Invalid "exports" main target ${JSONStringify(target)} defined ` +
`in the package config ${pkgPath}${sep}package.json`;
} else {
return `Invalid "exports" target ${JSONStringify(target)} defined for '${
StringPrototypeSlice(key, 0, -subpath.length || key.length)}' in the ` +
`package config ${pkgPath}${sep}package.json`;
}
}, Error);
E('ERR_INVALID_PERFORMANCE_MARK',
'The "%s" performance mark has not been set', Error);
E('ERR_INVALID_PROTOCOL',
@@ -1216,6 +1235,14 @@ E('ERR_OUT_OF_RANGE',
msg += ` It must be ${range}. Received ${received}`;
return msg;
}, RangeError);
E('ERR_PACKAGE_PATH_NOT_EXPORTED', (pkgPath, subpath) => {
if (subpath === '.') {
return `No "exports" main resolved in ${pkgPath}${sep}package.json`;
} else {
return `Package subpath '${subpath}' is not defined by "exports" in ${
pkgPath}${sep}package.json`;
}
}, Error);
E('ERR_REQUIRE_ESM',
(filename, parentPath = null, packageJsonPath = null) => {
let msg = `Must use import to load ES Module: ${filename}`;
+51 -53
View File
@@ -83,6 +83,9 @@ const {
ERR_INVALID_ARG_VALUE,
ERR_INVALID_OPT_VALUE,
ERR_INVALID_PACKAGE_CONFIG,
ERR_INVALID_PACKAGE_TARGET,
ERR_INVALID_MODULE_SPECIFIER,
ERR_PACKAGE_PATH_NOT_EXPORTED,
ERR_REQUIRE_ESM
} = require('internal/errors').codes;
const { validateString } = require('internal/validators');
@@ -500,13 +503,9 @@ function applyExports(basePath, expansion) {
if (ObjectPrototypeHasOwnProperty(pkgExports, mappingKey)) {
const mapping = pkgExports[mappingKey];
return resolveExportsTarget(pathToFileURL(basePath + '/'), mapping, '',
basePath, mappingKey);
mappingKey);
}
// Fallback to CJS main lookup when no main export is defined
if (mappingKey === '.')
return basePath;
let dirMatch = '';
for (const candidateKey of ObjectKeys(pkgExports)) {
if (candidateKey[candidateKey.length - 1] !== '/') continue;
@@ -520,18 +519,11 @@ function applyExports(basePath, expansion) {
const mapping = pkgExports[dirMatch];
const subpath = StringPrototypeSlice(mappingKey, dirMatch.length);
return resolveExportsTarget(pathToFileURL(basePath + '/'), mapping,
subpath, basePath, mappingKey);
subpath, mappingKey);
}
}
// Fallback to CJS main lookup when no main export is defined
if (mappingKey === '.')
return basePath;
// eslint-disable-next-line no-restricted-syntax
const e = new Error(`Package exports for '${basePath}' do not define ` +
`a '${mappingKey}' subpath`);
e.code = 'MODULE_NOT_FOUND';
throw e;
throw new ERR_PACKAGE_PATH_NOT_EXPORTED(basePath, mappingKey);
}
// This only applies to requests of a specific form:
@@ -566,39 +558,53 @@ function isArrayIndex(p) {
return n >= 0 && n < (2 ** 32) - 1;
}
function resolveExportsTarget(pkgPath, target, subpath, basePath, mappingKey) {
function resolveExportsTarget(baseUrl, target, subpath, mappingKey) {
if (typeof target === 'string') {
if (target.startsWith('./') &&
(subpath.length === 0 || target.endsWith('/'))) {
const resolvedTarget = new URL(target, pkgPath);
const pkgPathPath = pkgPath.pathname;
const resolvedTargetPath = resolvedTarget.pathname;
if (StringPrototypeStartsWith(resolvedTargetPath, pkgPathPath) &&
let resolvedTarget, resolvedTargetPath;
const pkgPathPath = baseUrl.pathname;
if (StringPrototypeStartsWith(target, './')) {
resolvedTarget = new URL(target, baseUrl);
resolvedTargetPath = resolvedTarget.pathname;
if (!StringPrototypeStartsWith(resolvedTargetPath, pkgPathPath) ||
StringPrototypeIndexOf(resolvedTargetPath, '/node_modules/',
pkgPathPath.length - 1) === -1) {
const resolved = new URL(subpath, resolvedTarget);
const resolvedPath = resolved.pathname;
if (StringPrototypeStartsWith(resolvedPath, resolvedTargetPath) &&
StringPrototypeIndexOf(resolvedPath, '/node_modules/',
pkgPathPath.length - 1) === -1) {
return fileURLToPath(resolved);
}
}
pkgPathPath.length - 1) !== -1)
resolvedTarget = undefined;
}
if (subpath.length > 0 && target[target.length - 1] !== '/')
resolvedTarget = undefined;
if (resolvedTarget === undefined)
throw new ERR_INVALID_PACKAGE_TARGET(StringPrototypeSlice(baseUrl.pathname
, 0, -1), mappingKey, subpath, target);
const resolved = new URL(subpath, resolvedTarget);
const resolvedPath = resolved.pathname;
if (StringPrototypeStartsWith(resolvedPath, resolvedTargetPath) &&
StringPrototypeIndexOf(resolvedPath, '/node_modules/',
pkgPathPath.length - 1) === -1) {
return fileURLToPath(resolved);
}
throw new ERR_INVALID_MODULE_SPECIFIER(StringPrototypeSlice(baseUrl.pathname
, 0, -1), mappingKey);
} else if (ArrayIsArray(target)) {
if (target.length === 0)
throw new ERR_INVALID_PACKAGE_TARGET(StringPrototypeSlice(baseUrl.pathname
, 0, -1), mappingKey, subpath, target);
for (const targetValue of target) {
if (ArrayIsArray(targetValue)) continue;
try {
return resolveExportsTarget(pkgPath, targetValue, subpath, basePath,
mappingKey);
return resolveExportsTarget(baseUrl, targetValue, subpath, mappingKey);
} catch (e) {
if (e.code !== 'MODULE_NOT_FOUND') throw e;
if (e.code !== 'ERR_PACKAGE_PATH_NOT_EXPORTED' &&
e.code !== 'ERR_INVALID_PACKAGE_TARGET')
throw e;
}
}
// Throw last fallback error
resolveExportsTarget(baseUrl, target[target.length - 1], subpath,
mappingKey);
assert(false);
} else if (typeof target === 'object' && target !== null) {
const keys = ObjectKeys(target);
if (keys.some(isArrayIndex)) {
throw new ERR_INVALID_PACKAGE_CONFIG(basePath, '"exports" cannot ' +
throw new ERR_INVALID_PACKAGE_CONFIG(baseUrl, '"exports" cannot ' +
'contain numeric property keys.');
}
for (const p of keys) {
@@ -607,34 +613,26 @@ function resolveExportsTarget(pkgPath, target, subpath, basePath, mappingKey) {
case 'require':
try {
emitExperimentalWarning('Conditional exports');
const result = resolveExportsTarget(pkgPath, target[p], subpath,
basePath, mappingKey);
return result;
return resolveExportsTarget(baseUrl, target[p], subpath,
mappingKey);
} catch (e) {
if (e.code !== 'MODULE_NOT_FOUND') throw e;
if (e.code !== 'ERR_PACKAGE_PATH_NOT_EXPORTED') throw e;
}
break;
case 'default':
try {
return resolveExportsTarget(pkgPath, target.default, subpath,
basePath, mappingKey);
return resolveExportsTarget(baseUrl, target.default, subpath,
mappingKey);
} catch (e) {
if (e.code !== 'MODULE_NOT_FOUND') throw e;
if (e.code !== 'ERR_PACKAGE_PATH_NOT_EXPORTED') throw e;
}
}
}
throw new ERR_PACKAGE_PATH_NOT_EXPORTED(
StringPrototypeSlice(baseUrl.pathname, 0, -1), mappingKey + subpath);
}
let e;
if (mappingKey !== '.') {
// eslint-disable-next-line no-restricted-syntax
e = new Error(`Package exports for '${basePath}' do not define a ` +
`valid '${mappingKey}' target${subpath ? ' for ' + subpath : ''}`);
} else {
// eslint-disable-next-line no-restricted-syntax
e = new Error(`No valid exports main found for '${basePath}'`);
}
e.code = 'MODULE_NOT_FOUND';
throw e;
throw new ERR_INVALID_PACKAGE_TARGET(
StringPrototypeSlice(baseUrl.pathname, 0, -1), mappingKey, subpath, target);
}
Module._findPath = function(request, paths, isMain) {
+147 -111
View File
@@ -832,10 +832,20 @@ void ThrowExportsNotFound(Environment* env,
const std::string& subpath,
const URL& pjson_url,
const URL& base) {
const std::string msg = "Package exports for " +
pjson_url.ToFilePath() + " do not define a '" + subpath +
"' subpath, imported from " + base.ToFilePath();
node::THROW_ERR_MODULE_NOT_FOUND(env, msg.c_str());
const std::string msg = "Package subpath '" + subpath + "' is not defined" +
" by \"exports\" in " + pjson_url.ToFilePath() + " imported from " +
base.ToFilePath();
node::THROW_ERR_PACKAGE_PATH_NOT_EXPORTED(env, msg.c_str());
}
void ThrowSubpathInvalid(Environment* env,
const std::string& subpath,
const URL& pjson_url,
const URL& base) {
const std::string msg = "Package subpath '" + subpath + "' is not a valid " +
"module request for the \"exports\" resolution of " +
pjson_url.ToFilePath() + " imported from " + base.ToFilePath();
node::THROW_ERR_INVALID_MODULE_SPECIFIER(env, msg.c_str());
}
void ThrowExportsInvalid(Environment* env,
@@ -844,14 +854,15 @@ void ThrowExportsInvalid(Environment* env,
const URL& pjson_url,
const URL& base) {
if (subpath.length()) {
const std::string msg = "Cannot resolve package exports target '" + target +
"' matched for '" + subpath + "' in " + pjson_url.ToFilePath() +
", imported from " + base.ToFilePath();
node::THROW_ERR_MODULE_NOT_FOUND(env, msg.c_str());
const std::string msg = "Invalid \"exports\" target \"" + target +
"\" defined for '" + subpath + "' in the package config " +
pjson_url.ToFilePath() + " imported from " + base.ToFilePath();
node::THROW_ERR_INVALID_PACKAGE_TARGET(env, msg.c_str());
} else {
const std::string msg = "Cannot resolve package main '" + target + "' in" +
pjson_url.ToFilePath() + ", imported from " + base.ToFilePath();
node::THROW_ERR_MODULE_NOT_FOUND(env, msg.c_str());
const std::string msg = "Invalid \"exports\" main target " + target +
" defined in the package config " + pjson_url.ToFilePath() +
" imported from " + base.ToFilePath();
node::THROW_ERR_INVALID_PACKAGE_TARGET(env, msg.c_str());
}
}
@@ -861,14 +872,20 @@ void ThrowExportsInvalid(Environment* env,
const URL& pjson_url,
const URL& base) {
Local<String> target_string;
if (target->ToString(env->context()).ToLocal(&target_string)) {
Utf8Value target_utf8(env->isolate(), target_string);
std::string target_str(*target_utf8, target_utf8.length());
if (target->IsArray()) {
target_str = '[' + target_str + ']';
}
ThrowExportsInvalid(env, subpath, target_str, pjson_url, base);
if (target->IsObject()) {
if (!v8::JSON::Stringify(env->context(), target.As<v8::Object>(),
v8::String::Empty(env->isolate())).ToLocal(&target_string))
return;
} else {
if (!target->ToString(env->context()).ToLocal(&target_string))
return;
}
Utf8Value target_utf8(env->isolate(), target_string);
std::string target_str(*target_utf8, target_utf8.length());
if (target->IsArray()) {
target_str = '[' + target_str + ']';
}
ThrowExportsInvalid(env, subpath, target_str, pjson_url, base);
}
Maybe<URL> ResolveExportsTargetString(Environment* env,
@@ -876,18 +893,13 @@ Maybe<URL> ResolveExportsTargetString(Environment* env,
const std::string& subpath,
const std::string& match,
const URL& pjson_url,
const URL& base,
bool throw_invalid = true) {
const URL& base) {
if (target.substr(0, 2) != "./") {
if (throw_invalid) {
ThrowExportsInvalid(env, match, target, pjson_url, base);
}
ThrowExportsInvalid(env, match, target, pjson_url, base);
return Nothing<URL>();
}
if (subpath.length() > 0 && target.back() != '/') {
if (throw_invalid) {
ThrowExportsInvalid(env, match, target, pjson_url, base);
}
ThrowExportsInvalid(env, match, target, pjson_url, base);
return Nothing<URL>();
}
URL resolved(target, pjson_url);
@@ -896,9 +908,7 @@ Maybe<URL> ResolveExportsTargetString(Environment* env,
if (resolved_path.find(pkg_path) != 0 ||
resolved_path.find("/node_modules/", pkg_path.length() - 1) !=
std::string::npos) {
if (throw_invalid) {
ThrowExportsInvalid(env, match, target, pjson_url, base);
}
ThrowExportsInvalid(env, match, target, pjson_url, base);
return Nothing<URL>();
}
if (subpath.length() == 0) return Just(resolved);
@@ -907,9 +917,7 @@ Maybe<URL> ResolveExportsTargetString(Environment* env,
if (subpath_resolved_path.find(resolved_path) != 0 ||
subpath_resolved_path.find("/node_modules/", pkg_path.length() - 1)
!= std::string::npos) {
if (throw_invalid) {
ThrowExportsInvalid(env, match, target + subpath, pjson_url, base);
}
ThrowSubpathInvalid(env, match + subpath, pjson_url, base);
return Nothing<URL>();
}
return Just(subpath_resolved);
@@ -939,15 +947,14 @@ Maybe<URL> ResolveExportsTarget(Environment* env,
Local<Value> target,
const std::string& subpath,
const std::string& pkg_subpath,
const URL& base,
bool throw_invalid = true) {
const URL& base) {
Isolate* isolate = env->isolate();
Local<Context> context = env->context();
if (target->IsString()) {
Utf8Value target_utf8(isolate, target.As<String>());
std::string target_str(*target_utf8, target_utf8.length());
Maybe<URL> resolved = ResolveExportsTargetString(env, target_str, subpath,
pkg_subpath, pjson_url, base, throw_invalid);
pkg_subpath, pjson_url, base);
if (resolved.IsNothing()) {
return Nothing<URL>();
}
@@ -956,40 +963,56 @@ Maybe<URL> ResolveExportsTarget(Environment* env,
Local<Array> target_arr = target.As<Array>();
const uint32_t length = target_arr->Length();
if (length == 0) {
if (throw_invalid) {
ThrowExportsInvalid(env, pkg_subpath, target, pjson_url, base);
}
ThrowExportsInvalid(env, pkg_subpath, target, pjson_url, base);
return Nothing<URL>();
}
for (uint32_t i = 0; i < length; i++) {
auto target_item = target_arr->Get(context, i).ToLocalChecked();
if (!target_item->IsArray()) {
{
TryCatchScope try_catch(env);
Maybe<URL> resolved = ResolveExportsTarget(env, pjson_url,
target_item, subpath, pkg_subpath, base, false);
if (resolved.IsNothing()) continue;
target_item, subpath, pkg_subpath, base);
if (resolved.IsNothing()) {
CHECK(try_catch.HasCaught());
if (try_catch.Exception().IsEmpty()) return Nothing<URL>();
Local<Object> e;
if (!try_catch.Exception()->ToObject(context).ToLocal(&e))
return Nothing<URL>();
Local<Value> code;
if (!e->Get(context, env->code_string()).ToLocal(&code))
return Nothing<URL>();
Local<String> code_string;
if (!code->ToString(context).ToLocal(&code_string))
return Nothing<URL>();
Utf8Value code_utf8(env->isolate(), code_string);
if (strcmp(*code_utf8, "ERR_PACKAGE_PATH_NOT_EXPORTED") == 0 ||
strcmp(*code_utf8, "ERR_INVALID_PACKAGE_TARGET") == 0) {
continue;
}
try_catch.ReThrow();
return Nothing<URL>();
}
CHECK(!try_catch.HasCaught());
return FinalizeResolution(env, resolved.FromJust(), base);
}
}
if (throw_invalid) {
auto invalid = target_arr->Get(context, length - 1).ToLocalChecked();
Maybe<URL> resolved = ResolveExportsTarget(env, pjson_url, invalid,
subpath, pkg_subpath, base, true);
CHECK(resolved.IsNothing());
}
auto invalid = target_arr->Get(context, length - 1).ToLocalChecked();
Maybe<URL> resolved = ResolveExportsTarget(env, pjson_url, invalid,
subpath, pkg_subpath, base);
CHECK(resolved.IsNothing());
return Nothing<URL>();
} else if (target->IsObject()) {
Local<Object> target_obj = target.As<Object>();
Local<Array> target_obj_keys =
target_obj->GetOwnPropertyNames(context).ToLocalChecked();
Local<Value> conditionalTarget;
bool matched = false;
for (uint32_t i = 0; i < target_obj_keys->Length(); ++i) {
Local<Value> key =
target_obj_keys->Get(context, i).ToLocalChecked();
if (IsArrayIndex(env, key)) {
const std::string msg = "Invalid package config for " +
pjson_url.ToFilePath() + ", \"exports\" cannot contain numeric " +
"property keys.";
const std::string msg = "Invalid package config " +
pjson_url.ToFilePath() + " imported from " + base.ToFilePath() +
". \"exports\" cannot contain numeric property keys.";
node::THROW_ERR_INVALID_PACKAGE_CONFIG(env, msg.c_str());
return Nothing<URL>();
}
@@ -1000,35 +1023,60 @@ Maybe<URL> ResolveExportsTarget(Environment* env,
key->ToString(context).ToLocalChecked());
std::string key_str(*key_utf8, key_utf8.length());
if (key_str == "node" || key_str == "import") {
matched = true;
conditionalTarget = target_obj->Get(context, key).ToLocalChecked();
Maybe<URL> resolved = ResolveExportsTarget(env, pjson_url,
conditionalTarget, subpath, pkg_subpath, base, false);
if (!resolved.IsNothing()) {
{
TryCatchScope try_catch(env);
Maybe<URL> resolved = ResolveExportsTarget(env, pjson_url,
conditionalTarget, subpath, pkg_subpath, base);
if (resolved.IsNothing()) {
CHECK(try_catch.HasCaught());
if (try_catch.Exception().IsEmpty()) return Nothing<URL>();
Local<Object> e;
if (!try_catch.Exception()->ToObject(context).ToLocal(&e))
return Nothing<URL>();
Local<Value> code;
if (!e->Get(context, env->code_string()).ToLocal(&code))
return Nothing<URL>();
Local<String> code_string;
if (!code->ToString(context).ToLocal(&code_string))
return Nothing<URL>();
Utf8Value code_utf8(env->isolate(), code_string);
if (strcmp(*code_utf8, "ERR_PACKAGE_PATH_NOT_EXPORTED") == 0)
continue;
try_catch.ReThrow();
return Nothing<URL>();
}
CHECK(!try_catch.HasCaught());
ProcessEmitExperimentalWarning(env, "Conditional exports");
return resolved;
}
} else if (key_str == "default") {
matched = true;
conditionalTarget = target_obj->Get(context, key).ToLocalChecked();
Maybe<URL> resolved = ResolveExportsTarget(env, pjson_url,
conditionalTarget, subpath, pkg_subpath, base, false);
if (!resolved.IsNothing()) {
{
TryCatchScope try_catch(env);
Maybe<URL> resolved = ResolveExportsTarget(env, pjson_url,
conditionalTarget, subpath, pkg_subpath, base);
if (resolved.IsNothing()) {
CHECK(try_catch.HasCaught() && !try_catch.Exception().IsEmpty());
auto e = try_catch.Exception()->ToObject(context).ToLocalChecked();
auto code = e->Get(context, env->code_string()).ToLocalChecked();
Utf8Value code_utf8(env->isolate(),
code->ToString(context).ToLocalChecked());
std::string code_str(*code_utf8, code_utf8.length());
if (code_str == "ERR_PACKAGE_PATH_NOT_EXPORTED") continue;
try_catch.ReThrow();
return Nothing<URL>();
}
CHECK(!try_catch.HasCaught());
ProcessEmitExperimentalWarning(env, "Conditional exports");
return resolved;
}
}
}
if (matched && throw_invalid) {
Maybe<URL> resolved = ResolveExportsTarget(env, pjson_url,
conditionalTarget, subpath, pkg_subpath, base, true);
CHECK(resolved.IsNothing());
return Nothing<URL>();
}
}
if (throw_invalid) {
ThrowExportsInvalid(env, pkg_subpath, target, pjson_url, base);
ThrowExportsNotFound(env, pkg_subpath, pjson_url, base);
return Nothing<URL>();
}
ThrowExportsInvalid(env, pkg_subpath, target, pjson_url, base);
return Nothing<URL>();
}
@@ -1050,8 +1098,8 @@ Maybe<bool> IsConditionalExportsMainSugar(Environment* env,
if (i == 0) {
isConditionalSugar = curIsConditionalSugar;
} else if (isConditionalSugar != curIsConditionalSugar) {
const std::string msg = "Cannot resolve package exports in " +
pjson_url.ToFilePath() + ", imported from " + base.ToFilePath() + ". " +
const std::string msg = "Invalid package config " + pjson_url.ToFilePath()
+ " imported from " + base.ToFilePath() + ". " +
"\"exports\" cannot contain some keys starting with '.' and some not." +
" The exports object must either be an object of package subpath keys" +
" or an object of main entry condition name keys only.";
@@ -1076,8 +1124,7 @@ Maybe<URL> PackageMainResolve(Environment* env,
if (isConditionalExportsMainSugar.IsNothing())
return Nothing<URL>();
if (isConditionalExportsMainSugar.FromJust()) {
return ResolveExportsTarget(env, pjson_url, exports, "", "", base,
true);
return ResolveExportsTarget(env, pjson_url, exports, "", "", base);
} else if (exports->IsObject()) {
Local<Object> exports_obj = exports.As<Object>();
if (exports_obj->HasOwnProperty(env->context(), env->dot_string())
@@ -1085,10 +1132,12 @@ Maybe<URL> PackageMainResolve(Environment* env,
Local<Value> target =
exports_obj->Get(env->context(), env->dot_string())
.ToLocalChecked();
return ResolveExportsTarget(env, pjson_url, target, "", "", base,
true);
return ResolveExportsTarget(env, pjson_url, target, "", "", base);
}
}
std::string msg = "No \"exports\" main resolved in " +
pjson_url.ToFilePath();
node::THROW_ERR_PACKAGE_PATH_NOT_EXPORTED(env, msg.c_str());
}
if (pcfg.has_main == HasMain::Yes) {
URL resolved(pcfg.main, pjson_url);
@@ -1180,39 +1229,6 @@ Maybe<URL> PackageExportsResolve(Environment* env,
return Nothing<URL>();
}
Maybe<URL> ResolveSelf(Environment* env,
const std::string& pkg_name,
const std::string& pkg_subpath,
const URL& base) {
const PackageConfig* pcfg;
if (GetPackageScopeConfig(env, base, base).To(&pcfg) &&
pcfg->exists == Exists::Yes) {
// TODO(jkrems): Find a way to forward the pair/iterator already generated
// while executing GetPackageScopeConfig
URL pjson_url("");
bool found_pjson = false;
for (auto it = env->package_json_cache.begin();
it != env->package_json_cache.end();
++it) {
if (&it->second == pcfg) {
pjson_url = URL::FromFilePath(it->first);
found_pjson = true;
}
}
if (!found_pjson || pcfg->name != pkg_name) return Nothing<URL>();
if (pcfg->exports.IsEmpty()) return Nothing<URL>();
if (pkg_subpath == "./") {
return Just(URL("./", pjson_url));
} else if (!pkg_subpath.length()) {
return PackageMainResolve(env, pjson_url, *pcfg, base);
} else {
return PackageExportsResolve(env, pjson_url, pkg_subpath, *pcfg, base);
}
}
return Nothing<URL>();
}
Maybe<URL> PackageResolve(Environment* env,
const std::string& specifier,
const URL& base) {
@@ -1253,10 +1269,30 @@ Maybe<URL> PackageResolve(Environment* env,
pkg_subpath = "." + specifier.substr(sep_index);
}
Maybe<URL> self_url = ResolveSelf(env, pkg_name, pkg_subpath, base);
if (self_url.IsJust()) {
ProcessEmitExperimentalWarning(env, "Package name self resolution");
return self_url;
// ResolveSelf
const PackageConfig* pcfg;
if (GetPackageScopeConfig(env, base, base).To(&pcfg) &&
pcfg->exists == Exists::Yes) {
// TODO(jkrems): Find a way to forward the pair/iterator already generated
// while executing GetPackageScopeConfig
URL pjson_url("");
bool found_pjson = false;
for (const auto& it : env->package_json_cache) {
if (&it.second == pcfg) {
pjson_url = URL::FromFilePath(it.first);
found_pjson = true;
}
}
if (found_pjson && pcfg->name == pkg_name && !pcfg->exports.IsEmpty()) {
ProcessEmitExperimentalWarning(env, "Package name self resolution");
if (pkg_subpath == "./") {
return Just(URL("./", pjson_url));
} else if (!pkg_subpath.length()) {
return PackageMainResolve(env, pjson_url, *pcfg, base);
} else {
return PackageExportsResolve(env, pjson_url, pkg_subpath, *pcfg, base);
}
}
}
URL pjson_url("./node_modules/" + pkg_name + "/package.json", &base);
+3 -1
View File
@@ -41,7 +41,8 @@ void OnFatalError(const char* location, const char* message);
V(ERR_OSSL_EVP_INVALID_DIGEST, Error) \
V(ERR_INVALID_ARG_TYPE, TypeError) \
V(ERR_INVALID_MODULE_SPECIFIER, TypeError) \
V(ERR_INVALID_PACKAGE_CONFIG, SyntaxError) \
V(ERR_INVALID_PACKAGE_CONFIG, Error) \
V(ERR_INVALID_PACKAGE_TARGET, Error) \
V(ERR_INVALID_TRANSFER_OBJECT, TypeError) \
V(ERR_MEMORY_ALLOCATION_FAILED, Error) \
V(ERR_MISSING_ARGS, TypeError) \
@@ -51,6 +52,7 @@ void OnFatalError(const char* location, const char* message);
V(ERR_NON_CONTEXT_AWARE_DISABLED, Error) \
V(ERR_MODULE_NOT_FOUND, Error) \
V(ERR_OUT_OF_RANGE, RangeError) \
V(ERR_PACKAGE_PATH_NOT_EXPORTED, Error) \
V(ERR_SCRIPT_EXECUTION_INTERRUPTED, Error) \
V(ERR_SCRIPT_EXECUTION_TIMEOUT, Error) \
V(ERR_STRING_TOO_LONG, Error) \
+32 -22
View File
@@ -33,7 +33,7 @@ import fromInside from '../fixtures/node_modules/pkgexports/lib/hole.js';
['pkgexports/resolve-self', isRequire ?
{ default: 'self-cjs' } : { default: 'self-mjs' }],
// Resolve self sugar
['pkgexports-sugar', { default: 'main' }]
['pkgexports-sugar', { default: 'main' }],
]);
for (const [validSpecifier, expected] of validSpecifiers) {
@@ -54,48 +54,59 @@ import fromInside from '../fixtures/node_modules/pkgexports/lib/hole.js';
// Sugar cases still encapsulate
['pkgexports-sugar/not-exported.js', './not-exported.js'],
['pkgexports-sugar2/not-exported.js', './not-exported.js'],
// Conditional exports with no match are "not exported" errors
['pkgexports/invalid1', './invalid1'],
['pkgexports/invalid4', './invalid4'],
]);
const invalidExports = new Map([
// Even though 'pkgexports/sub/asdf.js' works, alternate "path-like"
// variants do not to prevent confusion and accidental loopholes.
['pkgexports/sub/./../asdf.js', './sub/./../asdf.js'],
// Directory mappings require a trailing / to work
['pkgexports/missingtrailer/x', './missingtrailer/'],
// This path steps back inside the package but goes through an exports
// target that escapes the package, so we still catch that as invalid
['pkgexports/belowdir/pkgexports/asdf.js', './belowdir/pkgexports/asdf.js'],
['pkgexports/belowdir/pkgexports/asdf.js', './belowdir/'],
// This target file steps below the package
['pkgexports/belowfile', './belowfile'],
// Directory mappings require a trailing / to work
['pkgexports/missingtrailer/x', './missingtrailer/x'],
// Invalid target handling
['pkgexports/null', './null'],
['pkgexports/invalid1', './invalid1'],
['pkgexports/invalid2', './invalid2'],
['pkgexports/invalid3', './invalid3'],
['pkgexports/invalid4', './invalid4'],
// Missing / invalid fallbacks
['pkgexports/nofallback1', './nofallback1'],
['pkgexports/nofallback2', './nofallback2'],
// Reaching into nested node_modules
['pkgexports/nodemodules', './nodemodules'],
// Self resolve invalid
['pkgexports/resolve-self-invalid', './invalid2'],
]);
const invalidSpecifiers = new Map([
// Even though 'pkgexports/sub/asdf.js' works, alternate "path-like"
// variants do not to prevent confusion and accidental loopholes.
['pkgexports/sub/./../asdf.js', './sub/./../asdf.js'],
]);
for (const [specifier, subpath] of undefinedExports) {
loadFixture(specifier).catch(mustCall((err) => {
strictEqual(err.code, (isRequire ? '' : 'ERR_') + 'MODULE_NOT_FOUND');
assertStartsWith(err.message, 'Package exports');
assertIncludes(err.message, `do not define a '${subpath}' subpath`);
strictEqual(err.code, 'ERR_PACKAGE_PATH_NOT_EXPORTED');
assertStartsWith(err.message, 'Package subpath ');
assertIncludes(err.message, subpath);
}));
}
for (const [specifier, subpath] of invalidExports) {
loadFixture(specifier).catch(mustCall((err) => {
strictEqual(err.code, (isRequire ? '' : 'ERR_') + 'MODULE_NOT_FOUND');
assertStartsWith(err.message, (isRequire ? 'Package exports' :
'Cannot resolve'));
assertIncludes(err.message, isRequire ?
`do not define a valid '${subpath}' target` :
`matched for '${subpath}'`);
strictEqual(err.code, 'ERR_INVALID_PACKAGE_TARGET');
assertStartsWith(err.message, 'Invalid "exports"');
assertIncludes(err.message, subpath);
}));
}
for (const [specifier, subpath] of invalidSpecifiers) {
loadFixture(specifier).catch(mustCall((err) => {
strictEqual(err.code, 'ERR_INVALID_MODULE_SPECIFIER');
assertStartsWith(err.message, 'Package subpath ');
assertIncludes(err.message, subpath);
}));
}
@@ -103,8 +114,8 @@ import fromInside from '../fixtures/node_modules/pkgexports/lib/hole.js';
// of falling back to main
if (isRequire) {
loadFixture('pkgexports-main').catch(mustCall((err) => {
strictEqual(err.code, 'MODULE_NOT_FOUND');
assertStartsWith(err.message, 'No valid export');
strictEqual(err.code, 'ERR_PACKAGE_PATH_NOT_EXPORTED');
assertStartsWith(err.message, 'No "exports" main ');
}));
}
@@ -131,8 +142,7 @@ import fromInside from '../fixtures/node_modules/pkgexports/lib/hole.js';
// Sugar conditional exports main mixed failure case
loadFixture('pkgexports-sugar-fail').catch(mustCall((err) => {
strictEqual(err.code, 'ERR_INVALID_PACKAGE_CONFIG');
assertStartsWith(err.message, (isRequire ? 'Invalid package' :
'Cannot resolve'));
assertStartsWith(err.message, 'Invalid package');
assertIncludes(err.message, '"exports" cannot contain some keys starting ' +
'with \'.\' and some not. The exports object must either be an object of ' +
'package subpath keys or an object of main entry condition name keys ' +
+4
View File
@@ -35,6 +35,10 @@
"./resolve-self": {
"require": "./resolve-self.js",
"import": "./resolve-self.mjs"
},
"./resolve-self-invalid": {
"require": "./resolve-self-invalid.js",
"import": "./resolve-self-invalid.mjs"
}
}
}
+1
View File
@@ -0,0 +1 @@
require('pkg-exports/invalid2');
+1
View File
@@ -0,0 +1 @@
import 'pkg-exports/invalid2';