Skip to content
Merged
Show file tree
Hide file tree
Changes from 55 commits
Commits
Show all changes
56 commits
Select commit Hold shift + click to select a range
2b6a00d
fix: scope codegraph batch complexity targets to file paths
carlos-alm Jul 5, 2026
b28051a
fix: exclude parameters and interface/type members from dead-role cla…
carlos-alm Jul 5, 2026
17fbcba
fix: credit import-type usages as exports consumers
carlos-alm Jul 5, 2026
26918bb
fix: prevent fn-impact/query crash when -f/--file is passed
carlos-alm Jul 5, 2026
be6432c
fix: correct exported-symbol detection for literal and object-literal…
carlos-alm Jul 5, 2026
4ead840
fix: exclude primitive type keywords from ast --kind string matching
carlos-alm Jul 5, 2026
f6326bf
fix: resolve call edges through renamed import specifiers
carlos-alm Jul 5, 2026
590f560
fix: couple file_hashes updates with edge regeneration in incremental…
carlos-alm Jul 5, 2026
d3ea4a4
fix: compare signature-change diffs using new-file line ranges
carlos-alm Jul 5, 2026
c306812
feat: add environment doctor check for stale native binary and missin…
carlos-alm Jul 5, 2026
8bb5893
fix: eliminate non-deterministic ordering in community detection
carlos-alm Jul 6, 2026
46037b1
fix: sync update-graph.sh hook extension allowlist with EXTENSIONS
carlos-alm Jul 6, 2026
6a84cf9
fix: recompute directory structure metrics for affected directories o…
carlos-alm Jul 6, 2026
8d936d1
refactor: register hardcoded execFileSync/execSync maxBuffer values i…
carlos-alm Jul 6, 2026
11c84be
fix: gate blast-radius check on newly introduced risk, not pre-existi…
carlos-alm Jul 6, 2026
963301a
fix: gate identifier-argument dynamic call edges on callback-acceptin…
carlos-alm Jul 6, 2026
3e8035d
fix: gate Array.from's callback arg by position, not just callee name
carlos-alm Jul 6, 2026
879635e
fix: scope reexportedSymbols to actually-named re-export specifiers
carlos-alm Jul 6, 2026
0fe9fc3
fix: stop CFG block/edge count from overriding AST-derived cyclomatic…
carlos-alm Jul 6, 2026
ccf3c19
fix: backfill edges.technique for incrementally-inserted calls edges
carlos-alm Jul 6, 2026
d5b1162
fix: wrap remote embedding JSON parse failure in EngineError
carlos-alm Jul 6, 2026
8971017
refactor: extract shared platform-default-path helper in config.ts
carlos-alm Jul 6, 2026
056c5e4
refactor: decompose loadConfig and related high-effort functions in c…
carlos-alm Jul 6, 2026
0738171
refactor: decompose findDbPath and openRepo in db/connection.ts (docs…
carlos-alm Jul 6, 2026
6f2423c
refactor: dedupe busy/locked error detection into isBusyOrLockedError
carlos-alm Jul 6, 2026
4c02378
fix: log statSync failures in findDbPath instead of silently swallowi…
carlos-alm Jul 6, 2026
0698e16
test: add direct unit coverage for closeDbPair/closeDbPairDeferred/cl…
carlos-alm Jul 6, 2026
4ac3b99
fix: correct blast-radius/fn-impact computation for line-shifted decl…
carlos-alm Jul 6, 2026
6767f09
feat: wire points-to solver max-iterations cap through DEFAULTS.analy…
carlos-alm Jul 6, 2026
5f6f30a
refactor: route console.log calls in domain/search through logger
carlos-alm Jul 6, 2026
b479318
refactor: reduce cyclomatic complexity of computeDeltaModularityDirected
carlos-alm Jul 6, 2026
c39ac40
refactor: unify impact-level rendering format between audit and fn-im…
carlos-alm Jul 6, 2026
067674f
refactor: dedupe computeSavings via pct helper and persist partial to…
carlos-alm Jul 6, 2026
f6807b4
fix: add main.rs driver to rust dynamic tracer fixture
carlos-alm Jul 6, 2026
1c07a54
fix: scope diff file-header detection to between-hunk positions
carlos-alm Jul 6, 2026
bf82aa2
fix: update titan-grind's dead-symbol script for current roles --json…
carlos-alm Jul 6, 2026
cd02d27
fix: thread configured busyTimeoutMs through remaining read-only quer…
carlos-alm Jul 6, 2026
980b5dc
fix: resolve computed string-literal keys in object-literal extractio…
carlos-alm Jul 6, 2026
4a873a3
fix: add same-class bare-call fallback to incremental rebuild path (d…
carlos-alm Jul 6, 2026
8f3348a
fix: unify Object.defineProperty accessor fallback kind-filtering bet…
carlos-alm Jul 6, 2026
acf804c
refactor: share chunked statement-cache primitive between builder and…
carlos-alm Jul 6, 2026
986c851
refactor: cache prepared statements in applyEdgeTechniquesAfterNative…
carlos-alm Jul 6, 2026
71e9174
fix: replace fixed-depth directory-proximity check with symmetric dis…
carlos-alm Jul 6, 2026
d2935cc
refactor: remove unreachable Partition delta-computation interface me…
carlos-alm Jul 6, 2026
6515186
fix: emit reference edges for function identifiers used as object-lit…
carlos-alm Jul 6, 2026
30c491a
refactor: unify call-ref and tests rendering format between audit and…
carlos-alm Jul 6, 2026
9db911b
fix: classify destructured bindings as constant, not function (docs c…
carlos-alm Jul 6, 2026
70559fc
refactor: adopt timeMedian in remaining benchmark timing loops
carlos-alm Jul 6, 2026
822e0eb
refactor: decompose runPerfBenchmarks in token-benchmark.ts
carlos-alm Jul 6, 2026
fcdfe7d
fix: attribute liveness to Lua functions assigned to global/builtin i…
carlos-alm Jul 6, 2026
ee6362c
refactor: extract shared sedi() helper for tracer scripts
carlos-alm Jul 6, 2026
d4e6212
fix: restore reflection dynamicKind for .call/.apply/.bind (docs chec…
carlos-alm Jul 6, 2026
aec5d2b
fix: restrict entry-role classification to function/method-kind symbo…
carlos-alm Jul 6, 2026
d250f8d
fix: credit destructured dynamic import() bindings as exports consumers
carlos-alm Jul 6, 2026
82caa41
fix: resolve merge conflicts with main
carlos-alm Jul 8, 2026
ad1396e
fix: handle satisfies-cast dynamic imports, add WASM timeout (#1921)
carlos-alm Jul 8, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 60 additions & 4 deletions crates/codegraph-core/src/extractors/javascript.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3036,14 +3036,29 @@ fn find_parent_class_no_fn_boundary(node: &Node, source: &[u8]) -> Option<String
None
}

/// Wrapper node kinds that can sit between a dynamic `import()` call and its
/// enclosing `variable_declarator` without changing which value gets bound —
/// `await`, redundant parentheses, and TypeScript `as` casts. Real-world call
/// sites often combine several of these, e.g.
/// `const { X } = (await import('./mod.js')) as { X: Fn }` nests
/// await_expression → parenthesized_expression → as_expression before
/// reaching the declarator (#1781).
const DYNAMIC_IMPORT_WRAPPER_KINDS: &[&str] =
&["await_expression", "parenthesized_expression", "as_expression"];

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Same gap as the TypeScript engine: non_null_expression (tree-sitter TypeScript grammar node for the ! non-null assertion suffix) is absent from the wrapper-kinds slice. const { x } = (await import('./foo.js'))! inserts a non_null_expression above the parenthesized_expression, which stops the Rust walk-up before it reaches the variable_declarator.

Suggested change
const DYNAMIC_IMPORT_WRAPPER_KINDS: &[&str] =
&["await_expression", "parenthesized_expression", "as_expression"];
const DYNAMIC_IMPORT_WRAPPER_KINDS: &[&str] =
&["await_expression", "parenthesized_expression", "as_expression", "non_null_expression"];

Fix in Claude Code


/// Extract named bindings from a dynamic `import()` call expression.
/// Handles: `const { a, b } = await import(...)` and `const mod = await import(...)`
/// Handles: `const { a, b } = await import(...)`, `const mod = await import(...)`,
/// and casts/parens wrapping the awaited call, e.g.
/// `const { a } = (await import(...)) as { a: Fn }`.
fn extract_dynamic_import_names(call_node: &Node, source: &[u8]) -> Vec<String> {
// Walk up: call_expression → await_expression? → variable_declarator
// Walk up through any combination/nesting of await/parenthesized/as-cast
// wrappers to reach the variable_declarator.
let mut current = call_node.parent();
if let Some(parent) = current {
if parent.kind() == "await_expression" {
while let Some(parent) = current {
if DYNAMIC_IMPORT_WRAPPER_KINDS.contains(&parent.kind()) {
current = parent.parent();
} else {
break;
}
}
let declarator = match current {
Expand Down Expand Up @@ -4205,6 +4220,47 @@ mod tests {
assert!(!dyn_imports[0].names.contains(&"nested".to_string()));
}

// Regression tests for #1781: `codegraph exports` failed to credit consumers
// reached via `const { X } = (await import('./mod.js')) as {...}` — the
// walk-up from the import() call to its enclosing variable_declarator only
// skipped a single optional await_expression, so the extra
// parenthesized_expression / as_expression layers introduced by wrapping
// parens and a TS type-assertion caused name extraction to bail out with
// an empty list, exactly as if the destructured names couldn't be
// determined at all.

#[test]
fn finds_dynamic_import_with_parenthesized_destructuring() {
let s = parse_ts("const { a, b } = (await import('./foo.js'));");
let dyn_imports: Vec<_> = s.imports.iter().filter(|i| i.dynamic_import == Some(true)).collect();
assert_eq!(dyn_imports.len(), 1);
assert!(dyn_imports[0].names.contains(&"a".to_string()));
assert!(dyn_imports[0].names.contains(&"b".to_string()));
}

#[test]
fn finds_dynamic_import_with_as_cast_destructuring() {
let s = parse_ts("const { a, b } = await import('./foo.js') as { a: Fn; b: Fn };");
let dyn_imports: Vec<_> = s.imports.iter().filter(|i| i.dynamic_import == Some(true)).collect();
assert_eq!(dyn_imports.len(), 1);
assert!(dyn_imports[0].names.contains(&"a".to_string()));
assert!(dyn_imports[0].names.contains(&"b".to_string()));
}

#[test]
fn finds_dynamic_import_with_parenthesized_as_cast_destructuring() {
// Exact repro shape from #1781 (native-orchestrator.ts):
// `const { X, Y } = (await import('../mod.js')) as { X: Fn; Y: Fn };`
let s = parse_ts(
"const { buildDataflowVerticesFromMap, buildDataflowEdges } = (await import('../../../../features/dataflow.js')) as { buildDataflowVerticesFromMap: Fn; buildDataflowEdges: Fn };",
);
let dyn_imports: Vec<_> = s.imports.iter().filter(|i| i.dynamic_import == Some(true)).collect();
assert_eq!(dyn_imports.len(), 1);
assert_eq!(dyn_imports[0].source, "../../../../features/dataflow.js");
assert!(dyn_imports[0].names.contains(&"buildDataflowVerticesFromMap".to_string()));
assert!(dyn_imports[0].names.contains(&"buildDataflowEdges".to_string()));
}

#[test]
fn extracts_callback_reference_in_router_use() {
let s = parse_js("router.use(handleToken);");
Expand Down
33 changes: 26 additions & 7 deletions src/extractors/javascript.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4051,22 +4051,41 @@ function extractImportNames(
return names;
}

/**
* Wrapper node types that can sit between a dynamic `import()` call and its
* enclosing `variable_declarator` without changing which value gets bound —
* `await`, redundant parentheses, and TypeScript `as` casts. Real-world
* dynamic-import call sites often combine several of these, e.g.
* `const { X } = (await import('./mod.js')) as { X: Fn }` nests
* await_expression → parenthesized_expression → as_expression before
* reaching the declarator (#1781).
*/
const DYNAMIC_IMPORT_WRAPPER_TYPES = new Set([
'await_expression',
'parenthesized_expression',
'as_expression',
]);
Comment on lines +4065 to +4070

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 satisfies_expression not included in the wrapper set

TypeScript 4.9+ allows const { X } = (await import('./mod.js')) satisfies { X: Fn }. tree-sitter-typescript parses that as a satisfies_expression wrapper, which is not in DYNAMIC_IMPORT_WRAPPER_TYPES (or the Rust equivalent), so the walk-up would bail out and return [] — the same symptom as the bug being fixed. The pattern is rare in practice but structurally identical to the as_expression case already handled. Worth adding now that the set is being explicitly maintained.

Fix in Claude Code

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed — added satisfies_expression to the wrapper set in both engines (verified it's a real tree-sitter-typescript node type first), plus a regression test in each in ad1396ed.

Comment on lines +4065 to +4070

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 The TypeScript non-null assertion operator (!) produces a non_null_expression node in the tree-sitter TypeScript grammar, which sits between the innermost wrapper and the variable_declarator. Because non_null_expression is not in DYNAMIC_IMPORT_WRAPPER_TYPES, a declaration like const { x } = (await import('./foo.js'))! will still return [] — the walk stops at non_null_expression, fails the variable_declarator check, and the binding is silently dropped. Adding it to the set handles this at essentially no cost.

Suggested change
const DYNAMIC_IMPORT_WRAPPER_TYPES = new Set([
'await_expression',
'parenthesized_expression',
'as_expression',
]);
const DYNAMIC_IMPORT_WRAPPER_TYPES = new Set([
'await_expression',
'parenthesized_expression',
'as_expression',
'non_null_expression',
]);

Fix in Claude Code


/**
* Extract destructured names from a dynamic import() call expression.
*
* Handles:
* const { a, b } = await import('./foo.js') → ['a', 'b']
* const mod = await import('./foo.js') → ['mod']
* import('./foo.js') → [] (no names extractable)
* const { a, b } = await import('./foo.js') → ['a', 'b']
* const mod = await import('./foo.js') → ['mod']
* const { a } = (await import('./foo.js')) as { a: Fn } → ['a']
* import('./foo.js') → [] (no names extractable)
*
* Walks up the AST from the call_expression to find the enclosing
* Walks up the AST from the call_expression — through any nesting of
* await/parenthesized/as-cast wrappers — to find the enclosing
* variable_declarator and reads the name/object_pattern.
*/
function extractDynamicImportNames(callNode: TreeSitterNode): string[] {
// Walk up: call_expression → await_expression → variable_declarator
// Walk up through await_expression / parenthesized_expression / as_expression
// wrappers, in any combination or order, to reach the variable_declarator.
let current = callNode.parent;
// Skip await_expression wrapper if present
if (current && current.type === 'await_expression') current = current.parent;
while (current && DYNAMIC_IMPORT_WRAPPER_TYPES.has(current.type)) {
current = current.parent;
}
// We should now be at a variable_declarator (or not, if standalone import())
if (current?.type !== 'variable_declarator') return [];

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,257 @@
/**
* Integration test for #1781: `codegraph exports` did not credit consumers
* reached via a dynamic `import()` expression whose destructured result is
* wrapped in redundant parentheses and/or a TypeScript `as {...}` type
* assertion — the exact shape used throughout
* `src/domain/graph/builder/stages/native-orchestrator.ts`:
*
* const { buildDataflowVerticesFromMap, ... } =
* (await import('../../../../features/dataflow.js')) as {...};
*
* Root cause: `extractDynamicImportNames` (TS) / `extract_dynamic_import_names`
* (Rust) walked up from the `import()` call through at most one optional
* `await_expression` before requiring the immediate parent to be a
* `variable_declarator`. The extra `parenthesized_expression` and/or
* `as_expression` wrapper layers introduced by parens and a type assertion
* broke that walk-up, so no destructured names were ever extracted — the
* import was recorded with `names: []`, `importedNames` never gained an
* entry for the destructured bindings, and the later call through the
* destructured local name never resolved to a `calls` edge. Both `codegraph
* exports` (consumer count) and `codegraph roles --role dead` therefore
* treated a genuinely-consumed export as unreferenced.
*
* Fix: the walk-up now skips any nesting/combination of `await_expression`,
* `parenthesized_expression`, and `as_expression` wrappers before checking
* for the enclosing `variable_declarator`, in both engines.
*
* Two consumer shapes are exercised against the same target module:
* - `usesPlain`: bare `const { X } = await import(...)` (no cast) — the
* pre-existing baseline that must keep working.
* - `usesCast`: `const { Y } = (await import(...)) as {...}` — the exact
* regression shape from native-orchestrator.ts.
*
* The target module and its consumer are deliberately placed in *different*
* directories (`features/` vs `domain/stages/`, mirroring the real repo
* layout) rather than side by side. A same-directory fixture does not
* discriminate this bug at all: the resolver's directory-scoped fallback
* tier (a same-directory, name-only match — one of several confidence tiers
* below the import-aware match) coincidentally "rescues" the call even when
* `extractDynamicImportNames` returns no names, producing a `calls` edge
* regardless of whether the fix is present. Cross-directory placement is
* required so the only way to resolve `usesCast`'s call is through the
* import-aware path this bug actually breaks.
*/

import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import Database from 'better-sqlite3';
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
import { buildGraph } from '../../src/domain/graph/builder.js';
import { exportsData } from '../../src/domain/queries.js';
import { isNativeAvailable } from '../../src/infrastructure/native.js';

const DEAD_ROLES = new Set(['dead-unresolved', 'dead-leaf', 'dead-entry', 'dead-ffi']);

const TARGET_FILE = 'features/dataflow.ts';

const FIXTURE = {
[TARGET_FILE]: `
export function buildDataflowVerticesFromMap(): number {
return 42;
}

export function buildDataflowP4ForNative(): number {
return 7;
}
`,
'domain/stages/consumer.ts': `
export async function usesPlain() {
const { buildDataflowVerticesFromMap } = await import('../../features/dataflow.js');
return buildDataflowVerticesFromMap();
}

export async function usesCast() {
const { buildDataflowP4ForNative } = (await import('../../features/dataflow.js')) as {
buildDataflowP4ForNative: () => number;
};
return buildDataflowP4ForNative();
}
`,
};

function readNodesWithRoles(dbPath: string) {
const db = new Database(dbPath, { readonly: true });
try {
return db.prepare('SELECT name, kind, role FROM nodes ORDER BY name').all() as Array<{
name: string;
kind: string;
role: string | null;
}>;
} finally {
db.close();
}
}

function getCallEdges(dbPath: string) {
const db = new Database(dbPath, { readonly: true });
try {
return db
.prepare(
`SELECT n1.name AS src, n2.name AS tgt, n2.file AS tgt_file
FROM edges e
JOIN nodes n1 ON e.source_id = n1.id
JOIN nodes n2 ON e.target_id = n2.id
WHERE e.kind = 'calls'
ORDER BY n1.name, n2.name`,
)
.all() as Array<{ src: string; tgt: string; tgt_file: string }>;
} finally {
db.close();
}
}

function writeFixture(rootDir: string) {
Comment on lines +107 to +114

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 WASM beforeAll has no explicit timeout

The native suite's beforeAll opts in to a 60-second timeout (}, 60_000), but the WASM beforeAll relies on vitest's default (5 seconds). If WASM initialisation plus two buildGraph calls ever run long on a slow CI machine, the whole WASM describe block will time out while the native one would not. Consider adding a matching explicit timeout for consistency (the exact value can be smaller than 60 s if WASM is consistently faster).

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!

Fix in Claude Code

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed — added a matching 60s timeout to the WASM beforeAll in ad1396ed.

for (const [rel, content] of Object.entries(FIXTURE)) {
const abs = path.join(rootDir, rel);
fs.mkdirSync(path.dirname(abs), { recursive: true });
fs.writeFileSync(abs, content);
}
}

describe('dynamic import() + destructure consumer crediting (#1781) — WASM', () => {
let tmpDir: string;

beforeAll(async () => {
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-1781-wasm-'));
writeFixture(tmpDir);
await buildGraph(tmpDir, { engine: 'wasm', incremental: false, skipRegistry: true });
});

afterAll(() => {
fs.rmSync(tmpDir, { recursive: true, force: true });
});

it('creates a calls edge for the bare (uncast) destructured binding', () => {
const dbPath = path.join(tmpDir, '.codegraph', 'graph.db');
const edges = getCallEdges(dbPath);
const edge = edges.find(
(e) => e.src === 'usesPlain' && e.tgt === 'buildDataflowVerticesFromMap',
);
expect(
edge,
`Expected usesPlain -> buildDataflowVerticesFromMap; got: ${JSON.stringify(edges)}`,
).toBeDefined();
expect(edge?.tgt_file).toBe(TARGET_FILE);
});

it('creates a calls edge for the parenthesized + `as`-cast destructured binding', () => {
const dbPath = path.join(tmpDir, '.codegraph', 'graph.db');
const edges = getCallEdges(dbPath);
const edge = edges.find((e) => e.src === 'usesCast' && e.tgt === 'buildDataflowP4ForNative');
expect(
edge,
`Expected usesCast -> buildDataflowP4ForNative; got: ${JSON.stringify(edges)}`,
).toBeDefined();
expect(edge?.tgt_file).toBe(TARGET_FILE);
});

it('codegraph exports credits both dynamically-imported functions with real consumers', () => {
const dbPath = path.join(tmpDir, '.codegraph', 'graph.db');
const data = exportsData(TARGET_FILE, dbPath);

const vertices = data.results.find(
(r: { name: string }) => r.name === 'buildDataflowVerticesFromMap',
);
expect(vertices).toBeDefined();
expect(vertices.consumerCount).toBeGreaterThanOrEqual(1);
expect(vertices.consumers.map((c: { name: string }) => c.name)).toContain('usesPlain');

const p4 = data.results.find((r: { name: string }) => r.name === 'buildDataflowP4ForNative');
expect(p4).toBeDefined();
expect(p4.consumerCount).toBeGreaterThanOrEqual(1);
expect(p4.consumers.map((c: { name: string }) => c.name)).toContain('usesCast');
});

it('does not classify either dynamically-imported export as dead', () => {
const dbPath = path.join(tmpDir, '.codegraph', 'graph.db');
const nodes = readNodesWithRoles(dbPath);
for (const name of ['buildDataflowVerticesFromMap', 'buildDataflowP4ForNative']) {
const node = nodes.find((n) => n.name === name && n.kind === 'function');
expect(node, `${name} node not found`).toBeDefined();
expect(
DEAD_ROLES.has(node!.role ?? ''),
`${name} was classified as ${node!.role} — expected a non-dead role now that a real edge exists`,
).toBe(false);
}
});
});

// ── Native engine parity ────────────────────────────────────────────────────
// Skipped when the native addon is not installed.

describe.skipIf(!isNativeAvailable())(
'dynamic import() + destructure consumer crediting (#1781) — native',
() => {
let nativeTmpDir: string;

beforeAll(async () => {
nativeTmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-1781-native-'));
writeFixture(nativeTmpDir);
await buildGraph(nativeTmpDir, { engine: 'native', incremental: false, skipRegistry: true });
}, 60_000);

afterAll(() => {
fs.rmSync(nativeTmpDir, { recursive: true, force: true });
});

it('creates a calls edge for the bare (uncast) destructured binding', () => {
const dbPath = path.join(nativeTmpDir, '.codegraph', 'graph.db');
const edges = getCallEdges(dbPath);
const edge = edges.find(
(e) => e.src === 'usesPlain' && e.tgt === 'buildDataflowVerticesFromMap',
);
expect(
edge,
`Expected native usesPlain -> buildDataflowVerticesFromMap; got: ${JSON.stringify(edges)}`,
).toBeDefined();
expect(edge?.tgt_file).toBe(TARGET_FILE);
});

it('creates a calls edge for the parenthesized + `as`-cast destructured binding', () => {
const dbPath = path.join(nativeTmpDir, '.codegraph', 'graph.db');
const edges = getCallEdges(dbPath);
const edge = edges.find((e) => e.src === 'usesCast' && e.tgt === 'buildDataflowP4ForNative');
expect(
edge,
`Expected native usesCast -> buildDataflowP4ForNative; got: ${JSON.stringify(edges)}`,
).toBeDefined();
expect(edge?.tgt_file).toBe(TARGET_FILE);
});

it('codegraph exports credits both dynamically-imported functions with real consumers', () => {
const dbPath = path.join(nativeTmpDir, '.codegraph', 'graph.db');
const data = exportsData(TARGET_FILE, dbPath);

const vertices = data.results.find(
(r: { name: string }) => r.name === 'buildDataflowVerticesFromMap',
);
expect(vertices).toBeDefined();
expect(vertices.consumerCount).toBeGreaterThanOrEqual(1);

const p4 = data.results.find((r: { name: string }) => r.name === 'buildDataflowP4ForNative');
expect(p4).toBeDefined();
expect(p4.consumerCount).toBeGreaterThanOrEqual(1);
});

it('does not classify either dynamically-imported export as dead', () => {
const dbPath = path.join(nativeTmpDir, '.codegraph', 'graph.db');
const nodes = readNodesWithRoles(dbPath);
for (const name of ['buildDataflowVerticesFromMap', 'buildDataflowP4ForNative']) {
const node = nodes.find((n) => n.name === name && n.kind === 'function');
expect(node, `${name} node not found (native)`).toBeDefined();
expect(DEAD_ROLES.has(node!.role ?? '')).toBe(false);
}
});
},
);
Loading
Loading