-
-
Notifications
You must be signed in to change notification settings - Fork 31.6k
module: ensure successful dynamic import returns the same result #46662
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
0f1fe00
3bf7e02
9f36bf7
aabe393
be69edd
dd06864
631d7c6
c279d18
56a8a07
abf105a
00ea14c
a791dc9
3638858
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,45 @@ | ||
// Tests the impact on eager operations required for policies affecting | ||
// general startup, does not test lazy operations | ||
'use strict'; | ||
const fs = require('node:fs'); | ||
const path = require('node:path'); | ||
const common = require('../common.js'); | ||
|
||
const tmpdir = require('../../test/common/tmpdir.js'); | ||
const { pathToFileURL } = require('node:url'); | ||
|
||
const benchmarkDirectory = pathToFileURL(path.resolve(tmpdir.path, 'benchmark-import')); | ||
|
||
const configs = { | ||
n: [1e3], | ||
specifier: [ | ||
'data:text/javascript,{i}', | ||
'./relative-existing.js', | ||
'./relative-nonexistent.js', | ||
'node:prefixed-nonexistent', | ||
'node:os', | ||
], | ||
}; | ||
|
||
const options = { | ||
flags: ['--expose-internals'], | ||
}; | ||
|
||
const bench = common.createBenchmark(main, configs, options); | ||
|
||
async function main(conf) { | ||
tmpdir.refresh(); | ||
|
||
fs.mkdirSync(benchmarkDirectory, { recursive: true }); | ||
fs.writeFileSync(new URL('./relative-existing.js', benchmarkDirectory), '\n'); | ||
|
||
bench.start(); | ||
|
||
for (let i = 0; i < conf.n; i++) { | ||
try { | ||
await import(new URL(conf.specifier.replace('{i}', i), benchmarkDirectory)); | ||
} catch { /* empty */ } | ||
} | ||
|
||
bench.end(conf.n); | ||
} |
Original file line number | Diff line number | Diff line change | ||||
---|---|---|---|---|---|---|
@@ -1,17 +1,92 @@ | ||||||
'use strict'; | ||||||
|
||||||
const { kImplicitAssertType } = require('internal/modules/esm/assert'); | ||||||
const { | ||||||
ArrayPrototypeJoin, | ||||||
ArrayPrototypeMap, | ||||||
ArrayPrototypeSort, | ||||||
JSONStringify, | ||||||
ObjectKeys, | ||||||
SafeMap, | ||||||
} = primordials; | ||||||
const { kImplicitAssertType } = require('internal/modules/esm/assert'); | ||||||
let debug = require('internal/util/debuglog').debuglog('esm', (fn) => { | ||||||
debug = fn; | ||||||
}); | ||||||
const { ERR_INVALID_ARG_TYPE } = require('internal/errors').codes; | ||||||
const { validateString } = require('internal/validators'); | ||||||
|
||||||
// Tracks the state of the loader-level module cache | ||||||
class ModuleMap extends SafeMap { | ||||||
/** | ||||||
* Cache the results of the `resolve` step of the module resolution and loading process. | ||||||
aduh95 marked this conversation as resolved.
Show resolved
Hide resolved
|
||||||
* Future resolutions of the same input (specifier, parent URL and import assertions) | ||||||
* must return the same result if the first attempt was successful, per | ||||||
* https://tc39.es/ecma262/#sec-HostLoadImportedModule. | ||||||
* This cache is *not* used when custom loaders are registered. | ||||||
*/ | ||||||
aduh95 marked this conversation as resolved.
Show resolved
Hide resolved
|
||||||
class ResolveCache extends SafeMap { | ||||||
constructor(i) { super(i); } // eslint-disable-line no-useless-constructor | ||||||
|
||||||
/** | ||||||
* Generates the internal serialized cache key and returns it along the actual cache object. | ||||||
* | ||||||
* It is exposed to allow more efficient read and overwrite a cache entry. | ||||||
* @param {string} specifier | ||||||
* @param {Record<string,string>} importAssertions | ||||||
* @returns {string} | ||||||
*/ | ||||||
serializeKey(specifier, importAssertions) { | ||||||
// To serialize the ModuleRequest (specifier + list of import assertions), | ||||||
// we need to sort the assertions by key, then stringifying, | ||||||
// so that different import statements with the same assertions are always treated | ||||||
// as identical. | ||||||
const keys = ObjectKeys(importAssertions); | ||||||
|
||||||
if (keys.length === 0) { | ||||||
return specifier + '::'; | ||||||
} | ||||||
|
||||||
return specifier + '::' + ArrayPrototypeJoin( | ||||||
ArrayPrototypeMap( | ||||||
ArrayPrototypeSort(keys), | ||||||
(key) => JSONStringify(key) + JSONStringify(importAssertions[key])), | ||||||
','); | ||||||
} | ||||||
|
||||||
#getModuleCachedImports(parentURL) { | ||||||
let internalCache = super.get(parentURL); | ||||||
if (internalCache == null) { | ||||||
super.set(parentURL, internalCache = { __proto__: null }); | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
And associated changes. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I'm not going to do that in this PR, if There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Fair enough. @JakobJingleheimer if you still do a refactor after this, maybe add this to the list of improvements? |
||||||
} | ||||||
return internalCache; | ||||||
} | ||||||
|
||||||
/** | ||||||
* @param {string} serializedKey | ||||||
* @param {string} parentURL | ||||||
* @returns {import('./loader').ModuleExports | Promise<import('./loader').ModuleExports>} | ||||||
*/ | ||||||
get(serializedKey, parentURL) { | ||||||
return this.#getModuleCachedImports(parentURL)[serializedKey]; | ||||||
} | ||||||
|
||||||
/** | ||||||
* @param {string} serializedKey | ||||||
* @param {string} parentURL | ||||||
* @param {{ format: string, url: URL['href'] }} result | ||||||
*/ | ||||||
set(serializedKey, parentURL, result) { | ||||||
this.#getModuleCachedImports(parentURL)[serializedKey] = result; | ||||||
return this; | ||||||
} | ||||||
|
||||||
has(serializedKey, parentURL) { | ||||||
return serializedKey in this.#getModuleCachedImports(parentURL); | ||||||
} | ||||||
} | ||||||
|
||||||
/** | ||||||
* Cache the results of the `load` step of the module resolution and loading process. | ||||||
*/ | ||||||
class LoadCache extends SafeMap { | ||||||
constructor(i) { super(i); } // eslint-disable-line no-useless-constructor | ||||||
get(url, type = kImplicitAssertType) { | ||||||
validateString(url, 'url'); | ||||||
|
@@ -29,7 +104,7 @@ class ModuleMap extends SafeMap { | |||||
} | ||||||
debug(`Storing ${url} (${ | ||||||
type === kImplicitAssertType ? 'implicit type' : type | ||||||
}) in ModuleMap`); | ||||||
}) in ModuleLoadMap`); | ||||||
const cachedJobsForUrl = super.get(url) ?? { __proto__: null }; | ||||||
cachedJobsForUrl[type] = job; | ||||||
return super.set(url, cachedJobsForUrl); | ||||||
|
@@ -40,4 +115,8 @@ class ModuleMap extends SafeMap { | |||||
return super.get(url)?.[type] !== undefined; | ||||||
} | ||||||
} | ||||||
module.exports = ModuleMap; | ||||||
|
||||||
module.exports = { | ||||||
LoadCache, | ||||||
ResolveCache, | ||||||
}; |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,25 @@ | ||
'use strict'; | ||
const common = require('../common'); | ||
const tmpdir = require('../common/tmpdir'); | ||
|
||
const assert = require('node:assert'); | ||
const fs = require('node:fs/promises'); | ||
const { pathToFileURL } = require('node:url'); | ||
|
||
tmpdir.refresh(); | ||
const tmpDir = pathToFileURL(tmpdir.path); | ||
|
||
const target = new URL(`./${Math.random()}.mjs`, tmpDir); | ||
|
||
(async () => { | ||
|
||
await assert.rejects(import(target), { code: 'ERR_MODULE_NOT_FOUND' }); | ||
|
||
await fs.writeFile(target, 'export default "actual target"\n'); | ||
|
||
const moduleRecord = await import(target); | ||
|
||
await fs.rm(target); | ||
|
||
assert.strictEqual(await import(target), moduleRecord); | ||
aduh95 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
})().then(common.mustCall()); |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,42 @@ | ||
import { spawnPromisified } from '../common/index.mjs'; | ||
import tmpdir from '../common/tmpdir.js'; | ||
|
||
import assert from 'node:assert'; | ||
import fs from 'node:fs/promises'; | ||
import { execPath } from 'node:process'; | ||
import { pathToFileURL } from 'node:url'; | ||
|
||
tmpdir.refresh(); | ||
const tmpDir = pathToFileURL(tmpdir.path); | ||
|
||
const target = new URL(`./${Math.random()}.mjs`, tmpDir); | ||
|
||
await assert.rejects(import(target), { code: 'ERR_MODULE_NOT_FOUND' }); | ||
|
||
await fs.writeFile(target, 'export default "actual target"\n'); | ||
|
||
const moduleRecord = await import(target); | ||
|
||
await fs.rm(target); | ||
|
||
assert.strictEqual(await import(target), moduleRecord); | ||
aduh95 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
// Add the file back, it should be deleted by the subprocess. | ||
await fs.writeFile(target, 'export default "actual target"\n'); | ||
|
||
assert.deepStrictEqual( | ||
await spawnPromisified(execPath, [ | ||
'--input-type=module', | ||
'--eval', | ||
[`import * as d from${JSON.stringify(target)};`, | ||
'import{rm}from"node:fs/promises";', | ||
`await rm(new URL(${JSON.stringify(target)}));`, | ||
'import{strictEqual}from"node:assert";', | ||
`strictEqual(JSON.stringify(await import(${JSON.stringify(target)})),JSON.stringify(d));`].join(''), | ||
aduh95 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
]), | ||
{ | ||
code: 0, | ||
signal: null, | ||
stderr: '', | ||
stdout: '', | ||
}); |
Uh oh!
There was an error while loading. Please reload this page.