1
0

resolution.test.ts 56 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606
  1. /**
  2. * Resolution Module Tests
  3. *
  4. * Tests for Phase 3: Reference Resolution
  5. */
  6. import { describe, it, expect, beforeEach, afterEach } from 'vitest';
  7. import * as fs from 'fs';
  8. import * as path from 'path';
  9. import * as os from 'os';
  10. import { CodeGraph } from '../src';
  11. import { Node, UnresolvedReference } from '../src/types';
  12. import { ReferenceResolver, createResolver, ResolutionContext } from '../src/resolution';
  13. import { matchReference } from '../src/resolution/name-matcher';
  14. import { resolveImportPath, extractImportMappings, resolveJvmImport, loadCppIncludeDirs, clearCppIncludeDirCache } from '../src/resolution/import-resolver';
  15. import type { UnresolvedRef } from '../src/resolution/types';
  16. import { detectFrameworks, getAllFrameworkResolvers } from '../src/resolution/frameworks';
  17. import { QueryBuilder } from '../src/db/queries';
  18. import { DatabaseConnection } from '../src/db';
  19. describe('Resolution Module', () => {
  20. let tempDir: string;
  21. let cg: CodeGraph;
  22. beforeEach(() => {
  23. // Create temp directory
  24. tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-resolution-test-'));
  25. });
  26. afterEach(() => {
  27. // Clean up
  28. if (cg) {
  29. cg.destroy();
  30. } else if (fs.existsSync(tempDir)) {
  31. fs.rmSync(tempDir, { recursive: true });
  32. }
  33. });
  34. describe('Name Matcher', () => {
  35. it('should match exact name references', () => {
  36. // Create a mock context
  37. const mockNodes: Node[] = [
  38. {
  39. id: 'func:test.ts:myFunction:10',
  40. kind: 'function',
  41. name: 'myFunction',
  42. qualifiedName: 'test.ts::myFunction',
  43. filePath: 'test.ts',
  44. language: 'typescript',
  45. startLine: 10,
  46. endLine: 20,
  47. startColumn: 0,
  48. endColumn: 0,
  49. updatedAt: Date.now(),
  50. },
  51. ];
  52. const context: ResolutionContext = {
  53. getNodesInFile: () => mockNodes,
  54. getNodesByName: (name) => mockNodes.filter((n) => n.name === name),
  55. getNodesByQualifiedName: () => [],
  56. getNodesByKind: () => [],
  57. fileExists: () => true,
  58. readFile: () => null,
  59. getProjectRoot: () => '/test',
  60. getAllFiles: () => ['test.ts'],
  61. };
  62. const ref = {
  63. fromNodeId: 'caller:main.ts:caller:5',
  64. referenceName: 'myFunction',
  65. referenceKind: 'calls' as const,
  66. line: 5,
  67. column: 10,
  68. filePath: 'main.ts',
  69. language: 'typescript' as const,
  70. };
  71. const result = matchReference(ref, context);
  72. expect(result).not.toBeNull();
  73. expect(result?.targetNodeId).toBe('func:test.ts:myFunction:10');
  74. expect(result?.resolvedBy).toBe('exact-match');
  75. });
  76. it('should prefer same-module candidates over cross-module matches', () => {
  77. // Simulates a Python monorepo where multiple apps define navigate()
  78. const candidateA: Node = {
  79. id: 'func:apps/app_a/src/server.py:navigate:10',
  80. kind: 'function',
  81. name: 'navigate',
  82. qualifiedName: 'apps/app_a/src/server.py::navigate',
  83. filePath: 'apps/app_a/src/server.py',
  84. language: 'python',
  85. startLine: 10,
  86. endLine: 20,
  87. startColumn: 0,
  88. endColumn: 0,
  89. updatedAt: Date.now(),
  90. };
  91. const candidateB: Node = {
  92. id: 'func:apps/app_b/src/server.py:navigate:15',
  93. kind: 'function',
  94. name: 'navigate',
  95. qualifiedName: 'apps/app_b/src/server.py::navigate',
  96. filePath: 'apps/app_b/src/server.py',
  97. language: 'python',
  98. startLine: 15,
  99. endLine: 25,
  100. startColumn: 0,
  101. endColumn: 0,
  102. updatedAt: Date.now(),
  103. };
  104. const context: ResolutionContext = {
  105. getNodesInFile: () => [],
  106. getNodesByName: (name) => name === 'navigate' ? [candidateA, candidateB] : [],
  107. getNodesByQualifiedName: () => [],
  108. getNodesByKind: () => [],
  109. fileExists: () => true,
  110. readFile: () => null,
  111. getProjectRoot: () => '/test',
  112. getAllFiles: () => [],
  113. getNodesByLowerName: () => [],
  114. getImportMappings: () => [],
  115. };
  116. // Reference from app_a should resolve to app_a's navigate, not app_b's
  117. const ref = {
  118. fromNodeId: 'func:apps/app_a/src/handler.py:handler:5',
  119. referenceName: 'navigate',
  120. referenceKind: 'calls' as const,
  121. line: 5,
  122. column: 10,
  123. filePath: 'apps/app_a/src/handler.py',
  124. language: 'python' as const,
  125. };
  126. const result = matchReference(ref, context);
  127. expect(result).not.toBeNull();
  128. expect(result?.targetNodeId).toBe('func:apps/app_a/src/server.py:navigate:10');
  129. expect(result?.resolvedBy).toBe('exact-match');
  130. });
  131. it('should lower confidence for cross-module exact matches', () => {
  132. // Only one candidate but in a completely different module
  133. const candidates: Node[] = [
  134. {
  135. id: 'func:apps/app_b/src/server.py:navigate:10',
  136. kind: 'function',
  137. name: 'navigate',
  138. qualifiedName: 'apps/app_b/src/server.py::navigate',
  139. filePath: 'apps/app_b/src/server.py',
  140. language: 'python',
  141. startLine: 10,
  142. endLine: 20,
  143. startColumn: 0,
  144. endColumn: 0,
  145. updatedAt: Date.now(),
  146. },
  147. {
  148. id: 'func:apps/app_c/src/server.py:navigate:10',
  149. kind: 'function',
  150. name: 'navigate',
  151. qualifiedName: 'apps/app_c/src/server.py::navigate',
  152. filePath: 'apps/app_c/src/server.py',
  153. language: 'python',
  154. startLine: 10,
  155. endLine: 20,
  156. startColumn: 0,
  157. endColumn: 0,
  158. updatedAt: Date.now(),
  159. },
  160. ];
  161. const context: ResolutionContext = {
  162. getNodesInFile: () => [],
  163. getNodesByName: (name) => name === 'navigate' ? candidates : [],
  164. getNodesByQualifiedName: () => [],
  165. getNodesByKind: () => [],
  166. fileExists: () => true,
  167. readFile: () => null,
  168. getProjectRoot: () => '/test',
  169. getAllFiles: () => [],
  170. getNodesByLowerName: () => [],
  171. getImportMappings: () => [],
  172. };
  173. // Reference from app_a — neither candidate is in the same module
  174. const ref = {
  175. fromNodeId: 'func:apps/app_a/src/handler.py:handler:5',
  176. referenceName: 'navigate',
  177. referenceKind: 'calls' as const,
  178. line: 5,
  179. column: 10,
  180. filePath: 'apps/app_a/src/handler.py',
  181. language: 'python' as const,
  182. };
  183. const result = matchReference(ref, context);
  184. // Should still resolve but with low confidence
  185. expect(result).not.toBeNull();
  186. expect(result?.confidence).toBeLessThanOrEqual(0.4);
  187. });
  188. it('should match qualified name references', () => {
  189. const mockClassNode: Node = {
  190. id: 'class:user.ts:User:5',
  191. kind: 'class',
  192. name: 'User',
  193. qualifiedName: 'user.ts::User',
  194. filePath: 'user.ts',
  195. language: 'typescript',
  196. startLine: 5,
  197. endLine: 30,
  198. startColumn: 0,
  199. endColumn: 0,
  200. updatedAt: Date.now(),
  201. };
  202. const mockMethodNode: Node = {
  203. id: 'method:user.ts:User.save:15',
  204. kind: 'method',
  205. name: 'save',
  206. qualifiedName: 'user.ts::User::save',
  207. filePath: 'user.ts',
  208. language: 'typescript',
  209. startLine: 15,
  210. endLine: 25,
  211. startColumn: 0,
  212. endColumn: 0,
  213. updatedAt: Date.now(),
  214. };
  215. const context: ResolutionContext = {
  216. getNodesInFile: (fp) => fp === 'user.ts' ? [mockClassNode, mockMethodNode] : [],
  217. getNodesByName: (name) => {
  218. if (name === 'User') return [mockClassNode];
  219. if (name === 'save') return [mockMethodNode];
  220. return [];
  221. },
  222. getNodesByQualifiedName: (qn) => {
  223. if (qn === 'user.ts::User::save') return [mockMethodNode];
  224. return [];
  225. },
  226. getNodesByKind: () => [],
  227. fileExists: () => true,
  228. readFile: () => null,
  229. getProjectRoot: () => '/test',
  230. getAllFiles: () => ['user.ts'],
  231. };
  232. const ref = {
  233. fromNodeId: 'caller:main.ts:main:5',
  234. referenceName: 'User.save',
  235. referenceKind: 'calls' as const,
  236. line: 5,
  237. column: 10,
  238. filePath: 'main.ts',
  239. language: 'typescript' as const,
  240. };
  241. const result = matchReference(ref, context);
  242. expect(result).not.toBeNull();
  243. expect(result?.targetNodeId).toBe('method:user.ts:User.save:15');
  244. });
  245. });
  246. describe('Import Resolver', () => {
  247. it('should resolve relative import paths', () => {
  248. const context: ResolutionContext = {
  249. getNodesInFile: () => [],
  250. getNodesByName: () => [],
  251. getNodesByQualifiedName: () => [],
  252. getNodesByKind: () => [],
  253. fileExists: (p) => p === 'src/components/utils.ts' || p === 'src/components/utils/index.ts',
  254. readFile: () => null,
  255. getProjectRoot: () => '',
  256. getAllFiles: () => ['src/components/utils.ts', 'src/components/utils/index.ts'],
  257. };
  258. const result = resolveImportPath(
  259. './utils',
  260. 'src/components/Button.ts',
  261. 'typescript',
  262. context
  263. );
  264. expect(result).toBe('src/components/utils.ts');
  265. });
  266. it('should resolve parent directory imports', () => {
  267. const context: ResolutionContext = {
  268. getNodesInFile: () => [],
  269. getNodesByName: () => [],
  270. getNodesByQualifiedName: () => [],
  271. getNodesByKind: () => [],
  272. fileExists: (p) => p === 'src/helpers.ts' || p === 'src/helpers/index.ts',
  273. readFile: () => null,
  274. getProjectRoot: () => '',
  275. getAllFiles: () => ['src/helpers.ts', 'src/helpers/index.ts'],
  276. };
  277. const result = resolveImportPath(
  278. '../helpers',
  279. 'src/components/Button.ts',
  280. 'typescript',
  281. context
  282. );
  283. expect(result).toBe('src/helpers.ts');
  284. });
  285. it('should extract JS/TS import mappings', () => {
  286. const content = `
  287. import { foo } from './foo';
  288. import bar from '../bar';
  289. import * as utils from './utils';
  290. import { baz, qux } from './baz';
  291. `;
  292. const mappings = extractImportMappings(
  293. 'src/index.ts',
  294. content,
  295. 'typescript'
  296. );
  297. expect(mappings.length).toBeGreaterThan(0);
  298. expect(mappings.some((m) => m.localName === 'foo')).toBe(true);
  299. expect(mappings.some((m) => m.localName === 'bar')).toBe(true);
  300. });
  301. it('should extract Python import mappings', () => {
  302. const content = `
  303. from utils import helper
  304. from .models import User
  305. import os
  306. from ..services import auth_service
  307. `;
  308. const mappings = extractImportMappings(
  309. 'src/main.py',
  310. content,
  311. 'python'
  312. );
  313. expect(mappings.length).toBeGreaterThan(0);
  314. expect(mappings.some((m) => m.localName === 'helper')).toBe(true);
  315. expect(mappings.some((m) => m.localName === 'User')).toBe(true);
  316. });
  317. });
  318. describe('JVM FQN Import Resolution', () => {
  319. // Build a ResolutionContext stub whose getNodesByQualifiedName answers
  320. // from a fixed table — the only context method resolveJvmImport touches.
  321. const makeContext = (byQName: Record<string, Node[]>): ResolutionContext => ({
  322. getNodesInFile: () => [],
  323. getNodesByName: () => [],
  324. getNodesByQualifiedName: (q) => byQName[q] ?? [],
  325. getNodesByKind: () => [],
  326. fileExists: () => false,
  327. readFile: () => null,
  328. getProjectRoot: () => '',
  329. getAllFiles: () => [],
  330. });
  331. const node = (id: string, name: string, qualifiedName: string, kind: Node['kind'] = 'class', language: Node['language'] = 'kotlin'): Node => ({
  332. id, kind, name, qualifiedName,
  333. filePath: 'Models.kt', language,
  334. startLine: 1, endLine: 1, startColumn: 0, endColumn: 0,
  335. updatedAt: 0,
  336. });
  337. const importRef = (referenceName: string, language: Node['language'] = 'kotlin'): UnresolvedRef => ({
  338. fromNodeId: 'caller',
  339. referenceName,
  340. referenceKind: 'imports',
  341. line: 1, column: 0,
  342. filePath: 'Caller.kt',
  343. language,
  344. });
  345. it('resolves a Kotlin class import by FQN regardless of filename', () => {
  346. const target = node('n1', 'Bar', 'com.example.foo::Bar');
  347. const ctx = makeContext({ 'com.example.foo::Bar': [target] });
  348. const result = resolveJvmImport(importRef('com.example.foo.Bar'), ctx);
  349. expect(result?.targetNodeId).toBe('n1');
  350. expect(result?.resolvedBy).toBe('import');
  351. });
  352. it('resolves a Kotlin top-level function import by FQN', () => {
  353. const util = node('n2', 'util', 'com.example.foo::util', 'function');
  354. const ctx = makeContext({ 'com.example.foo::util': [util] });
  355. const result = resolveJvmImport(importRef('com.example.foo.util'), ctx);
  356. expect(result?.targetNodeId).toBe('n2');
  357. });
  358. it('resolves a Java import by FQN', () => {
  359. const target = node('n3', 'Bar', 'com.example.foo::Bar', 'class', 'java');
  360. const ctx = makeContext({ 'com.example.foo::Bar': [target] });
  361. const result = resolveJvmImport(importRef('com.example.foo.Bar', 'java'), ctx);
  362. expect(result?.targetNodeId).toBe('n3');
  363. });
  364. it('resolves cross-language: Kotlin importing a Java class', () => {
  365. // The Kotlin file declares `import com.example.JavaBar` — the target is
  366. // a Java class node. JVM interop means the resolver doesn't care about
  367. // the source language of the target, only that the FQN matches.
  368. const target = node('n4', 'JavaBar', 'com.example::JavaBar', 'class', 'java');
  369. const ctx = makeContext({ 'com.example::JavaBar': [target] });
  370. const result = resolveJvmImport(importRef('com.example.JavaBar'), ctx);
  371. expect(result?.targetNodeId).toBe('n4');
  372. });
  373. it('disambiguates a name collision across packages', () => {
  374. // Two classes named `Bar` in different packages. Each import resolves
  375. // to the one whose FQN matches — not to "whichever was found first".
  376. const barA = node('n5a', 'Bar', 'com.example.alpha::Bar');
  377. const barB = node('n5b', 'Bar', 'com.example.beta::Bar');
  378. const ctx = makeContext({
  379. 'com.example.alpha::Bar': [barA],
  380. 'com.example.beta::Bar': [barB],
  381. });
  382. expect(resolveJvmImport(importRef('com.example.alpha.Bar'), ctx)?.targetNodeId).toBe('n5a');
  383. expect(resolveJvmImport(importRef('com.example.beta.Bar'), ctx)?.targetNodeId).toBe('n5b');
  384. });
  385. it('returns null for wildcard imports', () => {
  386. const ctx = makeContext({});
  387. expect(resolveJvmImport(importRef('com.example.foo.*'), ctx)).toBeNull();
  388. });
  389. it('returns null for unqualified names', () => {
  390. // A single-segment name has no package; nothing to look up by FQN.
  391. const ctx = makeContext({ 'Bar': [node('n6', 'Bar', 'Bar')] });
  392. expect(resolveJvmImport(importRef('Bar'), ctx)).toBeNull();
  393. });
  394. it('returns null for non-JVM languages', () => {
  395. const target = node('n7', 'Bar', 'com.example::Bar');
  396. const ctx = makeContext({ 'com.example::Bar': [target] });
  397. expect(resolveJvmImport(importRef('com.example.Bar', 'typescript'), ctx)).toBeNull();
  398. });
  399. it('returns null for non-imports reference kinds', () => {
  400. // The resolver intentionally only acts on `imports` refs; ordinary
  401. // `calls`/`extends` refs fall through to the framework + name-matcher
  402. // strategies.
  403. const target = node('n8', 'Bar', 'com.example::Bar');
  404. const ctx = makeContext({ 'com.example::Bar': [target] });
  405. const ref: UnresolvedRef = {
  406. fromNodeId: 'caller', referenceName: 'com.example.Bar',
  407. referenceKind: 'calls', line: 1, column: 0,
  408. filePath: 'Caller.kt', language: 'kotlin',
  409. };
  410. expect(resolveJvmImport(ref, ctx)).toBeNull();
  411. });
  412. it('returns null when the FQN is not in the index', () => {
  413. const ctx = makeContext({});
  414. expect(resolveJvmImport(importRef('com.example.Unknown'), ctx)).toBeNull();
  415. });
  416. });
  417. describe('Framework Detection', () => {
  418. it('should detect React framework', () => {
  419. const context: ResolutionContext = {
  420. getNodesInFile: () => [],
  421. getNodesByName: () => [],
  422. getNodesByQualifiedName: () => [],
  423. getNodesByKind: () => [],
  424. fileExists: () => false,
  425. readFile: (p) => {
  426. if (p === 'package.json') {
  427. return JSON.stringify({
  428. dependencies: { react: '^18.0.0' },
  429. });
  430. }
  431. return null;
  432. },
  433. getProjectRoot: () => '/test',
  434. getAllFiles: () => ['package.json', 'src/App.tsx'],
  435. };
  436. const frameworks = detectFrameworks(context);
  437. expect(frameworks.some((f) => f.name === 'react')).toBe(true);
  438. });
  439. it('should detect Express framework', () => {
  440. const context: ResolutionContext = {
  441. getNodesInFile: () => [],
  442. getNodesByName: () => [],
  443. getNodesByQualifiedName: () => [],
  444. getNodesByKind: () => [],
  445. fileExists: () => false,
  446. readFile: (p) => {
  447. if (p === 'package.json') {
  448. return JSON.stringify({
  449. dependencies: { express: '^4.18.0' },
  450. });
  451. }
  452. return null;
  453. },
  454. getProjectRoot: () => '/test',
  455. getAllFiles: () => ['package.json', 'src/app.js'],
  456. };
  457. const frameworks = detectFrameworks(context);
  458. expect(frameworks.some((f) => f.name === 'express')).toBe(true);
  459. });
  460. it('should detect Laravel framework', () => {
  461. const context: ResolutionContext = {
  462. getNodesInFile: () => [],
  463. getNodesByName: () => [],
  464. getNodesByQualifiedName: () => [],
  465. getNodesByKind: () => [],
  466. fileExists: (p) => p === 'artisan',
  467. readFile: () => null,
  468. getProjectRoot: () => '/test',
  469. getAllFiles: () => ['artisan', 'app/Http/Kernel.php'],
  470. };
  471. const frameworks = detectFrameworks(context);
  472. expect(frameworks.some((f) => f.name === 'laravel')).toBe(true);
  473. });
  474. it('should return all framework resolvers', () => {
  475. const resolvers = getAllFrameworkResolvers();
  476. expect(resolvers.length).toBeGreaterThan(0);
  477. expect(resolvers.some((r) => r.name === 'react')).toBe(true);
  478. expect(resolvers.some((r) => r.name === 'express')).toBe(true);
  479. expect(resolvers.some((r) => r.name === 'laravel')).toBe(true);
  480. });
  481. });
  482. describe('React Framework Resolver', () => {
  483. it('should resolve React component references', () => {
  484. const mockNodes: Node[] = [
  485. {
  486. id: 'component:src/Button.tsx:Button:5',
  487. kind: 'component',
  488. name: 'Button',
  489. qualifiedName: 'src/Button.tsx::Button',
  490. filePath: 'src/Button.tsx',
  491. language: 'tsx',
  492. startLine: 5,
  493. endLine: 20,
  494. startColumn: 0,
  495. endColumn: 0,
  496. updatedAt: Date.now(),
  497. },
  498. ];
  499. const context: ResolutionContext = {
  500. getNodesInFile: (fp) => (fp === 'src/Button.tsx' ? mockNodes : []),
  501. getNodesByName: () => mockNodes,
  502. getNodesByQualifiedName: () => [],
  503. getNodesByKind: () => [],
  504. fileExists: () => false,
  505. readFile: (p) => {
  506. if (p === 'package.json') {
  507. return JSON.stringify({ dependencies: { react: '^18.0.0' } });
  508. }
  509. return null;
  510. },
  511. getProjectRoot: () => '/test',
  512. getAllFiles: () => ['package.json', 'src/Button.tsx', 'src/App.tsx'],
  513. };
  514. const frameworks = detectFrameworks(context);
  515. const reactResolver = frameworks.find((f) => f.name === 'react');
  516. expect(reactResolver).toBeDefined();
  517. const ref = {
  518. fromNodeId: 'component:src/App.tsx:App:1',
  519. referenceName: 'Button',
  520. referenceKind: 'renders' as const,
  521. line: 10,
  522. column: 5,
  523. filePath: 'src/App.tsx',
  524. language: 'typescript' as const,
  525. };
  526. const result = reactResolver!.resolve(ref, context);
  527. expect(result).not.toBeNull();
  528. expect(result?.targetNodeId).toBe('component:src/Button.tsx:Button:5');
  529. });
  530. it('should resolve custom hook references', () => {
  531. const mockNodes: Node[] = [
  532. {
  533. id: 'hook:src/hooks/useAuth.ts:useAuth:1',
  534. kind: 'function',
  535. name: 'useAuth',
  536. qualifiedName: 'src/hooks/useAuth.ts::useAuth',
  537. filePath: 'src/hooks/useAuth.ts',
  538. language: 'typescript',
  539. startLine: 1,
  540. endLine: 20,
  541. startColumn: 0,
  542. endColumn: 0,
  543. updatedAt: Date.now(),
  544. },
  545. ];
  546. const context: ResolutionContext = {
  547. getNodesInFile: (fp) => (fp.includes('useAuth') ? mockNodes : []),
  548. getNodesByName: () => mockNodes,
  549. getNodesByQualifiedName: () => [],
  550. getNodesByKind: () => [],
  551. fileExists: () => false,
  552. readFile: (p) => {
  553. if (p === 'package.json') {
  554. return JSON.stringify({ dependencies: { react: '^18.0.0' } });
  555. }
  556. return null;
  557. },
  558. getProjectRoot: () => '/test',
  559. getAllFiles: () => ['package.json', 'src/hooks/useAuth.ts'],
  560. };
  561. const frameworks = detectFrameworks(context);
  562. const reactResolver = frameworks.find((f) => f.name === 'react');
  563. const ref = {
  564. fromNodeId: 'component:src/App.tsx:App:1',
  565. referenceName: 'useAuth',
  566. referenceKind: 'calls' as const,
  567. line: 5,
  568. column: 10,
  569. filePath: 'src/App.tsx',
  570. language: 'typescript' as const,
  571. };
  572. const result = reactResolver!.resolve(ref, context);
  573. expect(result).not.toBeNull();
  574. expect(result?.targetNodeId).toBe('hook:src/hooks/useAuth.ts:useAuth:1');
  575. });
  576. });
  577. describe('Integration Tests', () => {
  578. it('should create resolver from CodeGraph instance', async () => {
  579. // Create a simple TypeScript project
  580. fs.writeFileSync(
  581. path.join(tempDir, 'package.json'),
  582. JSON.stringify({ name: 'test', dependencies: { react: '^18.0.0' } })
  583. );
  584. const srcDir = path.join(tempDir, 'src');
  585. fs.mkdirSync(srcDir);
  586. // Create utility file
  587. fs.writeFileSync(
  588. path.join(srcDir, 'utils.ts'),
  589. `export function formatDate(date: Date): string {
  590. return date.toISOString();
  591. }
  592. export function parseDate(str: string): Date {
  593. return new Date(str);
  594. }`
  595. );
  596. // Create main file that uses utils
  597. fs.writeFileSync(
  598. path.join(srcDir, 'main.ts'),
  599. `import { formatDate, parseDate } from './utils';
  600. function processDate(input: string): string {
  601. const date = parseDate(input);
  602. return formatDate(date);
  603. }`
  604. );
  605. // Initialize and index
  606. cg = await CodeGraph.init(tempDir, { index: true });
  607. // Check that resolver detected React framework
  608. const frameworks = cg.getDetectedFrameworks();
  609. expect(frameworks).toContain('react');
  610. // Get stats to verify indexing worked
  611. const stats = cg.getStats();
  612. expect(stats.fileCount).toBe(2);
  613. expect(stats.nodeCount).toBeGreaterThan(0);
  614. });
  615. it('should resolve references after indexing', async () => {
  616. // Create a project with references
  617. const srcDir = path.join(tempDir, 'src');
  618. fs.mkdirSync(srcDir, { recursive: true });
  619. fs.writeFileSync(
  620. path.join(srcDir, 'helper.ts'),
  621. `export function helperFunction(): void {
  622. console.log('helper');
  623. }`
  624. );
  625. fs.writeFileSync(
  626. path.join(srcDir, 'main.ts'),
  627. `import { helperFunction } from './helper';
  628. function main(): void {
  629. helperFunction();
  630. }`
  631. );
  632. cg = await CodeGraph.init(tempDir, { index: true });
  633. // Run reference resolution
  634. const result = cg.resolveReferences();
  635. // Should have attempted resolution
  636. expect(result.stats.total).toBeGreaterThanOrEqual(0);
  637. });
  638. it('promotes calls→instantiates when target resolves to a class (Python)', async () => {
  639. // Python has no `new` keyword — `Foo()` is the standard
  640. // instantiation syntax. Extraction can't tell that apart from
  641. // a function call without symbol info, so it emits a `calls`
  642. // ref. Resolution promotes it to `instantiates` once the
  643. // target is known to be a class.
  644. const srcDir = path.join(tempDir, 'src');
  645. fs.mkdirSync(srcDir, { recursive: true });
  646. fs.writeFileSync(
  647. path.join(srcDir, 'app.py'),
  648. `class UserService:
  649. def __init__(self):
  650. self.db = None
  651. def bootstrap():
  652. return UserService()
  653. `
  654. );
  655. cg = await CodeGraph.init(tempDir, { index: true });
  656. cg.resolveReferences();
  657. const bootstrap = cg
  658. .getNodesByKind('function')
  659. .find((n) => n.name === 'bootstrap');
  660. expect(bootstrap).toBeDefined();
  661. const outgoing = cg.getOutgoingEdges(bootstrap!.id);
  662. const instantiates = outgoing.find((e) => e.kind === 'instantiates');
  663. expect(instantiates).toBeDefined();
  664. // Same edge must NOT also appear as a `calls` edge — promotion
  665. // replaces the kind, doesn't duplicate.
  666. const callsToUserService = outgoing.filter(
  667. (e) => e.kind === 'calls' && e.target === instantiates!.target
  668. );
  669. expect(callsToUserService).toHaveLength(0);
  670. });
  671. it('resolves Go cross-package qualified calls via go.mod module path (#388)', async () => {
  672. // Pre-#388, every `pkga.FuncX(...)` call in a Go monorepo was flagged
  673. // external (isExternalImport returned true for any non-`/internal/`
  674. // import without `.`-prefix) and resolution fell through to name-match
  675. // with path proximity — recall on cross-package callers was ~<1%.
  676. fs.writeFileSync(
  677. path.join(tempDir, 'go.mod'),
  678. 'module github.com/example/myproject\n\ngo 1.21\n'
  679. );
  680. const pkgaDir = path.join(tempDir, 'pkga');
  681. const pkgbDir = path.join(tempDir, 'pkgb');
  682. const pkgcDir = path.join(tempDir, 'pkgc');
  683. fs.mkdirSync(pkgaDir);
  684. fs.mkdirSync(pkgbDir);
  685. fs.mkdirSync(pkgcDir);
  686. // Same-name exported function in two packages — only the imported one
  687. // should resolve. Exercises disambiguation, not just connectivity.
  688. fs.writeFileSync(
  689. path.join(pkgaDir, 'conv.go'),
  690. 'package pkga\nfunc Convert(x int) int { return x * 2 }\n'
  691. );
  692. fs.writeFileSync(
  693. path.join(pkgbDir, 'conv.go'),
  694. 'package pkgb\nfunc Convert(x int) int { return x + 1 }\n'
  695. );
  696. fs.writeFileSync(
  697. path.join(pkgcDir, 'use.go'),
  698. `package pkgc
  699. import "github.com/example/myproject/pkga"
  700. func UsePkga() {
  701. pkga.Convert(5)
  702. }
  703. `
  704. );
  705. cg = await CodeGraph.init(tempDir, { index: true });
  706. const usePkga = cg.getNodesByKind('function').filter((n) => n.name ==='UsePkga')[0];
  707. expect(usePkga).toBeDefined();
  708. const outgoing = cg.getOutgoingEdges(usePkga!.id);
  709. const callEdges = outgoing.filter((e) => e.kind === 'calls');
  710. expect(callEdges).toHaveLength(1);
  711. const target = cg.getNode(callEdges[0]!.target);
  712. expect(target?.name).toBe('Convert');
  713. // Critical: the resolver must pick the imported pkga's Convert,
  714. // not pkgb's. With the broken (pre-fix) resolver this lands on
  715. // whichever Convert happens to be cheaper under path proximity.
  716. expect(target?.filePath.replace(/\\/g, '/')).toBe('pkga/conv.go');
  717. });
  718. it('resolves Go aliased imports across packages (#388)', async () => {
  719. fs.writeFileSync(
  720. path.join(tempDir, 'go.mod'),
  721. 'module github.com/example/myproject\n\ngo 1.21\n'
  722. );
  723. fs.mkdirSync(path.join(tempDir, 'pkgb'));
  724. fs.mkdirSync(path.join(tempDir, 'pkgd'));
  725. fs.writeFileSync(
  726. path.join(tempDir, 'pkgb', 'lib.go'),
  727. 'package pkgb\nfunc Compute(x int) int { return x }\n'
  728. );
  729. fs.writeFileSync(
  730. path.join(tempDir, 'pkgd', 'use.go'),
  731. `package pkgd
  732. import (
  733. "fmt"
  734. alias "github.com/example/myproject/pkgb"
  735. )
  736. func UseAliased() {
  737. fmt.Println("hi")
  738. alias.Compute(3)
  739. }
  740. `
  741. );
  742. cg = await CodeGraph.init(tempDir, { index: true });
  743. const useAliased = cg.getNodesByKind('function').filter((n) => n.name ==='UseAliased')[0];
  744. expect(useAliased).toBeDefined();
  745. const calls = cg.getOutgoingEdges(useAliased!.id).filter((e) => e.kind === 'calls');
  746. // fmt.Println is stdlib — must stay external. alias.Compute must resolve.
  747. expect(calls).toHaveLength(1);
  748. const target = cg.getNode(calls[0]!.target);
  749. expect(target?.name).toBe('Compute');
  750. expect(target?.filePath.replace(/\\/g, '/')).toBe('pkgb/lib.go');
  751. });
  752. it('TS type_alias object-shape members resolve method calls (#359)', async () => {
  753. // Pre-#359, `recorder.stop()` (recorder: RecorderHandle) attached
  754. // to `StdioMcpClient.stop` in a sibling directory via path-proximity
  755. // because the type_alias had no `stop` node — only the unrelated
  756. // class did. Now type_alias produces member nodes (property/method),
  757. // so the camelCase receiver↔type word overlap pulls the call to
  758. // `RecorderHandle::stop` instead of the look-alike class.
  759. fs.mkdirSync(path.join(tempDir, 'voice'));
  760. fs.mkdirSync(path.join(tempDir, 'codegraph'));
  761. fs.writeFileSync(
  762. path.join(tempDir, 'voice', 'recorder.ts'),
  763. `export type RecorderHandle = {
  764. wavPath: string;
  765. stop: () => Promise<{ ok: true }>;
  766. };
  767. `
  768. );
  769. fs.writeFileSync(
  770. path.join(tempDir, 'voice', 'controller.ts'),
  771. `import type { RecorderHandle } from "./recorder";
  772. export async function finaliseRecording(recorder: RecorderHandle) {
  773. return await recorder.stop();
  774. }
  775. `
  776. );
  777. fs.writeFileSync(
  778. path.join(tempDir, 'codegraph', 'stdio-client.ts'),
  779. `export class StdioMcpClient {
  780. private stopped = false;
  781. async stop(): Promise<void> { this.stopped = true; }
  782. }
  783. `
  784. );
  785. cg = await CodeGraph.init(tempDir, { index: true });
  786. const handleStop = cg
  787. .getNodesByKind('method')
  788. .find((n) => n.qualifiedName === 'RecorderHandle::stop');
  789. expect(handleStop).toBeDefined();
  790. const clientStop = cg
  791. .getNodesByKind('method')
  792. .find((n) => n.qualifiedName === 'StdioMcpClient::stop');
  793. expect(clientStop).toBeDefined();
  794. const handleCallers = cg.getIncomingEdges(handleStop!.id).filter((e) => e.kind === 'calls');
  795. const clientCallers = cg.getIncomingEdges(clientStop!.id).filter((e) => e.kind === 'calls');
  796. expect(handleCallers.length).toBeGreaterThanOrEqual(1);
  797. // The class method must have NO callers — voice/'s call must NOT
  798. // mis-attribute. A non-empty list would mean the false-positive
  799. // path is still firing.
  800. expect(clientCallers).toHaveLength(0);
  801. // Function-typed property surfaces as a `method` node, not `property`,
  802. // because `stop()` semantics at the call site are method semantics.
  803. expect(handleStop!.kind).toBe('method');
  804. });
  805. it('Java import disambiguates same-name classes across modules (#314)', async () => {
  806. // Pre-#314 the import resolver had no Java branch at all, so a
  807. // multi-module Maven repo where `dao/converter/FooConverter` and
  808. // `service/converter/FooConverter` both export a `convert` method
  809. // resolved by file-path proximity — picking whichever class was
  810. // closer to the caller, which is wrong any time the caller lives
  811. // in an equidistant cross-cutting module.
  812. const daoDir = path.join(tempDir, 'dao/src/main/java/com/example/dao/converter');
  813. const serviceDir = path.join(tempDir, 'service/src/main/java/com/example/service/converter');
  814. const webDir = path.join(tempDir, 'web/src/main/java/com/example/web');
  815. fs.mkdirSync(daoDir, { recursive: true });
  816. fs.mkdirSync(serviceDir, { recursive: true });
  817. fs.mkdirSync(webDir, { recursive: true });
  818. fs.writeFileSync(
  819. path.join(daoDir, 'FooConverter.java'),
  820. `package com.example.dao.converter;
  821. public class FooConverter { public String convert(String x) { return "dao:" + x; } }
  822. `
  823. );
  824. fs.writeFileSync(
  825. path.join(serviceDir, 'FooConverter.java'),
  826. `package com.example.service.converter;
  827. public class FooConverter { public String convert(String x) { return "svc:" + x; } }
  828. `
  829. );
  830. // The caller imports the SERVICE version — even though dao is
  831. // alphabetically/lexically first in the candidate list, the
  832. // import must trump that order.
  833. fs.writeFileSync(
  834. path.join(webDir, 'Handler.java'),
  835. `package com.example.web;
  836. import com.example.service.converter.FooConverter;
  837. public class Handler {
  838. private FooConverter fooConverter;
  839. public String use() { return fooConverter.convert("input"); }
  840. }
  841. `
  842. );
  843. cg = await CodeGraph.init(tempDir, { index: true });
  844. const use = cg
  845. .getNodesByKind('method')
  846. .find((n) => n.qualifiedName === 'com.example.web::Handler::use');
  847. expect(use).toBeDefined();
  848. const calls = cg.getOutgoingEdges(use!.id).filter((e) => e.kind === 'calls');
  849. expect(calls.length).toBeGreaterThanOrEqual(1);
  850. const target = cg.getNode(calls[0]!.target);
  851. expect(target?.name).toBe('convert');
  852. expect(target?.filePath.replace(/\\/g, '/')).toBe(
  853. 'service/src/main/java/com/example/service/converter/FooConverter.java'
  854. );
  855. });
  856. it('C# extracts references from method/property/field types (#381)', async () => {
  857. // Pre-#381, every C# project produced ZERO `references` edges:
  858. // csharp.ts was missing returnField, and the type-leaf walker
  859. // only recognized TS/Java's `type_identifier` nodes — C# uses
  860. // `identifier`/`predefined_type`/`qualified_name`/`generic_name`.
  861. const srcDir = path.join(tempDir, 'src');
  862. fs.mkdirSync(srcDir, { recursive: true });
  863. fs.writeFileSync(
  864. path.join(srcDir, 'Dtos.cs'),
  865. `namespace MyApp;
  866. public class SessionInfoDto { public string Id { get; set; } = ""; }
  867. public class UserDto { public string Name { get; set; } = ""; }
  868. `
  869. );
  870. fs.writeFileSync(
  871. path.join(srcDir, 'Service.cs'),
  872. `using System.Threading.Tasks;
  873. namespace MyApp;
  874. public class DataExporter
  875. {
  876. public SessionInfoDto Build(UserDto user, SessionInfoDto session) { return session; }
  877. public Task<SessionInfoDto> BuildAsync(UserDto user) { return Task.FromResult(new SessionInfoDto()); }
  878. public SessionInfoDto Latest { get; set; } = new();
  879. private UserDto _cached;
  880. }
  881. `
  882. );
  883. cg = await CodeGraph.init(tempDir, { index: true });
  884. const sessionDto = cg
  885. .getNodesByKind('class')
  886. .find((n) => n.name === 'SessionInfoDto');
  887. const userDto = cg
  888. .getNodesByKind('class')
  889. .find((n) => n.name === 'UserDto');
  890. expect(sessionDto).toBeDefined();
  891. expect(userDto).toBeDefined();
  892. const sessionIncoming = cg
  893. .getIncomingEdges(sessionDto!.id)
  894. .filter((e) => e.kind === 'references');
  895. const userIncoming = cg
  896. .getIncomingEdges(userDto!.id)
  897. .filter((e) => e.kind === 'references');
  898. // SessionInfoDto: Build return, Build param, BuildAsync return (inside Task<>), Latest property.
  899. // UserDto: Build param, BuildAsync param, _cached field.
  900. expect(sessionIncoming.length).toBeGreaterThanOrEqual(4);
  901. expect(userIncoming.length).toBeGreaterThanOrEqual(3);
  902. });
  903. it('Go: leaves stdlib calls (fmt.Println, etc.) external', async () => {
  904. fs.writeFileSync(
  905. path.join(tempDir, 'go.mod'),
  906. 'module github.com/example/myproject\n\ngo 1.21\n'
  907. );
  908. fs.writeFileSync(
  909. path.join(tempDir, 'main.go'),
  910. `package main
  911. import "fmt"
  912. func main() {
  913. fmt.Println("hi")
  914. }
  915. `
  916. );
  917. cg = await CodeGraph.init(tempDir, { index: true });
  918. const mainFn = cg.getNodesByKind('function').filter((n) => n.name ==='main')[0];
  919. const calls = cg.getOutgoingEdges(mainFn!.id).filter((e) => e.kind === 'calls');
  920. // No spurious in-project edge — fmt.* must stay unresolved/external.
  921. expect(calls).toHaveLength(0);
  922. });
  923. });
  924. describe('Name Matcher: kind bias for new ref kinds', () => {
  925. const baseContext = (candidates: Node[]): ResolutionContext => ({
  926. getNodesInFile: () => [],
  927. getNodesByName: (name) => candidates.filter((c) => c.name === name),
  928. getNodesByQualifiedName: () => [],
  929. getNodesByKind: () => [],
  930. fileExists: () => true,
  931. readFile: () => null,
  932. getProjectRoot: () => '/test',
  933. getAllFiles: () => [],
  934. getNodesByLowerName: () => [],
  935. getImportMappings: () => [],
  936. });
  937. it('prefers a class candidate over a function for `instantiates` refs', () => {
  938. // A class and a function share a name across the codebase.
  939. // Without the kind bias, the function (which gets the +25 `calls`
  940. // bonus historically applied to all candidates of that kind) would
  941. // win. Now the instantiates branch reverses it.
  942. const fn: Node = {
  943. id: 'func:utils.ts:Logger:5', kind: 'function', name: 'Logger',
  944. qualifiedName: 'utils.ts::Logger', filePath: 'utils.ts', language: 'typescript',
  945. startLine: 5, endLine: 7, startColumn: 0, endColumn: 0, updatedAt: Date.now(),
  946. };
  947. const cls: Node = {
  948. id: 'class:logger.ts:Logger:10', kind: 'class', name: 'Logger',
  949. qualifiedName: 'logger.ts::Logger', filePath: 'logger.ts', language: 'typescript',
  950. startLine: 10, endLine: 30, startColumn: 0, endColumn: 0, updatedAt: Date.now(),
  951. };
  952. const ref = {
  953. fromNodeId: 'func:main.ts:bootstrap:1',
  954. referenceName: 'Logger',
  955. referenceKind: 'instantiates' as const,
  956. line: 5, column: 0, filePath: 'main.ts', language: 'typescript' as const,
  957. };
  958. const result = matchReference(ref, baseContext([fn, cls]));
  959. expect(result?.targetNodeId).toBe('class:logger.ts:Logger:10');
  960. });
  961. it('prefers a function candidate over a non-function for `decorates` refs', () => {
  962. const variable: Node = {
  963. id: 'var:config.ts:Inject:5', kind: 'variable', name: 'Inject',
  964. qualifiedName: 'config.ts::Inject', filePath: 'config.ts', language: 'typescript',
  965. startLine: 5, endLine: 5, startColumn: 0, endColumn: 0, updatedAt: Date.now(),
  966. };
  967. const decorator: Node = {
  968. id: 'func:di.ts:Inject:10', kind: 'function', name: 'Inject',
  969. qualifiedName: 'di.ts::Inject', filePath: 'di.ts', language: 'typescript',
  970. startLine: 10, endLine: 20, startColumn: 0, endColumn: 0, updatedAt: Date.now(),
  971. };
  972. const ref = {
  973. fromNodeId: 'class:svc.ts:UserService:1',
  974. referenceName: 'Inject',
  975. referenceKind: 'decorates' as const,
  976. line: 5, column: 0, filePath: 'svc.ts', language: 'typescript' as const,
  977. };
  978. const result = matchReference(ref, baseContext([variable, decorator]));
  979. expect(result?.targetNodeId).toBe('func:di.ts:Inject:10');
  980. });
  981. });
  982. describe('tsconfig path aliases', () => {
  983. it('resolves an aliased import to the alias-mapped file (not a same-named file elsewhere)', async () => {
  984. // Two same-named exports in different directories. Without alias
  985. // resolution, name-matcher would pick whichever it finds first;
  986. // with alias resolution, the import path uniquely picks one.
  987. fs.mkdirSync(path.join(tempDir, 'src/utils'), { recursive: true });
  988. fs.mkdirSync(path.join(tempDir, 'src/legacy'), { recursive: true });
  989. fs.writeFileSync(
  990. path.join(tempDir, 'src/utils/format.ts'),
  991. `export function pickMe(): number { return 1; }\n`
  992. );
  993. fs.writeFileSync(
  994. path.join(tempDir, 'src/legacy/format.ts'),
  995. `export function pickMe(): number { return 99; }\n`
  996. );
  997. fs.writeFileSync(
  998. path.join(tempDir, 'src/main.ts'),
  999. `import { pickMe } from '@utils/format';\nexport function go(): number { return pickMe(); }\n`
  1000. );
  1001. fs.writeFileSync(
  1002. path.join(tempDir, 'tsconfig.json'),
  1003. JSON.stringify({
  1004. compilerOptions: {
  1005. baseUrl: './src',
  1006. paths: { '@utils/*': ['utils/*'] },
  1007. },
  1008. })
  1009. );
  1010. cg = await CodeGraph.init(tempDir, { index: true });
  1011. cg.resolveReferences();
  1012. // The two pickMe nodes live in different files. The aliased
  1013. // import should attach the call edge to the @utils-mapped one,
  1014. // not the legacy duplicate.
  1015. const all = cg.getNodesByKind('function').filter((n) => n.name === 'pickMe');
  1016. const utilsNode = all.find((n) => n.filePath === 'src/utils/format.ts');
  1017. const legacyNode = all.find((n) => n.filePath === 'src/legacy/format.ts');
  1018. expect(utilsNode).toBeDefined();
  1019. expect(legacyNode).toBeDefined();
  1020. const utilsCallers = cg.getCallers(utilsNode!.id);
  1021. const legacyCallers = cg.getCallers(legacyNode!.id);
  1022. expect(utilsCallers.length).toBeGreaterThan(0);
  1023. expect(utilsCallers.some((c) => c.node.filePath === 'src/main.ts')).toBe(true);
  1024. // The legacy node should NOT have a caller from src/main.ts —
  1025. // the alias correctly picked the utils version.
  1026. expect(legacyCallers.some((c) => c.node.filePath === 'src/main.ts')).toBe(false);
  1027. });
  1028. it('falls back gracefully when tsconfig is absent', async () => {
  1029. fs.mkdirSync(path.join(tempDir, 'src'), { recursive: true });
  1030. fs.writeFileSync(
  1031. path.join(tempDir, 'src/a.ts'),
  1032. `export function aFn(): void {}\n`
  1033. );
  1034. fs.writeFileSync(
  1035. path.join(tempDir, 'src/b.ts'),
  1036. `import { aFn } from './a';\nexport function bFn(): void { aFn(); }\n`
  1037. );
  1038. cg = await CodeGraph.init(tempDir, { index: true });
  1039. // No tsconfig present — index should still complete and the
  1040. // relative-import-based call edge should be created.
  1041. const aFn = cg.getNodesByKind('function').find((n) => n.name === 'aFn');
  1042. expect(aFn).toBeDefined();
  1043. const callers = cg.getCallers(aFn!.id);
  1044. expect(callers.some((c) => c.node.filePath === 'src/b.ts')).toBe(true);
  1045. });
  1046. });
  1047. describe('re-export chain following', () => {
  1048. it('chases a 3-hop barrel chain (wildcard → named → declaration)', async () => {
  1049. // main.ts → all.ts (wildcard) → index.ts (named) → auth.ts (declaration).
  1050. // Without chain following, `signIn` resolves to nothing because
  1051. // none of the barrel files declare it directly.
  1052. fs.mkdirSync(path.join(tempDir, 'src/services'), { recursive: true });
  1053. fs.writeFileSync(
  1054. path.join(tempDir, 'src/services/auth.ts'),
  1055. `export function signIn(): void {}\n`
  1056. );
  1057. fs.writeFileSync(
  1058. path.join(tempDir, 'src/services/index.ts'),
  1059. `export { signIn } from './auth';\n`
  1060. );
  1061. fs.writeFileSync(
  1062. path.join(tempDir, 'src/all.ts'),
  1063. `export * from './services/index';\n`
  1064. );
  1065. fs.writeFileSync(
  1066. path.join(tempDir, 'src/main.ts'),
  1067. `import { signIn } from './all';\nexport function go(): void { signIn(); }\n`
  1068. );
  1069. cg = await CodeGraph.init(tempDir, { index: true });
  1070. cg.resolveReferences();
  1071. const signInNode = cg
  1072. .getNodesByKind('function')
  1073. .find((n) => n.name === 'signIn' && n.filePath === 'src/services/auth.ts');
  1074. expect(signInNode).toBeDefined();
  1075. const callers = cg.getCallers(signInNode!.id);
  1076. expect(callers.some((c) => c.node.filePath === 'src/main.ts')).toBe(true);
  1077. });
  1078. it('follows a renamed named re-export (export { foo as bar } from ...)', async () => {
  1079. // The chase has to look up `foo` in the upstream module even
  1080. // though the importer asked for `bar` — exercises the rename
  1081. // branch of findExportedSymbol.
  1082. fs.mkdirSync(path.join(tempDir, 'src'), { recursive: true });
  1083. fs.writeFileSync(
  1084. path.join(tempDir, 'src/auth.ts'),
  1085. `export function signIn(): void {}\n`
  1086. );
  1087. fs.writeFileSync(
  1088. path.join(tempDir, 'src/index.ts'),
  1089. `export { signIn as login } from './auth';\n`
  1090. );
  1091. fs.writeFileSync(
  1092. path.join(tempDir, 'src/main.ts'),
  1093. `import { login } from './index';\nexport function go(): void { login(); }\n`
  1094. );
  1095. cg = await CodeGraph.init(tempDir, { index: true });
  1096. cg.resolveReferences();
  1097. const signInNode = cg
  1098. .getNodesByKind('function')
  1099. .find((n) => n.name === 'signIn' && n.filePath === 'src/auth.ts');
  1100. expect(signInNode).toBeDefined();
  1101. const callers = cg.getCallers(signInNode!.id);
  1102. expect(callers.some((c) => c.node.filePath === 'src/main.ts')).toBe(true);
  1103. });
  1104. });
  1105. describe('C/C++ Import Resolution', () => {
  1106. afterEach(() => {
  1107. clearCppIncludeDirCache();
  1108. });
  1109. it('should resolve C include to header in same directory', () => {
  1110. const context: ResolutionContext = {
  1111. getNodesInFile: () => [],
  1112. getNodesByName: () => [],
  1113. getNodesByQualifiedName: () => [],
  1114. getNodesByKind: () => [],
  1115. fileExists: (p) => p === 'utils.h',
  1116. readFile: () => null,
  1117. getProjectRoot: () => '',
  1118. getAllFiles: () => ['utils.h', 'main.c'],
  1119. };
  1120. const result = resolveImportPath(
  1121. 'utils.h',
  1122. 'main.c',
  1123. 'c',
  1124. context
  1125. );
  1126. expect(result).toBe('utils.h');
  1127. });
  1128. it('should resolve C++ include with .hpp extension', () => {
  1129. const context: ResolutionContext = {
  1130. getNodesInFile: () => [],
  1131. getNodesByName: () => [],
  1132. getNodesByQualifiedName: () => [],
  1133. getNodesByKind: () => [],
  1134. fileExists: (p) => p === 'include/myclass.hpp',
  1135. readFile: () => null,
  1136. getProjectRoot: () => '',
  1137. getAllFiles: () => ['include/myclass.hpp', 'src/main.cpp'],
  1138. getCppIncludeDirs: () => ['include'],
  1139. };
  1140. const result = resolveImportPath(
  1141. 'myclass.hpp',
  1142. 'src/main.cpp',
  1143. 'cpp',
  1144. context
  1145. );
  1146. expect(result).toBe('include/myclass.hpp');
  1147. });
  1148. it('should resolve include with subdirectory path', () => {
  1149. const context: ResolutionContext = {
  1150. getNodesInFile: () => [],
  1151. getNodesByName: () => [],
  1152. getNodesByQualifiedName: () => [],
  1153. getNodesByKind: () => [],
  1154. fileExists: (p) => p === 'utils/helpers.h',
  1155. readFile: () => null,
  1156. getProjectRoot: () => '',
  1157. getAllFiles: () => ['utils/helpers.h', 'main.c'],
  1158. };
  1159. const result = resolveImportPath(
  1160. 'utils/helpers.h',
  1161. 'main.c',
  1162. 'c',
  1163. context
  1164. );
  1165. expect(result).toBe('utils/helpers.h');
  1166. });
  1167. it('should resolve include via include directories', () => {
  1168. const context: ResolutionContext = {
  1169. getNodesInFile: () => [],
  1170. getNodesByName: () => [],
  1171. getNodesByQualifiedName: () => [],
  1172. getNodesByKind: () => [],
  1173. fileExists: (p) => p === 'include/myheader.h',
  1174. readFile: () => null,
  1175. getProjectRoot: () => '',
  1176. getAllFiles: () => ['include/myheader.h', 'src/main.cpp'],
  1177. getCppIncludeDirs: () => ['include'],
  1178. };
  1179. const result = resolveImportPath(
  1180. 'myheader.h',
  1181. 'src/main.cpp',
  1182. 'cpp',
  1183. context
  1184. );
  1185. expect(result).toBe('include/myheader.h');
  1186. });
  1187. it('should resolve include trying multiple extensions', () => {
  1188. const context: ResolutionContext = {
  1189. getNodesInFile: () => [],
  1190. getNodesByName: () => [],
  1191. getNodesByQualifiedName: () => [],
  1192. getNodesByKind: () => [],
  1193. // myclass.h does not exist, but myclass.hpp does
  1194. fileExists: (p) => p === 'include/myclass.hpp',
  1195. readFile: () => null,
  1196. getProjectRoot: () => '',
  1197. getAllFiles: () => ['include/myclass.hpp', 'src/main.cpp'],
  1198. getCppIncludeDirs: () => ['include'],
  1199. };
  1200. const result = resolveImportPath(
  1201. 'myclass',
  1202. 'src/main.cpp',
  1203. 'cpp',
  1204. context
  1205. );
  1206. expect(result).toBe('include/myclass.hpp');
  1207. });
  1208. it('should return null for system headers', () => {
  1209. const context: ResolutionContext = {
  1210. getNodesInFile: () => [],
  1211. getNodesByName: () => [],
  1212. getNodesByQualifiedName: () => [],
  1213. getNodesByKind: () => [],
  1214. fileExists: () => true,
  1215. readFile: () => null,
  1216. getProjectRoot: () => '',
  1217. getAllFiles: () => [],
  1218. };
  1219. // C standard library header
  1220. expect(resolveImportPath('stdio.h', 'main.c', 'c', context)).toBeNull();
  1221. // C++ standard library header
  1222. expect(resolveImportPath('vector', 'main.cpp', 'cpp', context)).toBeNull();
  1223. // C++ C-wrapper header
  1224. expect(resolveImportPath('cstdio', 'main.cpp', 'cpp', context)).toBeNull();
  1225. });
  1226. it('should return null for single-component third-party paths that cannot be resolved', () => {
  1227. const context: ResolutionContext = {
  1228. getNodesInFile: () => [],
  1229. getNodesByName: () => [],
  1230. getNodesByQualifiedName: () => [],
  1231. getNodesByKind: () => [],
  1232. fileExists: () => false,
  1233. readFile: () => null,
  1234. getProjectRoot: () => '',
  1235. getAllFiles: () => [],
  1236. getCppIncludeDirs: () => [],
  1237. };
  1238. // Third-party bare header without path — not resolvable, returns null
  1239. const result = resolveImportPath(
  1240. 'openssl/ssl.h',
  1241. 'main.cpp',
  1242. 'cpp',
  1243. context
  1244. );
  1245. expect(result).toBeNull();
  1246. });
  1247. it('should not filter project headers with path separators', () => {
  1248. const context: ResolutionContext = {
  1249. getNodesInFile: () => [],
  1250. getNodesByName: () => [],
  1251. getNodesByQualifiedName: () => [],
  1252. getNodesByKind: () => [],
  1253. fileExists: (p) => p === 'mylib/utils.h',
  1254. readFile: () => null,
  1255. getProjectRoot: () => '',
  1256. getAllFiles: () => ['mylib/utils.h'],
  1257. };
  1258. // Path with separator should NOT be filtered as external
  1259. const result = resolveImportPath(
  1260. 'mylib/utils.h',
  1261. 'main.c',
  1262. 'c',
  1263. context
  1264. );
  1265. expect(result).toBe('mylib/utils.h');
  1266. });
  1267. it('should extract C/C++ import mappings from #include directives', () => {
  1268. const code = `#include <iostream>
  1269. #include "myheader.h"
  1270. #include "utils/helpers.hpp"`;
  1271. const mappings = extractImportMappings('main.cpp', code, 'cpp');
  1272. expect(mappings.length).toBe(3);
  1273. expect(mappings[0]).toEqual({
  1274. localName: 'iostream',
  1275. exportedName: '*',
  1276. source: 'iostream',
  1277. isDefault: false,
  1278. isNamespace: true,
  1279. });
  1280. expect(mappings[1]).toEqual({
  1281. localName: 'myheader',
  1282. exportedName: '*',
  1283. source: 'myheader.h',
  1284. isDefault: false,
  1285. isNamespace: true,
  1286. });
  1287. expect(mappings[2]).toEqual({
  1288. localName: 'helpers',
  1289. exportedName: '*',
  1290. source: 'utils/helpers.hpp',
  1291. isDefault: false,
  1292. isNamespace: true,
  1293. });
  1294. });
  1295. it('should discover include directories from compile_commands.json', () => {
  1296. // Create a temp project with compile_commands.json
  1297. const tempProject = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-cpp-test-'));
  1298. try {
  1299. const compileDb = [
  1300. {
  1301. directory: tempProject,
  1302. command: 'g++ -Iinclude -Isrc/lib -isystem /usr/include -c src/main.cpp',
  1303. file: 'src/main.cpp',
  1304. },
  1305. ];
  1306. fs.writeFileSync(
  1307. path.join(tempProject, 'compile_commands.json'),
  1308. JSON.stringify(compileDb)
  1309. );
  1310. // Create the include dirs so they exist
  1311. fs.mkdirSync(path.join(tempProject, 'include'), { recursive: true });
  1312. fs.mkdirSync(path.join(tempProject, 'src', 'lib'), { recursive: true });
  1313. clearCppIncludeDirCache();
  1314. const dirs = loadCppIncludeDirs(tempProject);
  1315. // Should find include and src/lib (relative to project root)
  1316. // /usr/include is absolute and outside project, should be excluded
  1317. expect(dirs).toContain('include');
  1318. expect(dirs).toContain('src/lib');
  1319. expect(dirs.some(d => d.includes('usr'))).toBe(false);
  1320. } finally {
  1321. fs.rmSync(tempProject, { recursive: true });
  1322. }
  1323. });
  1324. it('should fall back to heuristic include dirs when no compile_commands.json', () => {
  1325. const tempProject = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-cpp-test-'));
  1326. try {
  1327. // Create include/ and src/ directories with headers
  1328. fs.mkdirSync(path.join(tempProject, 'include'), { recursive: true });
  1329. fs.writeFileSync(path.join(tempProject, 'include', 'types.h'), '');
  1330. fs.mkdirSync(path.join(tempProject, 'src'), { recursive: true });
  1331. fs.writeFileSync(path.join(tempProject, 'src', 'main.cpp'), '');
  1332. // Create a directory without headers — should not be included
  1333. fs.mkdirSync(path.join(tempProject, 'docs'), { recursive: true });
  1334. clearCppIncludeDirCache();
  1335. const dirs = loadCppIncludeDirs(tempProject);
  1336. expect(dirs).toContain('include');
  1337. expect(dirs).toContain('src');
  1338. expect(dirs).not.toContain('docs');
  1339. } finally {
  1340. fs.rmSync(tempProject, { recursive: true });
  1341. }
  1342. });
  1343. // Documents the cross-language `.h` behavior. Objective-C and C++ share
  1344. // the `.h` extension, so in a mixed iOS-style project an Obj-C header
  1345. // dir gets claimed as a C/C++ include dir too. That's intentional — a
  1346. // C++ file legitimately can `#include "Foo.h"` against an Obj-C header
  1347. // (Obj-C++ / .mm callers), and false-positive inclusion is far cheaper
  1348. // than missing real resolutions. The test pins this so a later
  1349. // "exclude objc dirs" refactor breaks loudly and reviewers see the
  1350. // trade-off explicitly.
  1351. it('heuristic claims any top-level dir containing .h files, including Obj-C', () => {
  1352. const tempProject = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-cpp-test-'));
  1353. try {
  1354. // C++ side: an `cppmod` dir with a .hpp (C++-only extension)
  1355. fs.mkdirSync(path.join(tempProject, 'cppmod'), { recursive: true });
  1356. fs.writeFileSync(path.join(tempProject, 'cppmod', 'shared.hpp'), '');
  1357. // Obj-C side: an `iosmod` dir with .h + .m (no .cpp/.hpp).
  1358. fs.mkdirSync(path.join(tempProject, 'iosmod'), { recursive: true });
  1359. fs.writeFileSync(path.join(tempProject, 'iosmod', 'View.h'), '');
  1360. fs.writeFileSync(path.join(tempProject, 'iosmod', 'View.m'), '');
  1361. clearCppIncludeDirCache();
  1362. const dirs = loadCppIncludeDirs(tempProject);
  1363. // Both included — Obj-C dirs are intentionally allowed.
  1364. expect(dirs).toContain('cppmod');
  1365. expect(dirs).toContain('iosmod');
  1366. } finally {
  1367. fs.rmSync(tempProject, { recursive: true });
  1368. }
  1369. });
  1370. // End-to-end: ensure `#include "X.h"` produces a file→file `imports` edge
  1371. // in the actual indexing pipeline (not just a phantom file→import-node
  1372. // edge). This pins the include-dir resolution path so the headline PR
  1373. // feature can't silently regress to a no-op in the indexing flow.
  1374. it('connects #include to the real header file via include-dir scan (end-to-end)', async () => {
  1375. const tempProject = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-cpp-e2e-'));
  1376. try {
  1377. fs.mkdirSync(path.join(tempProject, 'include'), { recursive: true });
  1378. fs.mkdirSync(path.join(tempProject, 'src'), { recursive: true });
  1379. fs.writeFileSync(
  1380. path.join(tempProject, 'include', 'utils.h'),
  1381. `#ifndef UTILS_H\n#define UTILS_H\nint add(int, int);\n#endif\n`
  1382. );
  1383. fs.writeFileSync(
  1384. path.join(tempProject, 'src', 'main.cpp'),
  1385. `#include "utils.h"\n#include <vector>\nint main(){ return add(1,2); }\n`
  1386. );
  1387. clearCppIncludeDirCache();
  1388. cg = await CodeGraph.init(tempProject, { index: true });
  1389. // Sanity: file nodes exist for the header and the cpp.
  1390. const allFiles = cg.getStats();
  1391. expect(allFiles.fileCount).toBe(2);
  1392. // The `#include "utils.h"` edge should target the real
  1393. // `include/utils.h` file node — not a floating `import` node
  1394. // living inside main.cpp.
  1395. const db = DatabaseConnection.open(path.join(tempProject, '.codegraph', 'codegraph.db'));
  1396. const rows = db.getDb().prepare(`
  1397. select dst.kind as dstKind, dst.file_path as dstPath
  1398. from edges e
  1399. join nodes src on e.source = src.id
  1400. join nodes dst on e.target = dst.id
  1401. where e.kind = 'imports'
  1402. and src.kind = 'file'
  1403. and src.file_path = 'src/main.cpp'
  1404. `).all() as Array<{ dstKind: string; dstPath: string }>;
  1405. const resolvedToHeader = rows.find(
  1406. (r) => r.dstKind === 'file' && r.dstPath === 'include/utils.h'
  1407. );
  1408. expect(resolvedToHeader, 'main.cpp → include/utils.h imports edge missing').toBeDefined();
  1409. // `<vector>` should NOT produce a file edge — it's a stdlib header.
  1410. const stdlibFile = rows.find(
  1411. (r) => r.dstKind === 'file' && r.dstPath && r.dstPath.endsWith('vector')
  1412. );
  1413. expect(stdlibFile).toBeUndefined();
  1414. } finally {
  1415. fs.rmSync(tempProject, { recursive: true, force: true });
  1416. }
  1417. });
  1418. });
  1419. });