Skip to content

Commit bb4c92d

Browse files
fix(defer): align the sealed namespace traps with its key list
The `get`, `has` and `getOwnPropertyDescriptor` traps answered `__esModule` synthetically and fell back to the exports object for unknown names, so a sealed target that omits them made `getOwnPropertyDescriptor` throw. Keep a genuinely exported `__esModule` in the key list, treat a definitively not-provided export as absent rather than unknown, and bail out when a name is emitted mangled. Pass export names from the re-export site too, and stop `ContextModule`'s bound padding argument from landing in the parameter.
1 parent 69f2094 commit bb4c92d

10 files changed

Lines changed: 116 additions & 30 deletions

File tree

‎lib/ContextModule.js‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -878,7 +878,9 @@ class ContextModule extends Module {
878878
}
879879
const type =
880880
typeof fakeMap === "number" ? fakeMap : fakeMapDataExpression;
881-
return `${asyncDeps} ? ${asyncDeps}.length ? ${RuntimeGlobals.deferredModuleAsyncTransitiveDependencies}(${asyncDeps}).then(${RuntimeGlobals.makeDeferredNamespaceObject}.bind(${RuntimeGlobals.require}, id, ${type} ^ 1, true)) : ${RuntimeGlobals.makeDeferredNamespaceObject}(id, ${type} ^ 1 | 16) : ${source}`;
881+
// The bound third argument absorbs the promise's resolved value, which
882+
// would otherwise land in the export-names parameter.
883+
return `${asyncDeps} ? ${asyncDeps}.length ? ${RuntimeGlobals.deferredModuleAsyncTransitiveDependencies}(${asyncDeps}).then(${RuntimeGlobals.makeDeferredNamespaceObject}.bind(${RuntimeGlobals.require}, id, ${type} ^ 1, undefined)) : ${RuntimeGlobals.makeDeferredNamespaceObject}(id, ${type} ^ 1 | 16) : ${source}`;
882884
}
883885
return source;
884886
}

‎lib/RuntimeTemplate.js‎

Lines changed: 8 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ const { InlinedUsedName } = require("./optimize/InlineExports");
3131
const {
3232
getDeferredCycleModuleIds,
3333
getDeferredCycleModules,
34+
getKnownExportNames,
3435
getMakeDeferredNamespaceModeFromExportsType,
3536
getOptimizedDeferredModule
3637
} = require("./runtime/MakeDeferredNamespaceObjectRuntime");
@@ -441,26 +442,6 @@ const isAsyncExternal = (/** @type {Module} */ module) =>
441442
Boolean(/** @type {BuildMeta} */ (module.buildMeta).async) &&
442443
module instanceof getExternalModule();
443444

444-
/**
445-
* The module's export names, sorted, when the graph knows them exhaustively.
446-
* @param {ModuleGraph} moduleGraph the module graph
447-
* @param {Module} module the deferred module
448-
* @returns {string[] | null} sorted export names, or null when unknown
449-
*/
450-
const getKnownExportNames = (moduleGraph, module) => {
451-
const exportsInfo = moduleGraph.getExportsInfo(module);
452-
if (exportsInfo.otherExportsInfo.provided !== false) return null;
453-
const names = [];
454-
for (const exportInfo of exportsInfo.orderedExports) {
455-
if (exportInfo.provided !== true) return null;
456-
if (exportInfo.name === "then" || exportInfo.name === "__esModule") {
457-
continue;
458-
}
459-
names.push(exportInfo.name);
460-
}
461-
return names.sort();
462-
};
463-
464445
class RuntimeTemplate {
465446
/**
466447
* Creates an instance of RuntimeTemplate.
@@ -2015,7 +1996,8 @@ class RuntimeTemplate {
20151996
// when they are fully known; otherwise the runtime stays permissive.
20161997
const deferredExportNames = getKnownExportNames(
20171998
chunkGraph.moduleGraph,
2018-
module
1999+
module,
2000+
undefined
20192001
);
20202002
mode += deferredExportNames
20212003
? `, ${JSON.stringify(deferredExportNames)}`
@@ -2497,7 +2479,11 @@ class RuntimeTemplate {
24972479
runtimeRequirements.add(RuntimeGlobals.makeDeferredNamespaceObject);
24982480
const id = chunkGraph.getModuleId(module);
24992481
const type = getMakeDeferredNamespaceModeFromExportsType(exportsType);
2500-
const names = getKnownExportNames(chunkGraph.moduleGraph, module);
2482+
const names = getKnownExportNames(
2483+
chunkGraph.moduleGraph,
2484+
module,
2485+
runtime
2486+
);
25012487
const init = `${RuntimeGlobals.makeDeferredNamespaceObject}(${JSON.stringify(
25022488
id
25032489
)}, ${type}${names ? `, ${JSON.stringify(names)}` : ""})`;

‎lib/dependencies/HarmonyExportImportedSpecifierDependency.js‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ const {
1717
isInlineEnabled
1818
} = require("../optimize/InlineExports");
1919
const {
20+
getKnownExportNames,
2021
getMakeDeferredNamespaceModeFromExportsType
2122
} = require("../runtime/MakeDeferredNamespaceObjectRuntime");
2223
const { countIterable } = require("../util/IterableHelpers");
@@ -1800,9 +1801,14 @@ HarmonyExportImportedSpecifierDependency.Template = class HarmonyExportImportedS
18001801
const map = new Map();
18011802
const moduleId = JSON.stringify(chunkGraph.getModuleId(module));
18021803
const mode = getMakeDeferredNamespaceModeFromExportsType(exportsType);
1804+
const names = getKnownExportNames(
1805+
chunkGraph.moduleGraph,
1806+
module,
1807+
undefined
1808+
);
18031809
map.set(
18041810
key,
1805-
`/* reexport deferred namespace object */ ${name}_deferred_namespace_cache || (${name}_deferred_namespace_cache = ${RuntimeGlobals.makeDeferredNamespaceObject}(${moduleId}, ${mode}))`
1811+
`/* reexport deferred namespace object */ ${name}_deferred_namespace_cache || (${name}_deferred_namespace_cache = ${RuntimeGlobals.makeDeferredNamespaceObject}(${moduleId}, ${mode}${names ? `, ${JSON.stringify(names)}` : ""}))`
18061812
);
18071813

18081814
return [

‎lib/runtime/MakeDeferredNamespaceObjectRuntime.js‎

Lines changed: 38 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ const HelperRuntimeModule = require("./HelperRuntimeModule");
1212
/** @import { ModuleId } from "../ChunkGraph" */
1313
/** @import Module, { RuntimeRequirements, ExportsType } from "../Module" */
1414
/** @import ModuleGraph from "../ModuleGraph" */
15+
/** @import { RuntimeSpec } from "../util/runtime" */
1516

1617
/**
1718
* @typedef {object} DeferredCycleState
@@ -490,20 +491,23 @@ class MakeDeferredNamespaceObjectRuntimeModule extends HelperRuntimeModule {
490491
`${runtimeTemplate.method("get", "_, name", [
491492
"switch (name) {",
492493
Template.indent([
493-
'case "__esModule": return true;',
494+
'case "__esModule": if (!exportNames) return true; break;',
494495
'case Symbol.toStringTag: return "Deferred Module";',
495496
'case "then": return undefined;'
496497
]),
497498
"}",
498499
'if (typeof name === "symbol") return ns_target[name];',
499500
init,
501+
// A sealed namespace has exactly the spec's keys, so anything
502+
// else is absent rather than read off the exports object.
503+
"if (exportNames) return exportNames.indexOf(name) < 0 ? undefined : ns[name];",
500504
"return ns[name];"
501505
])},`,
502506
`${runtimeTemplate.method("has", "_, name", [
503507
"switch (name) {",
504508
Template.indent(
505509
[
506-
'case "__esModule":',
510+
'case "__esModule": if (!exportNames) return true; break;',
507511
"case Symbol.toStringTag:",
508512
hasAsync
509513
? `case ${RuntimeGlobals.deferredModuleAsyncTransitiveDependenciesSymbol}:`
@@ -516,6 +520,7 @@ class MakeDeferredNamespaceObjectRuntimeModule extends HelperRuntimeModule {
516520
"}",
517521
'if (typeof name === "symbol") return name in ns_target;',
518522
init,
523+
"if (exportNames) return exportNames.indexOf(name) >= 0;",
519524
"return name in ns;"
520525
])},`,
521526
`${runtimeTemplate.method("ownKeys", "", [
@@ -549,7 +554,7 @@ class MakeDeferredNamespaceObjectRuntimeModule extends HelperRuntimeModule {
549554
init,
550555
// A namespace exposes data properties; webpack backs the exports
551556
// with getters, so the spec's shape is synthesized here.
552-
"if (exportNames && exportNames.indexOf(name) >= 0) return { value: ns[name], writable: true, enumerable: true, configurable: false };",
557+
"if (exportNames) return exportNames.indexOf(name) < 0 ? undefined : { value: ns[name], writable: true, enumerable: true, configurable: false };",
553558
`${lt} desc = Reflect.getOwnPropertyDescriptor(ns, name);`,
554559
'if (mode & 2 && name == "default" && !desc) {',
555560
Template.indent("desc = { value: ns, configurable: true };"),
@@ -588,12 +593,42 @@ class MakeDeferredNamespaceObjectRuntimeModule extends HelperRuntimeModule {
588593
}
589594
}
590595

596+
/**
597+
* The module's export names, sorted, when the graph knows them exhaustively.
598+
* Bails out when a name is emitted mangled, since the runtime reads them off
599+
* the exports object.
600+
* @param {ModuleGraph} moduleGraph the module graph
601+
* @param {Module} module the deferred module
602+
* @param {RuntimeSpec} runtime the runtime
603+
* @returns {string[] | null} sorted export names, or null when unknown
604+
*/
605+
const getKnownExportNames = (moduleGraph, module, runtime) => {
606+
const exportsInfo = moduleGraph.getExportsInfo(module);
607+
if (exportsInfo.otherExportsInfo.provided !== false) return null;
608+
const names = [];
609+
for (const exportInfo of exportsInfo.orderedExports) {
610+
// `false` is a definitive "not an export" (webpack records `__esModule`
611+
// that way); anything but a definitive answer means the list is unknown.
612+
if (exportInfo.provided === false) continue;
613+
if (exportInfo.provided !== true) return null;
614+
// A namespace never exposes `then`, so it is not one of the spec's keys.
615+
if (exportInfo.name === "then") continue;
616+
const usedName = exportInfo.getUsedName(exportInfo.name, runtime);
617+
if (typeof usedName === "string" && usedName !== exportInfo.name) {
618+
return null;
619+
}
620+
names.push(exportInfo.name);
621+
}
622+
return names.sort();
623+
};
624+
591625
module.exports.MakeDeferredNamespaceObjectRuntimeModule =
592626
MakeDeferredNamespaceObjectRuntimeModule;
593627
module.exports.MakeOptimizedDeferredNamespaceObjectRuntimeModule =
594628
MakeOptimizedDeferredNamespaceObjectRuntimeModule;
595629
module.exports.getDeferredCycleModuleIds = getDeferredCycleModuleIds;
596630
module.exports.getDeferredCycleModules = getDeferredCycleModules;
631+
module.exports.getKnownExportNames = getKnownExportNames;
597632
module.exports.getMakeDeferredNamespaceModeFromExportsType =
598633
getMakeDeferredNamespaceModeFromExportsType;
599634
module.exports.getOptimizedDeferredModule = getOptimizedDeferredModule;
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
import defer * as reexported from "./dep.js";
2+
3+
export { reexported };
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
export const alpha = 1;
2+
export const beta = 2;
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
import defer * as ns from "./dep.js";
2+
import { reexported } from "./barrel.js";
3+
4+
// Opaque keys: webpack resolves a literal member access statically, so it
5+
// never reaches the namespace object.
6+
const opaque = (name) => name;
7+
const absent = opaque("notAnExport");
8+
const esModule = opaque("__esModule");
9+
10+
it("gives a deferred namespace the spec's exotic shape", () => {
11+
expect(Reflect.isExtensible(ns)).toBe(false);
12+
expect(Reflect.ownKeys(ns)).toEqual(["alpha", "beta", Symbol.toStringTag]);
13+
expect(Object.getOwnPropertyDescriptor(ns, "alpha")).toEqual({
14+
value: 1,
15+
writable: true,
16+
enumerable: true,
17+
configurable: false
18+
});
19+
});
20+
21+
it("reports only the module's exports", () => {
22+
expect(esModule in ns).toBe(false);
23+
expect(ns[esModule]).toBe(undefined);
24+
expect(Object.getOwnPropertyDescriptor(ns, esModule)).toBe(undefined);
25+
expect(absent in ns).toBe(false);
26+
expect(ns[absent]).toBe(undefined);
27+
expect(Object.getOwnPropertyDescriptor(ns, absent)).toBe(undefined);
28+
});
29+
30+
it("keeps one shape when the same module is also re-exported", () => {
31+
expect(reexported).toBe(ns);
32+
expect(Reflect.isExtensible(reexported)).toBe(false);
33+
expect({ ...reexported }).toEqual({ alpha: 1, beta: 2 });
34+
});
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
"use strict";
2+
3+
const supportsAsync = require("../../../helpers/supportsAsync");
4+
5+
module.exports = () => supportsAsync();
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: [`async-node${process.versions.node.split(".").map(Number)[0]}`],
6+
mode: "development",
7+
optimization: {
8+
concatenateModules: false,
9+
minimize: false
10+
},
11+
experiments: {
12+
deferImport: true
13+
}
14+
};

‎test/test262.spectest.js‎

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -201,9 +201,8 @@ const expectedAbandonedRejections = new Map([
201201
// Fail identically unbundled in a plain `vm` on the pinned Node.js, so the
202202
// divergence is the host's and not webpack's.
203203
const knownHostBugs = [
204-
// `nonextensible-applies-to-private`: adding a private field to a
205-
// non-extensible object must throw, which the pinned Node.js does not do,
206-
// so it fails the same way unbundled.
204+
// Adding a private field to a non-extensible object must throw, which the
205+
// pinned Node.js does not do, so it fails the same way unbundled.
207206
"import/import-defer/evaluation-triggers/ignore-private-name-access.js",
208207
"destructuring/binding/keyed-destructuring-property-reference-target-evaluation-order-with-bindings.js",
209208
"expressions/assignment/S11.13.1_A5_T1.js",

0 commit comments

Comments
 (0)