extraction.test.ts 169 KB

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