devlensio 1.1.1 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/dist/graph/buildLookup.d.ts +30 -0
  2. package/dist/graph/buildLookup.js +36 -1
  3. package/dist/graph/edges/aliasChain.d.ts +7 -0
  4. package/dist/graph/edges/aliasChain.js +63 -0
  5. package/dist/graph/edges/aliasResolution.test.d.ts +1 -0
  6. package/dist/graph/edges/aliasResolution.test.js +351 -0
  7. package/dist/graph/edges/callEdges.js +178 -18
  8. package/dist/graph/edges/callEdges.test.js +119 -0
  9. package/dist/graph/edges/callOrder.test.d.ts +1 -0
  10. package/dist/graph/edges/callOrder.test.js +227 -0
  11. package/dist/graph/edges/importEdges.js +124 -0
  12. package/dist/graph/edges/propEdges.js +6 -1
  13. package/dist/index.d.ts +1 -0
  14. package/dist/index.js +1 -0
  15. package/dist/parser/callFlow.d.ts +15 -0
  16. package/dist/parser/callFlow.js +302 -0
  17. package/dist/parser/callOrder.test.d.ts +1 -0
  18. package/dist/parser/callOrder.test.js +407 -0
  19. package/dist/parser/declarationIds.d.ts +23 -0
  20. package/dist/parser/declarationIds.js +123 -0
  21. package/dist/parser/exportsMap.js +1 -90
  22. package/dist/parser/extractors/components.js +18 -28
  23. package/dist/parser/extractors/functions.d.ts +21 -1
  24. package/dist/parser/extractors/functions.js +92 -60
  25. package/dist/parser/extractors/moduleScope.d.ts +8 -0
  26. package/dist/parser/extractors/moduleScope.js +80 -0
  27. package/dist/parser/index.js +12 -0
  28. package/dist/parser/moduleScope.test.d.ts +1 -0
  29. package/dist/parser/moduleScope.test.js +176 -0
  30. package/dist/summarizer/index.js +53 -4
  31. package/dist/summarizer/prompts.js +111 -50
  32. package/dist/summarizer/prompts.test.d.ts +1 -0
  33. package/dist/summarizer/prompts.test.js +112 -0
  34. package/dist/types.d.ts +63 -0
  35. package/dist/version.d.ts +1 -0
  36. package/dist/version.js +2 -0
  37. package/extractors/go/bin/darwin-amd64/devlens_go_extractor +0 -0
  38. package/extractors/go/bin/darwin-arm64/devlens_go_extractor +0 -0
  39. package/extractors/go/bin/linux-amd64/devlens_go_extractor +0 -0
  40. package/extractors/go/bin/linux-arm64/devlens_go_extractor +0 -0
  41. package/extractors/go/bin/windows-amd64/devlens_go_extractor.exe +0 -0
  42. package/extractors/go/calls.go +131 -10
  43. package/extractors/go/nodes.go +29 -11
  44. package/extractors/go/parser.go +376 -41
  45. package/extractors/java/devlens_java_extractor.jar +0 -0
  46. package/extractors/java/src/devlens/extractor/Extractor.java +52 -12
  47. package/extractors/java/src/devlens/extractor/LookupMaps.java +2 -0
  48. package/extractors/java/src/devlens/extractor/Parser.java +420 -1
  49. package/extractors/java/src/devlens/extractor/edges/Calls.java +105 -5
  50. package/extractors/python/devlens_extractors_python/edges/calls.py +199 -36
  51. package/extractors/python/devlens_extractors_python/edges/imports.py +21 -1
  52. package/extractors/python/devlens_extractors_python/lookup.py +9 -0
  53. package/extractors/python/devlens_extractors_python/parser/__init__.py +11 -1
  54. package/extractors/python/devlens_extractors_python/parser/functions.py +199 -42
  55. package/extractors/rust/bin/darwin-amd64/devlens_rust_extractor +0 -0
  56. package/extractors/rust/bin/darwin-arm64/devlens_rust_extractor +0 -0
  57. package/extractors/rust/bin/linux-amd64/devlens_rust_extractor +0 -0
  58. package/extractors/rust/bin/linux-arm64/devlens_rust_extractor +0 -0
  59. package/extractors/rust/bin/windows-amd64/devlens_rust_extractor.exe +0 -0
  60. package/extractors/rust/src/calls.rs +114 -8
  61. package/extractors/rust/src/lookup.rs +66 -0
  62. package/extractors/rust/src/nodes.rs +29 -0
  63. package/extractors/rust/src/parser.rs +362 -27
  64. package/package.json +77 -73
@@ -1,4 +1,5 @@
1
1
  import { closestByPath } from "./utils.js";
2
+ import { buildAliasChain } from "./aliasChain.js";
2
3
  // Arity compatibility: a candidate matches when the call provides at least all
3
4
  // required (non-optional, non-rest) params, and does not exceed the declared
4
5
  // count unless the candidate declares a rest parameter. Candidates without
@@ -86,14 +87,28 @@ export function detectCallEdges(nodes, lookupMp) {
86
87
  const createdLocalEdges = new Set();
87
88
  // Accumulate resolved calls per node — written back to metadata after edge loop
88
89
  const resolvedCallsMap = new Map();
90
+ // Every ordinal that resolved to one (caller, target, type) key. The edge
91
+ // mirror is optional export data; consumers read resolvedCalls instead.
92
+ // Every ordinal that resolved to one (caller, target), so the NODE can carry
93
+ // the repeat positions itself (resolvedCalls[].orders).
94
+ const resolvedOrders = new Map();
89
95
  // Lazily-created method nodes for default/namespace import member-access calls
90
96
  const createdMethodNodes = new Map();
97
+ // id → node, for turning resolved export bindings back into candidates
98
+ const nodesById = new Map();
99
+ for (const n of nodes)
100
+ nodesById.set(n.id, n);
101
+ // memoized alias chains (provenance only; see aliasChain.ts)
102
+ const aliasChainCache = new Map();
91
103
  for (const node of nodes) {
92
- // Only functions, hooks, components, and class methods make direct calls
104
+ // FILE is a caller for module-scope execution (calls executed at file
105
+ // load, attached by parser/extractors/moduleScope.ts). TEST/STORY are
106
+ // leaves and deliberately excluded.
93
107
  if (node.type !== "FUNCTION" &&
94
108
  node.type !== "HOOK" &&
95
109
  node.type !== "COMPONENT" &&
96
- node.type !== "METHOD")
110
+ node.type !== "METHOD" &&
111
+ node.type !== "FILE")
97
112
  continue;
98
113
  const calls = node.metadata.calls;
99
114
  const uses = node.metadata.uses;
@@ -124,6 +139,9 @@ export function detectCallEdges(nodes, lookupMp) {
124
139
  ? callSites
125
140
  : (primaryNames ?? []).map((name) => ({ name, argCount: -1 }));
126
141
  for (const callSite of primaryCallSites) {
142
+ // Hooks are ordered too, but hookEdges.ts owns their edges.
143
+ if (callSite.kind === "hook")
144
+ continue;
127
145
  const calledName = callSite.name;
128
146
  // ── Third-party guard ─────────────────────────────────────────
129
147
  // The alias map is keyed by node.filePath (relative) and populated
@@ -168,13 +186,46 @@ export function detectCallEdges(nodes, lookupMp) {
168
186
  tpNodeId = methodNodeId;
169
187
  }
170
188
  const edgeKey = `${node.id}→${tpNodeId}:CALLS`;
189
+ if (callSite.order !== undefined) {
190
+ // Third-party targets are nodes too, so their ordinal lives in
191
+ // resolvedCalls like any other callee (no edge mirror).
192
+ let perTarget = resolvedOrders.get(node.id);
193
+ if (!perTarget) {
194
+ perTarget = new Map();
195
+ resolvedOrders.set(node.id, perTarget);
196
+ }
197
+ const list = perTarget.get(tpNodeId);
198
+ if (list)
199
+ list.push(callSite.order);
200
+ else
201
+ perTarget.set(tpNodeId, [callSite.order]);
202
+ let entries = resolvedCallsMap.get(node.id);
203
+ if (!entries) {
204
+ entries = [];
205
+ resolvedCallsMap.set(node.id, entries);
206
+ }
207
+ if (!entries.some((e) => e.nodeId === tpNodeId)) {
208
+ entries.push({
209
+ name: createdMethodNodes.get(tpNodeId)?.name
210
+ ?? nodesById.get(tpNodeId)?.name
211
+ ?? calledName,
212
+ nodeId: tpNodeId,
213
+ firstOrder: callSite.order,
214
+ line: callSite.line,
215
+ });
216
+ }
217
+ }
171
218
  if (!createdThirdPartyEdges.has(edgeKey)) {
172
219
  createdThirdPartyEdges.add(edgeKey);
173
220
  edges.push({
174
221
  from: node.id,
175
222
  to: tpNodeId,
176
223
  type: "CALLS",
177
- metadata: { calledName, isThirdParty: true },
224
+ metadata: {
225
+ calledName,
226
+ isThirdParty: true,
227
+ ...(node.type === "FILE" ? { scope: "module" } : {}),
228
+ },
178
229
  });
179
230
  }
180
231
  continue;
@@ -194,18 +245,66 @@ export function detectCallEdges(nodes, lookupMp) {
194
245
  // continue;
195
246
  // }
196
247
  // ── Local node lookup ─────────────────────────────────────────
197
- // Direct name match first; if it misses, try substituting the
198
- // root through the local-import alias map (`US.get()` where
199
- // `import { UserService as US }` → resolve `UserService.get`).
200
- let targets = lookupMp.nodesByName.get(calledName);
248
+ // Tier 2 — module-scoped (binding-aware). The import resolved to a
249
+ // file, and that file's export table already points at the ORIGIN
250
+ // declaration: TypeScript's checker followed every `export … from`,
251
+ // `export *` and `export { a as b }` when the table was built. Two
252
+ // map reads, independent of chain depth.
253
+ let targets;
201
254
  let resolvedName = calledName;
202
- if ((!targets || targets.length === 0) && calledName.includes(".")) {
203
- const rootName = calledName.split(".")[0];
204
- const fileAliases = lookupMp.localImportSymbols.get(node.filePath);
205
- const importedName = fileAliases?.get(rootName);
206
- if (importedName) {
207
- resolvedName = importedName + calledName.slice(rootName.length);
208
- targets = lookupMp.nodesByName.get(resolvedName);
255
+ let aliasChain;
256
+ const rootName = calledName.split(".")[0];
257
+ const importTarget = lookupMp.importTargets.get(node.filePath)?.get(rootName);
258
+ if (importTarget) {
259
+ const suffix = calledName.slice(rootName.length); // "" or ".get"
260
+ let exportName = importTarget.importedName;
261
+ let memberSuffix = suffix;
262
+ if (importTarget.kind === "namespace") {
263
+ // `import * as ns` + `ns.member()` → the member is the export
264
+ const member = suffix.startsWith(".") ? suffix.slice(1) : "";
265
+ exportName = member.split(".")[0];
266
+ memberSuffix = member.slice(exportName.length);
267
+ }
268
+ if (exportName) {
269
+ const ids = lookupMp.exportBindings.get(importTarget.targetFile)?.get(exportName);
270
+ if (ids && ids.length > 0) {
271
+ if (memberSuffix) {
272
+ // Member access on an imported class/object: nodes are
273
+ // dotted (`file::Class.method`). Accept only ids that
274
+ // exist — never invent an edge to the container.
275
+ const memberIds = ids
276
+ .map((id) => `${id}${memberSuffix}`)
277
+ .filter((id) => lookupMp.nodeIds.has(id));
278
+ targets = memberIds
279
+ .map((id) => nodesById.get(id))
280
+ .filter((n) => !!n);
281
+ }
282
+ else {
283
+ targets = ids
284
+ .map((id) => nodesById.get(id))
285
+ .filter((n) => !!n);
286
+ }
287
+ if (targets.length > 0) {
288
+ aliasChain = buildAliasChain(lookupMp, importTarget, aliasChainCache);
289
+ }
290
+ }
291
+ }
292
+ }
293
+ // Tier 3 — legacy name-based fallback (unchanged behaviour): direct
294
+ // name match, then the one-hop local alias substitution. Keeps repos
295
+ // where module resolution fails (no config, exotic layouts) exactly
296
+ // as they were.
297
+ if (!targets || targets.length === 0) {
298
+ resolvedName = calledName;
299
+ targets = lookupMp.nodesByName.get(calledName);
300
+ if (!targets || targets.length === 0) {
301
+ const importedName = lookupMp.localImportSymbols.get(node.filePath)?.get(rootName);
302
+ if (importedName) {
303
+ resolvedName = calledName.includes(".")
304
+ ? importedName + calledName.slice(rootName.length)
305
+ : importedName;
306
+ targets = lookupMp.nodesByName.get(resolvedName);
307
+ }
209
308
  }
210
309
  }
211
310
  if (!targets || targets.length === 0)
@@ -213,7 +312,32 @@ export function detectCallEdges(nodes, lookupMp) {
213
312
  const { target, matchedBy } = resolveOverloadTarget(targets, node, callSite.argCount >= 0 ? callSite : undefined);
214
313
  if (target.id === node.id)
215
314
  continue; // skip self-reference
315
+ // The origin symbol's own name — for an aliased call this differs
316
+ // from what the caller wrote (`httpResponse` → `data`).
317
+ resolvedName = target.name;
318
+ // A chain that ends inside a module (local `export { a as b }`) gets
319
+ // the origin file appended, so every chain ends at the node the edge
320
+ // points to. Skipped when the last hop already *is* that id (or its
321
+ // overload base, e.g. `fmt::fmt` vs `fmt::fmt#1`).
322
+ if (aliasChain && aliasChain.length > 0) {
323
+ const last = aliasChain[aliasChain.length - 1];
324
+ if (last !== target.id && !target.id.startsWith(last)) {
325
+ aliasChain = [...aliasChain, target.id];
326
+ }
327
+ }
216
328
  const localEdgeKey = `${node.id}→${target.id}:${edgeType}`;
329
+ if (callSite.order !== undefined) {
330
+ let perTarget = resolvedOrders.get(node.id);
331
+ if (!perTarget) {
332
+ perTarget = new Map();
333
+ resolvedOrders.set(node.id, perTarget);
334
+ }
335
+ const list = perTarget.get(target.id);
336
+ if (list)
337
+ list.push(callSite.order);
338
+ else
339
+ perTarget.set(target.id, [callSite.order]);
340
+ }
217
341
  if (createdLocalEdges.has(localEdgeKey))
218
342
  continue;
219
343
  createdLocalEdges.add(localEdgeKey);
@@ -221,13 +345,35 @@ export function detectCallEdges(nodes, lookupMp) {
221
345
  from: node.id,
222
346
  to: target.id,
223
347
  type: edgeType,
224
- metadata: { calledName: resolvedName, matchedBy },
348
+ metadata: {
349
+ // as written at the call site
350
+ calledName,
351
+ // the declaration the graph edge actually points at
352
+ resolvedName,
353
+ // true when the name was aliased (import alias, re-export, …)
354
+ ...(calledName !== target.name ? { aliased: true } : {}),
355
+ // provenance for the UI — only when a re-export chain exists
356
+ ...(aliasChain ? { aliasChain } : {}),
357
+ matchedBy,
358
+ ...(node.type === "FILE" ? { scope: "module" } : {}),
359
+ },
225
360
  });
226
361
  if (!resolvedCallsMap.has(node.id))
227
362
  resolvedCallsMap.set(node.id, []);
228
363
  const existing = resolvedCallsMap.get(node.id);
229
364
  if (!existing.some(r => r.nodeId === target.id)) {
230
- existing.push({ name: resolvedName, nodeId: target.id });
365
+ existing.push({
366
+ name: resolvedName,
367
+ nodeId: target.id,
368
+ ...(callSite.order !== undefined && { firstOrder: callSite.order }),
369
+ ...(callSite.line !== undefined && { line: callSite.line }),
370
+ ...(callSite.defer && { defer: callSite.defer }),
371
+ ...(callSite.deferDetail && { deferDetail: callSite.deferDetail }),
372
+ ...(callSite.awaited && { awaited: true }),
373
+ ...(callSite.conc && { conc: true }),
374
+ ...(callSite.repeat && { repeat: true }),
375
+ ...(callSite.maybe && { maybe: true }),
376
+ });
231
377
  }
232
378
  }
233
379
  // ── Hook / dependency names: third-party edges only ──────────────
@@ -253,9 +399,23 @@ export function detectCallEdges(nodes, lookupMp) {
253
399
  }
254
400
  }
255
401
  }
256
- // Write resolved calls back onto nodes
402
+ // Write resolved calls back onto nodes. `orders` carries every position that
403
+ // reached a target (only when more than one). Ordering is node metadata only:
404
+ // edges describe structure, never sequence (docs/CALL_ORDER.md §3.2).
257
405
  for (const node of nodes) {
258
- node.metadata.resolvedCalls = resolvedCallsMap.get(node.id) ?? [];
406
+ const entries = resolvedCallsMap.get(node.id) ?? [];
407
+ const perTarget = resolvedOrders.get(node.id);
408
+ if (perTarget) {
409
+ for (const entry of entries) {
410
+ const list = perTarget.get(entry.nodeId);
411
+ if (!list)
412
+ continue;
413
+ const unique = [...new Set(list)].sort((a, b) => a - b);
414
+ if (unique.length > 1)
415
+ entry.orders = unique;
416
+ }
417
+ }
418
+ node.metadata.resolvedCalls = entries;
259
419
  }
260
420
  return { edges, newThirdPartyNodes: [...createdMethodNodes.values()] };
261
421
  }
@@ -352,3 +352,122 @@ describe("detectCallEdges with overloads", () => {
352
352
  deleteFakeRepo(repo);
353
353
  });
354
354
  });
355
+ // ─── Module-scope callers (FILE nodes) ────────────────────────────────────────
356
+ //
357
+ // Calls executed at file load are owned by the FILE node (moduleScope.ts).
358
+ // They must produce normal CALLS edges — no new edge type — with
359
+ // metadata.scope = "module" so consumers can label them.
360
+ describe("detectCallEdges with module-scope callers", () => {
361
+ it("emits FILE -> FUNCTION CALLS from a top-level call", () => {
362
+ const repo = createFakeRepo({
363
+ "lib/startAll.ts": `export function startAll() { return () => {}; }`,
364
+ "main.ts": `
365
+ import { startAll } from "./lib/startAll";
366
+ const cleanup = startAll();
367
+ process.on("SIGTERM", cleanup);
368
+ `,
369
+ });
370
+ const { edges, all } = detectCalls(repo);
371
+ expect(edges).toContainEqual(expect.objectContaining({
372
+ from: "file::main.ts",
373
+ to: "lib/startAll.ts::startAll",
374
+ type: "CALLS",
375
+ metadata: expect.objectContaining({ calledName: "startAll", scope: "module" }),
376
+ }));
377
+ const file = all.find((n) => n.id === "file::main.ts");
378
+ expect(file.metadata.resolvedCalls).toEqual([
379
+ expect.objectContaining({ name: "startAll", nodeId: "lib/startAll.ts::startAll", firstOrder: 1 }),
380
+ ]);
381
+ deleteFakeRepo(repo);
382
+ });
383
+ it("resolves module-scope calls through a local import alias", () => {
384
+ const repo = createFakeRepo({
385
+ "lib/startAll.ts": `export function startAll() { return 1; }`,
386
+ "main.ts": `
387
+ import { startAll as boot } from "./lib/startAll";
388
+ boot();
389
+ `,
390
+ });
391
+ const { edges } = detectCalls(repo);
392
+ expect(edges).toContainEqual(expect.objectContaining({
393
+ from: "file::main.ts",
394
+ to: "lib/startAll.ts::startAll",
395
+ type: "CALLS",
396
+ // calledName is the text at the call site; resolvedName is the origin
397
+ // symbol the edge points at (they differ for aliased imports).
398
+ metadata: expect.objectContaining({
399
+ calledName: "boot",
400
+ resolvedName: "startAll",
401
+ aliased: true,
402
+ }),
403
+ }));
404
+ deleteFakeRepo(repo);
405
+ });
406
+ it("does not tag function-origin calls with scope=module", () => {
407
+ const repo = createFakeRepo({
408
+ "src/a.ts": `
409
+ export function helper() { return 1; }
410
+ export function caller() { return helper(); }
411
+ `,
412
+ });
413
+ const { edges } = detectCalls(repo);
414
+ const edge = edges.find((e) => e.from === "src/a.ts::caller" && e.to === "src/a.ts::helper");
415
+ expect(edge).toBeDefined();
416
+ expect(edge.metadata?.scope).toBeUndefined();
417
+ deleteFakeRepo(repo);
418
+ });
419
+ it("keeps module scope separate from a same-file function call", () => {
420
+ const repo = createFakeRepo({
421
+ "src/boot.ts": `
422
+ export function helper() { return 1; }
423
+ const sentinel = helper();
424
+ export function caller() { return helper(); }
425
+ `,
426
+ });
427
+ const { edges } = detectCalls(repo);
428
+ const fromFile = edges.filter((e) => e.from === "file::src/boot.ts");
429
+ const fromFn = edges.filter((e) => e.from === "src/boot.ts::caller");
430
+ expect(fromFile).toHaveLength(1);
431
+ expect(fromFile[0].to).toBe("src/boot.ts::helper");
432
+ expect(fromFile[0].metadata?.scope).toBe("module");
433
+ expect(fromFn).toHaveLength(1);
434
+ expect(fromFn[0].metadata?.scope).toBeUndefined();
435
+ deleteFakeRepo(repo);
436
+ });
437
+ });
438
+ // ─── Third-party gate (must be identical to function callers) ────────────────
439
+ describe("detectCallEdges — module-scope third-party gate", () => {
440
+ const files = {
441
+ "package.json": JSON.stringify({
442
+ name: "gate-fixture",
443
+ version: "1.0.0",
444
+ dependencies: { express: "^4.0.0" },
445
+ }),
446
+ "main.ts": `
447
+ import express from "express";
448
+ const app = express();
449
+ `,
450
+ };
451
+ it("emits NO third-party node or CALLS edge when the option is absent", () => {
452
+ const repo = createFakeRepo(files);
453
+ const { edges, all } = detectCalls(repo); // no third-party nodes
454
+ expect(all.some((n) => n.id.startsWith("[npm]"))).toBe(false);
455
+ expect(edges.some((e) => e.to.startsWith("[npm]"))).toBe(false);
456
+ // metadata still records the name (not gated)
457
+ const file = all.find((n) => n.id === "file::main.ts");
458
+ expect(file.metadata.calls).toContain("express");
459
+ deleteFakeRepo(repo);
460
+ });
461
+ it("emits FILE -> [npm]/express CALLS when the option is set", () => {
462
+ const repo = createFakeRepo(files);
463
+ const extra = buildThirdPartyNodes(repo, ["express"]);
464
+ const { edges } = detectCalls(repo, extra);
465
+ expect(edges).toContainEqual(expect.objectContaining({
466
+ from: "file::main.ts",
467
+ to: "[npm]/express",
468
+ type: "CALLS",
469
+ metadata: expect.objectContaining({ isThirdParty: true, scope: "module" }),
470
+ }));
471
+ deleteFakeRepo(repo);
472
+ });
473
+ });
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,227 @@
1
+ import fs from "fs";
2
+ import path from "path";
3
+ import os from "os";
4
+ import { parseRepo } from "../../parser/index.js";
5
+ import { buildLookupMaps } from "../buildLookup.js";
6
+ import { detectImportEdges } from "./importEdges.js";
7
+ import { detectCallEdges } from "./callEdges.js";
8
+ import { detectPropEdges } from "./propEdges.js";
9
+ import { detectHookEdges } from "./hookEdges.js";
10
+ import { buildThirdPartyNodes } from "../thirdPartyLibs.js";
11
+ // callOrder/v1 edge projection. docs/CALL_ORDER.md §3.2.
12
+ function createFakeRepo(files) {
13
+ const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "devlens-callorder-edge-"));
14
+ for (const [filePath, content] of Object.entries(files)) {
15
+ const fullPath = path.join(tmpDir, filePath);
16
+ fs.mkdirSync(path.dirname(fullPath), { recursive: true });
17
+ fs.writeFileSync(fullPath, content);
18
+ }
19
+ return tmpDir;
20
+ }
21
+ function deleteFakeRepo(repoPath) {
22
+ fs.rmSync(repoPath, { recursive: true, force: true });
23
+ }
24
+ function detectCalls(repoPath, extraNodes = []) {
25
+ const { nodes } = parseRepo(repoPath);
26
+ const all = [...nodes, ...extraNodes];
27
+ const lookup = buildLookupMaps(all);
28
+ detectImportEdges(lookup, repoPath);
29
+ const result = detectCallEdges(all, lookup);
30
+ return { nodes, edges: result.edges };
31
+ }
32
+ function edgeOf(edges, from, to, type = "CALLS") {
33
+ const found = edges.find((e) => e.from === from && e.to === to && e.type === type);
34
+ if (!found)
35
+ throw new Error(`edge not found: ${from} -> ${to} (${type})`);
36
+ return found;
37
+ }
38
+ function nodeOf(nodes, name) {
39
+ const found = nodes.find((n) => n.name === name);
40
+ if (!found)
41
+ throw new Error(`node not found: ${name}`);
42
+ return found;
43
+ }
44
+ describe("callOrder edges — CALLS", () => {
45
+ it("keeps the first position and every repeated position on the node, not the edge", () => {
46
+ const repo = createFakeRepo({
47
+ "main.ts": `
48
+ function a() {}
49
+ function b() {}
50
+ function run() { a(); b(); a(); }
51
+ `,
52
+ });
53
+ const { nodes, edges } = detectCalls(repo);
54
+ const run = nodeOf(nodes, "run");
55
+ const a = nodeOf(nodes, "a");
56
+ const b = nodeOf(nodes, "b");
57
+ const rc = (run.metadata.resolvedCalls ?? []);
58
+ expect(rc.find((r) => r.nodeId === a.id)).toMatchObject({ firstOrder: 1, orders: [1, 3] });
59
+ expect(rc.find((r) => r.nodeId === b.id)).toMatchObject({ firstOrder: 2 });
60
+ expect(rc.find((r) => r.nodeId === b.id)?.orders).toBeUndefined();
61
+ // The edge is structure only.
62
+ expect(edgeOf(edges, run.id, a.id).metadata).not.toHaveProperty("firstCallOrder");
63
+ deleteFakeRepo(repo);
64
+ });
65
+ it("still emits exactly one edge per target", () => {
66
+ const repo = createFakeRepo({
67
+ "main.ts": `
68
+ function a() {}
69
+ function run() { a(); a(); a(); }
70
+ `,
71
+ });
72
+ const { edges } = detectCalls(repo);
73
+ expect(edges.filter((e) => e.type === "CALLS")).toHaveLength(1);
74
+ deleteFakeRepo(repo);
75
+ });
76
+ it("mirrors the position into resolvedCalls with the call-site line", () => {
77
+ const repo = createFakeRepo({
78
+ "main.ts": `
79
+ function a() {}
80
+ function run() {
81
+ a();
82
+ }
83
+ `,
84
+ });
85
+ const { nodes } = detectCalls(repo);
86
+ const run = nodeOf(nodes, "run");
87
+ expect(run.metadata.resolvedCalls).toEqual([
88
+ expect.objectContaining({ name: "a", firstOrder: 1, line: 4 }),
89
+ ]);
90
+ deleteFakeRepo(repo);
91
+ });
92
+ it("numbers third-party calls in the same sequence", () => {
93
+ const repo = createFakeRepo({
94
+ "main.ts": `
95
+ import axios from "axios";
96
+ declare function local(): void;
97
+ function run() { local(); axios.get("/x"); }
98
+ `,
99
+ });
100
+ const extra = buildThirdPartyNodes(repo, ["axios"]);
101
+ const { nodes, edges } = detectCalls(repo, extra);
102
+ const run = nodeOf(nodes, "run");
103
+ const thirdParty = edges.find((e) => e.from === run.id && e.to.endsWith("axios::get"));
104
+ expect(thirdParty).toBeDefined();
105
+ expect(thirdParty?.metadata).not.toHaveProperty("firstCallOrder");
106
+ const rc = (run.metadata.resolvedCalls ?? []);
107
+ expect(rc.find((r) => r.nodeId === thirdParty.to)?.firstOrder).toBe(2);
108
+ deleteFakeRepo(repo);
109
+ });
110
+ it("leaves structure-only callers without an order", () => {
111
+ const nodes = [
112
+ {
113
+ id: "f.ts::a",
114
+ name: "a",
115
+ type: "FUNCTION",
116
+ filePath: "f.ts",
117
+ startLine: 1,
118
+ endLine: 1,
119
+ metadata: {},
120
+ },
121
+ {
122
+ id: "f.ts::run",
123
+ name: "run",
124
+ type: "FUNCTION",
125
+ filePath: "f.ts",
126
+ startLine: 2,
127
+ endLine: 2,
128
+ metadata: { calls: ["a"] },
129
+ },
130
+ ];
131
+ const lookup = buildLookupMaps(nodes);
132
+ const { edges } = detectCallEdges(nodes, lookup);
133
+ expect(edges).toHaveLength(1);
134
+ expect(edges[0].metadata?.firstCallOrder).toBeUndefined();
135
+ });
136
+ });
137
+ describe("callOrder edges — hooks and components", () => {
138
+ it("numbers hook CALLS edges", () => {
139
+ const repo = createFakeRepo({
140
+ "main.tsx": `
141
+ import { useState } from "react";
142
+ function useTheme() { return "dark"; }
143
+ function Panel() {
144
+ const [v] = useState(0);
145
+ const t = useTheme();
146
+ return <div>{v}{t}</div>;
147
+ }
148
+ `,
149
+ });
150
+ const { nodes } = parseRepo(repo);
151
+ const edges = detectHookEdges(nodes, buildLookupMaps(nodes));
152
+ const panel = nodeOf(nodes, "Panel");
153
+ const theme = nodeOf(nodes, "useTheme");
154
+ const hookEdge = edgeOf(edges, panel.id, theme.id);
155
+ expect(hookEdge.metadata).toMatchObject({ isHookCall: true });
156
+ // The ordinal lives on the caller's callSites, never on the edge.
157
+ expect(hookEdge.metadata).not.toHaveProperty("firstCallOrder");
158
+ const site = panel.metadata.callSites.find((c) => c.name === "useTheme");
159
+ expect(site.order).toBe(2);
160
+ deleteFakeRepo(repo);
161
+ });
162
+ it("numbers USES edges from components", () => {
163
+ const repo = createFakeRepo({
164
+ "main.tsx": `
165
+ declare function formatName(v: string): string;
166
+ function Card({ name }: { name: string }) {
167
+ return <span>{formatName(name)}</span>;
168
+ }
169
+ `,
170
+ });
171
+ const { nodes, edges } = detectCalls(repo);
172
+ const card = nodeOf(nodes, "Card");
173
+ const formatName = nodes.find((n) => n.name === "formatName");
174
+ if (formatName) {
175
+ const uses = edgeOf(edges, card.id, formatName.id, "USES");
176
+ expect(uses.metadata).not.toHaveProperty("firstCallOrder");
177
+ expect(uses.metadata).not.toHaveProperty("callOrder");
178
+ const rc = (card.metadata.resolvedCalls ?? []);
179
+ expect(rc.find((r) => r.nodeId === formatName.id)?.firstOrder).toBe(1);
180
+ }
181
+ else {
182
+ expect(card.metadata.uses).toEqual(["formatName"]);
183
+ }
184
+ deleteFakeRepo(repo);
185
+ });
186
+ it("numbers PROP_PASS render order, including repeats", () => {
187
+ const repo = createFakeRepo({
188
+ "main.tsx": `
189
+ function Item({ v }: { v: number }) { return <li>{v}</li>; }
190
+ function List() { return <ul><Item v={1} /><Item v={2} /></ul>; }
191
+ `,
192
+ });
193
+ const { nodes } = parseRepo(repo);
194
+ const edges = detectPropEdges(nodes, buildLookupMaps(nodes), repo);
195
+ const list = nodeOf(nodes, "List");
196
+ const item = nodeOf(nodes, "Item");
197
+ const edge = edgeOf(edges, list.id, item.id, "PROP_PASS");
198
+ expect(edge.metadata).toMatchObject({ renderCount: 2 });
199
+ deleteFakeRepo(repo);
200
+ });
201
+ // Guard: ordering is node metadata only. If this fails, someone re-added the
202
+ // denormalised edge mirror that the cloud had to strip at ingest.
203
+ it("writes no ordering keys into any edge metadata", () => {
204
+ const repo = createFakeRepo({
205
+ "main.tsx": `
206
+ function Item({ v }: { v: number }) { return <li>{v}</li>; }
207
+ function List() { return <ul><Item v={1} /><Item v={2} /></ul>; }
208
+ declare function formatName(v: string): string;
209
+ function Page({ name }: { name: string }) {
210
+ return <span>{formatName(name)}<List /></span>;
211
+ }
212
+ `,
213
+ });
214
+ const { nodes, edges } = detectCalls(repo);
215
+ const FORBIDDEN = ["firstCallOrder", "callOrder", "firstRenderOrder", "renderOrders"];
216
+ for (const edge of edges) {
217
+ for (const key of FORBIDDEN) {
218
+ expect(edge.metadata ?? {}).not.toHaveProperty(key);
219
+ }
220
+ }
221
+ // ...while the ordinal is still available on the caller.
222
+ const page = nodeOf(nodes, "Page");
223
+ const rc = (page.metadata.resolvedCalls ?? []);
224
+ expect(rc.find((r) => r.name === "formatName")?.firstOrder).toBe(1);
225
+ deleteFakeRepo(repo);
226
+ });
227
+ });