1
0

extraction.test.ts 125 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897
  1. /**
  2. * Extraction Tests
  3. *
  4. * Tests for the tree-sitter extraction system.
  5. */
  6. import { describe, it, expect, beforeAll, beforeEach, afterEach } from 'vitest';
  7. import * as fs from 'fs';
  8. import * as path from 'path';
  9. import * as os from 'os';
  10. import { CodeGraph } from '../src';
  11. import { extractFromSource, scanDirectory } from '../src/extraction';
  12. import { detectLanguage, isLanguageSupported, getSupportedLanguages, initGrammars, loadAllGrammars } from '../src/extraction/grammars';
  13. import { normalizePath } from '../src/utils';
  14. beforeAll(async () => {
  15. await initGrammars();
  16. await loadAllGrammars();
  17. });
  18. // Create a temporary directory for each test
  19. function createTempDir(): string {
  20. return fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-test-'));
  21. }
  22. // Clean up temporary directory
  23. function cleanupTempDir(dir: string): void {
  24. if (fs.existsSync(dir)) {
  25. fs.rmSync(dir, { recursive: true, force: true });
  26. }
  27. }
  28. describe('Language Detection', () => {
  29. it('should detect TypeScript files', () => {
  30. expect(detectLanguage('src/index.ts')).toBe('typescript');
  31. expect(detectLanguage('components/Button.tsx')).toBe('tsx');
  32. });
  33. it('should detect JavaScript files', () => {
  34. expect(detectLanguage('index.js')).toBe('javascript');
  35. expect(detectLanguage('App.jsx')).toBe('jsx');
  36. expect(detectLanguage('config.mjs')).toBe('javascript');
  37. });
  38. it('should detect Python files', () => {
  39. expect(detectLanguage('main.py')).toBe('python');
  40. });
  41. it('should detect Go files', () => {
  42. expect(detectLanguage('main.go')).toBe('go');
  43. });
  44. it('should detect Rust files', () => {
  45. expect(detectLanguage('lib.rs')).toBe('rust');
  46. });
  47. it('should detect Java files', () => {
  48. expect(detectLanguage('Main.java')).toBe('java');
  49. });
  50. it('should detect C files', () => {
  51. expect(detectLanguage('main.c')).toBe('c');
  52. expect(detectLanguage('utils.h')).toBe('c');
  53. });
  54. it('should detect C++ files', () => {
  55. expect(detectLanguage('main.cpp')).toBe('cpp');
  56. expect(detectLanguage('class.hpp')).toBe('cpp');
  57. });
  58. it('should detect C# files', () => {
  59. expect(detectLanguage('Program.cs')).toBe('csharp');
  60. });
  61. it('should detect PHP files', () => {
  62. expect(detectLanguage('index.php')).toBe('php');
  63. });
  64. it('should detect Ruby files', () => {
  65. expect(detectLanguage('app.rb')).toBe('ruby');
  66. });
  67. it('should detect Swift files', () => {
  68. expect(detectLanguage('ViewController.swift')).toBe('swift');
  69. });
  70. it('should detect Kotlin files', () => {
  71. expect(detectLanguage('MainActivity.kt')).toBe('kotlin');
  72. expect(detectLanguage('build.gradle.kts')).toBe('kotlin');
  73. });
  74. it('should detect Dart files', () => {
  75. expect(detectLanguage('main.dart')).toBe('dart');
  76. });
  77. it('should return unknown for unsupported extensions', () => {
  78. expect(detectLanguage('styles.css')).toBe('unknown');
  79. expect(detectLanguage('data.json')).toBe('unknown');
  80. });
  81. });
  82. describe('Language Support', () => {
  83. it('should report supported languages', () => {
  84. expect(isLanguageSupported('typescript')).toBe(true);
  85. expect(isLanguageSupported('python')).toBe(true);
  86. expect(isLanguageSupported('go')).toBe(true);
  87. expect(isLanguageSupported('unknown')).toBe(false);
  88. });
  89. it('should list all supported languages', () => {
  90. const languages = getSupportedLanguages();
  91. expect(languages).toContain('typescript');
  92. expect(languages).toContain('javascript');
  93. expect(languages).toContain('python');
  94. expect(languages).toContain('go');
  95. expect(languages).toContain('rust');
  96. expect(languages).toContain('java');
  97. expect(languages).toContain('csharp');
  98. expect(languages).toContain('php');
  99. expect(languages).toContain('ruby');
  100. expect(languages).toContain('swift');
  101. expect(languages).toContain('kotlin');
  102. expect(languages).toContain('dart');
  103. });
  104. });
  105. describe('TypeScript Extraction', () => {
  106. it('should extract function declarations', () => {
  107. const code = `
  108. export function processPayment(amount: number): Promise<Receipt> {
  109. return stripe.charge(amount);
  110. }
  111. `;
  112. const result = extractFromSource('payment.ts', code);
  113. // File node + function node
  114. const fileNode = result.nodes.find((n) => n.kind === 'file');
  115. expect(fileNode).toBeDefined();
  116. expect(fileNode?.name).toBe('payment.ts');
  117. const funcNode = result.nodes.find((n) => n.kind === 'function');
  118. expect(funcNode).toMatchObject({
  119. kind: 'function',
  120. name: 'processPayment',
  121. language: 'typescript',
  122. isExported: true,
  123. });
  124. expect(funcNode?.signature).toContain('amount: number');
  125. });
  126. it('should extract class declarations', () => {
  127. const code = `
  128. export class PaymentService {
  129. private stripe: StripeClient;
  130. constructor(apiKey: string) {
  131. this.stripe = new StripeClient(apiKey);
  132. }
  133. async charge(amount: number): Promise<Receipt> {
  134. return this.stripe.charge(amount);
  135. }
  136. }
  137. `;
  138. const result = extractFromSource('service.ts', code);
  139. const classNode = result.nodes.find((n) => n.kind === 'class');
  140. const methodNodes = result.nodes.filter((n) => n.kind === 'method');
  141. expect(classNode).toBeDefined();
  142. expect(classNode?.name).toBe('PaymentService');
  143. expect(classNode?.isExported).toBe(true);
  144. expect(methodNodes.length).toBeGreaterThanOrEqual(1);
  145. const chargeMethod = methodNodes.find((m) => m.name === 'charge');
  146. expect(chargeMethod).toBeDefined();
  147. });
  148. it('should extract interfaces', () => {
  149. const code = `
  150. export interface User {
  151. id: string;
  152. name: string;
  153. email: string;
  154. }
  155. `;
  156. const result = extractFromSource('types.ts', code);
  157. const fileNode = result.nodes.find((n) => n.kind === 'file');
  158. expect(fileNode).toBeDefined();
  159. const ifaceNode = result.nodes.find((n) => n.kind === 'interface');
  160. expect(ifaceNode).toMatchObject({
  161. kind: 'interface',
  162. name: 'User',
  163. isExported: true,
  164. });
  165. });
  166. it('should track function calls', () => {
  167. const code = `
  168. function main() {
  169. const result = processData();
  170. console.log(result);
  171. }
  172. `;
  173. const result = extractFromSource('main.ts', code);
  174. expect(result.unresolvedReferences.length).toBeGreaterThan(0);
  175. const calls = result.unresolvedReferences.filter((r) => r.referenceKind === 'calls');
  176. expect(calls.some((c) => c.referenceName === 'processData')).toBe(true);
  177. });
  178. });
  179. describe('Arrow Function Export Extraction', () => {
  180. it('should extract exported arrow functions assigned to const', () => {
  181. const code = `
  182. export const useAuth = (): AuthContextValue => {
  183. return useContext(AuthContext);
  184. };
  185. `;
  186. const result = extractFromSource('hooks.ts', code);
  187. const funcNode = result.nodes.find((n) => n.kind === 'function' && n.name === 'useAuth');
  188. expect(funcNode).toBeDefined();
  189. expect(funcNode).toMatchObject({
  190. kind: 'function',
  191. name: 'useAuth',
  192. isExported: true,
  193. });
  194. });
  195. it('should extract exported function expressions assigned to const', () => {
  196. const code = `
  197. export const processData = function(input: string): string {
  198. return input.trim();
  199. };
  200. `;
  201. const result = extractFromSource('utils.ts', code);
  202. const funcNode = result.nodes.find((n) => n.kind === 'function' && n.name === 'processData');
  203. expect(funcNode).toBeDefined();
  204. expect(funcNode).toMatchObject({
  205. kind: 'function',
  206. name: 'processData',
  207. isExported: true,
  208. });
  209. });
  210. it('should not extract non-exported arrow functions as exported', () => {
  211. const code = `
  212. const internalHelper = () => {
  213. return 42;
  214. };
  215. `;
  216. const result = extractFromSource('internal.ts', code);
  217. const helperNode = result.nodes.find((n) => n.name === 'internalHelper');
  218. expect(helperNode).toBeDefined();
  219. expect(helperNode?.isExported).toBeFalsy();
  220. });
  221. it('should still skip truly anonymous arrow functions', () => {
  222. const code = `
  223. const items = [1, 2, 3].map((x) => x * 2);
  224. `;
  225. const result = extractFromSource('anon.ts', code);
  226. // The inline arrow function passed to .map() has no variable_declarator parent
  227. // and should remain anonymous (skipped)
  228. const anonFunctions = result.nodes.filter(
  229. (n) => n.kind === 'function' && n.name === '<anonymous>'
  230. );
  231. expect(anonFunctions).toHaveLength(0);
  232. });
  233. it('should extract multiple exported arrow functions from the same file', () => {
  234. const code = `
  235. export const add = (a: number, b: number): number => a + b;
  236. export const subtract = (a: number, b: number): number => a - b;
  237. const internal = () => 'not exported';
  238. `;
  239. const result = extractFromSource('math.ts', code);
  240. const exported = result.nodes.filter((n) => n.kind === 'function' && n.isExported);
  241. expect(exported).toHaveLength(2);
  242. expect(exported.map((n) => n.name).sort()).toEqual(['add', 'subtract']);
  243. const internalNode = result.nodes.find((n) => n.name === 'internal');
  244. expect(internalNode).toBeDefined();
  245. expect(internalNode?.isExported).toBeFalsy();
  246. });
  247. it('should extract arrow functions in JavaScript files', () => {
  248. const code = `
  249. export const fetchData = async () => {
  250. const response = await fetch('/api/data');
  251. return response.json();
  252. };
  253. `;
  254. const result = extractFromSource('api.js', code);
  255. const funcNode = result.nodes.find((n) => n.kind === 'function' && n.name === 'fetchData');
  256. expect(funcNode).toBeDefined();
  257. expect(funcNode).toMatchObject({
  258. kind: 'function',
  259. name: 'fetchData',
  260. isExported: true,
  261. });
  262. });
  263. });
  264. describe('Type Alias Extraction', () => {
  265. it('should extract exported type aliases in TypeScript', () => {
  266. const code = `
  267. export type AuthContextValue = {
  268. user: User | null;
  269. login: () => void;
  270. logout: () => void;
  271. };
  272. `;
  273. const result = extractFromSource('types.ts', code);
  274. const typeNode = result.nodes.find((n) => n.kind === 'type_alias');
  275. expect(typeNode).toMatchObject({
  276. kind: 'type_alias',
  277. name: 'AuthContextValue',
  278. isExported: true,
  279. });
  280. });
  281. it('should extract non-exported type aliases', () => {
  282. const code = `
  283. type InternalState = {
  284. loading: boolean;
  285. error: string | null;
  286. };
  287. `;
  288. const result = extractFromSource('internal.ts', code);
  289. const typeNode = result.nodes.find((n) => n.kind === 'type_alias');
  290. expect(typeNode).toMatchObject({
  291. kind: 'type_alias',
  292. name: 'InternalState',
  293. isExported: false,
  294. });
  295. });
  296. it('should extract multiple type aliases from the same file', () => {
  297. const code = `
  298. export type UnitSystem = 'metric' | 'imperial';
  299. export type DateFormat = 'ISO' | 'US' | 'EU';
  300. type Internal = string;
  301. `;
  302. const result = extractFromSource('config.ts', code);
  303. const typeAliases = result.nodes.filter((n) => n.kind === 'type_alias');
  304. expect(typeAliases).toHaveLength(3);
  305. const exported = typeAliases.filter((n) => n.isExported);
  306. expect(exported).toHaveLength(2);
  307. expect(exported.map((n) => n.name).sort()).toEqual(['DateFormat', 'UnitSystem']);
  308. });
  309. });
  310. describe('Exported Variable Extraction', () => {
  311. it('should extract exported const with call expression (Zustand store)', () => {
  312. const code = `
  313. export const useUIStore = create<UIState>((set) => ({
  314. isOpen: false,
  315. toggle: () => set((s) => ({ isOpen: !s.isOpen })),
  316. }));
  317. `;
  318. const result = extractFromSource('store.ts', code);
  319. const varNode = result.nodes.find((n) => n.kind === 'constant' && n.name === 'useUIStore');
  320. expect(varNode).toBeDefined();
  321. expect(varNode?.isExported).toBe(true);
  322. });
  323. it('should extract exported const with object literal', () => {
  324. const code = `
  325. export const config = {
  326. apiUrl: 'https://api.example.com',
  327. timeout: 5000,
  328. };
  329. `;
  330. const result = extractFromSource('config.ts', code);
  331. const varNode = result.nodes.find((n) => n.kind === 'constant' && n.name === 'config');
  332. expect(varNode).toBeDefined();
  333. expect(varNode?.isExported).toBe(true);
  334. });
  335. it('should extract exported const with array literal', () => {
  336. const code = `
  337. export const SCREEN_NAMES = ['home', 'settings', 'profile'] as const;
  338. `;
  339. const result = extractFromSource('constants.ts', code);
  340. const varNode = result.nodes.find((n) => n.kind === 'constant' && n.name === 'SCREEN_NAMES');
  341. expect(varNode).toBeDefined();
  342. expect(varNode?.isExported).toBe(true);
  343. });
  344. it('should extract exported const with primitive value', () => {
  345. const code = `
  346. export const MAX_RETRIES = 3;
  347. export const API_VERSION = "v2";
  348. `;
  349. const result = extractFromSource('constants.ts', code);
  350. const variables = result.nodes.filter((n) => n.kind === 'constant');
  351. expect(variables).toHaveLength(2);
  352. expect(variables.map((n) => n.name).sort()).toEqual(['API_VERSION', 'MAX_RETRIES']);
  353. });
  354. it('should NOT duplicate arrow functions as both function and variable', () => {
  355. const code = `
  356. export const useAuth = () => {
  357. return useContext(AuthContext);
  358. };
  359. `;
  360. const result = extractFromSource('hooks.ts', code);
  361. // Should be extracted as function (from arrow function handler), NOT as variable
  362. const funcNodes = result.nodes.filter((n) => n.kind === 'function' && n.name === 'useAuth');
  363. const varNodes = result.nodes.filter((n) => n.kind === 'variable' && n.name === 'useAuth');
  364. expect(funcNodes).toHaveLength(1);
  365. expect(varNodes).toHaveLength(0);
  366. });
  367. it('should extract non-exported const as non-exported variable', () => {
  368. const code = `
  369. const internalConfig = {
  370. debug: true,
  371. };
  372. `;
  373. const result = extractFromSource('internal.ts', code);
  374. // Non-exported const at file level should be extracted as a constant (not exported)
  375. const varNodes = result.nodes.filter((n) => (n.kind === 'variable' || n.kind === 'constant') && n.name === 'internalConfig');
  376. expect(varNodes).toHaveLength(1);
  377. expect(varNodes[0]?.isExported).toBeFalsy();
  378. });
  379. it('should extract Zod schema exports', () => {
  380. const code = `
  381. export const userSchema = z.object({
  382. id: z.string(),
  383. name: z.string(),
  384. email: z.string().email(),
  385. });
  386. `;
  387. const result = extractFromSource('schemas.ts', code);
  388. const varNode = result.nodes.find((n) => n.kind === 'constant' && n.name === 'userSchema');
  389. expect(varNode).toBeDefined();
  390. expect(varNode?.isExported).toBe(true);
  391. });
  392. it('should extract XState machine exports', () => {
  393. const code = `
  394. export const authMachine = createMachine({
  395. id: "auth",
  396. initial: "idle",
  397. states: {
  398. idle: {},
  399. authenticated: {},
  400. },
  401. });
  402. `;
  403. const result = extractFromSource('machine.ts', code);
  404. const varNode = result.nodes.find((n) => n.kind === 'constant' && n.name === 'authMachine');
  405. expect(varNode).toBeDefined();
  406. expect(varNode?.isExported).toBe(true);
  407. });
  408. });
  409. describe('File Node Extraction', () => {
  410. it('should create a file-kind node for each parsed file', () => {
  411. const code = `
  412. export function greet(name: string): string {
  413. return "Hello " + name;
  414. }
  415. `;
  416. const result = extractFromSource('greeter.ts', code);
  417. const fileNode = result.nodes.find((n) => n.kind === 'file');
  418. expect(fileNode).toBeDefined();
  419. expect(fileNode?.name).toBe('greeter.ts');
  420. expect(fileNode?.filePath).toBe('greeter.ts');
  421. expect(fileNode?.language).toBe('typescript');
  422. expect(fileNode?.startLine).toBe(1);
  423. });
  424. it('should create file nodes for Python files', () => {
  425. const code = `
  426. def main():
  427. pass
  428. `;
  429. const result = extractFromSource('main.py', code);
  430. const fileNode = result.nodes.find((n) => n.kind === 'file');
  431. expect(fileNode).toBeDefined();
  432. expect(fileNode?.name).toBe('main.py');
  433. expect(fileNode?.language).toBe('python');
  434. });
  435. it('should create containment edges from file node to top-level declarations', () => {
  436. const code = `
  437. export function foo() {}
  438. export function bar() {}
  439. `;
  440. const result = extractFromSource('fns.ts', code);
  441. const fileNode = result.nodes.find((n) => n.kind === 'file');
  442. expect(fileNode).toBeDefined();
  443. // There should be contains edges from the file node to each function
  444. const containsEdges = result.edges.filter(
  445. (e) => e.source === fileNode?.id && e.kind === 'contains'
  446. );
  447. expect(containsEdges.length).toBeGreaterThanOrEqual(2);
  448. });
  449. });
  450. describe('Python Extraction', () => {
  451. it('should extract function definitions', () => {
  452. const code = `
  453. def calculate_total(items: list, tax_rate: float) -> float:
  454. """Calculate total with tax."""
  455. subtotal = sum(item.price for item in items)
  456. return subtotal * (1 + tax_rate)
  457. `;
  458. const result = extractFromSource('calc.py', code);
  459. const fileNode = result.nodes.find((n) => n.kind === 'file');
  460. expect(fileNode).toBeDefined();
  461. const funcNode = result.nodes.find((n) => n.kind === 'function');
  462. expect(funcNode).toMatchObject({
  463. kind: 'function',
  464. name: 'calculate_total',
  465. language: 'python',
  466. });
  467. });
  468. it('should extract class definitions', () => {
  469. const code = `
  470. class UserService:
  471. """Service for managing users."""
  472. def __init__(self, db):
  473. self.db = db
  474. def get_user(self, user_id: str) -> User:
  475. return self.db.find_user(user_id)
  476. `;
  477. const result = extractFromSource('service.py', code);
  478. const classNode = result.nodes.find((n) => n.kind === 'class');
  479. expect(classNode).toBeDefined();
  480. expect(classNode?.name).toBe('UserService');
  481. });
  482. });
  483. describe('Go Extraction', () => {
  484. it('should extract function declarations', () => {
  485. const code = `
  486. package main
  487. func ProcessOrder(order Order) (Receipt, error) {
  488. // Process the order
  489. return Receipt{}, nil
  490. }
  491. `;
  492. const result = extractFromSource('main.go', code);
  493. const funcNode = result.nodes.find((n) => n.kind === 'function');
  494. expect(funcNode).toBeDefined();
  495. expect(funcNode?.name).toBe('ProcessOrder');
  496. });
  497. it('should extract method declarations', () => {
  498. const code = `
  499. package main
  500. type Service struct {
  501. db *Database
  502. }
  503. func (s *Service) GetUser(id string) (*User, error) {
  504. return s.db.FindUser(id)
  505. }
  506. `;
  507. const result = extractFromSource('service.go', code);
  508. const methodNode = result.nodes.find((n) => n.kind === 'method');
  509. expect(methodNode).toBeDefined();
  510. expect(methodNode?.name).toBe('GetUser');
  511. });
  512. });
  513. describe('Rust Extraction', () => {
  514. it('should extract function declarations', () => {
  515. const code = `
  516. pub fn process_data(input: &str) -> Result<Output, Error> {
  517. // Process data
  518. Ok(Output::new())
  519. }
  520. `;
  521. const result = extractFromSource('lib.rs', code);
  522. const funcNode = result.nodes.find((n) => n.kind === 'function');
  523. expect(funcNode).toBeDefined();
  524. expect(funcNode?.name).toBe('process_data');
  525. expect(funcNode?.visibility).toBe('public');
  526. });
  527. it('should extract struct declarations', () => {
  528. const code = `
  529. pub struct User {
  530. pub id: String,
  531. pub name: String,
  532. email: String,
  533. }
  534. `;
  535. const result = extractFromSource('models.rs', code);
  536. const structNode = result.nodes.find((n) => n.kind === 'struct');
  537. expect(structNode).toBeDefined();
  538. expect(structNode?.name).toBe('User');
  539. });
  540. it('should extract trait declarations', () => {
  541. const code = `
  542. pub trait Repository {
  543. fn find(&self, id: &str) -> Option<Entity>;
  544. fn save(&mut self, entity: Entity) -> Result<(), Error>;
  545. }
  546. `;
  547. const result = extractFromSource('traits.rs', code);
  548. const traitNode = result.nodes.find((n) => n.kind === 'trait');
  549. expect(traitNode).toBeDefined();
  550. expect(traitNode?.name).toBe('Repository');
  551. });
  552. it('should extract impl Trait for Type as implements edges', () => {
  553. const code = `
  554. pub struct MyCache {}
  555. pub trait Cache {
  556. fn get(&self, key: &str) -> Option<String>;
  557. }
  558. impl Cache for MyCache {
  559. fn get(&self, key: &str) -> Option<String> {
  560. None
  561. }
  562. }
  563. `;
  564. const result = extractFromSource('cache.rs', code);
  565. // Should have an unresolved reference for implements
  566. const implRef = result.unresolvedReferences.find(
  567. (r) => r.referenceKind === 'implements' && r.referenceName === 'Cache'
  568. );
  569. expect(implRef).toBeDefined();
  570. // The struct MyCache should be the source
  571. const myCacheNode = result.nodes.find((n) => n.name === 'MyCache' && n.kind === 'struct');
  572. expect(myCacheNode).toBeDefined();
  573. expect(implRef?.fromNodeId).toBe(myCacheNode?.id);
  574. });
  575. it('should extract trait supertraits as extends references', () => {
  576. const code = `
  577. pub trait Display {}
  578. pub trait Error: Display {
  579. fn description(&self) -> &str;
  580. }
  581. `;
  582. const result = extractFromSource('error.rs', code);
  583. const extendsRef = result.unresolvedReferences.find(
  584. (r) => r.referenceKind === 'extends' && r.referenceName === 'Display'
  585. );
  586. expect(extendsRef).toBeDefined();
  587. const errorTrait = result.nodes.find((n) => n.name === 'Error' && n.kind === 'trait');
  588. expect(errorTrait).toBeDefined();
  589. expect(extendsRef?.fromNodeId).toBe(errorTrait?.id);
  590. });
  591. it('should not create implements edges for plain impl blocks', () => {
  592. const code = `
  593. pub struct Counter {
  594. count: u32,
  595. }
  596. impl Counter {
  597. pub fn new() -> Counter {
  598. Counter { count: 0 }
  599. }
  600. pub fn increment(&mut self) {
  601. self.count += 1;
  602. }
  603. }
  604. `;
  605. const result = extractFromSource('counter.rs', code);
  606. // Should have no implements references (no trait involved)
  607. const implRefs = result.unresolvedReferences.filter(
  608. (r) => r.referenceKind === 'implements'
  609. );
  610. expect(implRefs).toHaveLength(0);
  611. });
  612. });
  613. describe('Java Extraction', () => {
  614. it('should extract class declarations', () => {
  615. const code = `
  616. public class UserService {
  617. private final UserRepository repository;
  618. public UserService(UserRepository repository) {
  619. this.repository = repository;
  620. }
  621. public User getUser(String id) {
  622. return repository.findById(id);
  623. }
  624. }
  625. `;
  626. const result = extractFromSource('UserService.java', code);
  627. const classNode = result.nodes.find((n) => n.kind === 'class');
  628. expect(classNode).toBeDefined();
  629. expect(classNode?.name).toBe('UserService');
  630. expect(classNode?.visibility).toBe('public');
  631. });
  632. it('should extract method declarations', () => {
  633. const code = `
  634. public class Calculator {
  635. public static int add(int a, int b) {
  636. return a + b;
  637. }
  638. }
  639. `;
  640. const result = extractFromSource('Calculator.java', code);
  641. const methodNode = result.nodes.find((n) => n.kind === 'method' && n.name === 'add');
  642. expect(methodNode).toBeDefined();
  643. expect(methodNode?.isStatic).toBe(true);
  644. });
  645. });
  646. describe('C# Extraction', () => {
  647. it('should extract class declarations', () => {
  648. const code = `
  649. public class OrderService
  650. {
  651. private readonly IOrderRepository _repository;
  652. public OrderService(IOrderRepository repository)
  653. {
  654. _repository = repository;
  655. }
  656. public async Task<Order> GetOrderAsync(string id)
  657. {
  658. return await _repository.FindByIdAsync(id);
  659. }
  660. }
  661. `;
  662. const result = extractFromSource('OrderService.cs', code);
  663. const classNode = result.nodes.find((n) => n.kind === 'class');
  664. expect(classNode).toBeDefined();
  665. expect(classNode?.name).toBe('OrderService');
  666. expect(classNode?.visibility).toBe('public');
  667. });
  668. });
  669. describe('PHP Extraction', () => {
  670. it('should extract class declarations', () => {
  671. const code = `<?php
  672. class UserController
  673. {
  674. private UserService $userService;
  675. public function __construct(UserService $userService)
  676. {
  677. $this->userService = $userService;
  678. }
  679. public function show(string $id): User
  680. {
  681. return $this->userService->find($id);
  682. }
  683. }
  684. `;
  685. const result = extractFromSource('UserController.php', code);
  686. const classNode = result.nodes.find((n) => n.kind === 'class');
  687. expect(classNode).toBeDefined();
  688. expect(classNode?.name).toBe('UserController');
  689. });
  690. it('should extract class inheritance (extends) and interface implementation', () => {
  691. const code = `<?php
  692. class ChildController extends BaseController implements Serializable, JsonSerializable
  693. {
  694. public function serialize(): string
  695. {
  696. return json_encode($this);
  697. }
  698. }
  699. `;
  700. const result = extractFromSource('ChildController.php', code);
  701. const classNode = result.nodes.find((n) => n.kind === 'class');
  702. expect(classNode).toBeDefined();
  703. expect(classNode?.name).toBe('ChildController');
  704. const extendsRef = result.unresolvedReferences.find(
  705. (r) => r.referenceKind === 'extends'
  706. );
  707. expect(extendsRef).toBeDefined();
  708. expect(extendsRef?.referenceName).toBe('BaseController');
  709. const implementsRefs = result.unresolvedReferences.filter(
  710. (r) => r.referenceKind === 'implements'
  711. );
  712. expect(implementsRefs.length).toBe(2);
  713. expect(implementsRefs.map((r) => r.referenceName)).toContain('Serializable');
  714. expect(implementsRefs.map((r) => r.referenceName)).toContain('JsonSerializable');
  715. });
  716. });
  717. describe('Swift Extraction', () => {
  718. it('should extract class declarations', () => {
  719. const code = `
  720. public class NetworkManager {
  721. private let session: URLSession
  722. public init(session: URLSession = .shared) {
  723. self.session = session
  724. }
  725. public func fetchData(from url: URL) async throws -> Data {
  726. let (data, _) = try await session.data(from: url)
  727. return data
  728. }
  729. }
  730. `;
  731. const result = extractFromSource('NetworkManager.swift', code);
  732. const classNode = result.nodes.find((n) => n.kind === 'class');
  733. expect(classNode).toBeDefined();
  734. expect(classNode?.name).toBe('NetworkManager');
  735. });
  736. it('should extract function declarations', () => {
  737. const code = `
  738. func calculateSum(_ numbers: [Int]) -> Int {
  739. return numbers.reduce(0, +)
  740. }
  741. public func formatCurrency(amount: Double) -> String {
  742. return String(format: "$%.2f", amount)
  743. }
  744. `;
  745. const result = extractFromSource('utils.swift', code);
  746. const functions = result.nodes.filter((n) => n.kind === 'function');
  747. expect(functions.length).toBeGreaterThanOrEqual(1);
  748. });
  749. it('should extract struct declarations', () => {
  750. const code = `
  751. public struct User {
  752. let id: UUID
  753. var name: String
  754. var email: String
  755. func displayName() -> String {
  756. return name
  757. }
  758. }
  759. `;
  760. const result = extractFromSource('User.swift', code);
  761. const structNode = result.nodes.find((n) => n.kind === 'struct');
  762. expect(structNode).toBeDefined();
  763. expect(structNode?.name).toBe('User');
  764. });
  765. it('should extract protocol declarations', () => {
  766. const code = `
  767. public protocol Repository {
  768. associatedtype Entity
  769. func find(id: String) async throws -> Entity?
  770. func save(_ entity: Entity) async throws
  771. }
  772. `;
  773. const result = extractFromSource('Repository.swift', code);
  774. const protocolNode = result.nodes.find((n) => n.kind === 'interface');
  775. expect(protocolNode).toBeDefined();
  776. expect(protocolNode?.name).toBe('Repository');
  777. });
  778. it('should extract class inheritance and protocol conformance', () => {
  779. const code = `
  780. class DataRequest: Request {
  781. func validate() {}
  782. }
  783. class UploadRequest: DataRequest, Sendable {
  784. func upload() {}
  785. }
  786. enum AFError: Error {
  787. case invalidURL
  788. }
  789. struct HTTPMethod: RawRepresentable {
  790. let rawValue: String
  791. }
  792. protocol UploadConvertible: URLRequestConvertible {
  793. func asURLRequest() throws -> URLRequest
  794. }
  795. `;
  796. const result = extractFromSource('Inheritance.swift', code);
  797. const extendsRefs = result.unresolvedReferences.filter(
  798. (r) => r.referenceKind === 'extends'
  799. );
  800. // DataRequest extends Request
  801. expect(extendsRefs.find((r) => r.referenceName === 'Request')).toBeDefined();
  802. // UploadRequest extends DataRequest and Sendable
  803. expect(extendsRefs.find((r) => r.referenceName === 'DataRequest')).toBeDefined();
  804. expect(extendsRefs.find((r) => r.referenceName === 'Sendable')).toBeDefined();
  805. // AFError extends Error
  806. expect(extendsRefs.find((r) => r.referenceName === 'Error')).toBeDefined();
  807. // HTTPMethod extends RawRepresentable
  808. expect(extendsRefs.find((r) => r.referenceName === 'RawRepresentable')).toBeDefined();
  809. // UploadConvertible extends URLRequestConvertible
  810. expect(extendsRefs.find((r) => r.referenceName === 'URLRequestConvertible')).toBeDefined();
  811. });
  812. });
  813. describe('Kotlin Extraction', () => {
  814. it('should extract class declarations', () => {
  815. const code = `
  816. class UserRepository(private val database: Database) {
  817. fun findById(id: String): User? {
  818. return database.query("SELECT * FROM users WHERE id = ?", id)
  819. }
  820. suspend fun save(user: User) {
  821. database.insert(user)
  822. }
  823. }
  824. `;
  825. const result = extractFromSource('UserRepository.kt', code);
  826. const classNode = result.nodes.find((n) => n.kind === 'class');
  827. expect(classNode).toBeDefined();
  828. expect(classNode?.name).toBe('UserRepository');
  829. });
  830. it('should extract function declarations', () => {
  831. const code = `
  832. fun calculateTotal(items: List<Item>): Double {
  833. return items.sumOf { it.price }
  834. }
  835. suspend fun fetchUserData(userId: String): User {
  836. return api.getUser(userId)
  837. }
  838. `;
  839. const result = extractFromSource('utils.kt', code);
  840. const functions = result.nodes.filter((n) => n.kind === 'function');
  841. expect(functions.length).toBeGreaterThanOrEqual(1);
  842. });
  843. it('should detect suspend functions as async', () => {
  844. const code = `
  845. suspend fun loadData(): List<String> {
  846. delay(1000)
  847. return listOf("a", "b", "c")
  848. }
  849. `;
  850. const result = extractFromSource('loader.kt', code);
  851. const funcNode = result.nodes.find((n) => n.kind === 'function');
  852. expect(funcNode).toBeDefined();
  853. expect(funcNode?.isAsync).toBe(true);
  854. });
  855. it('should extract fun interface declarations', () => {
  856. const code = `
  857. fun interface OnObjectRetainedListener {
  858. fun onObjectRetained()
  859. }
  860. `;
  861. const result = extractFromSource('listener.kt', code);
  862. const ifaceNode = result.nodes.find((n) => n.kind === 'interface');
  863. expect(ifaceNode).toBeDefined();
  864. expect(ifaceNode?.name).toBe('OnObjectRetainedListener');
  865. const methodNode = result.nodes.find((n) => n.kind === 'method');
  866. expect(methodNode).toBeDefined();
  867. expect(methodNode?.name).toBe('onObjectRetained');
  868. expect(methodNode?.qualifiedName).toBe('OnObjectRetainedListener::onObjectRetained');
  869. });
  870. it('should extract complex fun interface with nested classes', () => {
  871. const code = `
  872. fun interface EventListener {
  873. fun onEvent(event: Event)
  874. sealed class Event {
  875. class DumpingHeap : Event()
  876. }
  877. }
  878. `;
  879. const result = extractFromSource('events.kt', code);
  880. const ifaceNode = result.nodes.find((n) => n.kind === 'interface');
  881. expect(ifaceNode).toBeDefined();
  882. expect(ifaceNode?.name).toBe('EventListener');
  883. // Nested sealed class should still be extracted (as sibling due to grammar limitations)
  884. const eventClass = result.nodes.find((n) => n.kind === 'class' && n.name === 'Event');
  885. expect(eventClass).toBeDefined();
  886. const dumpingHeap = result.nodes.find((n) => n.kind === 'class' && n.name === 'DumpingHeap');
  887. expect(dumpingHeap).toBeDefined();
  888. });
  889. it('should not affect regular function declarations', () => {
  890. const code = `
  891. fun interface MyCallback {
  892. fun invoke(value: Int)
  893. }
  894. fun regularFunction(): String {
  895. return "hello"
  896. }
  897. `;
  898. const result = extractFromSource('mixed.kt', code);
  899. const ifaceNode = result.nodes.find((n) => n.kind === 'interface');
  900. expect(ifaceNode).toBeDefined();
  901. expect(ifaceNode?.name).toBe('MyCallback');
  902. const funcNode = result.nodes.find((n) => n.kind === 'function');
  903. expect(funcNode).toBeDefined();
  904. expect(funcNode?.name).toBe('regularFunction');
  905. });
  906. it('should extract fun interface with annotation on method (Pattern 2b)', () => {
  907. // When the SAM method has annotations like @Throws, tree-sitter produces a different
  908. // misparse: function_declaration > ERROR("interface Name {") instead of
  909. // function_declaration > user_type("interface"). This is the OkHttp Interceptor pattern.
  910. const code = `
  911. import java.io.IOException
  912. fun interface Interceptor {
  913. @Throws(IOException::class)
  914. fun intercept(chain: Chain): Response
  915. }
  916. `;
  917. const result = extractFromSource('interceptor.kt', code);
  918. const ifaceNode = result.nodes.find((n) => n.kind === 'interface');
  919. expect(ifaceNode).toBeDefined();
  920. expect(ifaceNode?.name).toBe('Interceptor');
  921. });
  922. it('should extract methods from interface with nested fun interface', () => {
  923. // When an interface contains a nested `fun interface`, tree-sitter misparsed
  924. // the parent body as ERROR. Methods inside should still be extracted.
  925. const code = `
  926. interface WebSocket {
  927. fun request(): Request
  928. fun send(text: String): Boolean
  929. fun cancel()
  930. fun interface Factory {
  931. fun newWebSocket(request: Request): WebSocket
  932. }
  933. }
  934. `;
  935. const result = extractFromSource('websocket.kt', code);
  936. const wsIface = result.nodes.find((n) => n.kind === 'interface' && n.name === 'WebSocket');
  937. expect(wsIface).toBeDefined();
  938. const methods = result.nodes.filter((n) => n.kind === 'method' && n.qualifiedName?.startsWith('WebSocket::'));
  939. const methodNames = methods.map((m) => m.name);
  940. expect(methodNames).toContain('request');
  941. expect(methodNames).toContain('send');
  942. expect(methodNames).toContain('cancel');
  943. });
  944. });
  945. describe('Dart Extraction', () => {
  946. it('should extract class declarations', () => {
  947. const code = `
  948. class UserService {
  949. final Database _db;
  950. Future<User> findById(String id) async {
  951. return await _db.query(id);
  952. }
  953. void _privateMethod() {}
  954. }
  955. `;
  956. const result = extractFromSource('service.dart', code);
  957. const classNode = result.nodes.find((n) => n.kind === 'class');
  958. expect(classNode).toBeDefined();
  959. expect(classNode?.name).toBe('UserService');
  960. expect(classNode?.visibility).toBe('public');
  961. const methodNodes = result.nodes.filter((n) => n.kind === 'method');
  962. expect(methodNodes.length).toBeGreaterThanOrEqual(2);
  963. const findById = methodNodes.find((m) => m.name === 'findById');
  964. expect(findById).toBeDefined();
  965. expect(findById?.isAsync).toBe(true);
  966. const privateMethod = methodNodes.find((m) => m.name === '_privateMethod');
  967. expect(privateMethod).toBeDefined();
  968. expect(privateMethod?.visibility).toBe('private');
  969. });
  970. it('should extract top-level function declarations', () => {
  971. const code = `
  972. void topLevelFunction(String name) {
  973. print(name);
  974. }
  975. `;
  976. const result = extractFromSource('utils.dart', code);
  977. const funcNode = result.nodes.find((n) => n.kind === 'function');
  978. expect(funcNode).toBeDefined();
  979. expect(funcNode?.name).toBe('topLevelFunction');
  980. expect(funcNode?.language).toBe('dart');
  981. });
  982. it('should extract enum declarations', () => {
  983. const code = `
  984. enum Status { active, inactive, pending }
  985. `;
  986. const result = extractFromSource('models.dart', code);
  987. const enumNode = result.nodes.find((n) => n.kind === 'enum');
  988. expect(enumNode).toBeDefined();
  989. expect(enumNode?.name).toBe('Status');
  990. });
  991. it('should extract mixin declarations', () => {
  992. const code = `
  993. mixin LoggerMixin {
  994. void log(String message) {}
  995. }
  996. `;
  997. const result = extractFromSource('mixins.dart', code);
  998. const classNode = result.nodes.find((n) => n.kind === 'class');
  999. expect(classNode).toBeDefined();
  1000. expect(classNode?.name).toBe('LoggerMixin');
  1001. const methodNode = result.nodes.find((n) => n.kind === 'method');
  1002. expect(methodNode).toBeDefined();
  1003. expect(methodNode?.name).toBe('log');
  1004. });
  1005. it('should extract extension declarations', () => {
  1006. const code = `
  1007. extension StringExt on String {
  1008. bool get isBlank => trim().isEmpty;
  1009. }
  1010. `;
  1011. const result = extractFromSource('extensions.dart', code);
  1012. const classNode = result.nodes.find((n) => n.kind === 'class');
  1013. expect(classNode).toBeDefined();
  1014. expect(classNode?.name).toBe('StringExt');
  1015. });
  1016. it('should detect static methods', () => {
  1017. const code = `
  1018. class Utils {
  1019. static void doWork() {}
  1020. }
  1021. `;
  1022. const result = extractFromSource('utils.dart', code);
  1023. const methodNode = result.nodes.find((n) => n.kind === 'method');
  1024. expect(methodNode).toBeDefined();
  1025. expect(methodNode?.name).toBe('doWork');
  1026. expect(methodNode?.isStatic).toBe(true);
  1027. });
  1028. it('should detect async functions', () => {
  1029. const code = `
  1030. Future<String> fetchData() async {
  1031. return await http.get('/data');
  1032. }
  1033. `;
  1034. const result = extractFromSource('api.dart', code);
  1035. const funcNode = result.nodes.find((n) => n.kind === 'function');
  1036. expect(funcNode).toBeDefined();
  1037. expect(funcNode?.name).toBe('fetchData');
  1038. expect(funcNode?.isAsync).toBe(true);
  1039. });
  1040. it('should detect private visibility via underscore convention', () => {
  1041. const code = `
  1042. void _privateHelper() {}
  1043. void publicFunction() {}
  1044. `;
  1045. const result = extractFromSource('helpers.dart', code);
  1046. const functions = result.nodes.filter((n) => n.kind === 'function');
  1047. const privateFunc = functions.find((f) => f.name === '_privateHelper');
  1048. const publicFunc = functions.find((f) => f.name === 'publicFunction');
  1049. expect(privateFunc?.visibility).toBe('private');
  1050. expect(publicFunc?.visibility).toBe('public');
  1051. });
  1052. });
  1053. describe('Import Extraction', () => {
  1054. describe('TypeScript/JavaScript imports', () => {
  1055. it('should extract default imports', () => {
  1056. const code = `import React from 'react';`;
  1057. const result = extractFromSource('app.tsx', code);
  1058. const importNode = result.nodes.find((n) => n.kind === 'import');
  1059. expect(importNode).toBeDefined();
  1060. expect(importNode?.name).toBe('react');
  1061. expect(importNode?.signature).toBe("import React from 'react';");
  1062. });
  1063. it('should extract named imports', () => {
  1064. const code = `import { Bug, Database } from '@phosphor-icons/react';`;
  1065. const result = extractFromSource('icons.tsx', code);
  1066. const importNode = result.nodes.find((n) => n.kind === 'import');
  1067. expect(importNode).toBeDefined();
  1068. expect(importNode?.name).toBe('@phosphor-icons/react');
  1069. expect(importNode?.signature).toContain('Bug');
  1070. expect(importNode?.signature).toContain('Database');
  1071. });
  1072. it('should extract namespace imports', () => {
  1073. const code = `import * as Icons from '@phosphor-icons/react';`;
  1074. const result = extractFromSource('icons.tsx', code);
  1075. const importNode = result.nodes.find((n) => n.kind === 'import');
  1076. expect(importNode).toBeDefined();
  1077. expect(importNode?.name).toBe('@phosphor-icons/react');
  1078. expect(importNode?.signature).toContain('* as Icons');
  1079. });
  1080. it('should extract side-effect imports', () => {
  1081. const code = `import './styles.css';`;
  1082. const result = extractFromSource('app.tsx', code);
  1083. const importNode = result.nodes.find((n) => n.kind === 'import');
  1084. expect(importNode).toBeDefined();
  1085. expect(importNode?.name).toBe('./styles.css');
  1086. });
  1087. it('should extract mixed imports (default + named)', () => {
  1088. const code = `import React, { useState, useEffect } from 'react';`;
  1089. const result = extractFromSource('app.tsx', code);
  1090. const importNode = result.nodes.find((n) => n.kind === 'import');
  1091. expect(importNode).toBeDefined();
  1092. expect(importNode?.name).toBe('react');
  1093. expect(importNode?.signature).toContain('React');
  1094. expect(importNode?.signature).toContain('useState');
  1095. expect(importNode?.signature).toContain('useEffect');
  1096. });
  1097. it('should extract multiple import statements', () => {
  1098. const code = `
  1099. import React from 'react';
  1100. import { Button } from './components';
  1101. import './styles.css';
  1102. `;
  1103. const result = extractFromSource('app.tsx', code);
  1104. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1105. expect(importNodes.length).toBe(3);
  1106. const names = importNodes.map((n) => n.name);
  1107. expect(names).toContain('react');
  1108. expect(names).toContain('./components');
  1109. expect(names).toContain('./styles.css');
  1110. });
  1111. it('should extract type imports', () => {
  1112. const code = `import type { FC, ReactNode } from 'react';`;
  1113. const result = extractFromSource('types.ts', code);
  1114. const importNode = result.nodes.find((n) => n.kind === 'import');
  1115. expect(importNode).toBeDefined();
  1116. expect(importNode?.name).toBe('react');
  1117. expect(importNode?.signature).toContain('type');
  1118. expect(importNode?.signature).toContain('FC');
  1119. });
  1120. it('should extract aliased named imports', () => {
  1121. const code = `import { useState as useStateAlias } from 'react';`;
  1122. const result = extractFromSource('hooks.ts', code);
  1123. const importNode = result.nodes.find((n) => n.kind === 'import');
  1124. expect(importNode).toBeDefined();
  1125. expect(importNode?.name).toBe('react');
  1126. expect(importNode?.signature).toContain('useState');
  1127. expect(importNode?.signature).toContain('useStateAlias');
  1128. });
  1129. it('should extract relative path imports', () => {
  1130. const code = `import { helper } from '../utils/helper';`;
  1131. const result = extractFromSource('components/Button.tsx', code);
  1132. const importNode = result.nodes.find((n) => n.kind === 'import');
  1133. expect(importNode).toBeDefined();
  1134. expect(importNode?.name).toBe('../utils/helper');
  1135. expect(importNode?.signature).toContain('helper');
  1136. });
  1137. });
  1138. describe('Python imports', () => {
  1139. it('should extract simple import statement', () => {
  1140. const code = `import json`;
  1141. const result = extractFromSource('utils.py', code);
  1142. const importNode = result.nodes.find((n) => n.kind === 'import');
  1143. expect(importNode).toBeDefined();
  1144. expect(importNode?.name).toBe('json');
  1145. });
  1146. it('should extract from import statement', () => {
  1147. const code = `from os import path`;
  1148. const result = extractFromSource('utils.py', code);
  1149. const importNode = result.nodes.find((n) => n.kind === 'import');
  1150. expect(importNode).toBeDefined();
  1151. expect(importNode?.name).toBe('os');
  1152. expect(importNode?.signature).toContain('path');
  1153. });
  1154. it('should extract multiple imports from same module', () => {
  1155. const code = `from typing import List, Dict, Optional`;
  1156. const result = extractFromSource('types.py', code);
  1157. const importNode = result.nodes.find((n) => n.kind === 'import');
  1158. expect(importNode).toBeDefined();
  1159. expect(importNode?.name).toBe('typing');
  1160. expect(importNode?.signature).toContain('List');
  1161. expect(importNode?.signature).toContain('Dict');
  1162. });
  1163. it('should extract multiple import statements', () => {
  1164. const code = `
  1165. import os
  1166. import sys
  1167. `;
  1168. const result = extractFromSource('main.py', code);
  1169. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1170. expect(importNodes.length).toBe(2);
  1171. const names = importNodes.map((n) => n.name);
  1172. expect(names).toContain('os');
  1173. expect(names).toContain('sys');
  1174. });
  1175. it('should extract aliased import', () => {
  1176. const code = `import numpy as np`;
  1177. const result = extractFromSource('data.py', code);
  1178. const importNode = result.nodes.find((n) => n.kind === 'import');
  1179. expect(importNode).toBeDefined();
  1180. expect(importNode?.name).toBe('numpy');
  1181. expect(importNode?.signature).toContain('as np');
  1182. });
  1183. it('should extract relative import', () => {
  1184. const code = `from .utils import helper`;
  1185. const result = extractFromSource('module.py', code);
  1186. const importNode = result.nodes.find((n) => n.kind === 'import');
  1187. expect(importNode).toBeDefined();
  1188. expect(importNode?.name).toBe('.utils');
  1189. expect(importNode?.signature).toContain('helper');
  1190. });
  1191. it('should extract wildcard import', () => {
  1192. const code = `from typing import *`;
  1193. const result = extractFromSource('types.py', code);
  1194. const importNode = result.nodes.find((n) => n.kind === 'import');
  1195. expect(importNode).toBeDefined();
  1196. expect(importNode?.name).toBe('typing');
  1197. expect(importNode?.signature).toContain('*');
  1198. });
  1199. });
  1200. describe('Rust imports', () => {
  1201. it('should extract simple use declaration', () => {
  1202. const code = `use std::io;`;
  1203. const result = extractFromSource('main.rs', code);
  1204. const importNode = result.nodes.find((n) => n.kind === 'import');
  1205. expect(importNode).toBeDefined();
  1206. expect(importNode?.name).toBe('std');
  1207. expect(importNode?.signature).toBe('use std::io;');
  1208. });
  1209. it('should extract scoped use list', () => {
  1210. const code = `use std::{ffi::OsStr, io, path::Path};`;
  1211. const result = extractFromSource('main.rs', code);
  1212. const importNode = result.nodes.find((n) => n.kind === 'import');
  1213. expect(importNode).toBeDefined();
  1214. expect(importNode?.name).toBe('std');
  1215. expect(importNode?.signature).toContain('ffi::OsStr');
  1216. expect(importNode?.signature).toContain('path::Path');
  1217. });
  1218. it('should extract crate imports', () => {
  1219. const code = `use crate::error::Error;`;
  1220. const result = extractFromSource('lib.rs', code);
  1221. const importNode = result.nodes.find((n) => n.kind === 'import');
  1222. expect(importNode).toBeDefined();
  1223. expect(importNode?.name).toBe('crate');
  1224. });
  1225. it('should extract super imports', () => {
  1226. const code = `use super::utils;`;
  1227. const result = extractFromSource('submod.rs', code);
  1228. const importNode = result.nodes.find((n) => n.kind === 'import');
  1229. expect(importNode).toBeDefined();
  1230. expect(importNode?.name).toBe('super');
  1231. });
  1232. it('should extract external crate imports', () => {
  1233. const code = `use serde::{Serialize, Deserialize};`;
  1234. const result = extractFromSource('types.rs', code);
  1235. const importNode = result.nodes.find((n) => n.kind === 'import');
  1236. expect(importNode).toBeDefined();
  1237. expect(importNode?.name).toBe('serde');
  1238. expect(importNode?.signature).toContain('Serialize');
  1239. expect(importNode?.signature).toContain('Deserialize');
  1240. });
  1241. });
  1242. describe('Go imports', () => {
  1243. it('should extract single import', () => {
  1244. const code = `
  1245. package main
  1246. import "fmt"
  1247. `;
  1248. const result = extractFromSource('main.go', code);
  1249. const importNode = result.nodes.find((n) => n.kind === 'import');
  1250. expect(importNode).toBeDefined();
  1251. expect(importNode?.name).toBe('fmt');
  1252. });
  1253. it('should extract grouped imports', () => {
  1254. const code = `
  1255. package main
  1256. import (
  1257. "fmt"
  1258. "os"
  1259. "encoding/json"
  1260. )
  1261. `;
  1262. const result = extractFromSource('main.go', code);
  1263. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1264. expect(importNodes.length).toBe(3);
  1265. const names = importNodes.map((n) => n.name);
  1266. expect(names).toContain('fmt');
  1267. expect(names).toContain('os');
  1268. expect(names).toContain('encoding/json');
  1269. });
  1270. it('should extract aliased import', () => {
  1271. const code = `
  1272. package main
  1273. import f "fmt"
  1274. `;
  1275. const result = extractFromSource('main.go', code);
  1276. const importNode = result.nodes.find((n) => n.kind === 'import');
  1277. expect(importNode).toBeDefined();
  1278. expect(importNode?.name).toBe('fmt');
  1279. expect(importNode?.signature).toContain('f');
  1280. });
  1281. it('should extract dot import', () => {
  1282. const code = `
  1283. package main
  1284. import . "math"
  1285. `;
  1286. const result = extractFromSource('main.go', code);
  1287. const importNode = result.nodes.find((n) => n.kind === 'import');
  1288. expect(importNode).toBeDefined();
  1289. expect(importNode?.name).toBe('math');
  1290. expect(importNode?.signature).toContain('.');
  1291. });
  1292. it('should extract blank import', () => {
  1293. const code = `
  1294. package main
  1295. import _ "github.com/go-sql-driver/mysql"
  1296. `;
  1297. const result = extractFromSource('main.go', code);
  1298. const importNode = result.nodes.find((n) => n.kind === 'import');
  1299. expect(importNode).toBeDefined();
  1300. expect(importNode?.name).toBe('github.com/go-sql-driver/mysql');
  1301. expect(importNode?.signature).toContain('_');
  1302. });
  1303. });
  1304. describe('Swift imports', () => {
  1305. it('should extract simple import', () => {
  1306. const code = `import Foundation`;
  1307. const result = extractFromSource('main.swift', code);
  1308. const importNode = result.nodes.find((n) => n.kind === 'import');
  1309. expect(importNode).toBeDefined();
  1310. expect(importNode?.name).toBe('Foundation');
  1311. expect(importNode?.signature).toBe('import Foundation');
  1312. });
  1313. it('should extract @testable import', () => {
  1314. const code = `@testable import Alamofire`;
  1315. const result = extractFromSource('Tests.swift', code);
  1316. const importNode = result.nodes.find((n) => n.kind === 'import');
  1317. expect(importNode).toBeDefined();
  1318. expect(importNode?.name).toBe('Alamofire');
  1319. expect(importNode?.signature).toContain('@testable');
  1320. });
  1321. it('should extract @preconcurrency import', () => {
  1322. const code = `@preconcurrency import Security`;
  1323. const result = extractFromSource('Auth.swift', code);
  1324. const importNode = result.nodes.find((n) => n.kind === 'import');
  1325. expect(importNode).toBeDefined();
  1326. expect(importNode?.name).toBe('Security');
  1327. });
  1328. it('should extract multiple imports', () => {
  1329. const code = `
  1330. import Foundation
  1331. import UIKit
  1332. import Alamofire
  1333. `;
  1334. const result = extractFromSource('App.swift', code);
  1335. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1336. expect(importNodes.length).toBe(3);
  1337. const names = importNodes.map((n) => n.name);
  1338. expect(names).toContain('Foundation');
  1339. expect(names).toContain('UIKit');
  1340. expect(names).toContain('Alamofire');
  1341. });
  1342. });
  1343. describe('Kotlin imports', () => {
  1344. it('should extract simple import', () => {
  1345. const code = `import java.io.IOException`;
  1346. const result = extractFromSource('Main.kt', code);
  1347. const importNode = result.nodes.find((n) => n.kind === 'import');
  1348. expect(importNode).toBeDefined();
  1349. expect(importNode?.name).toBe('java.io.IOException');
  1350. expect(importNode?.signature).toBe('import java.io.IOException');
  1351. });
  1352. it('should extract aliased import', () => {
  1353. const code = `import okhttp3.Request.Builder as RequestBuilder`;
  1354. const result = extractFromSource('Utils.kt', code);
  1355. const importNode = result.nodes.find((n) => n.kind === 'import');
  1356. expect(importNode).toBeDefined();
  1357. expect(importNode?.name).toBe('okhttp3.Request.Builder');
  1358. expect(importNode?.signature).toContain('as RequestBuilder');
  1359. });
  1360. it('should extract wildcard import', () => {
  1361. const code = `import java.util.concurrent.TimeUnit.*`;
  1362. const result = extractFromSource('Time.kt', code);
  1363. const importNode = result.nodes.find((n) => n.kind === 'import');
  1364. expect(importNode).toBeDefined();
  1365. expect(importNode?.name).toBe('java.util.concurrent.TimeUnit');
  1366. expect(importNode?.signature).toContain('.*');
  1367. });
  1368. it('should extract multiple imports', () => {
  1369. const code = `
  1370. import java.io.IOException
  1371. import kotlin.test.assertFailsWith
  1372. import okhttp3.OkHttpClient
  1373. `;
  1374. const result = extractFromSource('Test.kt', code);
  1375. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1376. expect(importNodes.length).toBe(3);
  1377. const names = importNodes.map((n) => n.name);
  1378. expect(names).toContain('java.io.IOException');
  1379. expect(names).toContain('kotlin.test.assertFailsWith');
  1380. expect(names).toContain('okhttp3.OkHttpClient');
  1381. });
  1382. });
  1383. describe('Java imports', () => {
  1384. it('should extract simple import', () => {
  1385. const code = `import java.util.List;`;
  1386. const result = extractFromSource('Main.java', code);
  1387. const importNode = result.nodes.find((n) => n.kind === 'import');
  1388. expect(importNode).toBeDefined();
  1389. expect(importNode?.name).toBe('java.util.List');
  1390. expect(importNode?.signature).toBe('import java.util.List;');
  1391. });
  1392. it('should extract static import', () => {
  1393. const code = `import static java.util.Collections.emptyList;`;
  1394. const result = extractFromSource('Utils.java', code);
  1395. const importNode = result.nodes.find((n) => n.kind === 'import');
  1396. expect(importNode).toBeDefined();
  1397. expect(importNode?.name).toBe('java.util.Collections.emptyList');
  1398. expect(importNode?.signature).toContain('static');
  1399. });
  1400. it('should extract wildcard import', () => {
  1401. const code = `import java.util.*;`;
  1402. const result = extractFromSource('App.java', code);
  1403. const importNode = result.nodes.find((n) => n.kind === 'import');
  1404. expect(importNode).toBeDefined();
  1405. expect(importNode?.name).toBe('java.util');
  1406. expect(importNode?.signature).toContain('.*');
  1407. });
  1408. it('should extract nested class import', () => {
  1409. const code = `import java.util.Map.Entry;`;
  1410. const result = extractFromSource('MapUtil.java', code);
  1411. const importNode = result.nodes.find((n) => n.kind === 'import');
  1412. expect(importNode).toBeDefined();
  1413. expect(importNode?.name).toBe('java.util.Map.Entry');
  1414. });
  1415. it('should extract multiple imports', () => {
  1416. const code = `
  1417. import java.util.List;
  1418. import java.util.Map;
  1419. import java.io.IOException;
  1420. `;
  1421. const result = extractFromSource('Service.java', code);
  1422. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1423. expect(importNodes.length).toBe(3);
  1424. const names = importNodes.map((n) => n.name);
  1425. expect(names).toContain('java.util.List');
  1426. expect(names).toContain('java.util.Map');
  1427. expect(names).toContain('java.io.IOException');
  1428. });
  1429. });
  1430. describe('C# imports', () => {
  1431. it('should extract simple using', () => {
  1432. const code = `using System;`;
  1433. const result = extractFromSource('Program.cs', code);
  1434. const importNode = result.nodes.find((n) => n.kind === 'import');
  1435. expect(importNode).toBeDefined();
  1436. expect(importNode?.name).toBe('System');
  1437. expect(importNode?.signature).toBe('using System;');
  1438. });
  1439. it('should extract qualified using', () => {
  1440. const code = `using System.Collections.Generic;`;
  1441. const result = extractFromSource('Utils.cs', code);
  1442. const importNode = result.nodes.find((n) => n.kind === 'import');
  1443. expect(importNode).toBeDefined();
  1444. expect(importNode?.name).toBe('System.Collections.Generic');
  1445. });
  1446. it('should extract static using', () => {
  1447. const code = `using static System.Console;`;
  1448. const result = extractFromSource('App.cs', code);
  1449. const importNode = result.nodes.find((n) => n.kind === 'import');
  1450. expect(importNode).toBeDefined();
  1451. expect(importNode?.name).toBe('System.Console');
  1452. expect(importNode?.signature).toContain('static');
  1453. });
  1454. it('should extract alias using', () => {
  1455. const code = `using MyList = System.Collections.Generic.List<int>;`;
  1456. const result = extractFromSource('Types.cs', code);
  1457. const importNode = result.nodes.find((n) => n.kind === 'import');
  1458. expect(importNode).toBeDefined();
  1459. expect(importNode?.name).toBe('System.Collections.Generic.List<int>');
  1460. expect(importNode?.signature).toContain('MyList =');
  1461. });
  1462. it('should extract multiple usings', () => {
  1463. const code = `
  1464. using System;
  1465. using System.Threading.Tasks;
  1466. using Microsoft.Extensions.DependencyInjection;
  1467. `;
  1468. const result = extractFromSource('Service.cs', code);
  1469. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1470. expect(importNodes.length).toBe(3);
  1471. const names = importNodes.map((n) => n.name);
  1472. expect(names).toContain('System');
  1473. expect(names).toContain('System.Threading.Tasks');
  1474. expect(names).toContain('Microsoft.Extensions.DependencyInjection');
  1475. });
  1476. });
  1477. describe('PHP imports', () => {
  1478. it('should extract simple use', () => {
  1479. const code = `<?php use PHPUnit\\Framework\\TestCase;`;
  1480. const result = extractFromSource('Test.php', code);
  1481. const importNode = result.nodes.find((n) => n.kind === 'import');
  1482. expect(importNode).toBeDefined();
  1483. expect(importNode?.name).toBe('PHPUnit\\Framework\\TestCase');
  1484. });
  1485. it('should extract aliased use', () => {
  1486. const code = `<?php use Mockery as m;`;
  1487. const result = extractFromSource('Test.php', code);
  1488. const importNode = result.nodes.find((n) => n.kind === 'import');
  1489. expect(importNode).toBeDefined();
  1490. expect(importNode?.name).toBe('Mockery');
  1491. expect(importNode?.signature).toContain('as m');
  1492. });
  1493. it('should extract function use', () => {
  1494. const code = `<?php use function Illuminate\\Support\\env;`;
  1495. const result = extractFromSource('helpers.php', code);
  1496. const importNode = result.nodes.find((n) => n.kind === 'import');
  1497. expect(importNode).toBeDefined();
  1498. expect(importNode?.name).toBe('Illuminate\\Support\\env');
  1499. expect(importNode?.signature).toContain('function');
  1500. });
  1501. it('should extract grouped use', () => {
  1502. const code = `<?php use Illuminate\\Database\\{Model, Builder};`;
  1503. const result = extractFromSource('Models.php', code);
  1504. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1505. expect(importNodes.length).toBe(2);
  1506. const names = importNodes.map((n) => n.name);
  1507. expect(names).toContain('Illuminate\\Database\\Model');
  1508. expect(names).toContain('Illuminate\\Database\\Builder');
  1509. });
  1510. it('should extract multiple uses', () => {
  1511. const code = `<?php
  1512. use Illuminate\\Support\\Collection;
  1513. use Illuminate\\Support\\Str;
  1514. use Closure;
  1515. `;
  1516. const result = extractFromSource('Service.php', code);
  1517. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1518. expect(importNodes.length).toBe(3);
  1519. const names = importNodes.map((n) => n.name);
  1520. expect(names).toContain('Illuminate\\Support\\Collection');
  1521. expect(names).toContain('Illuminate\\Support\\Str');
  1522. expect(names).toContain('Closure');
  1523. });
  1524. });
  1525. describe('Ruby imports', () => {
  1526. it('should extract require', () => {
  1527. const code = `require 'json'`;
  1528. const result = extractFromSource('app.rb', code);
  1529. const importNode = result.nodes.find((n) => n.kind === 'import');
  1530. expect(importNode).toBeDefined();
  1531. expect(importNode?.name).toBe('json');
  1532. expect(importNode?.signature).toBe("require 'json'");
  1533. });
  1534. it('should extract require with path', () => {
  1535. const code = `require 'active_support/core_ext/string'`;
  1536. const result = extractFromSource('config.rb', code);
  1537. const importNode = result.nodes.find((n) => n.kind === 'import');
  1538. expect(importNode).toBeDefined();
  1539. expect(importNode?.name).toBe('active_support/core_ext/string');
  1540. });
  1541. it('should extract require_relative', () => {
  1542. const code = `require_relative '../test_helper'`;
  1543. const result = extractFromSource('test/my_test.rb', code);
  1544. const importNode = result.nodes.find((n) => n.kind === 'import');
  1545. expect(importNode).toBeDefined();
  1546. expect(importNode?.name).toBe('../test_helper');
  1547. expect(importNode?.signature).toContain('require_relative');
  1548. });
  1549. it('should not extract non-require calls', () => {
  1550. const code = `puts 'hello'`;
  1551. const result = extractFromSource('app.rb', code);
  1552. const importNode = result.nodes.find((n) => n.kind === 'import');
  1553. expect(importNode).toBeUndefined();
  1554. });
  1555. it('should extract multiple requires', () => {
  1556. const code = `
  1557. require 'json'
  1558. require 'yaml'
  1559. require_relative 'helper'
  1560. `;
  1561. const result = extractFromSource('lib.rb', code);
  1562. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1563. expect(importNodes.length).toBe(3);
  1564. const names = importNodes.map((n) => n.name);
  1565. expect(names).toContain('json');
  1566. expect(names).toContain('yaml');
  1567. expect(names).toContain('helper');
  1568. });
  1569. });
  1570. describe('Ruby modules', () => {
  1571. it('should extract module as module node with containment', () => {
  1572. const code = `
  1573. module CachedCounting
  1574. def self.disable
  1575. @enabled = false
  1576. end
  1577. def perform_increment!(key, count)
  1578. write_cache!(key, count)
  1579. end
  1580. end
  1581. `;
  1582. const result = extractFromSource('concerns/cached_counting.rb', code);
  1583. const moduleNode = result.nodes.find((n) => n.kind === 'module' && n.name === 'CachedCounting');
  1584. expect(moduleNode).toBeDefined();
  1585. expect(moduleNode?.qualifiedName).toBe('CachedCounting');
  1586. // Methods inside module should have module-qualified names
  1587. const disableMethod = result.nodes.find((n) => n.name === 'disable' && n.kind === 'method');
  1588. expect(disableMethod).toBeDefined();
  1589. expect(disableMethod?.qualifiedName).toBe('CachedCounting::disable');
  1590. const incrementMethod = result.nodes.find((n) => n.name === 'perform_increment!' && n.kind === 'method');
  1591. expect(incrementMethod).toBeDefined();
  1592. expect(incrementMethod?.qualifiedName).toBe('CachedCounting::perform_increment!');
  1593. // Containment edge from module to methods
  1594. const containsEdges = result.edges.filter((e) => e.source === moduleNode?.id && e.kind === 'contains');
  1595. expect(containsEdges.length).toBeGreaterThanOrEqual(2);
  1596. });
  1597. it('should handle nested modules with classes', () => {
  1598. const code = `
  1599. module Discourse
  1600. module Auth
  1601. class AuthProvider
  1602. def authenticate(params)
  1603. validate(params)
  1604. end
  1605. end
  1606. end
  1607. end
  1608. `;
  1609. const result = extractFromSource('lib/auth.rb', code);
  1610. const discourseModule = result.nodes.find((n) => n.kind === 'module' && n.name === 'Discourse');
  1611. expect(discourseModule).toBeDefined();
  1612. const authModule = result.nodes.find((n) => n.kind === 'module' && n.name === 'Auth');
  1613. expect(authModule).toBeDefined();
  1614. expect(authModule?.qualifiedName).toBe('Discourse::Auth');
  1615. const authProvider = result.nodes.find((n) => n.kind === 'class' && n.name === 'AuthProvider');
  1616. expect(authProvider).toBeDefined();
  1617. expect(authProvider?.qualifiedName).toBe('Discourse::Auth::AuthProvider');
  1618. const authMethod = result.nodes.find((n) => n.name === 'authenticate');
  1619. expect(authMethod).toBeDefined();
  1620. expect(authMethod?.qualifiedName).toBe('Discourse::Auth::AuthProvider::authenticate');
  1621. });
  1622. });
  1623. describe('C/C++ imports', () => {
  1624. it('should extract system include', () => {
  1625. const code = `#include <iostream>`;
  1626. const result = extractFromSource('main.cpp', code);
  1627. const importNode = result.nodes.find((n) => n.kind === 'import');
  1628. expect(importNode).toBeDefined();
  1629. expect(importNode?.name).toBe('iostream');
  1630. expect(importNode?.signature).toBe('#include <iostream>');
  1631. });
  1632. it('should extract system include with path', () => {
  1633. const code = `#include <nlohmann/json.hpp>`;
  1634. const result = extractFromSource('app.cpp', code);
  1635. const importNode = result.nodes.find((n) => n.kind === 'import');
  1636. expect(importNode).toBeDefined();
  1637. expect(importNode?.name).toBe('nlohmann/json.hpp');
  1638. });
  1639. it('should extract local include', () => {
  1640. const code = `#include "myheader.h"`;
  1641. const result = extractFromSource('main.cpp', code);
  1642. const importNode = result.nodes.find((n) => n.kind === 'import');
  1643. expect(importNode).toBeDefined();
  1644. expect(importNode?.name).toBe('myheader.h');
  1645. });
  1646. it('should extract C header', () => {
  1647. const code = `#include <stdio.h>`;
  1648. const result = extractFromSource('main.c', code);
  1649. const importNode = result.nodes.find((n) => n.kind === 'import');
  1650. expect(importNode).toBeDefined();
  1651. expect(importNode?.name).toBe('stdio.h');
  1652. });
  1653. it('should extract multiple includes', () => {
  1654. const code = `
  1655. #include <iostream>
  1656. #include <vector>
  1657. #include "config.h"
  1658. `;
  1659. const result = extractFromSource('app.cpp', code);
  1660. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1661. expect(importNodes.length).toBe(3);
  1662. const names = importNodes.map((n) => n.name);
  1663. expect(names).toContain('iostream');
  1664. expect(names).toContain('vector');
  1665. expect(names).toContain('config.h');
  1666. });
  1667. });
  1668. describe('Dart imports', () => {
  1669. it('should extract dart: import', () => {
  1670. const code = `import 'dart:async';`;
  1671. const result = extractFromSource('main.dart', code);
  1672. const importNode = result.nodes.find((n) => n.kind === 'import');
  1673. expect(importNode).toBeDefined();
  1674. expect(importNode?.name).toBe('dart:async');
  1675. expect(importNode?.signature).toBe("import 'dart:async';");
  1676. });
  1677. it('should extract package import', () => {
  1678. const code = `import 'package:flutter/material.dart';`;
  1679. const result = extractFromSource('app.dart', code);
  1680. const importNode = result.nodes.find((n) => n.kind === 'import');
  1681. expect(importNode).toBeDefined();
  1682. expect(importNode?.name).toBe('package:flutter/material.dart');
  1683. });
  1684. it('should extract aliased import', () => {
  1685. const code = `import 'package:http/http.dart' as http;`;
  1686. const result = extractFromSource('api.dart', code);
  1687. const importNode = result.nodes.find((n) => n.kind === 'import');
  1688. expect(importNode).toBeDefined();
  1689. expect(importNode?.name).toBe('package:http/http.dart');
  1690. expect(importNode?.signature).toContain('as http');
  1691. });
  1692. it('should extract multiple imports', () => {
  1693. const code = `
  1694. import 'dart:async';
  1695. import 'dart:convert';
  1696. import 'package:flutter/material.dart';
  1697. `;
  1698. const result = extractFromSource('main.dart', code);
  1699. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1700. expect(importNodes.length).toBe(3);
  1701. const names = importNodes.map((n) => n.name);
  1702. expect(names).toContain('dart:async');
  1703. expect(names).toContain('dart:convert');
  1704. expect(names).toContain('package:flutter/material.dart');
  1705. });
  1706. it('should extract relative import', () => {
  1707. const code = `import '../utils/helpers.dart';`;
  1708. const result = extractFromSource('lib/main.dart', code);
  1709. const importNode = result.nodes.find((n) => n.kind === 'import');
  1710. expect(importNode).toBeDefined();
  1711. expect(importNode?.name).toBe('../utils/helpers.dart');
  1712. });
  1713. });
  1714. describe('Liquid imports', () => {
  1715. it('should extract render tag', () => {
  1716. const code = `{% render 'loading-spinner' %}`;
  1717. const result = extractFromSource('template.liquid', code);
  1718. const importNode = result.nodes.find((n) => n.kind === 'import');
  1719. expect(importNode).toBeDefined();
  1720. expect(importNode?.name).toBe('loading-spinner');
  1721. expect(importNode?.signature).toContain('render');
  1722. });
  1723. it('should extract section tag', () => {
  1724. const code = `{% section 'header' %}`;
  1725. const result = extractFromSource('layout/theme.liquid', code);
  1726. const importNode = result.nodes.find((n) => n.kind === 'import');
  1727. expect(importNode).toBeDefined();
  1728. expect(importNode?.name).toBe('header');
  1729. expect(importNode?.signature).toContain('section');
  1730. });
  1731. it('should extract include tag', () => {
  1732. const code = `{% include 'icon-cart' %}`;
  1733. const result = extractFromSource('snippets/header.liquid', code);
  1734. const importNode = result.nodes.find((n) => n.kind === 'import');
  1735. expect(importNode).toBeDefined();
  1736. expect(importNode?.name).toBe('icon-cart');
  1737. expect(importNode?.signature).toContain('include');
  1738. });
  1739. it('should extract render with whitespace control', () => {
  1740. const code = `{%- render 'price' -%}`;
  1741. const result = extractFromSource('snippets/product.liquid', code);
  1742. const importNode = result.nodes.find((n) => n.kind === 'import');
  1743. expect(importNode).toBeDefined();
  1744. expect(importNode?.name).toBe('price');
  1745. });
  1746. it('should extract multiple imports', () => {
  1747. const code = `
  1748. {% section 'header' %}
  1749. {% render 'loading-spinner' %}
  1750. {% render 'cart-drawer' %}
  1751. `;
  1752. const result = extractFromSource('layout/theme.liquid', code);
  1753. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1754. expect(importNodes.length).toBe(3);
  1755. const names = importNodes.map((n) => n.name);
  1756. expect(names).toContain('header');
  1757. expect(names).toContain('loading-spinner');
  1758. expect(names).toContain('cart-drawer');
  1759. });
  1760. });
  1761. });
  1762. // =============================================================================
  1763. // Pascal / Delphi Extraction
  1764. // =============================================================================
  1765. describe('Pascal / Delphi Extraction', () => {
  1766. describe('Language detection', () => {
  1767. it('should detect Pascal files', () => {
  1768. expect(detectLanguage('UAuth.pas')).toBe('pascal');
  1769. expect(detectLanguage('App.dpr')).toBe('pascal');
  1770. expect(detectLanguage('Package.dpk')).toBe('pascal');
  1771. expect(detectLanguage('App.lpr')).toBe('pascal');
  1772. expect(detectLanguage('MainForm.dfm')).toBe('pascal');
  1773. expect(detectLanguage('MainForm.fmx')).toBe('pascal');
  1774. });
  1775. it('should report Pascal as supported', () => {
  1776. expect(isLanguageSupported('pascal')).toBe(true);
  1777. expect(getSupportedLanguages()).toContain('pascal');
  1778. });
  1779. });
  1780. describe('Unit extraction', () => {
  1781. it('should extract unit as module', () => {
  1782. const code = `unit MyUnit;\ninterface\nimplementation\nend.`;
  1783. const result = extractFromSource('MyUnit.pas', code);
  1784. const moduleNode = result.nodes.find((n) => n.kind === 'module');
  1785. expect(moduleNode).toBeDefined();
  1786. expect(moduleNode?.name).toBe('MyUnit');
  1787. expect(moduleNode?.language).toBe('pascal');
  1788. });
  1789. it('should extract program as module', () => {
  1790. const code = `program MyApp;\nbegin\nend.`;
  1791. const result = extractFromSource('MyApp.dpr', code);
  1792. const moduleNode = result.nodes.find((n) => n.kind === 'module');
  1793. expect(moduleNode).toBeDefined();
  1794. expect(moduleNode?.name).toBe('MyApp');
  1795. });
  1796. it('should fallback to filename when module name is empty', () => {
  1797. // Some .dpr templates use "program;" without a name
  1798. const code = `program;\nuses SysUtils;\nbegin\nend.`;
  1799. const result = extractFromSource('Console.dpr', code);
  1800. const moduleNode = result.nodes.find((n) => n.kind === 'module');
  1801. expect(moduleNode).toBeDefined();
  1802. expect(moduleNode?.name).toBe('Console');
  1803. });
  1804. });
  1805. describe('Uses clause (imports)', () => {
  1806. it('should extract uses as individual imports', () => {
  1807. const code = `unit Test;\ninterface\nuses\n System.SysUtils,\n System.Classes;\nimplementation\nend.`;
  1808. const result = extractFromSource('Test.pas', code);
  1809. const imports = result.nodes.filter((n) => n.kind === 'import');
  1810. expect(imports.length).toBe(2);
  1811. expect(imports.map((n) => n.name)).toContain('System.SysUtils');
  1812. expect(imports.map((n) => n.name)).toContain('System.Classes');
  1813. });
  1814. it('should create unresolved references for imports', () => {
  1815. const code = `unit Test;\ninterface\nuses\n UAuth;\nimplementation\nend.`;
  1816. const result = extractFromSource('Test.pas', code);
  1817. const importRef = result.unresolvedReferences.find(
  1818. (r) => r.referenceKind === 'imports'
  1819. );
  1820. expect(importRef).toBeDefined();
  1821. expect(importRef?.referenceName).toBe('UAuth');
  1822. });
  1823. });
  1824. describe('Class extraction', () => {
  1825. it('should extract class declarations', () => {
  1826. const code = `unit Test;\ninterface\ntype\n TMyClass = class\n public\n procedure DoSomething;\n end;\nimplementation\nend.`;
  1827. const result = extractFromSource('Test.pas', code);
  1828. const classNode = result.nodes.find((n) => n.kind === 'class');
  1829. expect(classNode).toBeDefined();
  1830. expect(classNode?.name).toBe('TMyClass');
  1831. });
  1832. it('should extract class with inheritance', () => {
  1833. const code = `unit Test;\ninterface\ntype\n TChild = class(TParent)\n end;\nimplementation\nend.`;
  1834. const result = extractFromSource('Test.pas', code);
  1835. const extendsRef = result.unresolvedReferences.find(
  1836. (r) => r.referenceKind === 'extends'
  1837. );
  1838. expect(extendsRef).toBeDefined();
  1839. expect(extendsRef?.referenceName).toBe('TParent');
  1840. });
  1841. it('should extract class with interface implementation', () => {
  1842. const code = `unit Test;\ninterface\ntype\n TService = class(TInterfacedObject, ILogger)\n end;\nimplementation\nend.`;
  1843. const result = extractFromSource('Test.pas', code);
  1844. const extendsRef = result.unresolvedReferences.find(
  1845. (r) => r.referenceKind === 'extends'
  1846. );
  1847. const implementsRef = result.unresolvedReferences.find(
  1848. (r) => r.referenceKind === 'implements'
  1849. );
  1850. expect(extendsRef?.referenceName).toBe('TInterfacedObject');
  1851. expect(implementsRef?.referenceName).toBe('ILogger');
  1852. });
  1853. });
  1854. describe('Record extraction', () => {
  1855. it('should extract records as class nodes', () => {
  1856. const code = `unit Test;\ninterface\ntype\n TPoint = record\n X: Double;\n Y: Double;\n end;\nimplementation\nend.`;
  1857. const result = extractFromSource('Test.pas', code);
  1858. const classNode = result.nodes.find((n) => n.kind === 'class');
  1859. expect(classNode).toBeDefined();
  1860. expect(classNode?.name).toBe('TPoint');
  1861. const fields = result.nodes.filter((n) => n.kind === 'field');
  1862. expect(fields.length).toBe(2);
  1863. expect(fields.map((f) => f.name)).toContain('X');
  1864. expect(fields.map((f) => f.name)).toContain('Y');
  1865. });
  1866. });
  1867. describe('Interface extraction', () => {
  1868. it('should extract interface declarations', () => {
  1869. const code = `unit Test;\ninterface\ntype\n ILogger = interface\n procedure Log(const AMsg: string);\n end;\nimplementation\nend.`;
  1870. const result = extractFromSource('Test.pas', code);
  1871. const ifaceNode = result.nodes.find((n) => n.kind === 'interface');
  1872. expect(ifaceNode).toBeDefined();
  1873. expect(ifaceNode?.name).toBe('ILogger');
  1874. });
  1875. });
  1876. describe('Method extraction', () => {
  1877. it('should extract methods with visibility', () => {
  1878. 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.`;
  1879. const result = extractFromSource('Test.pas', code);
  1880. const methods = result.nodes.filter((n) => n.kind === 'method');
  1881. expect(methods.length).toBe(2);
  1882. const createMethod = methods.find((m) => m.name === 'Create');
  1883. expect(createMethod?.visibility).toBe('public');
  1884. const getValue = methods.find((m) => m.name === 'GetValue');
  1885. expect(getValue?.visibility).toBe('public');
  1886. const fields = result.nodes.filter((n) => n.kind === 'field');
  1887. const fValue = fields.find((f) => f.name === 'FValue');
  1888. expect(fValue?.visibility).toBe('private');
  1889. });
  1890. it('should detect static methods (class methods)', () => {
  1891. const code = `unit Test;\ninterface\ntype\n THelper = class\n public\n class function Create: THelper; static;\n end;\nimplementation\nend.`;
  1892. const result = extractFromSource('Test.pas', code);
  1893. const methods = result.nodes.filter((n) => n.kind === 'method');
  1894. const staticMethod = methods.find((m) => m.name === 'Create');
  1895. expect(staticMethod?.isStatic).toBe(true);
  1896. });
  1897. });
  1898. describe('Enum extraction', () => {
  1899. it('should extract enums with members', () => {
  1900. const code = `unit Test;\ninterface\ntype\n TColor = (clRed, clGreen, clBlue);\nimplementation\nend.`;
  1901. const result = extractFromSource('Test.pas', code);
  1902. const enumNode = result.nodes.find((n) => n.kind === 'enum');
  1903. expect(enumNode).toBeDefined();
  1904. expect(enumNode?.name).toBe('TColor');
  1905. const members = result.nodes.filter((n) => n.kind === 'enum_member');
  1906. expect(members.length).toBe(3);
  1907. expect(members.map((m) => m.name)).toEqual(['clRed', 'clGreen', 'clBlue']);
  1908. });
  1909. });
  1910. describe('Property extraction', () => {
  1911. it('should extract properties', () => {
  1912. const code = `unit Test;\ninterface\ntype\n TObj = class\n public\n property Name: string read FName write FName;\n end;\nimplementation\nend.`;
  1913. const result = extractFromSource('Test.pas', code);
  1914. const propNode = result.nodes.find((n) => n.kind === 'property');
  1915. expect(propNode).toBeDefined();
  1916. expect(propNode?.name).toBe('Name');
  1917. expect(propNode?.visibility).toBe('public');
  1918. });
  1919. });
  1920. describe('Constant extraction', () => {
  1921. it('should extract constants', () => {
  1922. const code = `unit Test;\ninterface\nconst\n MAX_RETRIES = 3;\n APP_NAME = 'MyApp';\nimplementation\nend.`;
  1923. const result = extractFromSource('Test.pas', code);
  1924. const constants = result.nodes.filter((n) => n.kind === 'constant');
  1925. expect(constants.length).toBe(2);
  1926. expect(constants.map((c) => c.name)).toContain('MAX_RETRIES');
  1927. expect(constants.map((c) => c.name)).toContain('APP_NAME');
  1928. });
  1929. });
  1930. describe('Type alias extraction', () => {
  1931. it('should extract type aliases', () => {
  1932. const code = `unit Test;\ninterface\ntype\n TUserName = string;\nimplementation\nend.`;
  1933. const result = extractFromSource('Test.pas', code);
  1934. const aliasNode = result.nodes.find((n) => n.kind === 'type_alias');
  1935. expect(aliasNode).toBeDefined();
  1936. expect(aliasNode?.name).toBe('TUserName');
  1937. });
  1938. });
  1939. describe('Call extraction', () => {
  1940. it('should extract calls from implementation bodies', () => {
  1941. 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.`;
  1942. const result = extractFromSource('Test.pas', code);
  1943. const callRef = result.unresolvedReferences.find(
  1944. (r) => r.referenceKind === 'calls'
  1945. );
  1946. expect(callRef).toBeDefined();
  1947. expect(callRef?.referenceName).toBe('WriteLn');
  1948. });
  1949. });
  1950. describe('Containment edges', () => {
  1951. it('should create contains edges for class members', () => {
  1952. const code = `unit Test;\ninterface\ntype\n TObj = class\n public\n procedure Foo;\n end;\nimplementation\nend.`;
  1953. const result = extractFromSource('Test.pas', code);
  1954. const classNode = result.nodes.find((n) => n.kind === 'class');
  1955. const methodNode = result.nodes.find((n) => n.kind === 'method');
  1956. expect(classNode).toBeDefined();
  1957. expect(methodNode).toBeDefined();
  1958. const containsEdge = result.edges.find(
  1959. (e) => e.source === classNode?.id && e.target === methodNode?.id && e.kind === 'contains'
  1960. );
  1961. expect(containsEdge).toBeDefined();
  1962. });
  1963. });
  1964. describe('Full fixture: UAuth.pas', () => {
  1965. const code = `unit UAuth;
  1966. interface
  1967. uses
  1968. System.SysUtils,
  1969. System.Classes;
  1970. type
  1971. ITokenValidator = interface
  1972. ['{11111111-1111-1111-1111-111111111111}']
  1973. function Validate(const AToken: string): Boolean;
  1974. end;
  1975. TAuthService = class(TInterfacedObject, ITokenValidator)
  1976. private
  1977. FToken: string;
  1978. FLoginCount: Integer;
  1979. procedure IncLoginCount;
  1980. protected
  1981. function GetToken: string;
  1982. public
  1983. constructor Create;
  1984. destructor Destroy; override;
  1985. function Validate(const AToken: string): Boolean;
  1986. function Login(const AUser, APass: string): string;
  1987. property Token: string read GetToken;
  1988. property LoginCount: Integer read FLoginCount;
  1989. end;
  1990. implementation
  1991. constructor TAuthService.Create;
  1992. begin
  1993. inherited Create;
  1994. FToken := '';
  1995. FLoginCount := 0;
  1996. end;
  1997. destructor TAuthService.Destroy;
  1998. begin
  1999. FToken := '';
  2000. inherited Destroy;
  2001. end;
  2002. procedure TAuthService.IncLoginCount;
  2003. begin
  2004. Inc(FLoginCount);
  2005. end;
  2006. function TAuthService.GetToken: string;
  2007. begin
  2008. Result := FToken;
  2009. end;
  2010. function TAuthService.Validate(const AToken: string): Boolean;
  2011. begin
  2012. Result := AToken <> '';
  2013. end;
  2014. function TAuthService.Login(const AUser, APass: string): string;
  2015. begin
  2016. IncLoginCount;
  2017. if Validate(AUser + ':' + APass) then
  2018. begin
  2019. FToken := AUser;
  2020. Result := 'ok';
  2021. end
  2022. else
  2023. Result := '';
  2024. end;
  2025. end.`;
  2026. it('should extract all expected nodes', () => {
  2027. const result = extractFromSource('UAuth.pas', code);
  2028. expect(result.errors).toHaveLength(0);
  2029. // Module
  2030. const moduleNode = result.nodes.find((n) => n.kind === 'module');
  2031. expect(moduleNode?.name).toBe('UAuth');
  2032. // Imports
  2033. const imports = result.nodes.filter((n) => n.kind === 'import');
  2034. expect(imports.length).toBe(2);
  2035. // Interface
  2036. const ifaceNode = result.nodes.find((n) => n.kind === 'interface');
  2037. expect(ifaceNode?.name).toBe('ITokenValidator');
  2038. // Class
  2039. const classNode = result.nodes.find((n) => n.kind === 'class');
  2040. expect(classNode?.name).toBe('TAuthService');
  2041. // Methods
  2042. const methods = result.nodes.filter((n) => n.kind === 'method');
  2043. expect(methods.length).toBeGreaterThanOrEqual(6);
  2044. expect(methods.map((m) => m.name)).toContain('Create');
  2045. expect(methods.map((m) => m.name)).toContain('Destroy');
  2046. expect(methods.map((m) => m.name)).toContain('Login');
  2047. // Fields
  2048. const fields = result.nodes.filter((n) => n.kind === 'field');
  2049. expect(fields.length).toBe(2);
  2050. expect(fields.every((f) => f.visibility === 'private')).toBe(true);
  2051. // Properties
  2052. const props = result.nodes.filter((n) => n.kind === 'property');
  2053. expect(props.length).toBe(2);
  2054. expect(props.map((p) => p.name)).toContain('Token');
  2055. expect(props.map((p) => p.name)).toContain('LoginCount');
  2056. });
  2057. it('should extract inheritance and interface implementation', () => {
  2058. const result = extractFromSource('UAuth.pas', code);
  2059. const extendsRef = result.unresolvedReferences.find(
  2060. (r) => r.referenceKind === 'extends'
  2061. );
  2062. expect(extendsRef?.referenceName).toBe('TInterfacedObject');
  2063. const implementsRef = result.unresolvedReferences.find(
  2064. (r) => r.referenceKind === 'implements'
  2065. );
  2066. expect(implementsRef?.referenceName).toBe('ITokenValidator');
  2067. });
  2068. it('should extract calls from implementation', () => {
  2069. const result = extractFromSource('UAuth.pas', code);
  2070. const callRefs = result.unresolvedReferences.filter(
  2071. (r) => r.referenceKind === 'calls'
  2072. );
  2073. expect(callRefs.map((r) => r.referenceName)).toContain('Inc');
  2074. expect(callRefs.map((r) => r.referenceName)).toContain('Validate');
  2075. });
  2076. });
  2077. describe('Full fixture: UTypes.pas', () => {
  2078. const code = `unit UTypes;
  2079. interface
  2080. uses
  2081. System.SysUtils;
  2082. const
  2083. C_MAX_RETRIES = 3;
  2084. C_DEFAULT_NAME = 'Guest';
  2085. type
  2086. TUserRole = (urAdmin, urEditor, urViewer);
  2087. TPoint2D = record
  2088. X: Double;
  2089. Y: Double;
  2090. end;
  2091. TUserName = string;
  2092. TUserInfo = class
  2093. public
  2094. type
  2095. TAddress = record
  2096. Street: string;
  2097. City: string;
  2098. Zip: string;
  2099. end;
  2100. private
  2101. FName: TUserName;
  2102. FRole: TUserRole;
  2103. FAddress: TAddress;
  2104. public
  2105. constructor Create(const AName: TUserName; ARole: TUserRole);
  2106. function GetDisplayName: string;
  2107. class function CreateAdmin(const AName: TUserName): TUserInfo; static;
  2108. property Name: TUserName read FName write FName;
  2109. property Role: TUserRole read FRole;
  2110. property Address: TAddress read FAddress write FAddress;
  2111. end;
  2112. implementation
  2113. constructor TUserInfo.Create(const AName: TUserName; ARole: TUserRole);
  2114. begin
  2115. FName := AName;
  2116. FRole := ARole;
  2117. end;
  2118. function TUserInfo.GetDisplayName: string;
  2119. begin
  2120. if FRole = urAdmin then
  2121. Result := '[Admin] ' + FName
  2122. else
  2123. Result := FName;
  2124. end;
  2125. class function TUserInfo.CreateAdmin(const AName: TUserName): TUserInfo;
  2126. begin
  2127. Result := TUserInfo.Create(AName, urAdmin);
  2128. end;
  2129. end.`;
  2130. it('should extract enums with members', () => {
  2131. const result = extractFromSource('UTypes.pas', code);
  2132. const enumNode = result.nodes.find((n) => n.kind === 'enum');
  2133. expect(enumNode?.name).toBe('TUserRole');
  2134. const members = result.nodes.filter((n) => n.kind === 'enum_member');
  2135. expect(members.length).toBe(3);
  2136. expect(members.map((m) => m.name)).toEqual(['urAdmin', 'urEditor', 'urViewer']);
  2137. });
  2138. it('should extract constants', () => {
  2139. const result = extractFromSource('UTypes.pas', code);
  2140. const constants = result.nodes.filter((n) => n.kind === 'constant');
  2141. expect(constants.length).toBe(2);
  2142. expect(constants.map((c) => c.name)).toContain('C_MAX_RETRIES');
  2143. expect(constants.map((c) => c.name)).toContain('C_DEFAULT_NAME');
  2144. });
  2145. it('should extract type aliases', () => {
  2146. const result = extractFromSource('UTypes.pas', code);
  2147. const aliases = result.nodes.filter((n) => n.kind === 'type_alias');
  2148. expect(aliases.map((a) => a.name)).toContain('TUserName');
  2149. });
  2150. it('should extract records as classes with fields', () => {
  2151. const result = extractFromSource('UTypes.pas', code);
  2152. const classes = result.nodes.filter((n) => n.kind === 'class');
  2153. expect(classes.map((c) => c.name)).toContain('TPoint2D');
  2154. // TPoint2D fields
  2155. const fields = result.nodes.filter((n) => n.kind === 'field');
  2156. expect(fields.map((f) => f.name)).toContain('X');
  2157. expect(fields.map((f) => f.name)).toContain('Y');
  2158. });
  2159. it('should extract static class methods', () => {
  2160. const result = extractFromSource('UTypes.pas', code);
  2161. const methods = result.nodes.filter((n) => n.kind === 'method');
  2162. const staticMethod = methods.find((m) => m.name === 'CreateAdmin');
  2163. expect(staticMethod).toBeDefined();
  2164. expect(staticMethod?.isStatic).toBe(true);
  2165. });
  2166. it('should extract nested types', () => {
  2167. const result = extractFromSource('UTypes.pas', code);
  2168. const classes = result.nodes.filter((n) => n.kind === 'class');
  2169. expect(classes.map((c) => c.name)).toContain('TAddress');
  2170. });
  2171. });
  2172. });
  2173. // =============================================================================
  2174. // DFM/FMX Extraction
  2175. // =============================================================================
  2176. describe('DFM/FMX Extraction', () => {
  2177. it('should extract components from DFM', () => {
  2178. const code = `object Form1: TForm1
  2179. Left = 0
  2180. Top = 0
  2181. Caption = 'My Form'
  2182. object Button1: TButton
  2183. Left = 10
  2184. Top = 10
  2185. Caption = 'Click Me'
  2186. end
  2187. end`;
  2188. const result = extractFromSource('Form1.dfm', code);
  2189. const components = result.nodes.filter((n) => n.kind === 'component');
  2190. expect(components.length).toBe(2);
  2191. expect(components.map((c) => c.name)).toContain('Form1');
  2192. expect(components.map((c) => c.name)).toContain('Button1');
  2193. const button = components.find((c) => c.name === 'Button1');
  2194. expect(button?.signature).toBe('TButton');
  2195. });
  2196. it('should extract nested component hierarchy', () => {
  2197. const code = `object Form1: TForm1
  2198. object Panel1: TPanel
  2199. object Label1: TLabel
  2200. Caption = 'Hello'
  2201. end
  2202. end
  2203. end`;
  2204. const result = extractFromSource('Form1.dfm', code);
  2205. const components = result.nodes.filter((n) => n.kind === 'component');
  2206. expect(components.length).toBe(3);
  2207. // Check nesting: Panel1 contains Label1
  2208. const panel = components.find((c) => c.name === 'Panel1');
  2209. const label = components.find((c) => c.name === 'Label1');
  2210. const containsEdge = result.edges.find(
  2211. (e) => e.source === panel?.id && e.target === label?.id && e.kind === 'contains'
  2212. );
  2213. expect(containsEdge).toBeDefined();
  2214. });
  2215. it('should extract event handler references', () => {
  2216. const code = `object Form1: TForm1
  2217. OnCreate = FormCreate
  2218. OnDestroy = FormDestroy
  2219. object Button1: TButton
  2220. OnClick = Button1Click
  2221. end
  2222. end`;
  2223. const result = extractFromSource('Form1.dfm', code);
  2224. const refs = result.unresolvedReferences;
  2225. expect(refs.length).toBe(3);
  2226. expect(refs.map((r) => r.referenceName)).toContain('FormCreate');
  2227. expect(refs.map((r) => r.referenceName)).toContain('FormDestroy');
  2228. expect(refs.map((r) => r.referenceName)).toContain('Button1Click');
  2229. expect(refs.every((r) => r.referenceKind === 'references')).toBe(true);
  2230. });
  2231. it('should handle multi-line properties', () => {
  2232. const code = `object Form1: TForm1
  2233. SQL.Strings = (
  2234. 'SELECT * FROM users'
  2235. 'WHERE active = 1')
  2236. object Button1: TButton
  2237. OnClick = Button1Click
  2238. end
  2239. end`;
  2240. const result = extractFromSource('Form1.dfm', code);
  2241. const components = result.nodes.filter((n) => n.kind === 'component');
  2242. expect(components.length).toBe(2);
  2243. const refs = result.unresolvedReferences;
  2244. expect(refs.length).toBe(1);
  2245. expect(refs[0]?.referenceName).toBe('Button1Click');
  2246. });
  2247. it('should handle inherited keyword', () => {
  2248. const code = `inherited Form1: TForm1
  2249. Caption = 'Inherited Form'
  2250. object Button1: TButton
  2251. OnClick = Button1Click
  2252. end
  2253. end`;
  2254. const result = extractFromSource('Form1.dfm', code);
  2255. const components = result.nodes.filter((n) => n.kind === 'component');
  2256. expect(components.length).toBe(2);
  2257. expect(components.map((c) => c.name)).toContain('Form1');
  2258. });
  2259. it('should handle item collection properties', () => {
  2260. const code = `object Form1: TForm1
  2261. object StatusBar1: TStatusBar
  2262. Panels = <
  2263. item
  2264. Width = 200
  2265. end
  2266. item
  2267. Width = 200
  2268. end>
  2269. end
  2270. end`;
  2271. const result = extractFromSource('Form1.dfm', code);
  2272. const components = result.nodes.filter((n) => n.kind === 'component');
  2273. expect(components.length).toBe(2);
  2274. });
  2275. describe('Full fixture: MainForm.dfm', () => {
  2276. const code = `object frmMain: TfrmMain
  2277. Left = 0
  2278. Top = 0
  2279. Caption = 'CodeGraph DFM Fixture'
  2280. ClientHeight = 480
  2281. ClientWidth = 640
  2282. OnCreate = FormCreate
  2283. OnDestroy = FormDestroy
  2284. object pnlTop: TPanel
  2285. Left = 0
  2286. Top = 0
  2287. Width = 640
  2288. Height = 50
  2289. object lblTitle: TLabel
  2290. Left = 16
  2291. Top = 16
  2292. Caption = 'Authentication Service'
  2293. end
  2294. object btnLogin: TButton
  2295. Left = 540
  2296. Top = 12
  2297. OnClick = btnLoginClick
  2298. end
  2299. end
  2300. object pnlContent: TPanel
  2301. Left = 0
  2302. Top = 50
  2303. object edtUsername: TEdit
  2304. Left = 16
  2305. Top = 16
  2306. OnChange = edtUsernameChange
  2307. end
  2308. object edtPassword: TEdit
  2309. Left = 16
  2310. Top = 48
  2311. OnKeyPress = edtPasswordKeyPress
  2312. end
  2313. object mmoLog: TMemo
  2314. Left = 16
  2315. Top = 88
  2316. end
  2317. end
  2318. object pnlStatus: TStatusBar
  2319. Left = 0
  2320. Top = 440
  2321. Panels = <
  2322. item
  2323. Width = 200
  2324. end
  2325. item
  2326. Width = 200
  2327. end>
  2328. end
  2329. end`;
  2330. it('should extract all components', () => {
  2331. const result = extractFromSource('MainForm.dfm', code);
  2332. const components = result.nodes.filter((n) => n.kind === 'component');
  2333. expect(components.length).toBe(9);
  2334. expect(components.map((c) => c.name)).toEqual(
  2335. expect.arrayContaining([
  2336. 'frmMain', 'pnlTop', 'lblTitle', 'btnLogin',
  2337. 'pnlContent', 'edtUsername', 'edtPassword', 'mmoLog', 'pnlStatus',
  2338. ])
  2339. );
  2340. });
  2341. it('should extract all event handlers', () => {
  2342. const result = extractFromSource('MainForm.dfm', code);
  2343. const refs = result.unresolvedReferences;
  2344. expect(refs.length).toBe(5);
  2345. expect(refs.map((r) => r.referenceName)).toEqual(
  2346. expect.arrayContaining([
  2347. 'FormCreate', 'FormDestroy', 'btnLoginClick',
  2348. 'edtUsernameChange', 'edtPasswordKeyPress',
  2349. ])
  2350. );
  2351. });
  2352. });
  2353. });
  2354. describe('Full Indexing', () => {
  2355. let tempDir: string;
  2356. beforeEach(() => {
  2357. tempDir = createTempDir();
  2358. });
  2359. afterEach(() => {
  2360. cleanupTempDir(tempDir);
  2361. });
  2362. it('should index a TypeScript file', async () => {
  2363. // Create test file
  2364. const srcDir = path.join(tempDir, 'src');
  2365. fs.mkdirSync(srcDir);
  2366. fs.writeFileSync(
  2367. path.join(srcDir, 'utils.ts'),
  2368. `
  2369. export function add(a: number, b: number): number {
  2370. return a + b;
  2371. }
  2372. export function multiply(a: number, b: number): number {
  2373. return a * b;
  2374. }
  2375. `
  2376. );
  2377. // Initialize and index
  2378. const cg = CodeGraph.initSync(tempDir);
  2379. const result = await cg.indexAll();
  2380. expect(result.success).toBe(true);
  2381. expect(result.filesIndexed).toBe(1);
  2382. expect(result.nodesCreated).toBeGreaterThanOrEqual(2);
  2383. // Check nodes were stored
  2384. const nodes = cg.getNodesInFile('src/utils.ts');
  2385. expect(nodes.length).toBeGreaterThanOrEqual(2);
  2386. const addFunc = nodes.find((n) => n.name === 'add');
  2387. expect(addFunc).toBeDefined();
  2388. expect(addFunc?.kind).toBe('function');
  2389. cg.close();
  2390. });
  2391. it('should index multiple files', async () => {
  2392. // Create test files
  2393. const srcDir = path.join(tempDir, 'src');
  2394. fs.mkdirSync(srcDir);
  2395. fs.writeFileSync(
  2396. path.join(srcDir, 'math.ts'),
  2397. `export function add(a: number, b: number) { return a + b; }`
  2398. );
  2399. fs.writeFileSync(
  2400. path.join(srcDir, 'string.ts'),
  2401. `export function capitalize(s: string) { return s.toUpperCase(); }`
  2402. );
  2403. // Initialize and index
  2404. const cg = CodeGraph.initSync(tempDir);
  2405. const result = await cg.indexAll();
  2406. expect(result.success).toBe(true);
  2407. expect(result.filesIndexed).toBe(2);
  2408. const files = cg.getFiles();
  2409. expect(files.length).toBe(2);
  2410. cg.close();
  2411. });
  2412. it('should track file hashes for incremental updates', async () => {
  2413. // Create initial file
  2414. const srcDir = path.join(tempDir, 'src');
  2415. fs.mkdirSync(srcDir);
  2416. fs.writeFileSync(path.join(srcDir, 'main.ts'), `export const x = 1;`);
  2417. // Initialize and index
  2418. const cg = CodeGraph.initSync(tempDir);
  2419. await cg.indexAll();
  2420. // Check file is tracked
  2421. const file = cg.getFile('src/main.ts');
  2422. expect(file).toBeDefined();
  2423. expect(file?.contentHash).toBeDefined();
  2424. // Modify file
  2425. fs.writeFileSync(path.join(srcDir, 'main.ts'), `export const x = 2;`);
  2426. // Check for changes
  2427. const changes = cg.getChangedFiles();
  2428. expect(changes.modified).toContain('src/main.ts');
  2429. cg.close();
  2430. });
  2431. it('should sync and detect changes', async () => {
  2432. // Create initial file
  2433. const srcDir = path.join(tempDir, 'src');
  2434. fs.mkdirSync(srcDir);
  2435. fs.writeFileSync(
  2436. path.join(srcDir, 'main.ts'),
  2437. `export function original() { return 1; }`
  2438. );
  2439. // Initialize and index
  2440. const cg = CodeGraph.initSync(tempDir);
  2441. await cg.indexAll();
  2442. const initialNodes = cg.getNodesInFile('src/main.ts');
  2443. expect(initialNodes.some((n) => n.name === 'original')).toBe(true);
  2444. // Modify file
  2445. fs.writeFileSync(
  2446. path.join(srcDir, 'main.ts'),
  2447. `export function updated() { return 2; }`
  2448. );
  2449. // Sync
  2450. const syncResult = await cg.sync();
  2451. expect(syncResult.filesModified).toBe(1);
  2452. // Check nodes were updated
  2453. const updatedNodes = cg.getNodesInFile('src/main.ts');
  2454. expect(updatedNodes.some((n) => n.name === 'updated')).toBe(true);
  2455. expect(updatedNodes.some((n) => n.name === 'original')).toBe(false);
  2456. cg.close();
  2457. });
  2458. });
  2459. describe('Path Normalization', () => {
  2460. it('should convert backslashes to forward slashes', () => {
  2461. expect(normalizePath('gui\\node_modules\\foo')).toBe('gui/node_modules/foo');
  2462. expect(normalizePath('src\\components\\Button.tsx')).toBe('src/components/Button.tsx');
  2463. });
  2464. it('should leave forward-slash paths unchanged', () => {
  2465. expect(normalizePath('src/components/Button.tsx')).toBe('src/components/Button.tsx');
  2466. });
  2467. it('should handle empty string', () => {
  2468. expect(normalizePath('')).toBe('');
  2469. });
  2470. });
  2471. describe('Directory Exclusion', () => {
  2472. let tempDir: string;
  2473. beforeEach(() => {
  2474. tempDir = createTempDir();
  2475. });
  2476. afterEach(() => {
  2477. cleanupTempDir(tempDir);
  2478. });
  2479. it('should exclude directories listed in .gitignore', () => {
  2480. // Create structure: src/index.ts + node_modules/pkg/index.js, gitignore node_modules
  2481. const srcDir = path.join(tempDir, 'src');
  2482. const nmDir = path.join(tempDir, 'node_modules', 'pkg');
  2483. fs.mkdirSync(srcDir, { recursive: true });
  2484. fs.mkdirSync(nmDir, { recursive: true });
  2485. fs.writeFileSync(path.join(srcDir, 'index.ts'), 'export const x = 1;');
  2486. fs.writeFileSync(path.join(nmDir, 'index.js'), 'module.exports = {};');
  2487. fs.writeFileSync(path.join(tempDir, '.gitignore'), 'node_modules/\n');
  2488. const files = scanDirectory(tempDir);
  2489. expect(files).toContain('src/index.ts');
  2490. expect(files.every((f) => !f.includes('node_modules'))).toBe(true);
  2491. });
  2492. it('should exclude nested node_modules via a root .gitignore', () => {
  2493. // A trailing-slash pattern with no leading slash matches at any depth.
  2494. const srcDir = path.join(tempDir, 'packages', 'app', 'src');
  2495. const nmDir = path.join(tempDir, 'packages', 'app', 'node_modules', 'pkg');
  2496. fs.mkdirSync(srcDir, { recursive: true });
  2497. fs.mkdirSync(nmDir, { recursive: true });
  2498. fs.writeFileSync(path.join(srcDir, 'index.ts'), 'export const x = 1;');
  2499. fs.writeFileSync(path.join(nmDir, 'index.js'), 'module.exports = {};');
  2500. fs.writeFileSync(path.join(tempDir, '.gitignore'), 'node_modules/\n');
  2501. const files = scanDirectory(tempDir);
  2502. expect(files).toContain('packages/app/src/index.ts');
  2503. expect(files.every((f) => !f.includes('node_modules'))).toBe(true);
  2504. });
  2505. it('should apply a nested .gitignore only to its own subtree', () => {
  2506. const appSrc = path.join(tempDir, 'app', 'src');
  2507. fs.mkdirSync(appSrc, { recursive: true });
  2508. fs.writeFileSync(path.join(appSrc, 'keep.ts'), 'export const a = 1;');
  2509. fs.writeFileSync(path.join(appSrc, 'skip.ts'), 'export const b = 2;');
  2510. fs.writeFileSync(path.join(tempDir, 'app', '.gitignore'), 'src/skip.ts\n');
  2511. // A sibling with the same name outside app/ must NOT be ignored.
  2512. const otherDir = path.join(tempDir, 'other', 'src');
  2513. fs.mkdirSync(otherDir, { recursive: true });
  2514. fs.writeFileSync(path.join(otherDir, 'skip.ts'), 'export const c = 3;');
  2515. const files = scanDirectory(tempDir);
  2516. expect(files).toContain('app/src/keep.ts');
  2517. expect(files).not.toContain('app/src/skip.ts');
  2518. expect(files).toContain('other/src/skip.ts');
  2519. });
  2520. it('should always skip .git directories', () => {
  2521. const srcDir = path.join(tempDir, 'src');
  2522. const gitDir = path.join(tempDir, '.git', 'objects');
  2523. fs.mkdirSync(srcDir, { recursive: true });
  2524. fs.mkdirSync(gitDir, { recursive: true });
  2525. fs.writeFileSync(path.join(srcDir, 'index.ts'), 'export const x = 1;');
  2526. fs.writeFileSync(path.join(gitDir, 'pack.ts'), 'export const y = 2;');
  2527. const files = scanDirectory(tempDir);
  2528. expect(files).toContain('src/index.ts');
  2529. expect(files.every((f) => !f.includes('.git'))).toBe(true);
  2530. });
  2531. it('should return forward-slash paths on all platforms', () => {
  2532. const srcDir = path.join(tempDir, 'src', 'components');
  2533. fs.mkdirSync(srcDir, { recursive: true });
  2534. fs.writeFileSync(path.join(srcDir, 'Button.tsx'), 'export function Button() {}');
  2535. const files = scanDirectory(tempDir);
  2536. expect(files.length).toBe(1);
  2537. expect(files[0]).toBe('src/components/Button.tsx');
  2538. expect(files[0]).not.toContain('\\');
  2539. });
  2540. });
  2541. describe('Git Submodules', () => {
  2542. let tempDir: string;
  2543. beforeEach(() => {
  2544. tempDir = createTempDir();
  2545. });
  2546. afterEach(() => {
  2547. cleanupTempDir(tempDir);
  2548. });
  2549. it('should index files inside git submodules (issue #147)', async () => {
  2550. const { execFileSync } = await import('child_process');
  2551. const git = (cwd: string, ...args: string[]) =>
  2552. execFileSync('git', args, { cwd, stdio: 'pipe' });
  2553. // Build a separate "library" repo to use as a submodule source.
  2554. const libDir = path.join(tempDir, '_lib');
  2555. fs.mkdirSync(libDir, { recursive: true });
  2556. git(libDir, 'init', '-q');
  2557. git(libDir, 'config', 'user.email', 'test@test.com');
  2558. git(libDir, 'config', 'user.name', 'Test');
  2559. fs.writeFileSync(path.join(libDir, 'lib.ts'), 'export const fromSubmodule = 1;');
  2560. git(libDir, 'add', '-A');
  2561. git(libDir, 'commit', '-q', '-m', 'lib init');
  2562. // Build the main repo and add the lib repo as a submodule.
  2563. const mainDir = path.join(tempDir, 'main');
  2564. fs.mkdirSync(mainDir, { recursive: true });
  2565. git(mainDir, 'init', '-q');
  2566. git(mainDir, 'config', 'user.email', 'test@test.com');
  2567. git(mainDir, 'config', 'user.name', 'Test');
  2568. fs.writeFileSync(path.join(mainDir, 'app.ts'), 'export const app = 1;');
  2569. git(mainDir, 'add', '-A');
  2570. git(mainDir, 'commit', '-q', '-m', 'app init');
  2571. // protocol.file.allow=always is required to add a local-path submodule on
  2572. // recent git versions (CVE-2022-39253 mitigation).
  2573. execFileSync(
  2574. 'git',
  2575. ['-c', 'protocol.file.allow=always', 'submodule', 'add', '-q', libDir, 'libs/lib'],
  2576. { cwd: mainDir, stdio: 'pipe' }
  2577. );
  2578. git(mainDir, 'commit', '-q', '-m', 'add submodule');
  2579. const files = scanDirectory(mainDir);
  2580. expect(files).toContain('app.ts');
  2581. expect(files).toContain('libs/lib/lib.ts');
  2582. });
  2583. });
  2584. describe('Nested non-submodule git repos', () => {
  2585. let tempDir: string;
  2586. beforeEach(() => {
  2587. tempDir = createTempDir();
  2588. });
  2589. afterEach(() => {
  2590. cleanupTempDir(tempDir);
  2591. });
  2592. it('should index files in embedded git repos run from a git super-repo (issue #193)', async () => {
  2593. const { execFileSync } = await import('child_process');
  2594. const git = (cwd: string, ...args: string[]) =>
  2595. execFileSync('git', args, { cwd, stdio: 'pipe' });
  2596. // Top-level workspace is itself a git repo, holding no source directly —
  2597. // the CMake "super-repo" layout from the issue.
  2598. const root = path.join(tempDir, 'root');
  2599. fs.mkdirSync(path.join(root, 'coding'), { recursive: true });
  2600. git(root, 'init', '-q');
  2601. git(root, 'config', 'user.email', 'test@test.com');
  2602. git(root, 'config', 'user.name', 'Test');
  2603. fs.writeFileSync(path.join(root, 'CMakeLists.txt'), 'cmake_minimum_required(VERSION 3.10)\n');
  2604. // Two independent clones living inside the workspace (NOT submodules):
  2605. // one with committed source, one with only untracked source.
  2606. const sub1 = path.join(root, 'sub_repo1', 'src');
  2607. fs.mkdirSync(sub1, { recursive: true });
  2608. git(path.join(root, 'sub_repo1'), 'init', '-q');
  2609. git(path.join(root, 'sub_repo1'), 'config', 'user.email', 'test@test.com');
  2610. git(path.join(root, 'sub_repo1'), 'config', 'user.name', 'Test');
  2611. fs.writeFileSync(path.join(sub1, 'one.ts'), 'export const one = 1;');
  2612. git(path.join(root, 'sub_repo1'), 'add', '-A');
  2613. git(path.join(root, 'sub_repo1'), 'commit', '-q', '-m', 'sub1 init');
  2614. const sub2 = path.join(root, 'sub_repo2', 'src');
  2615. fs.mkdirSync(sub2, { recursive: true });
  2616. git(path.join(root, 'sub_repo2'), 'init', '-q');
  2617. fs.writeFileSync(path.join(sub2, 'two.ts'), 'export const two = 2;');
  2618. const files = scanDirectory(root);
  2619. // Both committed and untracked source from the nested repos must be found.
  2620. expect(files).toContain('sub_repo1/src/one.ts');
  2621. expect(files).toContain('sub_repo2/src/two.ts');
  2622. });
  2623. it('should respect each embedded repo\'s own .gitignore', async () => {
  2624. const { execFileSync } = await import('child_process');
  2625. const git = (cwd: string, ...args: string[]) =>
  2626. execFileSync('git', args, { cwd, stdio: 'pipe' });
  2627. const root = path.join(tempDir, 'root');
  2628. fs.mkdirSync(root, { recursive: true });
  2629. git(root, 'init', '-q');
  2630. const sub = path.join(root, 'sub_repo', 'src');
  2631. fs.mkdirSync(sub, { recursive: true });
  2632. git(path.join(root, 'sub_repo'), 'init', '-q');
  2633. fs.writeFileSync(path.join(root, 'sub_repo', '.gitignore'), 'src/generated.ts\n');
  2634. fs.writeFileSync(path.join(sub, 'real.ts'), 'export const real = 1;');
  2635. fs.writeFileSync(path.join(sub, 'generated.ts'), 'export const generated = 1;');
  2636. const files = scanDirectory(root);
  2637. expect(files).toContain('sub_repo/src/real.ts');
  2638. expect(files).not.toContain('sub_repo/src/generated.ts');
  2639. });
  2640. });
  2641. // =============================================================================
  2642. // Scala
  2643. // =============================================================================
  2644. describe('Scala Extraction', () => {
  2645. describe('Language detection', () => {
  2646. it('should detect Scala files', () => {
  2647. expect(detectLanguage('Main.scala')).toBe('scala');
  2648. expect(detectLanguage('script.sc')).toBe('scala');
  2649. expect(detectLanguage('src/UserService.scala')).toBe('scala');
  2650. });
  2651. it('should report Scala as supported', () => {
  2652. expect(isLanguageSupported('scala')).toBe(true);
  2653. expect(getSupportedLanguages()).toContain('scala');
  2654. });
  2655. });
  2656. describe('Class extraction', () => {
  2657. it('should extract class definitions', () => {
  2658. const code = `
  2659. class UserService(private val repo: UserRepository) {
  2660. def findUser(id: String): Option[String] = Some(id)
  2661. }
  2662. `;
  2663. const result = extractFromSource('UserService.scala', code);
  2664. const cls = result.nodes.find((n) => n.kind === 'class' && n.name === 'UserService');
  2665. expect(cls).toBeDefined();
  2666. expect(cls?.language).toBe('scala');
  2667. });
  2668. it('should extract object definitions as class kind', () => {
  2669. const code = `
  2670. object DatabaseConfig {
  2671. val url = "jdbc:postgresql://localhost/mydb"
  2672. }
  2673. `;
  2674. const result = extractFromSource('Config.scala', code);
  2675. const obj = result.nodes.find((n) => n.kind === 'class' && n.name === 'DatabaseConfig');
  2676. expect(obj).toBeDefined();
  2677. });
  2678. it('should extract trait definitions as trait kind', () => {
  2679. const code = `
  2680. trait Repository[A] {
  2681. def findById(id: String): Option[A]
  2682. def save(entity: A): Unit
  2683. }
  2684. `;
  2685. const result = extractFromSource('Repository.scala', code);
  2686. const trait_ = result.nodes.find((n) => n.kind === 'trait' && n.name === 'Repository');
  2687. expect(trait_).toBeDefined();
  2688. });
  2689. });
  2690. describe('Method and function extraction', () => {
  2691. it('should extract method definitions inside a class', () => {
  2692. const code = `
  2693. class Calculator {
  2694. def add(a: Int, b: Int): Int = a + b
  2695. def divide(a: Double, b: Double): Double = a / b
  2696. }
  2697. `;
  2698. const result = extractFromSource('Calculator.scala', code);
  2699. const methods = result.nodes.filter((n) => n.kind === 'method');
  2700. expect(methods.find((m) => m.name === 'add')).toBeDefined();
  2701. expect(methods.find((m) => m.name === 'divide')).toBeDefined();
  2702. });
  2703. it('should extract method signatures', () => {
  2704. const code = `
  2705. class Greeter {
  2706. def greet(name: String): String = s"Hello, \${name}!"
  2707. }
  2708. `;
  2709. const result = extractFromSource('Greeter.scala', code);
  2710. const method = result.nodes.find((n) => n.name === 'greet');
  2711. expect(method?.signature).toContain('name: String');
  2712. expect(method?.signature).toContain('String');
  2713. });
  2714. it('should extract top-level function definitions as functions', () => {
  2715. const code = `
  2716. def factorial(n: Int): Int = if (n <= 1) 1 else n * factorial(n - 1)
  2717. def greet(name: String): String = s"Hello, \${name}!"
  2718. `;
  2719. const result = extractFromSource('utils.scala', code);
  2720. const fns = result.nodes.filter((n) => n.kind === 'function');
  2721. expect(fns.find((f) => f.name === 'factorial')).toBeDefined();
  2722. expect(fns.find((f) => f.name === 'greet')).toBeDefined();
  2723. });
  2724. });
  2725. describe('Val and var extraction', () => {
  2726. it('should extract val inside a class as field', () => {
  2727. const code = `
  2728. class Config {
  2729. val timeout: Int = 30
  2730. val host: String = "localhost"
  2731. }
  2732. `;
  2733. const result = extractFromSource('Config.scala', code);
  2734. const fields = result.nodes.filter((n) => n.kind === 'field');
  2735. expect(fields.find((f) => f.name === 'timeout')).toBeDefined();
  2736. expect(fields.find((f) => f.name === 'host')).toBeDefined();
  2737. });
  2738. it('should extract var inside a class as field', () => {
  2739. const code = `
  2740. class Counter {
  2741. var count: Int = 0
  2742. }
  2743. `;
  2744. const result = extractFromSource('Counter.scala', code);
  2745. const field = result.nodes.find((n) => n.kind === 'field' && n.name === 'count');
  2746. expect(field).toBeDefined();
  2747. });
  2748. it('should extract top-level val as constant', () => {
  2749. const code = `
  2750. val MaxConnections: Int = 100
  2751. val DefaultTimeout = 30
  2752. `;
  2753. const result = extractFromSource('constants.scala', code);
  2754. const consts = result.nodes.filter((n) => n.kind === 'constant');
  2755. expect(consts.find((c) => c.name === 'MaxConnections')).toBeDefined();
  2756. });
  2757. it('should extract top-level var as variable', () => {
  2758. const code = `
  2759. var retries: Int = 3
  2760. `;
  2761. const result = extractFromSource('state.scala', code);
  2762. const v = result.nodes.find((n) => n.kind === 'variable' && n.name === 'retries');
  2763. expect(v).toBeDefined();
  2764. });
  2765. it('should include type in val/var signature', () => {
  2766. const code = `
  2767. class Service {
  2768. val timeout: Int = 30
  2769. }
  2770. `;
  2771. const result = extractFromSource('Service.scala', code);
  2772. const field = result.nodes.find((n) => n.name === 'timeout');
  2773. expect(field?.signature).toContain('timeout');
  2774. expect(field?.signature).toContain('Int');
  2775. });
  2776. });
  2777. describe('Enum extraction', () => {
  2778. it('should extract enum definitions', () => {
  2779. const code = `
  2780. enum Color:
  2781. case Red
  2782. case Green
  2783. case Blue
  2784. `;
  2785. const result = extractFromSource('Color.scala', code);
  2786. const enumNode = result.nodes.find((n) => n.kind === 'enum' && n.name === 'Color');
  2787. expect(enumNode).toBeDefined();
  2788. });
  2789. it('should extract enum cases as enum_member', () => {
  2790. const code = `
  2791. enum Direction:
  2792. case North
  2793. case South
  2794. case East
  2795. case West
  2796. `;
  2797. const result = extractFromSource('Direction.scala', code);
  2798. const members = result.nodes.filter((n) => n.kind === 'enum_member');
  2799. expect(members.find((m) => m.name === 'North')).toBeDefined();
  2800. expect(members.find((m) => m.name === 'South')).toBeDefined();
  2801. expect(members.length).toBeGreaterThanOrEqual(4);
  2802. });
  2803. });
  2804. describe('Type alias extraction', () => {
  2805. it('should extract type aliases', () => {
  2806. const code = `
  2807. type UserId = String
  2808. type UserMap = Map[String, String]
  2809. `;
  2810. const result = extractFromSource('types.scala', code);
  2811. const aliases = result.nodes.filter((n) => n.kind === 'type_alias');
  2812. expect(aliases.find((a) => a.name === 'UserId')).toBeDefined();
  2813. expect(aliases.find((a) => a.name === 'UserMap')).toBeDefined();
  2814. });
  2815. });
  2816. describe('Import extraction', () => {
  2817. it('should extract import declarations', () => {
  2818. const code = `
  2819. import scala.collection.mutable.ListBuffer
  2820. import scala.concurrent.Future
  2821. `;
  2822. const result = extractFromSource('imports.scala', code);
  2823. const imports = result.nodes.filter((n) => n.kind === 'import');
  2824. expect(imports.length).toBeGreaterThanOrEqual(2);
  2825. });
  2826. });
  2827. describe('Visibility modifiers', () => {
  2828. it('should extract private visibility', () => {
  2829. const code = `
  2830. class Service {
  2831. private val secret: String = "abc"
  2832. private def helper(): Unit = {}
  2833. }
  2834. `;
  2835. const result = extractFromSource('Service.scala', code);
  2836. const secretField = result.nodes.find((n) => n.name === 'secret');
  2837. expect(secretField?.visibility).toBe('private');
  2838. const helperMethod = result.nodes.find((n) => n.name === 'helper');
  2839. expect(helperMethod?.visibility).toBe('private');
  2840. });
  2841. it('should extract protected visibility', () => {
  2842. const code = `
  2843. class Base {
  2844. protected def helperMethod(): Unit = {}
  2845. }
  2846. `;
  2847. const result = extractFromSource('Base.scala', code);
  2848. const method = result.nodes.find((n) => n.name === 'helperMethod');
  2849. expect(method?.visibility).toBe('protected');
  2850. });
  2851. it('should default to public visibility', () => {
  2852. const code = `
  2853. class Greeter {
  2854. def hello(): Unit = {}
  2855. }
  2856. `;
  2857. const result = extractFromSource('Greeter.scala', code);
  2858. const method = result.nodes.find((n) => n.name === 'hello');
  2859. expect(method?.visibility).toBe('public');
  2860. });
  2861. });
  2862. describe('Inheritance', () => {
  2863. it('should extract extends relationships', () => {
  2864. const code = `
  2865. class AdminUser extends User {
  2866. def adminAction(): Unit = {}
  2867. }
  2868. `;
  2869. const result = extractFromSource('AdminUser.scala', code);
  2870. const extendsRefs = result.unresolvedReferences.filter((r) => r.referenceKind === 'extends');
  2871. expect(extendsRefs.find((r) => r.referenceName === 'User')).toBeDefined();
  2872. });
  2873. });
  2874. describe('Call extraction', () => {
  2875. it('should extract function call expressions', () => {
  2876. const code = `
  2877. def processData(): Unit = {
  2878. val result = computeResult()
  2879. println(result)
  2880. }
  2881. `;
  2882. const result = extractFromSource('processor.scala', code);
  2883. const calls = result.unresolvedReferences.filter((r) => r.referenceKind === 'calls');
  2884. expect(calls.length).toBeGreaterThan(0);
  2885. });
  2886. });
  2887. });
  2888. describe('Vue Extraction', () => {
  2889. it('should detect Vue files', () => {
  2890. expect(detectLanguage('App.vue')).toBe('vue');
  2891. expect(detectLanguage('components/Button.vue')).toBe('vue');
  2892. expect(isLanguageSupported('vue')).toBe(true);
  2893. });
  2894. it('should extract component node from a Vue SFC', () => {
  2895. const code = `<template>
  2896. <div>{{ message }}</div>
  2897. </template>
  2898. <script>
  2899. export default {
  2900. data() {
  2901. return { message: 'Hello' };
  2902. }
  2903. }
  2904. </script>
  2905. `;
  2906. const result = extractFromSource('HelloWorld.vue', code);
  2907. const componentNode = result.nodes.find((n) => n.kind === 'component');
  2908. expect(componentNode).toBeDefined();
  2909. expect(componentNode?.name).toBe('HelloWorld');
  2910. expect(componentNode?.language).toBe('vue');
  2911. expect(componentNode?.isExported).toBe(true);
  2912. });
  2913. it('should extract functions from <script> block', () => {
  2914. const code = `<template>
  2915. <button @click="handleClick">Click</button>
  2916. </template>
  2917. <script>
  2918. function handleClick() {
  2919. console.log('clicked');
  2920. }
  2921. const count = 0;
  2922. </script>
  2923. `;
  2924. const result = extractFromSource('Button.vue', code);
  2925. const componentNode = result.nodes.find((n) => n.kind === 'component');
  2926. expect(componentNode).toBeDefined();
  2927. expect(componentNode?.name).toBe('Button');
  2928. const funcNode = result.nodes.find((n) => n.kind === 'function' && n.name === 'handleClick');
  2929. expect(funcNode).toBeDefined();
  2930. expect(funcNode?.language).toBe('vue');
  2931. });
  2932. it('should extract from <script setup lang="ts"> block', () => {
  2933. const code = `<template>
  2934. <div>{{ count }}</div>
  2935. </template>
  2936. <script setup lang="ts">
  2937. import { ref } from 'vue';
  2938. const count = ref(0);
  2939. function increment(): void {
  2940. count.value++;
  2941. }
  2942. </script>
  2943. `;
  2944. const result = extractFromSource('Counter.vue', code);
  2945. const componentNode = result.nodes.find((n) => n.kind === 'component');
  2946. expect(componentNode).toBeDefined();
  2947. expect(componentNode?.name).toBe('Counter');
  2948. const funcNode = result.nodes.find((n) => n.kind === 'function' && n.name === 'increment');
  2949. expect(funcNode).toBeDefined();
  2950. expect(funcNode?.language).toBe('vue');
  2951. // All nodes should be marked as vue language
  2952. for (const node of result.nodes) {
  2953. expect(node.language).toBe('vue');
  2954. }
  2955. });
  2956. it('should extract from both <script> and <script setup> blocks', () => {
  2957. const code = `<template>
  2958. <div>{{ msg }}</div>
  2959. </template>
  2960. <script>
  2961. export default {
  2962. name: 'DualScript'
  2963. }
  2964. </script>
  2965. <script setup>
  2966. const msg = 'hello';
  2967. function greet() {
  2968. return msg;
  2969. }
  2970. </script>
  2971. `;
  2972. const result = extractFromSource('DualScript.vue', code);
  2973. const componentNode = result.nodes.find((n) => n.kind === 'component');
  2974. expect(componentNode).toBeDefined();
  2975. const greetFunc = result.nodes.find((n) => n.kind === 'function' && n.name === 'greet');
  2976. expect(greetFunc).toBeDefined();
  2977. });
  2978. it('should create component node for template-only Vue file', () => {
  2979. const code = `<template>
  2980. <div>Static content</div>
  2981. </template>
  2982. `;
  2983. const result = extractFromSource('Static.vue', code);
  2984. const componentNode = result.nodes.find((n) => n.kind === 'component');
  2985. expect(componentNode).toBeDefined();
  2986. expect(componentNode?.name).toBe('Static');
  2987. expect(componentNode?.language).toBe('vue');
  2988. // Only the component node should exist (no script nodes)
  2989. expect(result.nodes.length).toBe(1);
  2990. });
  2991. it('should create containment edges from component to script nodes', () => {
  2992. const code = `<template>
  2993. <div>{{ value }}</div>
  2994. </template>
  2995. <script setup lang="ts">
  2996. const value = 42;
  2997. </script>
  2998. `;
  2999. const result = extractFromSource('Contained.vue', code);
  3000. const componentNode = result.nodes.find((n) => n.kind === 'component');
  3001. expect(componentNode).toBeDefined();
  3002. // Should have containment edges from component to child nodes
  3003. const containEdges = result.edges.filter(
  3004. (e) => e.source === componentNode!.id && e.kind === 'contains'
  3005. );
  3006. expect(containEdges.length).toBeGreaterThan(0);
  3007. });
  3008. });
  3009. describe('Instantiates + Decorates edge extraction', () => {
  3010. it('emits an instantiates ref for `new Foo()`', () => {
  3011. const code = `
  3012. class Foo {}
  3013. function bootstrap() { return new Foo(); }
  3014. `;
  3015. const result = extractFromSource('app.ts', code);
  3016. const ref = result.unresolvedReferences.find(
  3017. (r) => r.referenceKind === 'instantiates' && r.referenceName === 'Foo'
  3018. );
  3019. expect(ref).toBeDefined();
  3020. });
  3021. it('strips type-argument suffix from generic constructors', () => {
  3022. const code = `
  3023. class Container<T> { constructor(_: T) {} }
  3024. function go() { return new Container<string>('x'); }
  3025. `;
  3026. const result = extractFromSource('app.ts', code);
  3027. const ref = result.unresolvedReferences.find(
  3028. (r) => r.referenceKind === 'instantiates'
  3029. );
  3030. expect(ref).toBeDefined();
  3031. // Container<string> must be normalised to "Container" — otherwise
  3032. // resolution can never match the class node.
  3033. expect(ref!.referenceName).toBe('Container');
  3034. });
  3035. it('keeps trailing identifier from qualified `new ns.Foo()`', () => {
  3036. const code = `
  3037. const ns = { Foo: class {} };
  3038. function go() { return new ns.Foo(); }
  3039. `;
  3040. const result = extractFromSource('app.ts', code);
  3041. const ref = result.unresolvedReferences.find(
  3042. (r) => r.referenceKind === 'instantiates'
  3043. );
  3044. // We can't always resolve which Foo, but the name should be the
  3045. // simple identifier so name-matching has a chance.
  3046. expect(ref?.referenceName).toBe('Foo');
  3047. });
  3048. it('emits a decorates ref for `@Foo class X {}`', () => {
  3049. const code = `
  3050. function Foo(_arg: string) { return (cls: any) => cls; }
  3051. @Foo('x')
  3052. class X {}
  3053. `;
  3054. const result = extractFromSource('app.ts', code);
  3055. const decorClass = result.unresolvedReferences.find(
  3056. (r) => r.referenceKind === 'decorates' && r.referenceName === 'Foo'
  3057. );
  3058. expect(decorClass).toBeDefined();
  3059. });
  3060. it('does NOT attribute a prior class\'s decorator to the next class', () => {
  3061. // Regression: the sibling-walk must stop at the first non-
  3062. // decorator separator. `@A class Foo {} @B class Bar {}` must
  3063. // produce `decorates(Foo, A)` and `decorates(Bar, B)` — never
  3064. // `decorates(Bar, A)`.
  3065. const code = `
  3066. function A(cls: any) { return cls; }
  3067. function B(cls: any) { return cls; }
  3068. @A
  3069. class Foo {}
  3070. @B
  3071. class Bar {}
  3072. `;
  3073. const result = extractFromSource('app.ts', code);
  3074. const decoratesEdges = result.unresolvedReferences.filter(
  3075. (r) => r.referenceKind === 'decorates'
  3076. );
  3077. // Exactly one decorates ref per decorated class, no cross-attribution.
  3078. const fromBar = decoratesEdges.filter((r) =>
  3079. result.nodes.find((n) => n.id === r.fromNodeId && n.name === 'Bar')
  3080. );
  3081. expect(fromBar.length).toBe(1);
  3082. expect(fromBar[0]!.referenceName).toBe('B');
  3083. });
  3084. it('emits a decorates ref for `@Foo method() {}`', () => {
  3085. const code = `
  3086. function Get(p: string) { return (t: any, k: string) => t; }
  3087. class Svc {
  3088. @Get('/x') method() { return 1; }
  3089. }
  3090. `;
  3091. const result = extractFromSource('app.ts', code);
  3092. const decorMethod = result.unresolvedReferences.find(
  3093. (r) => r.referenceKind === 'decorates' && r.referenceName === 'Get'
  3094. );
  3095. expect(decorMethod).toBeDefined();
  3096. // The decorated symbol must be `method`, not the constructor or class.
  3097. const decoratedNode = result.nodes.find((n) => n.id === decorMethod!.fromNodeId);
  3098. expect(decoratedNode?.name).toBe('method');
  3099. });
  3100. });
  3101. // =============================================================================
  3102. // Lua
  3103. // =============================================================================
  3104. describe('Lua Extraction', () => {
  3105. describe('Language detection', () => {
  3106. it('should detect Lua files', () => {
  3107. expect(detectLanguage('init.lua')).toBe('lua');
  3108. expect(detectLanguage('src/util.lua')).toBe('lua');
  3109. });
  3110. it('should report Lua as supported', () => {
  3111. expect(isLanguageSupported('lua')).toBe(true);
  3112. expect(getSupportedLanguages()).toContain('lua');
  3113. });
  3114. });
  3115. describe('Function extraction', () => {
  3116. it('should extract global and local functions', () => {
  3117. const code = `
  3118. function configure(opts) return opts end
  3119. local function helper(x) return x * 2 end
  3120. `;
  3121. const result = extractFromSource('init.lua', code);
  3122. const funcs = result.nodes.filter((n) => n.kind === 'function').map((n) => n.name);
  3123. expect(funcs).toContain('configure');
  3124. expect(funcs).toContain('helper');
  3125. const configure = result.nodes.find((n) => n.name === 'configure');
  3126. expect(configure?.language).toBe('lua');
  3127. expect(configure?.signature).toBe('(opts)');
  3128. });
  3129. it('should split table/method functions into a receiver and method name', () => {
  3130. const code = `
  3131. function M.connect(host, port) return host end
  3132. function M:send(data) return self end
  3133. `;
  3134. const result = extractFromSource('init.lua', code);
  3135. const methods = result.nodes.filter((n) => n.kind === 'method');
  3136. const connect = methods.find((m) => m.name === 'connect');
  3137. expect(connect?.qualifiedName).toBe('M::connect');
  3138. const send = methods.find((m) => m.name === 'send');
  3139. expect(send?.qualifiedName).toBe('M::send');
  3140. });
  3141. });
  3142. describe('Variable extraction', () => {
  3143. it('should extract local variable declarations', () => {
  3144. const code = `
  3145. local M = {}
  3146. local count = 0
  3147. `;
  3148. const result = extractFromSource('mod.lua', code);
  3149. const vars = result.nodes.filter((n) => n.kind === 'variable').map((n) => n.name);
  3150. expect(vars).toContain('M');
  3151. expect(vars).toContain('count');
  3152. });
  3153. });
  3154. describe('Import extraction (require)', () => {
  3155. it('should extract require() in local declarations and bare calls', () => {
  3156. const code = `
  3157. local socket = require("socket")
  3158. local http = require "resty.http"
  3159. require("side.effect")
  3160. `;
  3161. const result = extractFromSource('net.lua', code);
  3162. const imports = result.nodes.filter((n) => n.kind === 'import').map((n) => n.name);
  3163. expect(imports).toContain('socket');
  3164. expect(imports).toContain('resty.http');
  3165. expect(imports).toContain('side.effect');
  3166. const ref = result.unresolvedReferences.find(
  3167. (r) => r.referenceKind === 'imports' && r.referenceName === 'socket'
  3168. );
  3169. expect(ref).toBeDefined();
  3170. });
  3171. // Regression: the tree-sitter-wasms Lua grammar (ABI 13) corrupts the shared
  3172. // WASM heap under web-tree-sitter 0.25, dropping nested calls/imports on every
  3173. // parse after the first. We vendor the ABI-15 grammar instead — this guards it
  3174. // by extracting several sources in sequence and asserting the LAST still works.
  3175. it('should keep extracting require across many sequential parses', () => {
  3176. let last;
  3177. for (let i = 0; i < 8; i++) {
  3178. last = extractFromSource(`f${i}.lua`, `local m = require("module.${i}")\nreturn m\n`);
  3179. }
  3180. const imports = last!.nodes.filter((n) => n.kind === 'import').map((n) => n.name);
  3181. expect(imports).toContain('module.7');
  3182. });
  3183. });
  3184. describe('Call extraction', () => {
  3185. it('should record intra-file calls as resolvable references', () => {
  3186. const code = `
  3187. local function helper(x) return x end
  3188. local function run(y) return helper(y) end
  3189. `;
  3190. const result = extractFromSource('calls.lua', code);
  3191. const call = result.unresolvedReferences.find(
  3192. (r) => r.referenceKind === 'calls' && r.referenceName === 'helper'
  3193. );
  3194. expect(call).toBeDefined();
  3195. });
  3196. });
  3197. });
  3198. // =============================================================================
  3199. // Luau (typed superset of Lua — https://luau.org)
  3200. // =============================================================================
  3201. describe('Luau Extraction', () => {
  3202. describe('Language detection', () => {
  3203. it('should detect Luau files', () => {
  3204. expect(detectLanguage('init.luau')).toBe('luau');
  3205. expect(detectLanguage('src/Client.luau')).toBe('luau');
  3206. });
  3207. it('should report Luau as supported', () => {
  3208. expect(isLanguageSupported('luau')).toBe(true);
  3209. expect(getSupportedLanguages()).toContain('luau');
  3210. });
  3211. });
  3212. describe('Type aliases', () => {
  3213. it('should extract `type` and `export type` definitions', () => {
  3214. const code = `
  3215. export type Vector = { x: number, y: number }
  3216. type Handler = (msg: string) -> boolean
  3217. `;
  3218. const result = extractFromSource('types.luau', code);
  3219. const aliases = result.nodes.filter((n) => n.kind === 'type_alias');
  3220. const vector = aliases.find((a) => a.name === 'Vector');
  3221. expect(vector).toBeDefined();
  3222. expect(vector?.isExported).toBe(true);
  3223. const handler = aliases.find((a) => a.name === 'Handler');
  3224. expect(handler).toBeDefined();
  3225. expect(handler?.isExported).toBe(false);
  3226. });
  3227. });
  3228. describe('Typed functions and methods', () => {
  3229. it('should capture typed signatures and split methods by receiver', () => {
  3230. const code = `
  3231. function configure(opts: { debug: boolean }): boolean
  3232. return opts.debug
  3233. end
  3234. function Client:fetch(path: string): Response
  3235. return path
  3236. end
  3237. `;
  3238. const result = extractFromSource('client.luau', code);
  3239. const configure = result.nodes.find((n) => n.kind === 'function' && n.name === 'configure');
  3240. expect(configure?.language).toBe('luau');
  3241. expect(configure?.signature).toBe('(opts: { debug: boolean }): boolean');
  3242. const fetch = result.nodes.find((n) => n.kind === 'method' && n.name === 'fetch');
  3243. expect(fetch?.qualifiedName).toBe('Client::fetch');
  3244. });
  3245. });
  3246. describe('Imports and variables', () => {
  3247. it('should extract string and Roblox instance-path require imports', () => {
  3248. const code = `
  3249. local http = require("http")
  3250. local Signal = require(script.Parent.Signal)
  3251. local count = 0
  3252. `;
  3253. const result = extractFromSource('mod.luau', code);
  3254. const imports = result.nodes.filter((n) => n.kind === 'import').map((n) => n.name);
  3255. expect(imports).toContain('http'); // string require
  3256. expect(imports).toContain('Signal'); // Roblox instance-path require
  3257. const vars = result.nodes.filter((n) => n.kind === 'variable').map((n) => n.name);
  3258. expect(vars).toContain('count');
  3259. });
  3260. });
  3261. });