extraction.test.ts 94 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974
  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. it('should extract class inheritance (extends) and interface implementation', () => {
  692. const code = `<?php
  693. class ChildController extends BaseController implements Serializable, JsonSerializable
  694. {
  695. public function serialize(): string
  696. {
  697. return json_encode($this);
  698. }
  699. }
  700. `;
  701. const result = extractFromSource('ChildController.php', code);
  702. const classNode = result.nodes.find((n) => n.kind === 'class');
  703. expect(classNode).toBeDefined();
  704. expect(classNode?.name).toBe('ChildController');
  705. const extendsRef = result.unresolvedReferences.find(
  706. (r) => r.referenceKind === 'extends'
  707. );
  708. expect(extendsRef).toBeDefined();
  709. expect(extendsRef?.referenceName).toBe('BaseController');
  710. const implementsRefs = result.unresolvedReferences.filter(
  711. (r) => r.referenceKind === 'implements'
  712. );
  713. expect(implementsRefs.length).toBe(2);
  714. expect(implementsRefs.map((r) => r.referenceName)).toContain('Serializable');
  715. expect(implementsRefs.map((r) => r.referenceName)).toContain('JsonSerializable');
  716. });
  717. });
  718. describe('Swift Extraction', () => {
  719. it('should extract class declarations', () => {
  720. const code = `
  721. public class NetworkManager {
  722. private let session: URLSession
  723. public init(session: URLSession = .shared) {
  724. self.session = session
  725. }
  726. public func fetchData(from url: URL) async throws -> Data {
  727. let (data, _) = try await session.data(from: url)
  728. return data
  729. }
  730. }
  731. `;
  732. const result = extractFromSource('NetworkManager.swift', code);
  733. const classNode = result.nodes.find((n) => n.kind === 'class');
  734. expect(classNode).toBeDefined();
  735. expect(classNode?.name).toBe('NetworkManager');
  736. });
  737. it('should extract function declarations', () => {
  738. const code = `
  739. func calculateSum(_ numbers: [Int]) -> Int {
  740. return numbers.reduce(0, +)
  741. }
  742. public func formatCurrency(amount: Double) -> String {
  743. return String(format: "$%.2f", amount)
  744. }
  745. `;
  746. const result = extractFromSource('utils.swift', code);
  747. const functions = result.nodes.filter((n) => n.kind === 'function');
  748. expect(functions.length).toBeGreaterThanOrEqual(1);
  749. });
  750. it('should extract struct declarations', () => {
  751. const code = `
  752. public struct User {
  753. let id: UUID
  754. var name: String
  755. var email: String
  756. func displayName() -> String {
  757. return name
  758. }
  759. }
  760. `;
  761. const result = extractFromSource('User.swift', code);
  762. const structNode = result.nodes.find((n) => n.kind === 'struct');
  763. expect(structNode).toBeDefined();
  764. expect(structNode?.name).toBe('User');
  765. });
  766. it('should extract protocol declarations', () => {
  767. const code = `
  768. public protocol Repository {
  769. associatedtype Entity
  770. func find(id: String) async throws -> Entity?
  771. func save(_ entity: Entity) async throws
  772. }
  773. `;
  774. const result = extractFromSource('Repository.swift', code);
  775. const protocolNode = result.nodes.find((n) => n.kind === 'interface');
  776. expect(protocolNode).toBeDefined();
  777. expect(protocolNode?.name).toBe('Repository');
  778. });
  779. it('should extract class inheritance and protocol conformance', () => {
  780. const code = `
  781. class DataRequest: Request {
  782. func validate() {}
  783. }
  784. class UploadRequest: DataRequest, Sendable {
  785. func upload() {}
  786. }
  787. enum AFError: Error {
  788. case invalidURL
  789. }
  790. struct HTTPMethod: RawRepresentable {
  791. let rawValue: String
  792. }
  793. protocol UploadConvertible: URLRequestConvertible {
  794. func asURLRequest() throws -> URLRequest
  795. }
  796. `;
  797. const result = extractFromSource('Inheritance.swift', code);
  798. const extendsRefs = result.unresolvedReferences.filter(
  799. (r) => r.referenceKind === 'extends'
  800. );
  801. // DataRequest extends Request
  802. expect(extendsRefs.find((r) => r.referenceName === 'Request')).toBeDefined();
  803. // UploadRequest extends DataRequest and Sendable
  804. expect(extendsRefs.find((r) => r.referenceName === 'DataRequest')).toBeDefined();
  805. expect(extendsRefs.find((r) => r.referenceName === 'Sendable')).toBeDefined();
  806. // AFError extends Error
  807. expect(extendsRefs.find((r) => r.referenceName === 'Error')).toBeDefined();
  808. // HTTPMethod extends RawRepresentable
  809. expect(extendsRefs.find((r) => r.referenceName === 'RawRepresentable')).toBeDefined();
  810. // UploadConvertible extends URLRequestConvertible
  811. expect(extendsRefs.find((r) => r.referenceName === 'URLRequestConvertible')).toBeDefined();
  812. });
  813. });
  814. describe('Kotlin Extraction', () => {
  815. it('should extract class declarations', () => {
  816. const code = `
  817. class UserRepository(private val database: Database) {
  818. fun findById(id: String): User? {
  819. return database.query("SELECT * FROM users WHERE id = ?", id)
  820. }
  821. suspend fun save(user: User) {
  822. database.insert(user)
  823. }
  824. }
  825. `;
  826. const result = extractFromSource('UserRepository.kt', code);
  827. const classNode = result.nodes.find((n) => n.kind === 'class');
  828. expect(classNode).toBeDefined();
  829. expect(classNode?.name).toBe('UserRepository');
  830. });
  831. it('should extract function declarations', () => {
  832. const code = `
  833. fun calculateTotal(items: List<Item>): Double {
  834. return items.sumOf { it.price }
  835. }
  836. suspend fun fetchUserData(userId: String): User {
  837. return api.getUser(userId)
  838. }
  839. `;
  840. const result = extractFromSource('utils.kt', code);
  841. const functions = result.nodes.filter((n) => n.kind === 'function');
  842. expect(functions.length).toBeGreaterThanOrEqual(1);
  843. });
  844. it('should detect suspend functions as async', () => {
  845. const code = `
  846. suspend fun loadData(): List<String> {
  847. delay(1000)
  848. return listOf("a", "b", "c")
  849. }
  850. `;
  851. const result = extractFromSource('loader.kt', code);
  852. const funcNode = result.nodes.find((n) => n.kind === 'function');
  853. expect(funcNode).toBeDefined();
  854. expect(funcNode?.isAsync).toBe(true);
  855. });
  856. });
  857. describe('Dart Extraction', () => {
  858. it('should extract class declarations', () => {
  859. const code = `
  860. class UserService {
  861. final Database _db;
  862. Future<User> findById(String id) async {
  863. return await _db.query(id);
  864. }
  865. void _privateMethod() {}
  866. }
  867. `;
  868. const result = extractFromSource('service.dart', code);
  869. const classNode = result.nodes.find((n) => n.kind === 'class');
  870. expect(classNode).toBeDefined();
  871. expect(classNode?.name).toBe('UserService');
  872. expect(classNode?.visibility).toBe('public');
  873. const methodNodes = result.nodes.filter((n) => n.kind === 'method');
  874. expect(methodNodes.length).toBeGreaterThanOrEqual(2);
  875. const findById = methodNodes.find((m) => m.name === 'findById');
  876. expect(findById).toBeDefined();
  877. expect(findById?.isAsync).toBe(true);
  878. const privateMethod = methodNodes.find((m) => m.name === '_privateMethod');
  879. expect(privateMethod).toBeDefined();
  880. expect(privateMethod?.visibility).toBe('private');
  881. });
  882. it('should extract top-level function declarations', () => {
  883. const code = `
  884. void topLevelFunction(String name) {
  885. print(name);
  886. }
  887. `;
  888. const result = extractFromSource('utils.dart', code);
  889. const funcNode = result.nodes.find((n) => n.kind === 'function');
  890. expect(funcNode).toBeDefined();
  891. expect(funcNode?.name).toBe('topLevelFunction');
  892. expect(funcNode?.language).toBe('dart');
  893. });
  894. it('should extract enum declarations', () => {
  895. const code = `
  896. enum Status { active, inactive, pending }
  897. `;
  898. const result = extractFromSource('models.dart', code);
  899. const enumNode = result.nodes.find((n) => n.kind === 'enum');
  900. expect(enumNode).toBeDefined();
  901. expect(enumNode?.name).toBe('Status');
  902. });
  903. it('should extract mixin declarations', () => {
  904. const code = `
  905. mixin LoggerMixin {
  906. void log(String message) {}
  907. }
  908. `;
  909. const result = extractFromSource('mixins.dart', code);
  910. const classNode = result.nodes.find((n) => n.kind === 'class');
  911. expect(classNode).toBeDefined();
  912. expect(classNode?.name).toBe('LoggerMixin');
  913. const methodNode = result.nodes.find((n) => n.kind === 'method');
  914. expect(methodNode).toBeDefined();
  915. expect(methodNode?.name).toBe('log');
  916. });
  917. it('should extract extension declarations', () => {
  918. const code = `
  919. extension StringExt on String {
  920. bool get isBlank => trim().isEmpty;
  921. }
  922. `;
  923. const result = extractFromSource('extensions.dart', code);
  924. const classNode = result.nodes.find((n) => n.kind === 'class');
  925. expect(classNode).toBeDefined();
  926. expect(classNode?.name).toBe('StringExt');
  927. });
  928. it('should detect static methods', () => {
  929. const code = `
  930. class Utils {
  931. static void doWork() {}
  932. }
  933. `;
  934. const result = extractFromSource('utils.dart', code);
  935. const methodNode = result.nodes.find((n) => n.kind === 'method');
  936. expect(methodNode).toBeDefined();
  937. expect(methodNode?.name).toBe('doWork');
  938. expect(methodNode?.isStatic).toBe(true);
  939. });
  940. it('should detect async functions', () => {
  941. const code = `
  942. Future<String> fetchData() async {
  943. return await http.get('/data');
  944. }
  945. `;
  946. const result = extractFromSource('api.dart', code);
  947. const funcNode = result.nodes.find((n) => n.kind === 'function');
  948. expect(funcNode).toBeDefined();
  949. expect(funcNode?.name).toBe('fetchData');
  950. expect(funcNode?.isAsync).toBe(true);
  951. });
  952. it('should detect private visibility via underscore convention', () => {
  953. const code = `
  954. void _privateHelper() {}
  955. void publicFunction() {}
  956. `;
  957. const result = extractFromSource('helpers.dart', code);
  958. const functions = result.nodes.filter((n) => n.kind === 'function');
  959. const privateFunc = functions.find((f) => f.name === '_privateHelper');
  960. const publicFunc = functions.find((f) => f.name === 'publicFunction');
  961. expect(privateFunc?.visibility).toBe('private');
  962. expect(publicFunc?.visibility).toBe('public');
  963. });
  964. });
  965. describe('Import Extraction', () => {
  966. describe('TypeScript/JavaScript imports', () => {
  967. it('should extract default imports', () => {
  968. const code = `import React from 'react';`;
  969. const result = extractFromSource('app.tsx', code);
  970. const importNode = result.nodes.find((n) => n.kind === 'import');
  971. expect(importNode).toBeDefined();
  972. expect(importNode?.name).toBe('react');
  973. expect(importNode?.signature).toBe("import React from 'react';");
  974. });
  975. it('should extract named imports', () => {
  976. const code = `import { Bug, Database } from '@phosphor-icons/react';`;
  977. const result = extractFromSource('icons.tsx', code);
  978. const importNode = result.nodes.find((n) => n.kind === 'import');
  979. expect(importNode).toBeDefined();
  980. expect(importNode?.name).toBe('@phosphor-icons/react');
  981. expect(importNode?.signature).toContain('Bug');
  982. expect(importNode?.signature).toContain('Database');
  983. });
  984. it('should extract namespace imports', () => {
  985. const code = `import * as Icons from '@phosphor-icons/react';`;
  986. const result = extractFromSource('icons.tsx', code);
  987. const importNode = result.nodes.find((n) => n.kind === 'import');
  988. expect(importNode).toBeDefined();
  989. expect(importNode?.name).toBe('@phosphor-icons/react');
  990. expect(importNode?.signature).toContain('* as Icons');
  991. });
  992. it('should extract side-effect imports', () => {
  993. const code = `import './styles.css';`;
  994. const result = extractFromSource('app.tsx', code);
  995. const importNode = result.nodes.find((n) => n.kind === 'import');
  996. expect(importNode).toBeDefined();
  997. expect(importNode?.name).toBe('./styles.css');
  998. });
  999. it('should extract mixed imports (default + named)', () => {
  1000. const code = `import React, { useState, useEffect } from 'react';`;
  1001. const result = extractFromSource('app.tsx', code);
  1002. const importNode = result.nodes.find((n) => n.kind === 'import');
  1003. expect(importNode).toBeDefined();
  1004. expect(importNode?.name).toBe('react');
  1005. expect(importNode?.signature).toContain('React');
  1006. expect(importNode?.signature).toContain('useState');
  1007. expect(importNode?.signature).toContain('useEffect');
  1008. });
  1009. it('should extract multiple import statements', () => {
  1010. const code = `
  1011. import React from 'react';
  1012. import { Button } from './components';
  1013. import './styles.css';
  1014. `;
  1015. const result = extractFromSource('app.tsx', code);
  1016. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1017. expect(importNodes.length).toBe(3);
  1018. const names = importNodes.map((n) => n.name);
  1019. expect(names).toContain('react');
  1020. expect(names).toContain('./components');
  1021. expect(names).toContain('./styles.css');
  1022. });
  1023. it('should extract type imports', () => {
  1024. const code = `import type { FC, ReactNode } from 'react';`;
  1025. const result = extractFromSource('types.ts', code);
  1026. const importNode = result.nodes.find((n) => n.kind === 'import');
  1027. expect(importNode).toBeDefined();
  1028. expect(importNode?.name).toBe('react');
  1029. expect(importNode?.signature).toContain('type');
  1030. expect(importNode?.signature).toContain('FC');
  1031. });
  1032. it('should extract aliased named imports', () => {
  1033. const code = `import { useState as useStateAlias } from 'react';`;
  1034. const result = extractFromSource('hooks.ts', code);
  1035. const importNode = result.nodes.find((n) => n.kind === 'import');
  1036. expect(importNode).toBeDefined();
  1037. expect(importNode?.name).toBe('react');
  1038. expect(importNode?.signature).toContain('useState');
  1039. expect(importNode?.signature).toContain('useStateAlias');
  1040. });
  1041. it('should extract relative path imports', () => {
  1042. const code = `import { helper } from '../utils/helper';`;
  1043. const result = extractFromSource('components/Button.tsx', code);
  1044. const importNode = result.nodes.find((n) => n.kind === 'import');
  1045. expect(importNode).toBeDefined();
  1046. expect(importNode?.name).toBe('../utils/helper');
  1047. expect(importNode?.signature).toContain('helper');
  1048. });
  1049. });
  1050. describe('Python imports', () => {
  1051. it('should extract simple import statement', () => {
  1052. const code = `import json`;
  1053. const result = extractFromSource('utils.py', code);
  1054. const importNode = result.nodes.find((n) => n.kind === 'import');
  1055. expect(importNode).toBeDefined();
  1056. expect(importNode?.name).toBe('json');
  1057. });
  1058. it('should extract from import statement', () => {
  1059. const code = `from os import path`;
  1060. const result = extractFromSource('utils.py', code);
  1061. const importNode = result.nodes.find((n) => n.kind === 'import');
  1062. expect(importNode).toBeDefined();
  1063. expect(importNode?.name).toBe('os');
  1064. expect(importNode?.signature).toContain('path');
  1065. });
  1066. it('should extract multiple imports from same module', () => {
  1067. const code = `from typing import List, Dict, Optional`;
  1068. const result = extractFromSource('types.py', code);
  1069. const importNode = result.nodes.find((n) => n.kind === 'import');
  1070. expect(importNode).toBeDefined();
  1071. expect(importNode?.name).toBe('typing');
  1072. expect(importNode?.signature).toContain('List');
  1073. expect(importNode?.signature).toContain('Dict');
  1074. });
  1075. it('should extract multiple import statements', () => {
  1076. const code = `
  1077. import os
  1078. import sys
  1079. `;
  1080. const result = extractFromSource('main.py', code);
  1081. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1082. expect(importNodes.length).toBe(2);
  1083. const names = importNodes.map((n) => n.name);
  1084. expect(names).toContain('os');
  1085. expect(names).toContain('sys');
  1086. });
  1087. it('should extract aliased import', () => {
  1088. const code = `import numpy as np`;
  1089. const result = extractFromSource('data.py', code);
  1090. const importNode = result.nodes.find((n) => n.kind === 'import');
  1091. expect(importNode).toBeDefined();
  1092. expect(importNode?.name).toBe('numpy');
  1093. expect(importNode?.signature).toContain('as np');
  1094. });
  1095. it('should extract relative import', () => {
  1096. const code = `from .utils import helper`;
  1097. const result = extractFromSource('module.py', code);
  1098. const importNode = result.nodes.find((n) => n.kind === 'import');
  1099. expect(importNode).toBeDefined();
  1100. expect(importNode?.name).toBe('.utils');
  1101. expect(importNode?.signature).toContain('helper');
  1102. });
  1103. it('should extract wildcard import', () => {
  1104. const code = `from typing import *`;
  1105. const result = extractFromSource('types.py', code);
  1106. const importNode = result.nodes.find((n) => n.kind === 'import');
  1107. expect(importNode).toBeDefined();
  1108. expect(importNode?.name).toBe('typing');
  1109. expect(importNode?.signature).toContain('*');
  1110. });
  1111. });
  1112. describe('Rust imports', () => {
  1113. it('should extract simple use declaration', () => {
  1114. const code = `use std::io;`;
  1115. const result = extractFromSource('main.rs', code);
  1116. const importNode = result.nodes.find((n) => n.kind === 'import');
  1117. expect(importNode).toBeDefined();
  1118. expect(importNode?.name).toBe('std');
  1119. expect(importNode?.signature).toBe('use std::io;');
  1120. });
  1121. it('should extract scoped use list', () => {
  1122. const code = `use std::{ffi::OsStr, io, path::Path};`;
  1123. const result = extractFromSource('main.rs', code);
  1124. const importNode = result.nodes.find((n) => n.kind === 'import');
  1125. expect(importNode).toBeDefined();
  1126. expect(importNode?.name).toBe('std');
  1127. expect(importNode?.signature).toContain('ffi::OsStr');
  1128. expect(importNode?.signature).toContain('path::Path');
  1129. });
  1130. it('should extract crate imports', () => {
  1131. const code = `use crate::error::Error;`;
  1132. const result = extractFromSource('lib.rs', code);
  1133. const importNode = result.nodes.find((n) => n.kind === 'import');
  1134. expect(importNode).toBeDefined();
  1135. expect(importNode?.name).toBe('crate');
  1136. });
  1137. it('should extract super imports', () => {
  1138. const code = `use super::utils;`;
  1139. const result = extractFromSource('submod.rs', code);
  1140. const importNode = result.nodes.find((n) => n.kind === 'import');
  1141. expect(importNode).toBeDefined();
  1142. expect(importNode?.name).toBe('super');
  1143. });
  1144. it('should extract external crate imports', () => {
  1145. const code = `use serde::{Serialize, Deserialize};`;
  1146. const result = extractFromSource('types.rs', code);
  1147. const importNode = result.nodes.find((n) => n.kind === 'import');
  1148. expect(importNode).toBeDefined();
  1149. expect(importNode?.name).toBe('serde');
  1150. expect(importNode?.signature).toContain('Serialize');
  1151. expect(importNode?.signature).toContain('Deserialize');
  1152. });
  1153. });
  1154. describe('Go imports', () => {
  1155. it('should extract single import', () => {
  1156. const code = `
  1157. package main
  1158. import "fmt"
  1159. `;
  1160. const result = extractFromSource('main.go', code);
  1161. const importNode = result.nodes.find((n) => n.kind === 'import');
  1162. expect(importNode).toBeDefined();
  1163. expect(importNode?.name).toBe('fmt');
  1164. });
  1165. it('should extract grouped imports', () => {
  1166. const code = `
  1167. package main
  1168. import (
  1169. "fmt"
  1170. "os"
  1171. "encoding/json"
  1172. )
  1173. `;
  1174. const result = extractFromSource('main.go', code);
  1175. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1176. expect(importNodes.length).toBe(3);
  1177. const names = importNodes.map((n) => n.name);
  1178. expect(names).toContain('fmt');
  1179. expect(names).toContain('os');
  1180. expect(names).toContain('encoding/json');
  1181. });
  1182. it('should extract aliased import', () => {
  1183. const code = `
  1184. package main
  1185. import f "fmt"
  1186. `;
  1187. const result = extractFromSource('main.go', code);
  1188. const importNode = result.nodes.find((n) => n.kind === 'import');
  1189. expect(importNode).toBeDefined();
  1190. expect(importNode?.name).toBe('fmt');
  1191. expect(importNode?.signature).toContain('f');
  1192. });
  1193. it('should extract dot import', () => {
  1194. const code = `
  1195. package main
  1196. import . "math"
  1197. `;
  1198. const result = extractFromSource('main.go', code);
  1199. const importNode = result.nodes.find((n) => n.kind === 'import');
  1200. expect(importNode).toBeDefined();
  1201. expect(importNode?.name).toBe('math');
  1202. expect(importNode?.signature).toContain('.');
  1203. });
  1204. it('should extract blank import', () => {
  1205. const code = `
  1206. package main
  1207. import _ "github.com/go-sql-driver/mysql"
  1208. `;
  1209. const result = extractFromSource('main.go', code);
  1210. const importNode = result.nodes.find((n) => n.kind === 'import');
  1211. expect(importNode).toBeDefined();
  1212. expect(importNode?.name).toBe('github.com/go-sql-driver/mysql');
  1213. expect(importNode?.signature).toContain('_');
  1214. });
  1215. });
  1216. describe('Swift imports', () => {
  1217. it('should extract simple import', () => {
  1218. const code = `import Foundation`;
  1219. const result = extractFromSource('main.swift', code);
  1220. const importNode = result.nodes.find((n) => n.kind === 'import');
  1221. expect(importNode).toBeDefined();
  1222. expect(importNode?.name).toBe('Foundation');
  1223. expect(importNode?.signature).toBe('import Foundation');
  1224. });
  1225. it('should extract @testable import', () => {
  1226. const code = `@testable import Alamofire`;
  1227. const result = extractFromSource('Tests.swift', code);
  1228. const importNode = result.nodes.find((n) => n.kind === 'import');
  1229. expect(importNode).toBeDefined();
  1230. expect(importNode?.name).toBe('Alamofire');
  1231. expect(importNode?.signature).toContain('@testable');
  1232. });
  1233. it('should extract @preconcurrency import', () => {
  1234. const code = `@preconcurrency import Security`;
  1235. const result = extractFromSource('Auth.swift', code);
  1236. const importNode = result.nodes.find((n) => n.kind === 'import');
  1237. expect(importNode).toBeDefined();
  1238. expect(importNode?.name).toBe('Security');
  1239. });
  1240. it('should extract multiple imports', () => {
  1241. const code = `
  1242. import Foundation
  1243. import UIKit
  1244. import Alamofire
  1245. `;
  1246. const result = extractFromSource('App.swift', code);
  1247. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1248. expect(importNodes.length).toBe(3);
  1249. const names = importNodes.map((n) => n.name);
  1250. expect(names).toContain('Foundation');
  1251. expect(names).toContain('UIKit');
  1252. expect(names).toContain('Alamofire');
  1253. });
  1254. });
  1255. describe('Kotlin imports', () => {
  1256. it('should extract simple import', () => {
  1257. const code = `import java.io.IOException`;
  1258. const result = extractFromSource('Main.kt', code);
  1259. const importNode = result.nodes.find((n) => n.kind === 'import');
  1260. expect(importNode).toBeDefined();
  1261. expect(importNode?.name).toBe('java.io.IOException');
  1262. expect(importNode?.signature).toBe('import java.io.IOException');
  1263. });
  1264. it('should extract aliased import', () => {
  1265. const code = `import okhttp3.Request.Builder as RequestBuilder`;
  1266. const result = extractFromSource('Utils.kt', code);
  1267. const importNode = result.nodes.find((n) => n.kind === 'import');
  1268. expect(importNode).toBeDefined();
  1269. expect(importNode?.name).toBe('okhttp3.Request.Builder');
  1270. expect(importNode?.signature).toContain('as RequestBuilder');
  1271. });
  1272. it('should extract wildcard import', () => {
  1273. const code = `import java.util.concurrent.TimeUnit.*`;
  1274. const result = extractFromSource('Time.kt', code);
  1275. const importNode = result.nodes.find((n) => n.kind === 'import');
  1276. expect(importNode).toBeDefined();
  1277. expect(importNode?.name).toBe('java.util.concurrent.TimeUnit');
  1278. expect(importNode?.signature).toContain('.*');
  1279. });
  1280. it('should extract multiple imports', () => {
  1281. const code = `
  1282. import java.io.IOException
  1283. import kotlin.test.assertFailsWith
  1284. import okhttp3.OkHttpClient
  1285. `;
  1286. const result = extractFromSource('Test.kt', code);
  1287. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1288. expect(importNodes.length).toBe(3);
  1289. const names = importNodes.map((n) => n.name);
  1290. expect(names).toContain('java.io.IOException');
  1291. expect(names).toContain('kotlin.test.assertFailsWith');
  1292. expect(names).toContain('okhttp3.OkHttpClient');
  1293. });
  1294. });
  1295. describe('Java imports', () => {
  1296. it('should extract simple import', () => {
  1297. const code = `import java.util.List;`;
  1298. const result = extractFromSource('Main.java', code);
  1299. const importNode = result.nodes.find((n) => n.kind === 'import');
  1300. expect(importNode).toBeDefined();
  1301. expect(importNode?.name).toBe('java.util.List');
  1302. expect(importNode?.signature).toBe('import java.util.List;');
  1303. });
  1304. it('should extract static import', () => {
  1305. const code = `import static java.util.Collections.emptyList;`;
  1306. const result = extractFromSource('Utils.java', code);
  1307. const importNode = result.nodes.find((n) => n.kind === 'import');
  1308. expect(importNode).toBeDefined();
  1309. expect(importNode?.name).toBe('java.util.Collections.emptyList');
  1310. expect(importNode?.signature).toContain('static');
  1311. });
  1312. it('should extract wildcard import', () => {
  1313. const code = `import java.util.*;`;
  1314. const result = extractFromSource('App.java', code);
  1315. const importNode = result.nodes.find((n) => n.kind === 'import');
  1316. expect(importNode).toBeDefined();
  1317. expect(importNode?.name).toBe('java.util');
  1318. expect(importNode?.signature).toContain('.*');
  1319. });
  1320. it('should extract nested class import', () => {
  1321. const code = `import java.util.Map.Entry;`;
  1322. const result = extractFromSource('MapUtil.java', code);
  1323. const importNode = result.nodes.find((n) => n.kind === 'import');
  1324. expect(importNode).toBeDefined();
  1325. expect(importNode?.name).toBe('java.util.Map.Entry');
  1326. });
  1327. it('should extract multiple imports', () => {
  1328. const code = `
  1329. import java.util.List;
  1330. import java.util.Map;
  1331. import java.io.IOException;
  1332. `;
  1333. const result = extractFromSource('Service.java', code);
  1334. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1335. expect(importNodes.length).toBe(3);
  1336. const names = importNodes.map((n) => n.name);
  1337. expect(names).toContain('java.util.List');
  1338. expect(names).toContain('java.util.Map');
  1339. expect(names).toContain('java.io.IOException');
  1340. });
  1341. });
  1342. describe('C# imports', () => {
  1343. it('should extract simple using', () => {
  1344. const code = `using System;`;
  1345. const result = extractFromSource('Program.cs', code);
  1346. const importNode = result.nodes.find((n) => n.kind === 'import');
  1347. expect(importNode).toBeDefined();
  1348. expect(importNode?.name).toBe('System');
  1349. expect(importNode?.signature).toBe('using System;');
  1350. });
  1351. it('should extract qualified using', () => {
  1352. const code = `using System.Collections.Generic;`;
  1353. const result = extractFromSource('Utils.cs', code);
  1354. const importNode = result.nodes.find((n) => n.kind === 'import');
  1355. expect(importNode).toBeDefined();
  1356. expect(importNode?.name).toBe('System.Collections.Generic');
  1357. });
  1358. it('should extract static using', () => {
  1359. const code = `using static System.Console;`;
  1360. const result = extractFromSource('App.cs', code);
  1361. const importNode = result.nodes.find((n) => n.kind === 'import');
  1362. expect(importNode).toBeDefined();
  1363. expect(importNode?.name).toBe('System.Console');
  1364. expect(importNode?.signature).toContain('static');
  1365. });
  1366. it('should extract alias using', () => {
  1367. const code = `using MyList = System.Collections.Generic.List<int>;`;
  1368. const result = extractFromSource('Types.cs', code);
  1369. const importNode = result.nodes.find((n) => n.kind === 'import');
  1370. expect(importNode).toBeDefined();
  1371. expect(importNode?.name).toBe('System.Collections.Generic.List<int>');
  1372. expect(importNode?.signature).toContain('MyList =');
  1373. });
  1374. it('should extract multiple usings', () => {
  1375. const code = `
  1376. using System;
  1377. using System.Threading.Tasks;
  1378. using Microsoft.Extensions.DependencyInjection;
  1379. `;
  1380. const result = extractFromSource('Service.cs', code);
  1381. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1382. expect(importNodes.length).toBe(3);
  1383. const names = importNodes.map((n) => n.name);
  1384. expect(names).toContain('System');
  1385. expect(names).toContain('System.Threading.Tasks');
  1386. expect(names).toContain('Microsoft.Extensions.DependencyInjection');
  1387. });
  1388. });
  1389. describe('PHP imports', () => {
  1390. it('should extract simple use', () => {
  1391. const code = `<?php use PHPUnit\\Framework\\TestCase;`;
  1392. const result = extractFromSource('Test.php', code);
  1393. const importNode = result.nodes.find((n) => n.kind === 'import');
  1394. expect(importNode).toBeDefined();
  1395. expect(importNode?.name).toBe('PHPUnit\\Framework\\TestCase');
  1396. });
  1397. it('should extract aliased use', () => {
  1398. const code = `<?php use Mockery as m;`;
  1399. const result = extractFromSource('Test.php', code);
  1400. const importNode = result.nodes.find((n) => n.kind === 'import');
  1401. expect(importNode).toBeDefined();
  1402. expect(importNode?.name).toBe('Mockery');
  1403. expect(importNode?.signature).toContain('as m');
  1404. });
  1405. it('should extract function use', () => {
  1406. const code = `<?php use function Illuminate\\Support\\env;`;
  1407. const result = extractFromSource('helpers.php', code);
  1408. const importNode = result.nodes.find((n) => n.kind === 'import');
  1409. expect(importNode).toBeDefined();
  1410. expect(importNode?.name).toBe('Illuminate\\Support\\env');
  1411. expect(importNode?.signature).toContain('function');
  1412. });
  1413. it('should extract grouped use', () => {
  1414. const code = `<?php use Illuminate\\Database\\{Model, Builder};`;
  1415. const result = extractFromSource('Models.php', code);
  1416. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1417. expect(importNodes.length).toBe(2);
  1418. const names = importNodes.map((n) => n.name);
  1419. expect(names).toContain('Illuminate\\Database\\Model');
  1420. expect(names).toContain('Illuminate\\Database\\Builder');
  1421. });
  1422. it('should extract multiple uses', () => {
  1423. const code = `<?php
  1424. use Illuminate\\Support\\Collection;
  1425. use Illuminate\\Support\\Str;
  1426. use Closure;
  1427. `;
  1428. const result = extractFromSource('Service.php', code);
  1429. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1430. expect(importNodes.length).toBe(3);
  1431. const names = importNodes.map((n) => n.name);
  1432. expect(names).toContain('Illuminate\\Support\\Collection');
  1433. expect(names).toContain('Illuminate\\Support\\Str');
  1434. expect(names).toContain('Closure');
  1435. });
  1436. });
  1437. describe('Ruby imports', () => {
  1438. it('should extract require', () => {
  1439. const code = `require 'json'`;
  1440. const result = extractFromSource('app.rb', code);
  1441. const importNode = result.nodes.find((n) => n.kind === 'import');
  1442. expect(importNode).toBeDefined();
  1443. expect(importNode?.name).toBe('json');
  1444. expect(importNode?.signature).toBe("require 'json'");
  1445. });
  1446. it('should extract require with path', () => {
  1447. const code = `require 'active_support/core_ext/string'`;
  1448. const result = extractFromSource('config.rb', code);
  1449. const importNode = result.nodes.find((n) => n.kind === 'import');
  1450. expect(importNode).toBeDefined();
  1451. expect(importNode?.name).toBe('active_support/core_ext/string');
  1452. });
  1453. it('should extract require_relative', () => {
  1454. const code = `require_relative '../test_helper'`;
  1455. const result = extractFromSource('test/my_test.rb', code);
  1456. const importNode = result.nodes.find((n) => n.kind === 'import');
  1457. expect(importNode).toBeDefined();
  1458. expect(importNode?.name).toBe('../test_helper');
  1459. expect(importNode?.signature).toContain('require_relative');
  1460. });
  1461. it('should not extract non-require calls', () => {
  1462. const code = `puts 'hello'`;
  1463. const result = extractFromSource('app.rb', code);
  1464. const importNode = result.nodes.find((n) => n.kind === 'import');
  1465. expect(importNode).toBeUndefined();
  1466. });
  1467. it('should extract multiple requires', () => {
  1468. const code = `
  1469. require 'json'
  1470. require 'yaml'
  1471. require_relative 'helper'
  1472. `;
  1473. const result = extractFromSource('lib.rb', code);
  1474. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1475. expect(importNodes.length).toBe(3);
  1476. const names = importNodes.map((n) => n.name);
  1477. expect(names).toContain('json');
  1478. expect(names).toContain('yaml');
  1479. expect(names).toContain('helper');
  1480. });
  1481. });
  1482. describe('Ruby modules', () => {
  1483. it('should extract module as module node with containment', () => {
  1484. const code = `
  1485. module CachedCounting
  1486. def self.disable
  1487. @enabled = false
  1488. end
  1489. def perform_increment!(key, count)
  1490. write_cache!(key, count)
  1491. end
  1492. end
  1493. `;
  1494. const result = extractFromSource('concerns/cached_counting.rb', code);
  1495. const moduleNode = result.nodes.find((n) => n.kind === 'module' && n.name === 'CachedCounting');
  1496. expect(moduleNode).toBeDefined();
  1497. expect(moduleNode?.qualifiedName).toBe('CachedCounting');
  1498. // Methods inside module should have module-qualified names
  1499. const disableMethod = result.nodes.find((n) => n.name === 'disable' && n.kind === 'method');
  1500. expect(disableMethod).toBeDefined();
  1501. expect(disableMethod?.qualifiedName).toBe('CachedCounting::disable');
  1502. const incrementMethod = result.nodes.find((n) => n.name === 'perform_increment!' && n.kind === 'method');
  1503. expect(incrementMethod).toBeDefined();
  1504. expect(incrementMethod?.qualifiedName).toBe('CachedCounting::perform_increment!');
  1505. // Containment edge from module to methods
  1506. const containsEdges = result.edges.filter((e) => e.source === moduleNode?.id && e.kind === 'contains');
  1507. expect(containsEdges.length).toBeGreaterThanOrEqual(2);
  1508. });
  1509. it('should handle nested modules with classes', () => {
  1510. const code = `
  1511. module Discourse
  1512. module Auth
  1513. class AuthProvider
  1514. def authenticate(params)
  1515. validate(params)
  1516. end
  1517. end
  1518. end
  1519. end
  1520. `;
  1521. const result = extractFromSource('lib/auth.rb', code);
  1522. const discourseModule = result.nodes.find((n) => n.kind === 'module' && n.name === 'Discourse');
  1523. expect(discourseModule).toBeDefined();
  1524. const authModule = result.nodes.find((n) => n.kind === 'module' && n.name === 'Auth');
  1525. expect(authModule).toBeDefined();
  1526. expect(authModule?.qualifiedName).toBe('Discourse::Auth');
  1527. const authProvider = result.nodes.find((n) => n.kind === 'class' && n.name === 'AuthProvider');
  1528. expect(authProvider).toBeDefined();
  1529. expect(authProvider?.qualifiedName).toBe('Discourse::Auth::AuthProvider');
  1530. const authMethod = result.nodes.find((n) => n.name === 'authenticate');
  1531. expect(authMethod).toBeDefined();
  1532. expect(authMethod?.qualifiedName).toBe('Discourse::Auth::AuthProvider::authenticate');
  1533. });
  1534. });
  1535. describe('C/C++ imports', () => {
  1536. it('should extract system include', () => {
  1537. const code = `#include <iostream>`;
  1538. const result = extractFromSource('main.cpp', code);
  1539. const importNode = result.nodes.find((n) => n.kind === 'import');
  1540. expect(importNode).toBeDefined();
  1541. expect(importNode?.name).toBe('iostream');
  1542. expect(importNode?.signature).toBe('#include <iostream>');
  1543. });
  1544. it('should extract system include with path', () => {
  1545. const code = `#include <nlohmann/json.hpp>`;
  1546. const result = extractFromSource('app.cpp', code);
  1547. const importNode = result.nodes.find((n) => n.kind === 'import');
  1548. expect(importNode).toBeDefined();
  1549. expect(importNode?.name).toBe('nlohmann/json.hpp');
  1550. });
  1551. it('should extract local include', () => {
  1552. const code = `#include "myheader.h"`;
  1553. const result = extractFromSource('main.cpp', code);
  1554. const importNode = result.nodes.find((n) => n.kind === 'import');
  1555. expect(importNode).toBeDefined();
  1556. expect(importNode?.name).toBe('myheader.h');
  1557. });
  1558. it('should extract C header', () => {
  1559. const code = `#include <stdio.h>`;
  1560. const result = extractFromSource('main.c', code);
  1561. const importNode = result.nodes.find((n) => n.kind === 'import');
  1562. expect(importNode).toBeDefined();
  1563. expect(importNode?.name).toBe('stdio.h');
  1564. });
  1565. it('should extract multiple includes', () => {
  1566. const code = `
  1567. #include <iostream>
  1568. #include <vector>
  1569. #include "config.h"
  1570. `;
  1571. const result = extractFromSource('app.cpp', code);
  1572. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1573. expect(importNodes.length).toBe(3);
  1574. const names = importNodes.map((n) => n.name);
  1575. expect(names).toContain('iostream');
  1576. expect(names).toContain('vector');
  1577. expect(names).toContain('config.h');
  1578. });
  1579. });
  1580. describe('Dart imports', () => {
  1581. it('should extract dart: import', () => {
  1582. const code = `import 'dart:async';`;
  1583. const result = extractFromSource('main.dart', code);
  1584. const importNode = result.nodes.find((n) => n.kind === 'import');
  1585. expect(importNode).toBeDefined();
  1586. expect(importNode?.name).toBe('dart:async');
  1587. expect(importNode?.signature).toBe("import 'dart:async';");
  1588. });
  1589. it('should extract package import', () => {
  1590. const code = `import 'package:flutter/material.dart';`;
  1591. const result = extractFromSource('app.dart', code);
  1592. const importNode = result.nodes.find((n) => n.kind === 'import');
  1593. expect(importNode).toBeDefined();
  1594. expect(importNode?.name).toBe('package:flutter/material.dart');
  1595. });
  1596. it('should extract aliased import', () => {
  1597. const code = `import 'package:http/http.dart' as http;`;
  1598. const result = extractFromSource('api.dart', code);
  1599. const importNode = result.nodes.find((n) => n.kind === 'import');
  1600. expect(importNode).toBeDefined();
  1601. expect(importNode?.name).toBe('package:http/http.dart');
  1602. expect(importNode?.signature).toContain('as http');
  1603. });
  1604. it('should extract multiple imports', () => {
  1605. const code = `
  1606. import 'dart:async';
  1607. import 'dart:convert';
  1608. import 'package:flutter/material.dart';
  1609. `;
  1610. const result = extractFromSource('main.dart', code);
  1611. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1612. expect(importNodes.length).toBe(3);
  1613. const names = importNodes.map((n) => n.name);
  1614. expect(names).toContain('dart:async');
  1615. expect(names).toContain('dart:convert');
  1616. expect(names).toContain('package:flutter/material.dart');
  1617. });
  1618. it('should extract relative import', () => {
  1619. const code = `import '../utils/helpers.dart';`;
  1620. const result = extractFromSource('lib/main.dart', code);
  1621. const importNode = result.nodes.find((n) => n.kind === 'import');
  1622. expect(importNode).toBeDefined();
  1623. expect(importNode?.name).toBe('../utils/helpers.dart');
  1624. });
  1625. });
  1626. describe('Liquid imports', () => {
  1627. it('should extract render tag', () => {
  1628. const code = `{% render 'loading-spinner' %}`;
  1629. const result = extractFromSource('template.liquid', code);
  1630. const importNode = result.nodes.find((n) => n.kind === 'import');
  1631. expect(importNode).toBeDefined();
  1632. expect(importNode?.name).toBe('loading-spinner');
  1633. expect(importNode?.signature).toContain('render');
  1634. });
  1635. it('should extract section tag', () => {
  1636. const code = `{% section 'header' %}`;
  1637. const result = extractFromSource('layout/theme.liquid', code);
  1638. const importNode = result.nodes.find((n) => n.kind === 'import');
  1639. expect(importNode).toBeDefined();
  1640. expect(importNode?.name).toBe('header');
  1641. expect(importNode?.signature).toContain('section');
  1642. });
  1643. it('should extract include tag', () => {
  1644. const code = `{% include 'icon-cart' %}`;
  1645. const result = extractFromSource('snippets/header.liquid', code);
  1646. const importNode = result.nodes.find((n) => n.kind === 'import');
  1647. expect(importNode).toBeDefined();
  1648. expect(importNode?.name).toBe('icon-cart');
  1649. expect(importNode?.signature).toContain('include');
  1650. });
  1651. it('should extract render with whitespace control', () => {
  1652. const code = `{%- render 'price' -%}`;
  1653. const result = extractFromSource('snippets/product.liquid', code);
  1654. const importNode = result.nodes.find((n) => n.kind === 'import');
  1655. expect(importNode).toBeDefined();
  1656. expect(importNode?.name).toBe('price');
  1657. });
  1658. it('should extract multiple imports', () => {
  1659. const code = `
  1660. {% section 'header' %}
  1661. {% render 'loading-spinner' %}
  1662. {% render 'cart-drawer' %}
  1663. `;
  1664. const result = extractFromSource('layout/theme.liquid', code);
  1665. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1666. expect(importNodes.length).toBe(3);
  1667. const names = importNodes.map((n) => n.name);
  1668. expect(names).toContain('header');
  1669. expect(names).toContain('loading-spinner');
  1670. expect(names).toContain('cart-drawer');
  1671. });
  1672. });
  1673. });
  1674. // =============================================================================
  1675. // Pascal / Delphi Extraction
  1676. // =============================================================================
  1677. describe('Pascal / Delphi Extraction', () => {
  1678. describe('Language detection', () => {
  1679. it('should detect Pascal files', () => {
  1680. expect(detectLanguage('UAuth.pas')).toBe('pascal');
  1681. expect(detectLanguage('App.dpr')).toBe('pascal');
  1682. expect(detectLanguage('Package.dpk')).toBe('pascal');
  1683. expect(detectLanguage('App.lpr')).toBe('pascal');
  1684. expect(detectLanguage('MainForm.dfm')).toBe('pascal');
  1685. expect(detectLanguage('MainForm.fmx')).toBe('pascal');
  1686. });
  1687. it('should report Pascal as supported', () => {
  1688. expect(isLanguageSupported('pascal')).toBe(true);
  1689. expect(getSupportedLanguages()).toContain('pascal');
  1690. });
  1691. });
  1692. describe('Unit extraction', () => {
  1693. it('should extract unit as module', () => {
  1694. const code = `unit MyUnit;\ninterface\nimplementation\nend.`;
  1695. const result = extractFromSource('MyUnit.pas', code);
  1696. const moduleNode = result.nodes.find((n) => n.kind === 'module');
  1697. expect(moduleNode).toBeDefined();
  1698. expect(moduleNode?.name).toBe('MyUnit');
  1699. expect(moduleNode?.language).toBe('pascal');
  1700. });
  1701. it('should extract program as module', () => {
  1702. const code = `program MyApp;\nbegin\nend.`;
  1703. const result = extractFromSource('MyApp.dpr', code);
  1704. const moduleNode = result.nodes.find((n) => n.kind === 'module');
  1705. expect(moduleNode).toBeDefined();
  1706. expect(moduleNode?.name).toBe('MyApp');
  1707. });
  1708. it('should fallback to filename when module name is empty', () => {
  1709. // Some .dpr templates use "program;" without a name
  1710. const code = `program;\nuses SysUtils;\nbegin\nend.`;
  1711. const result = extractFromSource('Console.dpr', code);
  1712. const moduleNode = result.nodes.find((n) => n.kind === 'module');
  1713. expect(moduleNode).toBeDefined();
  1714. expect(moduleNode?.name).toBe('Console');
  1715. });
  1716. });
  1717. describe('Uses clause (imports)', () => {
  1718. it('should extract uses as individual imports', () => {
  1719. const code = `unit Test;\ninterface\nuses\n System.SysUtils,\n System.Classes;\nimplementation\nend.`;
  1720. const result = extractFromSource('Test.pas', code);
  1721. const imports = result.nodes.filter((n) => n.kind === 'import');
  1722. expect(imports.length).toBe(2);
  1723. expect(imports.map((n) => n.name)).toContain('System.SysUtils');
  1724. expect(imports.map((n) => n.name)).toContain('System.Classes');
  1725. });
  1726. it('should create unresolved references for imports', () => {
  1727. const code = `unit Test;\ninterface\nuses\n UAuth;\nimplementation\nend.`;
  1728. const result = extractFromSource('Test.pas', code);
  1729. const importRef = result.unresolvedReferences.find(
  1730. (r) => r.referenceKind === 'imports'
  1731. );
  1732. expect(importRef).toBeDefined();
  1733. expect(importRef?.referenceName).toBe('UAuth');
  1734. });
  1735. });
  1736. describe('Class extraction', () => {
  1737. it('should extract class declarations', () => {
  1738. const code = `unit Test;\ninterface\ntype\n TMyClass = class\n public\n procedure DoSomething;\n end;\nimplementation\nend.`;
  1739. const result = extractFromSource('Test.pas', code);
  1740. const classNode = result.nodes.find((n) => n.kind === 'class');
  1741. expect(classNode).toBeDefined();
  1742. expect(classNode?.name).toBe('TMyClass');
  1743. });
  1744. it('should extract class with inheritance', () => {
  1745. const code = `unit Test;\ninterface\ntype\n TChild = class(TParent)\n end;\nimplementation\nend.`;
  1746. const result = extractFromSource('Test.pas', code);
  1747. const extendsRef = result.unresolvedReferences.find(
  1748. (r) => r.referenceKind === 'extends'
  1749. );
  1750. expect(extendsRef).toBeDefined();
  1751. expect(extendsRef?.referenceName).toBe('TParent');
  1752. });
  1753. it('should extract class with interface implementation', () => {
  1754. const code = `unit Test;\ninterface\ntype\n TService = class(TInterfacedObject, ILogger)\n end;\nimplementation\nend.`;
  1755. const result = extractFromSource('Test.pas', code);
  1756. const extendsRef = result.unresolvedReferences.find(
  1757. (r) => r.referenceKind === 'extends'
  1758. );
  1759. const implementsRef = result.unresolvedReferences.find(
  1760. (r) => r.referenceKind === 'implements'
  1761. );
  1762. expect(extendsRef?.referenceName).toBe('TInterfacedObject');
  1763. expect(implementsRef?.referenceName).toBe('ILogger');
  1764. });
  1765. });
  1766. describe('Record extraction', () => {
  1767. it('should extract records as class nodes', () => {
  1768. const code = `unit Test;\ninterface\ntype\n TPoint = record\n X: Double;\n Y: Double;\n end;\nimplementation\nend.`;
  1769. const result = extractFromSource('Test.pas', code);
  1770. const classNode = result.nodes.find((n) => n.kind === 'class');
  1771. expect(classNode).toBeDefined();
  1772. expect(classNode?.name).toBe('TPoint');
  1773. const fields = result.nodes.filter((n) => n.kind === 'field');
  1774. expect(fields.length).toBe(2);
  1775. expect(fields.map((f) => f.name)).toContain('X');
  1776. expect(fields.map((f) => f.name)).toContain('Y');
  1777. });
  1778. });
  1779. describe('Interface extraction', () => {
  1780. it('should extract interface declarations', () => {
  1781. const code = `unit Test;\ninterface\ntype\n ILogger = interface\n procedure Log(const AMsg: string);\n end;\nimplementation\nend.`;
  1782. const result = extractFromSource('Test.pas', code);
  1783. const ifaceNode = result.nodes.find((n) => n.kind === 'interface');
  1784. expect(ifaceNode).toBeDefined();
  1785. expect(ifaceNode?.name).toBe('ILogger');
  1786. });
  1787. });
  1788. describe('Method extraction', () => {
  1789. it('should extract methods with visibility', () => {
  1790. 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.`;
  1791. const result = extractFromSource('Test.pas', code);
  1792. const methods = result.nodes.filter((n) => n.kind === 'method');
  1793. expect(methods.length).toBe(2);
  1794. const createMethod = methods.find((m) => m.name === 'Create');
  1795. expect(createMethod?.visibility).toBe('public');
  1796. const getValue = methods.find((m) => m.name === 'GetValue');
  1797. expect(getValue?.visibility).toBe('public');
  1798. const fields = result.nodes.filter((n) => n.kind === 'field');
  1799. const fValue = fields.find((f) => f.name === 'FValue');
  1800. expect(fValue?.visibility).toBe('private');
  1801. });
  1802. it('should detect static methods (class methods)', () => {
  1803. const code = `unit Test;\ninterface\ntype\n THelper = class\n public\n class function Create: THelper; static;\n end;\nimplementation\nend.`;
  1804. const result = extractFromSource('Test.pas', code);
  1805. const methods = result.nodes.filter((n) => n.kind === 'method');
  1806. const staticMethod = methods.find((m) => m.name === 'Create');
  1807. expect(staticMethod?.isStatic).toBe(true);
  1808. });
  1809. });
  1810. describe('Enum extraction', () => {
  1811. it('should extract enums with members', () => {
  1812. const code = `unit Test;\ninterface\ntype\n TColor = (clRed, clGreen, clBlue);\nimplementation\nend.`;
  1813. const result = extractFromSource('Test.pas', code);
  1814. const enumNode = result.nodes.find((n) => n.kind === 'enum');
  1815. expect(enumNode).toBeDefined();
  1816. expect(enumNode?.name).toBe('TColor');
  1817. const members = result.nodes.filter((n) => n.kind === 'enum_member');
  1818. expect(members.length).toBe(3);
  1819. expect(members.map((m) => m.name)).toEqual(['clRed', 'clGreen', 'clBlue']);
  1820. });
  1821. });
  1822. describe('Property extraction', () => {
  1823. it('should extract properties', () => {
  1824. const code = `unit Test;\ninterface\ntype\n TObj = class\n public\n property Name: string read FName write FName;\n end;\nimplementation\nend.`;
  1825. const result = extractFromSource('Test.pas', code);
  1826. const propNode = result.nodes.find((n) => n.kind === 'property');
  1827. expect(propNode).toBeDefined();
  1828. expect(propNode?.name).toBe('Name');
  1829. expect(propNode?.visibility).toBe('public');
  1830. });
  1831. });
  1832. describe('Constant extraction', () => {
  1833. it('should extract constants', () => {
  1834. const code = `unit Test;\ninterface\nconst\n MAX_RETRIES = 3;\n APP_NAME = 'MyApp';\nimplementation\nend.`;
  1835. const result = extractFromSource('Test.pas', code);
  1836. const constants = result.nodes.filter((n) => n.kind === 'constant');
  1837. expect(constants.length).toBe(2);
  1838. expect(constants.map((c) => c.name)).toContain('MAX_RETRIES');
  1839. expect(constants.map((c) => c.name)).toContain('APP_NAME');
  1840. });
  1841. });
  1842. describe('Type alias extraction', () => {
  1843. it('should extract type aliases', () => {
  1844. const code = `unit Test;\ninterface\ntype\n TUserName = string;\nimplementation\nend.`;
  1845. const result = extractFromSource('Test.pas', code);
  1846. const aliasNode = result.nodes.find((n) => n.kind === 'type_alias');
  1847. expect(aliasNode).toBeDefined();
  1848. expect(aliasNode?.name).toBe('TUserName');
  1849. });
  1850. });
  1851. describe('Call extraction', () => {
  1852. it('should extract calls from implementation bodies', () => {
  1853. 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.`;
  1854. const result = extractFromSource('Test.pas', code);
  1855. const callRef = result.unresolvedReferences.find(
  1856. (r) => r.referenceKind === 'calls'
  1857. );
  1858. expect(callRef).toBeDefined();
  1859. expect(callRef?.referenceName).toBe('WriteLn');
  1860. });
  1861. });
  1862. describe('Containment edges', () => {
  1863. it('should create contains edges for class members', () => {
  1864. const code = `unit Test;\ninterface\ntype\n TObj = class\n public\n procedure Foo;\n end;\nimplementation\nend.`;
  1865. const result = extractFromSource('Test.pas', code);
  1866. const classNode = result.nodes.find((n) => n.kind === 'class');
  1867. const methodNode = result.nodes.find((n) => n.kind === 'method');
  1868. expect(classNode).toBeDefined();
  1869. expect(methodNode).toBeDefined();
  1870. const containsEdge = result.edges.find(
  1871. (e) => e.source === classNode?.id && e.target === methodNode?.id && e.kind === 'contains'
  1872. );
  1873. expect(containsEdge).toBeDefined();
  1874. });
  1875. });
  1876. describe('Full fixture: UAuth.pas', () => {
  1877. const code = `unit UAuth;
  1878. interface
  1879. uses
  1880. System.SysUtils,
  1881. System.Classes;
  1882. type
  1883. ITokenValidator = interface
  1884. ['{11111111-1111-1111-1111-111111111111}']
  1885. function Validate(const AToken: string): Boolean;
  1886. end;
  1887. TAuthService = class(TInterfacedObject, ITokenValidator)
  1888. private
  1889. FToken: string;
  1890. FLoginCount: Integer;
  1891. procedure IncLoginCount;
  1892. protected
  1893. function GetToken: string;
  1894. public
  1895. constructor Create;
  1896. destructor Destroy; override;
  1897. function Validate(const AToken: string): Boolean;
  1898. function Login(const AUser, APass: string): string;
  1899. property Token: string read GetToken;
  1900. property LoginCount: Integer read FLoginCount;
  1901. end;
  1902. implementation
  1903. constructor TAuthService.Create;
  1904. begin
  1905. inherited Create;
  1906. FToken := '';
  1907. FLoginCount := 0;
  1908. end;
  1909. destructor TAuthService.Destroy;
  1910. begin
  1911. FToken := '';
  1912. inherited Destroy;
  1913. end;
  1914. procedure TAuthService.IncLoginCount;
  1915. begin
  1916. Inc(FLoginCount);
  1917. end;
  1918. function TAuthService.GetToken: string;
  1919. begin
  1920. Result := FToken;
  1921. end;
  1922. function TAuthService.Validate(const AToken: string): Boolean;
  1923. begin
  1924. Result := AToken <> '';
  1925. end;
  1926. function TAuthService.Login(const AUser, APass: string): string;
  1927. begin
  1928. IncLoginCount;
  1929. if Validate(AUser + ':' + APass) then
  1930. begin
  1931. FToken := AUser;
  1932. Result := 'ok';
  1933. end
  1934. else
  1935. Result := '';
  1936. end;
  1937. end.`;
  1938. it('should extract all expected nodes', () => {
  1939. const result = extractFromSource('UAuth.pas', code);
  1940. expect(result.errors).toHaveLength(0);
  1941. // Module
  1942. const moduleNode = result.nodes.find((n) => n.kind === 'module');
  1943. expect(moduleNode?.name).toBe('UAuth');
  1944. // Imports
  1945. const imports = result.nodes.filter((n) => n.kind === 'import');
  1946. expect(imports.length).toBe(2);
  1947. // Interface
  1948. const ifaceNode = result.nodes.find((n) => n.kind === 'interface');
  1949. expect(ifaceNode?.name).toBe('ITokenValidator');
  1950. // Class
  1951. const classNode = result.nodes.find((n) => n.kind === 'class');
  1952. expect(classNode?.name).toBe('TAuthService');
  1953. // Methods
  1954. const methods = result.nodes.filter((n) => n.kind === 'method');
  1955. expect(methods.length).toBeGreaterThanOrEqual(6);
  1956. expect(methods.map((m) => m.name)).toContain('Create');
  1957. expect(methods.map((m) => m.name)).toContain('Destroy');
  1958. expect(methods.map((m) => m.name)).toContain('Login');
  1959. // Fields
  1960. const fields = result.nodes.filter((n) => n.kind === 'field');
  1961. expect(fields.length).toBe(2);
  1962. expect(fields.every((f) => f.visibility === 'private')).toBe(true);
  1963. // Properties
  1964. const props = result.nodes.filter((n) => n.kind === 'property');
  1965. expect(props.length).toBe(2);
  1966. expect(props.map((p) => p.name)).toContain('Token');
  1967. expect(props.map((p) => p.name)).toContain('LoginCount');
  1968. });
  1969. it('should extract inheritance and interface implementation', () => {
  1970. const result = extractFromSource('UAuth.pas', code);
  1971. const extendsRef = result.unresolvedReferences.find(
  1972. (r) => r.referenceKind === 'extends'
  1973. );
  1974. expect(extendsRef?.referenceName).toBe('TInterfacedObject');
  1975. const implementsRef = result.unresolvedReferences.find(
  1976. (r) => r.referenceKind === 'implements'
  1977. );
  1978. expect(implementsRef?.referenceName).toBe('ITokenValidator');
  1979. });
  1980. it('should extract calls from implementation', () => {
  1981. const result = extractFromSource('UAuth.pas', code);
  1982. const callRefs = result.unresolvedReferences.filter(
  1983. (r) => r.referenceKind === 'calls'
  1984. );
  1985. expect(callRefs.map((r) => r.referenceName)).toContain('Inc');
  1986. expect(callRefs.map((r) => r.referenceName)).toContain('Validate');
  1987. });
  1988. });
  1989. describe('Full fixture: UTypes.pas', () => {
  1990. const code = `unit UTypes;
  1991. interface
  1992. uses
  1993. System.SysUtils;
  1994. const
  1995. C_MAX_RETRIES = 3;
  1996. C_DEFAULT_NAME = 'Guest';
  1997. type
  1998. TUserRole = (urAdmin, urEditor, urViewer);
  1999. TPoint2D = record
  2000. X: Double;
  2001. Y: Double;
  2002. end;
  2003. TUserName = string;
  2004. TUserInfo = class
  2005. public
  2006. type
  2007. TAddress = record
  2008. Street: string;
  2009. City: string;
  2010. Zip: string;
  2011. end;
  2012. private
  2013. FName: TUserName;
  2014. FRole: TUserRole;
  2015. FAddress: TAddress;
  2016. public
  2017. constructor Create(const AName: TUserName; ARole: TUserRole);
  2018. function GetDisplayName: string;
  2019. class function CreateAdmin(const AName: TUserName): TUserInfo; static;
  2020. property Name: TUserName read FName write FName;
  2021. property Role: TUserRole read FRole;
  2022. property Address: TAddress read FAddress write FAddress;
  2023. end;
  2024. implementation
  2025. constructor TUserInfo.Create(const AName: TUserName; ARole: TUserRole);
  2026. begin
  2027. FName := AName;
  2028. FRole := ARole;
  2029. end;
  2030. function TUserInfo.GetDisplayName: string;
  2031. begin
  2032. if FRole = urAdmin then
  2033. Result := '[Admin] ' + FName
  2034. else
  2035. Result := FName;
  2036. end;
  2037. class function TUserInfo.CreateAdmin(const AName: TUserName): TUserInfo;
  2038. begin
  2039. Result := TUserInfo.Create(AName, urAdmin);
  2040. end;
  2041. end.`;
  2042. it('should extract enums with members', () => {
  2043. const result = extractFromSource('UTypes.pas', code);
  2044. const enumNode = result.nodes.find((n) => n.kind === 'enum');
  2045. expect(enumNode?.name).toBe('TUserRole');
  2046. const members = result.nodes.filter((n) => n.kind === 'enum_member');
  2047. expect(members.length).toBe(3);
  2048. expect(members.map((m) => m.name)).toEqual(['urAdmin', 'urEditor', 'urViewer']);
  2049. });
  2050. it('should extract constants', () => {
  2051. const result = extractFromSource('UTypes.pas', code);
  2052. const constants = result.nodes.filter((n) => n.kind === 'constant');
  2053. expect(constants.length).toBe(2);
  2054. expect(constants.map((c) => c.name)).toContain('C_MAX_RETRIES');
  2055. expect(constants.map((c) => c.name)).toContain('C_DEFAULT_NAME');
  2056. });
  2057. it('should extract type aliases', () => {
  2058. const result = extractFromSource('UTypes.pas', code);
  2059. const aliases = result.nodes.filter((n) => n.kind === 'type_alias');
  2060. expect(aliases.map((a) => a.name)).toContain('TUserName');
  2061. });
  2062. it('should extract records as classes with fields', () => {
  2063. const result = extractFromSource('UTypes.pas', code);
  2064. const classes = result.nodes.filter((n) => n.kind === 'class');
  2065. expect(classes.map((c) => c.name)).toContain('TPoint2D');
  2066. // TPoint2D fields
  2067. const fields = result.nodes.filter((n) => n.kind === 'field');
  2068. expect(fields.map((f) => f.name)).toContain('X');
  2069. expect(fields.map((f) => f.name)).toContain('Y');
  2070. });
  2071. it('should extract static class methods', () => {
  2072. const result = extractFromSource('UTypes.pas', code);
  2073. const methods = result.nodes.filter((n) => n.kind === 'method');
  2074. const staticMethod = methods.find((m) => m.name === 'CreateAdmin');
  2075. expect(staticMethod).toBeDefined();
  2076. expect(staticMethod?.isStatic).toBe(true);
  2077. });
  2078. it('should extract nested types', () => {
  2079. const result = extractFromSource('UTypes.pas', code);
  2080. const classes = result.nodes.filter((n) => n.kind === 'class');
  2081. expect(classes.map((c) => c.name)).toContain('TAddress');
  2082. });
  2083. });
  2084. });
  2085. // =============================================================================
  2086. // DFM/FMX Extraction
  2087. // =============================================================================
  2088. describe('DFM/FMX Extraction', () => {
  2089. it('should extract components from DFM', () => {
  2090. const code = `object Form1: TForm1
  2091. Left = 0
  2092. Top = 0
  2093. Caption = 'My Form'
  2094. object Button1: TButton
  2095. Left = 10
  2096. Top = 10
  2097. Caption = 'Click Me'
  2098. end
  2099. end`;
  2100. const result = extractFromSource('Form1.dfm', code);
  2101. const components = result.nodes.filter((n) => n.kind === 'component');
  2102. expect(components.length).toBe(2);
  2103. expect(components.map((c) => c.name)).toContain('Form1');
  2104. expect(components.map((c) => c.name)).toContain('Button1');
  2105. const button = components.find((c) => c.name === 'Button1');
  2106. expect(button?.signature).toBe('TButton');
  2107. });
  2108. it('should extract nested component hierarchy', () => {
  2109. const code = `object Form1: TForm1
  2110. object Panel1: TPanel
  2111. object Label1: TLabel
  2112. Caption = 'Hello'
  2113. end
  2114. end
  2115. end`;
  2116. const result = extractFromSource('Form1.dfm', code);
  2117. const components = result.nodes.filter((n) => n.kind === 'component');
  2118. expect(components.length).toBe(3);
  2119. // Check nesting: Panel1 contains Label1
  2120. const panel = components.find((c) => c.name === 'Panel1');
  2121. const label = components.find((c) => c.name === 'Label1');
  2122. const containsEdge = result.edges.find(
  2123. (e) => e.source === panel?.id && e.target === label?.id && e.kind === 'contains'
  2124. );
  2125. expect(containsEdge).toBeDefined();
  2126. });
  2127. it('should extract event handler references', () => {
  2128. const code = `object Form1: TForm1
  2129. OnCreate = FormCreate
  2130. OnDestroy = FormDestroy
  2131. object Button1: TButton
  2132. OnClick = Button1Click
  2133. end
  2134. end`;
  2135. const result = extractFromSource('Form1.dfm', code);
  2136. const refs = result.unresolvedReferences;
  2137. expect(refs.length).toBe(3);
  2138. expect(refs.map((r) => r.referenceName)).toContain('FormCreate');
  2139. expect(refs.map((r) => r.referenceName)).toContain('FormDestroy');
  2140. expect(refs.map((r) => r.referenceName)).toContain('Button1Click');
  2141. expect(refs.every((r) => r.referenceKind === 'references')).toBe(true);
  2142. });
  2143. it('should handle multi-line properties', () => {
  2144. const code = `object Form1: TForm1
  2145. SQL.Strings = (
  2146. 'SELECT * FROM users'
  2147. 'WHERE active = 1')
  2148. object Button1: TButton
  2149. OnClick = Button1Click
  2150. end
  2151. end`;
  2152. const result = extractFromSource('Form1.dfm', code);
  2153. const components = result.nodes.filter((n) => n.kind === 'component');
  2154. expect(components.length).toBe(2);
  2155. const refs = result.unresolvedReferences;
  2156. expect(refs.length).toBe(1);
  2157. expect(refs[0]?.referenceName).toBe('Button1Click');
  2158. });
  2159. it('should handle inherited keyword', () => {
  2160. const code = `inherited Form1: TForm1
  2161. Caption = 'Inherited Form'
  2162. object Button1: TButton
  2163. OnClick = Button1Click
  2164. end
  2165. end`;
  2166. const result = extractFromSource('Form1.dfm', code);
  2167. const components = result.nodes.filter((n) => n.kind === 'component');
  2168. expect(components.length).toBe(2);
  2169. expect(components.map((c) => c.name)).toContain('Form1');
  2170. });
  2171. it('should handle item collection properties', () => {
  2172. const code = `object Form1: TForm1
  2173. object StatusBar1: TStatusBar
  2174. Panels = <
  2175. item
  2176. Width = 200
  2177. end
  2178. item
  2179. Width = 200
  2180. end>
  2181. end
  2182. end`;
  2183. const result = extractFromSource('Form1.dfm', code);
  2184. const components = result.nodes.filter((n) => n.kind === 'component');
  2185. expect(components.length).toBe(2);
  2186. });
  2187. describe('Full fixture: MainForm.dfm', () => {
  2188. const code = `object frmMain: TfrmMain
  2189. Left = 0
  2190. Top = 0
  2191. Caption = 'CodeGraph DFM Fixture'
  2192. ClientHeight = 480
  2193. ClientWidth = 640
  2194. OnCreate = FormCreate
  2195. OnDestroy = FormDestroy
  2196. object pnlTop: TPanel
  2197. Left = 0
  2198. Top = 0
  2199. Width = 640
  2200. Height = 50
  2201. object lblTitle: TLabel
  2202. Left = 16
  2203. Top = 16
  2204. Caption = 'Authentication Service'
  2205. end
  2206. object btnLogin: TButton
  2207. Left = 540
  2208. Top = 12
  2209. OnClick = btnLoginClick
  2210. end
  2211. end
  2212. object pnlContent: TPanel
  2213. Left = 0
  2214. Top = 50
  2215. object edtUsername: TEdit
  2216. Left = 16
  2217. Top = 16
  2218. OnChange = edtUsernameChange
  2219. end
  2220. object edtPassword: TEdit
  2221. Left = 16
  2222. Top = 48
  2223. OnKeyPress = edtPasswordKeyPress
  2224. end
  2225. object mmoLog: TMemo
  2226. Left = 16
  2227. Top = 88
  2228. end
  2229. end
  2230. object pnlStatus: TStatusBar
  2231. Left = 0
  2232. Top = 440
  2233. Panels = <
  2234. item
  2235. Width = 200
  2236. end
  2237. item
  2238. Width = 200
  2239. end>
  2240. end
  2241. end`;
  2242. it('should extract all components', () => {
  2243. const result = extractFromSource('MainForm.dfm', code);
  2244. const components = result.nodes.filter((n) => n.kind === 'component');
  2245. expect(components.length).toBe(9);
  2246. expect(components.map((c) => c.name)).toEqual(
  2247. expect.arrayContaining([
  2248. 'frmMain', 'pnlTop', 'lblTitle', 'btnLogin',
  2249. 'pnlContent', 'edtUsername', 'edtPassword', 'mmoLog', 'pnlStatus',
  2250. ])
  2251. );
  2252. });
  2253. it('should extract all event handlers', () => {
  2254. const result = extractFromSource('MainForm.dfm', code);
  2255. const refs = result.unresolvedReferences;
  2256. expect(refs.length).toBe(5);
  2257. expect(refs.map((r) => r.referenceName)).toEqual(
  2258. expect.arrayContaining([
  2259. 'FormCreate', 'FormDestroy', 'btnLoginClick',
  2260. 'edtUsernameChange', 'edtPasswordKeyPress',
  2261. ])
  2262. );
  2263. });
  2264. });
  2265. });
  2266. describe('Full Indexing', () => {
  2267. let tempDir: string;
  2268. beforeEach(() => {
  2269. tempDir = createTempDir();
  2270. });
  2271. afterEach(() => {
  2272. cleanupTempDir(tempDir);
  2273. });
  2274. it('should index a TypeScript file', async () => {
  2275. // Create test file
  2276. const srcDir = path.join(tempDir, 'src');
  2277. fs.mkdirSync(srcDir);
  2278. fs.writeFileSync(
  2279. path.join(srcDir, 'utils.ts'),
  2280. `
  2281. export function add(a: number, b: number): number {
  2282. return a + b;
  2283. }
  2284. export function multiply(a: number, b: number): number {
  2285. return a * b;
  2286. }
  2287. `
  2288. );
  2289. // Initialize and index
  2290. const cg = CodeGraph.initSync(tempDir);
  2291. const result = await cg.indexAll();
  2292. expect(result.success).toBe(true);
  2293. expect(result.filesIndexed).toBe(1);
  2294. expect(result.nodesCreated).toBeGreaterThanOrEqual(2);
  2295. // Check nodes were stored
  2296. const nodes = cg.getNodesInFile('src/utils.ts');
  2297. expect(nodes.length).toBeGreaterThanOrEqual(2);
  2298. const addFunc = nodes.find((n) => n.name === 'add');
  2299. expect(addFunc).toBeDefined();
  2300. expect(addFunc?.kind).toBe('function');
  2301. cg.close();
  2302. });
  2303. it('should index multiple files', async () => {
  2304. // Create test files
  2305. const srcDir = path.join(tempDir, 'src');
  2306. fs.mkdirSync(srcDir);
  2307. fs.writeFileSync(
  2308. path.join(srcDir, 'math.ts'),
  2309. `export function add(a: number, b: number) { return a + b; }`
  2310. );
  2311. fs.writeFileSync(
  2312. path.join(srcDir, 'string.ts'),
  2313. `export function capitalize(s: string) { return s.toUpperCase(); }`
  2314. );
  2315. // Initialize and index
  2316. const cg = CodeGraph.initSync(tempDir);
  2317. const result = await cg.indexAll();
  2318. expect(result.success).toBe(true);
  2319. expect(result.filesIndexed).toBe(2);
  2320. const files = cg.getFiles();
  2321. expect(files.length).toBe(2);
  2322. cg.close();
  2323. });
  2324. it('should track file hashes for incremental updates', async () => {
  2325. // Create initial file
  2326. const srcDir = path.join(tempDir, 'src');
  2327. fs.mkdirSync(srcDir);
  2328. fs.writeFileSync(path.join(srcDir, 'main.ts'), `export const x = 1;`);
  2329. // Initialize and index
  2330. const cg = CodeGraph.initSync(tempDir);
  2331. await cg.indexAll();
  2332. // Check file is tracked
  2333. const file = cg.getFile('src/main.ts');
  2334. expect(file).toBeDefined();
  2335. expect(file?.contentHash).toBeDefined();
  2336. // Modify file
  2337. fs.writeFileSync(path.join(srcDir, 'main.ts'), `export const x = 2;`);
  2338. // Check for changes
  2339. const changes = cg.getChangedFiles();
  2340. expect(changes.modified).toContain('src/main.ts');
  2341. cg.close();
  2342. });
  2343. it('should sync and detect changes', async () => {
  2344. // Create initial file
  2345. const srcDir = path.join(tempDir, 'src');
  2346. fs.mkdirSync(srcDir);
  2347. fs.writeFileSync(
  2348. path.join(srcDir, 'main.ts'),
  2349. `export function original() { return 1; }`
  2350. );
  2351. // Initialize and index
  2352. const cg = CodeGraph.initSync(tempDir);
  2353. await cg.indexAll();
  2354. const initialNodes = cg.getNodesInFile('src/main.ts');
  2355. expect(initialNodes.some((n) => n.name === 'original')).toBe(true);
  2356. // Modify file
  2357. fs.writeFileSync(
  2358. path.join(srcDir, 'main.ts'),
  2359. `export function updated() { return 2; }`
  2360. );
  2361. // Sync
  2362. const syncResult = await cg.sync();
  2363. expect(syncResult.filesModified).toBe(1);
  2364. // Check nodes were updated
  2365. const updatedNodes = cg.getNodesInFile('src/main.ts');
  2366. expect(updatedNodes.some((n) => n.name === 'updated')).toBe(true);
  2367. expect(updatedNodes.some((n) => n.name === 'original')).toBe(false);
  2368. cg.close();
  2369. });
  2370. });
  2371. describe('Path Normalization', () => {
  2372. it('should convert backslashes to forward slashes', () => {
  2373. expect(normalizePath('gui\\node_modules\\foo')).toBe('gui/node_modules/foo');
  2374. expect(normalizePath('src\\components\\Button.tsx')).toBe('src/components/Button.tsx');
  2375. });
  2376. it('should leave forward-slash paths unchanged', () => {
  2377. expect(normalizePath('src/components/Button.tsx')).toBe('src/components/Button.tsx');
  2378. });
  2379. it('should handle empty string', () => {
  2380. expect(normalizePath('')).toBe('');
  2381. });
  2382. });
  2383. describe('Directory Exclusion', () => {
  2384. let tempDir: string;
  2385. beforeEach(() => {
  2386. tempDir = createTempDir();
  2387. });
  2388. afterEach(() => {
  2389. cleanupTempDir(tempDir);
  2390. });
  2391. it('should exclude node_modules directories', () => {
  2392. // Create structure: src/index.ts + node_modules/pkg/index.js
  2393. const srcDir = path.join(tempDir, 'src');
  2394. const nmDir = path.join(tempDir, 'node_modules', 'pkg');
  2395. fs.mkdirSync(srcDir, { recursive: true });
  2396. fs.mkdirSync(nmDir, { recursive: true });
  2397. fs.writeFileSync(path.join(srcDir, 'index.ts'), 'export const x = 1;');
  2398. fs.writeFileSync(path.join(nmDir, 'index.js'), 'module.exports = {};');
  2399. const config = { ...DEFAULT_CONFIG, rootDir: tempDir };
  2400. const files = scanDirectory(tempDir, config);
  2401. expect(files).toContain('src/index.ts');
  2402. expect(files.every((f) => !f.includes('node_modules'))).toBe(true);
  2403. });
  2404. it('should exclude nested node_modules directories', () => {
  2405. // Create structure: packages/app/node_modules/pkg/index.js
  2406. const srcDir = path.join(tempDir, 'packages', 'app', 'src');
  2407. const nmDir = path.join(tempDir, 'packages', 'app', 'node_modules', 'pkg');
  2408. fs.mkdirSync(srcDir, { recursive: true });
  2409. fs.mkdirSync(nmDir, { recursive: true });
  2410. fs.writeFileSync(path.join(srcDir, 'index.ts'), 'export const x = 1;');
  2411. fs.writeFileSync(path.join(nmDir, 'index.js'), 'module.exports = {};');
  2412. const config = { ...DEFAULT_CONFIG, rootDir: tempDir };
  2413. const files = scanDirectory(tempDir, config);
  2414. expect(files).toContain('packages/app/src/index.ts');
  2415. expect(files.every((f) => !f.includes('node_modules'))).toBe(true);
  2416. });
  2417. it('should exclude .git directories', () => {
  2418. const srcDir = path.join(tempDir, 'src');
  2419. const gitDir = path.join(tempDir, '.git', 'objects');
  2420. fs.mkdirSync(srcDir, { recursive: true });
  2421. fs.mkdirSync(gitDir, { recursive: true });
  2422. fs.writeFileSync(path.join(srcDir, 'index.ts'), 'export const x = 1;');
  2423. fs.writeFileSync(path.join(gitDir, 'pack.ts'), 'export const y = 2;');
  2424. const config = { ...DEFAULT_CONFIG, rootDir: tempDir };
  2425. const files = scanDirectory(tempDir, config);
  2426. expect(files).toContain('src/index.ts');
  2427. expect(files.every((f) => !f.includes('.git'))).toBe(true);
  2428. });
  2429. it('should return forward-slash paths on all platforms', () => {
  2430. const srcDir = path.join(tempDir, 'src', 'components');
  2431. fs.mkdirSync(srcDir, { recursive: true });
  2432. fs.writeFileSync(path.join(srcDir, 'Button.tsx'), 'export function Button() {}');
  2433. const config = { ...DEFAULT_CONFIG, rootDir: tempDir };
  2434. const files = scanDirectory(tempDir, config);
  2435. expect(files.length).toBe(1);
  2436. expect(files[0]).toBe('src/components/Button.tsx');
  2437. expect(files[0]).not.toContain('\\');
  2438. });
  2439. it('should respect .codegraphignore marker', () => {
  2440. const srcDir = path.join(tempDir, 'src');
  2441. const vendorDir = path.join(tempDir, 'vendor');
  2442. fs.mkdirSync(srcDir, { recursive: true });
  2443. fs.mkdirSync(vendorDir, { recursive: true });
  2444. fs.writeFileSync(path.join(srcDir, 'index.ts'), 'export const x = 1;');
  2445. fs.writeFileSync(path.join(vendorDir, 'lib.ts'), 'export const y = 2;');
  2446. fs.writeFileSync(path.join(vendorDir, '.codegraphignore'), '');
  2447. const config = { ...DEFAULT_CONFIG, rootDir: tempDir };
  2448. const files = scanDirectory(tempDir, config);
  2449. expect(files).toContain('src/index.ts');
  2450. expect(files.every((f) => !f.includes('vendor'))).toBe(true);
  2451. });
  2452. });