• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1// Copyright Joyent, Inc. and other Node contributors.
2//
3// Permission is hereby granted, free of charge, to any person obtaining a
4// copy of this software and associated documentation files (the
5// "Software"), to deal in the Software without restriction, including
6// without limitation the rights to use, copy, modify, merge, publish,
7// distribute, sublicense, and/or sell copies of the Software, and to permit
8// persons to whom the Software is furnished to do so, subject to the
9// following conditions:
10//
11// The above copyright notice and this permission notice shall be included
12// in all copies or substantial portions of the Software.
13//
14// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
17// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
20// USE OR OTHER DEALINGS IN THE SOFTWARE.
21
22'use strict';
23
24const {
25  ArrayIsArray,
26  ArrayPrototypeFilter,
27  ArrayPrototypeIncludes,
28  ArrayPrototypeIndexOf,
29  ArrayPrototypeJoin,
30  ArrayPrototypeMap,
31  ArrayPrototypePush,
32  ArrayPrototypePushApply,
33  ArrayPrototypeSlice,
34  ArrayPrototypeSplice,
35  ArrayPrototypeUnshift,
36  ArrayPrototypeUnshiftApply,
37  Boolean,
38  Error,
39  JSONParse,
40  ObjectCreate,
41  ObjectDefineProperty,
42  ObjectFreeze,
43  ObjectGetOwnPropertyDescriptor,
44  ObjectGetPrototypeOf,
45  ObjectKeys,
46  ObjectPrototype,
47  ObjectPrototypeHasOwnProperty,
48  ObjectSetPrototypeOf,
49  Proxy,
50  ReflectApply,
51  ReflectSet,
52  RegExpPrototypeExec,
53  SafeMap,
54  SafeWeakMap,
55  String,
56  Symbol,
57  StringPrototypeCharAt,
58  StringPrototypeCharCodeAt,
59  StringPrototypeEndsWith,
60  StringPrototypeIndexOf,
61  StringPrototypeRepeat,
62  StringPrototypeSlice,
63  StringPrototypeSplit,
64  StringPrototypeStartsWith,
65} = primordials;
66
67// Map used to store CJS parsing data.
68const cjsParseCache = new SafeWeakMap();
69
70// Set first due to cycle with ESM loader functions.
71module.exports = {
72  wrapSafe, Module, cjsParseCache,
73  get hasLoadedAnyUserCJSModule() { return hasLoadedAnyUserCJSModule; },
74  initializeCJS,
75};
76
77const { BuiltinModule } = require('internal/bootstrap/realm');
78const {
79  maybeCacheSourceMap,
80} = require('internal/source_map/source_map_cache');
81const { pathToFileURL, fileURLToPath, isURL } = require('internal/url');
82const {
83  pendingDeprecate,
84  emitExperimentalWarning,
85  kEmptyObject,
86  setOwnProperty,
87  getLazy,
88} = require('internal/util');
89const {
90  internalCompileFunction,
91  makeContextifyScript,
92  runScriptInThisContext,
93} = require('internal/vm');
94
95const assert = require('internal/assert');
96const fs = require('fs');
97const path = require('path');
98const { internalModuleStat } = internalBinding('fs');
99const { safeGetenv } = internalBinding('credentials');
100const {
101  privateSymbols: {
102    require_private_symbol,
103  },
104} = internalBinding('util');
105const {
106  getCjsConditions,
107  initializeCjsConditions,
108  hasEsmSyntax,
109  loadBuiltinModule,
110  makeRequireFunction,
111  normalizeReferrerURL,
112  stripBOM,
113  toRealPath,
114} = require('internal/modules/helpers');
115const packageJsonReader = require('internal/modules/package_json_reader');
116const { getOptionValue, getEmbedderOptions } = require('internal/options');
117const policy = getLazy(
118  () => (getOptionValue('--experimental-policy') ? require('internal/process/policy') : null),
119);
120const shouldReportRequiredModules = getLazy(() => process.env.WATCH_REPORT_DEPENDENCIES);
121
122const getCascadedLoader = getLazy(
123  () => require('internal/process/esm_loader').esmLoader,
124);
125
126// Whether any user-provided CJS modules had been loaded (executed).
127// Used for internal assertions.
128let hasLoadedAnyUserCJSModule = false;
129
130const {
131  codes: {
132    ERR_INVALID_ARG_VALUE,
133    ERR_INVALID_MODULE_SPECIFIER,
134    ERR_REQUIRE_ESM,
135    ERR_UNKNOWN_BUILTIN_MODULE,
136  },
137  setArrowMessage,
138} = require('internal/errors');
139const { validateString } = require('internal/validators');
140
141const {
142  CHAR_BACKWARD_SLASH,
143  CHAR_COLON,
144  CHAR_DOT,
145  CHAR_FORWARD_SLASH,
146} = require('internal/constants');
147
148const {
149  isProxy,
150} = require('internal/util/types');
151
152const { kEvaluated } = internalBinding('module_wrap');
153const isWindows = process.platform === 'win32';
154
155const relativeResolveCache = ObjectCreate(null);
156
157let requireDepth = 0;
158let isPreloading = false;
159let statCache = null;
160
161/**
162 * Our internal implementation of `require`.
163 * @param {Module} module Parent module of what is being required
164 * @param {string} id Specifier of the child module being imported
165 */
166function internalRequire(module, id) {
167  validateString(id, 'id');
168  if (id === '') {
169    throw new ERR_INVALID_ARG_VALUE('id', id,
170                                    'must be a non-empty string');
171  }
172  requireDepth++;
173  try {
174    return Module._load(id, module, /* isMain */ false);
175  } finally {
176    requireDepth--;
177  }
178}
179
180/**
181 * Get a path's properties, using an in-memory cache to minimize lookups.
182 * @param {string} filename Absolute path to the file
183 */
184function stat(filename) {
185  filename = path.toNamespacedPath(filename);
186  if (statCache !== null) {
187    const result = statCache.get(filename);
188    if (result !== undefined) { return result; }
189  }
190  const result = internalModuleStat(filename);
191  if (statCache !== null && result >= 0) {
192    // Only set cache when `internalModuleStat(filename)` succeeds.
193    statCache.set(filename, result);
194  }
195  return result;
196}
197
198let _stat = stat;
199ObjectDefineProperty(Module, '_stat', {
200  __proto__: null,
201  get() { return _stat; },
202  set(stat) {
203    emitExperimentalWarning('Module._stat');
204    _stat = stat;
205    return true;
206  },
207  configurable: true,
208});
209
210/**
211 * Update the parent's children array with the child module.
212 * @param {Module} parent Module requiring the children
213 * @param {Module} child Module being required
214 * @param {boolean} scan Add the child to the parent's children if not already present
215 */
216function updateChildren(parent, child, scan) {
217  const children = parent?.children;
218  if (children && !(scan && ArrayPrototypeIncludes(children, child))) {
219    ArrayPrototypePush(children, child);
220  }
221}
222
223/**
224 * Tell the watch mode that a module was required.
225 * @param {string} filename Absolute path of the module
226 */
227function reportModuleToWatchMode(filename) {
228  if (shouldReportRequiredModules() && process.send) {
229    process.send({ 'watch:require': [filename] });
230  }
231}
232
233/**
234 * Tell the watch mode that a module was not found.
235 * @param {string} basePath The absolute path that errored
236 * @param {string[]} extensions The extensions that were tried
237 */
238function reportModuleNotFoundToWatchMode(basePath, extensions) {
239  if (shouldReportRequiredModules() && process.send) {
240    process.send({ 'watch:require': ArrayPrototypeMap(extensions, (ext) => path.resolve(`${basePath}${ext}`)) });
241  }
242}
243
244/** @type {Map<Module, Module>} */
245const moduleParentCache = new SafeWeakMap();
246/**
247 * Create a new module instance.
248 * @param {string} id
249 * @param {Module} parent
250 */
251function Module(id = '', parent) {
252  this.id = id;
253  this.path = path.dirname(id);
254  setOwnProperty(this, 'exports', {});
255  moduleParentCache.set(this, parent);
256  updateChildren(parent, this, false);
257  this.filename = null;
258  this.loaded = false;
259  this.children = [];
260  let redirects;
261  const manifest = policy()?.manifest;
262  if (manifest) {
263    const moduleURL = pathToFileURL(id);
264    redirects = manifest.getDependencyMapper(moduleURL);
265    // TODO(rafaelgss): remove the necessity of this branch
266    setOwnProperty(this, 'require', makeRequireFunction(this, redirects));
267    // eslint-disable-next-line no-proto
268    setOwnProperty(this.__proto__, 'require', makeRequireFunction(this, redirects));
269  }
270  this[require_private_symbol] = internalRequire;
271}
272
273/** @type {Record<string, Module>} */
274Module._cache = { __proto__: null };
275/** @type {Record<string, string>} */
276Module._pathCache = { __proto__: null };
277/** @type {Record<string, (module: Module, filename: string) => void>} */
278Module._extensions = { __proto__: null };
279/** @type {string[]} */
280let modulePaths = [];
281/** @type {string[]} */
282Module.globalPaths = [];
283
284let patched = false;
285
286/**
287 * Add the CommonJS wrapper around a module's source code.
288 * @param {string} script Module source code
289 */
290let wrap = function(script) { // eslint-disable-line func-style
291  return Module.wrapper[0] + script + Module.wrapper[1];
292};
293
294const wrapper = [
295  '(function (exports, require, module, __filename, __dirname) { ',
296  '\n});',
297];
298
299let wrapperProxy = new Proxy(wrapper, {
300  __proto__: null,
301
302  set(target, property, value, receiver) {
303    patched = true;
304    return ReflectSet(target, property, value, receiver);
305  },
306
307  defineProperty(target, property, descriptor) {
308    patched = true;
309    return ObjectDefineProperty(target, property, descriptor);
310  },
311});
312
313ObjectDefineProperty(Module, 'wrap', {
314  __proto__: null,
315  get() {
316    return wrap;
317  },
318
319  set(value) {
320    patched = true;
321    wrap = value;
322  },
323});
324
325ObjectDefineProperty(Module, 'wrapper', {
326  __proto__: null,
327  get() {
328    return wrapperProxy;
329  },
330
331  set(value) {
332    patched = true;
333    wrapperProxy = value;
334  },
335});
336
337const isPreloadingDesc = { get() { return isPreloading; } };
338ObjectDefineProperty(Module.prototype, 'isPreloading', isPreloadingDesc);
339ObjectDefineProperty(BuiltinModule.prototype, 'isPreloading', isPreloadingDesc);
340
341/**
342 * Get the parent of the current module from our cache.
343 */
344function getModuleParent() {
345  return moduleParentCache.get(this);
346}
347
348/**
349 * Set the parent of the current module in our cache.
350 * @param {Module} value
351 */
352function setModuleParent(value) {
353  moduleParentCache.set(this, value);
354}
355
356let debug = require('internal/util/debuglog').debuglog('module', (fn) => {
357  debug = fn;
358});
359
360ObjectDefineProperty(Module.prototype, 'parent', {
361  __proto__: null,
362  get: pendingDeprecate(
363    getModuleParent,
364    'module.parent is deprecated due to accuracy issues. Please use ' +
365      'require.main to find program entry point instead.',
366    'DEP0144',
367  ),
368  set: pendingDeprecate(
369    setModuleParent,
370    'module.parent is deprecated due to accuracy issues. Please use ' +
371      'require.main to find program entry point instead.',
372    'DEP0144',
373  ),
374});
375Module._debug = pendingDeprecate(debug, 'Module._debug is deprecated.', 'DEP0077');
376Module.isBuiltin = BuiltinModule.isBuiltin;
377
378/**
379 * Prepare to run CommonJS code.
380 * This function is called during pre-execution, before any user code is run.
381 */
382function initializeCJS() {
383  // This need to be done at runtime in case --expose-internals is set.
384  const builtinModules = BuiltinModule.getCanBeRequiredByUsersWithoutSchemeList();
385  Module.builtinModules = ObjectFreeze(builtinModules);
386
387  initializeCjsConditions();
388
389  if (!getEmbedderOptions().noGlobalSearchPaths) {
390    Module._initPaths();
391  }
392
393  // TODO(joyeecheung): deprecate this in favor of a proper hook?
394  Module.runMain =
395    require('internal/modules/run_main').executeUserEntryPoint;
396}
397
398// Given a module name, and a list of paths to test, returns the first
399// matching file in the following precedence.
400//
401// require("a.<ext>")
402//   -> a.<ext>
403//
404// require("a")
405//   -> a
406//   -> a.<ext>
407//   -> a/index.<ext>
408
409let _readPackage = packageJsonReader.readPackage;
410ObjectDefineProperty(Module, '_readPackage', {
411  __proto__: null,
412  get() { return _readPackage; },
413  set(readPackage) {
414    emitExperimentalWarning('Module._readPackage');
415    _readPackage = readPackage;
416    return true;
417  },
418  configurable: true,
419});
420
421/**
422 * Try to load a specifier as a package.
423 * @param {string} requestPath The path to what we are trying to load
424 * @param {string[]} exts File extensions to try appending in order to resolve the file
425 * @param {boolean} isMain Whether the file is the main entry point of the app
426 * @param {string} originalPath The specifier passed to `require`
427 */
428function tryPackage(requestPath, exts, isMain, originalPath) {
429  const pkg = _readPackage(requestPath).main;
430
431  if (!pkg) {
432    return tryExtensions(path.resolve(requestPath, 'index'), exts, isMain);
433  }
434
435  const filename = path.resolve(requestPath, pkg);
436  let actual = tryFile(filename, isMain) ||
437    tryExtensions(filename, exts, isMain) ||
438    tryExtensions(path.resolve(filename, 'index'), exts, isMain);
439  if (actual === false) {
440    actual = tryExtensions(path.resolve(requestPath, 'index'), exts, isMain);
441    if (!actual) {
442      // eslint-disable-next-line no-restricted-syntax
443      const err = new Error(
444        `Cannot find module '${filename}'. ` +
445        'Please verify that the package.json has a valid "main" entry',
446      );
447      err.code = 'MODULE_NOT_FOUND';
448      err.path = path.resolve(requestPath, 'package.json');
449      err.requestPath = originalPath;
450      // TODO(BridgeAR): Add the requireStack as well.
451      throw err;
452    } else {
453      const jsonPath = path.resolve(requestPath, 'package.json');
454      process.emitWarning(
455        `Invalid 'main' field in '${jsonPath}' of '${pkg}'. ` +
456          'Please either fix that or report it to the module author',
457        'DeprecationWarning',
458        'DEP0128',
459      );
460    }
461  }
462  return actual;
463}
464
465/**
466 * Check if the file exists and is not a directory if using `--preserve-symlinks` and `isMain` is false, keep symlinks
467 * intact, otherwise resolve to the absolute realpath.
468 * @param {string} requestPath The path to the file to load.
469 * @param {boolean} isMain Whether the file is the main module.
470 */
471function tryFile(requestPath, isMain) {
472  const rc = _stat(requestPath);
473  if (rc !== 0) { return; }
474  if (getOptionValue('--preserve-symlinks') && !isMain) {
475    return path.resolve(requestPath);
476  }
477  return toRealPath(requestPath);
478}
479
480/**
481 * Given a path, check if the file exists with any of the set extensions.
482 * @param {string} basePath The path and filename without extension
483 * @param {string[]} exts The extensions to try
484 * @param {boolean} isMain Whether the module is the main module
485 */
486function tryExtensions(basePath, exts, isMain) {
487  for (let i = 0; i < exts.length; i++) {
488    const filename = tryFile(basePath + exts[i], isMain);
489
490    if (filename) {
491      return filename;
492    }
493  }
494  return false;
495}
496
497/**
498 * Find the longest (possibly multi-dot) extension registered in `Module._extensions`.
499 * @param {string} filename The filename to find the longest registered extension for.
500 */
501function findLongestRegisteredExtension(filename) {
502  const name = path.basename(filename);
503  let currentExtension;
504  let index;
505  let startIndex = 0;
506  while ((index = StringPrototypeIndexOf(name, '.', startIndex)) !== -1) {
507    startIndex = index + 1;
508    if (index === 0) { continue; } // Skip dotfiles like .gitignore
509    currentExtension = StringPrototypeSlice(name, index);
510    if (Module._extensions[currentExtension]) { return currentExtension; }
511  }
512  return '.js';
513}
514
515/**
516 * Tries to get the absolute file path of the parent module.
517 * @param {Module} parent The parent module object.
518 */
519function trySelfParentPath(parent) {
520  if (!parent) { return false; }
521
522  if (parent.filename) {
523    return parent.filename;
524  } else if (parent.id === '<repl>' || parent.id === 'internal/preload') {
525    try {
526      return process.cwd() + path.sep;
527    } catch {
528      return false;
529    }
530  }
531}
532
533/**
534 * Attempt to resolve a module request using the parent module package metadata.
535 * @param {string} parentPath The path of the parent module
536 * @param {string} request The module request to resolve
537 */
538function trySelf(parentPath, request) {
539  if (!parentPath) { return false; }
540
541  const { data: pkg, path: pkgPath } = packageJsonReader.readPackageScope(parentPath);
542  if (!pkg || pkg.exports == null || pkg.name === undefined) {
543    return false;
544  }
545
546  let expansion;
547  if (request === pkg.name) {
548    expansion = '.';
549  } else if (StringPrototypeStartsWith(request, `${pkg.name}/`)) {
550    expansion = '.' + StringPrototypeSlice(request, pkg.name.length);
551  } else {
552    return false;
553  }
554
555  try {
556    const { packageExportsResolve } = require('internal/modules/esm/resolve');
557    return finalizeEsmResolution(packageExportsResolve(
558      pathToFileURL(pkgPath + '/package.json'), expansion, pkg,
559      pathToFileURL(parentPath), getCjsConditions()), parentPath, pkgPath);
560  } catch (e) {
561    if (e.code === 'ERR_MODULE_NOT_FOUND') {
562      throw createEsmNotFoundErr(request, pkgPath + '/package.json');
563    }
564    throw e;
565  }
566}
567
568/**
569 * This only applies to requests of a specific form:
570 * 1. `name/.*`
571 * 2. `@scope/name/.*`
572 */
573const EXPORTS_PATTERN = /^((?:@[^/\\%]+\/)?[^./\\%][^/\\%]*)(\/.*)?$/;
574
575/**
576 * Resolves the exports for a given module path and request.
577 * @param {string} nmPath The path to the module.
578 * @param {string} request The request for the module.
579 */
580function resolveExports(nmPath, request) {
581  // The implementation's behavior is meant to mirror resolution in ESM.
582  const { 1: name, 2: expansion = '' } =
583    RegExpPrototypeExec(EXPORTS_PATTERN, request) || kEmptyObject;
584  if (!name) { return; }
585  const pkgPath = path.resolve(nmPath, name);
586  const pkg = _readPackage(pkgPath);
587  if (pkg.exists && pkg.exports != null) {
588    try {
589      const { packageExportsResolve } = require('internal/modules/esm/resolve');
590      return finalizeEsmResolution(packageExportsResolve(
591        pathToFileURL(pkgPath + '/package.json'), '.' + expansion, pkg, null,
592        getCjsConditions()), null, pkgPath);
593    } catch (e) {
594      if (e.code === 'ERR_MODULE_NOT_FOUND') {
595        throw createEsmNotFoundErr(request, pkgPath + '/package.json');
596      }
597      throw e;
598    }
599  }
600}
601
602/**
603 * Get the absolute path to a module.
604 * @param {string} request Relative or absolute file path
605 * @param {Array<string>} paths Folders to search as file paths
606 * @param {boolean} isMain Whether the request is the main app entry point
607 * @returns {string | false}
608 */
609Module._findPath = function(request, paths, isMain) {
610  const absoluteRequest = path.isAbsolute(request);
611  if (absoluteRequest) {
612    paths = [''];
613  } else if (!paths || paths.length === 0) {
614    return false;
615  }
616
617  const cacheKey = request + '\x00' + ArrayPrototypeJoin(paths, '\x00');
618  const entry = Module._pathCache[cacheKey];
619  if (entry) {
620    return entry;
621  }
622
623  let exts;
624  const trailingSlash = request.length > 0 &&
625    (StringPrototypeCharCodeAt(request, request.length - 1) === CHAR_FORWARD_SLASH || (
626      StringPrototypeCharCodeAt(request, request.length - 1) === CHAR_DOT &&
627      (
628        request.length === 1 ||
629        StringPrototypeCharCodeAt(request, request.length - 2) === CHAR_FORWARD_SLASH ||
630        (StringPrototypeCharCodeAt(request, request.length - 2) === CHAR_DOT && (
631          request.length === 2 ||
632          StringPrototypeCharCodeAt(request, request.length - 3) === CHAR_FORWARD_SLASH
633        ))
634      )
635    ));
636
637  const isRelative = StringPrototypeCharCodeAt(request, 0) === CHAR_DOT &&
638    (
639      request.length === 1 ||
640      StringPrototypeCharCodeAt(request, 1) === CHAR_FORWARD_SLASH ||
641      (isWindows && StringPrototypeCharCodeAt(request, 1) === CHAR_BACKWARD_SLASH) ||
642      (StringPrototypeCharCodeAt(request, 1) === CHAR_DOT && ((
643        request.length === 2 ||
644        StringPrototypeCharCodeAt(request, 2) === CHAR_FORWARD_SLASH) ||
645        (isWindows && StringPrototypeCharCodeAt(request, 2) === CHAR_BACKWARD_SLASH)))
646    );
647  let insidePath = true;
648  if (isRelative) {
649    const normalizedRequest = path.normalize(request);
650    if (StringPrototypeStartsWith(normalizedRequest, '..')) {
651      insidePath = false;
652    }
653  }
654
655  // For each path
656  for (let i = 0; i < paths.length; i++) {
657    // Don't search further if path doesn't exist and request is inside the path
658    const curPath = paths[i];
659    if (insidePath && curPath && _stat(curPath) < 1) {
660      continue;
661    }
662
663    if (!absoluteRequest) {
664      const exportsResolved = resolveExports(curPath, request);
665      if (exportsResolved) {
666        return exportsResolved;
667      }
668    }
669
670    const basePath = path.resolve(curPath, request);
671    let filename;
672
673    const rc = _stat(basePath);
674    if (!trailingSlash) {
675      if (rc === 0) {  // File.
676        if (!isMain) {
677          if (getOptionValue('--preserve-symlinks')) {
678            filename = path.resolve(basePath);
679          } else {
680            filename = toRealPath(basePath);
681          }
682        } else if (getOptionValue('--preserve-symlinks-main')) {
683          // For the main module, we use the --preserve-symlinks-main flag instead
684          // mainly for backward compatibility, as the preserveSymlinks flag
685          // historically has not applied to the main module.  Most likely this
686          // was intended to keep .bin/ binaries working, as following those
687          // symlinks is usually required for the imports in the corresponding
688          // files to resolve; that said, in some use cases following symlinks
689          // causes bigger problems which is why the --preserve-symlinks-main option
690          // is needed.
691          filename = path.resolve(basePath);
692        } else {
693          filename = toRealPath(basePath);
694        }
695      }
696
697      if (!filename) {
698        // Try it with each of the extensions
699        if (exts === undefined) {
700          exts = ObjectKeys(Module._extensions);
701        }
702        filename = tryExtensions(basePath, exts, isMain);
703      }
704    }
705
706    if (!filename && rc === 1) {  // Directory.
707      // try it with each of the extensions at "index"
708      if (exts === undefined) {
709        exts = ObjectKeys(Module._extensions);
710      }
711      filename = tryPackage(basePath, exts, isMain, request);
712    }
713
714    if (filename) {
715      Module._pathCache[cacheKey] = filename;
716      return filename;
717    }
718
719    const extensions = [''];
720    if (exts !== undefined) {
721      ArrayPrototypePushApply(extensions, exts);
722    }
723    reportModuleNotFoundToWatchMode(basePath, extensions);
724  }
725
726  return false;
727};
728
729/** `node_modules` character codes reversed */
730const nmChars = [ 115, 101, 108, 117, 100, 111, 109, 95, 101, 100, 111, 110 ];
731const nmLen = nmChars.length;
732if (isWindows) {
733  /**
734   * Get the paths to the `node_modules` folder for a given path.
735   * @param {string} from `__dirname` of the module
736   */
737  Module._nodeModulePaths = function(from) {
738    // Guarantee that 'from' is absolute.
739    from = path.resolve(from);
740
741    // note: this approach *only* works when the path is guaranteed
742    // to be absolute.  Doing a fully-edge-case-correct path.split
743    // that works on both Windows and Posix is non-trivial.
744
745    // return root node_modules when path is 'D:\\'.
746    // path.resolve will make sure from.length >=3 in Windows.
747    if (StringPrototypeCharCodeAt(from, from.length - 1) ===
748          CHAR_BACKWARD_SLASH &&
749        StringPrototypeCharCodeAt(from, from.length - 2) === CHAR_COLON) {
750      return [from + 'node_modules'];
751    }
752
753    /** @type {string[]} */
754    const paths = [];
755    for (let i = from.length - 1, p = 0, last = from.length; i >= 0; --i) {
756      const code = StringPrototypeCharCodeAt(from, i);
757      // The path segment separator check ('\' and '/') was used to get
758      // node_modules path for every path segment.
759      // Use colon as an extra condition since we can get node_modules
760      // path for drive root like 'C:\node_modules' and don't need to
761      // parse drive name.
762      if (code === CHAR_BACKWARD_SLASH ||
763          code === CHAR_FORWARD_SLASH ||
764          code === CHAR_COLON) {
765        if (p !== nmLen) {
766          ArrayPrototypePush(
767            paths,
768            StringPrototypeSlice(from, 0, last) + '\\node_modules',
769          );
770        }
771        last = i;
772        p = 0;
773      } else if (p !== -1) {
774        if (nmChars[p] === code) {
775          ++p;
776        } else {
777          p = -1;
778        }
779      }
780    }
781
782    return paths;
783  };
784} else { // posix
785  /**
786   * Get the paths to the `node_modules` folder for a given path.
787   * @param {string} from `__dirname` of the module
788   */
789  Module._nodeModulePaths = function(from) {
790    // Guarantee that 'from' is absolute.
791    from = path.resolve(from);
792    // Return early not only to avoid unnecessary work, but to *avoid* returning
793    // an array of two items for a root: [ '//node_modules', '/node_modules' ]
794    if (from === '/') {
795      return ['/node_modules'];
796    }
797
798    // note: this approach *only* works when the path is guaranteed
799    // to be absolute.  Doing a fully-edge-case-correct path.split
800    // that works on both Windows and Posix is non-trivial.
801    /** @type {string[]} */
802    const paths = [];
803    for (let i = from.length - 1, p = 0, last = from.length; i >= 0; --i) {
804      const code = StringPrototypeCharCodeAt(from, i);
805      if (code === CHAR_FORWARD_SLASH) {
806        if (p !== nmLen) {
807          ArrayPrototypePush(
808            paths,
809            StringPrototypeSlice(from, 0, last) + '/node_modules',
810          );
811        }
812        last = i;
813        p = 0;
814      } else if (p !== -1) {
815        if (nmChars[p] === code) {
816          ++p;
817        } else {
818          p = -1;
819        }
820      }
821    }
822
823    // Append /node_modules to handle root paths.
824    ArrayPrototypePush(paths, '/node_modules');
825
826    return paths;
827  };
828}
829
830/**
831 * Get the paths for module resolution.
832 * @param {string} request
833 * @param {Module} parent
834 */
835Module._resolveLookupPaths = function(request, parent) {
836  if (BuiltinModule.normalizeRequirableId(request)) {
837    debug('looking for %j in []', request);
838    return null;
839  }
840
841  // Check for node modules paths.
842  if (StringPrototypeCharAt(request, 0) !== '.' ||
843      (request.length > 1 &&
844      StringPrototypeCharAt(request, 1) !== '.' &&
845      StringPrototypeCharAt(request, 1) !== '/' &&
846      (!isWindows || StringPrototypeCharAt(request, 1) !== '\\'))) {
847
848    /** @type {string[]} */
849    let paths;
850    if (parent?.paths?.length) {
851      paths = ArrayPrototypeSlice(modulePaths);
852      ArrayPrototypeUnshiftApply(paths, parent.paths);
853    } else {
854      paths = modulePaths;
855    }
856
857    debug('looking for %j in %j', request, paths);
858    return paths.length > 0 ? paths : null;
859  }
860
861  // In REPL, parent.filename is null.
862  if (!parent || !parent.id || !parent.filename) {
863    // Make require('./path/to/foo') work - normally the path is taken
864    // from realpath(__filename) but in REPL there is no filename
865    const mainPaths = ['.'];
866
867    debug('looking for %j in %j', request, mainPaths);
868    return mainPaths;
869  }
870
871  debug('RELATIVE: requested: %s from parent.id %s', request, parent.id);
872
873  const parentDir = [path.dirname(parent.filename)];
874  debug('looking for %j', parentDir);
875  return parentDir;
876};
877
878/**
879 * Emits a warning when a non-existent property of module exports is accessed inside a circular dependency.
880 * @param {string} prop The name of the non-existent property.
881 */
882function emitCircularRequireWarning(prop) {
883  process.emitWarning(
884    `Accessing non-existent property '${String(prop)}' of module exports ` +
885    'inside circular dependency',
886  );
887}
888
889// A Proxy that can be used as the prototype of a module.exports object and
890// warns when non-existent properties are accessed.
891const CircularRequirePrototypeWarningProxy = new Proxy({}, {
892  __proto__: null,
893
894  get(target, prop) {
895    // Allow __esModule access in any case because it is used in the output
896    // of transpiled code to determine whether something comes from an
897    // ES module, and is not used as a regular key of `module.exports`.
898    if (prop in target || prop === '__esModule') { return target[prop]; }
899    emitCircularRequireWarning(prop);
900    return undefined;
901  },
902
903  getOwnPropertyDescriptor(target, prop) {
904    if (ObjectPrototypeHasOwnProperty(target, prop) || prop === '__esModule') {
905      return ObjectGetOwnPropertyDescriptor(target, prop);
906    }
907    emitCircularRequireWarning(prop);
908    return undefined;
909  },
910});
911
912/**
913 * Returns the exports object for a module that has a circular `require`.
914 * If the exports object is a plain object, it is wrapped in a proxy that warns
915 * about circular dependencies.
916 * @param {Module} module The module instance
917 */
918function getExportsForCircularRequire(module) {
919  if (module.exports &&
920      !isProxy(module.exports) &&
921      ObjectGetPrototypeOf(module.exports) === ObjectPrototype &&
922      // Exclude transpiled ES6 modules / TypeScript code because those may
923      // employ unusual patterns for accessing 'module.exports'. That should
924      // be okay because ES6 modules have a different approach to circular
925      // dependencies anyway.
926      !module.exports.__esModule) {
927    // This is later unset once the module is done loading.
928    ObjectSetPrototypeOf(
929      module.exports, CircularRequirePrototypeWarningProxy);
930  }
931
932  return module.exports;
933}
934
935/**
936 * Load a module from cache if it exists, otherwise create a new module instance.
937 * 1. If a module already exists in the cache: return its exports object.
938 * 2. If the module is native: call
939 *    `BuiltinModule.prototype.compileForPublicLoader()` and return the exports.
940 * 3. Otherwise, create a new module for the file and save it to the cache.
941 *    Then have it load the file contents before returning its exports object.
942 * @param {string} request Specifier of module to load via `require`
943 * @param {string} parent Absolute path of the module importing the child
944 * @param {boolean} isMain Whether the module is the main entry point
945 */
946Module._load = function(request, parent, isMain) {
947  let relResolveCacheIdentifier;
948  if (parent) {
949    debug('Module._load REQUEST %s parent: %s', request, parent.id);
950    // Fast path for (lazy loaded) modules in the same directory. The indirect
951    // caching is required to allow cache invalidation without changing the old
952    // cache key names.
953    relResolveCacheIdentifier = `${parent.path}\x00${request}`;
954    const filename = relativeResolveCache[relResolveCacheIdentifier];
955    reportModuleToWatchMode(filename);
956    if (filename !== undefined) {
957      const cachedModule = Module._cache[filename];
958      if (cachedModule !== undefined) {
959        updateChildren(parent, cachedModule, true);
960        if (!cachedModule.loaded) {
961          return getExportsForCircularRequire(cachedModule);
962        }
963        return cachedModule.exports;
964      }
965      delete relativeResolveCache[relResolveCacheIdentifier];
966    }
967  }
968
969  if (StringPrototypeStartsWith(request, 'node:')) {
970    // Slice 'node:' prefix
971    const id = StringPrototypeSlice(request, 5);
972
973    if (!BuiltinModule.canBeRequiredByUsers(id)) {
974      throw new ERR_UNKNOWN_BUILTIN_MODULE(request);
975    }
976
977    const module = loadBuiltinModule(id, request);
978    return module.exports;
979  }
980
981  const filename = Module._resolveFilename(request, parent, isMain);
982  const cachedModule = Module._cache[filename];
983  if (cachedModule !== undefined) {
984    updateChildren(parent, cachedModule, true);
985    if (!cachedModule.loaded) {
986      const parseCachedModule = cjsParseCache.get(cachedModule);
987      if (!parseCachedModule || parseCachedModule.loaded) {
988        return getExportsForCircularRequire(cachedModule);
989      }
990      parseCachedModule.loaded = true;
991    } else {
992      return cachedModule.exports;
993    }
994  }
995
996  if (BuiltinModule.canBeRequiredWithoutScheme(filename)) {
997    const mod = loadBuiltinModule(filename, request);
998    return mod.exports;
999  }
1000
1001  // Don't call updateChildren(), Module constructor already does.
1002  const module = cachedModule || new Module(filename, parent);
1003
1004  if (isMain) {
1005    setOwnProperty(process, 'mainModule', module);
1006    setOwnProperty(module.require, 'main', process.mainModule);
1007    module.id = '.';
1008  }
1009
1010  reportModuleToWatchMode(filename);
1011
1012  Module._cache[filename] = module;
1013  if (parent !== undefined) {
1014    relativeResolveCache[relResolveCacheIdentifier] = filename;
1015  }
1016
1017  let threw = true;
1018  try {
1019    module.load(filename);
1020    threw = false;
1021  } finally {
1022    if (threw) {
1023      delete Module._cache[filename];
1024      if (parent !== undefined) {
1025        delete relativeResolveCache[relResolveCacheIdentifier];
1026        const children = parent?.children;
1027        if (ArrayIsArray(children)) {
1028          const index = ArrayPrototypeIndexOf(children, module);
1029          if (index !== -1) {
1030            ArrayPrototypeSplice(children, index, 1);
1031          }
1032        }
1033      }
1034    } else if (module.exports &&
1035               !isProxy(module.exports) &&
1036               ObjectGetPrototypeOf(module.exports) ===
1037                 CircularRequirePrototypeWarningProxy) {
1038      ObjectSetPrototypeOf(module.exports, ObjectPrototype);
1039    }
1040  }
1041
1042  return module.exports;
1043};
1044
1045/**
1046 * Given a `require` string and its context, get its absolute file path.
1047 * @param {string} request The specifier to resolve
1048 * @param {Module} parent The module containing the `require` call
1049 * @param {boolean} isMain Whether the module is the main entry point
1050 * @param {ResolveFilenameOptions} options Options object
1051 * @typedef {object} ResolveFilenameOptions
1052 * @property {string[]} paths Paths to search for modules in
1053 */
1054Module._resolveFilename = function(request, parent, isMain, options) {
1055  if (BuiltinModule.normalizeRequirableId(request)) {
1056    return request;
1057  }
1058
1059  let paths;
1060
1061  if (typeof options === 'object' && options !== null) {
1062    if (ArrayIsArray(options.paths)) {
1063      const isRelative = StringPrototypeStartsWith(request, './') ||
1064          StringPrototypeStartsWith(request, '../') ||
1065          ((isWindows && StringPrototypeStartsWith(request, '.\\')) ||
1066          StringPrototypeStartsWith(request, '..\\'));
1067
1068      if (isRelative) {
1069        paths = options.paths;
1070      } else {
1071        const fakeParent = new Module('', null);
1072
1073        paths = [];
1074
1075        for (let i = 0; i < options.paths.length; i++) {
1076          const path = options.paths[i];
1077          fakeParent.paths = Module._nodeModulePaths(path);
1078          const lookupPaths = Module._resolveLookupPaths(request, fakeParent);
1079
1080          for (let j = 0; j < lookupPaths.length; j++) {
1081            if (!ArrayPrototypeIncludes(paths, lookupPaths[j])) {
1082              ArrayPrototypePush(paths, lookupPaths[j]);
1083            }
1084          }
1085        }
1086      }
1087    } else if (options.paths === undefined) {
1088      paths = Module._resolveLookupPaths(request, parent);
1089    } else {
1090      throw new ERR_INVALID_ARG_VALUE('options.paths', options.paths);
1091    }
1092  } else {
1093    paths = Module._resolveLookupPaths(request, parent);
1094  }
1095
1096  if (request[0] === '#' && (parent?.filename || parent?.id === '<repl>')) {
1097    const parentPath = parent?.filename ?? process.cwd() + path.sep;
1098    const pkg = packageJsonReader.readPackageScope(parentPath) || { __proto__: null };
1099    if (pkg.data?.imports != null) {
1100      try {
1101        const { packageImportsResolve } = require('internal/modules/esm/resolve');
1102        return finalizeEsmResolution(
1103          packageImportsResolve(request, pathToFileURL(parentPath),
1104                                getCjsConditions()), parentPath,
1105          pkg.path);
1106      } catch (e) {
1107        if (e.code === 'ERR_MODULE_NOT_FOUND') {
1108          throw createEsmNotFoundErr(request);
1109        }
1110        throw e;
1111      }
1112    }
1113  }
1114
1115  // Try module self resolution first
1116  const parentPath = trySelfParentPath(parent);
1117  const selfResolved = trySelf(parentPath, request);
1118  if (selfResolved) {
1119    const cacheKey = request + '\x00' +
1120         (paths.length === 1 ? paths[0] : ArrayPrototypeJoin(paths, '\x00'));
1121    Module._pathCache[cacheKey] = selfResolved;
1122    return selfResolved;
1123  }
1124
1125  // Look up the filename first, since that's the cache key.
1126  const filename = Module._findPath(request, paths, isMain);
1127  if (filename) { return filename; }
1128  const requireStack = [];
1129  for (let cursor = parent;
1130    cursor;
1131    cursor = moduleParentCache.get(cursor)) {
1132    ArrayPrototypePush(requireStack, cursor.filename || cursor.id);
1133  }
1134  let message = `Cannot find module '${request}'`;
1135  if (requireStack.length > 0) {
1136    message = message + '\nRequire stack:\n- ' +
1137              ArrayPrototypeJoin(requireStack, '\n- ');
1138  }
1139  // eslint-disable-next-line no-restricted-syntax
1140  const err = new Error(message);
1141  err.code = 'MODULE_NOT_FOUND';
1142  err.requireStack = requireStack;
1143  throw err;
1144};
1145
1146/**
1147 * Finishes resolving an ES module specifier into an absolute file path.
1148 * @param {string} resolved The resolved module specifier
1149 * @param {string} parentPath The path of the parent module
1150 * @param {string} pkgPath The path of the package.json file
1151 * @throws {ERR_INVALID_MODULE_SPECIFIER} If the resolved module specifier contains encoded `/` or `\\` characters
1152 * @throws {Error} If the module cannot be found
1153 */
1154function finalizeEsmResolution(resolved, parentPath, pkgPath) {
1155  const { encodedSepRegEx } = require('internal/modules/esm/resolve');
1156  if (RegExpPrototypeExec(encodedSepRegEx, resolved) !== null) {
1157    throw new ERR_INVALID_MODULE_SPECIFIER(
1158      resolved, 'must not include encoded "/" or "\\" characters', parentPath);
1159  }
1160  const filename = fileURLToPath(resolved);
1161  const actual = tryFile(filename);
1162  if (actual) {
1163    return actual;
1164  }
1165  const err = createEsmNotFoundErr(filename,
1166                                   path.resolve(pkgPath, 'package.json'));
1167  throw err;
1168}
1169
1170/**
1171 * Creates an error object for when a requested ES module cannot be found.
1172 * @param {string} request The name of the requested module
1173 * @param {string} [path] The path to the requested module
1174 */
1175function createEsmNotFoundErr(request, path) {
1176  // eslint-disable-next-line no-restricted-syntax
1177  const err = new Error(`Cannot find module '${request}'`);
1178  err.code = 'MODULE_NOT_FOUND';
1179  if (path) {
1180    err.path = path;
1181  }
1182  // TODO(BridgeAR): Add the requireStack as well.
1183  return err;
1184}
1185
1186/**
1187 * Given a file name, pass it to the proper extension handler.
1188 * @param {string} filename The `require` specifier
1189 */
1190Module.prototype.load = function(filename) {
1191  debug('load %j for module %j', filename, this.id);
1192
1193  assert(!this.loaded);
1194  this.filename = filename;
1195  this.paths = Module._nodeModulePaths(path.dirname(filename));
1196
1197  const extension = findLongestRegisteredExtension(filename);
1198  // allow .mjs to be overridden
1199  if (StringPrototypeEndsWith(filename, '.mjs') && !Module._extensions['.mjs']) {
1200    throw new ERR_REQUIRE_ESM(filename, true);
1201  }
1202
1203  Module._extensions[extension](this, filename);
1204  this.loaded = true;
1205
1206  const cascadedLoader = getCascadedLoader();
1207  // Create module entry at load time to snapshot exports correctly
1208  const exports = this.exports;
1209  // Preemptively cache
1210  if ((module?.module === undefined ||
1211       module.module.getStatus() < kEvaluated) &&
1212      !cascadedLoader.cjsCache.has(this)) {
1213    cascadedLoader.cjsCache.set(this, exports);
1214  }
1215};
1216
1217/**
1218 * Loads a module at the given file path. Returns that module's `exports` property.
1219 * Note: when using the experimental policy mechanism this function is overridden.
1220 * @param {string} id
1221 * @throws {ERR_INVALID_ARG_TYPE} When `id` is not a string
1222 */
1223Module.prototype.require = function(id) {
1224  validateString(id, 'id');
1225  if (id === '') {
1226    throw new ERR_INVALID_ARG_VALUE('id', id,
1227                                    'must be a non-empty string');
1228  }
1229  requireDepth++;
1230  try {
1231    return Module._load(id, this, /* isMain */ false);
1232  } finally {
1233    requireDepth--;
1234  }
1235};
1236
1237/**
1238 * Resolved path to `process.argv[1]` will be lazily placed here
1239 * (needed for setting breakpoint when called with `--inspect-brk`).
1240 * @type {string | undefined}
1241 */
1242let resolvedArgv;
1243let hasPausedEntry = false;
1244/** @type {import('vm').Script} */
1245
1246/**
1247 * Wraps the given content in a script and runs it in a new context.
1248 * @param {string} filename The name of the file being loaded
1249 * @param {string} content The content of the file being loaded
1250 * @param {Module} cjsModuleInstance The CommonJS loader instance
1251 */
1252function wrapSafe(filename, content, cjsModuleInstance) {
1253  const hostDefinedOptionId = Symbol(`cjs:${filename}`);
1254  async function importModuleDynamically(specifier, _, importAttributes) {
1255    const cascadedLoader = getCascadedLoader();
1256    return cascadedLoader.import(specifier, normalizeReferrerURL(filename),
1257                                 importAttributes);
1258  }
1259  if (patched) {
1260    const wrapped = Module.wrap(content);
1261    const script = makeContextifyScript(
1262      wrapped,                 // code
1263      filename,                // filename
1264      0,                       // lineOffset
1265      0,                       // columnOffset
1266      undefined,               // cachedData
1267      false,                   // produceCachedData
1268      undefined,               // parsingContext
1269      hostDefinedOptionId,     // hostDefinedOptionId
1270      importModuleDynamically, // importModuleDynamically
1271    );
1272
1273    // Cache the source map for the module if present.
1274    if (script.sourceMapURL) {
1275      maybeCacheSourceMap(filename, content, this, false, undefined, script.sourceMapURL);
1276    }
1277
1278    return runScriptInThisContext(script, true, false);
1279  }
1280
1281  const params = [ 'exports', 'require', 'module', '__filename', '__dirname' ];
1282  try {
1283    const result = internalCompileFunction(
1284      content,                           // code,
1285      filename,                          // filename
1286      0,                                 // lineOffset
1287      0,                                 // columnOffset,
1288      undefined,                         // cachedData
1289      false,                             // produceCachedData
1290      undefined,                         // parsingContext
1291      undefined,                         // contextExtensions
1292      params,                            // params
1293      hostDefinedOptionId,               // hostDefinedOptionId
1294      importModuleDynamically,           // importModuleDynamically
1295    );
1296
1297    // Cache the source map for the module if present.
1298    if (result.sourceMapURL) {
1299      maybeCacheSourceMap(filename, content, this, false, undefined, result.sourceMapURL);
1300    }
1301
1302    return result.function;
1303  } catch (err) {
1304    if (process.mainModule === cjsModuleInstance) {
1305      const { enrichCJSError } = require('internal/modules/esm/translators');
1306      enrichCJSError(err, content);
1307    }
1308    throw err;
1309  }
1310}
1311
1312/**
1313 * Run the file contents in the correct scope or sandbox. Expose the correct helper variables (`require`, `module`,
1314 * `exports`) to the file. Returns exception, if any.
1315 * @param {string} content The source code of the module
1316 * @param {string} filename The file path of the module
1317 */
1318Module.prototype._compile = function(content, filename) {
1319  let moduleURL;
1320  let redirects;
1321  const manifest = policy()?.manifest;
1322  if (manifest) {
1323    moduleURL = pathToFileURL(filename);
1324    redirects = manifest.getDependencyMapper(moduleURL);
1325    manifest.assertIntegrity(moduleURL, content);
1326  }
1327
1328  const compiledWrapper = wrapSafe(filename, content, this);
1329
1330  let inspectorWrapper = null;
1331  if (getOptionValue('--inspect-brk') && process._eval == null) {
1332    if (!resolvedArgv) {
1333      // We enter the repl if we're not given a filename argument.
1334      if (process.argv[1]) {
1335        try {
1336          resolvedArgv = Module._resolveFilename(process.argv[1], null, false);
1337        } catch {
1338          // We only expect this codepath to be reached in the case of a
1339          // preloaded module (it will fail earlier with the main entry)
1340          assert(ArrayIsArray(getOptionValue('--require')));
1341        }
1342      } else {
1343        resolvedArgv = 'repl';
1344      }
1345    }
1346
1347    // Set breakpoint on module start
1348    if (resolvedArgv && !hasPausedEntry && filename === resolvedArgv) {
1349      hasPausedEntry = true;
1350      inspectorWrapper = internalBinding('inspector').callAndPauseOnStart;
1351    }
1352  }
1353  const dirname = path.dirname(filename);
1354  const require = makeRequireFunction(this, redirects);
1355  let result;
1356  const exports = this.exports;
1357  const thisValue = exports;
1358  const module = this;
1359  if (requireDepth === 0) { statCache = new SafeMap(); }
1360  if (inspectorWrapper) {
1361    result = inspectorWrapper(compiledWrapper, thisValue, exports,
1362                              require, module, filename, dirname);
1363  } else {
1364    result = ReflectApply(compiledWrapper, thisValue,
1365                          [exports, require, module, filename, dirname]);
1366  }
1367  hasLoadedAnyUserCJSModule = true;
1368  if (requireDepth === 0) { statCache = null; }
1369  return result;
1370};
1371
1372/**
1373 * Native handler for `.js` files.
1374 * @param {Module} module The module to compile
1375 * @param {string} filename The file path of the module
1376 */
1377Module._extensions['.js'] = function(module, filename) {
1378  // If already analyzed the source, then it will be cached.
1379  const cached = cjsParseCache.get(module);
1380  let content;
1381  if (cached?.source) {
1382    content = cached.source;
1383    cached.source = undefined;
1384  } else {
1385    content = fs.readFileSync(filename, 'utf8');
1386  }
1387  if (StringPrototypeEndsWith(filename, '.js')) {
1388    const pkg = packageJsonReader.readPackageScope(filename) || { __proto__: null };
1389    // Function require shouldn't be used in ES modules.
1390    if (pkg.data?.type === 'module') {
1391      const parent = moduleParentCache.get(module);
1392      const parentPath = parent?.filename;
1393      const packageJsonPath = path.resolve(pkg.path, 'package.json');
1394      const usesEsm = hasEsmSyntax(content);
1395      const err = new ERR_REQUIRE_ESM(filename, usesEsm, parentPath,
1396                                      packageJsonPath);
1397      // Attempt to reconstruct the parent require frame.
1398      if (Module._cache[parentPath]) {
1399        let parentSource;
1400        try {
1401          parentSource = fs.readFileSync(parentPath, 'utf8');
1402        } catch {
1403          // Continue regardless of error.
1404        }
1405        if (parentSource) {
1406          const errLine = StringPrototypeSplit(
1407            StringPrototypeSlice(err.stack, StringPrototypeIndexOf(
1408              err.stack, '    at ')), '\n', 1)[0];
1409          const { 1: line, 2: col } =
1410              RegExpPrototypeExec(/(\d+):(\d+)\)/, errLine) || [];
1411          if (line && col) {
1412            const srcLine = StringPrototypeSplit(parentSource, '\n')[line - 1];
1413            const frame = `${parentPath}:${line}\n${srcLine}\n${
1414              StringPrototypeRepeat(' ', col - 1)}^\n`;
1415            setArrowMessage(err, frame);
1416          }
1417        }
1418      }
1419      throw err;
1420    }
1421  }
1422  module._compile(content, filename);
1423};
1424
1425/**
1426 * Native handler for `.json` files.
1427 * @param {Module} module The module to compile
1428 * @param {string} filename The file path of the module
1429 */
1430Module._extensions['.json'] = function(module, filename) {
1431  const content = fs.readFileSync(filename, 'utf8');
1432
1433  const manifest = policy()?.manifest;
1434  if (manifest) {
1435    const moduleURL = pathToFileURL(filename);
1436    manifest.assertIntegrity(moduleURL, content);
1437  }
1438
1439  try {
1440    setOwnProperty(module, 'exports', JSONParse(stripBOM(content)));
1441  } catch (err) {
1442    err.message = filename + ': ' + err.message;
1443    throw err;
1444  }
1445};
1446
1447/**
1448 * Native handler for `.node` files.
1449 * @param {Module} module The module to compile
1450 * @param {string} filename The file path of the module
1451 */
1452Module._extensions['.node'] = function(module, filename) {
1453  const manifest = policy()?.manifest;
1454  if (manifest) {
1455    const content = fs.readFileSync(filename);
1456    const moduleURL = pathToFileURL(filename);
1457    manifest.assertIntegrity(moduleURL, content);
1458  }
1459  // Be aware this doesn't use `content`
1460  return process.dlopen(module, path.toNamespacedPath(filename));
1461};
1462
1463/**
1464 * Creates a `require` function that can be used to load modules from the specified path.
1465 * @param {string} filename The path to the module
1466 */
1467function createRequireFromPath(filename) {
1468  // Allow a directory to be passed as the filename
1469  const trailingSlash =
1470    StringPrototypeEndsWith(filename, '/') ||
1471    (isWindows && StringPrototypeEndsWith(filename, '\\'));
1472
1473  const proxyPath = trailingSlash ?
1474    path.join(filename, 'noop.js') :
1475    filename;
1476
1477  const m = new Module(proxyPath);
1478  m.filename = proxyPath;
1479
1480  m.paths = Module._nodeModulePaths(m.path);
1481  return makeRequireFunction(m, null);
1482}
1483
1484const createRequireError = 'must be a file URL object, file URL string, or ' +
1485  'absolute path string';
1486
1487/**
1488 * Creates a new `require` function that can be used to load modules.
1489 * @param {string | URL} filename The path or URL to the module context for this `require`
1490 * @throws {ERR_INVALID_ARG_VALUE} If `filename` is not a string or URL, or if it is a relative path that cannot be
1491 * resolved to an absolute path.
1492 */
1493function createRequire(filename) {
1494  let filepath;
1495
1496  if (isURL(filename) ||
1497      (typeof filename === 'string' && !path.isAbsolute(filename))) {
1498    try {
1499      filepath = fileURLToPath(filename);
1500    } catch {
1501      throw new ERR_INVALID_ARG_VALUE('filename', filename,
1502                                      createRequireError);
1503    }
1504  } else if (typeof filename !== 'string') {
1505    throw new ERR_INVALID_ARG_VALUE('filename', filename, createRequireError);
1506  } else {
1507    filepath = filename;
1508  }
1509  return createRequireFromPath(filepath);
1510}
1511
1512Module.createRequire = createRequire;
1513
1514/**
1515 * Define the paths to use for resolving a module.
1516 */
1517Module._initPaths = function() {
1518  const homeDir = isWindows ? process.env.USERPROFILE : safeGetenv('HOME');
1519  const nodePath = isWindows ? process.env.NODE_PATH : safeGetenv('NODE_PATH');
1520
1521  // process.execPath is $PREFIX/bin/node except on Windows where it is
1522  // $PREFIX\node.exe where $PREFIX is the root of the Node.js installation.
1523  const prefixDir = isWindows ?
1524    path.resolve(process.execPath, '..') :
1525    path.resolve(process.execPath, '..', '..');
1526
1527  const paths = [path.resolve(prefixDir, 'lib', 'node')];
1528
1529  if (homeDir) {
1530    ArrayPrototypeUnshift(paths, path.resolve(homeDir, '.node_libraries'));
1531    ArrayPrototypeUnshift(paths, path.resolve(homeDir, '.node_modules'));
1532  }
1533
1534  if (nodePath) {
1535    ArrayPrototypeUnshiftApply(paths, ArrayPrototypeFilter(
1536      StringPrototypeSplit(nodePath, path.delimiter),
1537      Boolean,
1538    ));
1539  }
1540
1541  modulePaths = paths;
1542
1543  // Clone as a shallow copy, for introspection.
1544  Module.globalPaths = ArrayPrototypeSlice(modulePaths);
1545};
1546
1547/**
1548 * Handle modules loaded via `--require`.
1549 * @param {string[]} requests The values of `--require`
1550 */
1551Module._preloadModules = function(requests) {
1552  if (!ArrayIsArray(requests)) { return; }
1553
1554  isPreloading = true;
1555
1556  // Preloaded modules have a dummy parent module which is deemed to exist
1557  // in the current working directory. This seeds the search path for
1558  // preloaded modules.
1559  const parent = new Module('internal/preload', null);
1560  try {
1561    parent.paths = Module._nodeModulePaths(process.cwd());
1562  } catch (e) {
1563    if (e.code !== 'ENOENT') {
1564      isPreloading = false;
1565      throw e;
1566    }
1567  }
1568  for (let n = 0; n < requests.length; n++) {
1569    internalRequire(parent, requests[n]);
1570  }
1571  isPreloading = false;
1572};
1573
1574/**
1575 * If the user has overridden an export from a builtin module, this function can ensure that the override is used in
1576 * both CommonJS and ES module contexts.
1577 */
1578Module.syncBuiltinESMExports = function syncBuiltinESMExports() {
1579  for (const mod of BuiltinModule.map.values()) {
1580    if (BuiltinModule.canBeRequiredWithoutScheme(mod.id)) {
1581      mod.syncExports();
1582    }
1583  }
1584};
1585
1586ObjectDefineProperty(Module.prototype, 'constructor', {
1587  __proto__: null,
1588  get: function() {
1589    return policy() ? undefined : Module;
1590  },
1591  configurable: false,
1592  enumerable: false,
1593});
1594
1595// Backwards compatibility
1596Module.Module = Module;
1597