Skip to content

Commit ae2fc3f

Browse files
feat(parser): add specNamespaceObject for spec namespace objects
`import * as ns` hands out `__webpack_exports__`, a plain object carrying `__esModule`, where the spec hands out a Module Namespace Exotic Object with a null prototype, sorted keys and non-writable bindings. The new parser option wraps it in a proxy that reports those, per module rather than per build: a spec namespace keeps every exported name, so it blocks pruning and costs runtime code that a normal build should not pay for. The option is read from the module being imported, never the importer, so every importer of one module is handed the same namespace object. A module that opts in also stops being concatenated, since concatenation would materialize the namespace inline and drop the exotic object silently. Takes 35 test262 cases off the skip list.
1 parent f1c6430 commit ae2fc3f

27 files changed

Lines changed: 350 additions & 49 deletions
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"webpack": minor
3+
---
4+
5+
Add `module.parser.javascript.specNamespaceObject` for spec namespace objects.

‎declarations/WebpackOptions.d.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4859,6 +4859,12 @@ export interface JavascriptParserOptions {
48594859
* Enable experimental tc39 proposal https://github.com/tc39/proposal-source-phase-imports. This allows importing modules at source phase.
48604860
*/
48614861
sourceImport?: boolean;
4862+
/**
4863+
* Hand out a spec-compliant Module Namespace Exotic Object for 'import * as ns' and 'import()' of this module instead of the plain exports object. Requires 'Proxy' in the target environment, keeps every exported name, and costs runtime code, so enable it per module. Set it on the imported module, not on the importer. An importer that is itself concatenated renders namespace access inline and does not consult this option yet.
4864+
* @since 5.111.0
4865+
* @experimental
4866+
*/
4867+
specNamespaceObject?: boolean;
48624868
/**
48634869
* @deprecated
48644870
* Deprecated in favor of "exportsPresence". Emit errors instead of warnings when imported names don't exist in imported module.

‎lib/Module.js‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -190,6 +190,7 @@ const makeSerializable = require("./util/makeSerializable");
190190
* Defines the build info properties common to all module types.
191191
* Module type specific properties live in the `Known*BuildInfo` typedef of the dedicated module class.
192192
* @typedef {object} KnownBuildInfo
193+
* @property {boolean=} specNamespaceObject the module hands out a spec Module Namespace Exotic Object
193194
* @property {boolean=} cacheable
194195
* @property {string[]=} notCacheableReasons reasons why the module is not cacheable (e.g. paths of loaders that marked it)
195196
* @property {boolean=} strict

‎lib/RuntimeGlobals.js‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -458,6 +458,11 @@ module.exports.setAnonymousDefaultName = "__webpack_require__.dn";
458458
*/
459459
module.exports.shareScopeMap = "__webpack_require__.S";
460460

461+
/**
462+
* wrap an exports object in a spec Module Namespace Exotic Object
463+
*/
464+
module.exports.specNamespaceObject = "__webpack_require__.ns";
465+
461466
/**
462467
* startup signal from runtime
463468
* This will be called when the runtime chunk has been loaded.

‎lib/RuntimePlugin.js‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,9 @@ const getGetWorkletBootstrapRuntimeModule = lazyModule(() =>
8181
const getGlobalRuntimeModule = lazyModule(() =>
8282
require("./runtime/GlobalRuntimeModule")
8383
);
84+
const getSpecNamespaceObjectRuntimeModule = lazyModule(() =>
85+
require("./runtime/SpecNamespaceObjectRuntimeModule")
86+
);
8487
const getHasOwnPropertyRuntimeModule = lazyModule(() =>
8588
require("./runtime/HasOwnPropertyRuntimeModule")
8689
);
@@ -214,6 +217,7 @@ const SIMPLE_TREE_RUNTIME_MODULES = [
214217
getCreateFakeNamespaceObjectRuntimeModule
215218
],
216219
[RuntimeGlobals.hasOwnProperty, getHasOwnPropertyRuntimeModule],
220+
[RuntimeGlobals.specNamespaceObject, getSpecNamespaceObjectRuntimeModule],
217221
[
218222
RuntimeGlobals.compatGetDefaultExport,
219223
getCompatGetDefaultExportRuntimeModule

‎lib/RuntimeTemplate.js‎

Lines changed: 43 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -445,6 +445,15 @@ const isAsyncExternal = (/** @type {Module} */ module) =>
445445
Boolean(/** @type {BuildMeta} */ (module.buildMeta).async) &&
446446
module instanceof getExternalModule();
447447

448+
/**
449+
* The imported module decides, never the importer: two importers of one
450+
* module have to be handed the same namespace object.
451+
* @param {Module} module the imported module
452+
* @returns {boolean} true when its namespace has to be a spec exotic object
453+
*/
454+
const usesSpecNamespaceObject = (module) =>
455+
Boolean(module.buildInfo && module.buildInfo.specNamespaceObject);
456+
448457
class RuntimeTemplate {
449458
/**
450459
* Creates an instance of RuntimeTemplate.
@@ -1955,14 +1964,21 @@ class RuntimeTemplate {
19551964
});
19561965
const exportsType = module.getExportsType(chunkGraph.moduleGraph, strict);
19571966
switch (exportsType) {
1958-
case "namespace":
1959-
return this.moduleRaw({
1967+
case "namespace": {
1968+
const raw = this.moduleRaw({
19601969
module,
19611970
chunkGraph,
19621971
request,
19631972
weak,
19641973
runtimeRequirements
19651974
});
1975+
1976+
if (!usesSpecNamespaceObject(module)) return raw;
1977+
1978+
runtimeRequirements.add(RuntimeGlobals.specNamespaceObject);
1979+
1980+
return `${RuntimeGlobals.specNamespaceObject}(${raw})`;
1981+
}
19661982
case "default-with-named":
19671983
runtimeRequirements.add(RuntimeGlobals.createFakeNamespaceObject);
19681984
return `${RuntimeGlobals.createFakeNamespaceObject}(${moduleId}, 3)`;
@@ -2149,6 +2165,12 @@ class RuntimeTemplate {
21492165
`${comment}${idExpr}`
21502166
)})`;
21512167
}
2168+
2169+
if (usesSpecNamespaceObject(module)) {
2170+
runtimeRequirements.add(RuntimeGlobals.specNamespaceObject);
2171+
appending += `.then(${RuntimeGlobals.specNamespaceObject})`;
2172+
}
2173+
21522174
break;
21532175
case "dynamic":
21542176
fakeType |= 4;
@@ -2597,11 +2619,29 @@ class RuntimeTemplate {
25972619
runtime,
25982620
runtimeRequirements
25992621
});
2600-
if (materialized !== undefined) return materialized;
2622+
if (materialized !== undefined) {
2623+
if (exportName.length > 0 || !usesSpecNamespaceObject(module)) {
2624+
return materialized;
2625+
}
2626+
2627+
runtimeRequirements.add(RuntimeGlobals.specNamespaceObject);
2628+
2629+
return `${RuntimeGlobals.specNamespaceObject}(${materialized})`;
2630+
}
26012631
}
26022632
// if we hit here, the importVar is either
26032633
// - already a ES module namespace object
26042634
// - or imported by a way that does not need interop.
2635+
if (
2636+
exportsType === "namespace" &&
2637+
exportName.length === 0 &&
2638+
usesSpecNamespaceObject(module)
2639+
) {
2640+
runtimeRequirements.add(RuntimeGlobals.specNamespaceObject);
2641+
2642+
return `${RuntimeGlobals.specNamespaceObject}(${importVar})`;
2643+
}
2644+
26052645
return importVar;
26062646
}
26072647

‎lib/config/defaults.js‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -897,6 +897,7 @@ const applyJavascriptParserOptionsDefaults = (
897897
D(parserOptions, "wrappedContextRecursive", true);
898898
D(parserOptions, "wrappedContextCritical", false);
899899
D(parserOptions, "strictThisContextOnImports", false);
900+
D(parserOptions, "specNamespaceObject", false);
900901
D(parserOptions, "importMeta", outputModule ? "preserve-unknown" : true);
901902
D(parserOptions, "dynamicImportMode", "lazy");
902903
D(parserOptions, "dynamicImportPrefetch", false);

‎lib/dependencies/HarmonyModulesPlugin.js‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@ const TopLevelAwaitDependency = require("./TopLevelAwaitDependency");
3535
*/
3636
/** @import Compiler from "../Compiler" */
3737
/** @import Parser from "../javascript/JavascriptParser" */
38+
/** @import { BuildInfo } from "../Module" */
3839

3940
/**
4041
* Defines the harmony modules plugin options type used by this module.
@@ -159,6 +160,15 @@ class HarmonyModulesPlugin {
159160
return;
160161
}
161162

163+
if (parserOptions.specNamespaceObject) {
164+
// Recorded on the module, because an importer asks the module it
165+
// imports whether its namespace is a spec exotic object.
166+
parser.hooks.program.tap(PLUGIN_NAME, () => {
167+
/** @type {BuildInfo} */
168+
(parser.state.module.buildInfo).specNamespaceObject = true;
169+
});
170+
}
171+
162172
new HarmonyDetectionParserPlugin().apply(parser);
163173
new HarmonyImportDependencyParserPlugin(parserOptions).apply(parser);
164174
new HarmonyExportDependencyParserPlugin(parserOptions).apply(parser);

‎lib/optimize/ModuleConcatenationPlugin.js‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -236,6 +236,19 @@ class ModuleConcatenationPlugin {
236236
continue;
237237
}
238238

239+
// Concatenation materializes the namespace inline, which would
240+
// silently drop the spec exotic object the module asked for.
241+
if (
242+
/** @type {BuildInfo} */
243+
(module.buildInfo).specNamespaceObject
244+
) {
245+
setBailoutReason(
246+
module,
247+
"Module hands out a spec namespace object"
248+
);
249+
continue;
250+
}
251+
239252
// Module must be in any chunk (we don't want to do useless work)
240253
if (chunkGraph.getNumberOfModuleChunks(module) === 0) {
241254
setBailoutReason(module, "Module is not in any chunk");
Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
/*
2+
MIT License http://www.opensource.org/licenses/mit-license.php
3+
Author Alexander Akait @alexander-akait
4+
*/
5+
6+
"use strict";
7+
8+
const RuntimeGlobals = require("../RuntimeGlobals");
9+
const Template = require("../Template");
10+
const HelperRuntimeModule = require("./HelperRuntimeModule");
11+
12+
/** @import Compilation from "../Compilation" */
13+
14+
class SpecNamespaceObjectRuntimeModule extends HelperRuntimeModule {
15+
constructor() {
16+
super("spec namespace object");
17+
}
18+
19+
/**
20+
* Generates runtime code for this runtime module.
21+
* @returns {string | null} runtime code
22+
*/
23+
generate() {
24+
const compilation = /** @type {Compilation} */ (this.compilation);
25+
const { runtimeTemplate } = compilation;
26+
const cst = runtimeTemplate.renderConst();
27+
const fn = RuntimeGlobals.specNamespaceObject;
28+
return Template.asString([
29+
`${fn} = ${runtimeTemplate.basicFunction("exports", [
30+
`${cst} cached = ${fn}.c.get(exports);`,
31+
"if (cached) return cached;",
32+
// The exports object keeps the live bindings; the sealed target
33+
// carries only their names, so the traps stay invariant-safe.
34+
`${cst} names = Object.getOwnPropertyNames(exports).filter(${runtimeTemplate.expressionFunction(
35+
"name !== '__esModule'",
36+
"name"
37+
)}).sort();`,
38+
`${cst} target = { __proto__: null };`,
39+
"for (var i = 0; i < names.length; i++) Object.defineProperty(target, names[i], { value: undefined, writable: true, enumerable: true, configurable: false });",
40+
"Object.defineProperty(target, Symbol.toStringTag, { value: 'Module' });",
41+
"Object.preventExtensions(target);",
42+
`${cst} own = ${runtimeTemplate.expressionFunction(
43+
"typeof name === 'string' && Object.prototype.hasOwnProperty.call(target, name)",
44+
"name"
45+
)};`,
46+
`${cst} ns = new Proxy(target, {`,
47+
Template.indent([
48+
"__proto__: null,",
49+
"getPrototypeOf: function() { return null; },",
50+
"setPrototypeOf: function(_, proto) { return proto === null; },",
51+
"isExtensible: function() { return false; },",
52+
"preventExtensions: function() { return true; },",
53+
"get: function(_, name, receiver) { return own(name) ? exports[name] : Reflect.get(target, name, receiver); },",
54+
"has: function(_, name) { return own(name) || Reflect.has(target, name); },",
55+
"ownKeys: function() { return Reflect.ownKeys(target); },",
56+
"getOwnPropertyDescriptor: function(_, name) { return own(name) ? { value: exports[name], writable: true, enumerable: true, configurable: false } : Reflect.getOwnPropertyDescriptor(target, name); },",
57+
"set: function() { return false; },",
58+
// A namespace may only be redefined to the descriptor it
59+
// already reports, so anything else is rejected.
60+
"defineProperty: function(_, name, descriptor) {",
61+
Template.indent([
62+
// Symbol keys are ordinary, so redefining Symbol.toStringTag
63+
// to the descriptor it already has must still succeed.
64+
"if (typeof name === 'symbol') return Reflect.defineProperty(target, name, descriptor);",
65+
"if (!own(name) || 'get' in descriptor || 'set' in descriptor) return false;",
66+
"if (descriptor.configurable === true || descriptor.enumerable === false || descriptor.writable === false) return false;",
67+
"return !('value' in descriptor) || Object.is(descriptor.value, exports[name]);"
68+
]),
69+
"},",
70+
"deleteProperty: function(_, name) { return !own(name) && !Reflect.has(target, name); }"
71+
]),
72+
"});",
73+
`${fn}.c.set(exports, ns);`,
74+
"return ns;"
75+
])};`,
76+
// The same exports object must always yield the same namespace.
77+
`${fn}.c = new WeakMap();`
78+
]);
79+
}
80+
}
81+
82+
module.exports = SpecNamespaceObjectRuntimeModule;

0 commit comments

Comments
 (0)