Skip to content

Commit

Permalink
module: refactor to use normalizeRequirableId in the CJS module loader
Browse files Browse the repository at this point in the history
`BuiltinModule.normalizeRequirableId()` was introduced in
#47779 to fix a bug in the require
function of SEAs and Snapshots, so that built-in modules with the
`node:` scheme could be required correctly. This change makes more use
of this API instead of `BuiltinModule.canBeRequiredByUsers()` and
`BuiltinModule.canBeRequiredWithoutScheme()` to reduce chances of
such bugs.

Signed-off-by: Darshan Sen <raisinten@gmail.com>
PR-URL: #47896
Reviewed-By: Geoffrey Booth <webadmin@geoffreybooth.com>
Reviewed-By: Yagiz Nizipli <yagiz@nizipli.com>
Reviewed-By: Mohammed Keyvanzadeh <mohammadkeyvanzade94@gmail.com>
  • Loading branch information
RaisinTen authored and targos committed May 12, 2023
1 parent 00668fc commit c19385c
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 22 deletions.
15 changes: 7 additions & 8 deletions lib/internal/bootstrap/realm.js
Original file line number Diff line number Diff line change
Expand Up @@ -287,17 +287,16 @@ class BuiltinModule {
}

static normalizeRequirableId(id) {
let normalizedId = id;
if (StringPrototypeStartsWith(id, 'node:')) {
normalizedId = StringPrototypeSlice(id, 5);
}

if (!BuiltinModule.canBeRequiredByUsers(normalizedId) ||
(id === normalizedId && !BuiltinModule.canBeRequiredWithoutScheme(normalizedId))) {
return undefined;
const normalizedId = StringPrototypeSlice(id, 5);
if (BuiltinModule.canBeRequiredByUsers(normalizedId)) {
return normalizedId;
}
} else if (BuiltinModule.canBeRequiredWithoutScheme(id)) {
return id;
}

return normalizedId;
return undefined;
}

static isBuiltin(id) {
Expand Down
16 changes: 2 additions & 14 deletions lib/internal/modules/cjs/loader.js
Original file line number Diff line number Diff line change
Expand Up @@ -792,12 +792,7 @@ if (isWindows) {
}

Module._resolveLookupPaths = function(request, parent) {
if ((
StringPrototypeStartsWith(request, 'node:') &&
BuiltinModule.canBeRequiredByUsers(StringPrototypeSlice(request, 5))
) || (
BuiltinModule.canBeRequiredWithoutScheme(request)
)) {
if (BuiltinModule.normalizeRequirableId(request)) {
debug('looking for %j in []', request);
return null;
}
Expand Down Expand Up @@ -989,14 +984,7 @@ Module._load = function(request, parent, isMain) {
};

Module._resolveFilename = function(request, parent, isMain, options) {
if (
(
StringPrototypeStartsWith(request, 'node:') &&
BuiltinModule.canBeRequiredByUsers(StringPrototypeSlice(request, 5))
) || (
BuiltinModule.canBeRequiredWithoutScheme(request)
)
) {
if (BuiltinModule.normalizeRequirableId(request)) {
return request;
}

Expand Down

0 comments on commit c19385c

Please sign in to comment.