Skip to content

fix(js,ts): an import reaches what its module hands on, not a namesake or the first export - #2754

Open
colbymchenry wants to merge 1 commit into
mainfrom
claude/import-forwarded-defaults
Open

colbymchenry wants to merge 1 commit into
mainfrom
claude/import-forwarded-defaults

Conversation

@colbymchenry

Copy link
Copy Markdown
Owner

Replaces #2451, re-done as a fresh, small change on current main (553d5d1). It keeps only what main still lacks.

What #2451 still added on main

#2451 had two halves.

The JSX half is covered on main. #2563 (exportedComponent), #2558 (barrel forwarding), #2738 (wrapper hops), #2420 (own declarations), #2442 (tag positions), #2475 (package gate) and #2476 (generic tags) cover it. 11 of #2451's 14 cases pass on main as they are. Of the 3 that fail:

  • Two are JSX-only, and main leaves them silent or acceptable, not wrong:
    • react.dev's export default memo(function SandpackWithHTMLOutput() {…}), where main renders nothing.
    • A codegenNativeComponent held in a const, where main renders the const.
  • The third is the general resolver below.

The general import resolver (findExportedSymbol) still gets these wrong on main. Each gives a wrong edge, not a missing one:

shape main links this PR links
import makeAvatar from './makeAvatar'; export default makeAvatar (index forwarding a default) a same-named function in another folder the module's own default
import presentUser from './user'; export { presentUser } (barrel forwarding an import) a namesake anywhere (outline: server/mcp/tools/*) presenters/user.ts
class Logger {…}; export default new Logger() the other app's Logger::info (outline: 355 server calls → app/utils/Logger.ts) the module's own class's methods
export default traceFunction({…})(accountProvisioner) the first exported function (provisionFirstCollection) accountProvisioner
export { createThing as default } the first exported function createThing

What changes (src/resolution/import-resolver.ts only)

  • The export default statement is read further. statedDefaultExport / readDefaultExport now also read:
    • new X(), as the class the file declares;
    • what a wrapper call hands on (handedOn), through nested wrappers (withTranslation()(withRouter(Login))):
      • its last argument list's first argument, when it is capitalized (observer(Login), React.memo(Row, areEqual)) or ends a curried chain (connect(mapState)(Login), traceFunction({…})(fn));
      • or a named function written there (memo(function X() {…}));
    • export { X as default }.
  • A default that names an import is that import. It is followed with the walk's visited set and depth (esmDefaultExport → importedDeclaration).
  • A local export clause naming an import is followed too. This covers export { X }, export { X as Y } and CommonJS module.exports = { X } (forwardedExport; clauseImports is filled beside clauseAliases), in both the named and the namespace-member branches.

Decisions, noted here instead of asking:

  • A wrapper's argument counts only when it can't be a factory's input. A lone call's lowercase argument doesn't count: createStore(reducer) is a store (a peer's catch on fix(react): a JSX tag renders what the file imports under that name #2451). Only a function, class or component of the file answers, so createContext(DefaultTheme) doesn't hand on the theme constant.
  • new X() and wrapper arguments resolve only inside the file. An imported class or wrapped import isn't followed: sync's tracking of re-exported bindings (ImportReader.exportedAs) covers plain bindings, not calls. Plain bindings (export default X, export { X }, { X as default }) are exactly what sync already tracks.
  • Main's first-export guess stays for a default the statement leaves unnamed (export default create()). fix(react): a JSX tag renders what the file imports under that name #2451 dropped the guess, and that was its topcoder loss: const reducer = require('…/meta'); reducer.factory() was right only through the guess.
  • A cast (export default LogBox as ILogBox) is still not read. That was fix(react): a JSX tag renders what the file imports under that name #2451's LogBox loss: 40 react-native calls moved from ILogBox.install to a let variable.
  • JSX is untouched. jsxChild reads modules through exportedComponent, and no synthesized edge (jsx-render or any other pass) changed in any A/B repo.

Validation

Tests. The regression test __tests__/import-forwarding.test.ts has 6 cases, and 5 fail on main. The sixth is a guard: createStore(reducer), and new Client() with .configure() chained on the next line, must not be read. The cases are:

  • a barrel forwarding imports under their own name and another, and through import * as;
  • an index forwarding a default, and { Marker as default } of an import;
  • a sync where the index changes the import it exports as its default, compared with a fresh index of the final tree;
  • new Logger() in two apps;
  • wrapper defaults and { createThing as default }.

The related suites pass: default-export-declaration, require-default, sync-default-export-change, sync-name-matched-imports, sync-jsx-import-forwarding.

A/B. Each repo got a fresh codegraph init -y with each arm's dist and kernel built from its own sources (main in a detached worktree at 553d5d1), dumped with scripts/dump-graph.mjs. Edges are paired by (source, kind, line, col, ref), or (source, via) for JSX:

repo retargeted added removed same target, now by import
proshop, next-saas, t3-turbo (controls), flask, gin (other languages) byte-identical
takenote, react-boilerplate, bulletproof-react, react.dev byte-identical
outline 448 348 0 516
react-native 71 7 0 4
excalidraw 4 2 0 35
mastodon 1 3 6 0
community-app (topcoder) 1 4 1 50
refine examples (281 apps) 0 21 0 23
redux-realworld 0 9 0 1

Triage. Every changed edge was checked against the source.

  • outline: server Logger.* 355 → server/logging/Logger.ts, all from server/ and plugins/*/server, none of which import the app logger. Presenters 72 → server/presenters/* through presenters/index.ts. accountProvisioner 21 → the wrapped function. Added edges cover presentPolicies → presentPolicy (214), the traceFunction commands (documentImporter, teamProvisioner, …), new Metrics(), HEADER_HEIGHT through components/Header.tsx, and observer(DocumentNew).
  • react-native: ReactNativeElement / ReadOnlyNode (71). Their module default is replaceConstructorWithoutSuper(X) as typeof X, and main had a first-export guess. Added edges cover 4 extends of those classes, and DeviceInfo.js / NativeExceptionsManager.js forwarding defaults.
  • excalidraw: index.tsx's import Footer from "./components/footer/FooterCenter"; export { Footer } now reaches FooterCenter, where main had the internal Footer. The same goes for LiveCollaborationTrigger and canvases/index.tsx.
  • mastodon, community-app, redux-realworld: route component={X} references now reach the component inside connect(…)(withRouter(X)), themr(…)(X) and the like.
  • refine: the finefoods apps' components/map/index.ts (import Map from './map'; … export { MapMarker, Map, AdvancedMarker }) and mern-dashboard-client's pages/index.ts now lead to their own app's files.
  • The 7 removed edges were all wrong. Six were name matches to a namesake in another folder (mastodon's ColumnSettings ×4 and UploadButton, community-app's JoinCommunity), where the import names a class default that a function_ref doesn't bind. One was mastodon's first-export guess (textForScreenReader for withOptionalRouter(injectIntl(Status))).
  • Unresolved refs. outline has 2 failed function_refs to the HEADER_HEIGHT constant that now park under the name instead of module:Header (importBindingTail: the module now provides the name). They are still failed, and no edge changes.

#2451's three loss patterns don't recur.

  • react-native has no removed edges, so LogBox and the JSX value defaults are unchanged.
  • community-app's require() member calls are unchanged.

Cost: none measurable. Interleaved init runs, alternating which arm goes first, medians: outline (5 main / 4 fix runs) total 15.61 s → 15.60 s, resolution phase 9.27 s → 9.37 s (main's own runs spread 9.17–9.50 s); react-native (3 / 3) total 45.98 s → 45.59 s, resolution 31.58 s → 30.59 s. The reading runs once per module (memoized per file); a forward costs one cached import-mapping lookup. One outline run aborted in the parse phase with libuv's UV_HANDLE_CLOSING assertion, the Windows Node abort of #2617, and was rerun.

Full suite: CODEGRAPH_KERNEL_EXPECT=1 npx vitest run --maxWorkers=4 --minWorkers=1 with the kernel built from this branch on Windows 11: test files 690 passed, 6 skipped, 0 failed (696); tests 8232 passed, 82 skipped, 0 failed (8314).

Not covered (follow-ups)

  • Sync, an existing gap this PR shares. When the module a barrel forwards from changes its default, or a barrel's named re-export changes, a sync keeps the old target where a fresh index has the new one. Main already does this for export … from re-exports. Probed sync against fresh on main:

    • export { default } from './a' with a's default moved: diverges.
    • export { default as named } from './a' → './b': diverges.
    • export { default as named } from './a' with a's default moved: diverges.

    With this PR the forwarded-import shapes behave the same way, except that a barrel changing the import it default-exports re-links correctly (that case is in the test). I'll take this up as a follow-up for both kinds of forwarding.

  • The JSX-only export default memo(function X() {…}). react.dev renders nothing there, on main and here (silent, not wrong).

🤖 Generated with Claude Code

…e or the first export

A module that exports an import of its own declares nothing under the
exported name: outline's `server/presenters/index.ts` is `import
presentUser from './user'; … export { presentUser, … }`, excalidraw's
`index.tsx` is `import Footer from "./components/footer/FooterCenter";
… export { Footer }`, and an `index.ts` beside a component is `import
Avatar from './Avatar'; export default Avatar`. findExportedSymbol found
no node there, so the import fell to a name match, which took any
namesake in the project. A default written as an expression had only the
first-exported-function guess behind it: `export default new Logger()`
sent outline's server logging calls to the browser app's Logger, and
`export default traceFunction({…})(accountProvisioner)` linked
`provisionFirstCollection`.

import-resolver.ts:
- statedDefaultExport also reads `new X()` (a class the file declares),
  what a wrapper call hands on (handedOn: a capitalized argument or the
  last of a curried chain, or a function written there, through nested
  wrappers; only a function, class or component of the file answers),
  and `export { X as default }`. A default naming a binding the file
  imports is that import, followed by esmDefaultExport with the walk's
  visited set and depth.
- A local export clause naming an import (`export { X }`, `export { X
  as Y }`, CommonJS `module.exports = { X }`) is followed too
  (forwardedExport; clauseImports is filled beside clauseAliases), in
  the named and the namespace-member branches.
- A default the statement leaves unnamed (`createStore(reducer)`) keeps
  the first-export guess, and a cast (`export default X as T`) is still
  not read.

Replaces #2451, whose JSX half #2563, #2558, #2738 and #2420 cover.

Regression test import-forwarding.test.ts: 6 cases, 5 fail on main (the
sixth guards `createStore(reducer)` and a call chained past `new X()`).
A/B on 16 repos, fresh init, each arm's kernel built from its own
sources: 9 byte-identical (5 controls); outline 448 retargeted, 348
added, 0 removed; react-native 71/7/0; excalidraw 4/2/0; mastodon
1/3/6; community-app 1/4/1; refine-examples 0/21/0; redux-realworld
0/9/0. Every changed edge triaged against the source.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@inth3shadows

Copy link
Copy Markdown
Contributor

Where the module is in the project, the new forwarding is right: on excalidraw (dd2f8fc32b92) it retargets or adds 7 edges, all correct, and removes none, and express, ky, got and codegraph's own source don't change. I found one new wrong edge, four sync cases where the synced graph differs from a fresh index, and two things to watch on the rebase.

Everything below was verified on head 4cd15ee9bf1f44ba331a8b69c4906f2aaafe2a62 against its merge base 553d5d101dd8c8ed65e83480e31192e836d8431a and against main 73c6cff66e525a92bff65675b6b0c46687e91ef1, CODEGRAPH_KERNEL=0, Node 22.

1. A factory called with a class is read as handing that class on.

// client.ts
class Config { get(k: string) { return k; } }
declare function makeClient(c: typeof Config): { get(k: string): Promise<string> };
export default makeClient(Config);
// use.ts
import client from './client';
export async function run4f() { return client.get('x'); }
  • Head (and head merged into main): run4f -> Config.get. Base and main: no edge.
  • client has the factory's return type, not Config's. The guard covers createStore(reducer) and createContext(DefaultTheme), but not a capitalized class argument, which is the shape of getRepository(User) or defineStore(Store).

2. After codegraph sync, these keep the old target; a fresh index of the same tree has the new one.

  • A barrel import presentUser from './user'; export { presentUser };, then user.ts moves its export default from userA to userB: sync keeps userA.
  • A barrel import { f } from './a'; export { f }; edited to import from ./b: sync keeps a.ts's f. Main already handles the export { f } from './a' form of this.
  • lib.ts changes export default new One() to export default new Two(): an importer's svc.ping() stays on One.ping.
  • Two hops (leaf.ts behind mid.ts's import leaf from './leaf'; export default leaf, then index.ts's export { m as thing }): leaf.ts switching its default keeps the old one.

The default-export reopen only looks at importers of the edited file and skips a barrel whose new default resolves nowhere; the named-forward case has no reopen pass.

3. On the rebase. Merging into main conflicts in CHANGELOG.md and seven hunks of import-resolver.ts. After resolving by hand, main's isStatedDefaultExport reads stated.id, which no longer compiles once StatedDefault can be { imported }. Two of main's assertions then need updating, both because the merged tree is now right: import-object-member-namesake.test.ts (export default memo(Card) now links Card) and import-forwarding.test.ts's Client:: case.

What holds. CommonJS destructured-require forwarding, aliased imports, default-plus-named and a local clause winning over export * resolve correctly; cycles end quietly; indexing time is unchanged on excalidraw.

Checked against the fixtures in graph-assay, which I maintain: the pr-2754 fixture and the pr-2800 fixture both read BROKEN on the merge base and on main, and FIXED on this head and on my hand merge into main. No other fixture verdict changed. Rerun: node bin/graph-assay replay <codegraph build>/dist/bin/codegraph.js pr-2754 pr-2800

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants