Skip to content

Commit

Permalink
esm: require braces for modules code
Browse files Browse the repository at this point in the history
PR-URL: #49657
Backport-PR-URL: #50669
Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com>
Reviewed-By: Jacob Smith <jacob@frende.me>
  • Loading branch information
GeoffreyBooth authored and targos committed Nov 23, 2023
1 parent fe26f8a commit 957725f
Show file tree
Hide file tree
Showing 12 changed files with 181 additions and 132 deletions.
12 changes: 10 additions & 2 deletions .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -53,10 +53,10 @@ module.exports = {
overrides: [
{
files: [
'test/es-module/test-esm-type-flag.js',
'test/es-module/test-esm-type-flag-alias.js',
'*.mjs',
'test/es-module/test-esm-example-loader.js',
'test/es-module/test-esm-type-flag.js',
'test/es-module/test-esm-type-flag-alias.js',
],
parserOptions: { sourceType: 'module' },
},
Expand Down Expand Up @@ -111,6 +111,14 @@ module.exports = {
},
] },
},
{
files: [
'lib/internal/modules/**/*.js',
],
rules: {
'curly': 'error',
},
},
],
rules: {
// ESLint built-in rules
Expand Down
109 changes: 67 additions & 42 deletions lib/internal/modules/cjs/loader.js
Original file line number Diff line number Diff line change
Expand Up @@ -172,7 +172,7 @@ function stat(filename) {
filename = path.toNamespacedPath(filename);
if (statCache !== null) {
const result = statCache.get(filename);
if (result !== undefined) return result;
if (result !== undefined) { return result; }
}
const result = internalModuleStat(filename);
if (statCache !== null && result >= 0) {
Expand All @@ -196,8 +196,9 @@ ObjectDefineProperty(Module, '_stat', {

function updateChildren(parent, child, scan) {
const children = parent?.children;
if (children && !(scan && ArrayPrototypeIncludes(children, child)))
if (children && !(scan && ArrayPrototypeIncludes(children, child))) {
ArrayPrototypePush(children, child);
}
}

function reportModuleToWatchMode(filename) {
Expand Down Expand Up @@ -379,13 +380,16 @@ function readPackageScope(checkPath) {
do {
separatorIndex = StringPrototypeLastIndexOf(checkPath, sep);
checkPath = StringPrototypeSlice(checkPath, 0, separatorIndex);
if (StringPrototypeEndsWith(checkPath, sep + 'node_modules'))
if (StringPrototypeEndsWith(checkPath, sep + 'node_modules')) {
return false;
}
const pjson = _readPackage(checkPath + sep);
if (pjson.exists) return {
data: pjson,
path: checkPath,
};
if (pjson.exists) {
return {
data: pjson,
path: checkPath,
};
}
} while (separatorIndex > rootSeparatorIndex);
return false;
}
Expand Down Expand Up @@ -438,7 +442,7 @@ const realpathCache = new SafeMap();
// absolute realpath.
function tryFile(requestPath, isMain) {
const rc = _stat(requestPath);
if (rc !== 0) return;
if (rc !== 0) { return; }
if (getOptionValue('--preserve-symlinks') && !isMain) {
return path.resolve(requestPath);
}
Expand Down Expand Up @@ -472,15 +476,15 @@ function findLongestRegisteredExtension(filename) {
let startIndex = 0;
while ((index = StringPrototypeIndexOf(name, '.', startIndex)) !== -1) {
startIndex = index + 1;
if (index === 0) continue; // Skip dotfiles like .gitignore
if (index === 0) { continue; } // Skip dotfiles like .gitignore
currentExtension = StringPrototypeSlice(name, index);
if (Module._extensions[currentExtension]) return currentExtension;
if (Module._extensions[currentExtension]) { return currentExtension; }
}
return '.js';
}

function trySelfParentPath(parent) {
if (!parent) return false;
if (!parent) { return false; }

if (parent.filename) {
return parent.filename;
Expand All @@ -494,7 +498,7 @@ function trySelfParentPath(parent) {
}

function trySelf(parentPath, request) {
if (!parentPath) return false;
if (!parentPath) { return false; }

const { data: pkg, path: pkgPath } = readPackageScope(parentPath);
if (!pkg || pkg.exports == null || pkg.name === undefined) {
Expand All @@ -516,8 +520,9 @@ function trySelf(parentPath, request) {
pathToFileURL(pkgPath + '/package.json'), expansion, pkg,
pathToFileURL(parentPath), getCjsConditions()), parentPath, pkgPath);
} catch (e) {
if (e.code === 'ERR_MODULE_NOT_FOUND')
if (e.code === 'ERR_MODULE_NOT_FOUND') {
throw createEsmNotFoundErr(request, pkgPath + '/package.json');
}
throw e;
}
}
Expand All @@ -530,8 +535,7 @@ function resolveExports(nmPath, request) {
// The implementation's behavior is meant to mirror resolution in ESM.
const { 1: name, 2: expansion = '' } =
RegExpPrototypeExec(EXPORTS_PATTERN, request) || kEmptyObject;
if (!name)
return;
if (!name) { return; }
const pkgPath = path.resolve(nmPath, name);
const pkg = _readPackage(pkgPath);
if (pkg.exists && pkg.exports != null) {
Expand All @@ -541,8 +545,9 @@ function resolveExports(nmPath, request) {
pathToFileURL(pkgPath + '/package.json'), '.' + expansion, pkg, null,
getCjsConditions()), null, pkgPath);
} catch (e) {
if (e.code === 'ERR_MODULE_NOT_FOUND')
if (e.code === 'ERR_MODULE_NOT_FOUND') {
throw createEsmNotFoundErr(request, pkgPath + '/package.json');
}
throw e;
}
}
Expand All @@ -564,8 +569,9 @@ Module._findPath = function(request, paths, isMain) {

const cacheKey = request + '\x00' + ArrayPrototypeJoin(paths, '\x00');
const entry = Module._pathCache[cacheKey];
if (entry)
if (entry) {
return entry;
}

let exts;
const trailingSlash = request.length > 0 &&
Expand Down Expand Up @@ -603,12 +609,15 @@ Module._findPath = function(request, paths, isMain) {
for (let i = 0; i < paths.length; i++) {
// Don't search further if path doesn't exist and request is inside the path
const curPath = paths[i];
if (insidePath && curPath && _stat(curPath) < 1) continue;
if (insidePath && curPath && _stat(curPath) < 1) {
continue;
}

if (!absoluteRequest) {
const exportsResolved = resolveExports(curPath, request);
if (exportsResolved)
if (exportsResolved) {
return exportsResolved;
}
}

const basePath = path.resolve(curPath, request);
Expand Down Expand Up @@ -640,16 +649,18 @@ Module._findPath = function(request, paths, isMain) {

if (!filename) {
// Try it with each of the extensions
if (exts === undefined)
if (exts === undefined) {
exts = ObjectKeys(Module._extensions);
}
filename = tryExtensions(basePath, exts, isMain);
}
}

if (!filename && rc === 1) { // Directory.
// try it with each of the extensions at "index"
if (exts === undefined)
if (exts === undefined) {
exts = ObjectKeys(Module._extensions);
}
filename = tryPackage(basePath, exts, isMain, request);
}

Expand Down Expand Up @@ -685,8 +696,9 @@ if (isWindows) {
// path.resolve will make sure from.length >=3 in Windows.
if (StringPrototypeCharCodeAt(from, from.length - 1) ===
CHAR_BACKWARD_SLASH &&
StringPrototypeCharCodeAt(from, from.length - 2) === CHAR_COLON)
StringPrototypeCharCodeAt(from, from.length - 2) === CHAR_COLON) {
return [from + 'node_modules'];
}

const paths = [];
for (let i = from.length - 1, p = 0, last = from.length; i >= 0; --i) {
Expand All @@ -699,11 +711,12 @@ if (isWindows) {
if (code === CHAR_BACKWARD_SLASH ||
code === CHAR_FORWARD_SLASH ||
code === CHAR_COLON) {
if (p !== nmLen)
if (p !== nmLen) {
ArrayPrototypePush(
paths,
StringPrototypeSlice(from, 0, last) + '\\node_modules',
);
}
last = i;
p = 0;
} else if (p !== -1) {
Expand All @@ -724,8 +737,9 @@ if (isWindows) {
from = path.resolve(from);
// Return early not only to avoid unnecessary work, but to *avoid* returning
// an array of two items for a root: [ '//node_modules', '/node_modules' ]
if (from === '/')
if (from === '/') {
return ['/node_modules'];
}

// note: this approach *only* works when the path is guaranteed
// to be absolute. Doing a fully-edge-case-correct path.split
Expand All @@ -734,11 +748,12 @@ if (isWindows) {
for (let i = from.length - 1, p = 0, last = from.length; i >= 0; --i) {
const code = StringPrototypeCharCodeAt(from, i);
if (code === CHAR_FORWARD_SLASH) {
if (p !== nmLen)
if (p !== nmLen) {
ArrayPrototypePush(
paths,
StringPrototypeSlice(from, 0, last) + '/node_modules',
);
}
last = i;
p = 0;
} else if (p !== -1) {
Expand Down Expand Up @@ -815,14 +830,15 @@ const CircularRequirePrototypeWarningProxy = new Proxy({}, {
// Allow __esModule access in any case because it is used in the output
// of transpiled code to determine whether something comes from an
// ES module, and is not used as a regular key of `module.exports`.
if (prop in target || prop === '__esModule') return target[prop];
if (prop in target || prop === '__esModule') { return target[prop]; }
emitCircularRequireWarning(prop);
return undefined;
},

getOwnPropertyDescriptor(target, prop) {
if (ObjectPrototypeHasOwnProperty(target, prop) || prop === '__esModule')
if (ObjectPrototypeHasOwnProperty(target, prop) || prop === '__esModule') {
return ObjectGetOwnPropertyDescriptor(target, prop);
}
emitCircularRequireWarning(prop);
return undefined;
},
Expand Down Expand Up @@ -866,8 +882,9 @@ Module._load = function(request, parent, isMain) {
const cachedModule = Module._cache[filename];
if (cachedModule !== undefined) {
updateChildren(parent, cachedModule, true);
if (!cachedModule.loaded)
if (!cachedModule.loaded) {
return getExportsForCircularRequire(cachedModule);
}
return cachedModule.exports;
}
delete relativeResolveCache[relResolveCacheIdentifier];
Expand All @@ -892,8 +909,9 @@ Module._load = function(request, parent, isMain) {
updateChildren(parent, cachedModule, true);
if (!cachedModule.loaded) {
const parseCachedModule = cjsParseCache.get(cachedModule);
if (!parseCachedModule || parseCachedModule.loaded)
if (!parseCachedModule || parseCachedModule.loaded) {
return getExportsForCircularRequire(cachedModule);
}
parseCachedModule.loaded = true;
} else {
return cachedModule.exports;
Expand Down Expand Up @@ -976,8 +994,9 @@ Module._resolveFilename = function(request, parent, isMain, options) {
const lookupPaths = Module._resolveLookupPaths(request, fakeParent);

for (let j = 0; j < lookupPaths.length; j++) {
if (!ArrayPrototypeIncludes(paths, lookupPaths[j]))
if (!ArrayPrototypeIncludes(paths, lookupPaths[j])) {
ArrayPrototypePush(paths, lookupPaths[j]);
}
}
}
}
Expand All @@ -1001,8 +1020,9 @@ Module._resolveFilename = function(request, parent, isMain, options) {
getCjsConditions()), parentPath,
pkg.path);
} catch (e) {
if (e.code === 'ERR_MODULE_NOT_FOUND')
if (e.code === 'ERR_MODULE_NOT_FOUND') {
throw createEsmNotFoundErr(request);
}
throw e;
}
}
Expand All @@ -1020,7 +1040,7 @@ Module._resolveFilename = function(request, parent, isMain, options) {

// Look up the filename first, since that's the cache key.
const filename = Module._findPath(request, paths, isMain);
if (filename) return filename;
if (filename) { return filename; }
const requireStack = [];
for (let cursor = parent;
cursor;
Expand All @@ -1041,13 +1061,15 @@ Module._resolveFilename = function(request, parent, isMain, options) {

function finalizeEsmResolution(resolved, parentPath, pkgPath) {
const { encodedSepRegEx } = require('internal/modules/esm/resolve');
if (RegExpPrototypeExec(encodedSepRegEx, resolved) !== null)
if (RegExpPrototypeExec(encodedSepRegEx, resolved) !== null) {
throw new ERR_INVALID_MODULE_SPECIFIER(
resolved, 'must not include encoded "/" or "\\" characters', parentPath);
}
const filename = fileURLToPath(resolved);
const actual = tryFile(filename);
if (actual)
if (actual) {
return actual;
}
const err = createEsmNotFoundErr(filename,
path.resolve(pkgPath, 'package.json'));
throw err;
Expand All @@ -1057,8 +1079,9 @@ function createEsmNotFoundErr(request, path) {
// eslint-disable-next-line no-restricted-syntax
const err = new Error(`Cannot find module '${request}'`);
err.code = 'MODULE_NOT_FOUND';
if (path)
if (path) {
err.path = path;
}
// TODO(BridgeAR): Add the requireStack as well.
return err;
}
Expand All @@ -1073,8 +1096,9 @@ Module.prototype.load = function(filename) {

const extension = findLongestRegisteredExtension(filename);
// allow .mjs to be overridden
if (StringPrototypeEndsWith(filename, '.mjs') && !Module._extensions['.mjs'])
if (StringPrototypeEndsWith(filename, '.mjs') && !Module._extensions['.mjs']) {
throw new ERR_REQUIRE_ESM(filename, true);
}

Module._extensions[extension](this, filename);
this.loaded = true;
Expand All @@ -1085,8 +1109,9 @@ Module.prototype.load = function(filename) {
// Preemptively cache
if ((module?.module === undefined ||
module.module.getStatus() < kEvaluated) &&
!cascadedLoader.cjsCache.has(this))
!cascadedLoader.cjsCache.has(this)) {
cascadedLoader.cjsCache.set(this, exports);
}
};

// Loads a module at the given file path. Returns that module's
Expand Down Expand Up @@ -1213,7 +1238,7 @@ Module.prototype._compile = function(content, filename) {
const exports = this.exports;
const thisValue = exports;
const module = this;
if (requireDepth === 0) statCache = new SafeMap();
if (requireDepth === 0) { statCache = new SafeMap(); }
if (inspectorWrapper) {
result = inspectorWrapper(compiledWrapper, thisValue, exports,
require, module, filename, dirname);
Expand All @@ -1222,7 +1247,7 @@ Module.prototype._compile = function(content, filename) {
[exports, require, module, filename, dirname]);
}
hasLoadedAnyUserCJSModule = true;
if (requireDepth === 0) statCache = null;
if (requireDepth === 0) { statCache = null; }
return result;
};

Expand Down Expand Up @@ -1379,8 +1404,7 @@ Module._initPaths = function() {
};

Module._preloadModules = function(requests) {
if (!ArrayIsArray(requests))
return;
if (!ArrayIsArray(requests)) { return; }

isPreloading = true;

Expand All @@ -1396,8 +1420,9 @@ Module._preloadModules = function(requests) {
throw e;
}
}
for (let n = 0; n < requests.length; n++)
for (let n = 0; n < requests.length; n++) {
internalRequire(parent, requests[n]);
}
isPreloading = false;
};

Expand Down

0 comments on commit 957725f

Please sign in to comment.