Skip to content

Commit 23658e1

Browse files
fix: await every async entry, and keep options webpack cannot read
Two defects a review found. The entry await was gated on the last entry and spliced into the startup buffer, so an earlier async entry still settled after the bundle did, and the `await` would have been a syntax error inside the synchronous startup function that `RuntimeGlobals.startup` renders. Capture each async entry instead and await them after the loop, only where the startup lands at the top level of an ESM chunk. `isStaticStringAttributes` returned true for a key that is not `with` or `assert`, so `import(request, { unused: effect() })` dropped `effect()`. Only those two keys can be read at build time; anything else keeps the argument.
1 parent 98d6ec1 commit 23658e1

10 files changed

Lines changed: 87 additions & 64 deletions

File tree

‎.changeset/010-esm-correctness.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,4 +2,4 @@
22
"webpack": patch
33
---
44

5-
Fix import() options, circular reexport severity, async ESM entry rejection and namespace import assignment.
5+
Fix import() options, circular reexports, async ESM entries, namespace writes.

‎lib/dependencies/ImportContextDependency.js‎

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -101,9 +101,8 @@ ImportContextDependency.Template = class ImportContextDependencyTemplate extends
101101
super.replaceCall(dep, source, moduleExports, templateContext);
102102
return;
103103
}
104-
// The spec evaluates the request, then the options, then checks them, so
105-
// both stay as arguments in that order. Their own source is left in
106-
// place, so nested dependencies in them still get their replacements.
104+
// Request then options, in that order; their own source is kept so
105+
// nested dependencies in them still get their replacements.
107106
const range = /** @type {Range} */ (dep.range);
108107
const valueRange = /** @type {Range} */ (dep.valueRange);
109108
const check = importOptionsCheck(

‎lib/dependencies/ImportParserPlugin.js‎

Lines changed: 12 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -209,20 +209,18 @@ const isStaticStringAttributes = (node) => {
209209
: key.type === "Literal"
210210
? key.value
211211
: undefined;
212-
if (keyName === "with" || keyName === "assert") {
213-
const value = prop.value;
214-
if (value.type !== "ObjectExpression") return false;
215-
for (const attr of value.properties) {
216-
if (attr.type !== "Property" || attr.kind !== "init" || attr.computed) {
217-
return false;
218-
}
219-
const attrValue = attr.value;
220-
if (
221-
attrValue.type !== "Literal" ||
222-
typeof attrValue.value !== "string"
223-
) {
224-
return false;
225-
}
212+
// Any other key is an expression webpack cannot account for, and its
213+
// value still evaluates, so the argument has to stay.
214+
if (keyName !== "with" && keyName !== "assert") return false;
215+
const value = prop.value;
216+
if (value.type !== "ObjectExpression") return false;
217+
for (const attr of value.properties) {
218+
if (attr.type !== "Property" || attr.kind !== "init" || attr.computed) {
219+
return false;
220+
}
221+
const attrValue = attr.value;
222+
if (attrValue.type !== "Literal" || typeof attrValue.value !== "string") {
223+
return false;
226224
}
227225
}
228226
}

‎lib/dependencies/importOptionsCheck.js‎

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,9 +10,8 @@ const Template = require("../Template");
1010
/** @import RuntimeTemplate from "../RuntimeTemplate" */
1111

1212
/**
13-
* Builds the call the spec's `import(specifier, options)` evaluation asks for:
14-
* the arguments are evaluated in source order, the options are checked, and a
15-
* failing check rejects rather than throws. The last parameter holds them.
13+
* Wraps an import so its arguments evaluate in source order and the options are
14+
* checked, rejecting rather than throwing. The last parameter holds them.
1615
* @param {RuntimeTemplate} runtimeTemplate the runtime template
1716
* @param {string[]} parameters parameter names, the options one last
1817
* @param {string} content the import expression to return once the check passes

‎lib/javascript/JavascriptModulesPlugin.js‎

Lines changed: 26 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1680,6 +1680,17 @@ class JavascriptModulesPlugin {
16801680
continue;
16811681
}
16821682
}
1683+
// `await` is only legal at the top level of an ESM chunk, never in
1684+
// the startup function rendered below.
1685+
const canAwaitEntry =
1686+
runtimeTemplate.isModule() &&
1687+
!runtimeRequirements.has(RuntimeGlobals.startup) &&
1688+
!(
1689+
runtimeRequirements.has(RuntimeGlobals.startupOnlyBefore) &&
1690+
runtimeRequirements.has(RuntimeGlobals.startupOnlyAfter)
1691+
);
1692+
/** @type {string[]} */
1693+
const awaitedEntries = [];
16831694
let i = jsEntries.length;
16841695
for (const [entryModule, entrypoint] of jsEntries) {
16851696
const chunks =
@@ -1806,23 +1817,19 @@ class JavascriptModulesPlugin {
18061817
)})`
18071818
);
18081819
} else if (useRequire) {
1820+
// An async entry nobody awaits settles after the bundle did,
1821+
// which orphans its rejection.
1822+
const awaitEntry =
1823+
canAwaitEntry && moduleGraph.isAsync(entryModule);
1824+
const target =
1825+
i === 0
1826+
? RuntimeGlobals.exports
1827+
: `${RuntimeGlobals.exports}_${i}`;
1828+
const needsDecl = i === 0 || awaitEntry;
18091829
buf2.push(
1810-
`${i === 0 ? `${exportsDecl} ${RuntimeGlobals.exports} = ` : ""}${
1811-
RuntimeGlobals.require
1812-
}(${moduleIdExpr});`
1830+
`${needsDecl ? `${exportsDecl} ${target} = ` : ""}${RuntimeGlobals.require}(${moduleIdExpr});`
18131831
);
1814-
// Only an ESM bundle can await its own entry. Without this an
1815-
// async entry's promise is nobody's, so the bundle settles
1816-
// before the entry did and its rejection is orphaned.
1817-
if (
1818-
i === 0 &&
1819-
runtimeTemplate.isModule() &&
1820-
moduleGraph.isAsync(entryModule)
1821-
) {
1822-
buf2.push(
1823-
`${RuntimeGlobals.exports} = await ${RuntimeGlobals.exports};`
1824-
);
1825-
}
1832+
if (awaitEntry) awaitedEntries.push(target);
18261833
} else {
18271834
if (i === 0) {
18281835
buf2.push(`${exportsDecl} ${RuntimeGlobals.exports} = {};`);
@@ -1865,6 +1872,10 @@ class JavascriptModulesPlugin {
18651872
`${RuntimeGlobals.exports} = ${RuntimeGlobals.onChunksLoaded}(${RuntimeGlobals.exports});`
18661873
);
18671874
}
1875+
// After the loop, so entries still start in parallel.
1876+
for (const target of awaitedEntries) {
1877+
buf2.push(`${target} = await ${target};`);
1878+
}
18681879
if (
18691880
runtimeRequirements.has(RuntimeGlobals.startup) ||
18701881
(runtimeRequirements.has(RuntimeGlobals.startupOnlyBefore) &&
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
globalThis.__firstEntryValue = await Promise.resolve("first");
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
it("should await an async entry that is not the last one", () => {
2+
expect(globalThis.__firstEntryValue).toBe("first");
3+
});
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
"use strict";
2+
3+
/** @type {import("../../../../").Configuration} */
4+
module.exports = {
5+
target: "node",
6+
mode: "development",
7+
devtool: false,
8+
experiments: { outputModule: true },
9+
output: {
10+
module: true,
11+
filename: "bundle0.mjs"
12+
},
13+
entry: ["./first.js", "./index.js"]
14+
};

‎test/configCases/parsing/import-options-side-effects/index.js‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,3 +25,15 @@ it("should reject an import() whose options are not an object", async () => {
2525
await expect(import("./a.js", 1)).rejects.toThrow(TypeError);
2626
await expect(import(`./${"a"}.js`, 1)).rejects.toThrow(TypeError);
2727
});
28+
29+
it("should evaluate an options object whose keys are not import attributes", async () => {
30+
const log = [];
31+
const effect = () => {
32+
log.push("effect");
33+
return 1;
34+
};
35+
const module = await import("./a.js", { unused: effect() });
36+
37+
expect(module.default).toBe(42);
38+
expect(log).toEqual(["effect"]);
39+
});

‎test/test262.spectest.js‎

Lines changed: 14 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -132,15 +132,12 @@ const knownHostEvalBugs = [
132132
];
133133
/* cspell:enable */
134134

135-
// A specifier that names no module: `import()` stringifies whatever it is
136-
// handed, so `import(import(...))` asks for "[object Promise]" and
137-
// `import(typeof x)` for "object". Rejecting is what the spec requires.
135+
// `import()` stringifies its argument, so these ask for a name nothing
136+
// resolves ("[object Promise]", "object") and reject, as the spec requires.
138137
const UNRESOLVED_SPECIFIER = /Cannot find module/;
139138

140-
// These abandon a rejected promise on purpose — an async body nothing awaits,
141-
// a short-circuited optional chain, an `import()` of a name nothing resolves.
142-
// jest records it against the running test, so the count and reason are
143-
// asserted and cleared below the way `rejectionHandled` would.
139+
// These abandon a rejected promise on purpose. jest blames the running test,
140+
// so the count and reason are asserted and cleared below.
144141
const expectedAbandonedRejections = new Map([
145142
[
146143
"statements/async-function/evaluation-body.js",
@@ -588,10 +585,8 @@ const compile = async (entry, scenario, options = {}) =>
588585
entry,
589586
context: path.dirname(entry),
590587
output: {
591-
// A Cyclic Module Record keeps its [[EvaluationError]] forever, so
592-
// re-importing a module that threw re-throws instead of re-running
593-
// it. webpack leaves this off by default for CommonJS's sake, so the
594-
// suite opts in to measure the spec-conformant output.
588+
// A Cyclic Module Record keeps its [[EvaluationError]] forever. Off
589+
// by default for CommonJS's sake, so the suite opts in.
595590
strictModuleErrorHandling: true,
596591
...webpackOptions.output,
597592
...(scenario === "module" ? { module: true } : { iife: false })
@@ -854,8 +849,7 @@ const knownBugs = [
854849
// `await` does, so the Script-goal early error is not raised.
855850
"statements/await-using/syntax/await-using-not-allowed-at-top-level-of-script.js",
856851
// `#mark in obj` needs `isExtensible() === false` without evaluating, so the
857-
// target must be sealed with every export name already on it — the names
858-
// emitted per deferred import, and a mismatch would silently lose a key.
852+
// target must be sealed with every export name on it, and a mismatch loses one.
859853
"import/import-defer/evaluation-triggers/ignore-private-name-access.js",
860854
// Host resolution errors must be reported eagerly even for deferred imports;
861855
// webpack turns a missing module into a build error resolved lazily instead.
@@ -872,15 +866,11 @@ const knownBugs = [
872866
// A deferred module must wait for the whole strongly-connected component when a
873867
// dependency's cycle root is still evaluating-async (`IsModuleSCCEvaluated`).
874868
"import/import-defer/evaluation-top-level-await/async-cycle-dependency-of-deferred-module/main.js",
875-
// Just bugs, need to fix
876-
// Extensibility is only its first assertion: it also wants `ownKeys` to be
877-
// the sorted exports plus `@@toStringTag`, so `__esModule` would have to go.
878-
// That is the namespace-object trade-off, not a defer-local fix.
869+
// It also wants `ownKeys` to be the sorted exports plus `@@toStringTag`, so
870+
// `__esModule` would have to go — the namespace trade-off, not a defer fix.
879871
"import/import-defer/deferred-namespace-object/exotic-object-behavior.js",
880-
// The assignment is now a build error, which is earlier than the spec's
881-
// runtime TypeError, so this test cannot observe the throw. It stays a
882-
// `var` because a runtime-condition import must be function-scoped and HMR
883-
// accept reassigns it, so `const` is not available to make the write throw.
872+
// Reported as a build error, earlier than the spec's runtime TypeError: the
873+
// binding stays a `var`, which a runtime condition and HMR accept both need.
884874
"module-code/instn-star-binding.js",
885875
// Improvement- bug with `delete` and `ns[0] = something` when using `import * as ns from "...";`
886876
"module-code/export-expname-binding-index.js",
@@ -1044,13 +1034,9 @@ const knownBugs = [
10441034
];
10451035

10461036
const knownProductionBuildBugs = [
1047-
// Deliberate: the inner graph reads a class heritage and an unused export's
1048-
// value as pure, so a `prototype` getter and a `ReferenceError` on a free
1049-
// name are not seen. Both only fire where the class or the export is
1050-
// unused — used, the heritage and the expression are emitted and observe
1051-
// the same as the spec, and development mode observes it either way.
1052-
// Tree-shaking an imported base class out of an unused class is the whole
1053-
// point of the first, which `configCases/inner-graph/issue-17565` pins.
1037+
// Deliberate: the inner graph reads an unused class heritage and an unused
1038+
// export's value as pure, which `configCases/inner-graph/issue-17565` pins.
1039+
// Used, both are emitted and observe the same as the spec, as does development.
10541040
"statements/class/definition/prototype-getter.js",
10551041
"module-code/eval-export-dflt-expr-err-get-value.js"
10561042
];

0 commit comments

Comments
 (0)