1
0

extraction.test.ts 139 KB

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