extraction.test.ts 87 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765
  1. /**
  2. * Extraction Tests
  3. *
  4. * Tests for the tree-sitter extraction system.
  5. */
  6. import { describe, it, expect, beforeAll, 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 { extractFromSource, scanDirectory, shouldIncludeFile } from '../src/extraction';
  12. import { detectLanguage, isLanguageSupported, getSupportedLanguages, initGrammars } from '../src/extraction/grammars';
  13. import { normalizePath } from '../src/utils';
  14. import { DEFAULT_CONFIG } from '../src/types';
  15. beforeAll(async () => {
  16. await initGrammars();
  17. });
  18. // Create a temporary directory for each test
  19. function createTempDir(): string {
  20. return fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-test-'));
  21. }
  22. // Clean up temporary directory
  23. function cleanupTempDir(dir: string): void {
  24. if (fs.existsSync(dir)) {
  25. fs.rmSync(dir, { recursive: true, force: true });
  26. }
  27. }
  28. describe('Language Detection', () => {
  29. it('should detect TypeScript files', () => {
  30. expect(detectLanguage('src/index.ts')).toBe('typescript');
  31. expect(detectLanguage('components/Button.tsx')).toBe('tsx');
  32. });
  33. it('should detect JavaScript files', () => {
  34. expect(detectLanguage('index.js')).toBe('javascript');
  35. expect(detectLanguage('App.jsx')).toBe('jsx');
  36. expect(detectLanguage('config.mjs')).toBe('javascript');
  37. });
  38. it('should detect Python files', () => {
  39. expect(detectLanguage('main.py')).toBe('python');
  40. });
  41. it('should detect Go files', () => {
  42. expect(detectLanguage('main.go')).toBe('go');
  43. });
  44. it('should detect Rust files', () => {
  45. expect(detectLanguage('lib.rs')).toBe('rust');
  46. });
  47. it('should detect Java files', () => {
  48. expect(detectLanguage('Main.java')).toBe('java');
  49. });
  50. it('should detect C files', () => {
  51. expect(detectLanguage('main.c')).toBe('c');
  52. expect(detectLanguage('utils.h')).toBe('c');
  53. });
  54. it('should detect C++ files', () => {
  55. expect(detectLanguage('main.cpp')).toBe('cpp');
  56. expect(detectLanguage('class.hpp')).toBe('cpp');
  57. });
  58. it('should detect C# files', () => {
  59. expect(detectLanguage('Program.cs')).toBe('csharp');
  60. });
  61. it('should detect PHP files', () => {
  62. expect(detectLanguage('index.php')).toBe('php');
  63. });
  64. it('should detect Ruby files', () => {
  65. expect(detectLanguage('app.rb')).toBe('ruby');
  66. });
  67. it('should detect Swift files', () => {
  68. expect(detectLanguage('ViewController.swift')).toBe('swift');
  69. });
  70. it('should detect Kotlin files', () => {
  71. expect(detectLanguage('MainActivity.kt')).toBe('kotlin');
  72. expect(detectLanguage('build.gradle.kts')).toBe('kotlin');
  73. });
  74. it('should detect Dart files', () => {
  75. expect(detectLanguage('main.dart')).toBe('dart');
  76. });
  77. it('should return unknown for unsupported extensions', () => {
  78. expect(detectLanguage('styles.css')).toBe('unknown');
  79. expect(detectLanguage('data.json')).toBe('unknown');
  80. });
  81. });
  82. describe('Language Support', () => {
  83. it('should report supported languages', () => {
  84. expect(isLanguageSupported('typescript')).toBe(true);
  85. expect(isLanguageSupported('python')).toBe(true);
  86. expect(isLanguageSupported('go')).toBe(true);
  87. expect(isLanguageSupported('unknown')).toBe(false);
  88. });
  89. it('should list all supported languages', () => {
  90. const languages = getSupportedLanguages();
  91. expect(languages).toContain('typescript');
  92. expect(languages).toContain('javascript');
  93. expect(languages).toContain('python');
  94. expect(languages).toContain('go');
  95. expect(languages).toContain('rust');
  96. expect(languages).toContain('java');
  97. expect(languages).toContain('csharp');
  98. expect(languages).toContain('php');
  99. expect(languages).toContain('ruby');
  100. expect(languages).toContain('swift');
  101. expect(languages).toContain('kotlin');
  102. expect(languages).toContain('dart');
  103. });
  104. });
  105. describe('TypeScript Extraction', () => {
  106. it('should extract function declarations', () => {
  107. const code = `
  108. export function processPayment(amount: number): Promise<Receipt> {
  109. return stripe.charge(amount);
  110. }
  111. `;
  112. const result = extractFromSource('payment.ts', code);
  113. // File node + function node
  114. const fileNode = result.nodes.find((n) => n.kind === 'file');
  115. expect(fileNode).toBeDefined();
  116. expect(fileNode?.name).toBe('payment.ts');
  117. const funcNode = result.nodes.find((n) => n.kind === 'function');
  118. expect(funcNode).toMatchObject({
  119. kind: 'function',
  120. name: 'processPayment',
  121. language: 'typescript',
  122. isExported: true,
  123. });
  124. expect(funcNode?.signature).toContain('amount: number');
  125. });
  126. it('should extract class declarations', () => {
  127. const code = `
  128. export class PaymentService {
  129. private stripe: StripeClient;
  130. constructor(apiKey: string) {
  131. this.stripe = new StripeClient(apiKey);
  132. }
  133. async charge(amount: number): Promise<Receipt> {
  134. return this.stripe.charge(amount);
  135. }
  136. }
  137. `;
  138. const result = extractFromSource('service.ts', code);
  139. const classNode = result.nodes.find((n) => n.kind === 'class');
  140. const methodNodes = result.nodes.filter((n) => n.kind === 'method');
  141. expect(classNode).toBeDefined();
  142. expect(classNode?.name).toBe('PaymentService');
  143. expect(classNode?.isExported).toBe(true);
  144. expect(methodNodes.length).toBeGreaterThanOrEqual(1);
  145. const chargeMethod = methodNodes.find((m) => m.name === 'charge');
  146. expect(chargeMethod).toBeDefined();
  147. });
  148. it('should extract interfaces', () => {
  149. const code = `
  150. export interface User {
  151. id: string;
  152. name: string;
  153. email: string;
  154. }
  155. `;
  156. const result = extractFromSource('types.ts', code);
  157. const fileNode = result.nodes.find((n) => n.kind === 'file');
  158. expect(fileNode).toBeDefined();
  159. const ifaceNode = result.nodes.find((n) => n.kind === 'interface');
  160. expect(ifaceNode).toMatchObject({
  161. kind: 'interface',
  162. name: 'User',
  163. isExported: true,
  164. });
  165. });
  166. it('should track function calls', () => {
  167. const code = `
  168. function main() {
  169. const result = processData();
  170. console.log(result);
  171. }
  172. `;
  173. const result = extractFromSource('main.ts', code);
  174. expect(result.unresolvedReferences.length).toBeGreaterThan(0);
  175. const calls = result.unresolvedReferences.filter((r) => r.referenceKind === 'calls');
  176. expect(calls.some((c) => c.referenceName === 'processData')).toBe(true);
  177. });
  178. });
  179. describe('Arrow Function Export Extraction', () => {
  180. it('should extract exported arrow functions assigned to const', () => {
  181. const code = `
  182. export const useAuth = (): AuthContextValue => {
  183. return useContext(AuthContext);
  184. };
  185. `;
  186. const result = extractFromSource('hooks.ts', code);
  187. const funcNode = result.nodes.find((n) => n.kind === 'function' && n.name === 'useAuth');
  188. expect(funcNode).toBeDefined();
  189. expect(funcNode).toMatchObject({
  190. kind: 'function',
  191. name: 'useAuth',
  192. isExported: true,
  193. });
  194. });
  195. it('should extract exported function expressions assigned to const', () => {
  196. const code = `
  197. export const processData = function(input: string): string {
  198. return input.trim();
  199. };
  200. `;
  201. const result = extractFromSource('utils.ts', code);
  202. const funcNode = result.nodes.find((n) => n.kind === 'function' && n.name === 'processData');
  203. expect(funcNode).toBeDefined();
  204. expect(funcNode).toMatchObject({
  205. kind: 'function',
  206. name: 'processData',
  207. isExported: true,
  208. });
  209. });
  210. it('should not extract non-exported arrow functions as exported', () => {
  211. const code = `
  212. const internalHelper = () => {
  213. return 42;
  214. };
  215. `;
  216. const result = extractFromSource('internal.ts', code);
  217. const helperNode = result.nodes.find((n) => n.name === 'internalHelper');
  218. expect(helperNode).toBeDefined();
  219. expect(helperNode?.isExported).toBeFalsy();
  220. });
  221. it('should still skip truly anonymous arrow functions', () => {
  222. const code = `
  223. const items = [1, 2, 3].map((x) => x * 2);
  224. `;
  225. const result = extractFromSource('anon.ts', code);
  226. // The inline arrow function passed to .map() has no variable_declarator parent
  227. // and should remain anonymous (skipped)
  228. const anonFunctions = result.nodes.filter(
  229. (n) => n.kind === 'function' && n.name === '<anonymous>'
  230. );
  231. expect(anonFunctions).toHaveLength(0);
  232. });
  233. it('should extract multiple exported arrow functions from the same file', () => {
  234. const code = `
  235. export const add = (a: number, b: number): number => a + b;
  236. export const subtract = (a: number, b: number): number => a - b;
  237. const internal = () => 'not exported';
  238. `;
  239. const result = extractFromSource('math.ts', code);
  240. const exported = result.nodes.filter((n) => n.kind === 'function' && n.isExported);
  241. expect(exported).toHaveLength(2);
  242. expect(exported.map((n) => n.name).sort()).toEqual(['add', 'subtract']);
  243. const internalNode = result.nodes.find((n) => n.name === 'internal');
  244. expect(internalNode).toBeDefined();
  245. expect(internalNode?.isExported).toBeFalsy();
  246. });
  247. it('should extract arrow functions in JavaScript files', () => {
  248. const code = `
  249. export const fetchData = async () => {
  250. const response = await fetch('/api/data');
  251. return response.json();
  252. };
  253. `;
  254. const result = extractFromSource('api.js', code);
  255. const funcNode = result.nodes.find((n) => n.kind === 'function' && n.name === 'fetchData');
  256. expect(funcNode).toBeDefined();
  257. expect(funcNode).toMatchObject({
  258. kind: 'function',
  259. name: 'fetchData',
  260. isExported: true,
  261. });
  262. });
  263. });
  264. describe('Type Alias Extraction', () => {
  265. it('should extract exported type aliases in TypeScript', () => {
  266. const code = `
  267. export type AuthContextValue = {
  268. user: User | null;
  269. login: () => void;
  270. logout: () => void;
  271. };
  272. `;
  273. const result = extractFromSource('types.ts', code);
  274. const typeNode = result.nodes.find((n) => n.kind === 'type_alias');
  275. expect(typeNode).toMatchObject({
  276. kind: 'type_alias',
  277. name: 'AuthContextValue',
  278. isExported: true,
  279. });
  280. });
  281. it('should extract non-exported type aliases', () => {
  282. const code = `
  283. type InternalState = {
  284. loading: boolean;
  285. error: string | null;
  286. };
  287. `;
  288. const result = extractFromSource('internal.ts', code);
  289. const typeNode = result.nodes.find((n) => n.kind === 'type_alias');
  290. expect(typeNode).toMatchObject({
  291. kind: 'type_alias',
  292. name: 'InternalState',
  293. isExported: false,
  294. });
  295. });
  296. it('should extract multiple type aliases from the same file', () => {
  297. const code = `
  298. export type UnitSystem = 'metric' | 'imperial';
  299. export type DateFormat = 'ISO' | 'US' | 'EU';
  300. type Internal = string;
  301. `;
  302. const result = extractFromSource('config.ts', code);
  303. const typeAliases = result.nodes.filter((n) => n.kind === 'type_alias');
  304. expect(typeAliases).toHaveLength(3);
  305. const exported = typeAliases.filter((n) => n.isExported);
  306. expect(exported).toHaveLength(2);
  307. expect(exported.map((n) => n.name).sort()).toEqual(['DateFormat', 'UnitSystem']);
  308. });
  309. });
  310. describe('Exported Variable Extraction', () => {
  311. it('should extract exported const with call expression (Zustand store)', () => {
  312. const code = `
  313. export const useUIStore = create<UIState>((set) => ({
  314. isOpen: false,
  315. toggle: () => set((s) => ({ isOpen: !s.isOpen })),
  316. }));
  317. `;
  318. const result = extractFromSource('store.ts', code);
  319. const varNode = result.nodes.find((n) => n.kind === 'variable' && n.name === 'useUIStore');
  320. expect(varNode).toBeDefined();
  321. expect(varNode?.isExported).toBe(true);
  322. });
  323. it('should extract exported const with object literal', () => {
  324. const code = `
  325. export const config = {
  326. apiUrl: 'https://api.example.com',
  327. timeout: 5000,
  328. };
  329. `;
  330. const result = extractFromSource('config.ts', code);
  331. const varNode = result.nodes.find((n) => n.kind === 'variable' && n.name === 'config');
  332. expect(varNode).toBeDefined();
  333. expect(varNode?.isExported).toBe(true);
  334. });
  335. it('should extract exported const with array literal', () => {
  336. const code = `
  337. export const SCREEN_NAMES = ['home', 'settings', 'profile'] as const;
  338. `;
  339. const result = extractFromSource('constants.ts', code);
  340. const varNode = result.nodes.find((n) => n.kind === 'variable' && n.name === 'SCREEN_NAMES');
  341. expect(varNode).toBeDefined();
  342. expect(varNode?.isExported).toBe(true);
  343. });
  344. it('should extract exported const with primitive value', () => {
  345. const code = `
  346. export const MAX_RETRIES = 3;
  347. export const API_VERSION = "v2";
  348. `;
  349. const result = extractFromSource('constants.ts', code);
  350. const variables = result.nodes.filter((n) => n.kind === 'variable');
  351. expect(variables).toHaveLength(2);
  352. expect(variables.map((n) => n.name).sort()).toEqual(['API_VERSION', 'MAX_RETRIES']);
  353. });
  354. it('should NOT duplicate arrow functions as both function and variable', () => {
  355. const code = `
  356. export const useAuth = () => {
  357. return useContext(AuthContext);
  358. };
  359. `;
  360. const result = extractFromSource('hooks.ts', code);
  361. // Should be extracted as function (from arrow function handler), NOT as variable
  362. const funcNodes = result.nodes.filter((n) => n.kind === 'function' && n.name === 'useAuth');
  363. const varNodes = result.nodes.filter((n) => n.kind === 'variable' && n.name === 'useAuth');
  364. expect(funcNodes).toHaveLength(1);
  365. expect(varNodes).toHaveLength(0);
  366. });
  367. it('should extract non-exported const as non-exported variable', () => {
  368. const code = `
  369. const internalConfig = {
  370. debug: true,
  371. };
  372. `;
  373. const result = extractFromSource('internal.ts', code);
  374. // Non-exported const at file level should be extracted as a constant (not exported)
  375. const varNodes = result.nodes.filter((n) => (n.kind === 'variable' || n.kind === 'constant') && n.name === 'internalConfig');
  376. expect(varNodes).toHaveLength(1);
  377. expect(varNodes[0]?.isExported).toBeFalsy();
  378. });
  379. it('should extract Zod schema exports', () => {
  380. const code = `
  381. export const userSchema = z.object({
  382. id: z.string(),
  383. name: z.string(),
  384. email: z.string().email(),
  385. });
  386. `;
  387. const result = extractFromSource('schemas.ts', code);
  388. const varNode = result.nodes.find((n) => n.kind === 'variable' && n.name === 'userSchema');
  389. expect(varNode).toBeDefined();
  390. expect(varNode?.isExported).toBe(true);
  391. });
  392. it('should extract XState machine exports', () => {
  393. const code = `
  394. export const authMachine = createMachine({
  395. id: "auth",
  396. initial: "idle",
  397. states: {
  398. idle: {},
  399. authenticated: {},
  400. },
  401. });
  402. `;
  403. const result = extractFromSource('machine.ts', code);
  404. const varNode = result.nodes.find((n) => n.kind === 'variable' && n.name === 'authMachine');
  405. expect(varNode).toBeDefined();
  406. expect(varNode?.isExported).toBe(true);
  407. });
  408. });
  409. describe('File Node Extraction', () => {
  410. it('should create a file-kind node for each parsed file', () => {
  411. const code = `
  412. export function greet(name: string): string {
  413. return "Hello " + name;
  414. }
  415. `;
  416. const result = extractFromSource('greeter.ts', code);
  417. const fileNode = result.nodes.find((n) => n.kind === 'file');
  418. expect(fileNode).toBeDefined();
  419. expect(fileNode?.name).toBe('greeter.ts');
  420. expect(fileNode?.filePath).toBe('greeter.ts');
  421. expect(fileNode?.language).toBe('typescript');
  422. expect(fileNode?.startLine).toBe(1);
  423. });
  424. it('should create file nodes for Python files', () => {
  425. const code = `
  426. def main():
  427. pass
  428. `;
  429. const result = extractFromSource('main.py', code);
  430. const fileNode = result.nodes.find((n) => n.kind === 'file');
  431. expect(fileNode).toBeDefined();
  432. expect(fileNode?.name).toBe('main.py');
  433. expect(fileNode?.language).toBe('python');
  434. });
  435. it('should create containment edges from file node to top-level declarations', () => {
  436. const code = `
  437. export function foo() {}
  438. export function bar() {}
  439. `;
  440. const result = extractFromSource('fns.ts', code);
  441. const fileNode = result.nodes.find((n) => n.kind === 'file');
  442. expect(fileNode).toBeDefined();
  443. // There should be contains edges from the file node to each function
  444. const containsEdges = result.edges.filter(
  445. (e) => e.source === fileNode?.id && e.kind === 'contains'
  446. );
  447. expect(containsEdges.length).toBeGreaterThanOrEqual(2);
  448. });
  449. });
  450. describe('Python Extraction', () => {
  451. it('should extract function definitions', () => {
  452. const code = `
  453. def calculate_total(items: list, tax_rate: float) -> float:
  454. """Calculate total with tax."""
  455. subtotal = sum(item.price for item in items)
  456. return subtotal * (1 + tax_rate)
  457. `;
  458. const result = extractFromSource('calc.py', code);
  459. const fileNode = result.nodes.find((n) => n.kind === 'file');
  460. expect(fileNode).toBeDefined();
  461. const funcNode = result.nodes.find((n) => n.kind === 'function');
  462. expect(funcNode).toMatchObject({
  463. kind: 'function',
  464. name: 'calculate_total',
  465. language: 'python',
  466. });
  467. });
  468. it('should extract class definitions', () => {
  469. const code = `
  470. class UserService:
  471. """Service for managing users."""
  472. def __init__(self, db):
  473. self.db = db
  474. def get_user(self, user_id: str) -> User:
  475. return self.db.find_user(user_id)
  476. `;
  477. const result = extractFromSource('service.py', code);
  478. const classNode = result.nodes.find((n) => n.kind === 'class');
  479. expect(classNode).toBeDefined();
  480. expect(classNode?.name).toBe('UserService');
  481. });
  482. });
  483. describe('Go Extraction', () => {
  484. it('should extract function declarations', () => {
  485. const code = `
  486. package main
  487. func ProcessOrder(order Order) (Receipt, error) {
  488. // Process the order
  489. return Receipt{}, nil
  490. }
  491. `;
  492. const result = extractFromSource('main.go', code);
  493. const funcNode = result.nodes.find((n) => n.kind === 'function');
  494. expect(funcNode).toBeDefined();
  495. expect(funcNode?.name).toBe('ProcessOrder');
  496. });
  497. it('should extract method declarations', () => {
  498. const code = `
  499. package main
  500. type Service struct {
  501. db *Database
  502. }
  503. func (s *Service) GetUser(id string) (*User, error) {
  504. return s.db.FindUser(id)
  505. }
  506. `;
  507. const result = extractFromSource('service.go', code);
  508. const methodNode = result.nodes.find((n) => n.kind === 'method');
  509. expect(methodNode).toBeDefined();
  510. expect(methodNode?.name).toBe('GetUser');
  511. });
  512. });
  513. describe('Rust Extraction', () => {
  514. it('should extract function declarations', () => {
  515. const code = `
  516. pub fn process_data(input: &str) -> Result<Output, Error> {
  517. // Process data
  518. Ok(Output::new())
  519. }
  520. `;
  521. const result = extractFromSource('lib.rs', code);
  522. const funcNode = result.nodes.find((n) => n.kind === 'function');
  523. expect(funcNode).toBeDefined();
  524. expect(funcNode?.name).toBe('process_data');
  525. expect(funcNode?.visibility).toBe('public');
  526. });
  527. it('should extract struct declarations', () => {
  528. const code = `
  529. pub struct User {
  530. pub id: String,
  531. pub name: String,
  532. email: String,
  533. }
  534. `;
  535. const result = extractFromSource('models.rs', code);
  536. const structNode = result.nodes.find((n) => n.kind === 'struct');
  537. expect(structNode).toBeDefined();
  538. expect(structNode?.name).toBe('User');
  539. });
  540. it('should extract trait declarations', () => {
  541. const code = `
  542. pub trait Repository {
  543. fn find(&self, id: &str) -> Option<Entity>;
  544. fn save(&mut self, entity: Entity) -> Result<(), Error>;
  545. }
  546. `;
  547. const result = extractFromSource('traits.rs', code);
  548. const traitNode = result.nodes.find((n) => n.kind === 'trait');
  549. expect(traitNode).toBeDefined();
  550. expect(traitNode?.name).toBe('Repository');
  551. });
  552. });
  553. describe('Java Extraction', () => {
  554. it('should extract class declarations', () => {
  555. const code = `
  556. public class UserService {
  557. private final UserRepository repository;
  558. public UserService(UserRepository repository) {
  559. this.repository = repository;
  560. }
  561. public User getUser(String id) {
  562. return repository.findById(id);
  563. }
  564. }
  565. `;
  566. const result = extractFromSource('UserService.java', code);
  567. const classNode = result.nodes.find((n) => n.kind === 'class');
  568. expect(classNode).toBeDefined();
  569. expect(classNode?.name).toBe('UserService');
  570. expect(classNode?.visibility).toBe('public');
  571. });
  572. it('should extract method declarations', () => {
  573. const code = `
  574. public class Calculator {
  575. public static int add(int a, int b) {
  576. return a + b;
  577. }
  578. }
  579. `;
  580. const result = extractFromSource('Calculator.java', code);
  581. const methodNode = result.nodes.find((n) => n.kind === 'method' && n.name === 'add');
  582. expect(methodNode).toBeDefined();
  583. expect(methodNode?.isStatic).toBe(true);
  584. });
  585. });
  586. describe('C# Extraction', () => {
  587. it('should extract class declarations', () => {
  588. const code = `
  589. public class OrderService
  590. {
  591. private readonly IOrderRepository _repository;
  592. public OrderService(IOrderRepository repository)
  593. {
  594. _repository = repository;
  595. }
  596. public async Task<Order> GetOrderAsync(string id)
  597. {
  598. return await _repository.FindByIdAsync(id);
  599. }
  600. }
  601. `;
  602. const result = extractFromSource('OrderService.cs', code);
  603. const classNode = result.nodes.find((n) => n.kind === 'class');
  604. expect(classNode).toBeDefined();
  605. expect(classNode?.name).toBe('OrderService');
  606. expect(classNode?.visibility).toBe('public');
  607. });
  608. });
  609. describe('PHP Extraction', () => {
  610. it('should extract class declarations', () => {
  611. const code = `<?php
  612. class UserController
  613. {
  614. private UserService $userService;
  615. public function __construct(UserService $userService)
  616. {
  617. $this->userService = $userService;
  618. }
  619. public function show(string $id): User
  620. {
  621. return $this->userService->find($id);
  622. }
  623. }
  624. `;
  625. const result = extractFromSource('UserController.php', code);
  626. const classNode = result.nodes.find((n) => n.kind === 'class');
  627. expect(classNode).toBeDefined();
  628. expect(classNode?.name).toBe('UserController');
  629. });
  630. });
  631. describe('Swift Extraction', () => {
  632. it('should extract class declarations', () => {
  633. const code = `
  634. public class NetworkManager {
  635. private let session: URLSession
  636. public init(session: URLSession = .shared) {
  637. self.session = session
  638. }
  639. public func fetchData(from url: URL) async throws -> Data {
  640. let (data, _) = try await session.data(from: url)
  641. return data
  642. }
  643. }
  644. `;
  645. const result = extractFromSource('NetworkManager.swift', code);
  646. const classNode = result.nodes.find((n) => n.kind === 'class');
  647. expect(classNode).toBeDefined();
  648. expect(classNode?.name).toBe('NetworkManager');
  649. });
  650. it('should extract function declarations', () => {
  651. const code = `
  652. func calculateSum(_ numbers: [Int]) -> Int {
  653. return numbers.reduce(0, +)
  654. }
  655. public func formatCurrency(amount: Double) -> String {
  656. return String(format: "$%.2f", amount)
  657. }
  658. `;
  659. const result = extractFromSource('utils.swift', code);
  660. const functions = result.nodes.filter((n) => n.kind === 'function');
  661. expect(functions.length).toBeGreaterThanOrEqual(1);
  662. });
  663. it('should extract struct declarations', () => {
  664. const code = `
  665. public struct User {
  666. let id: UUID
  667. var name: String
  668. var email: String
  669. func displayName() -> String {
  670. return name
  671. }
  672. }
  673. `;
  674. const result = extractFromSource('User.swift', code);
  675. const structNode = result.nodes.find((n) => n.kind === 'struct');
  676. expect(structNode).toBeDefined();
  677. expect(structNode?.name).toBe('User');
  678. });
  679. it('should extract protocol declarations', () => {
  680. const code = `
  681. public protocol Repository {
  682. associatedtype Entity
  683. func find(id: String) async throws -> Entity?
  684. func save(_ entity: Entity) async throws
  685. }
  686. `;
  687. const result = extractFromSource('Repository.swift', code);
  688. const protocolNode = result.nodes.find((n) => n.kind === 'interface');
  689. expect(protocolNode).toBeDefined();
  690. expect(protocolNode?.name).toBe('Repository');
  691. });
  692. });
  693. describe('Kotlin Extraction', () => {
  694. it('should extract class declarations', () => {
  695. const code = `
  696. class UserRepository(private val database: Database) {
  697. fun findById(id: String): User? {
  698. return database.query("SELECT * FROM users WHERE id = ?", id)
  699. }
  700. suspend fun save(user: User) {
  701. database.insert(user)
  702. }
  703. }
  704. `;
  705. const result = extractFromSource('UserRepository.kt', code);
  706. const classNode = result.nodes.find((n) => n.kind === 'class');
  707. expect(classNode).toBeDefined();
  708. expect(classNode?.name).toBe('UserRepository');
  709. });
  710. it('should extract function declarations', () => {
  711. const code = `
  712. fun calculateTotal(items: List<Item>): Double {
  713. return items.sumOf { it.price }
  714. }
  715. suspend fun fetchUserData(userId: String): User {
  716. return api.getUser(userId)
  717. }
  718. `;
  719. const result = extractFromSource('utils.kt', code);
  720. const functions = result.nodes.filter((n) => n.kind === 'function');
  721. expect(functions.length).toBeGreaterThanOrEqual(1);
  722. });
  723. it('should detect suspend functions as async', () => {
  724. const code = `
  725. suspend fun loadData(): List<String> {
  726. delay(1000)
  727. return listOf("a", "b", "c")
  728. }
  729. `;
  730. const result = extractFromSource('loader.kt', code);
  731. const funcNode = result.nodes.find((n) => n.kind === 'function');
  732. expect(funcNode).toBeDefined();
  733. expect(funcNode?.isAsync).toBe(true);
  734. });
  735. });
  736. describe('Dart Extraction', () => {
  737. it('should extract class declarations', () => {
  738. const code = `
  739. class UserService {
  740. final Database _db;
  741. Future<User> findById(String id) async {
  742. return await _db.query(id);
  743. }
  744. void _privateMethod() {}
  745. }
  746. `;
  747. const result = extractFromSource('service.dart', code);
  748. const classNode = result.nodes.find((n) => n.kind === 'class');
  749. expect(classNode).toBeDefined();
  750. expect(classNode?.name).toBe('UserService');
  751. expect(classNode?.visibility).toBe('public');
  752. const methodNodes = result.nodes.filter((n) => n.kind === 'method');
  753. expect(methodNodes.length).toBeGreaterThanOrEqual(2);
  754. const findById = methodNodes.find((m) => m.name === 'findById');
  755. expect(findById).toBeDefined();
  756. expect(findById?.isAsync).toBe(true);
  757. const privateMethod = methodNodes.find((m) => m.name === '_privateMethod');
  758. expect(privateMethod).toBeDefined();
  759. expect(privateMethod?.visibility).toBe('private');
  760. });
  761. it('should extract top-level function declarations', () => {
  762. const code = `
  763. void topLevelFunction(String name) {
  764. print(name);
  765. }
  766. `;
  767. const result = extractFromSource('utils.dart', code);
  768. const funcNode = result.nodes.find((n) => n.kind === 'function');
  769. expect(funcNode).toBeDefined();
  770. expect(funcNode?.name).toBe('topLevelFunction');
  771. expect(funcNode?.language).toBe('dart');
  772. });
  773. it('should extract enum declarations', () => {
  774. const code = `
  775. enum Status { active, inactive, pending }
  776. `;
  777. const result = extractFromSource('models.dart', code);
  778. const enumNode = result.nodes.find((n) => n.kind === 'enum');
  779. expect(enumNode).toBeDefined();
  780. expect(enumNode?.name).toBe('Status');
  781. });
  782. it('should extract mixin declarations', () => {
  783. const code = `
  784. mixin LoggerMixin {
  785. void log(String message) {}
  786. }
  787. `;
  788. const result = extractFromSource('mixins.dart', code);
  789. const classNode = result.nodes.find((n) => n.kind === 'class');
  790. expect(classNode).toBeDefined();
  791. expect(classNode?.name).toBe('LoggerMixin');
  792. const methodNode = result.nodes.find((n) => n.kind === 'method');
  793. expect(methodNode).toBeDefined();
  794. expect(methodNode?.name).toBe('log');
  795. });
  796. it('should extract extension declarations', () => {
  797. const code = `
  798. extension StringExt on String {
  799. bool get isBlank => trim().isEmpty;
  800. }
  801. `;
  802. const result = extractFromSource('extensions.dart', code);
  803. const classNode = result.nodes.find((n) => n.kind === 'class');
  804. expect(classNode).toBeDefined();
  805. expect(classNode?.name).toBe('StringExt');
  806. });
  807. it('should detect static methods', () => {
  808. const code = `
  809. class Utils {
  810. static void doWork() {}
  811. }
  812. `;
  813. const result = extractFromSource('utils.dart', code);
  814. const methodNode = result.nodes.find((n) => n.kind === 'method');
  815. expect(methodNode).toBeDefined();
  816. expect(methodNode?.name).toBe('doWork');
  817. expect(methodNode?.isStatic).toBe(true);
  818. });
  819. it('should detect async functions', () => {
  820. const code = `
  821. Future<String> fetchData() async {
  822. return await http.get('/data');
  823. }
  824. `;
  825. const result = extractFromSource('api.dart', code);
  826. const funcNode = result.nodes.find((n) => n.kind === 'function');
  827. expect(funcNode).toBeDefined();
  828. expect(funcNode?.name).toBe('fetchData');
  829. expect(funcNode?.isAsync).toBe(true);
  830. });
  831. it('should detect private visibility via underscore convention', () => {
  832. const code = `
  833. void _privateHelper() {}
  834. void publicFunction() {}
  835. `;
  836. const result = extractFromSource('helpers.dart', code);
  837. const functions = result.nodes.filter((n) => n.kind === 'function');
  838. const privateFunc = functions.find((f) => f.name === '_privateHelper');
  839. const publicFunc = functions.find((f) => f.name === 'publicFunction');
  840. expect(privateFunc?.visibility).toBe('private');
  841. expect(publicFunc?.visibility).toBe('public');
  842. });
  843. });
  844. describe('Import Extraction', () => {
  845. describe('TypeScript/JavaScript imports', () => {
  846. it('should extract default imports', () => {
  847. const code = `import React from 'react';`;
  848. const result = extractFromSource('app.tsx', code);
  849. const importNode = result.nodes.find((n) => n.kind === 'import');
  850. expect(importNode).toBeDefined();
  851. expect(importNode?.name).toBe('react');
  852. expect(importNode?.signature).toBe("import React from 'react';");
  853. });
  854. it('should extract named imports', () => {
  855. const code = `import { Bug, Database } from '@phosphor-icons/react';`;
  856. const result = extractFromSource('icons.tsx', code);
  857. const importNode = result.nodes.find((n) => n.kind === 'import');
  858. expect(importNode).toBeDefined();
  859. expect(importNode?.name).toBe('@phosphor-icons/react');
  860. expect(importNode?.signature).toContain('Bug');
  861. expect(importNode?.signature).toContain('Database');
  862. });
  863. it('should extract namespace imports', () => {
  864. const code = `import * as Icons from '@phosphor-icons/react';`;
  865. const result = extractFromSource('icons.tsx', code);
  866. const importNode = result.nodes.find((n) => n.kind === 'import');
  867. expect(importNode).toBeDefined();
  868. expect(importNode?.name).toBe('@phosphor-icons/react');
  869. expect(importNode?.signature).toContain('* as Icons');
  870. });
  871. it('should extract side-effect imports', () => {
  872. const code = `import './styles.css';`;
  873. const result = extractFromSource('app.tsx', code);
  874. const importNode = result.nodes.find((n) => n.kind === 'import');
  875. expect(importNode).toBeDefined();
  876. expect(importNode?.name).toBe('./styles.css');
  877. });
  878. it('should extract mixed imports (default + named)', () => {
  879. const code = `import React, { useState, useEffect } from 'react';`;
  880. const result = extractFromSource('app.tsx', code);
  881. const importNode = result.nodes.find((n) => n.kind === 'import');
  882. expect(importNode).toBeDefined();
  883. expect(importNode?.name).toBe('react');
  884. expect(importNode?.signature).toContain('React');
  885. expect(importNode?.signature).toContain('useState');
  886. expect(importNode?.signature).toContain('useEffect');
  887. });
  888. it('should extract multiple import statements', () => {
  889. const code = `
  890. import React from 'react';
  891. import { Button } from './components';
  892. import './styles.css';
  893. `;
  894. const result = extractFromSource('app.tsx', code);
  895. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  896. expect(importNodes.length).toBe(3);
  897. const names = importNodes.map((n) => n.name);
  898. expect(names).toContain('react');
  899. expect(names).toContain('./components');
  900. expect(names).toContain('./styles.css');
  901. });
  902. it('should extract type imports', () => {
  903. const code = `import type { FC, ReactNode } from 'react';`;
  904. const result = extractFromSource('types.ts', code);
  905. const importNode = result.nodes.find((n) => n.kind === 'import');
  906. expect(importNode).toBeDefined();
  907. expect(importNode?.name).toBe('react');
  908. expect(importNode?.signature).toContain('type');
  909. expect(importNode?.signature).toContain('FC');
  910. });
  911. it('should extract aliased named imports', () => {
  912. const code = `import { useState as useStateAlias } from 'react';`;
  913. const result = extractFromSource('hooks.ts', code);
  914. const importNode = result.nodes.find((n) => n.kind === 'import');
  915. expect(importNode).toBeDefined();
  916. expect(importNode?.name).toBe('react');
  917. expect(importNode?.signature).toContain('useState');
  918. expect(importNode?.signature).toContain('useStateAlias');
  919. });
  920. it('should extract relative path imports', () => {
  921. const code = `import { helper } from '../utils/helper';`;
  922. const result = extractFromSource('components/Button.tsx', code);
  923. const importNode = result.nodes.find((n) => n.kind === 'import');
  924. expect(importNode).toBeDefined();
  925. expect(importNode?.name).toBe('../utils/helper');
  926. expect(importNode?.signature).toContain('helper');
  927. });
  928. });
  929. describe('Python imports', () => {
  930. it('should extract simple import statement', () => {
  931. const code = `import json`;
  932. const result = extractFromSource('utils.py', code);
  933. const importNode = result.nodes.find((n) => n.kind === 'import');
  934. expect(importNode).toBeDefined();
  935. expect(importNode?.name).toBe('json');
  936. });
  937. it('should extract from import statement', () => {
  938. const code = `from os import path`;
  939. const result = extractFromSource('utils.py', code);
  940. const importNode = result.nodes.find((n) => n.kind === 'import');
  941. expect(importNode).toBeDefined();
  942. expect(importNode?.name).toBe('os');
  943. expect(importNode?.signature).toContain('path');
  944. });
  945. it('should extract multiple imports from same module', () => {
  946. const code = `from typing import List, Dict, Optional`;
  947. const result = extractFromSource('types.py', code);
  948. const importNode = result.nodes.find((n) => n.kind === 'import');
  949. expect(importNode).toBeDefined();
  950. expect(importNode?.name).toBe('typing');
  951. expect(importNode?.signature).toContain('List');
  952. expect(importNode?.signature).toContain('Dict');
  953. });
  954. it('should extract multiple import statements', () => {
  955. const code = `
  956. import os
  957. import sys
  958. `;
  959. const result = extractFromSource('main.py', code);
  960. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  961. expect(importNodes.length).toBe(2);
  962. const names = importNodes.map((n) => n.name);
  963. expect(names).toContain('os');
  964. expect(names).toContain('sys');
  965. });
  966. it('should extract aliased import', () => {
  967. const code = `import numpy as np`;
  968. const result = extractFromSource('data.py', code);
  969. const importNode = result.nodes.find((n) => n.kind === 'import');
  970. expect(importNode).toBeDefined();
  971. expect(importNode?.name).toBe('numpy');
  972. expect(importNode?.signature).toContain('as np');
  973. });
  974. it('should extract relative import', () => {
  975. const code = `from .utils import helper`;
  976. const result = extractFromSource('module.py', code);
  977. const importNode = result.nodes.find((n) => n.kind === 'import');
  978. expect(importNode).toBeDefined();
  979. expect(importNode?.name).toBe('.utils');
  980. expect(importNode?.signature).toContain('helper');
  981. });
  982. it('should extract wildcard import', () => {
  983. const code = `from typing import *`;
  984. const result = extractFromSource('types.py', code);
  985. const importNode = result.nodes.find((n) => n.kind === 'import');
  986. expect(importNode).toBeDefined();
  987. expect(importNode?.name).toBe('typing');
  988. expect(importNode?.signature).toContain('*');
  989. });
  990. });
  991. describe('Rust imports', () => {
  992. it('should extract simple use declaration', () => {
  993. const code = `use std::io;`;
  994. const result = extractFromSource('main.rs', code);
  995. const importNode = result.nodes.find((n) => n.kind === 'import');
  996. expect(importNode).toBeDefined();
  997. expect(importNode?.name).toBe('std');
  998. expect(importNode?.signature).toBe('use std::io;');
  999. });
  1000. it('should extract scoped use list', () => {
  1001. const code = `use std::{ffi::OsStr, io, path::Path};`;
  1002. const result = extractFromSource('main.rs', code);
  1003. const importNode = result.nodes.find((n) => n.kind === 'import');
  1004. expect(importNode).toBeDefined();
  1005. expect(importNode?.name).toBe('std');
  1006. expect(importNode?.signature).toContain('ffi::OsStr');
  1007. expect(importNode?.signature).toContain('path::Path');
  1008. });
  1009. it('should extract crate imports', () => {
  1010. const code = `use crate::error::Error;`;
  1011. const result = extractFromSource('lib.rs', code);
  1012. const importNode = result.nodes.find((n) => n.kind === 'import');
  1013. expect(importNode).toBeDefined();
  1014. expect(importNode?.name).toBe('crate');
  1015. });
  1016. it('should extract super imports', () => {
  1017. const code = `use super::utils;`;
  1018. const result = extractFromSource('submod.rs', code);
  1019. const importNode = result.nodes.find((n) => n.kind === 'import');
  1020. expect(importNode).toBeDefined();
  1021. expect(importNode?.name).toBe('super');
  1022. });
  1023. it('should extract external crate imports', () => {
  1024. const code = `use serde::{Serialize, Deserialize};`;
  1025. const result = extractFromSource('types.rs', code);
  1026. const importNode = result.nodes.find((n) => n.kind === 'import');
  1027. expect(importNode).toBeDefined();
  1028. expect(importNode?.name).toBe('serde');
  1029. expect(importNode?.signature).toContain('Serialize');
  1030. expect(importNode?.signature).toContain('Deserialize');
  1031. });
  1032. });
  1033. describe('Go imports', () => {
  1034. it('should extract single import', () => {
  1035. const code = `
  1036. package main
  1037. import "fmt"
  1038. `;
  1039. const result = extractFromSource('main.go', code);
  1040. const importNode = result.nodes.find((n) => n.kind === 'import');
  1041. expect(importNode).toBeDefined();
  1042. expect(importNode?.name).toBe('fmt');
  1043. });
  1044. it('should extract grouped imports', () => {
  1045. const code = `
  1046. package main
  1047. import (
  1048. "fmt"
  1049. "os"
  1050. "encoding/json"
  1051. )
  1052. `;
  1053. const result = extractFromSource('main.go', code);
  1054. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1055. expect(importNodes.length).toBe(3);
  1056. const names = importNodes.map((n) => n.name);
  1057. expect(names).toContain('fmt');
  1058. expect(names).toContain('os');
  1059. expect(names).toContain('encoding/json');
  1060. });
  1061. it('should extract aliased import', () => {
  1062. const code = `
  1063. package main
  1064. import f "fmt"
  1065. `;
  1066. const result = extractFromSource('main.go', code);
  1067. const importNode = result.nodes.find((n) => n.kind === 'import');
  1068. expect(importNode).toBeDefined();
  1069. expect(importNode?.name).toBe('fmt');
  1070. expect(importNode?.signature).toContain('f');
  1071. });
  1072. it('should extract dot import', () => {
  1073. const code = `
  1074. package main
  1075. import . "math"
  1076. `;
  1077. const result = extractFromSource('main.go', code);
  1078. const importNode = result.nodes.find((n) => n.kind === 'import');
  1079. expect(importNode).toBeDefined();
  1080. expect(importNode?.name).toBe('math');
  1081. expect(importNode?.signature).toContain('.');
  1082. });
  1083. it('should extract blank import', () => {
  1084. const code = `
  1085. package main
  1086. import _ "github.com/go-sql-driver/mysql"
  1087. `;
  1088. const result = extractFromSource('main.go', code);
  1089. const importNode = result.nodes.find((n) => n.kind === 'import');
  1090. expect(importNode).toBeDefined();
  1091. expect(importNode?.name).toBe('github.com/go-sql-driver/mysql');
  1092. expect(importNode?.signature).toContain('_');
  1093. });
  1094. });
  1095. describe('Swift imports', () => {
  1096. it('should extract simple import', () => {
  1097. const code = `import Foundation`;
  1098. const result = extractFromSource('main.swift', code);
  1099. const importNode = result.nodes.find((n) => n.kind === 'import');
  1100. expect(importNode).toBeDefined();
  1101. expect(importNode?.name).toBe('Foundation');
  1102. expect(importNode?.signature).toBe('import Foundation');
  1103. });
  1104. it('should extract @testable import', () => {
  1105. const code = `@testable import Alamofire`;
  1106. const result = extractFromSource('Tests.swift', code);
  1107. const importNode = result.nodes.find((n) => n.kind === 'import');
  1108. expect(importNode).toBeDefined();
  1109. expect(importNode?.name).toBe('Alamofire');
  1110. expect(importNode?.signature).toContain('@testable');
  1111. });
  1112. it('should extract @preconcurrency import', () => {
  1113. const code = `@preconcurrency import Security`;
  1114. const result = extractFromSource('Auth.swift', code);
  1115. const importNode = result.nodes.find((n) => n.kind === 'import');
  1116. expect(importNode).toBeDefined();
  1117. expect(importNode?.name).toBe('Security');
  1118. });
  1119. it('should extract multiple imports', () => {
  1120. const code = `
  1121. import Foundation
  1122. import UIKit
  1123. import Alamofire
  1124. `;
  1125. const result = extractFromSource('App.swift', code);
  1126. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1127. expect(importNodes.length).toBe(3);
  1128. const names = importNodes.map((n) => n.name);
  1129. expect(names).toContain('Foundation');
  1130. expect(names).toContain('UIKit');
  1131. expect(names).toContain('Alamofire');
  1132. });
  1133. });
  1134. describe('Kotlin imports', () => {
  1135. it('should extract simple import', () => {
  1136. const code = `import java.io.IOException`;
  1137. const result = extractFromSource('Main.kt', code);
  1138. const importNode = result.nodes.find((n) => n.kind === 'import');
  1139. expect(importNode).toBeDefined();
  1140. expect(importNode?.name).toBe('java.io.IOException');
  1141. expect(importNode?.signature).toBe('import java.io.IOException');
  1142. });
  1143. it('should extract aliased import', () => {
  1144. const code = `import okhttp3.Request.Builder as RequestBuilder`;
  1145. const result = extractFromSource('Utils.kt', code);
  1146. const importNode = result.nodes.find((n) => n.kind === 'import');
  1147. expect(importNode).toBeDefined();
  1148. expect(importNode?.name).toBe('okhttp3.Request.Builder');
  1149. expect(importNode?.signature).toContain('as RequestBuilder');
  1150. });
  1151. it('should extract wildcard import', () => {
  1152. const code = `import java.util.concurrent.TimeUnit.*`;
  1153. const result = extractFromSource('Time.kt', code);
  1154. const importNode = result.nodes.find((n) => n.kind === 'import');
  1155. expect(importNode).toBeDefined();
  1156. expect(importNode?.name).toBe('java.util.concurrent.TimeUnit');
  1157. expect(importNode?.signature).toContain('.*');
  1158. });
  1159. it('should extract multiple imports', () => {
  1160. const code = `
  1161. import java.io.IOException
  1162. import kotlin.test.assertFailsWith
  1163. import okhttp3.OkHttpClient
  1164. `;
  1165. const result = extractFromSource('Test.kt', code);
  1166. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1167. expect(importNodes.length).toBe(3);
  1168. const names = importNodes.map((n) => n.name);
  1169. expect(names).toContain('java.io.IOException');
  1170. expect(names).toContain('kotlin.test.assertFailsWith');
  1171. expect(names).toContain('okhttp3.OkHttpClient');
  1172. });
  1173. });
  1174. describe('Java imports', () => {
  1175. it('should extract simple import', () => {
  1176. const code = `import java.util.List;`;
  1177. const result = extractFromSource('Main.java', code);
  1178. const importNode = result.nodes.find((n) => n.kind === 'import');
  1179. expect(importNode).toBeDefined();
  1180. expect(importNode?.name).toBe('java.util.List');
  1181. expect(importNode?.signature).toBe('import java.util.List;');
  1182. });
  1183. it('should extract static import', () => {
  1184. const code = `import static java.util.Collections.emptyList;`;
  1185. const result = extractFromSource('Utils.java', code);
  1186. const importNode = result.nodes.find((n) => n.kind === 'import');
  1187. expect(importNode).toBeDefined();
  1188. expect(importNode?.name).toBe('java.util.Collections.emptyList');
  1189. expect(importNode?.signature).toContain('static');
  1190. });
  1191. it('should extract wildcard import', () => {
  1192. const code = `import java.util.*;`;
  1193. const result = extractFromSource('App.java', code);
  1194. const importNode = result.nodes.find((n) => n.kind === 'import');
  1195. expect(importNode).toBeDefined();
  1196. expect(importNode?.name).toBe('java.util');
  1197. expect(importNode?.signature).toContain('.*');
  1198. });
  1199. it('should extract nested class import', () => {
  1200. const code = `import java.util.Map.Entry;`;
  1201. const result = extractFromSource('MapUtil.java', code);
  1202. const importNode = result.nodes.find((n) => n.kind === 'import');
  1203. expect(importNode).toBeDefined();
  1204. expect(importNode?.name).toBe('java.util.Map.Entry');
  1205. });
  1206. it('should extract multiple imports', () => {
  1207. const code = `
  1208. import java.util.List;
  1209. import java.util.Map;
  1210. import java.io.IOException;
  1211. `;
  1212. const result = extractFromSource('Service.java', code);
  1213. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1214. expect(importNodes.length).toBe(3);
  1215. const names = importNodes.map((n) => n.name);
  1216. expect(names).toContain('java.util.List');
  1217. expect(names).toContain('java.util.Map');
  1218. expect(names).toContain('java.io.IOException');
  1219. });
  1220. });
  1221. describe('C# imports', () => {
  1222. it('should extract simple using', () => {
  1223. const code = `using System;`;
  1224. const result = extractFromSource('Program.cs', code);
  1225. const importNode = result.nodes.find((n) => n.kind === 'import');
  1226. expect(importNode).toBeDefined();
  1227. expect(importNode?.name).toBe('System');
  1228. expect(importNode?.signature).toBe('using System;');
  1229. });
  1230. it('should extract qualified using', () => {
  1231. const code = `using System.Collections.Generic;`;
  1232. const result = extractFromSource('Utils.cs', code);
  1233. const importNode = result.nodes.find((n) => n.kind === 'import');
  1234. expect(importNode).toBeDefined();
  1235. expect(importNode?.name).toBe('System.Collections.Generic');
  1236. });
  1237. it('should extract static using', () => {
  1238. const code = `using static System.Console;`;
  1239. const result = extractFromSource('App.cs', code);
  1240. const importNode = result.nodes.find((n) => n.kind === 'import');
  1241. expect(importNode).toBeDefined();
  1242. expect(importNode?.name).toBe('System.Console');
  1243. expect(importNode?.signature).toContain('static');
  1244. });
  1245. it('should extract alias using', () => {
  1246. const code = `using MyList = System.Collections.Generic.List<int>;`;
  1247. const result = extractFromSource('Types.cs', code);
  1248. const importNode = result.nodes.find((n) => n.kind === 'import');
  1249. expect(importNode).toBeDefined();
  1250. expect(importNode?.name).toBe('System.Collections.Generic.List<int>');
  1251. expect(importNode?.signature).toContain('MyList =');
  1252. });
  1253. it('should extract multiple usings', () => {
  1254. const code = `
  1255. using System;
  1256. using System.Threading.Tasks;
  1257. using Microsoft.Extensions.DependencyInjection;
  1258. `;
  1259. const result = extractFromSource('Service.cs', code);
  1260. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1261. expect(importNodes.length).toBe(3);
  1262. const names = importNodes.map((n) => n.name);
  1263. expect(names).toContain('System');
  1264. expect(names).toContain('System.Threading.Tasks');
  1265. expect(names).toContain('Microsoft.Extensions.DependencyInjection');
  1266. });
  1267. });
  1268. describe('PHP imports', () => {
  1269. it('should extract simple use', () => {
  1270. const code = `<?php use PHPUnit\\Framework\\TestCase;`;
  1271. const result = extractFromSource('Test.php', code);
  1272. const importNode = result.nodes.find((n) => n.kind === 'import');
  1273. expect(importNode).toBeDefined();
  1274. expect(importNode?.name).toBe('PHPUnit\\Framework\\TestCase');
  1275. });
  1276. it('should extract aliased use', () => {
  1277. const code = `<?php use Mockery as m;`;
  1278. const result = extractFromSource('Test.php', code);
  1279. const importNode = result.nodes.find((n) => n.kind === 'import');
  1280. expect(importNode).toBeDefined();
  1281. expect(importNode?.name).toBe('Mockery');
  1282. expect(importNode?.signature).toContain('as m');
  1283. });
  1284. it('should extract function use', () => {
  1285. const code = `<?php use function Illuminate\\Support\\env;`;
  1286. const result = extractFromSource('helpers.php', code);
  1287. const importNode = result.nodes.find((n) => n.kind === 'import');
  1288. expect(importNode).toBeDefined();
  1289. expect(importNode?.name).toBe('Illuminate\\Support\\env');
  1290. expect(importNode?.signature).toContain('function');
  1291. });
  1292. it('should extract grouped use', () => {
  1293. const code = `<?php use Illuminate\\Database\\{Model, Builder};`;
  1294. const result = extractFromSource('Models.php', code);
  1295. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1296. expect(importNodes.length).toBe(2);
  1297. const names = importNodes.map((n) => n.name);
  1298. expect(names).toContain('Illuminate\\Database\\Model');
  1299. expect(names).toContain('Illuminate\\Database\\Builder');
  1300. });
  1301. it('should extract multiple uses', () => {
  1302. const code = `<?php
  1303. use Illuminate\\Support\\Collection;
  1304. use Illuminate\\Support\\Str;
  1305. use Closure;
  1306. `;
  1307. const result = extractFromSource('Service.php', code);
  1308. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1309. expect(importNodes.length).toBe(3);
  1310. const names = importNodes.map((n) => n.name);
  1311. expect(names).toContain('Illuminate\\Support\\Collection');
  1312. expect(names).toContain('Illuminate\\Support\\Str');
  1313. expect(names).toContain('Closure');
  1314. });
  1315. });
  1316. describe('Ruby imports', () => {
  1317. it('should extract require', () => {
  1318. const code = `require 'json'`;
  1319. const result = extractFromSource('app.rb', code);
  1320. const importNode = result.nodes.find((n) => n.kind === 'import');
  1321. expect(importNode).toBeDefined();
  1322. expect(importNode?.name).toBe('json');
  1323. expect(importNode?.signature).toBe("require 'json'");
  1324. });
  1325. it('should extract require with path', () => {
  1326. const code = `require 'active_support/core_ext/string'`;
  1327. const result = extractFromSource('config.rb', code);
  1328. const importNode = result.nodes.find((n) => n.kind === 'import');
  1329. expect(importNode).toBeDefined();
  1330. expect(importNode?.name).toBe('active_support/core_ext/string');
  1331. });
  1332. it('should extract require_relative', () => {
  1333. const code = `require_relative '../test_helper'`;
  1334. const result = extractFromSource('test/my_test.rb', code);
  1335. const importNode = result.nodes.find((n) => n.kind === 'import');
  1336. expect(importNode).toBeDefined();
  1337. expect(importNode?.name).toBe('../test_helper');
  1338. expect(importNode?.signature).toContain('require_relative');
  1339. });
  1340. it('should not extract non-require calls', () => {
  1341. const code = `puts 'hello'`;
  1342. const result = extractFromSource('app.rb', code);
  1343. const importNode = result.nodes.find((n) => n.kind === 'import');
  1344. expect(importNode).toBeUndefined();
  1345. });
  1346. it('should extract multiple requires', () => {
  1347. const code = `
  1348. require 'json'
  1349. require 'yaml'
  1350. require_relative 'helper'
  1351. `;
  1352. const result = extractFromSource('lib.rb', code);
  1353. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1354. expect(importNodes.length).toBe(3);
  1355. const names = importNodes.map((n) => n.name);
  1356. expect(names).toContain('json');
  1357. expect(names).toContain('yaml');
  1358. expect(names).toContain('helper');
  1359. });
  1360. });
  1361. describe('C/C++ imports', () => {
  1362. it('should extract system include', () => {
  1363. const code = `#include <iostream>`;
  1364. const result = extractFromSource('main.cpp', code);
  1365. const importNode = result.nodes.find((n) => n.kind === 'import');
  1366. expect(importNode).toBeDefined();
  1367. expect(importNode?.name).toBe('iostream');
  1368. expect(importNode?.signature).toBe('#include <iostream>');
  1369. });
  1370. it('should extract system include with path', () => {
  1371. const code = `#include <nlohmann/json.hpp>`;
  1372. const result = extractFromSource('app.cpp', code);
  1373. const importNode = result.nodes.find((n) => n.kind === 'import');
  1374. expect(importNode).toBeDefined();
  1375. expect(importNode?.name).toBe('nlohmann/json.hpp');
  1376. });
  1377. it('should extract local include', () => {
  1378. const code = `#include "myheader.h"`;
  1379. const result = extractFromSource('main.cpp', code);
  1380. const importNode = result.nodes.find((n) => n.kind === 'import');
  1381. expect(importNode).toBeDefined();
  1382. expect(importNode?.name).toBe('myheader.h');
  1383. });
  1384. it('should extract C header', () => {
  1385. const code = `#include <stdio.h>`;
  1386. const result = extractFromSource('main.c', code);
  1387. const importNode = result.nodes.find((n) => n.kind === 'import');
  1388. expect(importNode).toBeDefined();
  1389. expect(importNode?.name).toBe('stdio.h');
  1390. });
  1391. it('should extract multiple includes', () => {
  1392. const code = `
  1393. #include <iostream>
  1394. #include <vector>
  1395. #include "config.h"
  1396. `;
  1397. const result = extractFromSource('app.cpp', code);
  1398. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1399. expect(importNodes.length).toBe(3);
  1400. const names = importNodes.map((n) => n.name);
  1401. expect(names).toContain('iostream');
  1402. expect(names).toContain('vector');
  1403. expect(names).toContain('config.h');
  1404. });
  1405. });
  1406. describe('Dart imports', () => {
  1407. it('should extract dart: import', () => {
  1408. const code = `import 'dart:async';`;
  1409. const result = extractFromSource('main.dart', code);
  1410. const importNode = result.nodes.find((n) => n.kind === 'import');
  1411. expect(importNode).toBeDefined();
  1412. expect(importNode?.name).toBe('dart:async');
  1413. expect(importNode?.signature).toBe("import 'dart:async';");
  1414. });
  1415. it('should extract package import', () => {
  1416. const code = `import 'package:flutter/material.dart';`;
  1417. const result = extractFromSource('app.dart', code);
  1418. const importNode = result.nodes.find((n) => n.kind === 'import');
  1419. expect(importNode).toBeDefined();
  1420. expect(importNode?.name).toBe('package:flutter/material.dart');
  1421. });
  1422. it('should extract aliased import', () => {
  1423. const code = `import 'package:http/http.dart' as http;`;
  1424. const result = extractFromSource('api.dart', code);
  1425. const importNode = result.nodes.find((n) => n.kind === 'import');
  1426. expect(importNode).toBeDefined();
  1427. expect(importNode?.name).toBe('package:http/http.dart');
  1428. expect(importNode?.signature).toContain('as http');
  1429. });
  1430. it('should extract multiple imports', () => {
  1431. const code = `
  1432. import 'dart:async';
  1433. import 'dart:convert';
  1434. import 'package:flutter/material.dart';
  1435. `;
  1436. const result = extractFromSource('main.dart', code);
  1437. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1438. expect(importNodes.length).toBe(3);
  1439. const names = importNodes.map((n) => n.name);
  1440. expect(names).toContain('dart:async');
  1441. expect(names).toContain('dart:convert');
  1442. expect(names).toContain('package:flutter/material.dart');
  1443. });
  1444. it('should extract relative import', () => {
  1445. const code = `import '../utils/helpers.dart';`;
  1446. const result = extractFromSource('lib/main.dart', code);
  1447. const importNode = result.nodes.find((n) => n.kind === 'import');
  1448. expect(importNode).toBeDefined();
  1449. expect(importNode?.name).toBe('../utils/helpers.dart');
  1450. });
  1451. });
  1452. describe('Liquid imports', () => {
  1453. it('should extract render tag', () => {
  1454. const code = `{% render 'loading-spinner' %}`;
  1455. const result = extractFromSource('template.liquid', code);
  1456. const importNode = result.nodes.find((n) => n.kind === 'import');
  1457. expect(importNode).toBeDefined();
  1458. expect(importNode?.name).toBe('loading-spinner');
  1459. expect(importNode?.signature).toContain('render');
  1460. });
  1461. it('should extract section tag', () => {
  1462. const code = `{% section 'header' %}`;
  1463. const result = extractFromSource('layout/theme.liquid', code);
  1464. const importNode = result.nodes.find((n) => n.kind === 'import');
  1465. expect(importNode).toBeDefined();
  1466. expect(importNode?.name).toBe('header');
  1467. expect(importNode?.signature).toContain('section');
  1468. });
  1469. it('should extract include tag', () => {
  1470. const code = `{% include 'icon-cart' %}`;
  1471. const result = extractFromSource('snippets/header.liquid', code);
  1472. const importNode = result.nodes.find((n) => n.kind === 'import');
  1473. expect(importNode).toBeDefined();
  1474. expect(importNode?.name).toBe('icon-cart');
  1475. expect(importNode?.signature).toContain('include');
  1476. });
  1477. it('should extract render with whitespace control', () => {
  1478. const code = `{%- render 'price' -%}`;
  1479. const result = extractFromSource('snippets/product.liquid', code);
  1480. const importNode = result.nodes.find((n) => n.kind === 'import');
  1481. expect(importNode).toBeDefined();
  1482. expect(importNode?.name).toBe('price');
  1483. });
  1484. it('should extract multiple imports', () => {
  1485. const code = `
  1486. {% section 'header' %}
  1487. {% render 'loading-spinner' %}
  1488. {% render 'cart-drawer' %}
  1489. `;
  1490. const result = extractFromSource('layout/theme.liquid', code);
  1491. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1492. expect(importNodes.length).toBe(3);
  1493. const names = importNodes.map((n) => n.name);
  1494. expect(names).toContain('header');
  1495. expect(names).toContain('loading-spinner');
  1496. expect(names).toContain('cart-drawer');
  1497. });
  1498. });
  1499. });
  1500. // =============================================================================
  1501. // Pascal / Delphi Extraction
  1502. // =============================================================================
  1503. describe('Pascal / Delphi Extraction', () => {
  1504. describe('Language detection', () => {
  1505. it('should detect Pascal files', () => {
  1506. expect(detectLanguage('UAuth.pas')).toBe('pascal');
  1507. expect(detectLanguage('App.dpr')).toBe('pascal');
  1508. expect(detectLanguage('Package.dpk')).toBe('pascal');
  1509. expect(detectLanguage('App.lpr')).toBe('pascal');
  1510. expect(detectLanguage('MainForm.dfm')).toBe('pascal');
  1511. expect(detectLanguage('MainForm.fmx')).toBe('pascal');
  1512. });
  1513. it('should report Pascal as supported', () => {
  1514. expect(isLanguageSupported('pascal')).toBe(true);
  1515. expect(getSupportedLanguages()).toContain('pascal');
  1516. });
  1517. });
  1518. describe('Unit extraction', () => {
  1519. it('should extract unit as module', () => {
  1520. const code = `unit MyUnit;\ninterface\nimplementation\nend.`;
  1521. const result = extractFromSource('MyUnit.pas', code);
  1522. const moduleNode = result.nodes.find((n) => n.kind === 'module');
  1523. expect(moduleNode).toBeDefined();
  1524. expect(moduleNode?.name).toBe('MyUnit');
  1525. expect(moduleNode?.language).toBe('pascal');
  1526. });
  1527. it('should extract program as module', () => {
  1528. const code = `program MyApp;\nbegin\nend.`;
  1529. const result = extractFromSource('MyApp.dpr', code);
  1530. const moduleNode = result.nodes.find((n) => n.kind === 'module');
  1531. expect(moduleNode).toBeDefined();
  1532. expect(moduleNode?.name).toBe('MyApp');
  1533. });
  1534. it('should fallback to filename when module name is empty', () => {
  1535. // Some .dpr templates use "program;" without a name
  1536. const code = `program;\nuses SysUtils;\nbegin\nend.`;
  1537. const result = extractFromSource('Console.dpr', code);
  1538. const moduleNode = result.nodes.find((n) => n.kind === 'module');
  1539. expect(moduleNode).toBeDefined();
  1540. expect(moduleNode?.name).toBe('Console');
  1541. });
  1542. });
  1543. describe('Uses clause (imports)', () => {
  1544. it('should extract uses as individual imports', () => {
  1545. const code = `unit Test;\ninterface\nuses\n System.SysUtils,\n System.Classes;\nimplementation\nend.`;
  1546. const result = extractFromSource('Test.pas', code);
  1547. const imports = result.nodes.filter((n) => n.kind === 'import');
  1548. expect(imports.length).toBe(2);
  1549. expect(imports.map((n) => n.name)).toContain('System.SysUtils');
  1550. expect(imports.map((n) => n.name)).toContain('System.Classes');
  1551. });
  1552. it('should create unresolved references for imports', () => {
  1553. const code = `unit Test;\ninterface\nuses\n UAuth;\nimplementation\nend.`;
  1554. const result = extractFromSource('Test.pas', code);
  1555. const importRef = result.unresolvedReferences.find(
  1556. (r) => r.referenceKind === 'imports'
  1557. );
  1558. expect(importRef).toBeDefined();
  1559. expect(importRef?.referenceName).toBe('UAuth');
  1560. });
  1561. });
  1562. describe('Class extraction', () => {
  1563. it('should extract class declarations', () => {
  1564. const code = `unit Test;\ninterface\ntype\n TMyClass = class\n public\n procedure DoSomething;\n end;\nimplementation\nend.`;
  1565. const result = extractFromSource('Test.pas', code);
  1566. const classNode = result.nodes.find((n) => n.kind === 'class');
  1567. expect(classNode).toBeDefined();
  1568. expect(classNode?.name).toBe('TMyClass');
  1569. });
  1570. it('should extract class with inheritance', () => {
  1571. const code = `unit Test;\ninterface\ntype\n TChild = class(TParent)\n end;\nimplementation\nend.`;
  1572. const result = extractFromSource('Test.pas', code);
  1573. const extendsRef = result.unresolvedReferences.find(
  1574. (r) => r.referenceKind === 'extends'
  1575. );
  1576. expect(extendsRef).toBeDefined();
  1577. expect(extendsRef?.referenceName).toBe('TParent');
  1578. });
  1579. it('should extract class with interface implementation', () => {
  1580. const code = `unit Test;\ninterface\ntype\n TService = class(TInterfacedObject, ILogger)\n end;\nimplementation\nend.`;
  1581. const result = extractFromSource('Test.pas', code);
  1582. const extendsRef = result.unresolvedReferences.find(
  1583. (r) => r.referenceKind === 'extends'
  1584. );
  1585. const implementsRef = result.unresolvedReferences.find(
  1586. (r) => r.referenceKind === 'implements'
  1587. );
  1588. expect(extendsRef?.referenceName).toBe('TInterfacedObject');
  1589. expect(implementsRef?.referenceName).toBe('ILogger');
  1590. });
  1591. });
  1592. describe('Record extraction', () => {
  1593. it('should extract records as class nodes', () => {
  1594. const code = `unit Test;\ninterface\ntype\n TPoint = record\n X: Double;\n Y: Double;\n end;\nimplementation\nend.`;
  1595. const result = extractFromSource('Test.pas', code);
  1596. const classNode = result.nodes.find((n) => n.kind === 'class');
  1597. expect(classNode).toBeDefined();
  1598. expect(classNode?.name).toBe('TPoint');
  1599. const fields = result.nodes.filter((n) => n.kind === 'field');
  1600. expect(fields.length).toBe(2);
  1601. expect(fields.map((f) => f.name)).toContain('X');
  1602. expect(fields.map((f) => f.name)).toContain('Y');
  1603. });
  1604. });
  1605. describe('Interface extraction', () => {
  1606. it('should extract interface declarations', () => {
  1607. const code = `unit Test;\ninterface\ntype\n ILogger = interface\n procedure Log(const AMsg: string);\n end;\nimplementation\nend.`;
  1608. const result = extractFromSource('Test.pas', code);
  1609. const ifaceNode = result.nodes.find((n) => n.kind === 'interface');
  1610. expect(ifaceNode).toBeDefined();
  1611. expect(ifaceNode?.name).toBe('ILogger');
  1612. });
  1613. });
  1614. describe('Method extraction', () => {
  1615. it('should extract methods with visibility', () => {
  1616. const code = `unit Test;\ninterface\ntype\n TMyClass = class\n private\n FValue: Integer;\n public\n constructor Create;\n function GetValue: Integer;\n end;\nimplementation\nend.`;
  1617. const result = extractFromSource('Test.pas', code);
  1618. const methods = result.nodes.filter((n) => n.kind === 'method');
  1619. expect(methods.length).toBe(2);
  1620. const createMethod = methods.find((m) => m.name === 'Create');
  1621. expect(createMethod?.visibility).toBe('public');
  1622. const getValue = methods.find((m) => m.name === 'GetValue');
  1623. expect(getValue?.visibility).toBe('public');
  1624. const fields = result.nodes.filter((n) => n.kind === 'field');
  1625. const fValue = fields.find((f) => f.name === 'FValue');
  1626. expect(fValue?.visibility).toBe('private');
  1627. });
  1628. it('should detect static methods (class methods)', () => {
  1629. const code = `unit Test;\ninterface\ntype\n THelper = class\n public\n class function Create: THelper; static;\n end;\nimplementation\nend.`;
  1630. const result = extractFromSource('Test.pas', code);
  1631. const methods = result.nodes.filter((n) => n.kind === 'method');
  1632. const staticMethod = methods.find((m) => m.name === 'Create');
  1633. expect(staticMethod?.isStatic).toBe(true);
  1634. });
  1635. });
  1636. describe('Enum extraction', () => {
  1637. it('should extract enums with members', () => {
  1638. const code = `unit Test;\ninterface\ntype\n TColor = (clRed, clGreen, clBlue);\nimplementation\nend.`;
  1639. const result = extractFromSource('Test.pas', code);
  1640. const enumNode = result.nodes.find((n) => n.kind === 'enum');
  1641. expect(enumNode).toBeDefined();
  1642. expect(enumNode?.name).toBe('TColor');
  1643. const members = result.nodes.filter((n) => n.kind === 'enum_member');
  1644. expect(members.length).toBe(3);
  1645. expect(members.map((m) => m.name)).toEqual(['clRed', 'clGreen', 'clBlue']);
  1646. });
  1647. });
  1648. describe('Property extraction', () => {
  1649. it('should extract properties', () => {
  1650. const code = `unit Test;\ninterface\ntype\n TObj = class\n public\n property Name: string read FName write FName;\n end;\nimplementation\nend.`;
  1651. const result = extractFromSource('Test.pas', code);
  1652. const propNode = result.nodes.find((n) => n.kind === 'property');
  1653. expect(propNode).toBeDefined();
  1654. expect(propNode?.name).toBe('Name');
  1655. expect(propNode?.visibility).toBe('public');
  1656. });
  1657. });
  1658. describe('Constant extraction', () => {
  1659. it('should extract constants', () => {
  1660. const code = `unit Test;\ninterface\nconst\n MAX_RETRIES = 3;\n APP_NAME = 'MyApp';\nimplementation\nend.`;
  1661. const result = extractFromSource('Test.pas', code);
  1662. const constants = result.nodes.filter((n) => n.kind === 'constant');
  1663. expect(constants.length).toBe(2);
  1664. expect(constants.map((c) => c.name)).toContain('MAX_RETRIES');
  1665. expect(constants.map((c) => c.name)).toContain('APP_NAME');
  1666. });
  1667. });
  1668. describe('Type alias extraction', () => {
  1669. it('should extract type aliases', () => {
  1670. const code = `unit Test;\ninterface\ntype\n TUserName = string;\nimplementation\nend.`;
  1671. const result = extractFromSource('Test.pas', code);
  1672. const aliasNode = result.nodes.find((n) => n.kind === 'type_alias');
  1673. expect(aliasNode).toBeDefined();
  1674. expect(aliasNode?.name).toBe('TUserName');
  1675. });
  1676. });
  1677. describe('Call extraction', () => {
  1678. it('should extract calls from implementation bodies', () => {
  1679. const code = `unit Test;\ninterface\ntype\n TObj = class\n public\n procedure DoWork;\n end;\nimplementation\nprocedure TObj.DoWork;\nbegin\n WriteLn('hello');\nend;\nend.`;
  1680. const result = extractFromSource('Test.pas', code);
  1681. const callRef = result.unresolvedReferences.find(
  1682. (r) => r.referenceKind === 'calls'
  1683. );
  1684. expect(callRef).toBeDefined();
  1685. expect(callRef?.referenceName).toBe('WriteLn');
  1686. });
  1687. });
  1688. describe('Containment edges', () => {
  1689. it('should create contains edges for class members', () => {
  1690. const code = `unit Test;\ninterface\ntype\n TObj = class\n public\n procedure Foo;\n end;\nimplementation\nend.`;
  1691. const result = extractFromSource('Test.pas', code);
  1692. const classNode = result.nodes.find((n) => n.kind === 'class');
  1693. const methodNode = result.nodes.find((n) => n.kind === 'method');
  1694. expect(classNode).toBeDefined();
  1695. expect(methodNode).toBeDefined();
  1696. const containsEdge = result.edges.find(
  1697. (e) => e.source === classNode?.id && e.target === methodNode?.id && e.kind === 'contains'
  1698. );
  1699. expect(containsEdge).toBeDefined();
  1700. });
  1701. });
  1702. describe('Full fixture: UAuth.pas', () => {
  1703. const code = `unit UAuth;
  1704. interface
  1705. uses
  1706. System.SysUtils,
  1707. System.Classes;
  1708. type
  1709. ITokenValidator = interface
  1710. ['{11111111-1111-1111-1111-111111111111}']
  1711. function Validate(const AToken: string): Boolean;
  1712. end;
  1713. TAuthService = class(TInterfacedObject, ITokenValidator)
  1714. private
  1715. FToken: string;
  1716. FLoginCount: Integer;
  1717. procedure IncLoginCount;
  1718. protected
  1719. function GetToken: string;
  1720. public
  1721. constructor Create;
  1722. destructor Destroy; override;
  1723. function Validate(const AToken: string): Boolean;
  1724. function Login(const AUser, APass: string): string;
  1725. property Token: string read GetToken;
  1726. property LoginCount: Integer read FLoginCount;
  1727. end;
  1728. implementation
  1729. constructor TAuthService.Create;
  1730. begin
  1731. inherited Create;
  1732. FToken := '';
  1733. FLoginCount := 0;
  1734. end;
  1735. destructor TAuthService.Destroy;
  1736. begin
  1737. FToken := '';
  1738. inherited Destroy;
  1739. end;
  1740. procedure TAuthService.IncLoginCount;
  1741. begin
  1742. Inc(FLoginCount);
  1743. end;
  1744. function TAuthService.GetToken: string;
  1745. begin
  1746. Result := FToken;
  1747. end;
  1748. function TAuthService.Validate(const AToken: string): Boolean;
  1749. begin
  1750. Result := AToken <> '';
  1751. end;
  1752. function TAuthService.Login(const AUser, APass: string): string;
  1753. begin
  1754. IncLoginCount;
  1755. if Validate(AUser + ':' + APass) then
  1756. begin
  1757. FToken := AUser;
  1758. Result := 'ok';
  1759. end
  1760. else
  1761. Result := '';
  1762. end;
  1763. end.`;
  1764. it('should extract all expected nodes', () => {
  1765. const result = extractFromSource('UAuth.pas', code);
  1766. expect(result.errors).toHaveLength(0);
  1767. // Module
  1768. const moduleNode = result.nodes.find((n) => n.kind === 'module');
  1769. expect(moduleNode?.name).toBe('UAuth');
  1770. // Imports
  1771. const imports = result.nodes.filter((n) => n.kind === 'import');
  1772. expect(imports.length).toBe(2);
  1773. // Interface
  1774. const ifaceNode = result.nodes.find((n) => n.kind === 'interface');
  1775. expect(ifaceNode?.name).toBe('ITokenValidator');
  1776. // Class
  1777. const classNode = result.nodes.find((n) => n.kind === 'class');
  1778. expect(classNode?.name).toBe('TAuthService');
  1779. // Methods
  1780. const methods = result.nodes.filter((n) => n.kind === 'method');
  1781. expect(methods.length).toBeGreaterThanOrEqual(6);
  1782. expect(methods.map((m) => m.name)).toContain('Create');
  1783. expect(methods.map((m) => m.name)).toContain('Destroy');
  1784. expect(methods.map((m) => m.name)).toContain('Login');
  1785. // Fields
  1786. const fields = result.nodes.filter((n) => n.kind === 'field');
  1787. expect(fields.length).toBe(2);
  1788. expect(fields.every((f) => f.visibility === 'private')).toBe(true);
  1789. // Properties
  1790. const props = result.nodes.filter((n) => n.kind === 'property');
  1791. expect(props.length).toBe(2);
  1792. expect(props.map((p) => p.name)).toContain('Token');
  1793. expect(props.map((p) => p.name)).toContain('LoginCount');
  1794. });
  1795. it('should extract inheritance and interface implementation', () => {
  1796. const result = extractFromSource('UAuth.pas', code);
  1797. const extendsRef = result.unresolvedReferences.find(
  1798. (r) => r.referenceKind === 'extends'
  1799. );
  1800. expect(extendsRef?.referenceName).toBe('TInterfacedObject');
  1801. const implementsRef = result.unresolvedReferences.find(
  1802. (r) => r.referenceKind === 'implements'
  1803. );
  1804. expect(implementsRef?.referenceName).toBe('ITokenValidator');
  1805. });
  1806. it('should extract calls from implementation', () => {
  1807. const result = extractFromSource('UAuth.pas', code);
  1808. const callRefs = result.unresolvedReferences.filter(
  1809. (r) => r.referenceKind === 'calls'
  1810. );
  1811. expect(callRefs.map((r) => r.referenceName)).toContain('Inc');
  1812. expect(callRefs.map((r) => r.referenceName)).toContain('Validate');
  1813. });
  1814. });
  1815. describe('Full fixture: UTypes.pas', () => {
  1816. const code = `unit UTypes;
  1817. interface
  1818. uses
  1819. System.SysUtils;
  1820. const
  1821. C_MAX_RETRIES = 3;
  1822. C_DEFAULT_NAME = 'Guest';
  1823. type
  1824. TUserRole = (urAdmin, urEditor, urViewer);
  1825. TPoint2D = record
  1826. X: Double;
  1827. Y: Double;
  1828. end;
  1829. TUserName = string;
  1830. TUserInfo = class
  1831. public
  1832. type
  1833. TAddress = record
  1834. Street: string;
  1835. City: string;
  1836. Zip: string;
  1837. end;
  1838. private
  1839. FName: TUserName;
  1840. FRole: TUserRole;
  1841. FAddress: TAddress;
  1842. public
  1843. constructor Create(const AName: TUserName; ARole: TUserRole);
  1844. function GetDisplayName: string;
  1845. class function CreateAdmin(const AName: TUserName): TUserInfo; static;
  1846. property Name: TUserName read FName write FName;
  1847. property Role: TUserRole read FRole;
  1848. property Address: TAddress read FAddress write FAddress;
  1849. end;
  1850. implementation
  1851. constructor TUserInfo.Create(const AName: TUserName; ARole: TUserRole);
  1852. begin
  1853. FName := AName;
  1854. FRole := ARole;
  1855. end;
  1856. function TUserInfo.GetDisplayName: string;
  1857. begin
  1858. if FRole = urAdmin then
  1859. Result := '[Admin] ' + FName
  1860. else
  1861. Result := FName;
  1862. end;
  1863. class function TUserInfo.CreateAdmin(const AName: TUserName): TUserInfo;
  1864. begin
  1865. Result := TUserInfo.Create(AName, urAdmin);
  1866. end;
  1867. end.`;
  1868. it('should extract enums with members', () => {
  1869. const result = extractFromSource('UTypes.pas', code);
  1870. const enumNode = result.nodes.find((n) => n.kind === 'enum');
  1871. expect(enumNode?.name).toBe('TUserRole');
  1872. const members = result.nodes.filter((n) => n.kind === 'enum_member');
  1873. expect(members.length).toBe(3);
  1874. expect(members.map((m) => m.name)).toEqual(['urAdmin', 'urEditor', 'urViewer']);
  1875. });
  1876. it('should extract constants', () => {
  1877. const result = extractFromSource('UTypes.pas', code);
  1878. const constants = result.nodes.filter((n) => n.kind === 'constant');
  1879. expect(constants.length).toBe(2);
  1880. expect(constants.map((c) => c.name)).toContain('C_MAX_RETRIES');
  1881. expect(constants.map((c) => c.name)).toContain('C_DEFAULT_NAME');
  1882. });
  1883. it('should extract type aliases', () => {
  1884. const result = extractFromSource('UTypes.pas', code);
  1885. const aliases = result.nodes.filter((n) => n.kind === 'type_alias');
  1886. expect(aliases.map((a) => a.name)).toContain('TUserName');
  1887. });
  1888. it('should extract records as classes with fields', () => {
  1889. const result = extractFromSource('UTypes.pas', code);
  1890. const classes = result.nodes.filter((n) => n.kind === 'class');
  1891. expect(classes.map((c) => c.name)).toContain('TPoint2D');
  1892. // TPoint2D fields
  1893. const fields = result.nodes.filter((n) => n.kind === 'field');
  1894. expect(fields.map((f) => f.name)).toContain('X');
  1895. expect(fields.map((f) => f.name)).toContain('Y');
  1896. });
  1897. it('should extract static class methods', () => {
  1898. const result = extractFromSource('UTypes.pas', code);
  1899. const methods = result.nodes.filter((n) => n.kind === 'method');
  1900. const staticMethod = methods.find((m) => m.name === 'CreateAdmin');
  1901. expect(staticMethod).toBeDefined();
  1902. expect(staticMethod?.isStatic).toBe(true);
  1903. });
  1904. it('should extract nested types', () => {
  1905. const result = extractFromSource('UTypes.pas', code);
  1906. const classes = result.nodes.filter((n) => n.kind === 'class');
  1907. expect(classes.map((c) => c.name)).toContain('TAddress');
  1908. });
  1909. });
  1910. });
  1911. // =============================================================================
  1912. // DFM/FMX Extraction
  1913. // =============================================================================
  1914. describe('DFM/FMX Extraction', () => {
  1915. it('should extract components from DFM', () => {
  1916. const code = `object Form1: TForm1
  1917. Left = 0
  1918. Top = 0
  1919. Caption = 'My Form'
  1920. object Button1: TButton
  1921. Left = 10
  1922. Top = 10
  1923. Caption = 'Click Me'
  1924. end
  1925. end`;
  1926. const result = extractFromSource('Form1.dfm', code);
  1927. const components = result.nodes.filter((n) => n.kind === 'component');
  1928. expect(components.length).toBe(2);
  1929. expect(components.map((c) => c.name)).toContain('Form1');
  1930. expect(components.map((c) => c.name)).toContain('Button1');
  1931. const button = components.find((c) => c.name === 'Button1');
  1932. expect(button?.signature).toBe('TButton');
  1933. });
  1934. it('should extract nested component hierarchy', () => {
  1935. const code = `object Form1: TForm1
  1936. object Panel1: TPanel
  1937. object Label1: TLabel
  1938. Caption = 'Hello'
  1939. end
  1940. end
  1941. end`;
  1942. const result = extractFromSource('Form1.dfm', code);
  1943. const components = result.nodes.filter((n) => n.kind === 'component');
  1944. expect(components.length).toBe(3);
  1945. // Check nesting: Panel1 contains Label1
  1946. const panel = components.find((c) => c.name === 'Panel1');
  1947. const label = components.find((c) => c.name === 'Label1');
  1948. const containsEdge = result.edges.find(
  1949. (e) => e.source === panel?.id && e.target === label?.id && e.kind === 'contains'
  1950. );
  1951. expect(containsEdge).toBeDefined();
  1952. });
  1953. it('should extract event handler references', () => {
  1954. const code = `object Form1: TForm1
  1955. OnCreate = FormCreate
  1956. OnDestroy = FormDestroy
  1957. object Button1: TButton
  1958. OnClick = Button1Click
  1959. end
  1960. end`;
  1961. const result = extractFromSource('Form1.dfm', code);
  1962. const refs = result.unresolvedReferences;
  1963. expect(refs.length).toBe(3);
  1964. expect(refs.map((r) => r.referenceName)).toContain('FormCreate');
  1965. expect(refs.map((r) => r.referenceName)).toContain('FormDestroy');
  1966. expect(refs.map((r) => r.referenceName)).toContain('Button1Click');
  1967. expect(refs.every((r) => r.referenceKind === 'references')).toBe(true);
  1968. });
  1969. it('should handle multi-line properties', () => {
  1970. const code = `object Form1: TForm1
  1971. SQL.Strings = (
  1972. 'SELECT * FROM users'
  1973. 'WHERE active = 1')
  1974. object Button1: TButton
  1975. OnClick = Button1Click
  1976. end
  1977. end`;
  1978. const result = extractFromSource('Form1.dfm', code);
  1979. const components = result.nodes.filter((n) => n.kind === 'component');
  1980. expect(components.length).toBe(2);
  1981. const refs = result.unresolvedReferences;
  1982. expect(refs.length).toBe(1);
  1983. expect(refs[0]?.referenceName).toBe('Button1Click');
  1984. });
  1985. it('should handle inherited keyword', () => {
  1986. const code = `inherited Form1: TForm1
  1987. Caption = 'Inherited Form'
  1988. object Button1: TButton
  1989. OnClick = Button1Click
  1990. end
  1991. end`;
  1992. const result = extractFromSource('Form1.dfm', code);
  1993. const components = result.nodes.filter((n) => n.kind === 'component');
  1994. expect(components.length).toBe(2);
  1995. expect(components.map((c) => c.name)).toContain('Form1');
  1996. });
  1997. it('should handle item collection properties', () => {
  1998. const code = `object Form1: TForm1
  1999. object StatusBar1: TStatusBar
  2000. Panels = <
  2001. item
  2002. Width = 200
  2003. end
  2004. item
  2005. Width = 200
  2006. end>
  2007. end
  2008. end`;
  2009. const result = extractFromSource('Form1.dfm', code);
  2010. const components = result.nodes.filter((n) => n.kind === 'component');
  2011. expect(components.length).toBe(2);
  2012. });
  2013. describe('Full fixture: MainForm.dfm', () => {
  2014. const code = `object frmMain: TfrmMain
  2015. Left = 0
  2016. Top = 0
  2017. Caption = 'CodeGraph DFM Fixture'
  2018. ClientHeight = 480
  2019. ClientWidth = 640
  2020. OnCreate = FormCreate
  2021. OnDestroy = FormDestroy
  2022. object pnlTop: TPanel
  2023. Left = 0
  2024. Top = 0
  2025. Width = 640
  2026. Height = 50
  2027. object lblTitle: TLabel
  2028. Left = 16
  2029. Top = 16
  2030. Caption = 'Authentication Service'
  2031. end
  2032. object btnLogin: TButton
  2033. Left = 540
  2034. Top = 12
  2035. OnClick = btnLoginClick
  2036. end
  2037. end
  2038. object pnlContent: TPanel
  2039. Left = 0
  2040. Top = 50
  2041. object edtUsername: TEdit
  2042. Left = 16
  2043. Top = 16
  2044. OnChange = edtUsernameChange
  2045. end
  2046. object edtPassword: TEdit
  2047. Left = 16
  2048. Top = 48
  2049. OnKeyPress = edtPasswordKeyPress
  2050. end
  2051. object mmoLog: TMemo
  2052. Left = 16
  2053. Top = 88
  2054. end
  2055. end
  2056. object pnlStatus: TStatusBar
  2057. Left = 0
  2058. Top = 440
  2059. Panels = <
  2060. item
  2061. Width = 200
  2062. end
  2063. item
  2064. Width = 200
  2065. end>
  2066. end
  2067. end`;
  2068. it('should extract all components', () => {
  2069. const result = extractFromSource('MainForm.dfm', code);
  2070. const components = result.nodes.filter((n) => n.kind === 'component');
  2071. expect(components.length).toBe(9);
  2072. expect(components.map((c) => c.name)).toEqual(
  2073. expect.arrayContaining([
  2074. 'frmMain', 'pnlTop', 'lblTitle', 'btnLogin',
  2075. 'pnlContent', 'edtUsername', 'edtPassword', 'mmoLog', 'pnlStatus',
  2076. ])
  2077. );
  2078. });
  2079. it('should extract all event handlers', () => {
  2080. const result = extractFromSource('MainForm.dfm', code);
  2081. const refs = result.unresolvedReferences;
  2082. expect(refs.length).toBe(5);
  2083. expect(refs.map((r) => r.referenceName)).toEqual(
  2084. expect.arrayContaining([
  2085. 'FormCreate', 'FormDestroy', 'btnLoginClick',
  2086. 'edtUsernameChange', 'edtPasswordKeyPress',
  2087. ])
  2088. );
  2089. });
  2090. });
  2091. });
  2092. describe('Full Indexing', () => {
  2093. let tempDir: string;
  2094. beforeEach(() => {
  2095. tempDir = createTempDir();
  2096. });
  2097. afterEach(() => {
  2098. cleanupTempDir(tempDir);
  2099. });
  2100. it('should index a TypeScript file', async () => {
  2101. // Create test file
  2102. const srcDir = path.join(tempDir, 'src');
  2103. fs.mkdirSync(srcDir);
  2104. fs.writeFileSync(
  2105. path.join(srcDir, 'utils.ts'),
  2106. `
  2107. export function add(a: number, b: number): number {
  2108. return a + b;
  2109. }
  2110. export function multiply(a: number, b: number): number {
  2111. return a * b;
  2112. }
  2113. `
  2114. );
  2115. // Initialize and index
  2116. const cg = CodeGraph.initSync(tempDir);
  2117. const result = await cg.indexAll();
  2118. expect(result.success).toBe(true);
  2119. expect(result.filesIndexed).toBe(1);
  2120. expect(result.nodesCreated).toBeGreaterThanOrEqual(2);
  2121. // Check nodes were stored
  2122. const nodes = cg.getNodesInFile('src/utils.ts');
  2123. expect(nodes.length).toBeGreaterThanOrEqual(2);
  2124. const addFunc = nodes.find((n) => n.name === 'add');
  2125. expect(addFunc).toBeDefined();
  2126. expect(addFunc?.kind).toBe('function');
  2127. cg.close();
  2128. });
  2129. it('should index multiple files', async () => {
  2130. // Create test files
  2131. const srcDir = path.join(tempDir, 'src');
  2132. fs.mkdirSync(srcDir);
  2133. fs.writeFileSync(
  2134. path.join(srcDir, 'math.ts'),
  2135. `export function add(a: number, b: number) { return a + b; }`
  2136. );
  2137. fs.writeFileSync(
  2138. path.join(srcDir, 'string.ts'),
  2139. `export function capitalize(s: string) { return s.toUpperCase(); }`
  2140. );
  2141. // Initialize and index
  2142. const cg = CodeGraph.initSync(tempDir);
  2143. const result = await cg.indexAll();
  2144. expect(result.success).toBe(true);
  2145. expect(result.filesIndexed).toBe(2);
  2146. const files = cg.getFiles();
  2147. expect(files.length).toBe(2);
  2148. cg.close();
  2149. });
  2150. it('should track file hashes for incremental updates', async () => {
  2151. // Create initial file
  2152. const srcDir = path.join(tempDir, 'src');
  2153. fs.mkdirSync(srcDir);
  2154. fs.writeFileSync(path.join(srcDir, 'main.ts'), `export const x = 1;`);
  2155. // Initialize and index
  2156. const cg = CodeGraph.initSync(tempDir);
  2157. await cg.indexAll();
  2158. // Check file is tracked
  2159. const file = cg.getFile('src/main.ts');
  2160. expect(file).toBeDefined();
  2161. expect(file?.contentHash).toBeDefined();
  2162. // Modify file
  2163. fs.writeFileSync(path.join(srcDir, 'main.ts'), `export const x = 2;`);
  2164. // Check for changes
  2165. const changes = cg.getChangedFiles();
  2166. expect(changes.modified).toContain('src/main.ts');
  2167. cg.close();
  2168. });
  2169. it('should sync and detect changes', async () => {
  2170. // Create initial file
  2171. const srcDir = path.join(tempDir, 'src');
  2172. fs.mkdirSync(srcDir);
  2173. fs.writeFileSync(
  2174. path.join(srcDir, 'main.ts'),
  2175. `export function original() { return 1; }`
  2176. );
  2177. // Initialize and index
  2178. const cg = CodeGraph.initSync(tempDir);
  2179. await cg.indexAll();
  2180. const initialNodes = cg.getNodesInFile('src/main.ts');
  2181. expect(initialNodes.some((n) => n.name === 'original')).toBe(true);
  2182. // Modify file
  2183. fs.writeFileSync(
  2184. path.join(srcDir, 'main.ts'),
  2185. `export function updated() { return 2; }`
  2186. );
  2187. // Sync
  2188. const syncResult = await cg.sync();
  2189. expect(syncResult.filesModified).toBe(1);
  2190. // Check nodes were updated
  2191. const updatedNodes = cg.getNodesInFile('src/main.ts');
  2192. expect(updatedNodes.some((n) => n.name === 'updated')).toBe(true);
  2193. expect(updatedNodes.some((n) => n.name === 'original')).toBe(false);
  2194. cg.close();
  2195. });
  2196. });
  2197. describe('Path Normalization', () => {
  2198. it('should convert backslashes to forward slashes', () => {
  2199. expect(normalizePath('gui\\node_modules\\foo')).toBe('gui/node_modules/foo');
  2200. expect(normalizePath('src\\components\\Button.tsx')).toBe('src/components/Button.tsx');
  2201. });
  2202. it('should leave forward-slash paths unchanged', () => {
  2203. expect(normalizePath('src/components/Button.tsx')).toBe('src/components/Button.tsx');
  2204. });
  2205. it('should handle empty string', () => {
  2206. expect(normalizePath('')).toBe('');
  2207. });
  2208. });
  2209. describe('Directory Exclusion', () => {
  2210. let tempDir: string;
  2211. beforeEach(() => {
  2212. tempDir = createTempDir();
  2213. });
  2214. afterEach(() => {
  2215. cleanupTempDir(tempDir);
  2216. });
  2217. it('should exclude node_modules directories', () => {
  2218. // Create structure: src/index.ts + node_modules/pkg/index.js
  2219. const srcDir = path.join(tempDir, 'src');
  2220. const nmDir = path.join(tempDir, 'node_modules', 'pkg');
  2221. fs.mkdirSync(srcDir, { recursive: true });
  2222. fs.mkdirSync(nmDir, { recursive: true });
  2223. fs.writeFileSync(path.join(srcDir, 'index.ts'), 'export const x = 1;');
  2224. fs.writeFileSync(path.join(nmDir, 'index.js'), 'module.exports = {};');
  2225. const config = { ...DEFAULT_CONFIG, rootDir: tempDir };
  2226. const files = scanDirectory(tempDir, config);
  2227. expect(files).toContain('src/index.ts');
  2228. expect(files.every((f) => !f.includes('node_modules'))).toBe(true);
  2229. });
  2230. it('should exclude nested node_modules directories', () => {
  2231. // Create structure: packages/app/node_modules/pkg/index.js
  2232. const srcDir = path.join(tempDir, 'packages', 'app', 'src');
  2233. const nmDir = path.join(tempDir, 'packages', 'app', 'node_modules', 'pkg');
  2234. fs.mkdirSync(srcDir, { recursive: true });
  2235. fs.mkdirSync(nmDir, { recursive: true });
  2236. fs.writeFileSync(path.join(srcDir, 'index.ts'), 'export const x = 1;');
  2237. fs.writeFileSync(path.join(nmDir, 'index.js'), 'module.exports = {};');
  2238. const config = { ...DEFAULT_CONFIG, rootDir: tempDir };
  2239. const files = scanDirectory(tempDir, config);
  2240. expect(files).toContain('packages/app/src/index.ts');
  2241. expect(files.every((f) => !f.includes('node_modules'))).toBe(true);
  2242. });
  2243. it('should exclude .git directories', () => {
  2244. const srcDir = path.join(tempDir, 'src');
  2245. const gitDir = path.join(tempDir, '.git', 'objects');
  2246. fs.mkdirSync(srcDir, { recursive: true });
  2247. fs.mkdirSync(gitDir, { recursive: true });
  2248. fs.writeFileSync(path.join(srcDir, 'index.ts'), 'export const x = 1;');
  2249. fs.writeFileSync(path.join(gitDir, 'pack.ts'), 'export const y = 2;');
  2250. const config = { ...DEFAULT_CONFIG, rootDir: tempDir };
  2251. const files = scanDirectory(tempDir, config);
  2252. expect(files).toContain('src/index.ts');
  2253. expect(files.every((f) => !f.includes('.git'))).toBe(true);
  2254. });
  2255. it('should return forward-slash paths on all platforms', () => {
  2256. const srcDir = path.join(tempDir, 'src', 'components');
  2257. fs.mkdirSync(srcDir, { recursive: true });
  2258. fs.writeFileSync(path.join(srcDir, 'Button.tsx'), 'export function Button() {}');
  2259. const config = { ...DEFAULT_CONFIG, rootDir: tempDir };
  2260. const files = scanDirectory(tempDir, config);
  2261. expect(files.length).toBe(1);
  2262. expect(files[0]).toBe('src/components/Button.tsx');
  2263. expect(files[0]).not.toContain('\\');
  2264. });
  2265. it('should respect .codegraphignore marker', () => {
  2266. const srcDir = path.join(tempDir, 'src');
  2267. const vendorDir = path.join(tempDir, 'vendor');
  2268. fs.mkdirSync(srcDir, { recursive: true });
  2269. fs.mkdirSync(vendorDir, { recursive: true });
  2270. fs.writeFileSync(path.join(srcDir, 'index.ts'), 'export const x = 1;');
  2271. fs.writeFileSync(path.join(vendorDir, 'lib.ts'), 'export const y = 2;');
  2272. fs.writeFileSync(path.join(vendorDir, '.codegraphignore'), '');
  2273. const config = { ...DEFAULT_CONFIG, rootDir: tempDir };
  2274. const files = scanDirectory(tempDir, config);
  2275. expect(files).toContain('src/index.ts');
  2276. expect(files.every((f) => !f.includes('vendor'))).toBe(true);
  2277. });
  2278. });