1
0

extraction.test.ts 87 KB

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