diff --git a/doc/api/errors.md b/doc/api/errors.md
index 5bc949d5b12..801f22727f3 100644
--- a/doc/api/errors.md
+++ b/doc/api/errors.md
@@ -2092,6 +2092,17 @@ An attempt was made to open an IPC communication channel with a synchronously
forked Node.js process. See the documentation for the [`child_process`][] module
for more information.
+
+
+### `ERR_LOADER_CHAIN_INCOMPLETE`
+
+
+
+An ESM loader hook returned without calling `next()` and without explicitly
+signaling a short circuit.
+
### `ERR_MANIFEST_ASSERT_INTEGRITY`
diff --git a/doc/api/esm.md b/doc/api/esm.md
index 3d09cc03bba..fd128397f49 100644
--- a/doc/api/esm.md
+++ b/doc/api/esm.md
@@ -7,6 +7,10 @@
> The loaders API is being redesigned. This hook may disappear or its
> signature may change. Do not rely on the API described below.
@@ -785,15 +835,21 @@ export async function resolve(specifier, context, defaultResolve) {
> In a previous version of this API, this was split across 3 separate, now
> deprecated, hooks (`getFormat`, `getSource`, and `transformSource`).
-* `url` {string}
+* `url` {string} The URL returned by the `resolve` chain
* `context` {Object}
+ * `conditions` {string\[]} Export conditions of the relevant `package.json`
* `format` {string|null|undefined} The format optionally supplied by the
- `resolve` hook.
+ `resolve` hook chain
* `importAssertions` {Object}
-* `defaultLoad` {Function}
+* `nextLoad` {Function} The subsequent `load` hook in the chain, or the
+ Node.js default `load` hook after the last user-supplied `load` hook
+ * `specifier` {string}
+ * `context` {Object}
* Returns: {Object}
* `format` {string}
- * `source` {string|ArrayBuffer|TypedArray}
+ * `shortCircuit` {undefined|boolean} A signal that this hook intends to
+ terminate the chain of `resolve` hooks. **Default:** `false`
+ * `source` {string|ArrayBuffer|TypedArray} The source for Node.js to evaluate
The `load` hook provides a way to define a custom method of determining how
a URL should be interpreted, retrieved, and parsed. It is also in charge of
@@ -834,20 +890,10 @@ avoid reading files from disk. It could also be used to map an unrecognized
format to a supported one, for example `yaml` to `module`.
```js
-/**
- * @param {string} url
- * @param {{
- format: string,
- }} context If resolve settled with a `format`, that value is included here.
- * @param {Function} defaultLoad
- * @returns {Promise<{
- format: string,
- source: string | ArrayBuffer | SharedArrayBuffer | Uint8Array,
- }>}
- */
-export async function load(url, context, defaultLoad) {
+export async function load(url, context, nextLoad) {
const { format } = context;
- if (Math.random() > 0.5) { // Some condition.
+
+ if (Math.random() > 0.5) { // Some condition
/*
For some or all URLs, do some custom logic for retrieving the source.
Always return an object of the form {
@@ -857,11 +903,13 @@ export async function load(url, context, defaultLoad) {
*/
return {
format,
+ shortCircuit: true,
source: '...',
};
}
- // Defer to Node.js for all other URLs.
- return defaultLoad(url, context, defaultLoad);
+
+ // Defer to the next hook in the chain.
+ return nextLoad(url, context);
}
```
@@ -870,13 +918,22 @@ source to a supported one (see [Examples](#examples) below).
#### `globalPreload()`
+
+
> The loaders API is being redesigned. This hook may disappear or its
> signature may change. Do not rely on the API described below.
> In a previous version of this API, this hook was named
> `getGlobalPreloadCode`.
-* Returns: {string}
+* `context` {Object} Information to assist the preload code
+ * `port` {MessagePort}
+* Returns: {string} Code to run before application startup
Sometimes it might be necessary to run some code inside of the same global
scope that the application runs in. This hook allows the return of a string
@@ -890,13 +947,7 @@ If the code needs more advanced `require` features, it has to construct
its own `require` using `module.createRequire()`.
```js
-/**
- * @param {{
- port: MessagePort,
- }} utilities Things that preload code might find useful
- * @returns {string} Code to run before application startup
- */
-export function globalPreload(utilities) {
+export function globalPreload(context) {
return `\
globalThis.someInjectedProperty = 42;
console.log('I just set some globals!');
@@ -921,10 +972,6 @@ close normally.
/**
* This example has the application context send a message to the loader
* and sends the message back to the application context
- * @param {{
- port: MessagePort,
- }} utilities Things that preload code might find useful
- * @returns {string} Code to run before application startup
*/
export function globalPreload({ port }) {
port.onmessage = (evt) => {
@@ -946,9 +993,11 @@ customizations of Node.js’ code loading and evaluation behaviors.
#### HTTPS loader
-In current Node.js, specifiers starting with `https://` are unsupported. The
-loader below registers hooks to enable rudimentary support for such specifiers.
-While this may seem like a significant improvement to Node.js core
+In current Node.js, specifiers starting with `https://` are experimental (see
+[HTTPS and HTTP imports][]).
+
+The loader below registers hooks to enable rudimentary support for such
+specifiers. While this may seem like a significant improvement to Node.js core
functionality, there are substantial downsides to actually using this loader:
performance is much slower than loading files from disk, there is no caching,
and there is no security.
@@ -957,7 +1006,7 @@ and there is no security.
// https-loader.mjs
import { get } from 'node:https';
-export function resolve(specifier, context, defaultResolve) {
+export function resolve(specifier, context, nextResolve) {
const { parentURL = null } = context;
// Normally Node.js would error on specifiers starting with 'https://', so
@@ -965,19 +1014,21 @@ export function resolve(specifier, context, defaultResolve) {
// passed along to the later hooks below.
if (specifier.startsWith('https://')) {
return {
+ shortCircuit: true,
url: specifier
};
} else if (parentURL && parentURL.startsWith('https://')) {
return {
- url: new URL(specifier, parentURL).href
+ shortCircuit: true,
+ url: new URL(specifier, parentURL).href,
};
}
// Let Node.js handle all other specifiers.
- return defaultResolve(specifier, context, defaultResolve);
+ return nextResolve(specifier, context);
}
-export function load(url, context, defaultLoad) {
+export function load(url, context, nextLoad) {
// For JavaScript to be loaded over the network, we need to fetch and
// return it.
if (url.startsWith('https://')) {
@@ -989,6 +1040,7 @@ export function load(url, context, defaultLoad) {
// This example assumes all network-provided JavaScript is ES module
// code.
format: 'module',
+ shortCircuit: true,
source: data,
}));
}).on('error', (err) => reject(err));
@@ -996,7 +1048,7 @@ export function load(url, context, defaultLoad) {
}
// Let Node.js handle all other URLs.
- return defaultLoad(url, context, defaultLoad);
+ return nextLoad(url, context);
}
```
@@ -1036,27 +1088,29 @@ const baseURL = pathToFileURL(`${cwd()}/`).href;
// CoffeeScript files end in .coffee, .litcoffee or .coffee.md.
const extensionsRegex = /\.coffee$|\.litcoffee$|\.coffee\.md$/;
-export async function resolve(specifier, context, defaultResolve) {
- const { parentURL = baseURL } = context;
-
- // Node.js normally errors on unknown file extensions, so return a URL for
- // specifiers ending in the CoffeeScript file extensions.
+export async function resolve(specifier, context, nextResolve) {
if (extensionsRegex.test(specifier)) {
+ const { parentURL = baseURL } = context;
+
+ // Node.js normally errors on unknown file extensions, so return a URL for
+ // specifiers ending in the CoffeeScript file extensions.
return {
+ shortCircuit: true,
url: new URL(specifier, parentURL).href
};
}
// Let Node.js handle all other specifiers.
- return defaultResolve(specifier, context, defaultResolve);
+ return nextResolve(specifier, context);
}
-export async function load(url, context, defaultLoad) {
- // Now that we patched resolve to let CoffeeScript URLs through, we need to
- // tell Node.js what format such URLs should be interpreted as. Because
- // CoffeeScript transpiles into JavaScript, it should be one of the two
- // JavaScript formats: 'commonjs' or 'module'.
+export async function load(url, context, nextLoad) {
if (extensionsRegex.test(url)) {
+ // Now that we patched resolve to let CoffeeScript URLs through, we need to
+ // tell Node.js what format such URLs should be interpreted as. Because
+ // CoffeeScript transpiles into JavaScript, it should be one of the two
+ // JavaScript formats: 'commonjs' or 'module'.
+
// CoffeeScript files can be either CommonJS or ES modules, so we want any
// CoffeeScript file to be treated by Node.js the same as a .js file at the
// same location. To determine how Node.js would interpret an arbitrary .js
@@ -1069,25 +1123,26 @@ export async function load(url, context, defaultLoad) {
// loader. Avoiding the need for a separate CommonJS handler is a future
// enhancement planned for ES module loaders.
if (format === 'commonjs') {
- return { format };
+ return {
+ format,
+ shortCircuit: true,
+ };
}
- const { source: rawSource } = await defaultLoad(url, { format });
+ const { source: rawSource } = await nextLoad(url, { ...context, format });
// This hook converts CoffeeScript source code into JavaScript source code
// for all imported CoffeeScript files.
- const transformedSource = CoffeeScript.compile(rawSource.toString(), {
- bare: true,
- filename: url,
- });
+ const transformedSource = coffeeCompile(rawSource.toString(), url);
return {
format,
+ shortCircuit: true,
source: transformedSource,
};
}
// Let Node.js handle all other URLs.
- return defaultLoad(url, context, defaultLoad);
+ return nextLoad(url, context);
}
async function getPackageType(url) {
@@ -1495,6 +1550,7 @@ success!
[Determining module system]: packages.md#determining-module-system
[Dynamic `import()`]: https://wiki.developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#Dynamic_Imports
[ES Module Integration Proposal for WebAssembly]: https://github.com/webassembly/esm-integration
+[HTTPS and HTTP imports]: #https-and-http-imports
[Import Assertions]: #import-assertions
[Import Assertions proposal]: https://github.com/tc39/proposal-import-assertions
[JSON modules]: #json-modules
@@ -1525,9 +1581,9 @@ success!
[`util.TextDecoder`]: util.md#class-utiltextdecoder
[cjs-module-lexer]: https://github.com/nodejs/cjs-module-lexer/tree/1.2.2
[custom https loader]: #https-loader
-[load hook]: #loadurl-context-defaultload
+[load hook]: #loadurl-context-nextload
[percent-encoded]: url.md#percent-encoding-in-urls
-[resolve hook]: #resolvespecifier-context-defaultresolve
+[resolve hook]: #resolvespecifier-context-nextresolve
[special scheme]: https://url.spec.whatwg.org/#special-scheme
[status code]: process.md#exit-codes
[the official standard format]: https://tc39.github.io/ecma262/#sec-modules
diff --git a/lib/internal/errors.js b/lib/internal/errors.js
index 2185e43a879..0afe58843ae 100644
--- a/lib/internal/errors.js
+++ b/lib/internal/errors.js
@@ -1359,6 +1359,13 @@ E('ERR_IPC_CHANNEL_CLOSED', 'Channel closed', Error);
E('ERR_IPC_DISCONNECTED', 'IPC channel is already disconnected', Error);
E('ERR_IPC_ONE_PIPE', 'Child process can have only one IPC pipe', Error);
E('ERR_IPC_SYNC_FORK', 'IPC cannot be used with synchronous forks', Error);
+E(
+ 'ERR_LOADER_CHAIN_INCOMPLETE',
+ 'The "%s" hook from %s did not call the next hook in its chain and did not' +
+ ' explicitly signal a short circuit. If this is intentional, include' +
+ ' `shortCircuit: true` in the hook\'s return.',
+ Error
+);
E('ERR_MANIFEST_ASSERT_INTEGRITY',
(moduleURL, realIntegrities) => {
let msg = `The content of "${
diff --git a/lib/internal/modules/esm/loader.js b/lib/internal/modules/esm/loader.js
index 39f8ebca59e..8bc22ef697d 100644
--- a/lib/internal/modules/esm/loader.js
+++ b/lib/internal/modules/esm/loader.js
@@ -23,12 +23,13 @@ const {
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
+ ERR_UNKNOWN_MODULE_FORMAT,
} = require('internal/errors').codes;
const { pathToFileURL, isURLInstance, URL } = require('internal/url');
const { emitExperimentalWarning } = require('internal/util');
@@ -36,6 +37,10 @@ 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');
@@ -56,10 +61,39 @@ const {
/**
- * Prevent the specifier resolution warning from being printed twice
+ * @typedef {object} ExportedHooks
+ * @property {Function} globalPreload
+ * @property {Function} resolve
+ * @property {Function} load
*/
-let emittedSpecifierResolutionWarning = false;
+/**
+ * @typedef {Record} 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;
/**
* An ESMLoader instance is used as the main entry point for loading ES modules.
@@ -70,27 +104,35 @@ class ESMLoader {
/**
* Prior to ESM loading. These are called once before any modules are started.
* @private
- * @property {Function[]} globalPreloaders First-in-first-out list of
- * preload hooks.
+ * @property {KeyedHook[]} globalPreloaders Last-in-first-out
+ * list of preload hooks.
*/
#globalPreloaders = [];
/**
* Phase 2 of 2 in ESM loading.
* @private
- * @property {Function[]} loaders First-in-first-out list of loader hooks.
+ * @property {KeyedHook[]} loaders Last-in-first-out
+ * collection of loader hooks.
*/
#loaders = [
- defaultLoad,
+ {
+ fn: defaultLoad,
+ url: 'node:internal/modules/esm/load',
+ },
];
/**
* Phase 1 of 2 in ESM loading.
* @private
- * @property {Function[]} resolvers First-in-first-out list of resolver hooks
+ * @property {KeyedHook[]} resolvers Last-in-first-out
+ * collection of resolver hooks.
*/
#resolvers = [
- defaultResolve,
+ {
+ fn: defaultResolve,
+ url: 'node:internal/modules/esm/resolve',
+ },
];
#importMetaInitializer = initializeImportMeta;
@@ -116,13 +158,16 @@ class ESMLoader {
translators = translators;
constructor() {
- if (getOptionValue('--experimental-loader')) {
+ if (getOptionValue('--experimental-loader').length > 0) {
emitExperimentalWarning('Custom ESM Loaders');
}
if (getOptionValue('--experimental-network-imports')) {
emitExperimentalWarning('Network Imports');
}
- if (getOptionValue('--experimental-specifier-resolution') === 'node' && !emittedSpecifierResolutionWarning) {
+ 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'
@@ -131,6 +176,11 @@ class ESMLoader {
}
}
+ /**
+ *
+ * @param {ModuleExports} exports
+ * @returns {ExportedHooks}
+ */
static pluckHooks({
globalPreload,
resolve,
@@ -194,34 +244,51 @@ class ESMLoader {
/**
* Collect custom/user-defined hook(s). After all hooks have been collected,
* calls global preload hook(s).
- * @param {object | object[]} customLoaders A list of exports from
- * user-defined loaders (as returned by ESMLoader.import()).
+ * @param {KeyedExports} customLoaders
+ * A list of exports from user-defined loaders (as returned by
+ * ESMLoader.import()).
*/
async addCustomLoaders(
customLoaders = [],
) {
- if (!ArrayIsArray(customLoaders)) customLoaders = [customLoaders];
-
for (let i = 0; i < customLoaders.length; i++) {
- const exports = customLoaders[i];
+ const {
+ exports,
+ url,
+ } = customLoaders[i];
const {
globalPreloader,
resolver,
loader,
} = ESMLoader.pluckHooks(exports);
- if (globalPreloader) ArrayPrototypePush(
- this.#globalPreloaders,
- FunctionPrototypeBind(globalPreloader, null), // [1]
- );
- if (resolver) ArrayPrototypePush(
- this.#resolvers,
- FunctionPrototypeBind(resolver, null), // [1]
- );
- if (loader) ArrayPrototypePush(
- this.#loaders,
- FunctionPrototypeBind(loader, null), // [1]
- );
+ 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
@@ -286,7 +353,7 @@ class ESMLoader {
// immediately and synchronously
url = fetchModule(new URL(url), { parentURL: url }).resolvedHREF;
// This should only occur if the module hasn't been fetched yet
- if (typeof url !== 'string') {
+ if (typeof url !== 'string') { // [2]
throw new ERR_INTERNAL_ASSERTION(`Base url for module ${url} not loaded.`);
}
}
@@ -308,12 +375,17 @@ class ESMLoader {
*/
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
+ // 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);
+ importAssertionsForResolve = ObjectAssign(
+ ObjectCreate(null),
+ importAssertions,
+ );
}
+
const { format, url } =
await this.resolve(specifier, parentURL, importAssertionsForResolve);
@@ -391,11 +463,21 @@ class ESMLoader {
* @param {string} parentURL Path of the parent importing the module.
* @param {Record} importAssertions Validations for the
* module import.
- * @returns {Promise