Skip to content

Commit e12e122

Browse files
fix(library): keep module library exports live (#22733)
* fix(library): keep module library let exports live in wrapped modules Hoist an exported module-level let out of its module function to the chunk's scope, so the ESM export binds to it instead of a one-time copy. * perf(library): resolve hoisted exports once and build the scan regexp with itemsToRegexp * fix(library): hoist live let exports under reserved names, renamed from parse data Record every reference to an exported module-level let while the module is parsed, and rename them to a webpack-reserved name the chunk's scope declares. Nothing scans source text and no name can collide, so globals other modules, externals or DefinePlugin read stay untouched. * fix(library): report live exports left as copies through analyzable bailouts A module library that cannot move a `let` out of its module now says why under performance.analyzableBailouts, and a module calling eval keeps its bindings, which eval may read by name. * fix(library): keep exported var bindings live, and report eval A var is hoisted when every module-level declarator of its name is one the walk renamed, counted while pre-walked. A module calling eval keeps its bindings, now reported. An inlined entry keeps its exports object while its body still defines exports on it. * fix(library): keep destructured, mixed var, function and class exports live Hoist a destructuring declaration, every var declared beside a hoisted one, and a reassigned function or class. Only bindings written after their declaration move. Exports bind to generated names, never shadowing a global. * fix(library): don't report modules a concatenated entry absorbs as copies Also tests the eval bailout after a write and runs the top-level await case from Node.js 14.8. * test(library): keep logical assignment out of fixtures Node.js 14 parses Moves the `??=` naming check to its own case, gated to Node.js 15 onward. * test(library): set the fixture's global through the harness, not globalThis Node.js 10 has no globalThis, and the library runs in its own context.
1 parent 256def9 commit e12e122

56 files changed

Lines changed: 1901 additions & 29 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"webpack": patch
3+
---
4+
5+
Keep module library exports live without shadowing other modules' globals.

‎lib/dependencies/esm/ESMExportSpecifierDependency.js‎

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,13 +8,14 @@
88
const Dependency = require("../../graph/Dependency");
99
const { isInlinedUsedName } = require("../../optimize/InlineExports");
1010
const makeSerializable = require("../../util/makeSerializable");
11+
const { getRuntimeKey } = require("../../util/runtime");
1112
const NullDependency = require("../core/NullDependency");
1213
const ESMExportInitFragment = require("./ESMExportInitFragment");
1314

1415
const { ExportBindingType } = ESMExportInitFragment;
1516

1617
/** @import { ReplaceSource } from "webpack-sources" */
17-
/** @import { ExportsSpec, LazyRole, UpdateHashContext } from "../../graph/Dependency" */
18+
/** @import { DependencyKinds, ExportsSpec, LazyRole, UpdateHashContext } from "../../graph/Dependency" */
1819
/** @import Module, { BuildInfo } from "../../module/Module" */
1920
/** @import Hash from "../../util/Hash" */
2021
/** @import { DependencyTemplateContext } from "../../template/DependencyTemplate" */
@@ -204,12 +205,22 @@ ESMExportSpecifierDependency.Template = class ESMExportSpecifierDependencyTempla
204205
meta !== undefined &&
205206
meta.onDemandExports === true;
206207

208+
// a module library may have moved the binding to the chunk's scope
209+
const live =
210+
meta !== undefined && meta.liveBindings !== undefined
211+
? meta.liveBindings.get(dep.id)
212+
: undefined;
213+
const local =
214+
live !== undefined && live.runtimes.has(getRuntimeKey(runtime))
215+
? live.name
216+
: dep.id;
217+
207218
/** @type {ExportMap} */
208219
const map = new Map();
209220
map.set(used, {
210-
value: `/* binding */ ${dep.id}`,
221+
value: `/* binding */ ${local}`,
211222
type: valueFormat ? ExportBindingType.Value : ExportBindingType.Getter,
212-
finalName: dep.id
223+
finalName: local
213224
});
214225
initFragments.push(
215226
new ESMExportInitFragment(
@@ -222,4 +233,10 @@ ESMExportSpecifierDependency.Template = class ESMExportSpecifierDependencyTempla
222233
}
223234
};
224235

236+
/** @type {Set<keyof DependencyKinds>} */
237+
ESMExportSpecifierDependency.KINDS = new Set([
238+
...NullDependency.KINDS,
239+
"esm-export-specifier"
240+
]);
241+
225242
module.exports = ESMExportSpecifierDependency;
Lines changed: 174 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,174 @@
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 makeSerializable = require("../../util/makeSerializable");
9+
const { getRuntimeKey } = require("../../util/runtime");
10+
const NullDependency = require("../core/NullDependency");
11+
12+
/** @import { ReplaceSource } from "webpack-sources" */
13+
/** @import Dependency, { DependencyKinds, UpdateHashContext } from "../../graph/Dependency" */
14+
/** @import ModuleGraph, { LiveBinding } from "../../graph/ModuleGraph" */
15+
/** @import Module from "../../module/Module" */
16+
/** @import { DependencyTemplateContext } from "../../template/DependencyTemplate" */
17+
/** @import Hash from "../../util/Hash" */
18+
/** @import { RuntimeSpec } from "../../util/runtime" */
19+
/** @typedef {import("../../serialization/ObjectMiddleware").ObjectDeserializerContext<[string[], number[], boolean]>} ObjectDeserializerContext */
20+
/** @typedef {import("../../serialization/ObjectMiddleware").ObjectSerializerContext<[string[], number[], boolean]>} ObjectSerializerContext */
21+
22+
/**
23+
* A module-level binding a module library may declare in the chunk's scope under a
24+
* reserved name, so the library exports the binding itself; it holds every reference.
25+
*/
26+
class ESMLiveExportDependency extends NullDependency {
27+
/**
28+
* Creates an instance of ESMLiveExportDependency.
29+
* @param {string[]} names every name the declaration declares
30+
* @param {number[]} occurrences flat triples of start, end and `name index * KINDS_PER_NAME + kind`, a kind from {@link ESMLiveExportDependency.REFERENCE}
31+
* @param {boolean} readByEval whether the module calls `eval`, which reads the names as written
32+
*/
33+
constructor(names, occurrences, readByEval) {
34+
super();
35+
this.names = names;
36+
this.occurrences = occurrences;
37+
this.readByEval = readByEval;
38+
}
39+
40+
get type() {
41+
return "harmony live export";
42+
}
43+
44+
/**
45+
* Returns the names the chunk's scope declares for this runtime, if it does.
46+
* @param {ModuleGraph} moduleGraph the module graph
47+
* @param {RuntimeSpec} runtime the runtime the module is generated for
48+
* @returns {string[] | undefined} the hoisted name of each declared name
49+
*/
50+
getHoistedNames(moduleGraph, runtime) {
51+
const meta = moduleGraph.getMetaIfExisting(
52+
/** @type {Module} */ (moduleGraph.getParentModule(this))
53+
);
54+
const bindings = meta && meta.liveBindings;
55+
if (bindings === undefined) return;
56+
const first = bindings.get(this.names[0]);
57+
if (first === undefined || !first.runtimes.has(getRuntimeKey(runtime))) {
58+
return;
59+
}
60+
return this.names.map(
61+
(name) => /** @type {LiveBinding} */ (bindings.get(name)).name
62+
);
63+
}
64+
65+
/**
66+
* Updates the hash with the data contributed by this instance.
67+
* @param {Hash} hash hash to be updated
68+
* @param {UpdateHashContext} context context
69+
* @returns {void}
70+
*/
71+
updateHash(hash, context) {
72+
const hoisted = this.getHoistedNames(
73+
context.chunkGraph.moduleGraph,
74+
context.runtime
75+
);
76+
if (hoisted !== undefined) hash.update(hoisted.join());
77+
}
78+
79+
/**
80+
* Serializes this instance into the provided serializer context.
81+
* @param {ObjectSerializerContext} context context
82+
*/
83+
serialize(context) {
84+
context.write(this.names).write(this.occurrences).write(this.readByEval);
85+
super.serialize(context);
86+
}
87+
88+
/**
89+
* Restores this instance from the provided deserializer context.
90+
* @param {ObjectDeserializerContext} context context
91+
*/
92+
deserialize(context) {
93+
this.names = context.read();
94+
const c1 = context.rest;
95+
this.occurrences = c1.read();
96+
const c2 = c1.rest;
97+
this.readByEval = c2.read();
98+
super.deserialize(c2.rest);
99+
}
100+
}
101+
102+
makeSerializable(
103+
ESMLiveExportDependency,
104+
"webpack/lib/dependencies/esm/ESMLiveExportDependency"
105+
);
106+
107+
ESMLiveExportDependency.Template = class ESMLiveExportDependencyTemplate extends (
108+
NullDependency.Template
109+
) {
110+
/**
111+
* Applies the plugin by registering its hooks on the compiler.
112+
* @param {Dependency} dependency the dependency for which the template should be applied
113+
* @param {ReplaceSource} source the current replace source which can be modified
114+
* @param {DependencyTemplateContext} templateContext the context object
115+
* @returns {void}
116+
*/
117+
apply(dependency, source, { moduleGraph, runtime }) {
118+
const dep = /** @type {ESMLiveExportDependency} */ (dependency);
119+
const hoisted = dep.getHoistedNames(moduleGraph, runtime);
120+
if (hoisted === undefined) return;
121+
const { occurrences, names } = dep;
122+
const kinds = ESMLiveExportDependency.KINDS_PER_NAME;
123+
for (let i = 0; i < occurrences.length; i += 3) {
124+
const start = occurrences[i];
125+
const end = occurrences[i + 1];
126+
const index = Math.floor(occurrences[i + 2] / kinds);
127+
switch (occurrences[i + 2] % kinds) {
128+
case ESMLiveExportDependency.KEYWORD:
129+
source.replace(start, end - 1, "");
130+
break;
131+
case ESMLiveExportDependency.REFERENCE:
132+
source.replace(start, end - 1, hoisted[index]);
133+
break;
134+
case ESMLiveExportDependency.SHORTHAND:
135+
source.replace(start, end - 1, `${names[index]}: ${hoisted[index]}`);
136+
break;
137+
case ESMLiveExportDependency.NAMED:
138+
// A property key gives the function or class the name the binding did
139+
source.insert(start, `{ ${names[index]}: `);
140+
source.insert(end, ` }.${names[index]}`);
141+
break;
142+
case ESMLiveExportDependency.PARENTHESIZED:
143+
source.insert(start, "(");
144+
source.insert(end, ")");
145+
break;
146+
default:
147+
source.insert(start, `\n${hoisted[index]} = ${names[index]};\n`);
148+
}
149+
}
150+
}
151+
};
152+
153+
/** An occurrence the hoisted name replaces */
154+
ESMLiveExportDependency.REFERENCE = 0;
155+
/** A shorthand property, which keeps its key */
156+
ESMLiveExportDependency.SHORTHAND = 1;
157+
/** An anonymous function or class the binding names */
158+
ESMLiveExportDependency.NAMED = 2;
159+
/** A declaration's `let` or `var`, dropped with the space up to its first name */
160+
ESMLiveExportDependency.KEYWORD = 3;
161+
/** A destructuring declarator that, without its keyword, needs parentheses */
162+
ESMLiveExportDependency.PARENTHESIZED = 4;
163+
/** Where a function or class declaration, which stays, sets the binding */
164+
ESMLiveExportDependency.INITIALIZE = 5;
165+
/** How many kinds an occurrence's third number tells apart per name */
166+
ESMLiveExportDependency.KINDS_PER_NAME = 6;
167+
168+
/** @type {Set<keyof DependencyKinds>} */
169+
ESMLiveExportDependency.KINDS = new Set([
170+
...NullDependency.KINDS,
171+
"esm-live-export"
172+
]);
173+
174+
module.exports = ESMLiveExportDependency;

0 commit comments

Comments
 (0)