devlensio 1.1.1 → 1.2.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 (43) 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 +101 -15
  8. package/dist/graph/edges/callEdges.test.js +119 -0
  9. package/dist/graph/edges/importEdges.js +124 -0
  10. package/dist/parser/declarationIds.d.ts +23 -0
  11. package/dist/parser/declarationIds.js +123 -0
  12. package/dist/parser/exportsMap.js +1 -90
  13. package/dist/parser/extractors/functions.d.ts +11 -0
  14. package/dist/parser/extractors/functions.js +69 -59
  15. package/dist/parser/extractors/moduleScope.d.ts +8 -0
  16. package/dist/parser/extractors/moduleScope.js +80 -0
  17. package/dist/parser/index.js +12 -0
  18. package/dist/parser/moduleScope.test.d.ts +1 -0
  19. package/dist/parser/moduleScope.test.js +174 -0
  20. package/extractors/go/bin/darwin-amd64/devlens_go_extractor +0 -0
  21. package/extractors/go/bin/darwin-arm64/devlens_go_extractor +0 -0
  22. package/extractors/go/bin/linux-amd64/devlens_go_extractor +0 -0
  23. package/extractors/go/bin/linux-arm64/devlens_go_extractor +0 -0
  24. package/extractors/go/bin/windows-amd64/devlens_go_extractor.exe +0 -0
  25. package/extractors/go/calls.go +45 -3
  26. package/extractors/go/parser.go +81 -36
  27. package/extractors/java/devlens_java_extractor.jar +0 -0
  28. package/extractors/java/src/devlens/extractor/Extractor.java +16 -2
  29. package/extractors/java/src/devlens/extractor/LookupMaps.java +2 -0
  30. package/extractors/java/src/devlens/extractor/Parser.java +33 -1
  31. package/extractors/java/src/devlens/extractor/edges/Calls.java +44 -0
  32. package/extractors/python/devlens_extractors_python/edges/calls.py +173 -33
  33. package/extractors/python/devlens_extractors_python/edges/imports.py +21 -1
  34. package/extractors/python/devlens_extractors_python/lookup.py +9 -0
  35. package/extractors/python/devlens_extractors_python/parser/__init__.py +10 -1
  36. package/extractors/rust/bin/darwin-amd64/devlens_rust_extractor +0 -0
  37. package/extractors/rust/bin/darwin-arm64/devlens_rust_extractor +0 -0
  38. package/extractors/rust/bin/linux-amd64/devlens_rust_extractor +0 -0
  39. package/extractors/rust/bin/linux-arm64/devlens_rust_extractor +0 -0
  40. package/extractors/rust/bin/windows-amd64/devlens_rust_extractor.exe +0 -0
  41. package/extractors/rust/src/calls.rs +32 -0
  42. package/extractors/rust/src/lookup.rs +66 -0
  43. package/package.json +1 -1
@@ -24,6 +24,7 @@
24
24
  // - Failures never break analysis: any error yields an absent map.
25
25
  import path from "path";
26
26
  import fs from "fs";
27
+ import { buildNodeIndex, resolveDeclarationToNode, } from "./declarationIds.js";
27
28
  const ENTRY_EXTENSIONS = [".ts", ".tsx", ".js", ".jsx"];
28
29
  const INDEX_NAMES = ["index.ts", "index.tsx", "index.js", "index.jsx"];
29
30
  export function buildExportsMap(project, repoPath, nodes) {
@@ -151,16 +152,6 @@ function starContributors(sf, cache) {
151
152
  cache.set(key, result);
152
153
  return result;
153
154
  }
154
- function buildNodeIndex(nodes) {
155
- const index = new Map();
156
- for (const node of nodes) {
157
- const base = `${node.filePath}::${node.name}`;
158
- if (!index.has(base))
159
- index.set(base, []);
160
- index.get(base).push(node);
161
- }
162
- return index;
163
- }
164
155
  function resolveEntryPoints(pkg, repoPath, project) {
165
156
  const entries = [];
166
157
  if (pkg.exports !== undefined) {
@@ -246,86 +237,6 @@ function resolveTargetFile(repoPath, target, project) {
246
237
  }
247
238
  return undefined;
248
239
  }
249
- function resolveDeclarationToNode(decl, repoPath, nodeIndex) {
250
- const name = declarationName(decl);
251
- if (!name)
252
- return undefined;
253
- const relPath = path.relative(repoPath, decl.getSourceFile().getFilePath()).replace(/\\/g, "/");
254
- const base = `${relPath}::${name}`;
255
- const candidates = nodeIndex.get(base);
256
- if (!candidates || candidates.length === 0)
257
- return undefined;
258
- if (candidates.length === 1)
259
- return { id: candidates[0].id, base };
260
- const match = matchOverloadedNode(decl, candidates);
261
- return match ? { id: match.id, base } : undefined;
262
- }
263
- function declarationName(decl) {
264
- const getName = decl.getName;
265
- if (typeof getName === "function") {
266
- try {
267
- const own = getName.call(decl);
268
- if (typeof own === "string" && own.length > 0)
269
- return own;
270
- }
271
- catch {
272
- // fall through to symbol
273
- }
274
- }
275
- const sym = decl.getSymbol()?.getName();
276
- if (sym && sym !== "default" && !sym.startsWith("__"))
277
- return sym;
278
- return undefined;
279
- }
280
- function matchOverloadedNode(decl, candidates) {
281
- const paramTypes = declarationParamTypes(decl);
282
- if (paramTypes === undefined)
283
- return undefined;
284
- const declKey = signatureKeyFromTypes(paramTypes);
285
- const matches = candidates.filter((node) => {
286
- const params = node.metadata?.parameters;
287
- if (!Array.isArray(params))
288
- return false;
289
- return signatureKeyFromNodeParams(params) === declKey;
290
- });
291
- return matches.length >= 1 ? matches[0] : undefined;
292
- }
293
- function declarationParamTypes(decl) {
294
- const anyDecl = decl;
295
- if (typeof anyDecl.getParameters !== "function")
296
- return undefined;
297
- try {
298
- const params = anyDecl.getParameters();
299
- if (!Array.isArray(params))
300
- return undefined;
301
- return params.map((p) => {
302
- const t = p.getTypeNode?.()?.getText() ?? "unknown";
303
- if (p.isRest?.())
304
- return `...${t}`;
305
- if (p.isOptional?.())
306
- return `${t}?`;
307
- return t;
308
- });
309
- }
310
- catch {
311
- return undefined;
312
- }
313
- }
314
- function signatureKeyFromTypes(types) {
315
- return `(${types.join(",")})`;
316
- }
317
- function signatureKeyFromNodeParams(params) {
318
- return `(${params
319
- .map((p) => {
320
- const t = typeof p?.type === "string" && p.type.length > 0 ? p.type : "unknown";
321
- if (p?.isRest)
322
- return `...${t}`;
323
- if (p?.isOptional)
324
- return `${t}?`;
325
- return t;
326
- })
327
- .join(",")})`;
328
- }
329
240
  export function validateExportsMap(map, nodeIds) {
330
241
  const dangling = [];
331
242
  for (const perPath of Object.values(map.exports)) {
@@ -10,6 +10,17 @@ export interface ExtractedCallData {
10
10
  dependencyNames: string[];
11
11
  contextRefs: string[];
12
12
  }
13
+ export interface CallAccumulator {
14
+ sites: CallSite[];
15
+ hookCalls: string[];
16
+ apiCalls: string[];
17
+ dependencyNames: string[];
18
+ contextRefs: string[];
19
+ seenSites: Set<string>;
20
+ }
21
+ export declare function createCallAccumulator(): CallAccumulator;
22
+ export declare function classifyCall(call: any, acc: CallAccumulator): void;
23
+ export declare function finishCalls(acc: CallAccumulator): ExtractedCallData;
13
24
  export declare function extractCallsWithSites(node: any): ExtractedCallData;
14
25
  export declare function extractFunctionCalls(node: any): string[];
15
26
  export declare function hasErrorHandling(node: any): boolean;
@@ -43,77 +43,87 @@ function inferArgType(arg) {
43
43
  // classifier below.
44
44
  const API_HOOK_FAMILIES = new Set(["useQuery", "useMutation", "useInfiniteQuery", "useSuspenseQuery", "useSWR", "useSWRMutation"]);
45
45
  const AXIOS_METHODS = new Set(["axios.get", "axios.post", "axios.put", "axios.delete", "axios.patch", "axios"]);
46
+ export function createCallAccumulator() {
47
+ return {
48
+ sites: [],
49
+ hookCalls: [],
50
+ apiCalls: [],
51
+ dependencyNames: [],
52
+ contextRefs: [],
53
+ seenSites: new Set(),
54
+ };
55
+ }
46
56
  // SINGLE traversal over all call expressions producing every call-derived
47
57
  // output at once: structured call sites + legacy bare names, custom hook
48
58
  // calls, and API-call strings. The per-aspect extractors used to walk the
49
59
  // same descendants tree four times per function-like; whole-repo cost is now
50
60
  // one walk.
51
- export function extractCallsWithSites(node) {
52
- const callExprs = node.getDescendantsOfKind(SyntaxKind.CallExpression);
53
- const sites = [];
54
- const seenSites = new Set();
55
- const hookCalls = [];
56
- const apiCalls = [];
57
- const dependencyNames = [];
58
- const contextRefs = [];
59
- for (const call of callExprs) {
60
- const name = call.getExpression().getText();
61
- // use* family: custom hooks (^use[A-Z]) plus ALL use* names (incl.
62
- // built-ins like useState) for hook dependency tracking
63
- if (name.startsWith("use")) {
64
- if (/^use[A-Z]/.test(name) && !hookCalls.includes(name))
65
- hookCalls.push(name);
66
- if (!dependencyNames.includes(name))
67
- dependencyNames.push(name);
68
- if (name === "useContext") {
69
- const ctxArg = call.getArguments()[0];
70
- if (ctxArg && !contextRefs.includes(ctxArg.getText()))
71
- contextRefs.push(ctxArg.getText());
72
- }
61
+ export function classifyCall(call, acc) {
62
+ const name = call.getExpression().getText();
63
+ // use* family: custom hooks (^use[A-Z]) plus ALL use* names (incl.
64
+ // built-ins like useState) for hook dependency tracking
65
+ if (name.startsWith("use")) {
66
+ if (/^use[A-Z]/.test(name) && !acc.hookCalls.includes(name))
67
+ acc.hookCalls.push(name);
68
+ if (!acc.dependencyNames.includes(name))
69
+ acc.dependencyNames.push(name);
70
+ if (name === "useContext") {
71
+ const ctxArg = call.getArguments()[0];
72
+ if (ctxArg && !acc.contextRefs.includes(ctxArg.getText()))
73
+ acc.contextRefs.push(ctxArg.getText());
73
74
  }
74
- // API-call families: fetch / axios.* / React Query / SWR
75
- if (name === "fetch" || AXIOS_METHODS.has(name) || API_HOOK_FAMILIES.has(name)) {
76
- const args = call.getArguments();
77
- if (args.length > 0)
78
- apiCalls.push(`${name}(${args[0].getText()})`);
79
- }
80
- // Plain calls/sites skip hooks and builtin noise
81
- if (name.startsWith("use"))
82
- continue;
83
- const rootName = name.split(".")[0];
84
- if (JS_BUILTINS.has(rootName))
85
- continue;
75
+ }
76
+ // API-call families: fetch / axios.* / React Query / SWR
77
+ if (name === "fetch" || AXIOS_METHODS.has(name) || API_HOOK_FAMILIES.has(name)) {
86
78
  const args = call.getArguments();
87
- let hasSpread = false;
88
- const argTypes = [];
89
- for (const arg of args) {
90
- if (arg.getKind?.() === SyntaxKind.SpreadElement) {
91
- hasSpread = true;
92
- argTypes.push("unknown");
93
- }
94
- else {
95
- argTypes.push(inferArgType(arg) ?? "unknown");
96
- }
79
+ if (args.length > 0)
80
+ acc.apiCalls.push(`${name}(${args[0].getText()})`);
81
+ }
82
+ // Plain calls/sites skip hooks and builtin noise
83
+ if (name.startsWith("use"))
84
+ return;
85
+ const rootName = name.split(".")[0];
86
+ if (JS_BUILTINS.has(rootName))
87
+ return;
88
+ const args = call.getArguments();
89
+ let hasSpread = false;
90
+ const argTypes = [];
91
+ for (const arg of args) {
92
+ if (arg.getKind?.() === SyntaxKind.SpreadElement) {
93
+ hasSpread = true;
94
+ argTypes.push("unknown");
95
+ }
96
+ else {
97
+ argTypes.push(inferArgType(arg) ?? "unknown");
97
98
  }
98
- // One record per (name, arity, argTypes) triple — two calls to the same
99
- // name with different arg counts OR arg type shapes are both overload
100
- // signals (same arity + different literal types can hit different
101
- // overloads, and each deserves its own edge).
102
- const key = `${name}/${args.length}/${argTypes.join(",")}`;
103
- if (seenSites.has(key))
104
- continue;
105
- seenSites.add(key);
106
- sites.push({ name, argCount: args.length, argTypes, ...(hasSpread && { hasSpread: true }) });
107
99
  }
100
+ // One record per (name, arity, argTypes) triple — two calls to the same
101
+ // name with different arg counts OR arg type shapes are both overload
102
+ // signals (same arity + different literal types can hit different
103
+ // overloads, and each deserves its own edge).
104
+ const key = `${name}/${args.length}/${argTypes.join(",")}`;
105
+ if (acc.seenSites.has(key))
106
+ return;
107
+ acc.seenSites.add(key);
108
+ acc.sites.push({ name, argCount: args.length, argTypes, ...(hasSpread && { hasSpread: true }) });
109
+ }
110
+ export function finishCalls(acc) {
108
111
  return {
109
- calls: [...new Set(sites.map((cs) => cs.name))],
110
- callSites: sites,
111
- hookCalls,
112
- apiCalls,
113
- dependencyNames,
114
- contextRefs,
112
+ calls: [...new Set(acc.sites.map((cs) => cs.name))],
113
+ callSites: acc.sites,
114
+ hookCalls: acc.hookCalls,
115
+ apiCalls: acc.apiCalls,
116
+ dependencyNames: acc.dependencyNames,
117
+ contextRefs: acc.contextRefs,
115
118
  };
116
119
  }
120
+ export function extractCallsWithSites(node) {
121
+ const acc = createCallAccumulator();
122
+ for (const call of node.getDescendantsOfKind(SyntaxKind.CallExpression)) {
123
+ classifyCall(call, acc);
124
+ }
125
+ return finishCalls(acc);
126
+ }
117
127
  export function extractFunctionCalls(node) {
118
128
  return extractCallsWithSites(node).calls;
119
129
  }
@@ -0,0 +1,8 @@
1
+ import { SourceFile } from "ts-morph";
2
+ import { type ExtractedCallData } from "./functions.js";
3
+ /**
4
+ * Collect every call executed at module scope, classified exactly like calls
5
+ * inside a function (same builtin filtering, hook/api tracking, call sites).
6
+ * Returns EMPTY data for files with no module-scope calls.
7
+ */
8
+ export declare function extractModuleScopeCalls(file: SourceFile): ExtractedCallData;
@@ -0,0 +1,80 @@
1
+ import { SyntaxKind } from "ts-morph";
2
+ import { classifyCall, createCallAccumulator, finishCalls, } from "./functions.js";
3
+ // ─── Module-scope call extraction ─────────────────────────────────────────────
4
+ //
5
+ // A FILE node represents the module itself. Calls executed at module scope
6
+ // (`const cleanup = startAll()`, `const app = express()`, top-level `if`
7
+ // blocks) belong to that FILE node, not to any child function. Entry files
8
+ // (main.ts, server.ts, workers.ts) do most of their work here, so without this
9
+ // pass the graph shows them importing things but never calling anything.
10
+ //
11
+ // Scope rule: a call is module scope iff its nearest function-like/class
12
+ // ancestor is absent. Everything nested in a function body, arrow initializer,
13
+ // class field, or static block belongs to that owner and is extracted by the
14
+ // regular per-declaration extractors.
15
+ const NON_MODULE_ANCESTORS = new Set([
16
+ SyntaxKind.FunctionDeclaration,
17
+ SyntaxKind.FunctionExpression,
18
+ SyntaxKind.ArrowFunction,
19
+ SyntaxKind.MethodDeclaration,
20
+ SyntaxKind.Constructor,
21
+ SyntaxKind.GetAccessor,
22
+ SyntaxKind.SetAccessor,
23
+ SyntaxKind.ClassDeclaration,
24
+ SyntaxKind.ClassExpression,
25
+ SyntaxKind.ClassStaticBlockDeclaration,
26
+ ]);
27
+ // Top-level statements that cannot contain module-scope calls. Skipping them
28
+ // before descending is the perf win: a 3k-line file of function declarations
29
+ // costs nothing here (correctness is still guaranteed by the ancestor guard).
30
+ const SKIP_TOP_LEVEL = new Set([
31
+ SyntaxKind.FunctionDeclaration,
32
+ SyntaxKind.ClassDeclaration,
33
+ SyntaxKind.InterfaceDeclaration,
34
+ SyntaxKind.TypeAliasDeclaration,
35
+ SyntaxKind.EnumDeclaration,
36
+ SyntaxKind.ModuleDeclaration,
37
+ SyntaxKind.ImportDeclaration,
38
+ SyntaxKind.ImportEqualsDeclaration,
39
+ SyntaxKind.ExportDeclaration,
40
+ ]);
41
+ /**
42
+ * Collect every call executed at module scope, classified exactly like calls
43
+ * inside a function (same builtin filtering, hook/api tracking, call sites).
44
+ * Returns EMPTY data for files with no module-scope calls.
45
+ */
46
+ export function extractModuleScopeCalls(file) {
47
+ const acc = createCallAccumulator();
48
+ for (const stmt of file.getStatements()) {
49
+ if (SKIP_TOP_LEVEL.has(stmt.getKind()))
50
+ continue;
51
+ for (const call of stmt.getDescendantsOfKind(SyntaxKind.CallExpression)) {
52
+ if (isOwnedByDeclaration(call))
53
+ continue;
54
+ // Dynamic import() is a CallExpression whose callee is ImportKeyword —
55
+ // not a function call; recording it as `import(...)` is pure noise.
56
+ if (call.getExpression().getKind() === SyntaxKind.ImportKeyword)
57
+ continue;
58
+ // IIFE: the callee is an inline function expression, so the "name" would
59
+ // be the whole function body text. Its body is already excluded by the
60
+ // ancestor rule; the call itself carries no resolvable name.
61
+ if (isIifeCallee(call.getExpression()))
62
+ continue;
63
+ classifyCall(call, acc);
64
+ }
65
+ }
66
+ return finishCalls(acc);
67
+ }
68
+ function isOwnedByDeclaration(call) {
69
+ return Boolean(call.getFirstAncestor((ancestor) => NON_MODULE_ANCESTORS.has(ancestor.getKind())));
70
+ }
71
+ // `(async () => { ... })()` / `(function () { ... })()` — unwrap parentheses
72
+ // and detect a function-expression callee.
73
+ function isIifeCallee(callee) {
74
+ let expr = callee;
75
+ while (expr.getKind() === SyntaxKind.ParenthesizedExpression) {
76
+ expr = expr.getExpression();
77
+ }
78
+ return (expr.getKind() === SyntaxKind.ArrowFunction ||
79
+ expr.getKind() === SyntaxKind.FunctionExpression);
80
+ }
@@ -7,6 +7,7 @@ import { extractFunctions } from "./extractors/functions.js";
7
7
  import { extractStores } from "./extractors/stores.js";
8
8
  import { extractObjectMethods } from "./extractors/objectMethods.js";
9
9
  import { extractClasses } from "./extractors/classes.js";
10
+ import { extractModuleScopeCalls } from "./extractors/moduleScope.js";
10
11
  import { detectFileDirective } from "./directives.js";
11
12
  import { applyOverloadDisambiguation } from "./overloads.js";
12
13
  import { buildExportsMap, validateExportsMap, exportsMapStats } from "./exportsMap.js";
@@ -107,6 +108,9 @@ export function parseRepo(repoPath) {
107
108
  },
108
109
  };
109
110
  const fileDirective = detectFileDirective(file);
111
+ // Module scope — calls executed at file load belong to the FILE node.
112
+ // TEST/STORY files are leaves and never carry them (same rule as children).
113
+ const moduleScope = fileType === "FILE" ? extractModuleScopeCalls(file) : undefined;
110
114
  const components = extractComponents(file, fileDirective);
111
115
  const hooks = extractHooks(file, fileDirective);
112
116
  const functions = extractFunctions(file, fileDirective);
@@ -145,6 +149,14 @@ export function parseRepo(repoPath) {
145
149
  else {
146
150
  fileNode.metadata.nodeCount = overloads.length;
147
151
  fileNode.metadata.childNodeIds = overloads.map(n => n.id);
152
+ // Module-scope call facts — only when non-empty so files with no
153
+ // top-level work don't gain four meaningless metadata keys.
154
+ if (moduleScope && moduleScope.callSites.length > 0) {
155
+ fileNode.metadata.calls = moduleScope.calls;
156
+ fileNode.metadata.callSites = moduleScope.callSites;
157
+ fileNode.metadata.hookCalls = moduleScope.hookCalls;
158
+ fileNode.metadata.apiCalls = moduleScope.apiCalls;
159
+ }
148
160
  // File node hash — based on all child code combined
149
161
  const fileRawCode = overloads.map(n => n.rawCode ?? "").join("\n");
150
162
  if (fileRawCode.trim()) {
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,174 @@
1
+ import fs from "fs";
2
+ import path from "path";
3
+ import os from "os";
4
+ import { Project } from "ts-morph";
5
+ import { extractModuleScopeCalls } from "./extractors/moduleScope.js";
6
+ import { parseRepo } from "./index.js";
7
+ // ─── Helpers ──────────────────────────────────────────────────────────────────
8
+ function parse(source) {
9
+ const project = new Project({ useInMemoryFileSystem: true });
10
+ const file = project.createSourceFile("main.ts", source);
11
+ return extractModuleScopeCalls(file);
12
+ }
13
+ function createFakeRepo(files) {
14
+ const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "devlens-module-scope-test-"));
15
+ for (const [filePath, content] of Object.entries(files)) {
16
+ const fullPath = path.join(tmpDir, filePath);
17
+ fs.mkdirSync(path.dirname(fullPath), { recursive: true });
18
+ fs.writeFileSync(fullPath, content);
19
+ }
20
+ return tmpDir;
21
+ }
22
+ function deleteFakeRepo(repoPath) {
23
+ fs.rmSync(repoPath, { recursive: true, force: true });
24
+ }
25
+ // ─── Scope rule ───────────────────────────────────────────────────────────────
26
+ describe("extractModuleScopeCalls — scope rule", () => {
27
+ it("collects a call in a top-level variable initializer", () => {
28
+ const data = parse(`
29
+ import { startAll } from "./lib/startAll";
30
+ const cleanup = startAll();
31
+ `);
32
+ expect(data.calls).toEqual(["startAll"]);
33
+ expect(data.callSites).toEqual([{ name: "startAll", argCount: 0, argTypes: [] }]);
34
+ });
35
+ it("collects calls inside a top-level if block", () => {
36
+ const data = parse(`
37
+ if (process.env.NODE_ENV === "production") {
38
+ startAll();
39
+ }
40
+ `);
41
+ expect(data.calls).toEqual(["startAll"]);
42
+ });
43
+ it("collects exported top-level initializers", () => {
44
+ const data = parse(`export const app = createApp();`);
45
+ expect(data.calls).toEqual(["createApp"]);
46
+ });
47
+ it("does NOT collect calls inside a function body", () => {
48
+ const data = parse(`
49
+ function boot() {
50
+ startAll();
51
+ }
52
+ `);
53
+ expect(data.calls).toEqual([]);
54
+ });
55
+ it("does NOT collect calls inside an arrow-function initializer", () => {
56
+ const data = parse(`const boot = () => startAll();`);
57
+ expect(data.calls).toEqual([]);
58
+ });
59
+ it("does NOT collect calls inside a class method", () => {
60
+ const data = parse(`
61
+ class Boot {
62
+ run() { startAll(); }
63
+ }
64
+ `);
65
+ expect(data.calls).toEqual([]);
66
+ });
67
+ it("does NOT collect calls inside a class field initializer", () => {
68
+ const data = parse(`
69
+ class Boot {
70
+ cleanup = startAll();
71
+ }
72
+ `);
73
+ expect(data.calls).toEqual([]);
74
+ });
75
+ it("does NOT collect calls inside a class static block", () => {
76
+ const data = parse(`
77
+ class Boot {
78
+ static { startAll(); }
79
+ }
80
+ `);
81
+ expect(data.calls).toEqual([]);
82
+ });
83
+ it("does NOT collect an IIFE body (the IIFE is a function scope)", () => {
84
+ const data = parse(`
85
+ (async () => { startAll(); })();
86
+ `);
87
+ expect(data.calls).toEqual([]);
88
+ });
89
+ it("does NOT collect dynamic import()", () => {
90
+ const data = parse(`const mod = await import("./lib/startAll");`);
91
+ expect(data.calls).toEqual([]);
92
+ });
93
+ it("returns empty data for a file with only declarations", () => {
94
+ const data = parse(`export function a() {} export class B {}`);
95
+ expect(data.calls).toEqual([]);
96
+ expect(data.callSites).toEqual([]);
97
+ });
98
+ });
99
+ // ─── Builtin noise (same rule as function bodies) ─────────────────────────────
100
+ describe("extractModuleScopeCalls — builtin filtering", () => {
101
+ it("drops console.* and Math.* at module scope", () => {
102
+ const data = parse(`
103
+ console.log("booting");
104
+ const n = Math.min(1, 2);
105
+ startAll();
106
+ `);
107
+ expect(data.calls).toEqual(["startAll"]);
108
+ });
109
+ it("drops builtin member calls but keeps user calls with the same shape", () => {
110
+ const data = parse(`
111
+ Object.keys({});
112
+ JSON.stringify({});
113
+ app.listen(3000);
114
+ `);
115
+ expect(data.calls).toEqual(["app.listen"]);
116
+ });
117
+ it("keeps use* names in hookCalls but not in calls (hook rule)", () => {
118
+ const data = parse(`
119
+ const theme = useTheme();
120
+ startAll();
121
+ `);
122
+ expect(data.calls).toEqual(["startAll"]);
123
+ expect(data.hookCalls).toEqual(["useTheme"]);
124
+ });
125
+ it("captures fetch at module scope as an api call", () => {
126
+ const data = parse(`const cfg = fetch("/config");`);
127
+ expect(data.apiCalls).toEqual(['fetch("/config")']);
128
+ });
129
+ });
130
+ // ─── parseRepo wiring ─────────────────────────────────────────────────────────
131
+ describe("parseRepo — module-scope metadata on FILE nodes", () => {
132
+ it("attaches calls/callSites to the FILE node", () => {
133
+ const repo = createFakeRepo({
134
+ "lib/startAll.ts": `export function startAll() { return () => {}; }`,
135
+ "main.ts": `
136
+ import { startAll } from "./lib/startAll";
137
+ const cleanup = startAll();
138
+ process.on("SIGTERM", cleanup);
139
+ `,
140
+ });
141
+ const { nodes } = parseRepo(repo);
142
+ const file = nodes.find((n) => n.id === "file::main.ts");
143
+ expect(file.type).toBe("FILE");
144
+ expect(file.metadata.calls).toEqual(["startAll", "process.on"]);
145
+ expect(file.metadata.callSites).toEqual([
146
+ { name: "startAll", argCount: 0, argTypes: [] },
147
+ { name: "process.on", argCount: 2, argTypes: ["string", "unknown"] },
148
+ ]);
149
+ deleteFakeRepo(repo);
150
+ });
151
+ it("does not attach module-scope keys to files with no top-level calls", () => {
152
+ const repo = createFakeRepo({
153
+ "lib/startAll.ts": `export function startAll() { return 1; }`,
154
+ });
155
+ const { nodes } = parseRepo(repo);
156
+ const file = nodes.find((n) => n.id === "file::lib/startAll.ts");
157
+ expect(file.metadata.calls).toBeUndefined();
158
+ expect(file.metadata.callSites).toBeUndefined();
159
+ deleteFakeRepo(repo);
160
+ });
161
+ it("does not attach module-scope facts to TEST file nodes", () => {
162
+ const repo = createFakeRepo({
163
+ "main.test.ts": `
164
+ import { startAll } from "./lib/startAll";
165
+ const cleanup = startAll();
166
+ `,
167
+ });
168
+ const { nodes } = parseRepo(repo);
169
+ const file = nodes.find((n) => n.id === "file::main.test.ts");
170
+ expect(file.type).toBe("TEST");
171
+ expect(file.metadata.calls).toBeUndefined();
172
+ deleteFakeRepo(repo);
173
+ });
174
+ });
@@ -60,6 +60,41 @@ func detectCalls(pr *parsedRepo, ti *TypeInfo, l *LookupMaps, opts *Options) []m
60
60
  }
61
61
  }
62
62
  }
63
+ // ── Module scope: package-level VAR initializers ──
64
+ // These run at init time and belong to the FILE node. Resolution uses the
65
+ // exact same ladder + registry (l.tp) as function callers, so the
66
+ // third-party gate applies identically.
67
+ for _, pf := range pr.files {
68
+ if pf.IsTest || len(pf.FileCalls) == 0 {
69
+ continue
70
+ }
71
+ callerID := "file::" + pf.RelPath
72
+ info := ti.Infos[pf.RelPath]
73
+ callStrings := make([]string, 0, len(pf.FileCalls))
74
+ var details []resolvedCall
75
+
76
+ for _, c := range pf.FileCalls {
77
+ callStrings = append(callStrings, c.Str)
78
+ target, method, class, e := resolveCallFor(c, pf.PkgPath, callerID, nil, pf, info, l)
79
+ if e != nil {
80
+ e["metadata"].(map[string]any)["scope"] = "module"
81
+ edges = append(edges, e)
82
+ }
83
+ if target != "" {
84
+ details = append(details, resolvedCall{Target: target, Method: method, Class: class})
85
+ }
86
+ }
87
+
88
+ if n, ok := l.NodeByID[callerID]; ok {
89
+ m := n["metadata"].(map[string]any)
90
+ m["calls"] = sortedUnique(callStrings)
91
+ m["callSites"] = callSitesMeta(pf.FileCalls)
92
+ if len(details) > 0 {
93
+ m["resolvedCalls"] = details
94
+ }
95
+ }
96
+ }
97
+
63
98
  return edges
64
99
  }
65
100
 
@@ -73,11 +108,18 @@ func nodeIDForFunc(rel string, fn *ParsedFunc) string {
73
108
 
74
109
  // resolveCall → (target node id, method, class, edge) — edge nil when
75
110
  // unresolvable (documented: builtins/locals/dynamic stay metadata-only).
111
+ // resolveCall — function/method caller wrapper. Keeps the ParsedFunc-based
112
+ // call sites untouched while the shared ladder works on a caller identity.
76
113
  func resolveCall(c CallSite, fn *ParsedFunc, pf *ParsedFile, info *types.Info,
77
114
  l *LookupMaps) (string, string, string, map[string]any) {
115
+ return resolveCallFor(c, fn.PkgPath, nodeIDForFunc(pf.RelPath, fn), fn, pf, info, l)
116
+ }
78
117
 
79
- pkgPath := fn.PkgPath
80
- callerID := nodeIDForFunc(pf.RelPath, fn)
118
+ // resolveCallFor — the resolution ladder for any caller identity (FUNCTION,
119
+ // METHOD, or FILE for module-scope VAR initializers).
120
+ func resolveCallFor(c CallSite, pkgPath, callerID string, fn *ParsedFunc,
121
+ pf *ParsedFile, info *types.Info,
122
+ l *LookupMaps) (string, string, string, map[string]any) {
81
123
 
82
124
  // ── 1. type-info resolution (exact) ──
83
125
  if info != nil {
@@ -117,7 +159,7 @@ func resolveCall(c CallSite, fn *ParsedFunc, pf *ParsedFile, info *types.Info,
117
159
  // ── 1.5 receiver-type-from-declaration (params / typed vars) ──
118
160
  // Handlers receive framework types by signature: func(c *gin.Context) —
119
161
  // the checker can't resolve external types, but the DECLARED type can.
120
- if c.IsSel {
162
+ if c.IsSel && fn != nil {
121
163
  if impPath, typeName, local := receiverDeclaredType(c, fn, pf, l); typeName != "" {
122
164
  if local {
123
165
  if id, ok := l.MethodNodeByPkgTypeName[impPath+"::"+typeName+"."+c.Sel]; ok {