diff --git a/doc/api/errors.md b/doc/api/errors.md
index d95266b7bebec0..45da62b3e0608a 100644
--- a/doc/api/errors.md
+++ b/doc/api/errors.md
@@ -2071,6 +2071,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 6b23178fa643c3..0f851c79fca44b 100644
--- a/doc/api/esm.md
+++ b/doc/api/esm.md
@@ -7,7 +7,12 @@
@@ -700,26 +739,35 @@ changes:
* `specifier` {string}
* `context` {Object}
- * `conditions` {string\[]}
+ * `conditions` {string\[]} Export conditions of the relevant `package.json`
* `importAssertions` {Object}
- * `parentURL` {string|undefined}
-* `defaultResolve` {Function} The Node.js default resolver.
+ * `parentURL` {string|undefined} The module importing this one, or undefined
+ if this is the Node.js entry point
+* `nextResolve` {Function} The subsequent `resolve` hook in the chain, or the
+ Node.js default `resolve` hook after the last user-supplied `resolve` hook
+ * `specifier` {string}
+ * `context` {Object}
* Returns: {Object}
- * `format` {string|null|undefined}
+ * `format` {string|null|undefined} A hint to the load hook (it might be
+ ignored)
`'builtin' | 'commonjs' | 'json' | 'module' | 'wasm'`
- * `url` {string} The absolute url to the import target (such as `file://…`)
-
-The `resolve` hook returns the resolved file URL for a given module specifier
-and parent URL, and optionally its format (such as `'module'`) as a hint to the
-`load` hook. If a format is specified, the `load` hook is ultimately responsible
-for providing the final `format` value (and it is free to ignore the hint
-provided by `resolve`); if `resolve` provides a `format`, a custom `load`
-hook is required even if only to pass the value to the Node.js default `load`
-hook.
+ * `shortCircuit` {undefined|boolean} A signal that this hook intends to
+ terminate the chain of `resolve` hooks. **Default:** `false`
+ * `url` {string} The absolute URL to which this input resolves
+
+The `resolve` hook chain is responsible for resolving file URL for a given
+module specifier and parent URL, and optionally its format (such as `'module'`)
+as a hint to the `load` hook. If a format is specified, the `load` hook is
+ultimately responsible for providing the final `format` value (and it is free to
+ignore the hint provided by `resolve`); if `resolve` provides a `format`, a
+custom `load` hook is required even if only to pass the value to the Node.js
+default `load` hook.
The module specifier is the string in an `import` statement or
-`import()` expression, and the parent URL is the URL of the module that imported
-this one, or `undefined` if this is the main entry point for the application.
+`import()` expression.
+
+The parent URL is the URL of the module that imported this one, or `undefined`
+if this is the main entry point for the application.
The `conditions` property in `context` is an array of conditions for
[package exports conditions][Conditional Exports] that apply to this resolution
@@ -733,40 +781,45 @@ Node.js module specifier resolution behavior_ when calling `defaultResolve`, the
`context.conditions` array originally passed into the `resolve` hook.
```js
-/**
- * @param {string} specifier
- * @param {{
- * conditions: string[],
- * parentURL: string | undefined,
- * }} context
- * @param {Function} defaultResolve
- * @returns {Promise<{ url: string }>}
- */
-export async function resolve(specifier, context, defaultResolve) {
+export async function resolve(specifier, context, nextResolve) {
const { parentURL = null } = context;
+
if (Math.random() > 0.5) { // Some condition.
// For some or all specifiers, do some custom logic for resolving.
// Always return an object of the form {url: }.
return {
+ shortCircuit: true,
url: parentURL ?
new URL(specifier, parentURL).href :
new URL(specifier).href,
};
}
+
if (Math.random() < 0.5) { // Another condition.
// When calling `defaultResolve`, the arguments can be modified. In this
// case it's adding another value for matching conditional exports.
- return defaultResolve(specifier, {
+ return nextResolve(specifier, {
...context,
conditions: [...context.conditions, 'another-condition'],
});
}
- // Defer to Node.js for all other specifiers.
- return defaultResolve(specifier, context, defaultResolve);
+
+ // Defer to the next hook in the chain, which would be the
+ // Node.js default resolve if this is the last user-specified loader.
+ return nextResolve(specifier, context);
}
```
-#### `load(url, context, defaultLoad)`
+#### `load(url, context, nextLoad)`
+
+
> The loaders API is being redesigned. This hook may disappear or its
> signature may change. Do not rely on the API described below.
@@ -774,15 +827,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
@@ -823,20 +882,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 {
@@ -846,11 +895,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);
}
```
@@ -859,13 +910,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
@@ -879,13 +939,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!');
@@ -910,10 +964,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) => {
@@ -935,9 +985,11 @@ customizations of the 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.
@@ -946,7 +998,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
@@ -954,19 +1006,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://')) {
@@ -978,6 +1032,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));
@@ -985,7 +1040,7 @@ export function load(url, context, defaultLoad) {
}
// Let Node.js handle all other URLs.
- return defaultLoad(url, context, defaultLoad);
+ return nextLoad(url, context);
}
```
@@ -1025,27 +1080,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
@@ -1058,25 +1115,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) {
@@ -1505,6 +1563,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
@@ -1535,9 +1594,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 1bb41fb0540918..fcb64bc02ae7b8 100644
--- a/lib/internal/errors.js
+++ b/lib/internal/errors.js
@@ -1358,6 +1358,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 0dccfebbd4f37f..b1c652a47dd5ce 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
+ */
+
+/**
+ * @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
*/
-let emittedSpecifierResolutionWarning = false;
+// [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