All files / lib/internal/modules/esm loader.js

95.07% Statements 849/893
92.8% Branches 129/139
95.45% Functions 21/22
95.07% Lines 849/893

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 3102x 3102x 3102x 3102x 3102x 3102x 3102x 3102x 3102x 3102x 3102x 3102x 3102x 3102x 3102x 3102x 3102x 3102x 3102x 239x 239x 239x 239x 239x 3102x 2863x 2863x       2863x 2863x 3102x 3102x 3102x 3005x 3005x 3005x 3005x 3005x 3005x 3005x 3000x 3000x 3000x 2833x 3005x 2833x 2833x 3102x 3102x 3102x 3102x 3102x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 6015x 78x 78x 6015x 4x 4x 6015x 6015x 6015x 6015x 12x 12x 12x 12x 12x 12x 6015x 145x 145x 145x 145x 145x 145x 145x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x             73x 1x 1x 1x 73x 2x 2x 2x 73x 1x 1x 1x 73x 1x 1x 1x 73x 73x 2x 2x 2x 2x 2x 73x 73x 73x 4x 4x 4x 73x 47x 47x 73x 35x 35x 73x 73x 73x 145x 145x 145x 145x 145x 145x 145x 145x 145x 38x 38x 38x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 4x 4x 4x 4x 4x 4x 4x 4x 73x 47x 47x 47x 47x 47x 47x 47x 47x 73x 35x 35x 35x 35x 35x 35x 35x 35x 73x 38x 38x 38x 38x 38x 145x 145x 51x 51x 51x 51x 51x 51x 51x 51x 2x 2x 51x 51x 51x 51x 51x 51x 51x 51x 26x 26x 26x 26x 51x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 1586x 1586x 1586x 1586x 98x 98x 98x 98x 98x 98x 98x 1586x 1586x 1586x 1461x 1461x 1461x 1461x 1575x     1461x 1564x 1245x 1245x 1461x 1461x 1586x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 1245x 1245x 1245x 1245x 1245x 1245x 1245x 1245x 1245x 1188x 1188x 1188x 1236x 2x 2x 1186x 1186x 1245x 1245x 1245x 1245x 164x 1245x 1245x 1245x 1245x 1245x 1245x 1245x 1245x 1245x 1245x 1245x 1245x 1245x 1245x 1245x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 563x 563x 563x 563x 563x 563x 563x 563x 563x 563x 563x 563x 563x 563x 563x 598x 598x 598x 598x 598x 598x 336x 504x 37x 37x 72x 72x 72x 72x 72x 72x 37x 37x 563x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 1257x 1257x 1257x 1257x 1257x 1257x 1257x 1257x 1257x 1257x 1304x 1x 1x 1x 1x 1x 1x 1x 1x 1303x 1303x 1303x 1289x 1289x 1289x 1x 1x 1x 1x 1x 1x 1289x 1302x 1302x 1257x 1257x 1257x 1257x 1257x 1219x 1219x 1252x 1x 1x 1x 1x 1x 1x 1218x 1257x 1218x 1257x 2x 2x 1216x 1216x 1216x 1216x 1216x 1216x 1216x 1252x 43x 43x 1216x 1216x 1216x 1216x 1216x 1216x     1216x 1216x 1257x               1216x 1252x 12x 12x 12x 12x 12x 12x 12x 12x 12x 1204x 1248x 1x 1x 1x 1x 1x 1x 1x 1203x 1203x 1234x 1257x 1257x 698x 1257x 4x 4x 4x 4x 4x 4x 4x 1199x 1199x 1199x 1199x 1199x 1199x 1257x 145x 145x 38x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x             4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 7x 7x 7x 7x   4x 4x 4x 4x 4x 1x     1x 1x 1x 4x 1x 4x 4x 4x 4x 1x 1x 4x 4x 38x 145x 145x 155x 155x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 1616x 1616x 1616x 1616x 1616x 1616x 1616x 1616x 1616x 11x 1616x 10x 10x 10x 10x 10x 10x 1606x 1606x 1606x 1606x 1606x 1606x 1606x 1606x 1606x 1606x 1606x 1606x 1606x 1606x 1606x 1701x 1701x 1701x 1701x 1701x 1701x 1701x 1606x 1606x 1606x 1606x 1606x 1481x 1481x 1605x             1481x 1616x 1481x 1616x 2x 2x 1479x 1479x 1479x 1479x 1479x 1479x 1479x 1515x 1616x 1616x 2x 2x 2x 2x 2x 2x 2x 1477x 1605x                   1477x 1477x 1578x 1288x 1288x 1288x 1x 1x 1x 1x 1x 1x 1x 1288x 1476x 1476x 1476x 1476x 1476x 1616x 145x 145x 145x 145x 145x  
'use strict';
 
// This is needed to avoid cycles in esm/resolve <-> cjs/loader
require('internal/modules/cjs/loader');
 
const {
  Array,
  ArrayIsArray,
  ArrayPrototypeJoin,
  ArrayPrototypePush,
  FunctionPrototypeBind,
  FunctionPrototypeCall,
  ObjectAssign,
  ObjectCreate,
  ObjectDefineProperty,
  ObjectSetPrototypeOf,
  PromiseAll,
  ReflectApply,
  RegExpPrototypeExec,
  SafeArrayIterator,
  SafeWeakMap,
  StringPrototypeSlice,
  StringPrototypeToUpperCase,
  globalThis,
} = primordials;
const { MessageChannel } = require('internal/worker/io');
 
const {
  ERR_LOADER_CHAIN_INCOMPLETE,
  ERR_INTERNAL_ASSERTION,
  ERR_INVALID_ARG_TYPE,
  ERR_INVALID_ARG_VALUE,
  ERR_INVALID_RETURN_PROPERTY_VALUE,
  ERR_INVALID_RETURN_VALUE,
  ERR_UNKNOWN_MODULE_FORMAT,
} = require('internal/errors').codes;
const { pathToFileURL, isURLInstance, URL } = require('internal/url');
const { emitExperimentalWarning } = require('internal/util');
const {
  isAnyArrayBuffer,
  isArrayBufferView,
} = require('internal/util/types');
const {
  validateObject,
  validateString,
} = require('internal/validators');
const ModuleMap = require('internal/modules/esm/module_map');
const ModuleJob = require('internal/modules/esm/module_job');
 
const {
  defaultResolve,
  DEFAULT_CONDITIONS,
} = require('internal/modules/esm/resolve');
const {
  initializeImportMeta
} = require('internal/modules/esm/initialize_import_meta');
const { defaultLoad } = require('internal/modules/esm/load');
const { translators } = require(
  'internal/modules/esm/translators');
const { getOptionValue } = require('internal/options');
 
/**
 * @typedef {object} ExportedHooks
 * @property {Function} globalPreload
 * @property {Function} resolve
 * @property {Function} load
 */
 
/**
 * @typedef {Record<string, any>} ModuleExports
 */
 
/**
 * @typedef {object} KeyedExports
 * @property {ModuleExports} exports
 * @property {URL['href']} url
 */
 
/**
 * @typedef {object} KeyedHook
 * @property {Function} fn
 * @property {URL['href']} url
 */
 
/**
 * @typedef {'builtin'|'commonjs'|'json'|'module'|'wasm'} ModuleFormat
 */
 
/**
 * @typedef {ArrayBuffer|TypedArray|string} ModuleSource
 */
 
// [2] `validate...()`s throw the wrong error
 
let emittedSpecifierResolutionWarning = false;
 
/**
 * A utility function to iterate through a hook chain, track advancement in the
 * chain, and generate and supply the `next<HookName>` argument to the custom
 * hook.
 * @param {KeyedHook[]} chain The whole hook chain.
 * @param {object} meta Properties that change as the current hook advances
 * along the chain.
 * @param {boolean} meta.chainFinished Whether the end of the chain has been
 * reached AND invoked.
 * @param {string} meta.hookErrIdentifier A user-facing identifier to help
 *  pinpoint where an error occurred. Ex "file:///foo.mjs 'resolve'".
 * @param {number} meta.hookIndex A non-negative integer tracking the current
 * position in the hook chain.
 * @param {string} meta.hookName The kind of hook the chain is (ex 'resolve')
 * @param {boolean} meta.shortCircuited Whether a hook signaled a short-circuit.
 * @param {(hookErrIdentifier, hookArgs) => void} validate A wrapper function
 *  containing all validation of a custom loader hook's intermediary output. Any
 *  validation within MUST throw.
 * @returns {function next<HookName>(...hookArgs)} The next hook in the chain.
 */
function nextHookFactory(chain, meta, validate) {
  // First, prepare the current
  const { hookName } = meta;
  const {
    fn: hook,
    url: hookFilePath,
  } = chain[meta.hookIndex];
 
  // ex 'nextResolve'
  const nextHookName = `next${
    StringPrototypeToUpperCase(hookName[0]) +
    StringPrototypeSlice(hookName, 1)
  }`;
 
  // When hookIndex is 0, it's reached the default, which does not call next()
  // so feed it a noop that blows up if called, so the problem is obvious.
  const generatedHookIndex = meta.hookIndex;
  let nextNextHook;
  if (meta.hookIndex > 0) {
    // Now, prepare the next: decrement the pointer so the next call to the
    // factory generates the next link in the chain.
    meta.hookIndex--;
 
    nextNextHook = nextHookFactory(chain, meta, validate);
  } else {
    // eslint-disable-next-line func-name-matching
    nextNextHook = function chainAdvancedTooFar() {
      throw new ERR_INTERNAL_ASSERTION(
        `ESM custom loader '${hookName}' advanced beyond the end of the chain.`
      );
    };
  }
 
  return ObjectDefineProperty(
    async (...args) => {
      // Update only when hook is invoked to avoid fingering the wrong filePath
      meta.hookErrIdentifier = `${hookFilePath} '${hookName}'`;
 
      validate(`${meta.hookErrIdentifier} hook's ${nextHookName}()`, args);
 
      // Set when next<HookName> is actually called, not just generated.
      if (generatedHookIndex === 0) { meta.chainFinished = true; }
 
      ArrayPrototypePush(args, nextNextHook);
      const output = await ReflectApply(hook, undefined, args);
 
      if (output?.shortCircuit === true) { meta.shortCircuited = true; }
      return output;
 
    },
    'name',
    { __proto__: null, value: nextHookName },
  );
}
 
/**
 * An ESMLoader instance is used as the main entry point for loading ES modules.
 * Currently, this is a singleton -- there is only one used for loading
 * the main module and everything in its dependency graph.
 */
class ESMLoader {
  /**
   * Prior to ESM loading. These are called once before any modules are started.
   * @private
   * @property {KeyedHook[]} globalPreloaders Last-in-first-out
   *  list of preload hooks.
   */
  #globalPreloaders = [];
 
  /**
   * Phase 2 of 2 in ESM loading.
   * @private
   * @property {KeyedHook[]} loaders Last-in-first-out
   *  collection of loader hooks.
   */
  #loaders = [
    {
      fn: defaultLoad,
      url: 'node:internal/modules/esm/load',
    },
  ];
 
  /**
   * Phase 1 of 2 in ESM loading.
   * @private
   * @property {KeyedHook[]} resolvers Last-in-first-out
   *  collection of resolver hooks.
   */
  #resolvers = [
    {
      fn: defaultResolve,
      url: 'node:internal/modules/esm/resolve',
    },
  ];
 
  #importMetaInitializer = initializeImportMeta;
 
  /**
   * Map of already-loaded CJS modules to use
   */
  cjsCache = new SafeWeakMap();
 
  /**
   * The index for assigning unique URLs to anonymous module evaluation
   */
  evalIndex = 0;
 
  /**
   * Registry of loaded modules, akin to `require.cache`
   */
  moduleMap = new ModuleMap();
 
  /**
   * Methods which translate input code or other information into ES modules
   */
  translators = translators;
 
  constructor() {
    if (getOptionValue('--experimental-loader').length > 0) {
      emitExperimentalWarning('Custom ESM Loaders');
    }
    if (getOptionValue('--experimental-network-imports')) {
      emitExperimentalWarning('Network Imports');
    }
    if (
      !emittedSpecifierResolutionWarning &&
      getOptionValue('--experimental-specifier-resolution') === 'node'
    ) {
      process.emitWarning(
        'The Node.js specifier resolution flag is experimental. It could change or be removed at any time.',
        'ExperimentalWarning'
      );
      emittedSpecifierResolutionWarning = true;
    }
  }
 
  /**
   *
   * @param {ModuleExports} exports
   * @returns {ExportedHooks}
   */
  static pluckHooks({
    globalPreload,
    resolve,
    load,
    // obsolete hooks:
    dynamicInstantiate,
    getFormat,
    getGlobalPreloadCode,
    getSource,
    transformSource,
  }) {
    const obsoleteHooks = [];
    const acceptedHooks = ObjectCreate(null);
 
    if (getGlobalPreloadCode) {
      globalPreload ??= getGlobalPreloadCode;

      process.emitWarning(
        'Loader hook "getGlobalPreloadCode" has been renamed to "globalPreload"'
      );
    }
    if (dynamicInstantiate) ArrayPrototypePush(
      obsoleteHooks,
      'dynamicInstantiate'
    );
    if (getFormat) ArrayPrototypePush(
      obsoleteHooks,
      'getFormat',
    );
    if (getSource) ArrayPrototypePush(
      obsoleteHooks,
      'getSource',
    );
    if (transformSource) ArrayPrototypePush(
      obsoleteHooks,
      'transformSource',
    );
 
    if (obsoleteHooks.length) process.emitWarning(
      `Obsolete loader hook(s) supplied and will be ignored: ${
        ArrayPrototypeJoin(obsoleteHooks, ', ')
      }`,
      'DeprecationWarning',
    );
 
    // Use .bind() to avoid giving access to the Loader instance when called.
    if (globalPreload) {
      acceptedHooks.globalPreloader =
        FunctionPrototypeBind(globalPreload, null);
    }
    if (resolve) {
      acceptedHooks.resolver = FunctionPrototypeBind(resolve, null);
    }
    if (load) {
      acceptedHooks.loader = FunctionPrototypeBind(load, null);
    }
 
    return acceptedHooks;
  }
 
  /**
   * Collect custom/user-defined hook(s). After all hooks have been collected,
   * calls global preload hook(s).
   * @param {KeyedExports} customLoaders
   *  A list of exports from user-defined loaders (as returned by
   *  ESMLoader.import()).
   */
  async addCustomLoaders(
    customLoaders = [],
  ) {
    for (let i = 0; i < customLoaders.length; i++) {
      const {
        exports,
        url,
      } = customLoaders[i];
      const {
        globalPreloader,
        resolver,
        loader,
      } = ESMLoader.pluckHooks(exports);
 
      if (globalPreloader) {
        ArrayPrototypePush(
          this.#globalPreloaders,
          {
            fn: FunctionPrototypeBind(globalPreloader), // [1]
            url,
          },
        );
      }
      if (resolver) {
        ArrayPrototypePush(
          this.#resolvers,
          {
            fn: FunctionPrototypeBind(resolver), // [1]
            url,
          },
        );
      }
      if (loader) {
        ArrayPrototypePush(
          this.#loaders,
          {
            fn: FunctionPrototypeBind(loader), // [1]
            url,
          },
        );
      }
    }
 
    // [1] ensure hook function is not bound to ESMLoader instance
 
    this.preload();
  }
 
  async eval(
    source,
    url = pathToFileURL(`${process.cwd()}/[eval${++this.evalIndex}]`).href
  ) {
    const evalInstance = (url) => {
      const { ModuleWrap, callbackMap } = internalBinding('module_wrap');
      const module = new ModuleWrap(url, undefined, source, 0, 0);
      callbackMap.set(module, {
        importModuleDynamically: (specifier, { url }, importAssertions) => {
          return this.import(specifier, url, importAssertions);
        }
      });
 
      return module;
    };
    const job = new ModuleJob(
      this, url, undefined, evalInstance, false, false);
    this.moduleMap.set(url, undefined, job);
    const { module } = await job.run();
 
    return {
      namespace: module.getNamespace(),
    };
  }
 
  /**
   * Get a (possibly still pending) module job from the cache,
   * or create one and return its Promise.
   * @param {string} specifier The string after `from` in an `import` statement,
   *                           or the first parameter of an `import()`
   *                           expression
   * @param {string | undefined} parentURL The URL of the module importing this
   *                                     one, unless this is the Node.js entry
   *                                     point.
   * @param {Record<string, string>} importAssertions Validations for the
   *                                                  module import.
   * @returns {Promise<ModuleJob>} The (possibly pending) module job
   */
  async getModuleJob(specifier, parentURL, importAssertions) {
    let importAssertionsForResolve;
 
    // By default, `this.#loaders` contains just the Node default load hook
    if (this.#loaders.length !== 1) {
      // We can skip cloning if there are no user-provided loaders because
      // the Node.js default resolve hook does not use import assertions.
      importAssertionsForResolve = ObjectAssign(
        ObjectCreate(null),
        importAssertions,
      );
    }
 
    const { format, url } =
      await this.resolve(specifier, parentURL, importAssertionsForResolve);
 
    let job = this.moduleMap.get(url, importAssertions.type);
 
    // CommonJS will set functions for lazy job evaluation.
    if (typeof job === 'function') {
      this.moduleMap.set(url, undefined, job = job());
    }
 
    if (job === undefined) {
      job = this.#createModuleJob(url, importAssertions, parentURL, format);
    }
 
    return job;
  }
 
  /**
   * Create and cache an object representing a loaded module.
   * @param {string} url The absolute URL that was resolved for this module
   * @param {Record<string, string>} importAssertions Validations for the
   *                                                  module import.
   * @param {string} [parentURL] The absolute URL of the module importing this
   *                             one, unless this is the Node.js entry point
   * @param {string} [format] The format hint possibly returned by the
   *                          `resolve` hook
   * @returns {Promise<ModuleJob>} The (possibly pending) module job
   */
  #createModuleJob(url, importAssertions, parentURL, format) {
    const moduleProvider = async (url, isMain) => {
      const {
        format: finalFormat,
        responseURL,
        source,
      } = await this.load(url, {
        format,
        importAssertions,
      });
 
      const translator = translators.get(finalFormat);
 
      if (!translator) {
        throw new ERR_UNKNOWN_MODULE_FORMAT(finalFormat, responseURL);
      }
 
      return FunctionPrototypeCall(translator, this, responseURL, source, isMain);
    };
 
    const inspectBrk = (
      parentURL === undefined &&
      getOptionValue('--inspect-brk')
    );
 
    const job = new ModuleJob(
      this,
      url,
      importAssertions,
      moduleProvider,
      parentURL === undefined,
      inspectBrk
    );
 
    this.moduleMap.set(url, importAssertions.type, job);
 
    return job;
  }
 
  /**
   * This method is usually called indirectly as part of the loading processes.
   * Internally, it is used directly to add loaders. Use directly with caution.
   *
   * This method must NOT be renamed: it functions as a dynamic import on a
   * loader module.
   *
   * @param {string | string[]} specifiers Path(s) to the module.
   * @param {string} parentURL Path of the parent importing the module.
   * @param {Record<string, string>} importAssertions Validations for the
   *                                                  module import.
   * @returns {Promise<ExportedHooks | KeyedExports[]>}
   *  A collection of module export(s) or a list of collections of module
   *  export(s).
   */
  async import(specifiers, parentURL, importAssertions) {
    // For loaders, `import` is passed multiple things to process, it returns a
    // list pairing the url and exports collected. This is especially useful for
    // error messaging, to identity from where an export came. But, in most
    // cases, only a single url is being "imported" (ex `import()`), so there is
    // only 1 possible url from which the exports were collected and it is
    // already known to the caller. Nesting that in a list would only ever
    // create redundant work for the caller, so it is later popped off the
    // internal list.
    const wasArr = ArrayIsArray(specifiers);
    if (!wasArr) { specifiers = [specifiers]; }
 
    const count = specifiers.length;
    const jobs = new Array(count);
 
    for (let i = 0; i < count; i++) {
      jobs[i] = this.getModuleJob(specifiers[i], parentURL, importAssertions)
        .then((job) => job.run())
        .then(({ module }) => module.getNamespace());
    }
 
    const namespaces = await PromiseAll(new SafeArrayIterator(jobs));
 
    if (!wasArr) { return namespaces[0]; } // We can skip the pairing below
 
    for (let i = 0; i < count; i++) {
      const namespace = ObjectCreate(null);
      namespace.url = specifiers[i];
      namespace.exports = namespaces[i];
 
      namespaces[i] = namespace;
    }
 
    return namespaces;
  }
 
  /**
   * Provide source that is understood by one of Node's translators.
   *
   * Internally, this behaves like a backwards iterator, wherein the stack of
   * hooks starts at the top and each call to `nextLoad()` moves down 1 step
   * until it reaches the bottom or short-circuits.
   *
   * @param {URL['href']} url The URL/path of the module to be loaded
   * @param {object} context Metadata about the module
   * @returns {{ format: ModuleFormat, source: ModuleSource }}
   */
  async load(url, context = {}) {
    const chain = this.#loaders;
    const meta = {
      chainFinished: null,
      hookErrIdentifier: '',
      hookIndex: chain.length - 1,
      hookName: 'load',
      shortCircuited: false,
    };
 
    const validate = (hookErrIdentifier, { 0: nextUrl, 1: ctx }) => {
      if (typeof nextUrl !== 'string') {
        // non-strings can be coerced to a url string
        // validateString() throws a less-specific error
        throw new ERR_INVALID_ARG_TYPE(
          `${hookErrIdentifier} url`,
          'a url string',
          nextUrl,
        );
      }
 
      // Try to avoid expensive URL instantiation for known-good urls
      if (!this.moduleMap.has(nextUrl)) {
        try {
          new URL(nextUrl);
        } catch {
          throw new ERR_INVALID_ARG_VALUE(
            `${hookErrIdentifier} url`,
            nextUrl,
            'should be a url string',
          );
        }
      }
 
      validateObject(ctx, `${hookErrIdentifier} context`);
    };
 
    const nextLoad = nextHookFactory(chain, meta, validate);
 
    const loaded = await nextLoad(url, context);
    const { hookErrIdentifier } = meta; // Retrieve the value after all settled
 
    if (typeof loaded !== 'object') { // [2]
      throw new ERR_INVALID_RETURN_VALUE(
        'an object',
        hookErrIdentifier,
        loaded,
      );
    }
 
    if (loaded?.shortCircuit === true) { meta.shortCircuited = true; }
 
    if (!meta.chainFinished && !meta.shortCircuited) {
      throw new ERR_LOADER_CHAIN_INCOMPLETE(hookErrIdentifier);
    }
 
    const {
      format,
      source,
    } = loaded;
    let responseURL = loaded.responseURL;
 
    if (responseURL === undefined) {
      responseURL = url;
    }
 
    let responseURLObj;
    if (typeof responseURL === 'string') {
      try {
        responseURLObj = new URL(responseURL);
      } catch {
        // responseURLObj not defined will throw in next branch.
      }
    }
 
    if (responseURLObj?.href !== responseURL) {
      throw new ERR_INVALID_RETURN_PROPERTY_VALUE(
        'undefined or a fully resolved URL string',
        hookErrIdentifier,
        'responseURL',
        responseURL,
      );
    }
 
    if (format == null) {
      const dataUrl = RegExpPrototypeExec(
        /^data:([^/]+\/[^;,]+)(?:[^,]*?)(;base64)?,/,
        url,
      );
 
      throw new ERR_UNKNOWN_MODULE_FORMAT(
        dataUrl ? dataUrl[1] : format,
        url);
    }
 
    if (typeof format !== 'string') { // [2]
      throw new ERR_INVALID_RETURN_PROPERTY_VALUE(
        'a string',
        hookErrIdentifier,
        'format',
        format,
      );
    }
 
    if (
      source != null &&
      typeof source !== 'string' &&
      !isAnyArrayBuffer(source) &&
      !isArrayBufferView(source)
    ) {
      throw ERR_INVALID_RETURN_PROPERTY_VALUE(
        'a string, an ArrayBuffer, or a TypedArray',
        hookErrIdentifier,
        'source',
        source
      );
    }
 
    return {
      format,
      responseURL,
      source,
    };
  }
 
  preload() {
    for (let i = this.#globalPreloaders.length - 1; i >= 0; i--) {
      const channel = new MessageChannel();
      const {
        port1: insidePreload,
        port2: insideLoader,
      } = channel;
 
      insidePreload.unref();
      insideLoader.unref();
 
      const {
        fn: preloader,
        url: specifier,
      } = this.#globalPreloaders[i];
 
      const preload = preloader({
        port: insideLoader,
      });
 
      if (preload == null) { return; }
 
      const hookErrIdentifier = `${specifier} globalPreload`;
 
      if (typeof preload !== 'string') { // [2]
        throw new ERR_INVALID_RETURN_VALUE(
          'a string',
          hookErrIdentifier,
          preload,
        );
      }
      const { compileFunction } = require('vm');
      const preloadInit = compileFunction(
        preload,
        ['getBuiltin', 'port', 'setImportMetaCallback'],
        {
          filename: '<preload>',
        }
      );
      const { NativeModule } = require('internal/bootstrap/loaders');
      // We only allow replacing the importMetaInitializer during preload,
      // after preload is finished, we disable the ability to replace it
      //
      // This exposes accidentally setting the initializer too late by
      // throwing an error.
      let finished = false;
      let replacedImportMetaInitializer = false;
      let next = this.#importMetaInitializer;
      try {
        // Calls the compiled preload source text gotten from the hook
        // Since the parameters are named we use positional parameters
        // see compileFunction above to cross reference the names
        FunctionPrototypeCall(
          preloadInit,
          globalThis,
          // Param getBuiltin
          (builtinName) => {
            if (NativeModule.canBeRequiredByUsers(builtinName) &&
                NativeModule.canBeRequiredWithoutScheme(builtinName)) {
              return require(builtinName);
            }
            throw new ERR_INVALID_ARG_VALUE('builtinName', builtinName);
          },
          // Param port
          insidePreload,
          // Param setImportMetaCallback
          (fn) => {
            if (finished || typeof fn !== 'function') {
              throw new ERR_INVALID_ARG_TYPE('fn', fn);
            }
            replacedImportMetaInitializer = true;
            const parent = next;
            next = (meta, context) => {
              return fn(meta, context, parent);
            };
          });
      } finally {
        finished = true;
        if (replacedImportMetaInitializer) {
          this.#importMetaInitializer = next;
        }
      }
    }
  }
 
  importMetaInitialize(meta, context) {
    this.#importMetaInitializer(meta, context);
  }
 
  /**
   * Resolve the location of the module.
   *
   * Internally, this behaves like a backwards iterator, wherein the stack of
   * hooks starts at the top and each call to `nextResolve()` moves down 1 step
   * until it reaches the bottom or short-circuits.
   *
   * @param {string} originalSpecifier The specified URL path of the module to
   *                                   be resolved.
   * @param {string} [parentURL] The URL path of the module's parent.
   * @param {ImportAssertions} [importAssertions] Assertions from the import
   *                                              statement or expression.
   * @returns {{ format: string, url: URL['href'] }}
   */
  async resolve(
    originalSpecifier,
    parentURL,
    importAssertions = ObjectCreate(null)
  ) {
    const isMain = parentURL === undefined;
 
    if (
      !isMain &&
      typeof parentURL !== 'string' &&
      !isURLInstance(parentURL)
    ) {
      throw new ERR_INVALID_ARG_TYPE(
        'parentURL',
        ['string', 'URL'],
        parentURL,
      );
    }
    const chain = this.#resolvers;
    const meta = {
      chainFinished: null,
      hookErrIdentifier: '',
      hookIndex: chain.length - 1,
      hookName: 'resolve',
      shortCircuited: false,
    };
 
    const context = {
      conditions: DEFAULT_CONDITIONS,
      importAssertions,
      parentURL,
    };
    const validate = (hookErrIdentifier, { 0: suppliedSpecifier, 1: ctx }) => {
 
      validateString(
        suppliedSpecifier,
        `${hookErrIdentifier} specifier`,
      ); // non-strings can be coerced to a url string
 
      validateObject(ctx, `${hookErrIdentifier} context`);
    };
 
    const nextResolve = nextHookFactory(chain, meta, validate);
 
    const resolution = await nextResolve(originalSpecifier, context);
    const { hookErrIdentifier } = meta; // Retrieve the value after all settled
 
    if (typeof resolution !== 'object') { // [2]
      throw new ERR_INVALID_RETURN_VALUE(
        'an object',
        hookErrIdentifier,
        resolution,
      );
    }
 
    if (resolution?.shortCircuit === true) { meta.shortCircuited = true; }
 
    if (!meta.chainFinished && !meta.shortCircuited) {
      throw new ERR_LOADER_CHAIN_INCOMPLETE(hookErrIdentifier);
    }
 
    const {
      format,
      url,
    } = resolution;
 
    if (
      format != null &&
      typeof format !== 'string' // [2]
    ) {
      throw new ERR_INVALID_RETURN_PROPERTY_VALUE(
        'a string',
        hookErrIdentifier,
        'format',
        format,
      );
    }
 
    if (typeof url !== 'string') {
      // non-strings can be coerced to a url string
      // validateString() throws a less-specific error
      throw new ERR_INVALID_RETURN_PROPERTY_VALUE(
        'a url string',
        hookErrIdentifier,
        'url',
        url,
      );
    }
 
    // Try to avoid expensive URL instantiation for known-good urls
    if (!this.moduleMap.has(url)) {
      try {
        new URL(url);
      } catch {
        throw new ERR_INVALID_RETURN_PROPERTY_VALUE(
          'a url string',
          hookErrIdentifier,
          'url',
          url,
        );
      }
    }
 
    return {
      format,
      url,
    };
  }
}
 
ObjectSetPrototypeOf(ESMLoader.prototype, null);
 
exports.ESMLoader = ESMLoader;