extraction.test.ts 129 KB

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