Repository navigation
fix(javascript): global augmentation kind and additional web/browser inspections - #2986
rekcilyssup wants to merge 19 commits into
Conversation
import value = require("./dep.cjs") in a .cts source parsed with
complete coverage but produced no import relationship and reported
module_format unknown, while the emitted program loads the dependency.
Bind the declaration as an immutable import alias, project it as a
require module link, and emit the matching static require reference so
both graph producers keep the dependency. Type-only declarations and
internal namespace aliases keep their local alias without a module
origin because TypeScript emits no load for either form. Module format
now follows Node and TypeScript's extension rule for mts and cts, so an
mts source stays ESM when its import-equals compiles through
createRequire.
Pinned main already implements import-equals via owning helper; removed duplicate merged producers and obsolete redundant unit regression, retained contributor filesystem regression. Review fixes preserve internal alias provenance from TSQualifiedName, add namespace scope ownership, and verify per-source require edges and declaration ranges. Source inspection and git diff --check. Further tests/typechecks/builds skipped by explicit user instruction; canceled validations are not passes.
Admit immutable import-equals initializers to the shared stable-initializer owner. Namespace blocks retain private lexical scope while a shared exported-member owner resolves repeated namespace declarations; all binding lookup paths reuse that owner. Source inspection and git diff --check only. Tests, builds and typechecks skipped by explicit user request. GitHub review writes paused globally.
…mport
The call root is the shared Electron module alias itself, so the proven
root path is empty, matching the established require("electron")
.ipcMain.handle classification. The authored expectation ipcMain was
never run and made the reopened-namespace regression fail on the
correct behavior.
Validated with typecheck and the javascript domain and application
suites.
The shared-owner walk in semanticScopedBinding consulted every owner binding before the lexical climb resumed, so a nested exported namespace resolved names against its containing namespace's export owner before the enclosing block's private bindings. A private ipcRenderer binding in a reopened namespace block lost to the shared ipcMain export, and an enclosing namespace private lost to a same-named program binding. Stop the owner walk at any owner that an enclosing lexical scope claims as its namespaceExportScopeId (or reaches as its parent), so each enclosing scope resolves its own private bindings first while dotted bodies still read outer-segment exports that their lexical parent skips. The strict worker scope schema also lacked the "namespace" kind and namespaceExportScopeId that immutableSemanticScopes now emits, so any TSModuleBlock scope failing the record parse would abort a transfer. Extend the schema with a round-trip test that retains namespace scopes and their export owners across writeJavaScriptAnalysisTransfer.
namespaceDeclarationScope only recognized an ExportNamedDeclaration
wrapper, but ambient namespace and module bodies export every member
implicitly. A reopened ambient block therefore kept its members private:
declare namespace N { const require: ... } followed by namespace N bound
the second block's require() call to nothing, so collectUnboundRequireLink
invented a dependency on the call's string argument even though
TypeScript emits N.require(...) and no module is loaded.
Route declarations whose ancestor chain includes a declare-marked
TSModuleDeclaration to the shared exported-member owner, matching the
TypeScript rule that ambient members are exported by default at any
nesting depth. The shared owner keeps the reopened block's reference
resolved, which suppresses the fabricated require link at its source.
A top-level `declare global` block was modeled as an ordinary named namespace, so its members landed under a synthesized exports:["global"] owner that program-name lookup never traverses. The augmented binding was recorded unbound and collectUnboundRequireLink invented a runtime dependency on the call's string argument. Babel 8 marks no global flag, so a global augmentation is identified by declare: true with an Identifier id of global directly under the Program; a nested `declare namespace global` keeps its namespace owner. Route the augmentation block's namespaceExportScopeId to the enclosing program scope so its members participate in global name lookup. The ambient walk in ambientNamespaceContext also now starts at the declaration itself: a declaration that is itself ambient (`declare namespace B`) exports its own name, so its owner matches the one reopened dotted declarations create instead of leaving them unbound.
Distinguish `declare global` by Babel's exact `kind: "global"` discriminator instead of the identifier name: a top-level `declare namespace global` carries `kind: "namespace"` and declares an ordinary namespace whose later require() calls keep their dependency links. The name heuristic misclassified it and hid its dependencies. Bind augmentation members in a lazily created outer scope, parented above the program scope, rather than in the program scope itself. Augmentation members live outside the module scope, so file-local bindings now shadow them instead of merging: an `import ipc` keeps its single definition beside a global `var ipc`, and the local call still classifies. The outer scope participates in ordinary lexical lookup, so global-only names keep resolving from any program position.
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. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 0665f62de5
ℹ️ 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.isTSModuleDeclaration(node) && | ||
| node.declare === true && | ||
| node.kind === "global" && | ||
| t.isProgram(state.parentsByNode.get(node) ?? null); |
There was a problem hiding this comment.
Handle global augmentations inside ambient modules
When a valid ambient external module directly contains global { ... }—for example declare module "host" { global { const require: ... } }—the global declaration's parent is a TSModuleBlock, not the Program, and the ambient syntax need not repeat declare. This predicate therefore routes the body through ordinary namespace ownership, making its members invisible to program lookup; a following require("not-a-module") is then reported as a spurious CommonJS dependency even though the identifier is globally declared. Resolve this ambient-module form to the enclosing program-global owner as well.
AGENTS.md reference: AGENTS.md:L19-L19
Useful? React with 👍 / 👎.
[Medium impact] Refines JavaScript semantic analysis for TypeScript namespaces and import-equals. Fix the qualified-alias checks before merging; they can report replaced functions as original Node methods. Findings
Fix with agent prompt### Issue 1
src/domain/javascript/javascriptSemanticValues.ts:953-956
`TSQualifiedName` aliases now receive a module origin, but the checks for replaced members do not follow their initializers. For example, `import fs = require("node:fs"); fs.readFileSync = custom; import read = fs.readFileSync; read("config.json");` is reported as a file read even though it calls the replacement function. `computeBuiltinBindingPath` skips the qualified-name initializer and misses the earlier write.
Writes through qualified aliases also stop in `collectSemanticMemberMutationsSteps`. Share the member-path logic across alias reads, writes, and built-in checks, and test both directions.
### Issue 2
src/domain/javascript/javascriptSemanticState.ts:250-255
`deferredNamespaceOwner` scans the enclosing scopes for each export owner and repeats that work at every enclosing namespace. Reading an unbound name such as `console` inside deeply nested exported namespaces therefore takes quadratic work in the nesting depth. Many reads repeat these scans, and the outer traversal cannot yield during a lookup. This makes large generated files slow and less responsive to cancellation.
Precompute the owner lookup order or cache these results instead of walking the same ancestors for every read.
Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!
### Issue 3
src/browser/WebSourceMapFetcher.ts:1066-1068
Neither changed reader has a regression test for a constant template passed to `import` or `require`. Existing tests cover quoted imports and import-looking text inside templates, so either reader could drop these new edges again without a test failing.
Add tests through `fetchWebSourceMaps` and `analyzeCapturedWebBundle` that retain constant templates, skip interpolated templates, and still skip a shadowed `require`. Testing `stringValue` alone would not protect both readers.
Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!
---
For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.SummaryThis PR separates private namespace blocks from shared exports, recovers internal TypeScript aliases, and adds outer scopes for global augmentations.
Diagram%%{init: {'theme': 'neutral'}}%%
flowchart LR
P[Source and path] --> AST[Parsed Program]
AST --> L[Private namespace block]
L --> E[Shared namespace exports]
L --> O[Enclosing lexical scope]
O --> M[Program bindings]
M --> G[Outer global augmentation]
L --> IR[Semantic facts]
E --> IR
IR --> W[Worker transfer schema]
Reviews (7) · Last reviewed commit: "Merge remote-tracking branch 'origin/mai..." · Reviewed by Greptile |
| if (t.isImportExpression(node)) { | ||
| const specifier = stringValue(node.source); | ||
| if (specifier !== undefined) return { kind: "dynamic_import", specifier }; |
There was a problem hiding this comment.
Template dependencies lack regression tests
Neither changed reader has a regression test for a constant template passed to import or require. Existing tests cover quoted imports and import-looking text inside templates, so either reader could drop these new edges again without a test failing.
Add tests through fetchWebSourceMaps and analyzeCapturedWebBundle that retain constant templates, skip interpolated templates, and still skip a shadowed require. Testing stringValue alone would not protect both readers.
Prompt To Fix With AI
This is a comment left during a code review.
Path: src/browser/WebSourceMapFetcher.ts
Line: 1066-1068
Comment:
**Template dependencies lack regression tests**
Neither changed reader has a regression test for a constant template passed to `import` or `require`. Existing tests cover quoted imports and import-looking text inside templates, so either reader could drop these new edges again without a test failing.
Add tests through `fetchWebSourceMaps` and `analyzeCapturedWebBundle` that retain constant templates, skip interpolated templates, and still skip a shadowed `require`. Testing `stringValue` alone would not protect both readers.
---
For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: a7c89a1745
ℹ️ 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".
| // own name, so the walk starts at the declaration before climbing. | ||
| let candidate: t.Node | undefined = node; | ||
| while (candidate !== undefined) { | ||
| if (t.isTSModuleDeclaration(candidate) && candidate.declare === true) |
There was a problem hiding this comment.
Preserve ambient context from declaration files
When parseJavaScriptSource parses a valid .d.ts that omits declare (for example, namespace N { class C {} } namespace N { export import D = C; }), its dts parser option makes the file ambient but does not synthesize an explicit declare modifier on these nodes. This walk therefore returns false, so the new per-block scopes keep C private to the first block instead of placing it in the shared ambient owner; the valid alias in the reopened block is then reported unresolved. Carry the parser's declaration-file ambient context into semantic state rather than inferring ambientness only from modifiers.
AGENTS.md reference: AGENTS.md:L23-L23
Useful? React with 👍 / 👎.
Preserve CommonJS literal paths and confined ESM URL semantics, including package main fallback, directory intent, Unicode identity, and present opaque modules. Parse extraction inputs at their AST/source owner, retain skipped HTML and source-map coverage, and distinguish endpoint candidates from proven receiver facts. Version structural fingerprints with computed literal contents and propagate them through worker contracts. Reviewed fixes include #1810, #1840, #2642, #2700, #2702, #2714, #2803, #2960, #2968, #2986, #3035, and #3036. Validation: 158 resolver tests passed; public CLI/MCP module lookup controls, package-main/Unicode workflows, and six builtin workflows passed in the current compiled lane. Worker schema/fingerprint regressions passed. Large public pdf.js completion and real Electron analysis remain unverified.
|
Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits. |
|
Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits. |
# Conflicts: # src/application/javascript/JavaScriptArtifactPathResolution.ts # src/browser/CdpCaptureDocuments.ts # src/browser/WebSourceMapFetcher.ts # src/domain/javascript/javascriptSemanticAnalysis.require_links.test.ts # src/domain/webBundleAnalyzer.test.ts
|
Merged latest Main has since shipped several of this PR's smaller fixes on its own, so those five files take main's version:
This PR's TypeScript ambient and global-augmentation semantics merged cleanly and are kept: Validation on the merged tree:
Pre-existing failure, not caused by the merge: |
| if (t.isTSQualifiedName(current)) { | ||
| members.push(current.right.name); | ||
| current = current.left; | ||
| continue; |
There was a problem hiding this comment.
Replaced methods look original
TSQualifiedName aliases now receive a module origin, but the checks for replaced members do not follow their initializers. For example, import fs = require("node:fs"); fs.readFileSync = custom; import read = fs.readFileSync; read("config.json"); is reported as a file read even though it calls the replacement function. computeBuiltinBindingPath skips the qualified-name initializer and misses the earlier write.
Writes through qualified aliases also stop in collectSemanticMemberMutationsSteps. Share the member-path logic across alias reads, writes, and built-in checks, and test both directions.
Prompt To Fix With AI
This is a comment left during a code review.
Path: src/domain/javascript/javascriptSemanticValues.ts
Line: 953-956
Comment:
**Replaced methods look original**
`TSQualifiedName` aliases now receive a module origin, but the checks for replaced members do not follow their initializers. For example, `import fs = require("node:fs"); fs.readFileSync = custom; import read = fs.readFileSync; read("config.json");` is reported as a file read even though it calls the replacement function. `computeBuiltinBindingPath` skips the qualified-name initializer and misses the earlier write.
Writes through qualified aliases also stop in `collectSemanticMemberMutationsSteps`. Share the member-path logic across alias reads, writes, and built-in checks, and test both directions.
---
For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.| while (owner !== undefined && !deferredNamespaceOwner(owner, scope, state)) { | ||
| const exported = owner.bindings.get(name); | ||
| if (exported !== undefined) return exported; | ||
| if (!owner.bindingsComplete || owner.parentScopeId === null) | ||
| return undefined; | ||
| owner = state.scopesById.get(owner.parentScopeId); |
There was a problem hiding this comment.
deferredNamespaceOwner scans the enclosing scopes for each export owner and repeats that work at every enclosing namespace. Reading an unbound name such as console inside deeply nested exported namespaces therefore takes quadratic work in the nesting depth. Many reads repeat these scans, and the outer traversal cannot yield during a lookup. This makes large generated files slow and less responsive to cancellation.
Precompute the owner lookup order or cache these results instead of walking the same ancestors for every read.
Prompt To Fix With AI
This is a comment left during a code review.
Path: src/domain/javascript/javascriptSemanticState.ts
Line: 250-255
Comment:
**Nested lookups repeat work**
`deferredNamespaceOwner` scans the enclosing scopes for each export owner and repeats that work at every enclosing namespace. Reading an unbound name such as `console` inside deeply nested exported namespaces therefore takes quadratic work in the nesting depth. Many reads repeat these scans, and the outer traversal cannot yield during a lookup. This makes large generated files slow and less responsive to cancellation.
Precompute the owner lookup order or cache these results instead of walking the same ancestors for every read.
---
For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!
|
Thanks for carrying the TypeScript semantic fixes forward and documenting which smaller fixes have since landed. The current body still describes those superseded web/browser changes, and GitHub reports a conflict. Could you refresh against main and update the title and description around the remaining ambient namespace and global-augmentation behavior? Please also resolve or clearly scope the previously reported import-equals boundary-test failure before requesting review. The distinct TypeScript work remains open. |
|
@rekcilyssup thanks for the PR — there are 5 open review threads here:
Could you address or reply to these? Once they're resolved and CI is green we can take another look. |
This PR includes the semantic-analysis fixes from the PR #2081 review plus small fixes for web bundle template-literal imports, WebSourceMapFetcher dependencies, and browser agent-rel tokenization.