Repository navigation
fix(reference): drop replaced CommonJS loaders from reference-source edges - #4072
VarunGore36 wants to merge 7 commits into
Conversation
…edges import-reference-source kept a parsed internal requires edge when the apparent loader call targeted a replaced local function: a for-in/of var head initializes its binding on every iteration, and an assignment inside with leaves the binding identity unknown. Both now fail closed like a plain assignment, while a truly uninitialized top-level var require retains its edge. Fixes morluto#3982
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
[Medium impact] Refactors require binding detection logic for edge cases. The PR should not merge until the two dependency-loss cases and the remaining skipped-property case are fixed. Findings
Fix with agent prompt### Issue 1
src/domain/referenceSourceRequireBindings.ts:348-349
A non-object `Symbol.unscopables` value now causes real dependencies to be dropped. For example, `with ({ require: null, [Symbol.unscopables]: null }) { require = () => 'local'; } require('./dep.cjs');` leaves Node's loader unchanged: the assignment updates the object's `require` property.
This check rejects that protection, marks the loader as written, and drops the real dependency. Recognize known non-object values as leaving the object's bindings available, and add a regression control.
### Issue 2
src/domain/referenceSourceRequireBindings.ts:542-543
The new recursive check drops real dependencies when a prototype setter has a primitive value. For example, `for (var require in { __proto__: 0 }) {} require('./dep.cjs');` still calls Node's loader. JavaScript ignores the primitive prototype value, so the loop has no keys and never assigns `require`.
This helper instead returns `false`, causing the importer to treat the loader as replaced. Preserve the empty-loop result for known primitive prototype values and add a regression control.
### Issue 3
src/domain/referenceSourceRequireBindings.ts:320-326
`withObjectDeclaresRequire` treats a literal `require` property as proof that a write cannot reach Node's loader. But `with ({ require: null, [Symbol.unscopables]: { require: true } }) { require = () => 'local'; }` replaces the loader because `Symbol.unscopables` makes the object skip that property.
The shortcut hides this write, so a later `require('./dep.cjs')` produces a false dependency. Only shield the write when the object is known to capture it.
---
For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.SummaryThe PR changes how the importer decides whether
Reviews (8) · Last reviewed commit: "fix(reference): close shield gaps for un..." · Reviewed by Greptile |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: f16dffda12
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| reference.name === "require" && | ||
| reference.role === "write" && | ||
| (reference.resolution === "unbound" || | ||
| reference.resolution === "unknown" || |
There was a problem hiding this comment.
Keep shadowed dynamic writes from invalidating the loader
When a with assignment sits inside a function that already shadows require—for example, function f(require) { with ({}) { require = () => "local"; } }—the semantic reference is unknown only because the with-object may receive the write; its lexical fallback is the parameter, so it cannot modify Node's program loader. Counting every such reference in this file-wide flag suppresses a separate top-level require("./dep") relationship, regressing the shadowed-loader behavior this module preserves. Restrict unknown writes to dynamic scopes whose fallback can actually reach the program or unbound loader.
AGENTS.md reference: AGENTS.md:L21-L21
Useful? React with 👍 / 👎.
|
Addressed the P1 in 3c8c340: unknown-resolution writes now kill the loader flag only when no lexical require binding intervenes between the write and program scope (function params and body var declarations, catch params, block and loop-head lexical declarations). The reported control keeps its edge and is now a regression fixture alongside a function-var variant; the issue's top-level cases still fail closed. Validation: shadowed-require suite plus the adjacent import/graph/summary suites green (53 tests), check:fast green. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 3c8c34047b
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| const functionBodyBindsRequire = (body: t.Node | null | undefined): boolean => { | ||
| if (body === null || body === undefined || !t.isBlockStatement(body)) | ||
| return false; | ||
| return body.body.some( |
There was a problem hiding this comment.
Resolve nested var bindings before invalidating the loader
The fresh evidence after the posted fix is functionBodyBindsRequire's direct body.body.some scan: in function patch() { if (false) { var require; } with ({}) { require = () => "local"; } }, the nested var is still hoisted to patch's function scope, so the dynamic write can target only the with-object or that local binding. This helper misses it, marks the program loader written, and drops a separate top-level require("./dep") edge even though Node's loader is untouched. Resolve the fallback through the existing semantic scope owner (or traverse all function-owned vars while excluding nested scopes) rather than duplicating only direct declarations.
AGENTS.md reference: AGENTS.md:L23-L23
Useful? React with 👍 / 👎.
| ((t.isForInStatement(parent) || t.isForOfStatement(parent)) && | ||
| parent.left === node); |
There was a problem hiding this comment.
Preserve the loader across zero-iteration var loops
For for (var require of []) {} (and other heads that execute zero iterations), the head never assigns the CommonJS wrapper parameter, so a following require("./dep") still loads dep. These lines set initialized solely from the syntactic parent, making hasUninitializedTopLevelVarRequire false and silently dropping that real relationship despite no loader replacement. Preserve the uninitialized case when the iterable is statically empty (and uncertainty when cardinality is not known) instead of treating every loop head as an executed assignment.
AGENTS.md reference: AGENTS.md:L21-L21
Useful? React with 👍 / 👎.
| return; | ||
| } | ||
| if ( | ||
| reference.resolution === "unknown" && |
There was a problem hiding this comment.
Small follow-up to consider: writes the analyzer marks ambiguous (rather than unknown) with a non-program binding still never kill the flag. If a dynamic-scope write can come out ambiguous instead of unknown, the same false edge returns through this branch. Worth either extending the treatment or noting it as explicitly out of scope.
| programRequireBinding: string, | ||
| ): boolean => { | ||
| let reached = false; | ||
| traverseJavaScriptAst(program, { |
There was a problem hiding this comment.
Perf note, non-blocking: this is now a second full AST walk per file where the old code scanned the references map. Fine for typical inputs, but worth knowing for very large generated files since the traversal has no early exit once reached is set.
| ); | ||
| }; | ||
|
|
||
| const functionBodyBindsRequire = (body: t.Node | null | undefined): boolean => { |
There was a problem hiding this comment.
Direct-child let/const (and using) in the function body also bind the function scope in all modes, so they shield just like var does here. Consider including non-var declarations — otherwise function f() { let require; with (O) { require = 1; } } still drops a valid top-level edge.
| "patch(null);", | ||
| "console.log(require('./loaded.cjs'));", | ||
| ].join("\n"), | ||
| "local-fn-var.cjs": [ |
There was a problem hiding this comment.
Coverage locks the shield on the uninitialized and param sides. Consider one companion fixture on the initialized side — e.g. function patch() { var require = () => 1; with ({}) { require = () => 2; } } — to pin that an initialized function-body binding also shields the top-level edge.
An unknown- or ambiguous-resolution write kills the CommonJS loader flag only when no lexical require binding intervenes between the write and program scope. Function params and direct body declarations, catch params, and block or loop-head lexical declarations shield the loader, so a dynamic write that can only reach a local binding keeps the real edge. A dynamic write with no such shield still fails closed. The full write traversal runs only when a require write exists. Adds local-binding shield fixtures and keeps the invalid cases edgeless.
26db13f to
40d7a86
Compare
|
Addressed the review threads in 40d7a86 (squashed): unknown- and ambiguous-resolution writes now kill the loader flag only when no lexical require binding intervenes (function params and direct body declarations, catch params, block and loop-head lexical declarations); the reported local-param control keeps its edge and is a regression fixture with three shield variants. The traversal runs only when a require write exists. Validation: 3/3 shadowed-require tests plus the adjacent import/graph/summary suites green, check:fast green. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 40d7a86347
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| if (scope === undefined) continue; | ||
| if (t.isProgram(scope)) return false; | ||
| if (t.isFunction(scope)) { | ||
| if (bindsRequireIdentifier(scope.params)) return true; |
There was a problem hiding this comment.
Exclude computed method keys from parameter shielding
When a with assignment is evaluated from a computed object-method key and that method declares a require parameter (for example, ({ [(() => { with ({}) { require = () => "local"; } })()](require) {} }); require("./dep")), the parameter is not in scope while the key runs; collectDefinitionsSteps already models this at src/domain/javascript/javascriptSemanticAnalysis.ts:749-755. This check nevertheless treats the method as an enclosing lexical scope and returns true, so the assignment that actually replaces the CommonJS wrapper loader is ignored and the later require is emitted as a real edge. Resolve the write through the shared semantic scope instead of AST ancestry.
AGENTS.md reference: AGENTS.md:L19-L19
Useful? React with 👍 / 👎.
…oops Function-body var bindings do not exist while parameter defaults run, and computed method keys evaluate in the outer scope, so neither shields a dynamic write there. Nested function-owned vars shield through hoisting, and heads over statically empty iterables never assign. Adds drop/keep fixtures for default params, computed keys, nested vars, and empty loops.
|
Addressed the latest threads in this push: parameter-default and computed-key writes no longer inherit body bindings (verified against Node execution semantics), nested function-owned vars shield through hoisting, and statically empty loop heads stay uninitialized. Regression fixtures cover all four shapes with Node oracles; the new cases fail without the source changes. Suites green (3/3 file tests, 51 adjacent), check:fast green. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 9e7f223d14
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| if (bindsRequireIdentifier(scope.params)) return true; | ||
| if (child === scope.body) { | ||
| if (functionBodyBindsRequire(scope.body)) return true; | ||
| } else if (functionDeclarationsBindRequire(scope.body)) return true; |
There was a problem hiding this comment.
Do not shield parameter-default writes with body functions
When a parameter default performs the dynamic write, declarations in the function body are not in scope during that parameter evaluation. The fresh final-tree counterexample function patch(x = (() => { with ({}) { require = () => "local"; } })()) { function require() {} } is nevertheless treated as shielded by this else, so a later top-level require("./dep") produces a false requires edge even though the default replaced the CommonJS loader; resolve this from the semantic scope owner rather than body syntax.
AGENTS.md reference: AGENTS.md:L19-L19
Useful? React with 👍 / 👎.
| child = scope; | ||
| continue; | ||
| } | ||
| if (!t.isBlockStatement(scope) && !t.isStaticBlock(scope)) { |
There was a problem hiding this comment.
Honor switch scopes when shielding dynamic writes
When a with assignment follows let require; in a switch case inside a function, that switch-wide lexical binding prevents the write from reaching the CommonJS wrapper loader. A fresh final-tree case such as switch (0) { case 0: let require; with ({}) { require = () => "local"; } } is missed because this ancestry scan skips SwitchCase/SwitchStatement, causing a separate real top-level require("./dep") edge to be dropped; use the existing semantic scope facts instead.
AGENTS.md reference: AGENTS.md:L19-L19
Useful? React with 👍 / 👎.
| }; | ||
|
|
||
| const isStaticallyEmptyIterable = (node: t.Node | null | undefined): boolean => | ||
| (t.isArrayExpression(node) && node.elements.length === 0) || |
There was a problem hiding this comment.
Preserve loaders across sparse zero-iteration
for-in loops
The post-fix counterexample for (var require in [,]) {} executes zero iterations with ordinary prototypes because for-in skips array holes, so a following require("./dep") still invokes the wrapper loader. Testing only elements.length === 0 treats the hole as an iteration, marks the binding initialized at line 383, and drops that real edge; emptiness needs to account for the loop kind and absent array elements.
AGENTS.md reference: AGENTS.md:L19-L19
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Addressed in 3299ed1 (verified locally; CI on this push pending): emptiness is now loop-kind aware — for-in counts present elements because it skips holes, for-of keeps length because it yields them. Fixture for (var require in [,]) {} keeps its edge (Node oracle loads the dep); for (var require of [,]) {} drops its (yields undefined, throws TypeError at the call — oracle-verified). Both live in the new test, which fails with the src hunk reverted.
| } | ||
| if (bindsRequireIdentifier(scope.params)) return true; | ||
| if (child === scope.body) { | ||
| if (functionBodyBindsRequire(scope.body)) return true; |
There was a problem hiding this comment.
Cache local-binding scans across dynamic writes
When a large generated CJS function contains many with assignments plus one local var require, every unknown write calls functionBodyBindsRequire and fully traverses the same function body; setting found only short-circuits callback work and does not prune traversal. With the number of writes proportional to body size this makes reference import quadratic, so derive or cache the function binding fact once (preferably from the existing semantic owner).
AGENTS.md reference: AGENTS.md:L46-L48
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Addressed in 3299ed1 (verified locally; CI on this push pending): per-function binding facts memoize in a WeakMap keyed by body node, and the write walk is additionally gated on a require write existing (provably equivalent — no write references means reached stays false). Measured ad hoc on a synthetic file (one var require, 1500 with writes): ~2000ms before, ~70-130ms after on this machine — the per-write body rescan dominated, and the pollution scan adds one linear pass. No committed timing test (flaky by nature); the suites below are the standing proof.
Parameter defaults run before body var bindings exist, and computed method keys evaluate in the outer scope, so neither inherits the other side's shield. Switch cases contribute their direct lexical bindings. Adds fixtures for default functions, computed keys, switch lets, and the empty-loop keep.
|
pushed fixes for the new threads. i verified all four shapes against node first: body function declarations do not exist yet when defaults run, computed keys run outside, switch lets do shield, and empty loops keep the loader. i scoped the shields to the write's own region, added fixtures for each, and left prototype pollution out since static analysis trusts intact intrinsics everywhere. 3/3 file tests and 51 adjacent pass, check:fast is green. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 74f9c436d2
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| if ( | ||
| (reference.resolution === "unknown" || | ||
| reference.resolution === "ambiguous") && | ||
| !writeShieldedByLocalBinding(node, readAncestors()) |
There was a problem hiding this comment.
Preserve loaders when a
with object captures the write
For a fresh binding object such as with ({ __proto__: null, require: null }) { require = () => 'local'; }, lookup must resolve to the object's own property, so the CommonJS wrapper parameter is untouched and a later top-level require('./dep') remains a real edge. This unknown-resolution branch only checks lexical shields, marks the program loader written, and drops that edge; the semantic with scope needs to retain a provable object binding instead of treating every such write as a fallback write.
AGENTS.md reference: AGENTS.md:L19-L19
Useful? React with 👍 / 👎.
| t.isVariableDeclaration(statement) && | ||
| statement.kind !== "var" && |
There was a problem hiding this comment.
Include block class bindings in dynamic-write shields
The fresh final-tree counterexample after the local-binding fixes is function patch() { { class require {}; with ({}) { require = () => 'local'; } } }: the assignment updates the block-local class binding, but this predicate recognizes only non-var variable declarations. Calling patch() therefore causes loaderWriteReachesProgramScope to suppress a separate top-level require('./dep') edge even though the wrapper loader is intact; use the semantic scope's declarations rather than this declaration-kind subset.
AGENTS.md reference: AGENTS.md:L19-L19
Useful? React with 👍 / 👎.
| if (bindsRequireIdentifier(scope.params)) return true; | ||
| if (child === scope.body && functionBodyBindsRequire(scope.body)) | ||
| return true; |
There was a problem hiding this comment.
Honor named function-expression bindings
The fresh final-tree counterexample const patch = function require() { with ({}) { require = () => 'local'; } }; patch(); require('./dep') leaves Node's wrapper loader unchanged because the write resolves to the function expression's private name binding. This branch checks parameters and body declarations but never the function's own name, so it marks the program loader written and loses the real top-level relationship; resolve the fallback through the existing function-name semantic scope.
AGENTS.md reference: AGENTS.md:L19-L19
Useful? React with 👍 / 👎.
| } | ||
| if (t.isCatchClause(scope) && bindsRequireIdentifier([scope.param])) | ||
| return true; | ||
| if (t.isSwitchCase(scope) && blockBindsLexicalRequire(scope.consequent)) |
There was a problem hiding this comment.
Search the whole switch scope for
require bindings
The fresh final-tree evidence after the posted switch fix is that this scans only the current case, although javascriptSemanticAnalysis.ts:1189-1191 models all cases as one lexical scope. In switch (1) { case 1: let require; case 0: with ({}) { require = () => 'local'; } }, execution initializes the switch-local binding and falls through before the write, so the wrapper loader is untouched; because the declaration is in a sibling case, this check misses it and drops a subsequent real top-level require('./dep') edge.
AGENTS.md reference: AGENTS.md:L19-L19
Useful? React with 👍 / 👎.
|
|
||
| const isStaticallyEmptyIterable = (node: t.Node | null | undefined): boolean => | ||
| (t.isArrayExpression(node) && node.elements.length === 0) || | ||
| (t.isObjectExpression(node) && node.properties.length === 0) || |
There was a problem hiding this comment.
Do not assume empty object literals make
for-in empty
When an inherited enumerable property exists, for example Object.prototype.inherited = 1; for (var require in {}) {}, the loop executes and replaces the wrapper parameter with the property name, so a following apparent require('./dep') call is not a loader call. Treating every zero-property object literal as statically empty instead leaves hasUninitializedTopLevelVarRequire true and emits a false requires edge; for-in emptiness must retain prototype/enumeration uncertainty rather than considering only own literal properties.
AGENTS.md reference: AGENTS.md:L21-L21
Useful? React with 👍 / 👎.
|
Latest threads addressed in 3299ed1 (verified locally; CI on this push pending):
Validation: 4/4 shadowed-require tests, 53 green across the five adjacent suites (dynamic imports, import, summary, graph), check:fast green (tsc+lint, 0 errors). Residual, stated in code: reflective prototype mutation (defineProperty/Reflect/setPrototypeOf) is not scanned — member writes are the realistic shape; the rest is a documented follow-up. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 3299ed11d8
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| const site = semanticWriteSiteTarget(node); | ||
| if (site === null) return; |
There was a problem hiding this comment.
Treat reflective prototype mutation as iteration pollution
When a CJS file calls Object.defineProperty(Object.prototype, "x", { enumerable: true, value: 1 }) before for (var require in {}) {}, the loop executes and overwrites the wrapper parameter. The fresh final-tree evidence after the earlier prototype fix is that this scanner returns immediately because the call has no semanticWriteSiteTarget, then classifies {} as empty and emits a later require("./dep") as a loader edge; reflective or otherwise unproved prototype mutation must remain pollution/unknown rather than absence.
AGENTS.md reference: AGENTS.md:L21-L21
Useful? React with 👍 / 👎.
| return isForIn | ||
| ? node.elements.every((element) => element === null) | ||
| : node.elements.length === 0; | ||
| if (t.isObjectExpression(node)) return node.properties.length === 0; |
There was a problem hiding this comment.
Ignore prototype setters when counting for-in keys
For for (var require in { __proto__: null }) {}, the non-computed __proto__ entry sets the literal's prototype and creates no enumerable own property, so the loop runs zero iterations and the wrapper loader remains intact. Testing properties.length nevertheless marks this binding initialized and drops a following real require("./dep") edge; determine whether the literal has enumerable string keys instead of counting this special setter as one.
Useful? React with 👍 / 👎.
| let initialized = false; | ||
| // Computed once per file: the exemption below infers non-iteration from | ||
| // literal contents, which holds only while shared prototypes are intact. | ||
| const mayPollute = fileMayPolluteIteration(program); |
There was a problem hiding this comment.
Skip the pollution scan without a candidate loop
Every non-explicit-module source invokes fileMayPolluteIteration before this helper has established that the file even contains a top-level var require in a potentially empty loop, adding a complete AST traversal to ordinary .js/.cjs files that cannot use its result. On large reference-source imports this is avoidable linear CPU work per file; collect pollution during the existing traversal or defer the extra pass until a candidate empty loop is found.
AGENTS.md reference: AGENTS.md:L49-L49
Useful? React with 👍 / 👎.
A with object that statically declares require captures the write, so it shields. Block class declarations and named function expression ids shield like other lexical bindings, and switch lets shield across sibling cases. Prototype pollution is now loop-kind aware: plain member writes affect for-in only, iterator and proto changes affect for-of, reflective mutation affects both. A non-computed __proto__ entry creates no key. The pollution scan runs only when a candidate empty loop exists.
|
pushed fixes for the new threads. i ran every shape in node first: with-objects holding require capture the write, block classes and named function ids shield, switch lets cover sibling cases, and plain member writes dont touch for-of iteration. i also split the pollution check by loop kind, added the reflective calls, and the scan now runs only when a candidate loop exists. 4/4 file tests and 51 adjacent pass, check:fast is green, new fixtures fail without the fix. |
| return object.properties.some( | ||
| (property) => | ||
| (t.isObjectProperty(property) || t.isObjectMethod(property)) && | ||
| !property.computed && | ||
| ((t.isIdentifier(property.key) && property.key.name === "require") || | ||
| (t.isStringLiteral(property.key) && | ||
| property.key.value === "require")), |
There was a problem hiding this comment.
Skipped properties hide loader writes
withObjectDeclaresRequire treats a literal require property as proof that a write cannot reach Node's loader. But with ({ require: null, [Symbol.unscopables]: { require: true } }) { require = () => 'local'; } replaces the loader because Symbol.unscopables makes the object skip that property.
The shortcut hides this write, so a later require('./dep.cjs') produces a false dependency. Only shield the write when the object is known to capture it.
Prompt To Fix With AI
This is a comment left during a code review.
Path: src/domain/referenceSourceRequireBindings.ts
Line: 320-326
Comment:
**Skipped properties hide loader writes**
`withObjectDeclaresRequire` treats a literal `require` property as proof that a write cannot reach Node's loader. But `with ({ require: null, [Symbol.unscopables]: { require: true } }) { require = () => 'local'; }` replaces the loader because `Symbol.unscopables` makes the object skip that property.
The shortcut hides this write, so a later `require('./dep.cjs')` produces a false dependency. Only shield the write when the object is known to capture it.
---
For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: a297eaecee
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| t.isIdentifier(object) && | ||
| ITERATION_PROTOTYPES.has(object.name) && | ||
| key === "prototype" |
There was a problem hiding this comment.
Resolve prototype aliases before declaring for-in inputs empty
The fresh final-tree case const proto = Object.prototype; proto.inherited = 1; for (var require in {}) {} is not recognized because this predicate only accepts a receiver literally named Object, Array, or String. The loop does execute and replaces the CommonJS wrapper parameter, yet isStaticallyEmptyIterable reports {} empty and a following require('./dep') is emitted as a false edge; resolve the receiver through the existing semantic binding/provenance facts before declaring no pollution.
AGENTS.md reference: AGENTS.md:L19-L19
Useful? React with 👍 / 👎.
| return landedComputed === true | ||
| ? FULL_ITERATION_POLLUTION | ||
| : { forIn: true, forOf: false }; |
There was a problem hiding this comment.
Use resolved computed keys for for-of pollution
For Array.prototype['helper'] = () => 1; for (var require of []) {}, semanticStaticPropertyKey has already proven that the key is helper, which neither changes the array iterator nor adds an element, so the loop still executes zero iterations. landedComputed nevertheless forces full pollution solely because the syntax is computed, causing the valid following require edge to be dropped; determine the for-of effect from the resolved key instead of the computed bit.
AGENTS.md reference: AGENTS.md:L19-L19
Useful? React with 👍 / 👎.
| const isNonComputedProtoSetter = (property: t.Node): boolean => | ||
| t.isObjectProperty(property) && | ||
| !property.computed && | ||
| ((t.isIdentifier(property.key) && property.key.name === "__proto__") || | ||
| (t.isStringLiteral(property.key) && property.key.value === "__proto__")); |
There was a problem hiding this comment.
Prove proto-setter prototypes before declaring objects empty
The final predicate treats every non-computed __proto__ entry as evidence that an object is empty, but for (var require in { __proto__: { inherited: 1 } }) {} executes once through the inherited enumerable key and replaces the CommonJS wrapper parameter. This leaves hasUninitializedTopLevelVarRequire true and emits a false later require edge; only classify the literal as empty when the setter value or resulting prototype's enumerable state is actually proven empty.
AGENTS.md reference: AGENTS.md:L21-L21
Useful? React with 👍 / 👎.
| if (!t.isWithStatement(scope)) continue; | ||
| const object = scope.object; | ||
| if (!t.isObjectExpression(object)) continue; | ||
| return object.properties.some( |
There was a problem hiding this comment.
Continue through outer with environments
With nested scopes such as with ({ require: null }) { with ({}) { require = () => 'local'; } }, lookup misses the inner object and is then captured by the outer object, so the wrapper loader remains intact. This returns false immediately for the inner object literal instead of examining the remaining ancestors, making loaderWriteReachesProgramScope drop a later real require('./dep') edge; continue the environment lookup through enclosing with scopes.
AGENTS.md reference: AGENTS.md:L19-L19
Useful? React with 👍 / 👎.
| (t.isObjectProperty(property) || t.isObjectMethod(property)) && | ||
| !property.computed && | ||
| ((t.isIdentifier(property.key) && property.key.name === "require") || | ||
| (t.isStringLiteral(property.key) && | ||
| property.key.value === "require")), |
There was a problem hiding this comment.
Honor unscopables when proving with-object capture
The property-name test treats an own require property as unconditional capture, but with ({ require: null, [Symbol.unscopables]: { require: true } }) { require = () => 'local'; } explicitly excludes that property from the environment, so the assignment falls through and replaces the CommonJS wrapper loader. Shielding this write causes the later apparent loader call to be emitted as a false edge; account for Symbol.unscopables or retain the capture as unknown.
AGENTS.md reference: AGENTS.md:L21-L21
Useful? React with 👍 / 👎.
| (t.isVariableDeclaration(statement) && | ||
| statement.kind !== "var" && | ||
| statement.declarations.some((declaration) => | ||
| bindsRequireIdentifier([declaration.id]), | ||
| )) || |
There was a problem hiding this comment.
Include block functions in lexical write shields
The final-tree case function patch() { { function require() {}; with ({}) { require = () => 'local'; } } } leaves the wrapper loader untouched because the write resolves to the block's function binding. blockBindsLexicalRequire recognizes lexical variables and classes but omits FunctionDeclaration, while the function-body scan also ignores this declaration because it is not a direct child of the function body, so a later real top-level edge is dropped; use the semantic scope's declaration facts here.
AGENTS.md reference: AGENTS.md:L19-L19
Useful? React with 👍 / 👎.
… keyed protos Symbol.unscopables entries opt the name back out, so a capturing object with one no longer shields. Switch case bindings do not cover the discriminant expression. Only keyless prototype chains keep an object literal empty for for-in. Adds fixtures for all three with Node oracles.
|
pushed fixes for the latest threads. i verified each one in node: unscopables with a require entry really does opt back out, discriminant writes run before case bindings exist, and only keyless proto chains iterate nothing. i also fixed my own unscopables matcher which never matched. 4/4 file tests and 51 adjacent pass, check:fast is green, new fixtures fail without the fix. |
| !t.isObjectProperty(unscopables) || | ||
| !t.isObjectExpression(unscopables.value) || |
There was a problem hiding this comment.
A non-object Symbol.unscopables value now causes real dependencies to be dropped. For example, with ({ require: null, [Symbol.unscopables]: null }) { require = () => 'local'; } require('./dep.cjs'); leaves Node's loader unchanged: the assignment updates the object's require property.
This check rejects that protection, marks the loader as written, and drops the real dependency. Recognize known non-object values as leaving the object's bindings available, and add a regression control.
Prompt To Fix With AI
This is a comment left during a code review.
Path: src/domain/referenceSourceRequireBindings.ts
Line: 348-349
Comment:
**Real dependencies disappear**
A non-object `Symbol.unscopables` value now causes real dependencies to be dropped. For example, `with ({ require: null, [Symbol.unscopables]: null }) { require = () => 'local'; } require('./dep.cjs');` leaves Node's loader unchanged: the assignment updates the object's `require` property.
This check rejects that protection, marks the loader as written, and drops the real dependency. Recognize known non-object values as leaving the object's bindings available, and add a regression control.
---
For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.| if (t.isNullLiteral(node)) return true; | ||
| if (!t.isObjectExpression(node)) return false; |
There was a problem hiding this comment.
The new recursive check drops real dependencies when a prototype setter has a primitive value. For example, for (var require in { __proto__: 0 }) {} require('./dep.cjs'); still calls Node's loader. JavaScript ignores the primitive prototype value, so the loop has no keys and never assigns require.
This helper instead returns false, causing the importer to treat the loader as replaced. Preserve the empty-loop result for known primitive prototype values and add a regression control.
Prompt To Fix With AI
This is a comment left during a code review.
Path: src/domain/referenceSourceRequireBindings.ts
Line: 542-543
Comment:
**Empty loops hide dependencies**
The new recursive check drops real dependencies when a prototype setter has a primitive value. For example, `for (var require in { __proto__: 0 }) {} require('./dep.cjs');` still calls Node's loader. JavaScript ignores the primitive prototype value, so the loop has no keys and never assigns `require`.
This helper instead returns `false`, causing the importer to treat the loader as replaced. Preserve the empty-loop result for known primitive prototype values and add a regression control.
---
For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: c04ab26a49
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| if (!t.isWithStatement(scope)) continue; | ||
| const object = scope.object; | ||
| if (!t.isObjectExpression(object)) continue; | ||
| if (!object.properties.some(isRequireKey)) continue; |
There was a problem hiding this comment.
Restrict with-object captures to active statement bodies
When a write occurs while evaluating an enclosing with object's expression, that outer environment is not active yet. In with ({ require: (() => { with ({}) { require = () => 'local'; } return null; })() }) {}; require('./dep'), the inner assignment replaces the CommonJS loader, but this ancestor-only scan sees the outer object's require property and calls the write shielded, so the later local call is emitted as a false requires edge. Restrict this check to nodes contained in scope.body, matching the shared semantic scope owner.
AGENTS.md reference: AGENTS.md:L19-L19
Useful? React with 👍 / 👎.
| callee.property.name === "defineProperty" || | ||
| callee.property.name === "defineProperties" || | ||
| callee.property.name === "setPrototypeOf" | ||
| ) | ||
| return true; |
There was a problem hiding this comment.
Check reflective mutation targets before polluting iteration
When a file also contains a reflective write unrelated to a shared prototype—for example, Object.defineProperty(module.exports, 'x', { value: 1 }); for (var require of []) {}; require('./dep')—the empty loop never assigns require and Node still loads dep. These lines classify the call as full iteration pollution solely from the callee name, making hasUninitializedTopLevelVarRequire report the loader initialized and dropping that real edge. Inspect the mutation target (and relevant key/descriptor) before setting pollution instead of treating unresolved applicability as shared-prototype mutation.
AGENTS.md reference: AGENTS.md:L21-L21
Useful? React with 👍 / 👎.
| const requireLoaderWasWritten = | ||
| hasRequireWrite && | ||
| loaderWriteReachesProgramScope( |
There was a problem hiding this comment.
Limit loader writes to calls they can precede
For a top-level call that precedes a dynamic write, such as require('./dep'); with ({}) { require = () => 'local'; }, the dependency is loaded before replacement. loaderWriteReachesProgramScope nevertheless sees the later unknown write, and this one file-wide boolean is applied to every call by the condition at line 98, so the commit drops the real earlier edge. Compute reachability relative to each call (at least preserving direct top-level source order) rather than globally.
AGENTS.md reference: AGENTS.md:L19-L19
Useful? React with 👍 / 👎.
Model the CommonJS wrapper binding and query shared lexical identity, mutation, and evaluation timing at each call. Remove duplicate importer interpretation and preserve uncertainty for with scopes, prototypes, repeated writes, and opaque object escapes. Validate generated fixtures against bounded Node oracles; no analyzed target execution is added. Refs: #3982, #4072 Co-authored-by: Geronimo <[email protected]>
|
Conflict check from the CI & conflict-fix track: this branch conflicts with main, and main's 1b9b725 ("fix(javascript): unify loader binding and mutation ownership") references #4072 and is co-authored from this PR, so the change has already landed there. Resolving the conflict would reduce this branch to main's version, so I left it untouched. A maintainer may want to close this as superseded. |
|
Sounds good. Thanks for letting me know :D |
Summary
Fixes #3982.
import-reference-sourcereported a parsed internalrequiresedge when the apparent loader call targeted a replaced local function: afor-in/ofvarhead initializes its binding on every iteration, and an assignment insidewithleaves the binding identity unknown. Both now fail closed like a plain assignment, while a truly uninitialized top-levelvar requireretains its edge.Problem and expected behavior
Trigger:
for (var require of [() => "local"]) {}orwith ({}) { require = () => "local"; }followed byrequire("./dep.cjs")in a.cjsfile. Node prints onlylocal; the importer reported a parsed internal edge todep.cjs.{"from_path": "main.cjs", "to": "dep.cjs", "kind": "requires", "resolution": "internal", "parse_state": "parsed"}.var requirecontrol keeps its edge.Change and scope
Two changes in
src/domain/referenceSourceRequireBindings.ts, the single owner of loader attribution:hasUninitializedTopLevelVarRequiretreats avardeclarator bindingrequireas initialized when it is the head of afor-in/ofstatement. A barefor (var require;;)head stays uninitialized.requireLoaderWasWrittencountsunknown-resolution writes alongside unbound ones, so an assignment under dynamic scope (with) fails closed instead of reading as an intact loader.Genuinely absent bindings, shadowing declarations, member overwrites, and calls lexically inside
withare unchanged. Test-only additions otherwise.Contribution scope fit and linked maintainer decision: ordinary fix within existing boundaries; not applicable.
Contract and boundary impact
referenceSourceRequireBindings.unshadowedReferenceSourceRequireCalls(reference-source import parsing).requiresrelationships; no schema changes.Expected effects:
Evidence and regression coverage
for-of-var,for-in-var, andwith-writefixtures intests/boundary/filesystem/referenceSourceShadowedRequire.test.ts, each with a Node-oracle stdout check, excluded from the expected dependency list. The existing valid controls are unchanged.relationshipsarray in the import result; no CLI flag changes.For evidence-bearing changes:
Validation performed
npm run test:focused -- tests/boundary/filesystem/referenceSourceShadowedRequire.test.ts— 2 passed.npm run test:focused -- <referenceSourceImport, ReferenceSourceImportEntries, referenceSourceGraph, referenceSourceSummary>— 51 passed.npm run check:fast(typecheck + lint) — green.git diff --check— clean.Compatibility, safety, and release
Author readiness
Human owner:
Before merge
type(scope): outcome.