Skip to content

Commit f8537a2

Browse files
fix: replace DefinePlugin undefined member access with undefined (#21040)
1 parent 169b511 commit f8537a2

10 files changed

Lines changed: 242 additions & 13 deletions

File tree

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+
Resolve `DefinePlugin` access to an undefined object member as `undefined`.

‎lib/DefinePlugin.js‎

Lines changed: 85 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ const createHash = require("./util/createHash");
3131
/** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */
3232
/** @typedef {import("./javascript/JavascriptParser")} JavascriptParser */
3333
/** @typedef {import("./javascript/JavascriptParser").DestructuringAssignmentProperties} DestructuringAssignmentProperties */
34+
/** @typedef {import("./javascript/JavascriptParser").Members} Members */
3435
/** @typedef {import("./javascript/JavascriptParser").Range} Range */
3536
/** @typedef {import("./logging/Logger").Logger} Logger */
3637
/** @typedef {import("./Compilation")} Compilation */
@@ -140,6 +141,17 @@ function getObjKeys(properties) {
140141
return new Set([...properties].map((p) => p.id));
141142
}
142143

144+
/**
145+
* Whether a value is a nested definition (plain object/array) to recurse into.
146+
* @param {CodeValue} code code value
147+
* @returns {code is Definitions} true for a plain object or array
148+
*/
149+
const isObjectDefinition = (code) =>
150+
Boolean(code) &&
151+
typeof code === "object" &&
152+
!(code instanceof RuntimeValue) &&
153+
!(code instanceof RegExp);
154+
143155
/** @typedef {Set<string> | null} ObjKeys */
144156
/** @typedef {boolean | undefined | null} AsiSafe */
145157

@@ -487,12 +499,7 @@ class DefinePlugin {
487499
const walkDefinitions = (definitions, prefix) => {
488500
for (const key of Object.keys(definitions)) {
489501
const code = definitions[key];
490-
if (
491-
code &&
492-
typeof code === "object" &&
493-
!(code instanceof RuntimeValue) &&
494-
!(code instanceof RegExp)
495-
) {
502+
if (isObjectDefinition(code)) {
496503
walkDefinitions(
497504
/** @type {Definitions} */ (code),
498505
`${prefix + key}.`
@@ -774,6 +781,77 @@ class DefinePlugin {
774781
}
775782
return toConstantDependency(parser, strCode)(expr);
776783
});
784+
// A property access not defined on the object resolves to `undefined`
785+
// and the whole object is never inlined (issue #15559). Keyed by the
786+
// chain root so dotted object keys (e.g. `a.b`) are also covered.
787+
const chainParts = key.split(".");
788+
// `import.meta` is one chain root (a MetaProperty), not two members.
789+
const isMeta =
790+
chainParts[0] === "import" && chainParts[1] === "meta";
791+
const chainRoot = isMeta ? "import.meta" : chainParts[0];
792+
const chainPrefix = chainParts.slice(isMeta ? 2 : 1);
793+
/**
794+
* Whether a member chain reads a property that is not defined.
795+
* Collects every define key consulted so the caller can record a
796+
* value dependency on each (a sibling key like `OBJECT.SUB2` affects
797+
* the result even though `OBJECT` registered the handler).
798+
* `member in value` keeps inherited members (e.g. `toString`) defined.
799+
* @param {Members} members chain members (after the root)
800+
* @param {string[]} deps consulted define keys (mutated)
801+
* @returns {boolean} true when the access resolves to `undefined`
802+
*/
803+
const isUndefinedMemberAccess = (members, deps) => {
804+
if (members.length <= chainPrefix.length) return false;
805+
for (let i = 0; i < chainPrefix.length; i++) {
806+
if (members[i] !== chainPrefix[i]) return false;
807+
}
808+
/** @type {CodeValue} */
809+
let value = /** @type {CodeValue} */ (obj);
810+
let path = key;
811+
for (let i = chainPrefix.length; i < members.length; i++) {
812+
// a leaf with members left is a real property access on a value
813+
if (!isObjectDefinition(value)) return false;
814+
const member = members[i];
815+
const nextPath = `${path}.${member}`;
816+
if (member in value) {
817+
value = value[member];
818+
} else if (
819+
Object.prototype.hasOwnProperty.call(definitions, nextPath)
820+
) {
821+
// defined via a dotted sibling key, e.g. `OBJECT.SUB2`
822+
deps.push(nextPath);
823+
value = definitions[nextPath];
824+
} else {
825+
return true;
826+
}
827+
path = nextPath;
828+
}
829+
return false;
830+
};
831+
parser.hooks.expressionMemberChain
832+
.for(chainRoot)
833+
.tap(PLUGIN_NAME, (expr, members) => {
834+
const deps = [key];
835+
if (!isUndefinedMemberAccess(members, deps)) return;
836+
for (const dep of deps) addValueDependency(dep);
837+
return toConstantDependency(parser, "undefined")(expr);
838+
});
839+
// In a call, replace only the callee so the call itself is kept:
840+
// `x.MISSING()` stays a (throwing) call and `x.MISSING?.()`
841+
// short-circuits, with the object never inlined.
842+
parser.hooks.callMemberChain
843+
.for(chainRoot)
844+
.tap(PLUGIN_NAME, (expr, members) => {
845+
const deps = [key];
846+
if (!isUndefinedMemberAccess(members, deps)) return;
847+
for (const dep of deps) addValueDependency(dep);
848+
toConstantDependency(
849+
parser,
850+
"undefined"
851+
)(/** @type {Expression} */ (expr.callee));
852+
parser.walkExpressions(expr.arguments);
853+
return true;
854+
});
777855
parser.hooks.typeof
778856
.for(key)
779857
.tap(
@@ -821,12 +899,7 @@ class DefinePlugin {
821899
warning.hideStack = true;
822900
compilation.warnings.push(warning);
823901
}
824-
if (
825-
code &&
826-
typeof code === "object" &&
827-
!(code instanceof RuntimeValue) &&
828-
!(code instanceof RegExp)
829-
) {
902+
if (isObjectDefinition(code)) {
830903
walkDefinitionsForValues(
831904
/** @type {Definitions} */ (code),
832905
`${prefix + key}.`
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
it("should define a member of an import.meta object key", function () {
2+
expect(import.meta.config.TOKEN).toBe("token");
3+
});
4+
it("should resolve unknown import.meta member access with undefined (issue 15559)", function () {
5+
const a = function () { return import.meta.config.MISSING; };
6+
const b = function () { return import.meta.config?.MISSING; };
7+
const c = function () { return import.meta.config.MISSING?.(); };
8+
expect(a.toString()).toBe("function () { return undefined; }");
9+
expect(b.toString()).toBe("function () { return undefined; }");
10+
expect(c.toString()).toBe("function () { return undefined?.(); }");
11+
expect(import.meta.config.MISSING).toBe(undefined);
12+
expect(import.meta.config?.MISSING).toBe(undefined);
13+
expect(import.meta.config.MISSING?.()).toBe(undefined);
14+
});
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
"use strict";
2+
3+
const supportsOptionalChaining = require("../../../helpers/supportsOptionalChaining");
4+
5+
module.exports = () => supportsOptionalChaining();
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
"use strict";
2+
3+
const { DefinePlugin } = require("../../../../");
4+
5+
/** @type {import("../../../../").Configuration} */
6+
module.exports = {
7+
target: "node",
8+
mode: "development",
9+
experiments: {
10+
outputModule: true
11+
},
12+
output: {
13+
module: true,
14+
chunkFormat: "module"
15+
},
16+
optimization: {
17+
minimize: false,
18+
concatenateModules: false
19+
},
20+
plugins: [
21+
new DefinePlugin({
22+
"import.meta.config": { TOKEN: JSON.stringify("token") }
23+
})
24+
]
25+
};
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
it("should resolve unknown optional and computed member access with undefined (issue 15559)", function () {
2+
const a = function () { return OBJECT?.SUB1?.UNKNOWN; };
3+
const b = function () { return OBJECT?.["SUB1"]?.["UNKNOWN"]; };
4+
const c = function () { return NOT_DEFINED?.SUB2?.b; };
5+
const d = function () { return NOT_DEFINED?.["SUB2"]?.["b"]; };
6+
expect(a.toString()).toBe("function () { return undefined; }");
7+
expect(b.toString()).toBe("function () { return undefined; }");
8+
expect(c.toString()).toBe("function () { return undefined; }");
9+
expect(d.toString()).toBe("function () { return undefined; }");
10+
expect(OBJECT?.SUB1?.UNKNOWN).toBe(undefined);
11+
expect(NOT_DEFINED?.SUB2?.b).toBe(undefined);
12+
});
13+
it("should resolve optional calls on an unknown member without inlining the object (issue 15559)", function () {
14+
const a = function () { return OBJECT.SUB1.UNKNOWN?.(); };
15+
const b = function () { return NOT_DEFINED.SUB2.b?.(); };
16+
const c = function () { return OBJECT.SUB1?.UNKNOWN?.(); };
17+
const d = function () { return OBJECT?.SUB1?.UNKNOWN?.(); };
18+
const e = function () { return OBJECT.SUB1["UNKNOWN"]?.(); };
19+
const f = function () { return OBJECT.SUB1.UNKNOWN?.().deep; };
20+
expect(a.toString()).toBe("function () { return undefined?.(); }");
21+
expect(b.toString()).toBe("function () { return undefined?.(); }");
22+
expect(c.toString()).toBe("function () { return undefined?.(); }");
23+
expect(d.toString()).toBe("function () { return undefined?.(); }");
24+
expect(e.toString()).toBe("function () { return undefined?.(); }");
25+
expect(f.toString()).toBe("function () { return undefined?.().deep; }");
26+
expect(OBJECT.SUB1.UNKNOWN?.()).toBe(undefined);
27+
expect(OBJECT?.SUB1?.UNKNOWN?.()).toBe(undefined);
28+
expect(NOT_DEFINED.SUB2.b?.()).toBe(undefined);
29+
expect(OBJECT.SUB1.UNKNOWN?.().deep).toBe(undefined);
30+
});
31+
it("should resolve unknown member calls with optional members without inlining the object (issue 15559)", function () {
32+
const a = function () { return OBJECT.SUB1?.UNKNOWN(); };
33+
const b = function () { return OBJECT?.SUB1?.UNKNOWN(); };
34+
const c = function () { return NOT_DEFINED.SUB2?.b(); };
35+
expect(a.toString()).toBe("function () { return undefined(); }");
36+
expect(b.toString()).toBe("function () { return undefined(); }");
37+
expect(c.toString()).toBe("function () { return undefined(); }");
38+
expect(() => OBJECT.SUB1?.UNKNOWN()).toThrow();
39+
});
40+
it("should still substitute arguments of an unknown member call (issue 15559)", function () {
41+
const a = function () { return OBJECT.SUB1.UNKNOWN?.(STRING); };
42+
expect(a.toString()).toBe('function () { return undefined?.("string"); }');
43+
expect(OBJECT.SUB1.UNKNOWN?.(STRING)).toBe(undefined);
44+
});
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
"use strict";
2+
3+
const supportsOptionalChaining = require("../../../helpers/supportsOptionalChaining");
4+
5+
module.exports = () => supportsOptionalChaining();
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
"use strict";
2+
3+
const { DefinePlugin } = require("../../../../");
4+
5+
/** @type {import("../../../../").Configuration} */
6+
module.exports = {
7+
plugins: [
8+
new DefinePlugin({
9+
OBJECT: { SUB1: { a: 1 } },
10+
"OBJECT.SUB2": { a: 1 },
11+
"NOT_DEFINED.SUB2": { a: 1 },
12+
STRING: JSON.stringify("string")
13+
})
14+
]
15+
};

‎test/configCases/plugins/define-plugin/index.js‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -154,6 +154,46 @@ it("should define OBJECT.SUB.STRING", function () {
154154
expect(sub.STRING).toBe("string");
155155
})(OBJECT.SUB);
156156
});
157+
it("should replace unknown member access with undefined (issue 15559)", function () {
158+
expect(typeof OBJECT.UNKNOWN).toBe("undefined");
159+
const a = function () { return OBJECT.UNKNOWN.A; };
160+
const b = function () { return OBJECT.SUB1.UNKNOWN; };
161+
expect(a.toString()).toBe("function () { return undefined; }");
162+
expect(b.toString()).toBe("function () { return undefined; }");
163+
expect(OBJECT.SUB1.a).toBe(1);
164+
expect(OBJECT.SUB2.a).toBe(1);
165+
expect(OBJECT.SUB2.b).toBe(undefined);
166+
expect(OBJECT.SUB2).toEqual({ a: 1 });
167+
expect(NOT_DEFINED.SUB2.a).toBe(1);
168+
expect(NOT_DEFINED.SUB2.b).toBe(undefined);
169+
expect(NOT_DEFINED.SUB2).toEqual({ a: 1 });
170+
});
171+
it("should resolve unknown member access on a dotted object key (issue 15559)", function () {
172+
// dotted key whose root also has a single-identifier object define
173+
const a = function () { return OBJECT.SUB2.b; };
174+
// dotted key whose root is only ever a dotted define (no inlining of the object)
175+
const b = function () { return NOT_DEFINED.SUB2.b; };
176+
expect(a.toString()).toBe("function () { return undefined; }");
177+
expect(b.toString()).toBe("function () { return undefined; }");
178+
});
179+
it("should not inline the object when calling an unknown member (issue 15559)", function () {
180+
const a = function () { return OBJECT.SUB1.UNKNOWN(); };
181+
const b = function () { return (OBJECT.SUB1.UNKNOWN)(); };
182+
const c = function () { return new OBJECT.SUB1.UNKNOWN(); };
183+
expect(a.toString()).toBe("function () { return undefined(); }");
184+
expect(b.toString()).toBe("function () { return (undefined)(); }");
185+
expect(c.toString()).toBe("function () { return new undefined(); }");
186+
// the object is not inlined; calling an undefined member still throws
187+
expect(() => OBJECT.SUB1.UNKNOWN()).toThrow();
188+
expect(() => new OBJECT.SUB1.UNKNOWN()).toThrow();
189+
});
190+
it("should keep inherited members of a defined object accessible (issue 15559)", function () {
191+
// resolved via `in` (not own-property), so inherited members stay reachable
192+
const a = function () { return OBJECT.SUB1.toString; };
193+
expect(a.toString()).toBe('function () { return ({"a":1}).toString; }');
194+
expect(OBJECT.SUB1.toString()).toBe("[object Object]");
195+
expect(OBJECT.SUB1.hasOwnProperty("a")).toBe(true);
196+
});
157197
it("should define ARRAY", function () {
158198
(donotcallme)
159199
ARRAY;

‎test/configCases/plugins/define-plugin/webpack.config.js‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,8 +46,11 @@ module.exports = {
4646
CODE: "(1+2)",
4747
REGEXP: /abc/i,
4848
STRING: JSON.stringify("string")
49-
}
49+
},
50+
SUB1: { a: 1 }
5051
},
52+
"OBJECT.SUB2": { a: 1 },
53+
"NOT_DEFINED.SUB2": { a: 1 },
5154
ARRAY: [2, [JSON.stringify("six")]],
5255
"process.env.DEFINED_NESTED_KEY": 5,
5356
"process.env.DEFINED_NESTED_KEY_STRING": '"string"',

0 commit comments

Comments
 (0)