diff --git a/lib/internal/modules/esm/loader.js b/lib/internal/modules/esm/loader.js index ff99764566a4..0103831c9ef1 100644 --- a/lib/internal/modules/esm/loader.js +++ b/lib/internal/modules/esm/loader.js @@ -508,6 +508,15 @@ class ModuleLoader { return this.#getOrCreateModuleJobAfterResolve(parentURL, resolveResult, request, requestType); } + #canUseImportCache(specifier, parentURL, phase, isEntryPoint) { + return phase === kEvaluationPhase && + !isEntryPoint && + !onImport.hasSubscribers && + typeof specifier === 'string' && + typeof parentURL === 'string' && + syncResolveHooks.length === 0; + } + /** * This method is usually called indirectly as part of the loading processes. * Use directly with caution. @@ -520,6 +529,16 @@ class ModuleLoader { * @returns {Promise} */ async import(specifier, parentURL, importAttributes, phase = kEvaluationPhase, isEntryPoint = false) { + if (this.#canUseImportCache(specifier, parentURL, phase, isEntryPoint)) { + const requestKey = this.#resolveCache.serializeKey(specifier, importAttributes); + const resolved = this.#resolveCache.get(requestKey, parentURL); + if (resolved !== undefined) { + const job = this.loadCache.get(resolved.url, importAttributes.type); + if (job?.namespace !== undefined) { + return job.namespace; + } + } + } // tracePromise() ignores the context when there are no subscribers, so only // create it when there are: a `{ __proto__: null }` literal is created in // dictionary mode, and import() can be called on a hot path. @@ -537,7 +556,12 @@ class ModuleLoader { return module.getModuleSourceObject(); } const { module } = await moduleJob.run(isEntryPoint); - return module.getNamespace(); + const namespace = module.getNamespace(); + // Skip async graphs to avoid caching in-flight TLA modules before they settle. + if (!module.hasAsyncGraph) { + moduleJob.namespace = namespace; + } + return namespace; }, traceContext); } diff --git a/lib/internal/modules/esm/module_job.js b/lib/internal/modules/esm/module_job.js index 6c98644a7321..e05d676be763 100644 --- a/lib/internal/modules/esm/module_job.js +++ b/lib/internal/modules/esm/module_job.js @@ -304,6 +304,7 @@ class ModuleJobBase { this.inspectBrk = inspectBrk; this.url = url; + this.namespace = undefined; } /** diff --git a/lib/internal/modules/esm/module_map.js b/lib/internal/modules/esm/module_map.js index 9020768abffd..6c89669cb585 100644 --- a/lib/internal/modules/esm/module_map.js +++ b/lib/internal/modules/esm/module_map.js @@ -14,6 +14,7 @@ let debug = require('internal/util/debuglog').debuglog('esm', (fn) => { debug = fn; }); const { ERR_INVALID_ARG_TYPE } = require('internal/errors').codes; +const { kEmptyObject } = require('internal/util'); const { validateString } = require('internal/validators'); /** @@ -34,6 +35,9 @@ class ResolveCache extends SafeMap { * @returns {string} */ serializeKey(specifier, importAttributes) { + if (importAttributes === kEmptyObject) { + return specifier + '::'; + } // To serialize the ModuleRequest (specifier + list of import attributes), // we need to sort the attributes by key, then stringifying, // so that different import statements with the same attributes are always treated diff --git a/lib/internal/modules/esm/utils.js b/lib/internal/modules/esm/utils.js index b8c8b10d3867..55d68fd0b587 100644 --- a/lib/internal/modules/esm/utils.js +++ b/lib/internal/modules/esm/utils.js @@ -3,6 +3,7 @@ const { ArrayIsArray, ObjectFreeze, + SafeMap, SafeSet, SafeWeakMap, Symbol, @@ -40,6 +41,7 @@ const { const { getOptionValue } = require('internal/options'); const { emitExperimentalWarning, + getLazy, kEmptyObject, } = require('internal/util'); const assert = require('internal/assert'); @@ -203,6 +205,22 @@ function initializeImportMetaObject(symbol, meta, wrap) { } } +const getCascadedLoader = getLazy( + () => require('internal/modules/esm/loader').getOrInitializeCascadedLoader(), +); +const scriptReferrerURLCache = new SafeMap(); + +function getCachedScriptParentURL(referrerName) { + let parentURL = scriptReferrerURLCache.get(referrerName); + if (parentURL === undefined) { + parentURL = normalizeReferrerURL(referrerName); + if (typeof parentURL === 'string') { + scriptReferrerURLCache.set(referrerName, parentURL); + } + } + return parentURL; +} + /** * Proxy the dynamic import handling to the default loader for source text modules. * @param {string} specifier - The module specifier string. @@ -212,8 +230,7 @@ function initializeImportMetaObject(symbol, meta, wrap) { * @returns {Promise} - The imported module object. */ function defaultImportModuleDynamicallyForModule(specifier, phase, attributes, referrerName) { - const cascadedLoader = require('internal/modules/esm/loader').getOrInitializeCascadedLoader(); - return cascadedLoader.import(specifier, referrerName, attributes, phase); + return getCascadedLoader().import(specifier, referrerName, attributes, phase); } /** @@ -225,9 +242,8 @@ function defaultImportModuleDynamicallyForModule(specifier, phase, attributes, r * @returns {Promise} - The imported module object. */ function defaultImportModuleDynamicallyForScript(specifier, phase, attributes, referrerName) { - const parentURL = normalizeReferrerURL(referrerName); - const cascadedLoader = require('internal/modules/esm/loader').getOrInitializeCascadedLoader(); - return cascadedLoader.import(specifier, parentURL, attributes, phase); + const parentURL = getCachedScriptParentURL(referrerName); + return getCascadedLoader().import(specifier, parentURL, attributes, phase); } /** @@ -257,13 +273,13 @@ function importModuleDynamicallyForEmbedder(specifier, phase, attributes, referr * @param {symbol} referrerSymbol - Referrer symbol of the registered script, function, module, or contextified object. * @param {string} specifier - The module specifier string. * @param {number} phase - The module import phase. - * @param {Record} attributes - The import attributes object. + * @param {Record|undefined} attributes - The import attributes object, or undefined if empty. * @param {string|null|undefined} referrerName - name of the referrer. * @returns {Promise} - The imported module object. * @throws {ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING} - If the callback function is missing. */ -async function importModuleDynamicallyCallback(referrerSymbol, specifier, phase, attributes, - referrerName) { +async function importModuleDynamicallyCallback(referrerSymbol, specifier, phase, + attributes = kEmptyObject, referrerName) { // For user-provided vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER, emit the warning // and fall back to the default loader. if (referrerSymbol === vm_dynamic_import_main_context_default) { diff --git a/src/module_wrap.cc b/src/module_wrap.cc index 2e5b1810d4f2..8d2032d66c42 100644 --- a/src/module_wrap.cc +++ b/src/module_wrap.cc @@ -1171,8 +1171,12 @@ static MaybeLocal ImportModuleDynamicallyWithPhase( return MaybeLocal(); } - Local attributes = - createImportAttributesContainer(realm, isolate, import_attributes, 2); + Local attributes = + import_attributes->Length() == 0 + ? Undefined(isolate).As() + : createImportAttributesContainer( + realm, isolate, import_attributes, 2) + .As(); Local import_args[] = { id, diff --git a/test/es-module/test-esm-dynamic-import-cache.mjs b/test/es-module/test-esm-dynamic-import-cache.mjs new file mode 100644 index 000000000000..4e960ae8a455 --- /dev/null +++ b/test/es-module/test-esm-dynamic-import-cache.mjs @@ -0,0 +1,80 @@ +import '../common/index.mjs'; +import tmpdir from '../common/tmpdir.js'; + +import assert from 'node:assert'; +import dc from 'node:diagnostics_channel'; +import fs from 'node:fs'; +import { createRequire, registerHooks } from 'node:module'; +import util from 'node:util'; + +tmpdir.refresh(); + +fs.writeFileSync(tmpdir.resolve('a.mjs'), 'export const id = "a";\n'); +fs.writeFileSync(tmpdir.resolve('b.mjs'), 'export const id = "b";\n'); +fs.writeFileSync(tmpdir.resolve('caller.cjs'), 'module.exports = () => import("./a.mjs");\n'); +fs.writeFileSync(tmpdir.resolve('tla-fail.mjs'), + 'await new Promise((r) => setTimeout(r, 20)); throw new Error("tla-boom");\n'); +fs.writeFileSync(tmpdir.resolve('tla-entry.mjs'), 'import "./tla-fail.mjs";\n'); + +const urlA = tmpdir.fileURL('a.mjs').href; +const urlB = tmpdir.fileURL('b.mjs').href; +const urlTlaFail = tmpdir.fileURL('tla-fail.mjs').href; +const urlTlaEntry = tmpdir.fileURL('tla-entry.mjs').href; + +// 1. Cached dynamic import() returns a pending Promise resolving to the same namespace. +{ + const first = await import(urlA); + const promise = import(urlA); + assert.strictEqual(util.inspect(promise), 'Promise { }'); + assert.strictEqual(await promise, first); + assert.strictEqual(await Promise.race([import(urlA), Promise.resolve('sync')]), 'sync'); +} + +// 2. Resolve hooks registered after caching still intercept import(). +{ + const hook = registerHooks({ + resolve(specifier, context, nextResolve) { + return specifier === urlA ? { url: urlB, shortCircuit: true } : nextResolve(specifier, context); + }, + }); + try { + assert.strictEqual((await import(urlA)).id, 'b'); + } finally { + hook.deregister(); + } + assert.strictEqual((await import(urlA)).id, 'a'); +} + +// 3. diagnostics_channel('module.import') subscribed after caching still fires for ESM & CJS. +{ + const loadA = createRequire(import.meta.url)(tmpdir.resolve('caller.cjs')); + const cachedA = await loadA(); + const channel = dc.tracingChannel('module.import'); + const events = []; + const sub = { + start(ctx) { events.push(['start', ctx.parentURL, ctx.url]); }, + asyncEnd(ctx) { events.push(['asyncEnd', ctx.parentURL, ctx.url, ctx.result]); }, + }; + channel.subscribe(sub); + try { + assert.strictEqual(await import(urlA), cachedA); + assert.strictEqual(await loadA(), cachedA); + } finally { + channel.unsubscribe(sub); + } + const cjsParent = tmpdir.fileURL('caller.cjs').href; + assert.deepStrictEqual(events, [ + ['start', import.meta.url, urlA], + ['asyncEnd', import.meta.url, urlA, cachedA], + ['start', cjsParent, './a.mjs'], + ['asyncEnd', cjsParent, './a.mjs', cachedA], + ]); +} + +// 4. In-flight TLA dependencies are not cached before settling. +{ + const entry = import(urlTlaEntry); + await import(urlTlaFail); + await assert.rejects(entry, { message: 'tla-boom' }); + await assert.rejects(import(urlTlaFail), { message: 'tla-boom' }); +} diff --git a/test/parallel/test-vfs-scoped-cache-purge.js b/test/parallel/test-vfs-scoped-cache-purge.js index 031dc58cd15e..cb61cbbe1515 100644 --- a/test/parallel/test-vfs-scoped-cache-purge.js +++ b/test/parallel/test-vfs-scoped-cache-purge.js @@ -54,4 +54,9 @@ const vfsImport = (path) => pathToFileURL(path).href; assert.strictEqual(ns, nsAgain); v.unmount(); + + // Unmounting must also invalidate cached dynamic import() results. + await assert.rejects(import(vfsImport(`${mountPoint}/m.mjs`)), { + code: /^(ENOENT|ENOTDIR|ERR_MODULE_NOT_FOUND)$/, + }); })().then(common.mustCall());