extraction.test.ts 90 KB

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