1
0

extraction.test.ts 260 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302
  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, buildDefaultIgnore } 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('captures docstrings for export- and const-wrapped declarations (#780)', () => {
  156. const code = `
  157. // plain class control
  158. class Ledger {}
  159. // exported class
  160. export class Invoice {}
  161. // export default
  162. export default function settle() { return true; }
  163. // exported arrow const
  164. export const refund = (amount: number) => amount;
  165. // non-export arrow const
  166. const audit = (amount: number) => amount;
  167. `;
  168. const byName = new Map(extractFromSource('doc.ts', code).nodes.map((n) => [n.name, n]));
  169. expect(byName.get('Ledger')?.docstring).toBe('plain class control'); // control still works
  170. expect(byName.get('Invoice')?.docstring).toBe('exported class');
  171. expect(byName.get('settle')?.docstring).toBe('export default');
  172. expect(byName.get('refund')?.docstring).toBe('exported arrow const');
  173. expect(byName.get('audit')?.docstring).toBe('non-export arrow const');
  174. });
  175. it('does not mis-attribute a class comment to an uncommented member (#780)', () => {
  176. const code = `
  177. // Comment for Box
  178. export class Box {
  179. noComment() {}
  180. // own comment
  181. withComment() {}
  182. }
  183. `;
  184. const byName = new Map(extractFromSource('box.ts', code).nodes.map((n) => [n.name, n]));
  185. expect(byName.get('Box')?.docstring).toBe('Comment for Box');
  186. expect(byName.get('noComment')?.docstring ?? null).toBeNull(); // no over-walk
  187. expect(byName.get('withComment')?.docstring).toBe('own comment');
  188. });
  189. it('captures docstrings for decorated Python declarations, stripping `#` (#780)', () => {
  190. const code = [
  191. '# decorated function',
  192. '@app.route("/x")',
  193. 'def py_handler():',
  194. ' return 1',
  195. '',
  196. '',
  197. '# plain function control',
  198. 'def py_plain():',
  199. ' return 1',
  200. '',
  201. '',
  202. '# decorated class',
  203. '@dataclass',
  204. 'class PyModel:',
  205. ' pass',
  206. '',
  207. ].join('\n');
  208. const byName = new Map(extractFromSource('mod.py', code).nodes.map((n) => [n.name, n]));
  209. expect(byName.get('py_handler')?.docstring).toBe('decorated function');
  210. expect(byName.get('py_plain')?.docstring).toBe('plain function control'); // `#` stripped
  211. expect(byName.get('PyModel')?.docstring).toBe('decorated class');
  212. });
  213. it('cleans comment markers across language styles (#780)', () => {
  214. const doc = (file: string, code: string, name: string) =>
  215. new Map(extractFromSource(file, code).nodes.map((n) => [n.name, n])).get(name)?.docstring;
  216. // Rust doc lines (`///`, `//!`) — the trailing slash used to leak through.
  217. expect(doc('m.rs', '/// rust doc line\nfn rs_fn() {}', 'rs_fn')).toBe('rust doc line');
  218. // Lua line + long-bracket comments.
  219. expect(doc('m.lua', '-- lua line\nfunction lua_fn() end', 'lua_fn')).toBe('lua line');
  220. expect(doc('b.lua', '--[[ lua block ]]\nfunction lua_b() end', 'lua_b')).toBe('lua block');
  221. // Pascal brace and paren-star comments.
  222. const pasUnit = (c: string) =>
  223. `unit U;\ninterface\n${c}\nprocedure P;\nimplementation\nprocedure P;\nbegin\nend;\nend.\n`;
  224. expect(doc('a.pas', pasUnit('{ pascal brace }'), 'P')).toBe('pascal brace');
  225. expect(doc('c.pas', pasUnit('(* pascal paren *)'), 'P')).toBe('pascal paren');
  226. // C block comment still clean (no regression).
  227. expect(doc('m.c', '/* c block */\nvoid c_fn(void) {}', 'c_fn')).toBe('c block');
  228. });
  229. it('should extract interfaces', () => {
  230. const code = `
  231. export interface User {
  232. id: string;
  233. name: string;
  234. email: string;
  235. }
  236. `;
  237. const result = extractFromSource('types.ts', code);
  238. const fileNode = result.nodes.find((n) => n.kind === 'file');
  239. expect(fileNode).toBeDefined();
  240. const ifaceNode = result.nodes.find((n) => n.kind === 'interface');
  241. expect(ifaceNode).toMatchObject({
  242. kind: 'interface',
  243. name: 'User',
  244. isExported: true,
  245. });
  246. });
  247. it('should extract type references from interface property signatures', () => {
  248. const code = `
  249. import type { IPage } from '../PromoterList';
  250. import type { IOrderField } from '../types';
  251. interface Hprops {
  252. value?: Partial<IPage> & Partial<IOrderField>;
  253. }
  254. `;
  255. const result = extractFromSource('HeaderFilter.ts', code);
  256. const refs = result.unresolvedReferences.filter((r) => r.referenceKind === 'references');
  257. expect(refs.some((r) => r.referenceName === 'IPage')).toBe(true);
  258. expect(refs.some((r) => r.referenceName === 'IOrderField')).toBe(true);
  259. });
  260. it('should extract type references from interface method signatures', () => {
  261. const code = `
  262. import type { IPage } from '../PromoterList';
  263. import type { IOrderField } from '../types';
  264. interface MethodForm {
  265. fetchPage(arg: IPage): IOrderField;
  266. }
  267. `;
  268. const result = extractFromSource('MethodForm.ts', code);
  269. const refs = result.unresolvedReferences.filter((r) => r.referenceKind === 'references');
  270. expect(refs.some((r) => r.referenceName === 'IPage')).toBe(true);
  271. expect(refs.some((r) => r.referenceName === 'IOrderField')).toBe(true);
  272. });
  273. it('extracts type references from in-body local variable annotations', () => {
  274. // A function that uses a type ONLY in its body — `const items: Foo[] = []` —
  275. // still depends on Foo. The body walker used to capture calls but never type
  276. // annotations, so impact / `affected` missed the dependency. Must cover
  277. // function, class-method, and object-literal-method bodies — and must NOT
  278. // turn the locals themselves into graph nodes (that would explode the graph).
  279. const code = `
  280. import { Foo } from './types';
  281. export function build(): void {
  282. const items: Foo[] = [];
  283. void items;
  284. }
  285. export class K {
  286. run(): void {
  287. const a: Foo = { x: 1 };
  288. void a;
  289. }
  290. }
  291. export const handler = {
  292. handle(): void {
  293. const b: Foo = { x: 1 };
  294. void b;
  295. },
  296. };
  297. `;
  298. const result = extractFromSource('inbody.ts', code);
  299. const fooRefs = result.unresolvedReferences.filter(
  300. (r) => r.referenceKind === 'references' && r.referenceName === 'Foo'
  301. );
  302. // One per body scope: build(), K.run(), handler.handle().
  303. expect(fooRefs.length).toBeGreaterThanOrEqual(3);
  304. // Each reference is attributed to its enclosing function/method node — never
  305. // to a local-variable node, because locals are intentionally not extracted.
  306. const byId = new Map(result.nodes.map((n) => [n.id, n]));
  307. for (const ref of fooRefs) {
  308. const owner = byId.get(ref.fromNodeId);
  309. expect(owner).toBeDefined();
  310. expect(['function', 'method']).toContain(owner!.kind);
  311. }
  312. // The locals (items/a/b) must not leak in as symbols.
  313. expect(result.nodes.some((n) => ['items', 'a', 'b'].includes(n.name))).toBe(false);
  314. });
  315. it('should track function calls', () => {
  316. const code = `
  317. function main() {
  318. const result = processData();
  319. console.log(result);
  320. }
  321. `;
  322. const result = extractFromSource('main.ts', code);
  323. expect(result.unresolvedReferences.length).toBeGreaterThan(0);
  324. const calls = result.unresolvedReferences.filter((r) => r.referenceKind === 'calls');
  325. expect(calls.some((c) => c.referenceName === 'processData')).toBe(true);
  326. });
  327. });
  328. describe('Arrow Function Export Extraction', () => {
  329. it('should extract exported arrow functions assigned to const', () => {
  330. const code = `
  331. export const useAuth = (): AuthContextValue => {
  332. return useContext(AuthContext);
  333. };
  334. `;
  335. const result = extractFromSource('hooks.ts', code);
  336. const funcNode = result.nodes.find((n) => n.kind === 'function' && n.name === 'useAuth');
  337. expect(funcNode).toBeDefined();
  338. expect(funcNode).toMatchObject({
  339. kind: 'function',
  340. name: 'useAuth',
  341. isExported: true,
  342. });
  343. });
  344. it('should extract exported function expressions assigned to const', () => {
  345. const code = `
  346. export const processData = function(input: string): string {
  347. return input.trim();
  348. };
  349. `;
  350. const result = extractFromSource('utils.ts', code);
  351. const funcNode = result.nodes.find((n) => n.kind === 'function' && n.name === 'processData');
  352. expect(funcNode).toBeDefined();
  353. expect(funcNode).toMatchObject({
  354. kind: 'function',
  355. name: 'processData',
  356. isExported: true,
  357. });
  358. });
  359. it('should not extract non-exported arrow functions as exported', () => {
  360. const code = `
  361. const internalHelper = () => {
  362. return 42;
  363. };
  364. `;
  365. const result = extractFromSource('internal.ts', code);
  366. const helperNode = result.nodes.find((n) => n.name === 'internalHelper');
  367. expect(helperNode).toBeDefined();
  368. expect(helperNode?.isExported).toBeFalsy();
  369. });
  370. it('should still skip truly anonymous arrow functions', () => {
  371. const code = `
  372. const items = [1, 2, 3].map((x) => x * 2);
  373. `;
  374. const result = extractFromSource('anon.ts', code);
  375. // The inline arrow function passed to .map() has no variable_declarator parent
  376. // and should remain anonymous (skipped)
  377. const anonFunctions = result.nodes.filter(
  378. (n) => n.kind === 'function' && n.name === '<anonymous>'
  379. );
  380. expect(anonFunctions).toHaveLength(0);
  381. });
  382. it('should extract multiple exported arrow functions from the same file', () => {
  383. const code = `
  384. export const add = (a: number, b: number): number => a + b;
  385. export const subtract = (a: number, b: number): number => a - b;
  386. const internal = () => 'not exported';
  387. `;
  388. const result = extractFromSource('math.ts', code);
  389. const exported = result.nodes.filter((n) => n.kind === 'function' && n.isExported);
  390. expect(exported).toHaveLength(2);
  391. expect(exported.map((n) => n.name).sort()).toEqual(['add', 'subtract']);
  392. const internalNode = result.nodes.find((n) => n.name === 'internal');
  393. expect(internalNode).toBeDefined();
  394. expect(internalNode?.isExported).toBeFalsy();
  395. });
  396. it('should extract arrow functions in JavaScript files', () => {
  397. const code = `
  398. export const fetchData = async () => {
  399. const response = await fetch('/api/data');
  400. return response.json();
  401. };
  402. `;
  403. const result = extractFromSource('api.js', code);
  404. const funcNode = result.nodes.find((n) => n.kind === 'function' && n.name === 'fetchData');
  405. expect(funcNode).toBeDefined();
  406. expect(funcNode).toMatchObject({
  407. kind: 'function',
  408. name: 'fetchData',
  409. isExported: true,
  410. });
  411. });
  412. });
  413. describe('Type Alias Extraction', () => {
  414. it('should extract exported type aliases in TypeScript', () => {
  415. const code = `
  416. export type AuthContextValue = {
  417. user: User | null;
  418. login: () => void;
  419. logout: () => void;
  420. };
  421. `;
  422. const result = extractFromSource('types.ts', code);
  423. const typeNode = result.nodes.find((n) => n.kind === 'type_alias');
  424. expect(typeNode).toMatchObject({
  425. kind: 'type_alias',
  426. name: 'AuthContextValue',
  427. isExported: true,
  428. });
  429. });
  430. it('should extract non-exported type aliases', () => {
  431. const code = `
  432. type InternalState = {
  433. loading: boolean;
  434. error: string | null;
  435. };
  436. `;
  437. const result = extractFromSource('internal.ts', code);
  438. const typeNode = result.nodes.find((n) => n.kind === 'type_alias');
  439. expect(typeNode).toMatchObject({
  440. kind: 'type_alias',
  441. name: 'InternalState',
  442. isExported: false,
  443. });
  444. });
  445. it('should extract multiple type aliases from the same file', () => {
  446. const code = `
  447. export type UnitSystem = 'metric' | 'imperial';
  448. export type DateFormat = 'ISO' | 'US' | 'EU';
  449. type Internal = string;
  450. `;
  451. const result = extractFromSource('config.ts', code);
  452. const typeAliases = result.nodes.filter((n) => n.kind === 'type_alias');
  453. expect(typeAliases).toHaveLength(3);
  454. const exported = typeAliases.filter((n) => n.isExported);
  455. expect(exported).toHaveLength(2);
  456. expect(exported.map((n) => n.name).sort()).toEqual(['DateFormat', 'UnitSystem']);
  457. });
  458. // A service/contract registry written as a tuple of generic instantiations —
  459. // the names are string-literal type arguments, not declarations, so static
  460. // extraction otherwise never indexes them (issue #634).
  461. it('extracts string-literal contract names from a generic tuple type alias (#634)', () => {
  462. const code = `
  463. interface Service<Name extends string, Req, Resp> { name: Name; }
  464. export type MyServiceList = [
  465. Service<'query_apply_record', { pageNo: number }, { ok: boolean }>,
  466. Service<'apply_confirm', { code: string }, { ok: boolean }>
  467. ];
  468. `;
  469. const result = extractFromSource('services/api.ts', code);
  470. const names = result.nodes.filter(
  471. (n) => n.kind === 'method' && n.qualifiedName.startsWith('MyServiceList::')
  472. );
  473. expect(names.map((n) => n.name).sort()).toEqual(['apply_confirm', 'query_apply_record']);
  474. const queryNode = names.find((n) => n.name === 'query_apply_record');
  475. expect(queryNode?.qualifiedName).toBe('MyServiceList::query_apply_record');
  476. // Signature carries the full contract entry so search results show context.
  477. expect(queryNode?.signature).toContain("Service<'query_apply_record'");
  478. // The string-literal name is contained by the type alias.
  479. const alias = result.nodes.find((n) => n.kind === 'type_alias' && n.name === 'MyServiceList');
  480. const containsEdge = result.edges.find(
  481. (e) => e.kind === 'contains' && e.source === alias?.id && e.target === queryNode?.id
  482. );
  483. expect(containsEdge).toBeDefined();
  484. });
  485. it('does not extract string literals from utility types or nested generics (#634)', () => {
  486. const code = `
  487. interface User { id: string; name: string; }
  488. interface Service<Name extends string, Req, Resp> { name: Name; }
  489. export type Picked = Pick<User, 'id' | 'name'>;
  490. export type Rec = Record<'foo' | 'bar', number>;
  491. // Tuple entry, but the name is a non-identifier route path; the nested Pick's
  492. // 'id' must also stay out (only DIRECT literal args of a tuple's generic count).
  493. export type Routes = [Service<'/api/users', Pick<User, 'id'>, {}>];
  494. // Bare string-literal tuple — not generic type arguments.
  495. export type Names = ['alpha', 'beta'];
  496. `;
  497. const result = extractFromSource('noise.ts', code);
  498. const leaked = result.nodes.filter(
  499. (n) =>
  500. (n.kind === 'method' || n.kind === 'property') &&
  501. ['id', 'name', 'foo', 'bar', 'alpha', 'beta'].includes(n.name)
  502. );
  503. expect(leaked).toEqual([]);
  504. });
  505. });
  506. describe('Exported Variable Extraction', () => {
  507. it('should extract exported const with call expression (Zustand store)', () => {
  508. const code = `
  509. export const useUIStore = create<UIState>((set) => ({
  510. isOpen: false,
  511. toggle: () => set((s) => ({ isOpen: !s.isOpen })),
  512. }));
  513. `;
  514. const result = extractFromSource('store.ts', code);
  515. const varNode = result.nodes.find((n) => n.kind === 'constant' && n.name === 'useUIStore');
  516. expect(varNode).toBeDefined();
  517. expect(varNode?.isExported).toBe(true);
  518. });
  519. it('should extract exported const with object literal', () => {
  520. const code = `
  521. export const config = {
  522. apiUrl: 'https://api.example.com',
  523. timeout: 5000,
  524. };
  525. `;
  526. const result = extractFromSource('config.ts', code);
  527. const varNode = result.nodes.find((n) => n.kind === 'constant' && n.name === 'config');
  528. expect(varNode).toBeDefined();
  529. expect(varNode?.isExported).toBe(true);
  530. });
  531. it('should extract exported const with array literal', () => {
  532. const code = `
  533. export const SCREEN_NAMES = ['home', 'settings', 'profile'] as const;
  534. `;
  535. const result = extractFromSource('constants.ts', code);
  536. const varNode = result.nodes.find((n) => n.kind === 'constant' && n.name === 'SCREEN_NAMES');
  537. expect(varNode).toBeDefined();
  538. expect(varNode?.isExported).toBe(true);
  539. });
  540. it('should extract exported const with primitive value', () => {
  541. const code = `
  542. export const MAX_RETRIES = 3;
  543. export const API_VERSION = "v2";
  544. `;
  545. const result = extractFromSource('constants.ts', code);
  546. const variables = result.nodes.filter((n) => n.kind === 'constant');
  547. expect(variables).toHaveLength(2);
  548. expect(variables.map((n) => n.name).sort()).toEqual(['API_VERSION', 'MAX_RETRIES']);
  549. });
  550. it('should NOT duplicate arrow functions as both function and variable', () => {
  551. const code = `
  552. export const useAuth = () => {
  553. return useContext(AuthContext);
  554. };
  555. `;
  556. const result = extractFromSource('hooks.ts', code);
  557. // Should be extracted as function (from arrow function handler), NOT as variable
  558. const funcNodes = result.nodes.filter((n) => n.kind === 'function' && n.name === 'useAuth');
  559. const varNodes = result.nodes.filter((n) => n.kind === 'variable' && n.name === 'useAuth');
  560. expect(funcNodes).toHaveLength(1);
  561. expect(varNodes).toHaveLength(0);
  562. });
  563. it('should extract non-exported const as non-exported variable', () => {
  564. const code = `
  565. const internalConfig = {
  566. debug: true,
  567. };
  568. `;
  569. const result = extractFromSource('internal.ts', code);
  570. // Non-exported const at file level should be extracted as a constant (not exported)
  571. const varNodes = result.nodes.filter((n) => (n.kind === 'variable' || n.kind === 'constant') && n.name === 'internalConfig');
  572. expect(varNodes).toHaveLength(1);
  573. expect(varNodes[0]?.isExported).toBeFalsy();
  574. });
  575. it('should extract Zod schema exports', () => {
  576. const code = `
  577. export const userSchema = z.object({
  578. id: z.string(),
  579. name: z.string(),
  580. email: z.string().email(),
  581. });
  582. `;
  583. const result = extractFromSource('schemas.ts', code);
  584. const varNode = result.nodes.find((n) => n.kind === 'constant' && n.name === 'userSchema');
  585. expect(varNode).toBeDefined();
  586. expect(varNode?.isExported).toBe(true);
  587. });
  588. it('should extract XState machine exports', () => {
  589. const code = `
  590. export const authMachine = createMachine({
  591. id: "auth",
  592. initial: "idle",
  593. states: {
  594. idle: {},
  595. authenticated: {},
  596. },
  597. });
  598. `;
  599. const result = extractFromSource('machine.ts', code);
  600. const varNode = result.nodes.find((n) => n.kind === 'constant' && n.name === 'authMachine');
  601. expect(varNode).toBeDefined();
  602. expect(varNode?.isExported).toBe(true);
  603. });
  604. it('should extract calls from a top-level variable initializer (issue #425)', () => {
  605. const code = `
  606. import { getTokenMp } from './api/upload';
  607. const token = getTokenMp();
  608. `;
  609. const result = extractFromSource('app.ts', code);
  610. const call = result.unresolvedReferences.find(
  611. (ref) => ref.referenceKind === 'calls' && ref.referenceName === 'getTokenMp'
  612. );
  613. expect(call).toBeDefined();
  614. });
  615. });
  616. describe('File Node Extraction', () => {
  617. it('should create a file-kind node for each parsed file', () => {
  618. const code = `
  619. export function greet(name: string): string {
  620. return "Hello " + name;
  621. }
  622. `;
  623. const result = extractFromSource('greeter.ts', code);
  624. const fileNode = result.nodes.find((n) => n.kind === 'file');
  625. expect(fileNode).toBeDefined();
  626. expect(fileNode?.name).toBe('greeter.ts');
  627. expect(fileNode?.filePath).toBe('greeter.ts');
  628. expect(fileNode?.language).toBe('typescript');
  629. expect(fileNode?.startLine).toBe(1);
  630. });
  631. it('should create file nodes for Python files', () => {
  632. const code = `
  633. def main():
  634. pass
  635. `;
  636. const result = extractFromSource('main.py', code);
  637. const fileNode = result.nodes.find((n) => n.kind === 'file');
  638. expect(fileNode).toBeDefined();
  639. expect(fileNode?.name).toBe('main.py');
  640. expect(fileNode?.language).toBe('python');
  641. });
  642. it('should create containment edges from file node to top-level declarations', () => {
  643. const code = `
  644. export function foo() {}
  645. export function bar() {}
  646. `;
  647. const result = extractFromSource('fns.ts', code);
  648. const fileNode = result.nodes.find((n) => n.kind === 'file');
  649. expect(fileNode).toBeDefined();
  650. // There should be contains edges from the file node to each function
  651. const containsEdges = result.edges.filter(
  652. (e) => e.source === fileNode?.id && e.kind === 'contains'
  653. );
  654. expect(containsEdges.length).toBeGreaterThanOrEqual(2);
  655. });
  656. });
  657. describe('Python Extraction', () => {
  658. it('should extract function definitions', () => {
  659. const code = `
  660. def calculate_total(items: list, tax_rate: float) -> float:
  661. """Calculate total with tax."""
  662. subtotal = sum(item.price for item in items)
  663. return subtotal * (1 + tax_rate)
  664. `;
  665. const result = extractFromSource('calc.py', code);
  666. const fileNode = result.nodes.find((n) => n.kind === 'file');
  667. expect(fileNode).toBeDefined();
  668. const funcNode = result.nodes.find((n) => n.kind === 'function');
  669. expect(funcNode).toMatchObject({
  670. kind: 'function',
  671. name: 'calculate_total',
  672. language: 'python',
  673. });
  674. });
  675. it('should extract class definitions', () => {
  676. const code = `
  677. class UserService:
  678. """Service for managing users."""
  679. def __init__(self, db):
  680. self.db = db
  681. def get_user(self, user_id: str) -> User:
  682. return self.db.find_user(user_id)
  683. `;
  684. const result = extractFromSource('service.py', code);
  685. const classNode = result.nodes.find((n) => n.kind === 'class');
  686. expect(classNode).toBeDefined();
  687. expect(classNode?.name).toBe('UserService');
  688. });
  689. });
  690. describe('Go Extraction', () => {
  691. it('should extract function declarations', () => {
  692. const code = `
  693. package main
  694. func ProcessOrder(order Order) (Receipt, error) {
  695. // Process the order
  696. return Receipt{}, nil
  697. }
  698. `;
  699. const result = extractFromSource('main.go', code);
  700. const funcNode = result.nodes.find((n) => n.kind === 'function');
  701. expect(funcNode).toBeDefined();
  702. expect(funcNode?.name).toBe('ProcessOrder');
  703. });
  704. it('should extract method declarations', () => {
  705. const code = `
  706. package main
  707. type Service struct {
  708. db *Database
  709. }
  710. func (s *Service) GetUser(id string) (*User, error) {
  711. return s.db.FindUser(id)
  712. }
  713. `;
  714. const result = extractFromSource('service.go', code);
  715. const methodNode = result.nodes.find((n) => n.kind === 'method');
  716. expect(methodNode).toBeDefined();
  717. expect(methodNode?.name).toBe('GetUser');
  718. });
  719. });
  720. describe('Rust Extraction', () => {
  721. it('should extract function declarations', () => {
  722. const code = `
  723. pub fn process_data(input: &str) -> Result<Output, Error> {
  724. // Process data
  725. Ok(Output::new())
  726. }
  727. `;
  728. const result = extractFromSource('lib.rs', code);
  729. const funcNode = result.nodes.find((n) => n.kind === 'function');
  730. expect(funcNode).toBeDefined();
  731. expect(funcNode?.name).toBe('process_data');
  732. expect(funcNode?.visibility).toBe('public');
  733. });
  734. it('should extract struct declarations', () => {
  735. const code = `
  736. pub struct User {
  737. pub id: String,
  738. pub name: String,
  739. email: String,
  740. }
  741. `;
  742. const result = extractFromSource('models.rs', code);
  743. const structNode = result.nodes.find((n) => n.kind === 'struct');
  744. expect(structNode).toBeDefined();
  745. expect(structNode?.name).toBe('User');
  746. });
  747. it('should extract trait declarations', () => {
  748. const code = `
  749. pub trait Repository {
  750. fn find(&self, id: &str) -> Option<Entity>;
  751. fn save(&mut self, entity: Entity) -> Result<(), Error>;
  752. }
  753. `;
  754. const result = extractFromSource('traits.rs', code);
  755. const traitNode = result.nodes.find((n) => n.kind === 'trait');
  756. expect(traitNode).toBeDefined();
  757. expect(traitNode?.name).toBe('Repository');
  758. });
  759. it('should extract impl Trait for Type as implements edges', () => {
  760. const code = `
  761. pub struct MyCache {}
  762. pub trait Cache {
  763. fn get(&self, key: &str) -> Option<String>;
  764. }
  765. impl Cache for MyCache {
  766. fn get(&self, key: &str) -> Option<String> {
  767. None
  768. }
  769. }
  770. `;
  771. const result = extractFromSource('cache.rs', code);
  772. // Should have an unresolved reference for implements
  773. const implRef = result.unresolvedReferences.find(
  774. (r) => r.referenceKind === 'implements' && r.referenceName === 'Cache'
  775. );
  776. expect(implRef).toBeDefined();
  777. // The struct MyCache should be the source
  778. const myCacheNode = result.nodes.find((n) => n.name === 'MyCache' && n.kind === 'struct');
  779. expect(myCacheNode).toBeDefined();
  780. expect(implRef?.fromNodeId).toBe(myCacheNode?.id);
  781. });
  782. it('should extract trait supertraits as extends references', () => {
  783. const code = `
  784. pub trait Display {}
  785. pub trait Error: Display {
  786. fn description(&self) -> &str;
  787. }
  788. `;
  789. const result = extractFromSource('error.rs', code);
  790. const extendsRef = result.unresolvedReferences.find(
  791. (r) => r.referenceKind === 'extends' && r.referenceName === 'Display'
  792. );
  793. expect(extendsRef).toBeDefined();
  794. const errorTrait = result.nodes.find((n) => n.name === 'Error' && n.kind === 'trait');
  795. expect(errorTrait).toBeDefined();
  796. expect(extendsRef?.fromNodeId).toBe(errorTrait?.id);
  797. });
  798. it('should not create implements edges for plain impl blocks', () => {
  799. const code = `
  800. pub struct Counter {
  801. count: u32,
  802. }
  803. impl Counter {
  804. pub fn new() -> Counter {
  805. Counter { count: 0 }
  806. }
  807. pub fn increment(&mut self) {
  808. self.count += 1;
  809. }
  810. }
  811. `;
  812. const result = extractFromSource('counter.rs', code);
  813. // Should have no implements references (no trait involved)
  814. const implRefs = result.unresolvedReferences.filter(
  815. (r) => r.referenceKind === 'implements'
  816. );
  817. expect(implRefs).toHaveLength(0);
  818. });
  819. });
  820. describe('Java Extraction', () => {
  821. it('should extract class declarations', () => {
  822. const code = `
  823. public class UserService {
  824. private final UserRepository repository;
  825. public UserService(UserRepository repository) {
  826. this.repository = repository;
  827. }
  828. public User getUser(String id) {
  829. return repository.findById(id);
  830. }
  831. }
  832. `;
  833. const result = extractFromSource('UserService.java', code);
  834. const classNode = result.nodes.find((n) => n.kind === 'class');
  835. expect(classNode).toBeDefined();
  836. expect(classNode?.name).toBe('UserService');
  837. expect(classNode?.visibility).toBe('public');
  838. });
  839. it('should extract method declarations', () => {
  840. const code = `
  841. public class Calculator {
  842. public static int add(int a, int b) {
  843. return a + b;
  844. }
  845. }
  846. `;
  847. const result = extractFromSource('Calculator.java', code);
  848. const methodNode = result.nodes.find((n) => n.kind === 'method' && n.name === 'add');
  849. expect(methodNode).toBeDefined();
  850. expect(methodNode?.isStatic).toBe(true);
  851. });
  852. it('wraps top-level declarations in a namespace from package_declaration', () => {
  853. const code = `
  854. package com.example.foo;
  855. public class Bar {
  856. public String greet() { return "hi"; }
  857. }
  858. `;
  859. const result = extractFromSource('Bar.java', code);
  860. const ns = result.nodes.find((n) => n.kind === 'namespace');
  861. expect(ns?.name).toBe('com.example.foo');
  862. const cls = result.nodes.find((n) => n.kind === 'class' && n.name === 'Bar');
  863. expect(cls?.qualifiedName).toBe('com.example.foo::Bar');
  864. const greet = result.nodes.find((n) => n.kind === 'method' && n.name === 'greet');
  865. expect(greet?.qualifiedName).toBe('com.example.foo::Bar::greet');
  866. });
  867. it('does not wrap when no package is declared', () => {
  868. const code = `
  869. public class Bar {
  870. public String greet() { return "hi"; }
  871. }
  872. `;
  873. const result = extractFromSource('Bar.java', code);
  874. expect(result.nodes.find((n) => n.kind === 'namespace')).toBeUndefined();
  875. const cls = result.nodes.find((n) => n.kind === 'class' && n.name === 'Bar');
  876. expect(cls?.qualifiedName).toBe('Bar');
  877. });
  878. it('extracts anonymous-class overrides from `new T() { ... }`', () => {
  879. // The pattern that breaks the trace through `strategy.foo()` in
  880. // libraries like guava's Splitter: the lambda-returned anonymous
  881. // class overrides abstract methods on the base, but without
  882. // extracting those overrides the interface→impl synthesizer has
  883. // nothing to bridge.
  884. const code = `
  885. package com.example;
  886. abstract class Base {
  887. abstract int compute(int x);
  888. }
  889. public class Factory {
  890. public Base make() {
  891. return new Base() {
  892. @Override
  893. int compute(int x) { return x + 1; }
  894. };
  895. }
  896. }
  897. `;
  898. const result = extractFromSource('Factory.java', code);
  899. const anon = result.nodes.find((n) => n.kind === 'class' && /Base\$anon@/.test(n.name));
  900. expect(anon, 'anonymous Base subclass should be extracted as a class').toBeDefined();
  901. const compute = result.nodes.find(
  902. (n) => n.kind === 'method' && n.name === 'compute' && n.qualifiedName.includes('$anon@')
  903. );
  904. expect(compute, 'override method should be a method on the anon class').toBeDefined();
  905. expect(compute!.qualifiedName).toContain('Factory::make::<Base$anon@');
  906. expect(compute!.qualifiedName.endsWith('::compute')).toBe(true);
  907. // Anon class must extend Base so Phase 5.5 (interface-impl) can bridge.
  908. const extendsRef = result.unresolvedReferences.find(
  909. (r) => r.referenceKind === 'extends' && r.referenceName === 'Base' && r.fromNodeId === anon!.id
  910. );
  911. expect(extendsRef, 'anon class should carry an `extends Base` reference').toBeDefined();
  912. // The enclosing `make` method still emits an instantiates edge to Base —
  913. // anon extraction must not swallow that signal.
  914. const instantiatesRef = result.unresolvedReferences.find(
  915. (r) => r.referenceKind === 'instantiates' && r.referenceName === 'Base'
  916. );
  917. expect(instantiatesRef, 'enclosing method should still instantiate Base').toBeDefined();
  918. });
  919. it('extracts anonymous-class overrides inside a lambda body', () => {
  920. // The exact guava pattern: a lambda is passed to a constructor, and the
  921. // lambda body returns `new T() { @Override ... }`. The anon class must
  922. // still surface even though it sits inside a lambda_expression node.
  923. const code = `
  924. package com.example;
  925. interface Strategy {
  926. java.util.Iterator<String> iterator(String s);
  927. }
  928. abstract class BaseIter implements java.util.Iterator<String> {
  929. abstract int separatorStart(int start);
  930. }
  931. public class Splitter {
  932. private final Strategy strategy;
  933. public Splitter(Strategy s) { this.strategy = s; }
  934. public static Splitter on(char c) {
  935. return new Splitter((seq) ->
  936. new BaseIter() {
  937. @Override
  938. int separatorStart(int start) { return start + 1; }
  939. @Override public boolean hasNext() { return false; }
  940. @Override public String next() { return null; }
  941. });
  942. }
  943. }
  944. `;
  945. const result = extractFromSource('Splitter.java', code);
  946. const anon = result.nodes.find((n) => n.kind === 'class' && /BaseIter\$anon@/.test(n.name));
  947. expect(anon, 'anon BaseIter inside the lambda body should be extracted').toBeDefined();
  948. const sepStart = result.nodes.find(
  949. (n) =>
  950. n.kind === 'method' &&
  951. n.name === 'separatorStart' &&
  952. n.qualifiedName.includes('$anon@')
  953. );
  954. expect(sepStart, 'override inside the lambda-returned anon class should be a method node').toBeDefined();
  955. });
  956. });
  957. describe('C# Extraction', () => {
  958. it('should extract class declarations', () => {
  959. const code = `
  960. public class OrderService
  961. {
  962. private readonly IOrderRepository _repository;
  963. public OrderService(IOrderRepository repository)
  964. {
  965. _repository = repository;
  966. }
  967. public async Task<Order> GetOrderAsync(string id)
  968. {
  969. return await _repository.FindByIdAsync(id);
  970. }
  971. }
  972. `;
  973. const result = extractFromSource('OrderService.cs', code);
  974. const classNode = result.nodes.find((n) => n.kind === 'class');
  975. expect(classNode).toBeDefined();
  976. expect(classNode?.name).toBe('OrderService');
  977. expect(classNode?.visibility).toBe('public');
  978. });
  979. it('indexes every record form with the right kind (#831)', () => {
  980. // The grammar parses ALL record forms as record_declaration — there is no
  981. // record_struct_declaration node — so the value-type forms are told apart
  982. // by their `struct` keyword child. Positional one-liners have no body
  983. // block and must still index (the no-body gate is for C/C++ forward
  984. // declarations, not records).
  985. const code = `
  986. namespace Fixture;
  987. public record SimplePositional(int A);
  988. public record WithBody(int A) { public int DoubleIt() => A * 2; }
  989. public record class ExplicitClassRec(string Name);
  990. public record struct ValueRec(int X);
  991. public readonly record struct ReadonlyRec(int X, int Y);
  992. public record DerivedRec(int A, string B) : SimplePositional(A);
  993. public record GenericRec<T>(T Value);
  994. public partial record PartialRec(int A);
  995. `;
  996. const result = extractFromSource('Records.cs', code);
  997. const kindOf = (name: string) => result.nodes.find((n) => n.name === name)?.kind;
  998. expect(kindOf('SimplePositional')).toBe('class');
  999. expect(kindOf('WithBody')).toBe('class');
  1000. expect(kindOf('ExplicitClassRec')).toBe('class');
  1001. expect(kindOf('DerivedRec')).toBe('class');
  1002. expect(kindOf('GenericRec')).toBe('class');
  1003. expect(kindOf('PartialRec')).toBe('class');
  1004. // Value-type records are structs, not classes.
  1005. expect(kindOf('ValueRec')).toBe('struct');
  1006. expect(kindOf('ReadonlyRec')).toBe('struct');
  1007. // Members of a bodied record still extract.
  1008. expect(kindOf('DoubleIt')).toBe('method');
  1009. });
  1010. it('indexes primary-constructor classes, including keyed-DI attribute params (#237)', () => {
  1011. // C# 12 primary constructors (`class Foo(IDep dep) { … }`) are parsed
  1012. // natively by the vendored tree-sitter-c-sharp 0.23.x grammar. The worst
  1013. // shape under the previous (older) grammar — an attribute-with-args on a
  1014. // ctor param (`[FromKeyedServices("primary")] …`, the ASP.NET keyed-DI
  1015. // pattern) — used to parse as an ERROR that swallowed the whole class, so
  1016. // the class and all its methods vanished. They now index in every case.
  1017. const code = `
  1018. public class DataService(IMemoryCache cache)
  1019. {
  1020. public void Warm() { }
  1021. }
  1022. public class InstanceService(InstanceManager m, ProfileManager p)
  1023. {
  1024. public void DeployAndLaunchAsync() { }
  1025. public void Deploy() { }
  1026. }
  1027. public partial class UpdateService(int x) : ILifetimeService
  1028. {
  1029. public void Run() { }
  1030. }
  1031. public class K1KeyedDi([FromKeyedServices("primary")] IMemoryCache cache)
  1032. {
  1033. public void Warm() { }
  1034. }
  1035. public record CatalogBrand(int Id, string Name);
  1036. `;
  1037. const result = extractFromSource('Services.cs', code);
  1038. const classNames = result.nodes.filter((n) => n.kind === 'class').map((n) => n.name);
  1039. expect(classNames).toContain('DataService');
  1040. expect(classNames).toContain('InstanceService');
  1041. expect(classNames).toContain('UpdateService'); // partial + base list
  1042. expect(classNames).toContain('K1KeyedDi'); // attribute-arg ctor param — used to vanish entirely
  1043. expect(classNames).toContain('CatalogBrand'); // record
  1044. const methods = result.nodes.filter((n) => n.kind === 'method').map((n) => n.name);
  1045. expect(methods).toContain('DeployAndLaunchAsync');
  1046. expect(methods).toContain('Deploy');
  1047. expect(methods).toContain('Run');
  1048. });
  1049. it('keeps a class indexable when a nested enum has #if-guarded members (#237)', () => {
  1050. // A `#if` directive inside an enum member list (the multi-targeting pattern
  1051. // in libraries like Newtonsoft.Json) makes the grammar emit an ERROR that,
  1052. // for a nested enum, detaches the enclosing class's member list — dropping
  1053. // most of the class's methods. A pre-parse pass blanks the directive lines
  1054. // (keeping both branches), so the class and all its methods still index.
  1055. const code = `
  1056. public class Reader
  1057. {
  1058. private enum ReadType
  1059. {
  1060. #if HAVE_DATE_TIME_OFFSET
  1061. ReadAsDateTimeOffset,
  1062. #endif
  1063. ReadAsDouble,
  1064. ReadAsString,
  1065. }
  1066. public void Open() { }
  1067. public void Close() { }
  1068. public int ReadInt() { return 0; }
  1069. }
  1070. `;
  1071. const result = extractFromSource('Reader.cs', code);
  1072. const methods = result.nodes.filter((n) => n.kind === 'method').map((n) => n.name);
  1073. // All three methods after the #if-bearing enum must survive.
  1074. expect(methods).toContain('Open');
  1075. expect(methods).toContain('Close');
  1076. expect(methods).toContain('ReadInt');
  1077. // Both enum branches are kept.
  1078. const enumMembers = result.nodes.filter((n) => n.kind === 'enum_member').map((n) => n.name);
  1079. expect(enumMembers).toContain('ReadAsDateTimeOffset');
  1080. expect(enumMembers).toContain('ReadAsDouble');
  1081. });
  1082. });
  1083. describe('PHP Extraction', () => {
  1084. it('should extract class declarations', () => {
  1085. const code = `<?php
  1086. class UserController
  1087. {
  1088. private UserService $userService;
  1089. public function __construct(UserService $userService)
  1090. {
  1091. $this->userService = $userService;
  1092. }
  1093. public function show(string $id): User
  1094. {
  1095. return $this->userService->find($id);
  1096. }
  1097. }
  1098. `;
  1099. const result = extractFromSource('UserController.php', code);
  1100. const classNode = result.nodes.find((n) => n.kind === 'class');
  1101. expect(classNode).toBeDefined();
  1102. expect(classNode?.name).toBe('UserController');
  1103. });
  1104. it('should extract class inheritance (extends) and interface implementation', () => {
  1105. const code = `<?php
  1106. class ChildController extends BaseController implements Serializable, JsonSerializable
  1107. {
  1108. public function serialize(): string
  1109. {
  1110. return json_encode($this);
  1111. }
  1112. }
  1113. `;
  1114. const result = extractFromSource('ChildController.php', code);
  1115. const classNode = result.nodes.find((n) => n.kind === 'class');
  1116. expect(classNode).toBeDefined();
  1117. expect(classNode?.name).toBe('ChildController');
  1118. const extendsRef = result.unresolvedReferences.find(
  1119. (r) => r.referenceKind === 'extends'
  1120. );
  1121. expect(extendsRef).toBeDefined();
  1122. expect(extendsRef?.referenceName).toBe('BaseController');
  1123. const implementsRefs = result.unresolvedReferences.filter(
  1124. (r) => r.referenceKind === 'implements'
  1125. );
  1126. expect(implementsRefs.length).toBe(2);
  1127. expect(implementsRefs.map((r) => r.referenceName)).toContain('Serializable');
  1128. expect(implementsRefs.map((r) => r.referenceName)).toContain('JsonSerializable');
  1129. });
  1130. });
  1131. describe('Swift Extraction', () => {
  1132. it('should extract class declarations', () => {
  1133. const code = `
  1134. public class NetworkManager {
  1135. private let session: URLSession
  1136. public init(session: URLSession = .shared) {
  1137. self.session = session
  1138. }
  1139. public func fetchData(from url: URL) async throws -> Data {
  1140. let (data, _) = try await session.data(from: url)
  1141. return data
  1142. }
  1143. }
  1144. `;
  1145. const result = extractFromSource('NetworkManager.swift', code);
  1146. const classNode = result.nodes.find((n) => n.kind === 'class');
  1147. expect(classNode).toBeDefined();
  1148. expect(classNode?.name).toBe('NetworkManager');
  1149. });
  1150. it('should extract function declarations', () => {
  1151. const code = `
  1152. func calculateSum(_ numbers: [Int]) -> Int {
  1153. return numbers.reduce(0, +)
  1154. }
  1155. public func formatCurrency(amount: Double) -> String {
  1156. return String(format: "$%.2f", amount)
  1157. }
  1158. `;
  1159. const result = extractFromSource('utils.swift', code);
  1160. const functions = result.nodes.filter((n) => n.kind === 'function');
  1161. expect(functions.length).toBeGreaterThanOrEqual(1);
  1162. });
  1163. it('should extract struct declarations', () => {
  1164. const code = `
  1165. public struct User {
  1166. let id: UUID
  1167. var name: String
  1168. var email: String
  1169. func displayName() -> String {
  1170. return name
  1171. }
  1172. }
  1173. `;
  1174. const result = extractFromSource('User.swift', code);
  1175. const structNode = result.nodes.find((n) => n.kind === 'struct');
  1176. expect(structNode).toBeDefined();
  1177. expect(structNode?.name).toBe('User');
  1178. });
  1179. it('should extract protocol declarations', () => {
  1180. const code = `
  1181. public protocol Repository {
  1182. associatedtype Entity
  1183. func find(id: String) async throws -> Entity?
  1184. func save(_ entity: Entity) async throws
  1185. }
  1186. `;
  1187. const result = extractFromSource('Repository.swift', code);
  1188. const protocolNode = result.nodes.find((n) => n.kind === 'interface');
  1189. expect(protocolNode).toBeDefined();
  1190. expect(protocolNode?.name).toBe('Repository');
  1191. });
  1192. it('should extract class inheritance and protocol conformance', () => {
  1193. const code = `
  1194. class DataRequest: Request {
  1195. func validate() {}
  1196. }
  1197. class UploadRequest: DataRequest, Sendable {
  1198. func upload() {}
  1199. }
  1200. enum AFError: Error {
  1201. case invalidURL
  1202. }
  1203. struct HTTPMethod: RawRepresentable {
  1204. let rawValue: String
  1205. }
  1206. protocol UploadConvertible: URLRequestConvertible {
  1207. func asURLRequest() throws -> URLRequest
  1208. }
  1209. `;
  1210. const result = extractFromSource('Inheritance.swift', code);
  1211. const extendsRefs = result.unresolvedReferences.filter(
  1212. (r) => r.referenceKind === 'extends'
  1213. );
  1214. // DataRequest extends Request
  1215. expect(extendsRefs.find((r) => r.referenceName === 'Request')).toBeDefined();
  1216. // UploadRequest extends DataRequest and Sendable
  1217. expect(extendsRefs.find((r) => r.referenceName === 'DataRequest')).toBeDefined();
  1218. expect(extendsRefs.find((r) => r.referenceName === 'Sendable')).toBeDefined();
  1219. // AFError extends Error
  1220. expect(extendsRefs.find((r) => r.referenceName === 'Error')).toBeDefined();
  1221. // HTTPMethod extends RawRepresentable
  1222. expect(extendsRefs.find((r) => r.referenceName === 'RawRepresentable')).toBeDefined();
  1223. // UploadConvertible extends URLRequestConvertible
  1224. expect(extendsRefs.find((r) => r.referenceName === 'URLRequestConvertible')).toBeDefined();
  1225. });
  1226. it('indexes Swift properties so they are findable: computed → property, stored → field, static → constant/variable (#1020)', () => {
  1227. const code = `
  1228. struct ReproConfig {
  1229. let reproStoredValue: Int
  1230. var reproComputedFlag: Bool {
  1231. reproStoredValue > 0
  1232. }
  1233. static let sharedLimit = 10
  1234. static var sharedCount = 0
  1235. func reproControlMethod() -> Bool {
  1236. reproComputedFlag
  1237. }
  1238. }
  1239. final class ReproService {
  1240. private let reproClassStored: String = "x"
  1241. var reproClassComputed: Int { reproClassStored.count }
  1242. }
  1243. `;
  1244. const result = extractFromSource('Repro.swift', code);
  1245. const byName = (name: string) => result.nodes.find((n) => n.name === name);
  1246. // Computed properties are the regression this fix targets: before #1020 they
  1247. // were dropped entirely, so search/explore returned nothing for them.
  1248. expect(byName('reproComputedFlag')?.kind).toBe('property');
  1249. expect(byName('reproClassComputed')?.kind).toBe('property');
  1250. // Stored instance properties stay `field` (fixed earlier in #708 — guard it).
  1251. expect(byName('reproStoredValue')?.kind).toBe('field');
  1252. expect(byName('reproClassStored')?.kind).toBe('field');
  1253. // `static let`/`static var` members remain shared constant/variable nodes.
  1254. expect(byName('sharedLimit')?.kind).toBe('constant');
  1255. expect(byName('sharedCount')?.kind).toBe('variable');
  1256. // The control method is unaffected.
  1257. expect(byName('reproControlMethod')?.kind).toBe('method');
  1258. });
  1259. it("attributes a computed property's getter calls to the property, not the type (SwiftUI body flow) (#1020)", () => {
  1260. const code = `
  1261. struct GreetingView {
  1262. let name: String
  1263. var body: some View {
  1264. let prefix = "Hi"
  1265. return VStack {
  1266. Text(greeting(prefix))
  1267. }
  1268. }
  1269. func greeting(_ p: String) -> String { p }
  1270. }
  1271. `;
  1272. const result = extractFromSource('View.swift', code);
  1273. const body = result.nodes.find((n) => n.kind === 'property' && n.name === 'body');
  1274. expect(body).toBeDefined();
  1275. // The getter's call to greeting() must originate from `body` (so a SwiftUI
  1276. // view's render flow is reachable through the property), not flatten onto the
  1277. // enclosing struct.
  1278. const callsFromBody = result.unresolvedReferences.filter(
  1279. (r) => r.fromNodeId === body!.id && r.referenceKind === 'calls'
  1280. );
  1281. expect(callsFromBody.some((r) => r.referenceName === 'greeting')).toBe(true);
  1282. // The getter is walked as a body, so a local declared inside it is NOT
  1283. // node-ified (locals are the data-flow frontier we leave uncovered). Before
  1284. // this fix the generic walker treated such a local as a struct `field`.
  1285. expect(result.nodes.find((n) => n.name === 'prefix')).toBeUndefined();
  1286. });
  1287. it('indexes a Swift protocol property requirement as a findable property (#1020)', () => {
  1288. const code = `
  1289. protocol Themable {
  1290. var accentColor: Color { get }
  1291. var title: String { get set }
  1292. }
  1293. `;
  1294. const result = extractFromSource('Themable.swift', code);
  1295. expect(result.nodes.find((n) => n.name === 'accentColor')?.kind).toBe('property');
  1296. expect(result.nodes.find((n) => n.name === 'title')?.kind).toBe('property');
  1297. });
  1298. });
  1299. describe('Kotlin Extraction', () => {
  1300. it('should extract class declarations', () => {
  1301. const code = `
  1302. class UserRepository(private val database: Database) {
  1303. fun findById(id: String): User? {
  1304. return database.query("SELECT * FROM users WHERE id = ?", id)
  1305. }
  1306. suspend fun save(user: User) {
  1307. database.insert(user)
  1308. }
  1309. }
  1310. `;
  1311. const result = extractFromSource('UserRepository.kt', code);
  1312. const classNode = result.nodes.find((n) => n.kind === 'class');
  1313. expect(classNode).toBeDefined();
  1314. expect(classNode?.name).toBe('UserRepository');
  1315. });
  1316. it('should extract function declarations', () => {
  1317. const code = `
  1318. fun calculateTotal(items: List<Item>): Double {
  1319. return items.sumOf { it.price }
  1320. }
  1321. suspend fun fetchUserData(userId: String): User {
  1322. return api.getUser(userId)
  1323. }
  1324. `;
  1325. const result = extractFromSource('utils.kt', code);
  1326. const functions = result.nodes.filter((n) => n.kind === 'function');
  1327. expect(functions.length).toBeGreaterThanOrEqual(1);
  1328. });
  1329. it('should detect suspend functions as async', () => {
  1330. const code = `
  1331. suspend fun loadData(): List<String> {
  1332. delay(1000)
  1333. return listOf("a", "b", "c")
  1334. }
  1335. `;
  1336. const result = extractFromSource('loader.kt', code);
  1337. const funcNode = result.nodes.find((n) => n.kind === 'function');
  1338. expect(funcNode).toBeDefined();
  1339. expect(funcNode?.isAsync).toBe(true);
  1340. });
  1341. it('should extract fun interface declarations', () => {
  1342. const code = `
  1343. fun interface OnObjectRetainedListener {
  1344. fun onObjectRetained()
  1345. }
  1346. `;
  1347. const result = extractFromSource('listener.kt', code);
  1348. const ifaceNode = result.nodes.find((n) => n.kind === 'interface');
  1349. expect(ifaceNode).toBeDefined();
  1350. expect(ifaceNode?.name).toBe('OnObjectRetainedListener');
  1351. const methodNode = result.nodes.find((n) => n.kind === 'method');
  1352. expect(methodNode).toBeDefined();
  1353. expect(methodNode?.name).toBe('onObjectRetained');
  1354. expect(methodNode?.qualifiedName).toBe('OnObjectRetainedListener::onObjectRetained');
  1355. });
  1356. it('should extract complex fun interface with nested classes', () => {
  1357. const code = `
  1358. fun interface EventListener {
  1359. fun onEvent(event: Event)
  1360. sealed class Event {
  1361. class DumpingHeap : Event()
  1362. }
  1363. }
  1364. `;
  1365. const result = extractFromSource('events.kt', code);
  1366. const ifaceNode = result.nodes.find((n) => n.kind === 'interface');
  1367. expect(ifaceNode).toBeDefined();
  1368. expect(ifaceNode?.name).toBe('EventListener');
  1369. // Nested sealed class should still be extracted (as sibling due to grammar limitations)
  1370. const eventClass = result.nodes.find((n) => n.kind === 'class' && n.name === 'Event');
  1371. expect(eventClass).toBeDefined();
  1372. const dumpingHeap = result.nodes.find((n) => n.kind === 'class' && n.name === 'DumpingHeap');
  1373. expect(dumpingHeap).toBeDefined();
  1374. });
  1375. it('should not affect regular function declarations', () => {
  1376. const code = `
  1377. fun interface MyCallback {
  1378. fun invoke(value: Int)
  1379. }
  1380. fun regularFunction(): String {
  1381. return "hello"
  1382. }
  1383. `;
  1384. const result = extractFromSource('mixed.kt', code);
  1385. const ifaceNode = result.nodes.find((n) => n.kind === 'interface');
  1386. expect(ifaceNode).toBeDefined();
  1387. expect(ifaceNode?.name).toBe('MyCallback');
  1388. const funcNode = result.nodes.find((n) => n.kind === 'function');
  1389. expect(funcNode).toBeDefined();
  1390. expect(funcNode?.name).toBe('regularFunction');
  1391. });
  1392. it('should extract fun interface with annotation on method (Pattern 2b)', () => {
  1393. // When the SAM method has annotations like @Throws, tree-sitter produces a different
  1394. // misparse: function_declaration > ERROR("interface Name {") instead of
  1395. // function_declaration > user_type("interface"). This is the OkHttp Interceptor pattern.
  1396. const code = `
  1397. import java.io.IOException
  1398. fun interface Interceptor {
  1399. @Throws(IOException::class)
  1400. fun intercept(chain: Chain): Response
  1401. }
  1402. `;
  1403. const result = extractFromSource('interceptor.kt', code);
  1404. const ifaceNode = result.nodes.find((n) => n.kind === 'interface');
  1405. expect(ifaceNode).toBeDefined();
  1406. expect(ifaceNode?.name).toBe('Interceptor');
  1407. });
  1408. it('should extract methods from interface with nested fun interface', () => {
  1409. // When an interface contains a nested `fun interface`, tree-sitter misparsed
  1410. // the parent body as ERROR. Methods inside should still be extracted.
  1411. const code = `
  1412. interface WebSocket {
  1413. fun request(): Request
  1414. fun send(text: String): Boolean
  1415. fun cancel()
  1416. fun interface Factory {
  1417. fun newWebSocket(request: Request): WebSocket
  1418. }
  1419. }
  1420. `;
  1421. const result = extractFromSource('websocket.kt', code);
  1422. const wsIface = result.nodes.find((n) => n.kind === 'interface' && n.name === 'WebSocket');
  1423. expect(wsIface).toBeDefined();
  1424. const methods = result.nodes.filter((n) => n.kind === 'method' && n.qualifiedName?.startsWith('WebSocket::'));
  1425. const methodNames = methods.map((m) => m.name);
  1426. expect(methodNames).toContain('request');
  1427. expect(methodNames).toContain('send');
  1428. expect(methodNames).toContain('cancel');
  1429. });
  1430. it('wraps top-level declarations in a namespace from package_header', () => {
  1431. const code = `
  1432. package com.example.foo
  1433. class Bar {
  1434. fun greet(): String = "hi"
  1435. }
  1436. fun util(): Int = 42
  1437. `;
  1438. const result = extractFromSource('Bar.kt', code);
  1439. const ns = result.nodes.find((n) => n.kind === 'namespace');
  1440. expect(ns?.name).toBe('com.example.foo');
  1441. const cls = result.nodes.find((n) => n.kind === 'class' && n.name === 'Bar');
  1442. expect(cls?.qualifiedName).toBe('com.example.foo::Bar');
  1443. const greet = result.nodes.find((n) => n.kind === 'method' && n.name === 'greet');
  1444. expect(greet?.qualifiedName).toBe('com.example.foo::Bar::greet');
  1445. const util = result.nodes.find((n) => n.kind === 'function' && n.name === 'util');
  1446. expect(util?.qualifiedName).toBe('com.example.foo::util');
  1447. });
  1448. it('handles a single-segment package', () => {
  1449. const code = `
  1450. package foo
  1451. class Bar
  1452. `;
  1453. const result = extractFromSource('Bar.kt', code);
  1454. const cls = result.nodes.find((n) => n.kind === 'class' && n.name === 'Bar');
  1455. expect(cls?.qualifiedName).toBe('foo::Bar');
  1456. });
  1457. it('does not wrap when no package is declared', () => {
  1458. const code = `
  1459. class Bar {
  1460. fun greet() = "hi"
  1461. }
  1462. `;
  1463. const result = extractFromSource('Bar.kt', code);
  1464. expect(result.nodes.find((n) => n.kind === 'namespace')).toBeUndefined();
  1465. const cls = result.nodes.find((n) => n.kind === 'class' && n.name === 'Bar');
  1466. expect(cls?.qualifiedName).toBe('Bar');
  1467. });
  1468. });
  1469. describe('Dart Extraction', () => {
  1470. it('should extract class declarations', () => {
  1471. const code = `
  1472. class UserService {
  1473. final Database _db;
  1474. Future<User> findById(String id) async {
  1475. return await _db.query(id);
  1476. }
  1477. void _privateMethod() {}
  1478. }
  1479. `;
  1480. const result = extractFromSource('service.dart', code);
  1481. const classNode = result.nodes.find((n) => n.kind === 'class');
  1482. expect(classNode).toBeDefined();
  1483. expect(classNode?.name).toBe('UserService');
  1484. expect(classNode?.visibility).toBe('public');
  1485. const methodNodes = result.nodes.filter((n) => n.kind === 'method');
  1486. expect(methodNodes.length).toBeGreaterThanOrEqual(2);
  1487. const findById = methodNodes.find((m) => m.name === 'findById');
  1488. expect(findById).toBeDefined();
  1489. expect(findById?.isAsync).toBe(true);
  1490. const privateMethod = methodNodes.find((m) => m.name === '_privateMethod');
  1491. expect(privateMethod).toBeDefined();
  1492. expect(privateMethod?.visibility).toBe('private');
  1493. // Dart models a method body as a SIBLING of the signature, so the method
  1494. // node must be extended to span its body (not just the signature line) —
  1495. // required for body-level analysis (callees, the callback synthesizer).
  1496. expect(findById!.endLine).toBeGreaterThan(findById!.startLine);
  1497. });
  1498. it('should extract top-level function declarations', () => {
  1499. const code = `
  1500. void topLevelFunction(String name) {
  1501. print(name);
  1502. }
  1503. `;
  1504. const result = extractFromSource('utils.dart', code);
  1505. const funcNode = result.nodes.find((n) => n.kind === 'function');
  1506. expect(funcNode).toBeDefined();
  1507. expect(funcNode?.name).toBe('topLevelFunction');
  1508. expect(funcNode?.language).toBe('dart');
  1509. });
  1510. it('should extract enum declarations', () => {
  1511. const code = `
  1512. enum Status { active, inactive, pending }
  1513. `;
  1514. const result = extractFromSource('models.dart', code);
  1515. const enumNode = result.nodes.find((n) => n.kind === 'enum');
  1516. expect(enumNode).toBeDefined();
  1517. expect(enumNode?.name).toBe('Status');
  1518. });
  1519. it('should extract mixin declarations', () => {
  1520. const code = `
  1521. mixin LoggerMixin {
  1522. void log(String message) {}
  1523. }
  1524. `;
  1525. const result = extractFromSource('mixins.dart', code);
  1526. const classNode = result.nodes.find((n) => n.kind === 'class');
  1527. expect(classNode).toBeDefined();
  1528. expect(classNode?.name).toBe('LoggerMixin');
  1529. const methodNode = result.nodes.find((n) => n.kind === 'method');
  1530. expect(methodNode).toBeDefined();
  1531. expect(methodNode?.name).toBe('log');
  1532. });
  1533. it('should extract extension declarations', () => {
  1534. const code = `
  1535. extension StringExt on String {
  1536. bool get isBlank => trim().isEmpty;
  1537. }
  1538. `;
  1539. const result = extractFromSource('extensions.dart', code);
  1540. const classNode = result.nodes.find((n) => n.kind === 'class');
  1541. expect(classNode).toBeDefined();
  1542. expect(classNode?.name).toBe('StringExt');
  1543. });
  1544. it('should detect static methods', () => {
  1545. const code = `
  1546. class Utils {
  1547. static void doWork() {}
  1548. }
  1549. `;
  1550. const result = extractFromSource('utils.dart', code);
  1551. const methodNode = result.nodes.find((n) => n.kind === 'method');
  1552. expect(methodNode).toBeDefined();
  1553. expect(methodNode?.name).toBe('doWork');
  1554. expect(methodNode?.isStatic).toBe(true);
  1555. });
  1556. it('should detect async functions', () => {
  1557. const code = `
  1558. Future<String> fetchData() async {
  1559. return await http.get('/data');
  1560. }
  1561. `;
  1562. const result = extractFromSource('api.dart', code);
  1563. const funcNode = result.nodes.find((n) => n.kind === 'function');
  1564. expect(funcNode).toBeDefined();
  1565. expect(funcNode?.name).toBe('fetchData');
  1566. expect(funcNode?.isAsync).toBe(true);
  1567. });
  1568. it('should detect private visibility via underscore convention', () => {
  1569. const code = `
  1570. void _privateHelper() {}
  1571. void publicFunction() {}
  1572. `;
  1573. const result = extractFromSource('helpers.dart', code);
  1574. const functions = result.nodes.filter((n) => n.kind === 'function');
  1575. const privateFunc = functions.find((f) => f.name === '_privateHelper');
  1576. const publicFunc = functions.find((f) => f.name === 'publicFunction');
  1577. expect(privateFunc?.visibility).toBe('private');
  1578. expect(publicFunc?.visibility).toBe('public');
  1579. });
  1580. });
  1581. describe('Import Extraction', () => {
  1582. describe('TypeScript/JavaScript imports', () => {
  1583. it('should extract default imports', () => {
  1584. const code = `import React from 'react';`;
  1585. const result = extractFromSource('app.tsx', code);
  1586. const importNode = result.nodes.find((n) => n.kind === 'import');
  1587. expect(importNode).toBeDefined();
  1588. expect(importNode?.name).toBe('react');
  1589. expect(importNode?.signature).toBe("import React from 'react';");
  1590. });
  1591. it('should extract named imports', () => {
  1592. const code = `import { Bug, Database } from '@phosphor-icons/react';`;
  1593. const result = extractFromSource('icons.tsx', code);
  1594. const importNode = result.nodes.find((n) => n.kind === 'import');
  1595. expect(importNode).toBeDefined();
  1596. expect(importNode?.name).toBe('@phosphor-icons/react');
  1597. expect(importNode?.signature).toContain('Bug');
  1598. expect(importNode?.signature).toContain('Database');
  1599. });
  1600. it('should extract namespace imports', () => {
  1601. const code = `import * as Icons from '@phosphor-icons/react';`;
  1602. const result = extractFromSource('icons.tsx', code);
  1603. const importNode = result.nodes.find((n) => n.kind === 'import');
  1604. expect(importNode).toBeDefined();
  1605. expect(importNode?.name).toBe('@phosphor-icons/react');
  1606. expect(importNode?.signature).toContain('* as Icons');
  1607. });
  1608. it('should extract side-effect imports', () => {
  1609. const code = `import './styles.css';`;
  1610. const result = extractFromSource('app.tsx', code);
  1611. const importNode = result.nodes.find((n) => n.kind === 'import');
  1612. expect(importNode).toBeDefined();
  1613. expect(importNode?.name).toBe('./styles.css');
  1614. });
  1615. it('should extract mixed imports (default + named)', () => {
  1616. const code = `import React, { useState, useEffect } from 'react';`;
  1617. const result = extractFromSource('app.tsx', code);
  1618. const importNode = result.nodes.find((n) => n.kind === 'import');
  1619. expect(importNode).toBeDefined();
  1620. expect(importNode?.name).toBe('react');
  1621. expect(importNode?.signature).toContain('React');
  1622. expect(importNode?.signature).toContain('useState');
  1623. expect(importNode?.signature).toContain('useEffect');
  1624. });
  1625. it('should extract multiple import statements', () => {
  1626. const code = `
  1627. import React from 'react';
  1628. import { Button } from './components';
  1629. import './styles.css';
  1630. `;
  1631. const result = extractFromSource('app.tsx', code);
  1632. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1633. expect(importNodes.length).toBe(3);
  1634. const names = importNodes.map((n) => n.name);
  1635. expect(names).toContain('react');
  1636. expect(names).toContain('./components');
  1637. expect(names).toContain('./styles.css');
  1638. });
  1639. it('should extract type imports', () => {
  1640. const code = `import type { FC, ReactNode } from 'react';`;
  1641. const result = extractFromSource('types.ts', code);
  1642. const importNode = result.nodes.find((n) => n.kind === 'import');
  1643. expect(importNode).toBeDefined();
  1644. expect(importNode?.name).toBe('react');
  1645. expect(importNode?.signature).toContain('type');
  1646. expect(importNode?.signature).toContain('FC');
  1647. });
  1648. it('should extract aliased named imports', () => {
  1649. const code = `import { useState as useStateAlias } from 'react';`;
  1650. const result = extractFromSource('hooks.ts', code);
  1651. const importNode = result.nodes.find((n) => n.kind === 'import');
  1652. expect(importNode).toBeDefined();
  1653. expect(importNode?.name).toBe('react');
  1654. expect(importNode?.signature).toContain('useState');
  1655. expect(importNode?.signature).toContain('useStateAlias');
  1656. });
  1657. it('should extract relative path imports', () => {
  1658. const code = `import { helper } from '../utils/helper';`;
  1659. const result = extractFromSource('components/Button.tsx', code);
  1660. const importNode = result.nodes.find((n) => n.kind === 'import');
  1661. expect(importNode).toBeDefined();
  1662. expect(importNode?.name).toBe('../utils/helper');
  1663. expect(importNode?.signature).toContain('helper');
  1664. });
  1665. });
  1666. describe('Python imports', () => {
  1667. it('should extract simple import statement', () => {
  1668. const code = `import json`;
  1669. const result = extractFromSource('utils.py', code);
  1670. const importNode = result.nodes.find((n) => n.kind === 'import');
  1671. expect(importNode).toBeDefined();
  1672. expect(importNode?.name).toBe('json');
  1673. });
  1674. it('should extract from import statement', () => {
  1675. const code = `from os import path`;
  1676. const result = extractFromSource('utils.py', code);
  1677. const importNode = result.nodes.find((n) => n.kind === 'import');
  1678. expect(importNode).toBeDefined();
  1679. expect(importNode?.name).toBe('os');
  1680. expect(importNode?.signature).toContain('path');
  1681. });
  1682. it('should extract multiple imports from same module', () => {
  1683. const code = `from typing import List, Dict, Optional`;
  1684. const result = extractFromSource('types.py', code);
  1685. const importNode = result.nodes.find((n) => n.kind === 'import');
  1686. expect(importNode).toBeDefined();
  1687. expect(importNode?.name).toBe('typing');
  1688. expect(importNode?.signature).toContain('List');
  1689. expect(importNode?.signature).toContain('Dict');
  1690. });
  1691. it('should extract multiple import statements', () => {
  1692. const code = `
  1693. import os
  1694. import sys
  1695. `;
  1696. const result = extractFromSource('main.py', code);
  1697. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1698. expect(importNodes.length).toBe(2);
  1699. const names = importNodes.map((n) => n.name);
  1700. expect(names).toContain('os');
  1701. expect(names).toContain('sys');
  1702. });
  1703. it('should extract aliased import', () => {
  1704. const code = `import numpy as np`;
  1705. const result = extractFromSource('data.py', code);
  1706. const importNode = result.nodes.find((n) => n.kind === 'import');
  1707. expect(importNode).toBeDefined();
  1708. expect(importNode?.name).toBe('numpy');
  1709. expect(importNode?.signature).toContain('as np');
  1710. });
  1711. it('should extract relative import', () => {
  1712. const code = `from .utils import helper`;
  1713. const result = extractFromSource('module.py', code);
  1714. const importNode = result.nodes.find((n) => n.kind === 'import');
  1715. expect(importNode).toBeDefined();
  1716. expect(importNode?.name).toBe('.utils');
  1717. expect(importNode?.signature).toContain('helper');
  1718. });
  1719. it('should extract wildcard import', () => {
  1720. const code = `from typing import *`;
  1721. const result = extractFromSource('types.py', code);
  1722. const importNode = result.nodes.find((n) => n.kind === 'import');
  1723. expect(importNode).toBeDefined();
  1724. expect(importNode?.name).toBe('typing');
  1725. expect(importNode?.signature).toContain('*');
  1726. });
  1727. });
  1728. describe('Rust imports', () => {
  1729. it('should extract simple use declaration', () => {
  1730. const code = `use std::io;`;
  1731. const result = extractFromSource('main.rs', code);
  1732. const importNode = result.nodes.find((n) => n.kind === 'import');
  1733. expect(importNode).toBeDefined();
  1734. expect(importNode?.name).toBe('std');
  1735. expect(importNode?.signature).toBe('use std::io;');
  1736. });
  1737. it('should extract scoped use list', () => {
  1738. const code = `use std::{ffi::OsStr, io, path::Path};`;
  1739. const result = extractFromSource('main.rs', code);
  1740. const importNode = result.nodes.find((n) => n.kind === 'import');
  1741. expect(importNode).toBeDefined();
  1742. expect(importNode?.name).toBe('std');
  1743. expect(importNode?.signature).toContain('ffi::OsStr');
  1744. expect(importNode?.signature).toContain('path::Path');
  1745. });
  1746. it('should extract crate imports', () => {
  1747. const code = `use crate::error::Error;`;
  1748. const result = extractFromSource('lib.rs', code);
  1749. const importNode = result.nodes.find((n) => n.kind === 'import');
  1750. expect(importNode).toBeDefined();
  1751. expect(importNode?.name).toBe('crate');
  1752. });
  1753. it('should extract super imports', () => {
  1754. const code = `use super::utils;`;
  1755. const result = extractFromSource('submod.rs', code);
  1756. const importNode = result.nodes.find((n) => n.kind === 'import');
  1757. expect(importNode).toBeDefined();
  1758. expect(importNode?.name).toBe('super');
  1759. });
  1760. it('should extract external crate imports', () => {
  1761. const code = `use serde::{Serialize, Deserialize};`;
  1762. const result = extractFromSource('types.rs', code);
  1763. const importNode = result.nodes.find((n) => n.kind === 'import');
  1764. expect(importNode).toBeDefined();
  1765. expect(importNode?.name).toBe('serde');
  1766. expect(importNode?.signature).toContain('Serialize');
  1767. expect(importNode?.signature).toContain('Deserialize');
  1768. });
  1769. });
  1770. describe('Go imports', () => {
  1771. it('should extract single import', () => {
  1772. const code = `
  1773. package main
  1774. import "fmt"
  1775. `;
  1776. const result = extractFromSource('main.go', code);
  1777. const importNode = result.nodes.find((n) => n.kind === 'import');
  1778. expect(importNode).toBeDefined();
  1779. expect(importNode?.name).toBe('fmt');
  1780. });
  1781. it('should extract grouped imports', () => {
  1782. const code = `
  1783. package main
  1784. import (
  1785. "fmt"
  1786. "os"
  1787. "encoding/json"
  1788. )
  1789. `;
  1790. const result = extractFromSource('main.go', code);
  1791. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1792. expect(importNodes.length).toBe(3);
  1793. const names = importNodes.map((n) => n.name);
  1794. expect(names).toContain('fmt');
  1795. expect(names).toContain('os');
  1796. expect(names).toContain('encoding/json');
  1797. });
  1798. it('should extract aliased import', () => {
  1799. const code = `
  1800. package main
  1801. import f "fmt"
  1802. `;
  1803. const result = extractFromSource('main.go', code);
  1804. const importNode = result.nodes.find((n) => n.kind === 'import');
  1805. expect(importNode).toBeDefined();
  1806. expect(importNode?.name).toBe('fmt');
  1807. expect(importNode?.signature).toContain('f');
  1808. });
  1809. it('should extract dot import', () => {
  1810. const code = `
  1811. package main
  1812. import . "math"
  1813. `;
  1814. const result = extractFromSource('main.go', code);
  1815. const importNode = result.nodes.find((n) => n.kind === 'import');
  1816. expect(importNode).toBeDefined();
  1817. expect(importNode?.name).toBe('math');
  1818. expect(importNode?.signature).toContain('.');
  1819. });
  1820. it('should extract blank import', () => {
  1821. const code = `
  1822. package main
  1823. import _ "github.com/go-sql-driver/mysql"
  1824. `;
  1825. const result = extractFromSource('main.go', code);
  1826. const importNode = result.nodes.find((n) => n.kind === 'import');
  1827. expect(importNode).toBeDefined();
  1828. expect(importNode?.name).toBe('github.com/go-sql-driver/mysql');
  1829. expect(importNode?.signature).toContain('_');
  1830. });
  1831. });
  1832. describe('Swift imports', () => {
  1833. it('should extract simple import', () => {
  1834. const code = `import Foundation`;
  1835. const result = extractFromSource('main.swift', code);
  1836. const importNode = result.nodes.find((n) => n.kind === 'import');
  1837. expect(importNode).toBeDefined();
  1838. expect(importNode?.name).toBe('Foundation');
  1839. expect(importNode?.signature).toBe('import Foundation');
  1840. });
  1841. it('should extract @testable import', () => {
  1842. const code = `@testable import Alamofire`;
  1843. const result = extractFromSource('Tests.swift', code);
  1844. const importNode = result.nodes.find((n) => n.kind === 'import');
  1845. expect(importNode).toBeDefined();
  1846. expect(importNode?.name).toBe('Alamofire');
  1847. expect(importNode?.signature).toContain('@testable');
  1848. });
  1849. it('should extract @preconcurrency import', () => {
  1850. const code = `@preconcurrency import Security`;
  1851. const result = extractFromSource('Auth.swift', code);
  1852. const importNode = result.nodes.find((n) => n.kind === 'import');
  1853. expect(importNode).toBeDefined();
  1854. expect(importNode?.name).toBe('Security');
  1855. });
  1856. it('should extract multiple imports', () => {
  1857. const code = `
  1858. import Foundation
  1859. import UIKit
  1860. import Alamofire
  1861. `;
  1862. const result = extractFromSource('App.swift', code);
  1863. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1864. expect(importNodes.length).toBe(3);
  1865. const names = importNodes.map((n) => n.name);
  1866. expect(names).toContain('Foundation');
  1867. expect(names).toContain('UIKit');
  1868. expect(names).toContain('Alamofire');
  1869. });
  1870. });
  1871. describe('Kotlin imports', () => {
  1872. it('should extract simple import', () => {
  1873. const code = `import java.io.IOException`;
  1874. const result = extractFromSource('Main.kt', code);
  1875. const importNode = result.nodes.find((n) => n.kind === 'import');
  1876. expect(importNode).toBeDefined();
  1877. expect(importNode?.name).toBe('java.io.IOException');
  1878. expect(importNode?.signature).toBe('import java.io.IOException');
  1879. });
  1880. it('should extract aliased import', () => {
  1881. const code = `import okhttp3.Request.Builder as RequestBuilder`;
  1882. const result = extractFromSource('Utils.kt', code);
  1883. const importNode = result.nodes.find((n) => n.kind === 'import');
  1884. expect(importNode).toBeDefined();
  1885. expect(importNode?.name).toBe('okhttp3.Request.Builder');
  1886. expect(importNode?.signature).toContain('as RequestBuilder');
  1887. });
  1888. it('should extract wildcard import', () => {
  1889. const code = `import java.util.concurrent.TimeUnit.*`;
  1890. const result = extractFromSource('Time.kt', code);
  1891. const importNode = result.nodes.find((n) => n.kind === 'import');
  1892. expect(importNode).toBeDefined();
  1893. expect(importNode?.name).toBe('java.util.concurrent.TimeUnit');
  1894. expect(importNode?.signature).toContain('.*');
  1895. });
  1896. it('should extract multiple imports', () => {
  1897. const code = `
  1898. import java.io.IOException
  1899. import kotlin.test.assertFailsWith
  1900. import okhttp3.OkHttpClient
  1901. `;
  1902. const result = extractFromSource('Test.kt', code);
  1903. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1904. expect(importNodes.length).toBe(3);
  1905. const names = importNodes.map((n) => n.name);
  1906. expect(names).toContain('java.io.IOException');
  1907. expect(names).toContain('kotlin.test.assertFailsWith');
  1908. expect(names).toContain('okhttp3.OkHttpClient');
  1909. });
  1910. });
  1911. describe('Java imports', () => {
  1912. it('should extract simple import', () => {
  1913. const code = `import java.util.List;`;
  1914. const result = extractFromSource('Main.java', code);
  1915. const importNode = result.nodes.find((n) => n.kind === 'import');
  1916. expect(importNode).toBeDefined();
  1917. expect(importNode?.name).toBe('java.util.List');
  1918. expect(importNode?.signature).toBe('import java.util.List;');
  1919. });
  1920. it('should extract static import', () => {
  1921. const code = `import static java.util.Collections.emptyList;`;
  1922. const result = extractFromSource('Utils.java', code);
  1923. const importNode = result.nodes.find((n) => n.kind === 'import');
  1924. expect(importNode).toBeDefined();
  1925. expect(importNode?.name).toBe('java.util.Collections.emptyList');
  1926. expect(importNode?.signature).toContain('static');
  1927. });
  1928. it('should extract wildcard import', () => {
  1929. const code = `import java.util.*;`;
  1930. const result = extractFromSource('App.java', code);
  1931. const importNode = result.nodes.find((n) => n.kind === 'import');
  1932. expect(importNode).toBeDefined();
  1933. expect(importNode?.name).toBe('java.util');
  1934. expect(importNode?.signature).toContain('.*');
  1935. });
  1936. it('should extract nested class import', () => {
  1937. const code = `import java.util.Map.Entry;`;
  1938. const result = extractFromSource('MapUtil.java', code);
  1939. const importNode = result.nodes.find((n) => n.kind === 'import');
  1940. expect(importNode).toBeDefined();
  1941. expect(importNode?.name).toBe('java.util.Map.Entry');
  1942. });
  1943. it('should extract multiple imports', () => {
  1944. const code = `
  1945. import java.util.List;
  1946. import java.util.Map;
  1947. import java.io.IOException;
  1948. `;
  1949. const result = extractFromSource('Service.java', code);
  1950. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1951. expect(importNodes.length).toBe(3);
  1952. const names = importNodes.map((n) => n.name);
  1953. expect(names).toContain('java.util.List');
  1954. expect(names).toContain('java.util.Map');
  1955. expect(names).toContain('java.io.IOException');
  1956. });
  1957. });
  1958. describe('C# imports', () => {
  1959. it('should extract simple using', () => {
  1960. const code = `using System;`;
  1961. const result = extractFromSource('Program.cs', code);
  1962. const importNode = result.nodes.find((n) => n.kind === 'import');
  1963. expect(importNode).toBeDefined();
  1964. expect(importNode?.name).toBe('System');
  1965. expect(importNode?.signature).toBe('using System;');
  1966. });
  1967. it('should extract qualified using', () => {
  1968. const code = `using System.Collections.Generic;`;
  1969. const result = extractFromSource('Utils.cs', code);
  1970. const importNode = result.nodes.find((n) => n.kind === 'import');
  1971. expect(importNode).toBeDefined();
  1972. expect(importNode?.name).toBe('System.Collections.Generic');
  1973. });
  1974. it('should extract static using', () => {
  1975. const code = `using static System.Console;`;
  1976. const result = extractFromSource('App.cs', code);
  1977. const importNode = result.nodes.find((n) => n.kind === 'import');
  1978. expect(importNode).toBeDefined();
  1979. expect(importNode?.name).toBe('System.Console');
  1980. expect(importNode?.signature).toContain('static');
  1981. });
  1982. it('should extract alias using', () => {
  1983. const code = `using MyList = System.Collections.Generic.List<int>;`;
  1984. const result = extractFromSource('Types.cs', code);
  1985. const importNode = result.nodes.find((n) => n.kind === 'import');
  1986. expect(importNode).toBeDefined();
  1987. expect(importNode?.name).toBe('System.Collections.Generic.List<int>');
  1988. expect(importNode?.signature).toContain('MyList =');
  1989. });
  1990. it('should extract multiple usings', () => {
  1991. const code = `
  1992. using System;
  1993. using System.Threading.Tasks;
  1994. using Microsoft.Extensions.DependencyInjection;
  1995. `;
  1996. const result = extractFromSource('Service.cs', code);
  1997. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1998. expect(importNodes.length).toBe(3);
  1999. const names = importNodes.map((n) => n.name);
  2000. expect(names).toContain('System');
  2001. expect(names).toContain('System.Threading.Tasks');
  2002. expect(names).toContain('Microsoft.Extensions.DependencyInjection');
  2003. });
  2004. });
  2005. describe('PHP imports', () => {
  2006. it('should extract simple use', () => {
  2007. const code = `<?php use PHPUnit\\Framework\\TestCase;`;
  2008. const result = extractFromSource('Test.php', code);
  2009. const importNode = result.nodes.find((n) => n.kind === 'import');
  2010. expect(importNode).toBeDefined();
  2011. expect(importNode?.name).toBe('PHPUnit\\Framework\\TestCase');
  2012. });
  2013. it('should extract aliased use', () => {
  2014. const code = `<?php use Mockery as m;`;
  2015. const result = extractFromSource('Test.php', code);
  2016. const importNode = result.nodes.find((n) => n.kind === 'import');
  2017. expect(importNode).toBeDefined();
  2018. expect(importNode?.name).toBe('Mockery');
  2019. expect(importNode?.signature).toContain('as m');
  2020. });
  2021. it('should extract function use', () => {
  2022. const code = `<?php use function Illuminate\\Support\\env;`;
  2023. const result = extractFromSource('helpers.php', code);
  2024. const importNode = result.nodes.find((n) => n.kind === 'import');
  2025. expect(importNode).toBeDefined();
  2026. expect(importNode?.name).toBe('Illuminate\\Support\\env');
  2027. expect(importNode?.signature).toContain('function');
  2028. });
  2029. it('should extract grouped use', () => {
  2030. const code = `<?php use Illuminate\\Database\\{Model, Builder};`;
  2031. const result = extractFromSource('Models.php', code);
  2032. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  2033. expect(importNodes.length).toBe(2);
  2034. const names = importNodes.map((n) => n.name);
  2035. expect(names).toContain('Illuminate\\Database\\Model');
  2036. expect(names).toContain('Illuminate\\Database\\Builder');
  2037. });
  2038. it('should extract multiple uses', () => {
  2039. const code = `<?php
  2040. use Illuminate\\Support\\Collection;
  2041. use Illuminate\\Support\\Str;
  2042. use Closure;
  2043. `;
  2044. const result = extractFromSource('Service.php', code);
  2045. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  2046. expect(importNodes.length).toBe(3);
  2047. const names = importNodes.map((n) => n.name);
  2048. expect(names).toContain('Illuminate\\Support\\Collection');
  2049. expect(names).toContain('Illuminate\\Support\\Str');
  2050. expect(names).toContain('Closure');
  2051. });
  2052. it('should extract include/require (+_once) static paths as imports (#660)', () => {
  2053. const code = `<?php
  2054. require_once("lib.php");
  2055. include 'other.php';
  2056. require 'r.php';
  2057. include_once("io.php");
  2058. `;
  2059. const result = extractFromSource('page.php', code);
  2060. const names = result.nodes.filter((n) => n.kind === 'import').map((n) => n.name);
  2061. expect(names).toContain('lib.php');
  2062. expect(names).toContain('other.php');
  2063. expect(names).toContain('r.php');
  2064. expect(names).toContain('io.php');
  2065. });
  2066. it('should skip dynamic include/require with no static path (#660)', () => {
  2067. const code = `<?php
  2068. require_once(__DIR__ . '/dyn.php');
  2069. include $file;
  2070. include "tpl/{$name}.php";
  2071. `;
  2072. const result = extractFromSource('page.php', code);
  2073. const imports = result.nodes.filter((n) => n.kind === 'import');
  2074. expect(imports).toHaveLength(0);
  2075. });
  2076. it('should extract include alongside namespace use without interference (#660)', () => {
  2077. const code = `<?php
  2078. use App\\Service\\Mailer;
  2079. require_once("bootstrap.php");
  2080. `;
  2081. const result = extractFromSource('page.php', code);
  2082. const names = result.nodes.filter((n) => n.kind === 'import').map((n) => n.name);
  2083. expect(names).toContain('App\\Service\\Mailer');
  2084. expect(names).toContain('bootstrap.php');
  2085. });
  2086. });
  2087. describe('Ruby imports', () => {
  2088. it('should extract require', () => {
  2089. const code = `require 'json'`;
  2090. const result = extractFromSource('app.rb', code);
  2091. const importNode = result.nodes.find((n) => n.kind === 'import');
  2092. expect(importNode).toBeDefined();
  2093. expect(importNode?.name).toBe('json');
  2094. expect(importNode?.signature).toBe("require 'json'");
  2095. });
  2096. it('should extract require with path', () => {
  2097. const code = `require 'active_support/core_ext/string'`;
  2098. const result = extractFromSource('config.rb', code);
  2099. const importNode = result.nodes.find((n) => n.kind === 'import');
  2100. expect(importNode).toBeDefined();
  2101. expect(importNode?.name).toBe('active_support/core_ext/string');
  2102. });
  2103. it('should extract require_relative', () => {
  2104. const code = `require_relative '../test_helper'`;
  2105. const result = extractFromSource('test/my_test.rb', code);
  2106. const importNode = result.nodes.find((n) => n.kind === 'import');
  2107. expect(importNode).toBeDefined();
  2108. expect(importNode?.name).toBe('../test_helper');
  2109. expect(importNode?.signature).toContain('require_relative');
  2110. });
  2111. it('should not extract non-require calls', () => {
  2112. const code = `puts 'hello'`;
  2113. const result = extractFromSource('app.rb', code);
  2114. const importNode = result.nodes.find((n) => n.kind === 'import');
  2115. expect(importNode).toBeUndefined();
  2116. });
  2117. it('should extract multiple requires', () => {
  2118. const code = `
  2119. require 'json'
  2120. require 'yaml'
  2121. require_relative 'helper'
  2122. `;
  2123. const result = extractFromSource('lib.rb', code);
  2124. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  2125. expect(importNodes.length).toBe(3);
  2126. const names = importNodes.map((n) => n.name);
  2127. expect(names).toContain('json');
  2128. expect(names).toContain('yaml');
  2129. expect(names).toContain('helper');
  2130. });
  2131. });
  2132. describe('Ruby modules', () => {
  2133. it('should extract module as module node with containment', () => {
  2134. const code = `
  2135. module CachedCounting
  2136. def self.disable
  2137. @enabled = false
  2138. end
  2139. def perform_increment!(key, count)
  2140. write_cache!(key, count)
  2141. end
  2142. end
  2143. `;
  2144. const result = extractFromSource('concerns/cached_counting.rb', code);
  2145. const moduleNode = result.nodes.find((n) => n.kind === 'module' && n.name === 'CachedCounting');
  2146. expect(moduleNode).toBeDefined();
  2147. expect(moduleNode?.qualifiedName).toBe('CachedCounting');
  2148. // Methods inside module should have module-qualified names
  2149. const disableMethod = result.nodes.find((n) => n.name === 'disable' && n.kind === 'method');
  2150. expect(disableMethod).toBeDefined();
  2151. expect(disableMethod?.qualifiedName).toBe('CachedCounting::disable');
  2152. const incrementMethod = result.nodes.find((n) => n.name === 'perform_increment!' && n.kind === 'method');
  2153. expect(incrementMethod).toBeDefined();
  2154. expect(incrementMethod?.qualifiedName).toBe('CachedCounting::perform_increment!');
  2155. // Containment edge from module to methods
  2156. const containsEdges = result.edges.filter((e) => e.source === moduleNode?.id && e.kind === 'contains');
  2157. expect(containsEdges.length).toBeGreaterThanOrEqual(2);
  2158. });
  2159. it('should handle nested modules with classes', () => {
  2160. const code = `
  2161. module Discourse
  2162. module Auth
  2163. class AuthProvider
  2164. def authenticate(params)
  2165. validate(params)
  2166. end
  2167. end
  2168. end
  2169. end
  2170. `;
  2171. const result = extractFromSource('lib/auth.rb', code);
  2172. const discourseModule = result.nodes.find((n) => n.kind === 'module' && n.name === 'Discourse');
  2173. expect(discourseModule).toBeDefined();
  2174. const authModule = result.nodes.find((n) => n.kind === 'module' && n.name === 'Auth');
  2175. expect(authModule).toBeDefined();
  2176. expect(authModule?.qualifiedName).toBe('Discourse::Auth');
  2177. const authProvider = result.nodes.find((n) => n.kind === 'class' && n.name === 'AuthProvider');
  2178. expect(authProvider).toBeDefined();
  2179. expect(authProvider?.qualifiedName).toBe('Discourse::Auth::AuthProvider');
  2180. const authMethod = result.nodes.find((n) => n.name === 'authenticate');
  2181. expect(authMethod).toBeDefined();
  2182. expect(authMethod?.qualifiedName).toBe('Discourse::Auth::AuthProvider::authenticate');
  2183. });
  2184. });
  2185. describe('PHP return type capture (#608)', () => {
  2186. it('captures self/static factory returns as the `self` marker; primitives as undefined', () => {
  2187. const code = `<?php
  2188. class ApiClient {
  2189. public static function for(string $c): self { return new self; }
  2190. public static function make(): static { return new static; }
  2191. public function send(array $p): array { return []; }
  2192. }`;
  2193. const result = extractFromSource('ApiClient.php', code);
  2194. expect(result.nodes.find((n) => n.name === 'for' && n.kind === 'method')?.returnType).toBe('self');
  2195. expect(result.nodes.find((n) => n.name === 'make' && n.kind === 'method')?.returnType).toBe('self');
  2196. // `array` is not a class to chain on → no return type recorded.
  2197. expect(result.nodes.find((n) => n.name === 'send' && n.kind === 'method')?.returnType).toBeUndefined();
  2198. });
  2199. it('captures a concrete return type as its short class name', () => {
  2200. const code = `<?php
  2201. namespace App;
  2202. class WidgetFactory { public static function make(): Widget { return new Widget(); } }`;
  2203. const result = extractFromSource('WidgetFactory.php', code);
  2204. expect(result.nodes.find((n) => n.name === 'make' && n.kind === 'method')?.returnType).toBe('Widget');
  2205. });
  2206. });
  2207. describe('C/C++ return type capture (#645)', () => {
  2208. it('captures the normalized return type of a C++ method/function', () => {
  2209. const code = `
  2210. struct Widget { void draw(); };
  2211. class Factory { public: static Widget create(); };
  2212. Widget Factory::create() { return Widget(); }
  2213. void doNothing() {}
  2214. `;
  2215. const result = extractFromSource('f.cpp', code);
  2216. const create = result.nodes.find(
  2217. (n) => n.name === 'create' && (n.kind === 'method' || n.kind === 'function')
  2218. );
  2219. expect(create?.returnType).toBe('Widget');
  2220. // A `void` return records no type, so resolution never tries to resolve a
  2221. // method on it.
  2222. const doNothing = result.nodes.find((n) => n.name === 'doNothing');
  2223. expect(doNothing).toBeDefined();
  2224. expect(doNothing?.returnType).toBeUndefined();
  2225. });
  2226. it('unwraps a smart-pointer return type to its pointee', () => {
  2227. const code = `
  2228. #include <memory>
  2229. struct Widget {};
  2230. std::unique_ptr<Widget> makeWidget() { return nullptr; }
  2231. `;
  2232. const result = extractFromSource('f.cpp', code);
  2233. const make = result.nodes.find((n) => n.name === 'makeWidget');
  2234. expect(make?.returnType).toBe('Widget');
  2235. });
  2236. });
  2237. describe('C++ macro-prefixed class/struct misparse (#946)', () => {
  2238. // An export/visibility macro before the class name plus a base clause
  2239. // (`class MACRO Name : public Base { … }`) makes tree-sitter read `class
  2240. // MACRO` as an elaborated type and the whole declaration as a
  2241. // function_definition named after the class, spanning the entire body — a
  2242. // phantom `function` that polluted callers/impact/blast-radius. It's dropped.
  2243. it('does not mint a phantom function for a macro-annotated class that inherits', () => {
  2244. const code = `#pragma once
  2245. #define MAPCORE_EXPORT __attribute__((visibility("default")))
  2246. class DataProvider {
  2247. public:
  2248. virtual bool Request(void* param) = 0;
  2249. };
  2250. class MAPCORE_EXPORT LocalDataProvider : public DataProvider
  2251. {
  2252. public:
  2253. LocalDataProvider(int dataType);
  2254. virtual bool Request(void* param) override;
  2255. };
  2256. `;
  2257. // A header rich in C++ (class / public: / virtual) detects as C++ — the
  2258. // issue's exact scenario (a `.h` file). Guard it so a detection regression
  2259. // can't make this test pass for the wrong reason.
  2260. expect(detectLanguage('provider.h', code)).toBe('cpp');
  2261. const result = extractFromSource('provider.h', code);
  2262. // The misparse used to surface as `function | LocalDataProvider` spanning
  2263. // the whole class body — a false caller in the graph. It's gone now.
  2264. expect(
  2265. result.nodes.find((n) => n.name === 'LocalDataProvider' && n.kind === 'function')
  2266. ).toBeUndefined();
  2267. // The sibling class without the macro is unaffected — still a class.
  2268. expect(result.nodes.find((n) => n.name === 'DataProvider')?.kind).toBe('class');
  2269. });
  2270. it('drops the struct variant too, without dropping a genuine class', () => {
  2271. const code = `
  2272. #define API __declspec(dllexport)
  2273. struct API Widget : public Base { int x; };
  2274. class Plain : public Base { public: int y; };
  2275. `;
  2276. const result = extractFromSource('widget.cpp', code);
  2277. // `struct MACRO Name : Base { … }` misparses the same way — no phantom function.
  2278. expect(
  2279. result.nodes.find((n) => n.name === 'Widget' && n.kind === 'function')
  2280. ).toBeUndefined();
  2281. // A normal class with a base clause and no macro must still be a class — the
  2282. // drop is precise, not a blanket "class with inheritance" filter.
  2283. expect(result.nodes.find((n) => n.name === 'Plain')?.kind).toBe('class');
  2284. });
  2285. });
  2286. describe('C/C++ imports', () => {
  2287. it('should extract system include', () => {
  2288. const code = `#include <iostream>`;
  2289. const result = extractFromSource('main.cpp', code);
  2290. const importNode = result.nodes.find((n) => n.kind === 'import');
  2291. expect(importNode).toBeDefined();
  2292. expect(importNode?.name).toBe('iostream');
  2293. expect(importNode?.signature).toBe('#include <iostream>');
  2294. });
  2295. it('should extract system include with path', () => {
  2296. const code = `#include <nlohmann/json.hpp>`;
  2297. const result = extractFromSource('app.cpp', code);
  2298. const importNode = result.nodes.find((n) => n.kind === 'import');
  2299. expect(importNode).toBeDefined();
  2300. expect(importNode?.name).toBe('nlohmann/json.hpp');
  2301. });
  2302. it('should extract local include', () => {
  2303. const code = `#include "myheader.h"`;
  2304. const result = extractFromSource('main.cpp', code);
  2305. const importNode = result.nodes.find((n) => n.kind === 'import');
  2306. expect(importNode).toBeDefined();
  2307. expect(importNode?.name).toBe('myheader.h');
  2308. });
  2309. it('should extract C header', () => {
  2310. const code = `#include <stdio.h>`;
  2311. const result = extractFromSource('main.c', code);
  2312. const importNode = result.nodes.find((n) => n.kind === 'import');
  2313. expect(importNode).toBeDefined();
  2314. expect(importNode?.name).toBe('stdio.h');
  2315. });
  2316. it('should extract multiple includes', () => {
  2317. const code = `
  2318. #include <iostream>
  2319. #include <vector>
  2320. #include "config.h"
  2321. `;
  2322. const result = extractFromSource('app.cpp', code);
  2323. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  2324. expect(importNodes.length).toBe(3);
  2325. const names = importNodes.map((n) => n.name);
  2326. expect(names).toContain('iostream');
  2327. expect(names).toContain('vector');
  2328. expect(names).toContain('config.h');
  2329. });
  2330. it('should create unresolved references for local includes', () => {
  2331. const code = `#include "myheader.h"`;
  2332. const result = extractFromSource('main.cpp', code);
  2333. const importRef = result.unresolvedReferences.find(
  2334. (r) => r.referenceKind === 'imports' && r.referenceName === 'myheader.h'
  2335. );
  2336. expect(importRef).toBeDefined();
  2337. expect(importRef?.line).toBe(1);
  2338. });
  2339. it('should create unresolved references for system includes', () => {
  2340. const code = `#include <iostream>`;
  2341. const result = extractFromSource('main.cpp', code);
  2342. const importRef = result.unresolvedReferences.find(
  2343. (r) => r.referenceKind === 'imports' && r.referenceName === 'iostream'
  2344. );
  2345. expect(importRef).toBeDefined();
  2346. });
  2347. });
  2348. describe('Dart imports', () => {
  2349. it('should extract dart: import', () => {
  2350. const code = `import 'dart:async';`;
  2351. const result = extractFromSource('main.dart', code);
  2352. const importNode = result.nodes.find((n) => n.kind === 'import');
  2353. expect(importNode).toBeDefined();
  2354. expect(importNode?.name).toBe('dart:async');
  2355. expect(importNode?.signature).toBe("import 'dart:async';");
  2356. });
  2357. it('should extract package import', () => {
  2358. const code = `import 'package:flutter/material.dart';`;
  2359. const result = extractFromSource('app.dart', code);
  2360. const importNode = result.nodes.find((n) => n.kind === 'import');
  2361. expect(importNode).toBeDefined();
  2362. expect(importNode?.name).toBe('package:flutter/material.dart');
  2363. });
  2364. it('should extract aliased import', () => {
  2365. const code = `import 'package:http/http.dart' as http;`;
  2366. const result = extractFromSource('api.dart', code);
  2367. const importNode = result.nodes.find((n) => n.kind === 'import');
  2368. expect(importNode).toBeDefined();
  2369. expect(importNode?.name).toBe('package:http/http.dart');
  2370. expect(importNode?.signature).toContain('as http');
  2371. });
  2372. it('should extract multiple imports', () => {
  2373. const code = `
  2374. import 'dart:async';
  2375. import 'dart:convert';
  2376. import 'package:flutter/material.dart';
  2377. `;
  2378. const result = extractFromSource('main.dart', code);
  2379. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  2380. expect(importNodes.length).toBe(3);
  2381. const names = importNodes.map((n) => n.name);
  2382. expect(names).toContain('dart:async');
  2383. expect(names).toContain('dart:convert');
  2384. expect(names).toContain('package:flutter/material.dart');
  2385. });
  2386. it('should extract relative import', () => {
  2387. const code = `import '../utils/helpers.dart';`;
  2388. const result = extractFromSource('lib/main.dart', code);
  2389. const importNode = result.nodes.find((n) => n.kind === 'import');
  2390. expect(importNode).toBeDefined();
  2391. expect(importNode?.name).toBe('../utils/helpers.dart');
  2392. });
  2393. });
  2394. describe('Liquid imports', () => {
  2395. it('should extract render tag', () => {
  2396. const code = `{% render 'loading-spinner' %}`;
  2397. const result = extractFromSource('template.liquid', code);
  2398. const importNode = result.nodes.find((n) => n.kind === 'import');
  2399. expect(importNode).toBeDefined();
  2400. expect(importNode?.name).toBe('loading-spinner');
  2401. expect(importNode?.signature).toContain('render');
  2402. });
  2403. it('should extract section tag', () => {
  2404. const code = `{% section 'header' %}`;
  2405. const result = extractFromSource('layout/theme.liquid', code);
  2406. const importNode = result.nodes.find((n) => n.kind === 'import');
  2407. expect(importNode).toBeDefined();
  2408. expect(importNode?.name).toBe('header');
  2409. expect(importNode?.signature).toContain('section');
  2410. });
  2411. it('should extract include tag', () => {
  2412. const code = `{% include 'icon-cart' %}`;
  2413. const result = extractFromSource('snippets/header.liquid', code);
  2414. const importNode = result.nodes.find((n) => n.kind === 'import');
  2415. expect(importNode).toBeDefined();
  2416. expect(importNode?.name).toBe('icon-cart');
  2417. expect(importNode?.signature).toContain('include');
  2418. });
  2419. it('should extract render with whitespace control', () => {
  2420. const code = `{%- render 'price' -%}`;
  2421. const result = extractFromSource('snippets/product.liquid', code);
  2422. const importNode = result.nodes.find((n) => n.kind === 'import');
  2423. expect(importNode).toBeDefined();
  2424. expect(importNode?.name).toBe('price');
  2425. });
  2426. it('should extract multiple imports', () => {
  2427. const code = `
  2428. {% section 'header' %}
  2429. {% render 'loading-spinner' %}
  2430. {% render 'cart-drawer' %}
  2431. `;
  2432. const result = extractFromSource('layout/theme.liquid', code);
  2433. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  2434. expect(importNodes.length).toBe(3);
  2435. const names = importNodes.map((n) => n.name);
  2436. expect(names).toContain('header');
  2437. expect(names).toContain('loading-spinner');
  2438. expect(names).toContain('cart-drawer');
  2439. });
  2440. });
  2441. });
  2442. // =============================================================================
  2443. // Pascal / Delphi Extraction
  2444. // =============================================================================
  2445. describe('Pascal / Delphi Extraction', () => {
  2446. describe('Language detection', () => {
  2447. it('should detect Pascal files', () => {
  2448. expect(detectLanguage('UAuth.pas')).toBe('pascal');
  2449. expect(detectLanguage('App.dpr')).toBe('pascal');
  2450. expect(detectLanguage('Package.dpk')).toBe('pascal');
  2451. expect(detectLanguage('App.lpr')).toBe('pascal');
  2452. expect(detectLanguage('MainForm.dfm')).toBe('pascal');
  2453. expect(detectLanguage('MainForm.fmx')).toBe('pascal');
  2454. });
  2455. it('should report Pascal as supported', () => {
  2456. expect(isLanguageSupported('pascal')).toBe(true);
  2457. expect(getSupportedLanguages()).toContain('pascal');
  2458. });
  2459. });
  2460. describe('Unit extraction', () => {
  2461. it('should extract unit as module', () => {
  2462. const code = `unit MyUnit;\ninterface\nimplementation\nend.`;
  2463. const result = extractFromSource('MyUnit.pas', code);
  2464. const moduleNode = result.nodes.find((n) => n.kind === 'module');
  2465. expect(moduleNode).toBeDefined();
  2466. expect(moduleNode?.name).toBe('MyUnit');
  2467. expect(moduleNode?.language).toBe('pascal');
  2468. });
  2469. it('should extract program as module', () => {
  2470. const code = `program MyApp;\nbegin\nend.`;
  2471. const result = extractFromSource('MyApp.dpr', code);
  2472. const moduleNode = result.nodes.find((n) => n.kind === 'module');
  2473. expect(moduleNode).toBeDefined();
  2474. expect(moduleNode?.name).toBe('MyApp');
  2475. });
  2476. it('should fallback to filename when module name is empty', () => {
  2477. // Some .dpr templates use "program;" without a name
  2478. const code = `program;\nuses SysUtils;\nbegin\nend.`;
  2479. const result = extractFromSource('Console.dpr', code);
  2480. const moduleNode = result.nodes.find((n) => n.kind === 'module');
  2481. expect(moduleNode).toBeDefined();
  2482. expect(moduleNode?.name).toBe('Console');
  2483. });
  2484. });
  2485. describe('Uses clause (imports)', () => {
  2486. it('should extract uses as individual imports', () => {
  2487. const code = `unit Test;\ninterface\nuses\n System.SysUtils,\n System.Classes;\nimplementation\nend.`;
  2488. const result = extractFromSource('Test.pas', code);
  2489. const imports = result.nodes.filter((n) => n.kind === 'import');
  2490. expect(imports.length).toBe(2);
  2491. expect(imports.map((n) => n.name)).toContain('System.SysUtils');
  2492. expect(imports.map((n) => n.name)).toContain('System.Classes');
  2493. });
  2494. it('should create unresolved references for imports', () => {
  2495. const code = `unit Test;\ninterface\nuses\n UAuth;\nimplementation\nend.`;
  2496. const result = extractFromSource('Test.pas', code);
  2497. const importRef = result.unresolvedReferences.find(
  2498. (r) => r.referenceKind === 'imports'
  2499. );
  2500. expect(importRef).toBeDefined();
  2501. expect(importRef?.referenceName).toBe('UAuth');
  2502. });
  2503. });
  2504. describe('Class extraction', () => {
  2505. it('should extract class declarations', () => {
  2506. const code = `unit Test;\ninterface\ntype\n TMyClass = class\n public\n procedure DoSomething;\n end;\nimplementation\nend.`;
  2507. const result = extractFromSource('Test.pas', code);
  2508. const classNode = result.nodes.find((n) => n.kind === 'class');
  2509. expect(classNode).toBeDefined();
  2510. expect(classNode?.name).toBe('TMyClass');
  2511. });
  2512. it('should extract class with inheritance', () => {
  2513. const code = `unit Test;\ninterface\ntype\n TChild = class(TParent)\n end;\nimplementation\nend.`;
  2514. const result = extractFromSource('Test.pas', code);
  2515. const extendsRef = result.unresolvedReferences.find(
  2516. (r) => r.referenceKind === 'extends'
  2517. );
  2518. expect(extendsRef).toBeDefined();
  2519. expect(extendsRef?.referenceName).toBe('TParent');
  2520. });
  2521. it('should extract class with interface implementation', () => {
  2522. const code = `unit Test;\ninterface\ntype\n TService = class(TInterfacedObject, ILogger)\n end;\nimplementation\nend.`;
  2523. const result = extractFromSource('Test.pas', code);
  2524. const extendsRef = result.unresolvedReferences.find(
  2525. (r) => r.referenceKind === 'extends'
  2526. );
  2527. const implementsRef = result.unresolvedReferences.find(
  2528. (r) => r.referenceKind === 'implements'
  2529. );
  2530. expect(extendsRef?.referenceName).toBe('TInterfacedObject');
  2531. expect(implementsRef?.referenceName).toBe('ILogger');
  2532. });
  2533. });
  2534. describe('Record extraction', () => {
  2535. it('should extract records as class nodes', () => {
  2536. const code = `unit Test;\ninterface\ntype\n TPoint = record\n X: Double;\n Y: Double;\n end;\nimplementation\nend.`;
  2537. const result = extractFromSource('Test.pas', code);
  2538. const classNode = result.nodes.find((n) => n.kind === 'class');
  2539. expect(classNode).toBeDefined();
  2540. expect(classNode?.name).toBe('TPoint');
  2541. const fields = result.nodes.filter((n) => n.kind === 'field');
  2542. expect(fields.length).toBe(2);
  2543. expect(fields.map((f) => f.name)).toContain('X');
  2544. expect(fields.map((f) => f.name)).toContain('Y');
  2545. });
  2546. });
  2547. describe('Interface extraction', () => {
  2548. it('should extract interface declarations', () => {
  2549. const code = `unit Test;\ninterface\ntype\n ILogger = interface\n procedure Log(const AMsg: string);\n end;\nimplementation\nend.`;
  2550. const result = extractFromSource('Test.pas', code);
  2551. const ifaceNode = result.nodes.find((n) => n.kind === 'interface');
  2552. expect(ifaceNode).toBeDefined();
  2553. expect(ifaceNode?.name).toBe('ILogger');
  2554. });
  2555. });
  2556. describe('Method extraction', () => {
  2557. it('should extract methods with visibility', () => {
  2558. 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.`;
  2559. const result = extractFromSource('Test.pas', code);
  2560. const methods = result.nodes.filter((n) => n.kind === 'method');
  2561. expect(methods.length).toBe(2);
  2562. const createMethod = methods.find((m) => m.name === 'Create');
  2563. expect(createMethod?.visibility).toBe('public');
  2564. const getValue = methods.find((m) => m.name === 'GetValue');
  2565. expect(getValue?.visibility).toBe('public');
  2566. const fields = result.nodes.filter((n) => n.kind === 'field');
  2567. const fValue = fields.find((f) => f.name === 'FValue');
  2568. expect(fValue?.visibility).toBe('private');
  2569. });
  2570. it('should detect static methods (class methods)', () => {
  2571. const code = `unit Test;\ninterface\ntype\n THelper = class\n public\n class function Create: THelper; static;\n end;\nimplementation\nend.`;
  2572. const result = extractFromSource('Test.pas', code);
  2573. const methods = result.nodes.filter((n) => n.kind === 'method');
  2574. const staticMethod = methods.find((m) => m.name === 'Create');
  2575. expect(staticMethod?.isStatic).toBe(true);
  2576. });
  2577. });
  2578. describe('Enum extraction', () => {
  2579. it('should extract enums with members', () => {
  2580. const code = `unit Test;\ninterface\ntype\n TColor = (clRed, clGreen, clBlue);\nimplementation\nend.`;
  2581. const result = extractFromSource('Test.pas', code);
  2582. const enumNode = result.nodes.find((n) => n.kind === 'enum');
  2583. expect(enumNode).toBeDefined();
  2584. expect(enumNode?.name).toBe('TColor');
  2585. const members = result.nodes.filter((n) => n.kind === 'enum_member');
  2586. expect(members.length).toBe(3);
  2587. expect(members.map((m) => m.name)).toEqual(['clRed', 'clGreen', 'clBlue']);
  2588. });
  2589. });
  2590. describe('Property extraction', () => {
  2591. it('should extract properties', () => {
  2592. const code = `unit Test;\ninterface\ntype\n TObj = class\n public\n property Name: string read FName write FName;\n end;\nimplementation\nend.`;
  2593. const result = extractFromSource('Test.pas', code);
  2594. const propNode = result.nodes.find((n) => n.kind === 'property');
  2595. expect(propNode).toBeDefined();
  2596. expect(propNode?.name).toBe('Name');
  2597. expect(propNode?.visibility).toBe('public');
  2598. });
  2599. });
  2600. describe('Constant extraction', () => {
  2601. it('should extract constants', () => {
  2602. const code = `unit Test;\ninterface\nconst\n MAX_RETRIES = 3;\n APP_NAME = 'MyApp';\nimplementation\nend.`;
  2603. const result = extractFromSource('Test.pas', code);
  2604. const constants = result.nodes.filter((n) => n.kind === 'constant');
  2605. expect(constants.length).toBe(2);
  2606. expect(constants.map((c) => c.name)).toContain('MAX_RETRIES');
  2607. expect(constants.map((c) => c.name)).toContain('APP_NAME');
  2608. });
  2609. });
  2610. describe('Type alias extraction', () => {
  2611. it('should extract type aliases', () => {
  2612. const code = `unit Test;\ninterface\ntype\n TUserName = string;\nimplementation\nend.`;
  2613. const result = extractFromSource('Test.pas', code);
  2614. const aliasNode = result.nodes.find((n) => n.kind === 'type_alias');
  2615. expect(aliasNode).toBeDefined();
  2616. expect(aliasNode?.name).toBe('TUserName');
  2617. });
  2618. });
  2619. describe('Call extraction', () => {
  2620. it('should extract calls from implementation bodies', () => {
  2621. 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.`;
  2622. const result = extractFromSource('Test.pas', code);
  2623. const callRef = result.unresolvedReferences.find(
  2624. (r) => r.referenceKind === 'calls'
  2625. );
  2626. expect(callRef).toBeDefined();
  2627. expect(callRef?.referenceName).toBe('WriteLn');
  2628. });
  2629. });
  2630. describe('Containment edges', () => {
  2631. it('should create contains edges for class members', () => {
  2632. const code = `unit Test;\ninterface\ntype\n TObj = class\n public\n procedure Foo;\n end;\nimplementation\nend.`;
  2633. const result = extractFromSource('Test.pas', code);
  2634. const classNode = result.nodes.find((n) => n.kind === 'class');
  2635. const methodNode = result.nodes.find((n) => n.kind === 'method');
  2636. expect(classNode).toBeDefined();
  2637. expect(methodNode).toBeDefined();
  2638. const containsEdge = result.edges.find(
  2639. (e) => e.source === classNode?.id && e.target === methodNode?.id && e.kind === 'contains'
  2640. );
  2641. expect(containsEdge).toBeDefined();
  2642. });
  2643. });
  2644. describe('Full fixture: UAuth.pas', () => {
  2645. const code = `unit UAuth;
  2646. interface
  2647. uses
  2648. System.SysUtils,
  2649. System.Classes;
  2650. type
  2651. ITokenValidator = interface
  2652. ['{11111111-1111-1111-1111-111111111111}']
  2653. function Validate(const AToken: string): Boolean;
  2654. end;
  2655. TAuthService = class(TInterfacedObject, ITokenValidator)
  2656. private
  2657. FToken: string;
  2658. FLoginCount: Integer;
  2659. procedure IncLoginCount;
  2660. protected
  2661. function GetToken: string;
  2662. public
  2663. constructor Create;
  2664. destructor Destroy; override;
  2665. function Validate(const AToken: string): Boolean;
  2666. function Login(const AUser, APass: string): string;
  2667. property Token: string read GetToken;
  2668. property LoginCount: Integer read FLoginCount;
  2669. end;
  2670. implementation
  2671. constructor TAuthService.Create;
  2672. begin
  2673. inherited Create;
  2674. FToken := '';
  2675. FLoginCount := 0;
  2676. end;
  2677. destructor TAuthService.Destroy;
  2678. begin
  2679. FToken := '';
  2680. inherited Destroy;
  2681. end;
  2682. procedure TAuthService.IncLoginCount;
  2683. begin
  2684. Inc(FLoginCount);
  2685. end;
  2686. function TAuthService.GetToken: string;
  2687. begin
  2688. Result := FToken;
  2689. end;
  2690. function TAuthService.Validate(const AToken: string): Boolean;
  2691. begin
  2692. Result := AToken <> '';
  2693. end;
  2694. function TAuthService.Login(const AUser, APass: string): string;
  2695. begin
  2696. IncLoginCount;
  2697. if Validate(AUser + ':' + APass) then
  2698. begin
  2699. FToken := AUser;
  2700. Result := 'ok';
  2701. end
  2702. else
  2703. Result := '';
  2704. end;
  2705. end.`;
  2706. it('should extract all expected nodes', () => {
  2707. const result = extractFromSource('UAuth.pas', code);
  2708. expect(result.errors).toHaveLength(0);
  2709. // Module
  2710. const moduleNode = result.nodes.find((n) => n.kind === 'module');
  2711. expect(moduleNode?.name).toBe('UAuth');
  2712. // Imports
  2713. const imports = result.nodes.filter((n) => n.kind === 'import');
  2714. expect(imports.length).toBe(2);
  2715. // Interface
  2716. const ifaceNode = result.nodes.find((n) => n.kind === 'interface');
  2717. expect(ifaceNode?.name).toBe('ITokenValidator');
  2718. // Class
  2719. const classNode = result.nodes.find((n) => n.kind === 'class');
  2720. expect(classNode?.name).toBe('TAuthService');
  2721. // Methods
  2722. const methods = result.nodes.filter((n) => n.kind === 'method');
  2723. expect(methods.length).toBeGreaterThanOrEqual(6);
  2724. expect(methods.map((m) => m.name)).toContain('Create');
  2725. expect(methods.map((m) => m.name)).toContain('Destroy');
  2726. expect(methods.map((m) => m.name)).toContain('Login');
  2727. // Fields
  2728. const fields = result.nodes.filter((n) => n.kind === 'field');
  2729. expect(fields.length).toBe(2);
  2730. expect(fields.every((f) => f.visibility === 'private')).toBe(true);
  2731. // Properties
  2732. const props = result.nodes.filter((n) => n.kind === 'property');
  2733. expect(props.length).toBe(2);
  2734. expect(props.map((p) => p.name)).toContain('Token');
  2735. expect(props.map((p) => p.name)).toContain('LoginCount');
  2736. });
  2737. it('should extract inheritance and interface implementation', () => {
  2738. const result = extractFromSource('UAuth.pas', code);
  2739. const extendsRef = result.unresolvedReferences.find(
  2740. (r) => r.referenceKind === 'extends'
  2741. );
  2742. expect(extendsRef?.referenceName).toBe('TInterfacedObject');
  2743. const implementsRef = result.unresolvedReferences.find(
  2744. (r) => r.referenceKind === 'implements'
  2745. );
  2746. expect(implementsRef?.referenceName).toBe('ITokenValidator');
  2747. });
  2748. it('should extract calls from implementation', () => {
  2749. const result = extractFromSource('UAuth.pas', code);
  2750. const callRefs = result.unresolvedReferences.filter(
  2751. (r) => r.referenceKind === 'calls'
  2752. );
  2753. expect(callRefs.map((r) => r.referenceName)).toContain('Inc');
  2754. expect(callRefs.map((r) => r.referenceName)).toContain('Validate');
  2755. });
  2756. });
  2757. describe('Full fixture: UTypes.pas', () => {
  2758. const code = `unit UTypes;
  2759. interface
  2760. uses
  2761. System.SysUtils;
  2762. const
  2763. C_MAX_RETRIES = 3;
  2764. C_DEFAULT_NAME = 'Guest';
  2765. type
  2766. TUserRole = (urAdmin, urEditor, urViewer);
  2767. TPoint2D = record
  2768. X: Double;
  2769. Y: Double;
  2770. end;
  2771. TUserName = string;
  2772. TUserInfo = class
  2773. public
  2774. type
  2775. TAddress = record
  2776. Street: string;
  2777. City: string;
  2778. Zip: string;
  2779. end;
  2780. private
  2781. FName: TUserName;
  2782. FRole: TUserRole;
  2783. FAddress: TAddress;
  2784. public
  2785. constructor Create(const AName: TUserName; ARole: TUserRole);
  2786. function GetDisplayName: string;
  2787. class function CreateAdmin(const AName: TUserName): TUserInfo; static;
  2788. property Name: TUserName read FName write FName;
  2789. property Role: TUserRole read FRole;
  2790. property Address: TAddress read FAddress write FAddress;
  2791. end;
  2792. implementation
  2793. constructor TUserInfo.Create(const AName: TUserName; ARole: TUserRole);
  2794. begin
  2795. FName := AName;
  2796. FRole := ARole;
  2797. end;
  2798. function TUserInfo.GetDisplayName: string;
  2799. begin
  2800. if FRole = urAdmin then
  2801. Result := '[Admin] ' + FName
  2802. else
  2803. Result := FName;
  2804. end;
  2805. class function TUserInfo.CreateAdmin(const AName: TUserName): TUserInfo;
  2806. begin
  2807. Result := TUserInfo.Create(AName, urAdmin);
  2808. end;
  2809. end.`;
  2810. it('should extract enums with members', () => {
  2811. const result = extractFromSource('UTypes.pas', code);
  2812. const enumNode = result.nodes.find((n) => n.kind === 'enum');
  2813. expect(enumNode?.name).toBe('TUserRole');
  2814. const members = result.nodes.filter((n) => n.kind === 'enum_member');
  2815. expect(members.length).toBe(3);
  2816. expect(members.map((m) => m.name)).toEqual(['urAdmin', 'urEditor', 'urViewer']);
  2817. });
  2818. it('should extract constants', () => {
  2819. const result = extractFromSource('UTypes.pas', code);
  2820. const constants = result.nodes.filter((n) => n.kind === 'constant');
  2821. expect(constants.length).toBe(2);
  2822. expect(constants.map((c) => c.name)).toContain('C_MAX_RETRIES');
  2823. expect(constants.map((c) => c.name)).toContain('C_DEFAULT_NAME');
  2824. });
  2825. it('should extract type aliases', () => {
  2826. const result = extractFromSource('UTypes.pas', code);
  2827. const aliases = result.nodes.filter((n) => n.kind === 'type_alias');
  2828. expect(aliases.map((a) => a.name)).toContain('TUserName');
  2829. });
  2830. it('should extract records as classes with fields', () => {
  2831. const result = extractFromSource('UTypes.pas', code);
  2832. const classes = result.nodes.filter((n) => n.kind === 'class');
  2833. expect(classes.map((c) => c.name)).toContain('TPoint2D');
  2834. // TPoint2D fields
  2835. const fields = result.nodes.filter((n) => n.kind === 'field');
  2836. expect(fields.map((f) => f.name)).toContain('X');
  2837. expect(fields.map((f) => f.name)).toContain('Y');
  2838. });
  2839. it('should extract static class methods', () => {
  2840. const result = extractFromSource('UTypes.pas', code);
  2841. const methods = result.nodes.filter((n) => n.kind === 'method');
  2842. const staticMethod = methods.find((m) => m.name === 'CreateAdmin');
  2843. expect(staticMethod).toBeDefined();
  2844. expect(staticMethod?.isStatic).toBe(true);
  2845. });
  2846. it('should extract nested types', () => {
  2847. const result = extractFromSource('UTypes.pas', code);
  2848. const classes = result.nodes.filter((n) => n.kind === 'class');
  2849. expect(classes.map((c) => c.name)).toContain('TAddress');
  2850. });
  2851. });
  2852. });
  2853. // =============================================================================
  2854. // DFM/FMX Extraction
  2855. // =============================================================================
  2856. describe('DFM/FMX Extraction', () => {
  2857. it('should extract components from DFM', () => {
  2858. const code = `object Form1: TForm1
  2859. Left = 0
  2860. Top = 0
  2861. Caption = 'My Form'
  2862. object Button1: TButton
  2863. Left = 10
  2864. Top = 10
  2865. Caption = 'Click Me'
  2866. end
  2867. end`;
  2868. const result = extractFromSource('Form1.dfm', code);
  2869. const components = result.nodes.filter((n) => n.kind === 'component');
  2870. expect(components.length).toBe(2);
  2871. expect(components.map((c) => c.name)).toContain('Form1');
  2872. expect(components.map((c) => c.name)).toContain('Button1');
  2873. const button = components.find((c) => c.name === 'Button1');
  2874. expect(button?.signature).toBe('TButton');
  2875. });
  2876. it('should extract nested component hierarchy', () => {
  2877. const code = `object Form1: TForm1
  2878. object Panel1: TPanel
  2879. object Label1: TLabel
  2880. Caption = 'Hello'
  2881. end
  2882. end
  2883. end`;
  2884. const result = extractFromSource('Form1.dfm', code);
  2885. const components = result.nodes.filter((n) => n.kind === 'component');
  2886. expect(components.length).toBe(3);
  2887. // Check nesting: Panel1 contains Label1
  2888. const panel = components.find((c) => c.name === 'Panel1');
  2889. const label = components.find((c) => c.name === 'Label1');
  2890. const containsEdge = result.edges.find(
  2891. (e) => e.source === panel?.id && e.target === label?.id && e.kind === 'contains'
  2892. );
  2893. expect(containsEdge).toBeDefined();
  2894. });
  2895. it('should extract event handler references', () => {
  2896. const code = `object Form1: TForm1
  2897. OnCreate = FormCreate
  2898. OnDestroy = FormDestroy
  2899. object Button1: TButton
  2900. OnClick = Button1Click
  2901. end
  2902. end`;
  2903. const result = extractFromSource('Form1.dfm', code);
  2904. const refs = result.unresolvedReferences;
  2905. expect(refs.length).toBe(3);
  2906. expect(refs.map((r) => r.referenceName)).toContain('FormCreate');
  2907. expect(refs.map((r) => r.referenceName)).toContain('FormDestroy');
  2908. expect(refs.map((r) => r.referenceName)).toContain('Button1Click');
  2909. expect(refs.every((r) => r.referenceKind === 'references')).toBe(true);
  2910. });
  2911. it('should handle multi-line properties', () => {
  2912. const code = `object Form1: TForm1
  2913. SQL.Strings = (
  2914. 'SELECT * FROM users'
  2915. 'WHERE active = 1')
  2916. object Button1: TButton
  2917. OnClick = Button1Click
  2918. end
  2919. end`;
  2920. const result = extractFromSource('Form1.dfm', code);
  2921. const components = result.nodes.filter((n) => n.kind === 'component');
  2922. expect(components.length).toBe(2);
  2923. const refs = result.unresolvedReferences;
  2924. expect(refs.length).toBe(1);
  2925. expect(refs[0]?.referenceName).toBe('Button1Click');
  2926. });
  2927. it('should handle inherited keyword', () => {
  2928. const code = `inherited Form1: TForm1
  2929. Caption = 'Inherited Form'
  2930. object Button1: TButton
  2931. OnClick = Button1Click
  2932. end
  2933. end`;
  2934. const result = extractFromSource('Form1.dfm', code);
  2935. const components = result.nodes.filter((n) => n.kind === 'component');
  2936. expect(components.length).toBe(2);
  2937. expect(components.map((c) => c.name)).toContain('Form1');
  2938. });
  2939. it('should handle item collection properties', () => {
  2940. const code = `object Form1: TForm1
  2941. object StatusBar1: TStatusBar
  2942. Panels = <
  2943. item
  2944. Width = 200
  2945. end
  2946. item
  2947. Width = 200
  2948. end>
  2949. end
  2950. end`;
  2951. const result = extractFromSource('Form1.dfm', code);
  2952. const components = result.nodes.filter((n) => n.kind === 'component');
  2953. expect(components.length).toBe(2);
  2954. });
  2955. describe('Full fixture: MainForm.dfm', () => {
  2956. const code = `object frmMain: TfrmMain
  2957. Left = 0
  2958. Top = 0
  2959. Caption = 'CodeGraph DFM Fixture'
  2960. ClientHeight = 480
  2961. ClientWidth = 640
  2962. OnCreate = FormCreate
  2963. OnDestroy = FormDestroy
  2964. object pnlTop: TPanel
  2965. Left = 0
  2966. Top = 0
  2967. Width = 640
  2968. Height = 50
  2969. object lblTitle: TLabel
  2970. Left = 16
  2971. Top = 16
  2972. Caption = 'Authentication Service'
  2973. end
  2974. object btnLogin: TButton
  2975. Left = 540
  2976. Top = 12
  2977. OnClick = btnLoginClick
  2978. end
  2979. end
  2980. object pnlContent: TPanel
  2981. Left = 0
  2982. Top = 50
  2983. object edtUsername: TEdit
  2984. Left = 16
  2985. Top = 16
  2986. OnChange = edtUsernameChange
  2987. end
  2988. object edtPassword: TEdit
  2989. Left = 16
  2990. Top = 48
  2991. OnKeyPress = edtPasswordKeyPress
  2992. end
  2993. object mmoLog: TMemo
  2994. Left = 16
  2995. Top = 88
  2996. end
  2997. end
  2998. object pnlStatus: TStatusBar
  2999. Left = 0
  3000. Top = 440
  3001. Panels = <
  3002. item
  3003. Width = 200
  3004. end
  3005. item
  3006. Width = 200
  3007. end>
  3008. end
  3009. end`;
  3010. it('should extract all components', () => {
  3011. const result = extractFromSource('MainForm.dfm', code);
  3012. const components = result.nodes.filter((n) => n.kind === 'component');
  3013. expect(components.length).toBe(9);
  3014. expect(components.map((c) => c.name)).toEqual(
  3015. expect.arrayContaining([
  3016. 'frmMain', 'pnlTop', 'lblTitle', 'btnLogin',
  3017. 'pnlContent', 'edtUsername', 'edtPassword', 'mmoLog', 'pnlStatus',
  3018. ])
  3019. );
  3020. });
  3021. it('should extract all event handlers', () => {
  3022. const result = extractFromSource('MainForm.dfm', code);
  3023. const refs = result.unresolvedReferences;
  3024. expect(refs.length).toBe(5);
  3025. expect(refs.map((r) => r.referenceName)).toEqual(
  3026. expect.arrayContaining([
  3027. 'FormCreate', 'FormDestroy', 'btnLoginClick',
  3028. 'edtUsernameChange', 'edtPasswordKeyPress',
  3029. ])
  3030. );
  3031. });
  3032. });
  3033. });
  3034. describe('Kotlin Multiplatform expect/actual', () => {
  3035. let tempDir: string;
  3036. let cg: CodeGraph;
  3037. beforeEach(() => {
  3038. tempDir = createTempDir();
  3039. });
  3040. afterEach(() => {
  3041. if (cg) cg.close();
  3042. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  3043. });
  3044. it('links expect declarations to platform actual implementations and surfaces them in impact', async () => {
  3045. const common = path.join(tempDir, 'src', 'commonMain');
  3046. const jvm = path.join(tempDir, 'src', 'jvmMain');
  3047. fs.mkdirSync(common, { recursive: true });
  3048. fs.mkdirSync(jvm, { recursive: true });
  3049. // common source set: expect declarations + a caller that uses them
  3050. fs.writeFileSync(
  3051. path.join(common, 'SystemProps.kt'),
  3052. `package demo.internal
  3053. expect fun systemProp(name: String): String?
  3054. expect class Platform {
  3055. fun describe(): String
  3056. }
  3057. `
  3058. );
  3059. fs.writeFileSync(
  3060. path.join(common, 'Caller.kt'),
  3061. `package demo
  3062. import demo.internal.systemProp
  3063. import demo.internal.Platform
  3064. fun useIt(): String {
  3065. val v = systemProp("os.name")
  3066. return Platform().describe() + v
  3067. }
  3068. `
  3069. );
  3070. // jvm source set: actual implementations
  3071. fs.writeFileSync(
  3072. path.join(jvm, 'SystemProps.kt'),
  3073. `package demo.internal
  3074. actual fun systemProp(name: String): String? = System.getProperty(name)
  3075. actual class Platform {
  3076. actual fun describe(): String = "JVM"
  3077. }
  3078. `
  3079. );
  3080. cg = CodeGraph.initSync(tempDir);
  3081. await cg.indexAll();
  3082. cg.resolveReferences();
  3083. // The expect/actual markers are captured onto the node's decorators.
  3084. const fns = cg.getNodesByKind('function');
  3085. const actualFn = fns.find(
  3086. (n) => n.name === 'systemProp' && n.decorators?.includes('actual')
  3087. );
  3088. const expectFn = fns.find(
  3089. (n) => n.name === 'systemProp' && n.decorators?.includes('expect')
  3090. );
  3091. expect(actualFn).toBeDefined();
  3092. expect(expectFn).toBeDefined();
  3093. expect(actualFn!.filePath).not.toBe(expectFn!.filePath);
  3094. // Editing the JVM actual must surface the common expect AND its caller —
  3095. // before the expect/actual bridge the actual had zero dependents.
  3096. const impact = cg.getImpactRadius(actualFn!.id, 3);
  3097. const impacted = [...impact.nodes.values()].map((n) => n.name);
  3098. expect(impacted).toContain('systemProp'); // the common expect
  3099. expect(impacted).toContain('useIt'); // the caller, reached transitively
  3100. // The bridging edge is a heuristic `calls` edge tagged by the synthesizer.
  3101. const bridge = impact.edges.find(
  3102. (e) =>
  3103. e.target === actualFn!.id &&
  3104. e.provenance === 'heuristic' &&
  3105. (e.metadata as { synthesizedBy?: string } | undefined)?.synthesizedBy ===
  3106. 'kotlin-expect-actual'
  3107. );
  3108. expect(bridge).toBeDefined();
  3109. expect(bridge!.source).toBe(expectFn!.id);
  3110. });
  3111. it('links an expect class to an actual typealias (different node kinds)', async () => {
  3112. const common = path.join(tempDir, 'src', 'commonMain');
  3113. const jvm = path.join(tempDir, 'src', 'jvmMain');
  3114. fs.mkdirSync(common, { recursive: true });
  3115. fs.mkdirSync(jvm, { recursive: true });
  3116. fs.writeFileSync(
  3117. path.join(common, 'Lock.kt'),
  3118. `package demo
  3119. expect class Lock {
  3120. fun acquire()
  3121. }
  3122. `
  3123. );
  3124. fs.writeFileSync(
  3125. path.join(jvm, 'Lock.kt'),
  3126. `package demo
  3127. actual typealias Lock = java.util.concurrent.locks.ReentrantLock
  3128. `
  3129. );
  3130. cg = CodeGraph.initSync(tempDir);
  3131. await cg.indexAll();
  3132. cg.resolveReferences();
  3133. const aliasNode = cg
  3134. .getNodesByKind('type_alias')
  3135. .find((n) => n.name === 'Lock' && n.decorators?.includes('actual'));
  3136. expect(aliasNode).toBeDefined();
  3137. // The actual typealias is now a cross-file dependency target (linked from
  3138. // the expect class), so it participates in impact rather than being orphaned.
  3139. const impact = cg.getImpactRadius(aliasNode!.id, 3);
  3140. const bridge = impact.edges.find(
  3141. (e) =>
  3142. e.target === aliasNode!.id &&
  3143. (e.metadata as { synthesizedBy?: string } | undefined)?.synthesizedBy ===
  3144. 'kotlin-expect-actual'
  3145. );
  3146. expect(bridge).toBeDefined();
  3147. });
  3148. });
  3149. describe('Scala cross-file dependencies', () => {
  3150. let tempDir: string;
  3151. let cg: CodeGraph;
  3152. beforeEach(() => {
  3153. tempDir = createTempDir();
  3154. });
  3155. afterEach(() => {
  3156. if (cg) cg.close();
  3157. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  3158. });
  3159. it('links parameterized supertypes, type annotations, and implicit params across files', async () => {
  3160. const src = path.join(tempDir, 'src', 'main', 'scala', 'demo');
  3161. fs.mkdirSync(src, { recursive: true });
  3162. fs.writeFileSync(
  3163. path.join(src, 'Semigroup.scala'),
  3164. `package demo
  3165. trait Semigroup[A] {
  3166. def combine(x: A, y: A): A
  3167. }
  3168. `
  3169. );
  3170. fs.writeFileSync(
  3171. path.join(src, 'Monoid.scala'),
  3172. `package demo
  3173. trait Monoid[A] extends Semigroup[A] {
  3174. def empty: A
  3175. }
  3176. `
  3177. );
  3178. fs.writeFileSync(
  3179. path.join(src, 'Instances.scala'),
  3180. `package demo
  3181. object Instances {
  3182. implicit val intMonoid: Monoid[Int] = new Monoid[Int] {
  3183. def empty: Int = 0
  3184. def combine(x: Int, y: Int): Int = x + y
  3185. }
  3186. }
  3187. `
  3188. );
  3189. fs.writeFileSync(
  3190. path.join(src, 'Folding.scala'),
  3191. `package demo
  3192. object Folding {
  3193. def fold[A](xs: List[A])(implicit M: Monoid[A]): A =
  3194. xs.foldLeft(M.empty)(M.combine)
  3195. }
  3196. `
  3197. );
  3198. cg = CodeGraph.initSync(tempDir);
  3199. await cg.indexAll();
  3200. cg.resolveReferences();
  3201. const monoid = cg.getNodesByKind('trait').find((n) => n.name === 'Monoid');
  3202. const semigroup = cg.getNodesByKind('trait').find((n) => n.name === 'Semigroup');
  3203. expect(monoid).toBeDefined();
  3204. expect(semigroup).toBeDefined();
  3205. expect(monoid!.filePath).not.toBe(semigroup!.filePath);
  3206. // Parameterized supertype `extends Semigroup[A]` must create an extends edge —
  3207. // the whole point of the fix (the `[A]` used to defeat name matching).
  3208. const semaImpact = cg.getImpactRadius(semigroup!.id, 3);
  3209. expect([...semaImpact.nodes.values()].map((n) => n.name)).toContain('Monoid');
  3210. // Editing Monoid surfaces the cross-file users: the instance val typed
  3211. // `Monoid[Int]` and the method taking it as an implicit (curried) param.
  3212. const impacted = [...cg.getImpactRadius(monoid!.id, 3).nodes.values()].map((n) => n.name);
  3213. expect(impacted).toContain('intMonoid'); // field type annotation
  3214. expect(impacted).toContain('fold'); // trailing implicit parameter list
  3215. });
  3216. });
  3217. describe('PHP namespace + import resolution', () => {
  3218. let tempDir: string;
  3219. let cg: CodeGraph;
  3220. beforeEach(() => {
  3221. tempDir = createTempDir();
  3222. });
  3223. afterEach(() => {
  3224. if (cg) cg.close();
  3225. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  3226. });
  3227. it('resolves `use` imports to the namespace-qualified definition and type-hints across files', async () => {
  3228. const src = path.join(tempDir, 'src');
  3229. // Two interfaces with the SAME simple name in different namespaces — the
  3230. // exact ambiguity (Laravel has 7+ `Factory`) that bare-name matching can't
  3231. // resolve. The namespace qualifies them; the `use` import disambiguates.
  3232. fs.mkdirSync(path.join(src, 'Cache'), { recursive: true });
  3233. fs.mkdirSync(path.join(src, 'Mail'), { recursive: true });
  3234. fs.mkdirSync(path.join(src, 'App'), { recursive: true });
  3235. fs.writeFileSync(
  3236. path.join(src, 'Cache', 'Factory.php'),
  3237. `<?php
  3238. namespace Contracts\\Cache;
  3239. interface Factory {
  3240. public function store(): object;
  3241. }
  3242. `
  3243. );
  3244. fs.writeFileSync(
  3245. path.join(src, 'Mail', 'Factory.php'),
  3246. `<?php
  3247. namespace Contracts\\Mail;
  3248. interface Factory {
  3249. public function mailer(): object;
  3250. }
  3251. `
  3252. );
  3253. fs.writeFileSync(
  3254. path.join(src, 'App', 'Service.php'),
  3255. `<?php
  3256. namespace App;
  3257. use Contracts\\Cache\\Factory;
  3258. class Service {
  3259. public function make(): Factory {
  3260. return resolve(Factory::class);
  3261. }
  3262. }
  3263. `
  3264. );
  3265. cg = CodeGraph.initSync(tempDir);
  3266. await cg.indexAll();
  3267. cg.resolveReferences();
  3268. // The PHP namespace is captured into the qualified name, so the two
  3269. // same-named interfaces are distinguishable.
  3270. const cacheFactory = cg
  3271. .getNodesByKind('interface')
  3272. .find((n) => n.qualifiedName === 'Contracts\\Cache::Factory');
  3273. const mailFactory = cg
  3274. .getNodesByKind('interface')
  3275. .find((n) => n.qualifiedName === 'Contracts\\Mail::Factory');
  3276. expect(cacheFactory).toBeDefined();
  3277. expect(mailFactory).toBeDefined();
  3278. // Service `use`s Contracts\Cache\Factory, so editing THAT interface reaches
  3279. // Service.php — and editing the same-named Contracts\Mail\Factory must NOT
  3280. // (the import resolved to the right namespace, not an arbitrary `Factory`).
  3281. const serviceFile = 'src/App/Service.php';
  3282. const cacheReaches = [...cg.getImpactRadius(cacheFactory!.id, 3).nodes.values()].some(
  3283. (n) => (n.filePath ?? '').endsWith(serviceFile)
  3284. );
  3285. const mailReaches = [...cg.getImpactRadius(mailFactory!.id, 3).nodes.values()].some(
  3286. (n) => (n.filePath ?? '').endsWith(serviceFile)
  3287. );
  3288. expect(cacheReaches).toBe(true);
  3289. expect(mailReaches).toBe(false);
  3290. });
  3291. });
  3292. describe('Ruby mixins (include/extend/prepend)', () => {
  3293. let tempDir: string;
  3294. let cg: CodeGraph;
  3295. beforeEach(() => {
  3296. tempDir = createTempDir();
  3297. });
  3298. afterEach(() => {
  3299. if (cg) cg.close();
  3300. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  3301. });
  3302. it('links include/extend/prepend to the mixed-in module across files', async () => {
  3303. const lib = path.join(tempDir, 'lib');
  3304. fs.mkdirSync(lib, { recursive: true });
  3305. fs.writeFileSync(
  3306. path.join(lib, 'concerns.rb'),
  3307. `module Trackable
  3308. def track; end
  3309. end
  3310. module Cacheable
  3311. def cache; end
  3312. end
  3313. module Loggable
  3314. def log; end
  3315. end
  3316. `
  3317. );
  3318. fs.writeFileSync(
  3319. path.join(lib, 'model.rb'),
  3320. `class Model
  3321. include Trackable
  3322. prepend Cacheable
  3323. extend Loggable
  3324. end
  3325. `
  3326. );
  3327. cg = CodeGraph.initSync(tempDir);
  3328. await cg.indexAll();
  3329. cg.resolveReferences();
  3330. const model = cg.getNodesByKind('class').find((n) => n.name === 'Model');
  3331. expect(model).toBeDefined();
  3332. // All three mixin forms create an `implements` edge Model → module, so
  3333. // editing a concern surfaces every class that mixes it in (across files).
  3334. for (const moduleName of ['Trackable', 'Cacheable', 'Loggable']) {
  3335. const mod = cg.getNodesByKind('module').find((n) => n.name === moduleName);
  3336. expect(mod, moduleName).toBeDefined();
  3337. const impacted = [...cg.getImpactRadius(mod!.id, 3).nodes.values()].map((n) => n.name);
  3338. expect(impacted, `${moduleName} should be depended on by Model`).toContain('Model');
  3339. }
  3340. });
  3341. it('resolves require / require_relative to the required file', async () => {
  3342. const lib = path.join(tempDir, 'lib');
  3343. fs.mkdirSync(path.join(lib, 'app'), { recursive: true });
  3344. // A leaf file whose class is referenced only dynamically — so without
  3345. // require resolution it would look like nothing depends on it.
  3346. fs.writeFileSync(
  3347. path.join(lib, 'app', 'fetcher.rb'),
  3348. `module App
  3349. class Fetcher
  3350. def fetch; end
  3351. end
  3352. end
  3353. `
  3354. );
  3355. // Pulled in by a load-path `require` …
  3356. fs.writeFileSync(
  3357. path.join(lib, 'app', 'worker.rb'),
  3358. `require "app/fetcher"
  3359. module App
  3360. class Worker; end
  3361. end
  3362. `
  3363. );
  3364. // … and a sibling pulled in by `require_relative`.
  3365. fs.writeFileSync(
  3366. path.join(lib, 'app', 'boot.rb'),
  3367. `require_relative "fetcher"
  3368. `
  3369. );
  3370. cg = CodeGraph.initSync(tempDir);
  3371. await cg.indexAll();
  3372. cg.resolveReferences();
  3373. // The require edges target fetcher.rb's FILE node. Editing it should reach
  3374. // BOTH the load-path requirer (worker.rb) and the require_relative one
  3375. // (boot.rb) — without require resolution its file would have no dependents.
  3376. const fetcher = cg.getNodesByKind('file').find((n) => n.filePath.endsWith('app/fetcher.rb'));
  3377. expect(fetcher, 'fetcher.rb indexed').toBeDefined();
  3378. const reached = [...cg.getImpactRadius(fetcher!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3379. expect(reached.some((p) => p.endsWith('app/worker.rb'))).toBe(true);
  3380. expect(reached.some((p) => p.endsWith('app/boot.rb'))).toBe(true);
  3381. });
  3382. });
  3383. describe('C++ free-function name extraction', () => {
  3384. let tempDir: string;
  3385. let cg: CodeGraph;
  3386. beforeEach(() => {
  3387. tempDir = createTempDir();
  3388. });
  3389. afterEach(() => {
  3390. if (cg) cg.close();
  3391. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  3392. });
  3393. it('names a free function correctly when it has qualified-type params or a trailing return type', async () => {
  3394. const src = path.join(tempDir, 'src');
  3395. fs.mkdirSync(src, { recursive: true });
  3396. // TableFileName has a `const std::string&` parameter; BuildName uses an
  3397. // `auto … -> std::string` trailing return type. Both used to be named
  3398. // `string` (picked up from the parameter / return type), so callers never
  3399. // resolved and the defining file looked like nothing depended on it.
  3400. fs.writeFileSync(
  3401. path.join(src, 'names.cc'),
  3402. `#include <string>
  3403. std::string TableFileName(const std::string& dbname, int number) {
  3404. return dbname;
  3405. }
  3406. auto BuildName(const std::string& a) -> std::string {
  3407. return a;
  3408. }
  3409. `
  3410. );
  3411. fs.writeFileSync(
  3412. path.join(src, 'user.cc'),
  3413. `#include <string>
  3414. std::string use() {
  3415. return TableFileName("db", 1) + BuildName("x");
  3416. }
  3417. `
  3418. );
  3419. cg = CodeGraph.initSync(tempDir);
  3420. await cg.indexAll();
  3421. cg.resolveReferences();
  3422. // The functions are extracted under their real names, not `string`.
  3423. const fns = cg.getNodesByKind('function');
  3424. const tableFn = fns.find((n) => n.name === 'TableFileName');
  3425. const buildFn = fns.find((n) => n.name === 'BuildName');
  3426. expect(tableFn, 'TableFileName extracted (not "string")').toBeDefined();
  3427. expect(buildFn, 'BuildName extracted (not "string")').toBeDefined();
  3428. // And the cross-file calls resolve to them, so editing names.cc surfaces user.cc.
  3429. for (const fn of [tableFn!, buildFn!]) {
  3430. const reached = [...cg.getImpactRadius(fn.id, 3).nodes.values()].map((n) => n.filePath ?? '');
  3431. expect(reached.some((p) => p.endsWith('user.cc')), `${fn.name} should be called from user.cc`).toBe(true);
  3432. }
  3433. });
  3434. });
  3435. describe('Dart mixins and type references', () => {
  3436. let tempDir: string;
  3437. let cg: CodeGraph;
  3438. beforeEach(() => {
  3439. tempDir = createTempDir();
  3440. });
  3441. afterEach(() => {
  3442. if (cg) cg.close();
  3443. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  3444. });
  3445. it('links `with` mixins and method parameter/return types across files', async () => {
  3446. const lib = path.join(tempDir, 'lib');
  3447. fs.mkdirSync(lib, { recursive: true });
  3448. fs.writeFileSync(
  3449. path.join(lib, 'models.dart'),
  3450. `class User {
  3451. final String name;
  3452. User(this.name);
  3453. }
  3454. mixin Loggable {
  3455. void log() {}
  3456. }
  3457. abstract class Repository {
  3458. User find(int id);
  3459. }
  3460. `
  3461. );
  3462. fs.writeFileSync(
  3463. path.join(lib, 'service.dart'),
  3464. `import 'models.dart';
  3465. class UserService extends Repository with Loggable {
  3466. @override
  3467. User find(int id) => User('x');
  3468. List<User> all() => [];
  3469. }
  3470. `
  3471. );
  3472. cg = CodeGraph.initSync(tempDir);
  3473. await cg.indexAll();
  3474. cg.resolveReferences();
  3475. const inModels = (name: string) =>
  3476. cg.getNodesByKind('class').concat(cg.getNodesByKind('module'))
  3477. .find((n) => n.name === name && n.filePath.endsWith('models.dart'));
  3478. // The `with Loggable` mixin records a dependency — editing the mixin surfaces
  3479. // the class that mixes it in (across files). Loggable is a `mixin`, indexed
  3480. // as a class-like node.
  3481. const loggable = cg.getNodesByKind('class').find((n) => n.name === 'Loggable')
  3482. ?? cg.getNodesByKind('module').find((n) => n.name === 'Loggable');
  3483. expect(loggable, 'Loggable mixin indexed').toBeDefined();
  3484. const mixinUsers = [...cg.getImpactRadius(loggable!.id, 3).nodes.values()].map((n) => n.name);
  3485. expect(mixinUsers).toContain('UserService');
  3486. // `User` is used only as a method parameter/return type in service.dart —
  3487. // editing it must still surface service.dart via the type references.
  3488. const user = inModels('User') ?? cg.getNodesByKind('class').find((n) => n.name === 'User');
  3489. expect(user, 'User indexed').toBeDefined();
  3490. const userDeps = [...cg.getImpactRadius(user!.id, 3).nodes.values()].map((n) => n.filePath ?? '');
  3491. expect(userDeps.some((p) => p.endsWith('service.dart'))).toBe(true);
  3492. });
  3493. });
  3494. describe('Static-member / value-read references', () => {
  3495. let tempDir: string;
  3496. let cg: CodeGraph;
  3497. beforeEach(() => {
  3498. tempDir = createTempDir();
  3499. });
  3500. afterEach(() => {
  3501. if (cg) cg.close();
  3502. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  3503. });
  3504. it('links a type referenced only via a static field / enum value (and ignores lowercase receivers)', async () => {
  3505. fs.writeFileSync(
  3506. path.join(tempDir, 'JsonScope.java'),
  3507. `class JsonScope {
  3508. static final int EMPTY_DOCUMENT = 1;
  3509. }
  3510. `
  3511. );
  3512. fs.writeFileSync(
  3513. path.join(tempDir, 'Reader.java'),
  3514. `class Reader {
  3515. private int helper;
  3516. int peek() {
  3517. return JsonScope.EMPTY_DOCUMENT;
  3518. }
  3519. int noop() {
  3520. return this.helper;
  3521. }
  3522. }
  3523. `
  3524. );
  3525. cg = CodeGraph.initSync(tempDir);
  3526. await cg.indexAll();
  3527. cg.resolveReferences();
  3528. // JsonScope is used ONLY as `JsonScope.EMPTY_DOCUMENT` (a static-field value
  3529. // read — never constructed or called), so before the static-member pass it
  3530. // had no dependents. Editing it now surfaces Reader.java.
  3531. const scope = cg.getNodesByKind('class').find((n) => n.name === 'JsonScope');
  3532. expect(scope, 'JsonScope indexed').toBeDefined();
  3533. const reached = [...cg.getImpactRadius(scope!.id, 3).nodes.values()].map((n) => n.filePath ?? '');
  3534. expect(reached.some((p) => p.endsWith('Reader.java'))).toBe(true);
  3535. // A lowercase receiver (`this.helper`) must NOT be emitted as a type ref —
  3536. // only Capitalized receivers (types) are. No node named `this`/`helper`
  3537. // should appear as a reference target from peek/noop beyond JsonScope.
  3538. const refTargets = cg
  3539. .getNodesByKind('class')
  3540. .filter((n) => n.name === 'this' || n.name === 'helper');
  3541. expect(refTargets.length).toBe(0);
  3542. });
  3543. it('does not link a static-member read across language families (coincidental name)', async () => {
  3544. // A native (Kotlin) `Build.VERSION` reads the Android system class — it must
  3545. // NOT link to a coincidentally same-named TS class (the cross-language false
  3546. // positive that name-matching produces; `references` edges are language-local).
  3547. fs.writeFileSync(
  3548. path.join(tempDir, 'Build.ts'),
  3549. `export class Build {\n static version = 1;\n}\n`
  3550. );
  3551. fs.writeFileSync(
  3552. path.join(tempDir, 'Device.kt'),
  3553. `package app\nclass Device {\n fun sdk(): Int = Build.VERSION\n}\n`
  3554. );
  3555. cg = CodeGraph.initSync(tempDir);
  3556. await cg.indexAll();
  3557. cg.resolveReferences();
  3558. const tsBuild = cg.getNodesByKind('class').find((n) => n.name === 'Build' && n.filePath.endsWith('Build.ts'));
  3559. expect(tsBuild).toBeDefined();
  3560. // The Kotlin file is `app/Device.kt`; the TS Build must have NO dependent there.
  3561. const deps = [...cg.getImpactRadius(tsBuild!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3562. expect(deps.some((p) => p.endsWith('Device.kt'))).toBe(false);
  3563. });
  3564. });
  3565. describe('Cross-language type/import gate (RN name collisions)', () => {
  3566. let tempDir: string;
  3567. let cg: CodeGraph;
  3568. beforeEach(() => {
  3569. tempDir = createTempDir();
  3570. });
  3571. afterEach(() => {
  3572. if (cg) cg.close();
  3573. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  3574. });
  3575. it('a TS PascalCase type ref lands on the TS type, never a same-named native class', async () => {
  3576. // react-native-async-storage's example app has a TS `type TestRunner` AND a
  3577. // Kotlin `class TestRunner`. The React PascalCase resolver name-matched the
  3578. // Kotlin `class` (its COMPONENT_KINDS includes `class`) with no language
  3579. // check at confidence 0.8, outranking the (cross-language-penalized 0.5)
  3580. // TS name-match — so a TS ref to `TestRunner` crossed web→jvm. The ref here
  3581. // is intentionally NOT imported: a clean relative import would mask the bug
  3582. // by resolving via the import map before the framework strategy can win.
  3583. fs.writeFileSync(
  3584. path.join(tempDir, 'package.json'),
  3585. JSON.stringify({ dependencies: { 'react-native': '*' } })
  3586. );
  3587. fs.writeFileSync(
  3588. path.join(tempDir, 'useTests.ts'),
  3589. `export type TestRunner = { run: () => void };\n`
  3590. );
  3591. fs.writeFileSync(
  3592. path.join(tempDir, 'basic.tsx'),
  3593. `export function useBasicTest(r: TestRunner): TestRunner {\n return r;\n}\n`
  3594. );
  3595. fs.writeFileSync(
  3596. path.join(tempDir, 'TestUtils.kt'),
  3597. `package app\nclass TestRunner {\n fun run() {}\n}\n`
  3598. );
  3599. cg = CodeGraph.initSync(tempDir);
  3600. await cg.indexAll();
  3601. cg.resolveReferences();
  3602. const ktRunner = cg
  3603. .getNodesByKind('class')
  3604. .find((n) => n.name === 'TestRunner' && n.filePath.endsWith('TestUtils.kt'));
  3605. expect(ktRunner, 'Kotlin TestRunner class').toBeDefined();
  3606. const ktDeps = [...cg.getImpactRadius(ktRunner!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3607. expect(ktDeps.some((p) => p.endsWith('basic.tsx')), 'Kotlin class has NO TS dependent').toBe(false);
  3608. const tsRunner = cg.getNodesByKind('type_alias').find((n) => n.name === 'TestRunner');
  3609. expect(tsRunner, 'TS TestRunner type_alias').toBeDefined();
  3610. const tsDeps = [...cg.getImpactRadius(tsRunner!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3611. expect(tsDeps.some((p) => p.endsWith('basic.tsx')), 'TS type captured the ref (re-pointed)').toBe(true);
  3612. });
  3613. it('gates a cross-family import name collision but keeps same-family imports', async () => {
  3614. // A TS `import { Widget }` that only matches a Swift `class Widget` must not
  3615. // create a web→apple dependency — but a sibling TS module imported by
  3616. // another TS file (same family) must still resolve (no over-gating).
  3617. fs.writeFileSync(path.join(tempDir, 'Widget.swift'), `class Widget {\n func render() {}\n}\n`);
  3618. fs.writeFileSync(
  3619. path.join(tempDir, 'widget.ts'),
  3620. `import { Widget } from './native';\nexport function mount(w: Widget) {}\n`
  3621. );
  3622. fs.writeFileSync(path.join(tempDir, 'util.ts'), `export class Helper {}\n`);
  3623. fs.writeFileSync(
  3624. path.join(tempDir, 'app.ts'),
  3625. `import { Helper } from './util';\nexport const h = new Helper();\n`
  3626. );
  3627. cg = CodeGraph.initSync(tempDir);
  3628. await cg.indexAll();
  3629. cg.resolveReferences();
  3630. const swiftWidget = cg
  3631. .getNodesByKind('class')
  3632. .find((n) => n.name === 'Widget' && n.filePath.endsWith('.swift'));
  3633. expect(swiftWidget, 'Swift Widget class').toBeDefined();
  3634. const wDeps = [...cg.getImpactRadius(swiftWidget!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3635. expect(wDeps.some((p) => p.endsWith('widget.ts')), 'Swift class has NO TS dependent').toBe(false);
  3636. // Same-family control — the TS Helper must still see its TS dependent.
  3637. const helper = cg.getNodesByKind('class').find((n) => n.name === 'Helper');
  3638. expect(helper, 'TS Helper class').toBeDefined();
  3639. const hDeps = [...cg.getImpactRadius(helper!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3640. expect(hDeps.some((p) => p.endsWith('app.ts')), 'same-family TS import preserved').toBe(true);
  3641. });
  3642. });
  3643. describe('Python absolute module import resolution', () => {
  3644. let tempDir: string;
  3645. let cg: CodeGraph;
  3646. beforeEach(() => {
  3647. tempDir = createTempDir();
  3648. });
  3649. afterEach(() => {
  3650. if (cg) cg.close();
  3651. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  3652. });
  3653. it('links a bare `import pkg.module` of an internal module to its file', async () => {
  3654. // `import conduit.apps.signals` (a Django-style side-effect import, and any
  3655. // dotted absolute module import) had no edge to the module file — only
  3656. // `from x import y` was linked — so a module imported by its dotted path
  3657. // looked like nothing depended on it.
  3658. fs.mkdirSync(path.join(tempDir, 'conduit/apps'), { recursive: true });
  3659. fs.writeFileSync(path.join(tempDir, 'conduit/__init__.py'), '');
  3660. fs.writeFileSync(path.join(tempDir, 'conduit/apps/__init__.py'), '');
  3661. fs.writeFileSync(path.join(tempDir, 'conduit/apps/signals.py'), `def handler():\n pass\n`);
  3662. fs.writeFileSync(
  3663. path.join(tempDir, 'conduit/apps/app.py'),
  3664. `import conduit.apps.signals\nimport os\n\nVALUE = 1\n`
  3665. );
  3666. cg = CodeGraph.initSync(tempDir);
  3667. await cg.indexAll();
  3668. cg.resolveReferences();
  3669. const signals = cg.getNodesByKind('file').find((n) => n.filePath.endsWith('conduit/apps/signals.py'));
  3670. expect(signals, 'signals.py indexed').toBeDefined();
  3671. const deps = [...cg.getImpactRadius(signals!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3672. expect(deps.some((p) => p.endsWith('app.py')), 'importer depends on the module').toBe(true);
  3673. // `import os` (stdlib) must NOT fabricate an edge — no os.py file in the repo.
  3674. const osNode = cg.getNodesByKind('file').find((n) => n.filePath.endsWith('/os.py'));
  3675. expect(osNode, 'no stdlib os.py node').toBeUndefined();
  3676. });
  3677. it('Django include() links the root URLconf to the included app urls module', async () => {
  3678. // `url(r'^api/', include('app.urls'))` should record a dependency from the
  3679. // root urlconf onto the included app's `urls.py` — so editing an app's routes
  3680. // surfaces the project urlconf that mounts them.
  3681. fs.mkdirSync(path.join(tempDir, 'app'), { recursive: true });
  3682. fs.writeFileSync(path.join(tempDir, 'requirements.txt'), `django==4.0\n`);
  3683. fs.writeFileSync(path.join(tempDir, 'app/__init__.py'), '');
  3684. fs.writeFileSync(path.join(tempDir, 'app/views.py'), `def home(request):\n return None\n`);
  3685. fs.writeFileSync(
  3686. path.join(tempDir, 'app/urls.py'),
  3687. `from django.conf.urls import url\nfrom . import views\nurlpatterns = [url(r'^$', views.home)]\n`
  3688. );
  3689. fs.writeFileSync(
  3690. path.join(tempDir, 'urls.py'),
  3691. `from django.conf.urls import include, url\nurlpatterns = [url(r'^app/', include('app.urls'))]\n`
  3692. );
  3693. cg = CodeGraph.initSync(tempDir);
  3694. await cg.indexAll();
  3695. cg.resolveReferences();
  3696. const appUrls = cg.getNodesByKind('file').find((n) => n.filePath.endsWith('app/urls.py'));
  3697. expect(appUrls, 'app/urls.py indexed').toBeDefined();
  3698. const deps = [...cg.getImpactRadius(appUrls!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3699. expect(deps.some((p) => p.endsWith('urls.py') && !p.endsWith('app/urls.py')), 'root urlconf depends on the included app urls').toBe(true);
  3700. });
  3701. it('resolves `from pkg import submodule` to the submodule under that package, not a same-named one', async () => {
  3702. // FastAPI router-aggregator pattern: `from app.api.routes import authentication`
  3703. // with same-named modules in sibling packages must resolve via the import's
  3704. // SOURCE (the package), not a coincidental same-basename file elsewhere.
  3705. fs.mkdirSync(path.join(tempDir, 'app/api/routes'), { recursive: true });
  3706. fs.mkdirSync(path.join(tempDir, 'app/api/dependencies'), { recursive: true });
  3707. for (const p of ['app/__init__.py', 'app/api/__init__.py', 'app/api/routes/__init__.py', 'app/api/dependencies/__init__.py']) {
  3708. fs.writeFileSync(path.join(tempDir, p), '');
  3709. }
  3710. fs.writeFileSync(path.join(tempDir, 'app/api/routes/authentication.py'), `def login():\n pass\n`);
  3711. fs.writeFileSync(path.join(tempDir, 'app/api/dependencies/authentication.py'), `def get_user():\n pass\n`);
  3712. fs.writeFileSync(
  3713. path.join(tempDir, 'app/api/routes/api.py'),
  3714. `from app.api.routes import authentication\n\nROUTER = authentication\n`
  3715. );
  3716. cg = CodeGraph.initSync(tempDir);
  3717. await cg.indexAll();
  3718. cg.resolveReferences();
  3719. const routesAuth = cg.getNodesByKind('file').find((n) => n.filePath.endsWith('routes/authentication.py'));
  3720. const depsAuth = cg.getNodesByKind('file').find((n) => n.filePath.endsWith('dependencies/authentication.py'));
  3721. expect(routesAuth && depsAuth).toBeTruthy();
  3722. const routesDeps = [...cg.getImpactRadius(routesAuth!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3723. const depsDeps = [...cg.getImpactRadius(depsAuth!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3724. expect(routesDeps.some((p) => p.endsWith('routes/api.py')), 'submodule under the imported package is the dependent').toBe(true);
  3725. expect(depsDeps.some((p) => p.endsWith('routes/api.py')), 'same-named module in a sibling package is NOT').toBe(false);
  3726. });
  3727. });
  3728. describe('Razor / Blazor markup extraction', () => {
  3729. let tempDir: string;
  3730. let cg: CodeGraph;
  3731. beforeEach(() => {
  3732. tempDir = createTempDir();
  3733. });
  3734. afterEach(() => {
  3735. if (cg) cg.close();
  3736. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  3737. });
  3738. it('links @model and Blazor component tags to their C# types; ignores HTML elements', async () => {
  3739. fs.mkdirSync(path.join(tempDir, 'Views'), { recursive: true });
  3740. fs.writeFileSync(
  3741. path.join(tempDir, 'LoginViewModel.cs'),
  3742. `namespace App { public class LoginViewModel { public string Email { get; set; } } }`
  3743. );
  3744. fs.writeFileSync(
  3745. path.join(tempDir, 'ToastComponent.cs'),
  3746. `namespace App { public class ToastComponent { } }`
  3747. );
  3748. fs.writeFileSync(
  3749. path.join(tempDir, 'Views/Login.cshtml'),
  3750. `@model LoginViewModel\n<div class="form">\n <input asp-for="Email" />\n</div>\n`
  3751. );
  3752. fs.writeFileSync(
  3753. path.join(tempDir, 'Index.razor'),
  3754. `<div>\n <ToastComponent />\n</div>\n`
  3755. );
  3756. cg = CodeGraph.initSync(tempDir);
  3757. await cg.indexAll();
  3758. cg.resolveReferences();
  3759. // `@model LoginViewModel` → the view-model class.
  3760. const vm = cg.getNodesByKind('class').find((n) => n.name === 'LoginViewModel');
  3761. expect(vm, 'LoginViewModel class').toBeDefined();
  3762. const vmDeps = [...cg.getImpactRadius(vm!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3763. expect(vmDeps.some((p) => p.endsWith('Login.cshtml')), '@model links the view').toBe(true);
  3764. // `<ToastComponent />` → the component class.
  3765. const toast = cg.getNodesByKind('class').find((n) => n.name === 'ToastComponent');
  3766. expect(toast, 'ToastComponent class').toBeDefined();
  3767. const toastDeps = [...cg.getImpactRadius(toast!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3768. expect(toastDeps.some((p) => p.endsWith('Index.razor')), 'Blazor tag links the component').toBe(true);
  3769. // HTML elements (`<div>`, `<input>`) must NOT become component references.
  3770. const htmlNodes = cg.getNodesByKind('class').filter((n) => n.name === 'div' || n.name === 'input');
  3771. expect(htmlNodes.length, 'no node for HTML elements').toBe(0);
  3772. });
  3773. it('C# namespaces qualify type names so same-named types are distinct', async () => {
  3774. fs.writeFileSync(path.join(tempDir, 'entity.cs'), `namespace App.Entities { public class CatalogBrand { } }`);
  3775. fs.writeFileSync(path.join(tempDir, 'dto.cs'), `namespace App.Models { public class CatalogBrand { } }`);
  3776. cg = CodeGraph.initSync(tempDir);
  3777. await cg.indexAll();
  3778. const brands = cg.getNodesByKind('class').filter((n) => n.name === 'CatalogBrand');
  3779. expect(brands.length, 'both CatalogBrand classes indexed').toBe(2);
  3780. const qns = brands.map((b) => b.qualifiedName).sort();
  3781. expect(qns[0]).not.toBe(qns[1]); // distinct qualified names (namespace-scoped)
  3782. expect(qns.some((q) => q.includes('Entities') && q.endsWith('CatalogBrand'))).toBe(true);
  3783. expect(qns.some((q) => q.includes('Models') && q.endsWith('CatalogBrand'))).toBe(true);
  3784. });
  3785. it('disambiguates a Razor type ref via @using (incl. folder _Imports.razor)', async () => {
  3786. // `CatalogBrand` exists as both a domain entity and a DTO; the component
  3787. // `@using`s the DTO's namespace (here via the folder _Imports.razor), so the
  3788. // ref must resolve to the DTO, not the same-named entity.
  3789. fs.mkdirSync(path.join(tempDir, 'Models'), { recursive: true });
  3790. fs.mkdirSync(path.join(tempDir, 'Entities'), { recursive: true });
  3791. fs.mkdirSync(path.join(tempDir, 'Pages'), { recursive: true });
  3792. fs.writeFileSync(path.join(tempDir, 'Models/CatalogBrand.cs'), `namespace App.Models { public class CatalogBrand { public int Id { get; set; } } }`);
  3793. fs.writeFileSync(path.join(tempDir, 'Entities/CatalogBrand.cs'), `namespace App.Entities { public class CatalogBrand { public int Id { get; set; } } }`);
  3794. fs.writeFileSync(path.join(tempDir, 'Pages/_Imports.razor'), `@using App.Models\n`);
  3795. fs.writeFileSync(
  3796. path.join(tempDir, 'Pages/List.razor'),
  3797. `<h1>List</h1>\n@code {\n private CatalogBrand _b = new CatalogBrand();\n}\n`
  3798. );
  3799. cg = CodeGraph.initSync(tempDir);
  3800. await cg.indexAll();
  3801. cg.resolveReferences();
  3802. const dto = cg.getNodesByKind('class').find((n) => n.qualifiedName === 'App.Models::CatalogBrand');
  3803. const entity = cg.getNodesByKind('class').find((n) => n.qualifiedName === 'App.Entities::CatalogBrand');
  3804. expect(dto && entity, 'both CatalogBrand classes').toBeTruthy();
  3805. const dtoDeps = [...cg.getImpactRadius(dto!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3806. const entityDeps = [...cg.getImpactRadius(entity!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3807. expect(dtoDeps.some((p) => p.endsWith('List.razor')), 'resolves to the @using\'d DTO').toBe(true);
  3808. expect(entityDeps.some((p) => p.endsWith('List.razor')), 'NOT the same-named entity').toBe(false);
  3809. });
  3810. it('delegates Blazor @code block C# to cover types used in component logic', async () => {
  3811. fs.writeFileSync(
  3812. path.join(tempDir, 'CatalogService.cs'),
  3813. `namespace App { public class CatalogService { public void Load() { } } }`
  3814. );
  3815. fs.writeFileSync(
  3816. path.join(tempDir, 'List.razor'),
  3817. `<h1>Catalog</h1>\n\n@code {\n private CatalogService _svc = new CatalogService();\n void Refresh() { _svc.Load(); }\n}\n`
  3818. );
  3819. cg = CodeGraph.initSync(tempDir);
  3820. await cg.indexAll();
  3821. cg.resolveReferences();
  3822. const svc = cg.getNodesByKind('class').find((n) => n.name === 'CatalogService');
  3823. expect(svc, 'CatalogService class').toBeDefined();
  3824. const deps = [...cg.getImpactRadius(svc!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3825. expect(deps.some((p) => p.endsWith('List.razor')), '@code usage links the component to the service').toBe(true);
  3826. });
  3827. });
  3828. describe('Default import resolution (renamed default export)', () => {
  3829. let tempDir: string;
  3830. let cg: CodeGraph;
  3831. beforeEach(() => {
  3832. tempDir = createTempDir();
  3833. });
  3834. afterEach(() => {
  3835. if (cg) cg.close();
  3836. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  3837. });
  3838. it('links a renamed default import to the module file', async () => {
  3839. // Express route aggregator: `import articlesController from './controller'`
  3840. // where the module does `export default router`. The renamed local can't be
  3841. // found as a symbol, so the controller file had no dependent — the dependency
  3842. // is on the module file regardless of the default export's name.
  3843. fs.mkdirSync(path.join(tempDir, 'app'), { recursive: true });
  3844. fs.writeFileSync(path.join(tempDir, 'app/controller.ts'), `const router = { get() {} };\nexport default router;\n`);
  3845. fs.writeFileSync(path.join(tempDir, 'app/routes.ts'), `import myController from './controller';\nexport const api = myController;\n`);
  3846. cg = CodeGraph.initSync(tempDir);
  3847. await cg.indexAll();
  3848. cg.resolveReferences();
  3849. const controller = cg.getNodesByKind('file').find((n) => n.filePath.endsWith('app/controller.ts'));
  3850. expect(controller, 'controller.ts indexed').toBeDefined();
  3851. const deps = [...cg.getImpactRadius(controller!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3852. expect(deps.some((p) => p.endsWith('routes.ts')), 'importer depends on the default-exporting module').toBe(true);
  3853. });
  3854. });
  3855. describe('Chained method-call resolution (C# extension methods)', () => {
  3856. let tempDir: string;
  3857. let cg: CodeGraph;
  3858. beforeEach(() => {
  3859. tempDir = createTempDir();
  3860. });
  3861. afterEach(() => {
  3862. if (cg) cg.close();
  3863. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  3864. });
  3865. it('resolves a chained extension-method call (a.b.Method()) to its definition', async () => {
  3866. // ASP.NET DI registration: `builder.Services.AddCoreServices(...)` calls a
  3867. // static extension method elsewhere. A multi-dot receiver chain matched no
  3868. // method-call pattern before, so the extension method had no caller.
  3869. fs.mkdirSync(path.join(tempDir, 'cfg'), { recursive: true });
  3870. fs.writeFileSync(
  3871. path.join(tempDir, 'cfg/Ext.cs'),
  3872. `namespace App {\n public static class Ext {\n public static object AddCoreServices(this object services, int x) { return services; }\n }\n}\n`
  3873. );
  3874. fs.writeFileSync(
  3875. path.join(tempDir, 'Program.cs'),
  3876. `namespace App {\n public class Program {\n public void Run(object builder) {\n builder.Services.AddCoreServices(1);\n }\n }\n}\n`
  3877. );
  3878. cg = CodeGraph.initSync(tempDir);
  3879. await cg.indexAll();
  3880. cg.resolveReferences();
  3881. const ext = cg
  3882. .getNodesByKind('method')
  3883. .find((n) => n.name === 'AddCoreServices')
  3884. ?? cg.getNodesByKind('function').find((n) => n.name === 'AddCoreServices');
  3885. expect(ext, 'AddCoreServices defined').toBeDefined();
  3886. const callers = [...cg.getImpactRadius(ext!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3887. expect(callers.some((p) => p.endsWith('Program.cs')), 'chained extension call resolves to its definition').toBe(true);
  3888. });
  3889. });
  3890. describe('Same-directory include + KMP import resolution', () => {
  3891. let tempDir: string;
  3892. let cg: CodeGraph;
  3893. beforeEach(() => {
  3894. tempDir = createTempDir();
  3895. });
  3896. afterEach(() => {
  3897. if (cg) cg.close();
  3898. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  3899. });
  3900. it('a C/C++ #include resolves to the same-directory header, not a same-named one elsewhere', async () => {
  3901. // A multi-platform native module has a header of the same basename per
  3902. // platform. `windows/Provider.cpp`'s `#include "Storage.h"` means its OWN
  3903. // sibling header — not `apple/Storage.h` (which sorts first and so was
  3904. // picked arbitrarily before, leaving the real local header with 0 deps).
  3905. fs.mkdirSync(path.join(tempDir, 'apple'), { recursive: true });
  3906. fs.mkdirSync(path.join(tempDir, 'windows'), { recursive: true });
  3907. fs.writeFileSync(path.join(tempDir, 'apple', 'Storage.h'), `#pragma once\nstruct Storage { int n; };\n`);
  3908. fs.writeFileSync(path.join(tempDir, 'windows', 'Storage.h'), `#pragma once\nstruct Storage { int n; };\n`);
  3909. fs.writeFileSync(
  3910. path.join(tempDir, 'windows', 'Provider.cpp'),
  3911. `#include "Storage.h"\nint use() { Storage s; return s.n; }\n`
  3912. );
  3913. cg = CodeGraph.initSync(tempDir);
  3914. await cg.indexAll();
  3915. cg.resolveReferences();
  3916. const winHeader = cg.getNodesByKind('file').find((n) => n.filePath.endsWith('windows/Storage.h'));
  3917. const appleHeader = cg.getNodesByKind('file').find((n) => n.filePath.endsWith('apple/Storage.h'));
  3918. expect(winHeader, 'windows/Storage.h indexed').toBeDefined();
  3919. expect(appleHeader, 'apple/Storage.h indexed').toBeDefined();
  3920. const winDeps = [...cg.getImpactRadius(winHeader!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3921. const appleDeps = [...cg.getImpactRadius(appleHeader!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3922. expect(winDeps.some((p) => p.endsWith('Provider.cpp')), 'same-dir header gets the includer').toBe(true);
  3923. expect(appleDeps.some((p) => p.endsWith('Provider.cpp')), 'other-platform header does NOT').toBe(false);
  3924. });
  3925. it('a Kotlin Multiplatform commonMain import resolves to the expect, not a platform actual', async () => {
  3926. const common = path.join(tempDir, 'src/commonMain/kotlin/app');
  3927. const android = path.join(tempDir, 'src/androidMain/kotlin/app');
  3928. fs.mkdirSync(common, { recursive: true });
  3929. fs.mkdirSync(android, { recursive: true });
  3930. fs.writeFileSync(path.join(common, 'Platform.kt'), `package app\nexpect class PlatformContext\n`);
  3931. fs.writeFileSync(path.join(android, 'Platform.android.kt'), `package app\nactual class PlatformContext\n`);
  3932. fs.writeFileSync(
  3933. path.join(common, 'Db.kt'),
  3934. `package app\nimport app.PlatformContext\nclass Db {\n fun open(ctx: PlatformContext) {}\n}\n`
  3935. );
  3936. cg = CodeGraph.initSync(tempDir);
  3937. await cg.indexAll();
  3938. cg.resolveReferences();
  3939. const expectCtx = cg
  3940. .getNodesByKind('class')
  3941. .find((n) => n.name === 'PlatformContext' && n.filePath.endsWith('commonMain/kotlin/app/Platform.kt'));
  3942. expect(expectCtx, 'commonMain expect PlatformContext').toBeDefined();
  3943. const deps = [...cg.getImpactRadius(expectCtx!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3944. expect(deps.some((p) => p.endsWith('Db.kt')), 'commonMain import lands on the expect, not the actual').toBe(true);
  3945. });
  3946. });
  3947. describe('Delphi form code-behind pairing', () => {
  3948. let tempDir: string;
  3949. let cg: CodeGraph;
  3950. beforeEach(() => {
  3951. tempDir = createTempDir();
  3952. });
  3953. afterEach(() => {
  3954. if (cg) cg.close();
  3955. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  3956. });
  3957. it('links a `.dfm` form to its sibling `.pas` code-behind unit', async () => {
  3958. // A Delphi form unit owns its visual form definition via `{$R *.dfm}`, not a
  3959. // `uses` clause — so a `.dfm` used only as a form definition looked orphaned.
  3960. fs.writeFileSync(path.join(tempDir, 'UFRMAbout.dfm'),
  3961. `object FRMAbout: TFRMAbout\n Caption = 'About'\nend\n`);
  3962. fs.writeFileSync(path.join(tempDir, 'UFRMAbout.pas'),
  3963. `unit UFRMAbout;\ninterface\nuses Forms;\ntype\n TFRMAbout = class(TForm)\n end;\nimplementation\n{$R *.dfm}\nend.\n`);
  3964. cg = CodeGraph.initSync(tempDir);
  3965. await cg.indexAll();
  3966. cg.resolveReferences();
  3967. const dfm = cg.getNodesByKind('file').find((n) => n.filePath.endsWith('UFRMAbout.dfm'));
  3968. expect(dfm, 'UFRMAbout.dfm file node').toBeDefined();
  3969. const deps = cg.getFileDependents(dfm!.filePath);
  3970. expect(deps.some((p) => p.endsWith('UFRMAbout.pas')), 'the .pas unit links its .dfm form').toBe(true);
  3971. });
  3972. });
  3973. describe('Liquid Shopify JSON template section resolution', () => {
  3974. let tempDir: string;
  3975. let cg: CodeGraph;
  3976. beforeEach(() => {
  3977. tempDir = createTempDir();
  3978. });
  3979. afterEach(() => {
  3980. if (cg) cg.close();
  3981. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  3982. });
  3983. it('links a Shopify JSON template section `type` to its sections/<type>.liquid', async () => {
  3984. // Shopify OS 2.0 templates are JSON, referencing sections by `type` — not
  3985. // a `{% section %}` Liquid tag — so a section used only from a JSON template
  3986. // looked unused. The JSON is now indexed and its `type`s linked.
  3987. fs.mkdirSync(path.join(tempDir, 'sections'), { recursive: true });
  3988. fs.mkdirSync(path.join(tempDir, 'templates/customers'), { recursive: true });
  3989. fs.writeFileSync(path.join(tempDir, 'sections/main-product.liquid'), `<div>{{ product.title }}</div>\n`);
  3990. fs.writeFileSync(path.join(tempDir, 'sections/main-login.liquid'), `<form>{{ 'customer.login' | t }}</form>\n`);
  3991. fs.writeFileSync(path.join(tempDir, 'templates/product.json'), JSON.stringify({ sections: { main: { type: 'main-product' } }, order: ['main'] }));
  3992. // Nested template dir (templates/customers/login.json) must resolve too.
  3993. fs.writeFileSync(path.join(tempDir, 'templates/customers/login.json'), JSON.stringify({ sections: { main: { type: 'main-login' } }, order: ['main'] }));
  3994. cg = CodeGraph.initSync(tempDir);
  3995. await cg.indexAll();
  3996. cg.resolveReferences();
  3997. const product = cg.getNodesByKind('file').find((n) => n.filePath.endsWith('sections/main-product.liquid'));
  3998. const login = cg.getNodesByKind('file').find((n) => n.filePath.endsWith('sections/main-login.liquid'));
  3999. expect(product, 'main-product section').toBeDefined();
  4000. expect(login, 'main-login section').toBeDefined();
  4001. expect(cg.getFileDependents(product!.filePath).some((p) => p.endsWith('templates/product.json')), 'top-level JSON template links its section').toBe(true);
  4002. expect(cg.getFileDependents(login!.filePath).some((p) => p.endsWith('customers/login.json')), 'nested JSON template links its section').toBe(true);
  4003. });
  4004. });
  4005. describe('Lua/Luau require resolution', () => {
  4006. let tempDir: string;
  4007. let cg: CodeGraph;
  4008. beforeEach(() => {
  4009. tempDir = createTempDir();
  4010. });
  4011. afterEach(() => {
  4012. if (cg) cg.close();
  4013. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  4014. });
  4015. it('resolves a dotted Lua require and an instance-path Luau require to their module files', async () => {
  4016. // The require is the ONLY link (no method call), so coverage here proves the
  4017. // require resolver specifically, not method-call name-matching.
  4018. // Lua dotted module path: require("myapp.config") → lua/myapp/config.lua.
  4019. fs.mkdirSync(path.join(tempDir, 'lua/myapp'), { recursive: true });
  4020. fs.writeFileSync(path.join(tempDir, 'lua/myapp/config.lua'), `local M = {}\nfunction M.setup() end\nreturn M\n`);
  4021. fs.writeFileSync(path.join(tempDir, 'lua/myapp/init.lua'), `local config = require("myapp.config")\nreturn config\n`);
  4022. // Luau Roblox instance-path require (only the leaf survives extraction):
  4023. // require(script.Util.helper) → src/Util/helper.luau.
  4024. fs.mkdirSync(path.join(tempDir, 'src/Util'), { recursive: true });
  4025. fs.writeFileSync(path.join(tempDir, 'src/Util/helper.luau'), `local H = {}\nfunction H.go() end\nreturn H\n`);
  4026. fs.writeFileSync(path.join(tempDir, 'src/init.luau'), `local helper = require(script.Util.helper)\nreturn helper\n`);
  4027. cg = CodeGraph.initSync(tempDir);
  4028. await cg.indexAll();
  4029. cg.resolveReferences();
  4030. const config = cg.getNodesByKind('file').find((n) => n.filePath.endsWith('myapp/config.lua'));
  4031. const helper = cg.getNodesByKind('file').find((n) => n.filePath.endsWith('Util/helper.luau'));
  4032. expect(config, 'config.lua file node').toBeDefined();
  4033. expect(helper, 'helper.luau file node').toBeDefined();
  4034. const cfgDeps = cg.getFileDependents(config!.filePath);
  4035. const helpDeps = cg.getFileDependents(helper!.filePath);
  4036. expect(cfgDeps.some((p) => p.endsWith('myapp/init.lua')), 'dotted Lua require resolves to the module').toBe(true);
  4037. expect(helpDeps.some((p) => p.endsWith('src/init.luau')), 'instance-path Luau require resolves to the module').toBe(true);
  4038. });
  4039. });
  4040. describe('Rust module-path call resolution', () => {
  4041. let tempDir: string;
  4042. let cg: CodeGraph;
  4043. beforeEach(() => {
  4044. tempDir = createTempDir();
  4045. });
  4046. afterEach(() => {
  4047. if (cg) cg.close();
  4048. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  4049. });
  4050. it('a bare submodule call (`users::router()`) resolves self-relative to the submodule fn', async () => {
  4051. // The canonical Axum router-assembly pattern: a parent module calls each
  4052. // submodule's `router()`. `users::` / `profiles::` are SELF-relative
  4053. // submodule prefixes (2018 edition) — `mod users;` makes `users` a child of
  4054. // the CURRENT module, NOT `crate::users`. Before the fix the bare prefix was
  4055. // resolved crate-relative only (looking for `src/users.rs`), so it found
  4056. // nothing and the handler modules looked dependent-less.
  4057. const http = path.join(tempDir, 'src/http');
  4058. fs.mkdirSync(http, { recursive: true });
  4059. fs.writeFileSync(path.join(tempDir, 'src/lib.rs'), `pub mod http;\n`);
  4060. fs.writeFileSync(
  4061. path.join(http, 'mod.rs'),
  4062. `mod users;\nmod profiles;\npub fn api_router() {\n users::router();\n profiles::router();\n}\n`
  4063. );
  4064. fs.writeFileSync(path.join(http, 'users.rs'), `pub fn router() -> i32 { 1 }\n`);
  4065. fs.writeFileSync(path.join(http, 'profiles.rs'), `pub fn router() -> i32 { 2 }\n`);
  4066. cg = CodeGraph.initSync(tempDir);
  4067. await cg.indexAll();
  4068. cg.resolveReferences();
  4069. // Each submodule's same-named `router` fn must get mod.rs as a dependent —
  4070. // proving the bare prefix resolved self-relative AND disambiguated the
  4071. // colliding `router` name to the correct file (not an arbitrary one).
  4072. const routers = cg.getNodesByKind('function').filter((n) => n.name === 'router');
  4073. const usersRouter = routers.find((n) => n.filePath.endsWith('http/users.rs'));
  4074. const profilesRouter = routers.find((n) => n.filePath.endsWith('http/profiles.rs'));
  4075. expect(usersRouter, 'users.rs router fn').toBeDefined();
  4076. expect(profilesRouter, 'profiles.rs router fn').toBeDefined();
  4077. const usersDeps = [...cg.getImpactRadius(usersRouter!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  4078. const profilesDeps = [...cg.getImpactRadius(profilesRouter!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  4079. expect(usersDeps.some((p) => p.endsWith('http/mod.rs')), 'users::router() lands on users.rs').toBe(true);
  4080. expect(profilesDeps.some((p) => p.endsWith('http/mod.rs')), 'profiles::router() lands on profiles.rs').toBe(true);
  4081. });
  4082. it('a 3-segment module-path call (`database::profiles::find()`) resolves to the leaf fn', async () => {
  4083. // A 2-level module path — the common `db.run(move |c| database::profiles::find(c))`
  4084. // / `crate::a::b::func()` shape. The reference-resolver pre-filter used to drop any
  4085. // `a::b::c` whose leaf it never checked (it tested only the first segment and the
  4086. // `b::c` remainder, neither of which names a symbol), so the call never reached the
  4087. // Rust path resolver and the leaf module looked dependent-less.
  4088. const routes = path.join(tempDir, 'src/routes');
  4089. const database = path.join(tempDir, 'src/database');
  4090. fs.mkdirSync(routes, { recursive: true });
  4091. fs.mkdirSync(database, { recursive: true });
  4092. fs.writeFileSync(path.join(tempDir, 'src/lib.rs'), `pub mod routes;\npub mod database;\n`);
  4093. fs.writeFileSync(path.join(database, 'mod.rs'), `pub mod profiles;\n`);
  4094. fs.writeFileSync(path.join(database, 'profiles.rs'), `pub fn find(id: i32) -> i32 { id }\n`);
  4095. fs.writeFileSync(
  4096. path.join(routes, 'mod.rs'),
  4097. `use crate::database;\npub fn get_profile(id: i32) -> i32 {\n database::profiles::find(id)\n}\n`
  4098. );
  4099. cg = CodeGraph.initSync(tempDir);
  4100. await cg.indexAll();
  4101. cg.resolveReferences();
  4102. const find = cg
  4103. .getNodesByKind('function')
  4104. .find((n) => n.name === 'find' && n.filePath.endsWith('database/profiles.rs'));
  4105. expect(find, 'database/profiles.rs find fn').toBeDefined();
  4106. const deps = [...cg.getImpactRadius(find!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  4107. expect(deps.some((p) => p.endsWith('routes/mod.rs')), 'database::profiles::find() resolves to the leaf fn').toBe(true);
  4108. });
  4109. it('Rocket `routes![…]` / `catchers![…]` macros link the mount to the handler fns', async () => {
  4110. // Tree-sitter leaves the macro body as a raw token tree, so the handler
  4111. // paths inside `routes![a::b::handler, …]` are invisible to the call walker
  4112. // and the handlers — mounted by Rocket at runtime, not called in-repo — look
  4113. // like they have no caller. The route-macro extractor reconstructs each path
  4114. // and emits a reference, which the Rust path resolver links to the handler.
  4115. const routes = path.join(tempDir, 'src/routes');
  4116. fs.mkdirSync(routes, { recursive: true });
  4117. fs.writeFileSync(path.join(tempDir, 'src/lib.rs'),
  4118. `mod routes;\nfn not_found() {}\npub fn rocket() {\n` +
  4119. ` rocket::build()\n` +
  4120. ` .mount("/api", routes![routes::users::post_users, routes::users::get_user])\n` +
  4121. ` .register("/", catchers![not_found]);\n}\n`);
  4122. fs.writeFileSync(path.join(routes, 'mod.rs'), `pub mod users;\n`);
  4123. fs.writeFileSync(path.join(routes, 'users.rs'), `pub fn post_users() {}\npub fn get_user() {}\n`);
  4124. cg = CodeGraph.initSync(tempDir);
  4125. await cg.indexAll();
  4126. cg.resolveReferences();
  4127. const handlers = cg.getNodesByKind('function').filter((n) => n.filePath.endsWith('routes/users.rs'));
  4128. expect(handlers.length, 'both handler fns indexed').toBe(2);
  4129. for (const h of handlers) {
  4130. const deps = [...cg.getImpactRadius(h.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  4131. expect(deps.some((p) => p.endsWith('lib.rs')), `routes![] links ${h.name} to its mount in lib.rs`).toBe(true);
  4132. }
  4133. });
  4134. });
  4135. describe('SvelteKit load → page synthesizer', () => {
  4136. let tempDir: string;
  4137. let cg: CodeGraph;
  4138. beforeEach(() => {
  4139. tempDir = createTempDir();
  4140. });
  4141. afterEach(() => {
  4142. if (cg) cg.close();
  4143. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  4144. });
  4145. it('links a +page.svelte to its OWN directory\'s +page.server.js load, not another route\'s', async () => {
  4146. // SvelteKit wires +page.server.js's `load` to +page.svelte's `data` BY FILE
  4147. // PATH — there is no static import — so editing a loader showed no impact on
  4148. // the page it feeds. The synthesizer links each page component to the `load`
  4149. // in its OWN directory (path-deterministic, so it never crosses routes).
  4150. const login = path.join(tempDir, 'src/routes/login');
  4151. const register = path.join(tempDir, 'src/routes/register');
  4152. fs.mkdirSync(login, { recursive: true });
  4153. fs.mkdirSync(register, { recursive: true });
  4154. fs.writeFileSync(path.join(login, '+page.svelte'), `<script>export let data;</script>\n<h1>Login {data.x}</h1>\n`);
  4155. fs.writeFileSync(path.join(login, '+page.server.js'), `export function load() { return { x: 1 }; }\n`);
  4156. fs.writeFileSync(path.join(register, '+page.svelte'), `<script>export let data;</script>\n<h1>Register</h1>\n`);
  4157. fs.writeFileSync(path.join(register, '+page.server.js'), `export function load() { return { y: 2 }; }\n`);
  4158. cg = CodeGraph.initSync(tempDir);
  4159. await cg.indexAll();
  4160. cg.resolveReferences();
  4161. const loginLoad = cg
  4162. .getNodesByKind('function')
  4163. .find((n) => n.name === 'load' && n.filePath.endsWith('login/+page.server.js'));
  4164. expect(loginLoad, 'login load fn').toBeDefined();
  4165. const impacted = [...cg.getImpactRadius(loginLoad!.id, 3).nodes.values()].map((n) => n.filePath ?? '');
  4166. // editing login's load surfaces login's page (the framework-wired data flow)…
  4167. expect(impacted.some((p) => p.endsWith('login/+page.svelte')), 'load links to its own page').toBe(true);
  4168. // …but never register's page (same-directory only).
  4169. expect(impacted.some((p) => p.endsWith('register/+page.svelte')), 'does not cross routes').toBe(false);
  4170. });
  4171. });
  4172. describe('Nuxt nested auto-imported component resolution', () => {
  4173. let tempDir: string;
  4174. let cg: CodeGraph;
  4175. beforeEach(() => {
  4176. tempDir = createTempDir();
  4177. });
  4178. afterEach(() => {
  4179. if (cg) cg.close();
  4180. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  4181. });
  4182. it('links a `<MediaCard/>` usage to components/media/Card.vue (Nuxt dir-prefixed auto-import)', async () => {
  4183. // Nuxt auto-imports a nested component by a DIRECTORY-PREFIXED name —
  4184. // components/media/Card.vue is used as <MediaCard/>, not <Card/> — but the
  4185. // component node is named by basename (`Card`), so the PascalCase usage
  4186. // didn't resolve and the nested component looked unused.
  4187. const media = path.join(tempDir, 'components/media');
  4188. fs.mkdirSync(media, { recursive: true });
  4189. fs.writeFileSync(path.join(media, 'Card.vue'), `<template><div>card</div></template>\n<script setup>defineProps(['item'])</script>\n`);
  4190. fs.writeFileSync(
  4191. path.join(tempDir, 'components/Grid.vue'),
  4192. `<template>\n <div><MediaCard :item="i" /></div>\n</template>\n<script setup>const i = {}</script>\n`
  4193. );
  4194. cg = CodeGraph.initSync(tempDir);
  4195. await cg.indexAll();
  4196. cg.resolveReferences();
  4197. const card = cg.getNodesByKind('component').find((n) => n.filePath.endsWith('media/Card.vue'));
  4198. expect(card, 'media/Card.vue component').toBeDefined();
  4199. const deps = [...cg.getImpactRadius(card!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  4200. expect(deps.some((p) => p.endsWith('components/Grid.vue')), '<MediaCard> links Grid to media/Card.vue').toBe(true);
  4201. });
  4202. });
  4203. describe('Swift property-wrapper attribute type references', () => {
  4204. let tempDir: string;
  4205. let cg: CodeGraph;
  4206. beforeEach(() => {
  4207. tempDir = createTempDir();
  4208. });
  4209. afterEach(() => {
  4210. if (cg) cg.close();
  4211. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  4212. });
  4213. it('a Fluent `@Siblings(through: Pivot.self)` links the model to the pivot type', async () => {
  4214. // A many-to-many pivot/join model is referenced ONLY through the relationship
  4215. // property wrapper's metatype argument (`Pivot.self`), never by a controller
  4216. // query. The wrapper type was captured but the argument expression wasn't
  4217. // walked, so the pivot model looked like nothing depended on it.
  4218. fs.writeFileSync(path.join(tempDir, 'Pivot.swift'),
  4219. `import Fluent\nfinal class AcronymCategoryPivot: Model {\n static let schema = "acronym-category"\n}\n`);
  4220. fs.writeFileSync(path.join(tempDir, 'Acronym.swift'),
  4221. `import Fluent\nfinal class Acronym: Model {\n` +
  4222. ` @Siblings(through: AcronymCategoryPivot.self, from: \\.$acronym, to: \\.$category)\n` +
  4223. ` var categories: [Category]\n}\n`);
  4224. cg = CodeGraph.initSync(tempDir);
  4225. await cg.indexAll();
  4226. cg.resolveReferences();
  4227. const pivot = cg.getNodesByKind('class').find((n) => n.name === 'AcronymCategoryPivot');
  4228. expect(pivot, 'pivot model class').toBeDefined();
  4229. const deps = [...cg.getImpactRadius(pivot!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  4230. expect(deps.some((p) => p.endsWith('Acronym.swift')), '@Siblings metatype arg links Acronym to the pivot').toBe(true);
  4231. });
  4232. });
  4233. describe('Objective-C messages, class receivers, and #import', () => {
  4234. let tempDir: string;
  4235. let cg: CodeGraph;
  4236. beforeEach(() => {
  4237. tempDir = createTempDir();
  4238. });
  4239. afterEach(() => {
  4240. if (cg) cg.close();
  4241. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  4242. });
  4243. it('resolves single-arg selectors, class-message receivers, and #import headers', async () => {
  4244. fs.writeFileSync(
  4245. path.join(tempDir, 'SDImageCache.h'),
  4246. `#import <Foundation/Foundation.h>
  4247. @interface SDImageCache : NSObject
  4248. + (instancetype)sharedCache;
  4249. + (void)storeImage:(NSString *)key;
  4250. @end
  4251. `
  4252. );
  4253. fs.writeFileSync(
  4254. path.join(tempDir, 'SDImageCache.m'),
  4255. `#import "SDImageCache.h"
  4256. @implementation SDImageCache
  4257. + (instancetype)sharedCache { return nil; }
  4258. + (void)storeImage:(NSString *)key { }
  4259. @end
  4260. `
  4261. );
  4262. fs.writeFileSync(
  4263. path.join(tempDir, 'SDManager.m'),
  4264. `#import "SDImageCache.h"
  4265. @interface SDManager : NSObject
  4266. @end
  4267. @implementation SDManager
  4268. - (void)run {
  4269. [SDImageCache sharedCache];
  4270. [SDImageCache storeImage:@"k"];
  4271. }
  4272. @end
  4273. `
  4274. );
  4275. cg = CodeGraph.initSync(tempDir);
  4276. await cg.indexAll();
  4277. cg.resolveReferences();
  4278. // 1. The single-argument selector `[SDImageCache storeImage:@"k"]` resolves
  4279. // to the `storeImage:` method — named WITH its colon both at the call site
  4280. // and the definition (before the fix the call site dropped the colon).
  4281. const storeImage = cg.getNodesByKind('method').find((n) => n.name === 'storeImage:');
  4282. expect(storeImage, 'storeImage: method').toBeDefined();
  4283. const storeCallers = [...cg.getImpactRadius(storeImage!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  4284. expect(storeCallers.some((p) => p.endsWith('SDManager.m'))).toBe(true);
  4285. // 2. The class-message receiver `[SDImageCache sharedCache]` references the
  4286. // SDImageCache class (whose @interface lives in the header).
  4287. const cache = cg.getNodesByKind('class').find((n) => n.name === 'SDImageCache');
  4288. expect(cache, 'SDImageCache class').toBeDefined();
  4289. const classDeps = [...cg.getImpactRadius(cache!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  4290. expect(classDeps.some((p) => p.endsWith('SDManager.m'))).toBe(true);
  4291. // 3. `#import "SDImageCache.h"` resolves to the header FILE — editing it
  4292. // surfaces both importers.
  4293. const header = cg.getNodesByKind('file').find((n) => n.filePath.endsWith('SDImageCache.h'));
  4294. expect(header, 'SDImageCache.h indexed').toBeDefined();
  4295. const importers = [...cg.getImpactRadius(header!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  4296. expect(importers.some((p) => p.endsWith('SDManager.m'))).toBe(true);
  4297. });
  4298. });
  4299. describe('Full Indexing', () => {
  4300. let tempDir: string;
  4301. beforeEach(() => {
  4302. tempDir = createTempDir();
  4303. });
  4304. afterEach(() => {
  4305. cleanupTempDir(tempDir);
  4306. });
  4307. it('should index a TypeScript file', async () => {
  4308. // Create test file
  4309. const srcDir = path.join(tempDir, 'src');
  4310. fs.mkdirSync(srcDir);
  4311. fs.writeFileSync(
  4312. path.join(srcDir, 'utils.ts'),
  4313. `
  4314. export function add(a: number, b: number): number {
  4315. return a + b;
  4316. }
  4317. export function multiply(a: number, b: number): number {
  4318. return a * b;
  4319. }
  4320. `
  4321. );
  4322. // Initialize and index
  4323. const cg = CodeGraph.initSync(tempDir);
  4324. const result = await cg.indexAll();
  4325. expect(result.success).toBe(true);
  4326. expect(result.filesIndexed).toBe(1);
  4327. expect(result.nodesCreated).toBeGreaterThanOrEqual(2);
  4328. // Check nodes were stored
  4329. const nodes = cg.getNodesInFile('src/utils.ts');
  4330. expect(nodes.length).toBeGreaterThanOrEqual(2);
  4331. const addFunc = nodes.find((n) => n.name === 'add');
  4332. expect(addFunc).toBeDefined();
  4333. expect(addFunc?.kind).toBe('function');
  4334. cg.close();
  4335. });
  4336. it('should index multiple files', async () => {
  4337. // Create test files
  4338. const srcDir = path.join(tempDir, 'src');
  4339. fs.mkdirSync(srcDir);
  4340. fs.writeFileSync(
  4341. path.join(srcDir, 'math.ts'),
  4342. `export function add(a: number, b: number) { return a + b; }`
  4343. );
  4344. fs.writeFileSync(
  4345. path.join(srcDir, 'string.ts'),
  4346. `export function capitalize(s: string) { return s.toUpperCase(); }`
  4347. );
  4348. // Initialize and index
  4349. const cg = CodeGraph.initSync(tempDir);
  4350. const result = await cg.indexAll();
  4351. expect(result.success).toBe(true);
  4352. expect(result.filesIndexed).toBe(2);
  4353. const files = cg.getFiles();
  4354. expect(files.length).toBe(2);
  4355. cg.close();
  4356. });
  4357. it('should track file hashes for incremental updates', async () => {
  4358. // Create initial file
  4359. const srcDir = path.join(tempDir, 'src');
  4360. fs.mkdirSync(srcDir);
  4361. fs.writeFileSync(path.join(srcDir, 'main.ts'), `export const x = 1;`);
  4362. // Initialize and index
  4363. const cg = CodeGraph.initSync(tempDir);
  4364. await cg.indexAll();
  4365. // Check file is tracked
  4366. const file = cg.getFile('src/main.ts');
  4367. expect(file).toBeDefined();
  4368. expect(file?.contentHash).toBeDefined();
  4369. // Modify file
  4370. fs.writeFileSync(path.join(srcDir, 'main.ts'), `export const x = 2;`);
  4371. // Check for changes
  4372. const changes = cg.getChangedFiles();
  4373. expect(changes.modified).toContain('src/main.ts');
  4374. cg.close();
  4375. });
  4376. it('should sync and detect changes', async () => {
  4377. // Create initial file
  4378. const srcDir = path.join(tempDir, 'src');
  4379. fs.mkdirSync(srcDir);
  4380. fs.writeFileSync(
  4381. path.join(srcDir, 'main.ts'),
  4382. `export function original() { return 1; }`
  4383. );
  4384. // Initialize and index
  4385. const cg = CodeGraph.initSync(tempDir);
  4386. await cg.indexAll();
  4387. const initialNodes = cg.getNodesInFile('src/main.ts');
  4388. expect(initialNodes.some((n) => n.name === 'original')).toBe(true);
  4389. // Modify file
  4390. fs.writeFileSync(
  4391. path.join(srcDir, 'main.ts'),
  4392. `export function updated() { return 2; }`
  4393. );
  4394. // Sync
  4395. const syncResult = await cg.sync();
  4396. expect(syncResult.filesModified).toBe(1);
  4397. // Check nodes were updated
  4398. const updatedNodes = cg.getNodesInFile('src/main.ts');
  4399. expect(updatedNodes.some((n) => n.name === 'updated')).toBe(true);
  4400. expect(updatedNodes.some((n) => n.name === 'original')).toBe(false);
  4401. cg.close();
  4402. });
  4403. it('should count file-level tracked YAML files as indexed', async () => {
  4404. fs.writeFileSync(path.join(tempDir, 'app.yaml'), 'name: test\n');
  4405. fs.writeFileSync(path.join(tempDir, 'routes.yml'), 'route: value\n');
  4406. const cg = CodeGraph.initSync(tempDir);
  4407. const result = await cg.indexAll();
  4408. expect(result.success).toBe(true);
  4409. expect(result.filesIndexed).toBe(2);
  4410. expect(result.filesSkipped).toBe(0);
  4411. expect(cg.getFiles().map((f) => f.path).sort()).toEqual(['app.yaml', 'routes.yml']);
  4412. cg.close();
  4413. });
  4414. it('should count file-level tracked YAML/Twig files as indexed in indexFiles()', async () => {
  4415. fs.writeFileSync(path.join(tempDir, 'app.yaml'), 'name: test\n');
  4416. fs.writeFileSync(path.join(tempDir, 'view.twig'), '{{ title }}\n');
  4417. const cg = CodeGraph.initSync(tempDir);
  4418. const result = await cg.indexFiles(['app.yaml', 'view.twig']);
  4419. expect(result.success).toBe(true);
  4420. expect(result.filesIndexed).toBe(2);
  4421. expect(result.filesSkipped).toBe(0);
  4422. const tracked = cg.getFiles().map((f) => `${f.path}:${f.language}`).sort();
  4423. expect(tracked).toEqual(['app.yaml:yaml', 'view.twig:twig']);
  4424. cg.close();
  4425. });
  4426. it('should count file-level tracked .properties files as indexed', async () => {
  4427. fs.writeFileSync(path.join(tempDir, 'application.properties'), 'server.port=8080\n');
  4428. fs.writeFileSync(path.join(tempDir, 'log.properties'), 'log.level=INFO\n');
  4429. const cg = CodeGraph.initSync(tempDir);
  4430. const result = await cg.indexAll();
  4431. expect(result.success).toBe(true);
  4432. expect(result.filesIndexed).toBe(2);
  4433. expect(result.filesSkipped).toBe(0);
  4434. cg.close();
  4435. });
  4436. it('should count the full file-level tracked class (yaml/twig/properties) in indexFiles()', async () => {
  4437. fs.writeFileSync(path.join(tempDir, 'app.yaml'), 'name: test\n');
  4438. fs.writeFileSync(path.join(tempDir, 'view.twig'), '{{ title }}\n');
  4439. fs.writeFileSync(path.join(tempDir, 'application.properties'), 'server.port=8080\n');
  4440. const cg = CodeGraph.initSync(tempDir);
  4441. const result = await cg.indexFiles(['app.yaml', 'view.twig', 'application.properties']);
  4442. expect(result.success).toBe(true);
  4443. expect(result.filesIndexed).toBe(3);
  4444. expect(result.filesSkipped).toBe(0);
  4445. const tracked = cg.getFiles().map((f) => `${f.path}:${f.language}`).sort();
  4446. expect(tracked).toEqual(['app.yaml:yaml', 'application.properties:properties', 'view.twig:twig']);
  4447. cg.close();
  4448. });
  4449. });
  4450. describe('Path Normalization', () => {
  4451. it('should convert backslashes to forward slashes', () => {
  4452. expect(normalizePath('gui\\node_modules\\foo')).toBe('gui/node_modules/foo');
  4453. expect(normalizePath('src\\components\\Button.tsx')).toBe('src/components/Button.tsx');
  4454. });
  4455. it('should leave forward-slash paths unchanged', () => {
  4456. expect(normalizePath('src/components/Button.tsx')).toBe('src/components/Button.tsx');
  4457. });
  4458. it('should handle empty string', () => {
  4459. expect(normalizePath('')).toBe('');
  4460. });
  4461. });
  4462. describe('Directory Exclusion', () => {
  4463. let tempDir: string;
  4464. beforeEach(() => {
  4465. tempDir = createTempDir();
  4466. });
  4467. afterEach(() => {
  4468. cleanupTempDir(tempDir);
  4469. });
  4470. it('should exclude directories listed in .gitignore', () => {
  4471. // Create structure: src/index.ts + node_modules/pkg/index.js, gitignore node_modules
  4472. const srcDir = path.join(tempDir, 'src');
  4473. const nmDir = path.join(tempDir, 'node_modules', 'pkg');
  4474. fs.mkdirSync(srcDir, { recursive: true });
  4475. fs.mkdirSync(nmDir, { recursive: true });
  4476. fs.writeFileSync(path.join(srcDir, 'index.ts'), 'export const x = 1;');
  4477. fs.writeFileSync(path.join(nmDir, 'index.js'), 'module.exports = {};');
  4478. fs.writeFileSync(path.join(tempDir, '.gitignore'), 'node_modules/\n');
  4479. const files = scanDirectory(tempDir);
  4480. expect(files).toContain('src/index.ts');
  4481. expect(files.every((f) => !f.includes('node_modules'))).toBe(true);
  4482. });
  4483. it('should exclude nested node_modules via a root .gitignore', () => {
  4484. // A trailing-slash pattern with no leading slash matches at any depth.
  4485. const srcDir = path.join(tempDir, 'packages', 'app', 'src');
  4486. const nmDir = path.join(tempDir, 'packages', 'app', 'node_modules', 'pkg');
  4487. fs.mkdirSync(srcDir, { recursive: true });
  4488. fs.mkdirSync(nmDir, { recursive: true });
  4489. fs.writeFileSync(path.join(srcDir, 'index.ts'), 'export const x = 1;');
  4490. fs.writeFileSync(path.join(nmDir, 'index.js'), 'module.exports = {};');
  4491. fs.writeFileSync(path.join(tempDir, '.gitignore'), 'node_modules/\n');
  4492. const files = scanDirectory(tempDir);
  4493. expect(files).toContain('packages/app/src/index.ts');
  4494. expect(files.every((f) => !f.includes('node_modules'))).toBe(true);
  4495. });
  4496. it('should apply a nested .gitignore only to its own subtree', () => {
  4497. const appSrc = path.join(tempDir, 'app', 'src');
  4498. fs.mkdirSync(appSrc, { recursive: true });
  4499. fs.writeFileSync(path.join(appSrc, 'keep.ts'), 'export const a = 1;');
  4500. fs.writeFileSync(path.join(appSrc, 'skip.ts'), 'export const b = 2;');
  4501. fs.writeFileSync(path.join(tempDir, 'app', '.gitignore'), 'src/skip.ts\n');
  4502. // A sibling with the same name outside app/ must NOT be ignored.
  4503. const otherDir = path.join(tempDir, 'other', 'src');
  4504. fs.mkdirSync(otherDir, { recursive: true });
  4505. fs.writeFileSync(path.join(otherDir, 'skip.ts'), 'export const c = 3;');
  4506. const files = scanDirectory(tempDir);
  4507. expect(files).toContain('app/src/keep.ts');
  4508. expect(files).not.toContain('app/src/skip.ts');
  4509. expect(files).toContain('other/src/skip.ts');
  4510. });
  4511. it('should always skip .git directories', () => {
  4512. const srcDir = path.join(tempDir, 'src');
  4513. const gitDir = path.join(tempDir, '.git', 'objects');
  4514. fs.mkdirSync(srcDir, { recursive: true });
  4515. fs.mkdirSync(gitDir, { recursive: true });
  4516. fs.writeFileSync(path.join(srcDir, 'index.ts'), 'export const x = 1;');
  4517. fs.writeFileSync(path.join(gitDir, 'pack.ts'), 'export const y = 2;');
  4518. const files = scanDirectory(tempDir);
  4519. expect(files).toContain('src/index.ts');
  4520. expect(files.every((f) => !f.includes('.git'))).toBe(true);
  4521. });
  4522. it('should return forward-slash paths on all platforms', () => {
  4523. const srcDir = path.join(tempDir, 'src', 'components');
  4524. fs.mkdirSync(srcDir, { recursive: true });
  4525. fs.writeFileSync(path.join(srcDir, 'Button.tsx'), 'export function Button() {}');
  4526. const files = scanDirectory(tempDir);
  4527. expect(files.length).toBe(1);
  4528. expect(files[0]).toBe('src/components/Button.tsx');
  4529. expect(files[0]).not.toContain('\\');
  4530. });
  4531. });
  4532. describe('Git Submodules', () => {
  4533. let tempDir: string;
  4534. beforeEach(() => {
  4535. tempDir = createTempDir();
  4536. });
  4537. afterEach(() => {
  4538. cleanupTempDir(tempDir);
  4539. });
  4540. it('should index files inside git submodules (issue #147)', async () => {
  4541. const { execFileSync } = await import('child_process');
  4542. const git = (cwd: string, ...args: string[]) =>
  4543. execFileSync('git', args, { cwd, stdio: 'pipe' });
  4544. // Build a separate "library" repo to use as a submodule source.
  4545. const libDir = path.join(tempDir, '_lib');
  4546. fs.mkdirSync(libDir, { recursive: true });
  4547. git(libDir, 'init', '-q');
  4548. git(libDir, 'config', 'user.email', 'test@test.com');
  4549. git(libDir, 'config', 'user.name', 'Test');
  4550. fs.writeFileSync(path.join(libDir, 'lib.ts'), 'export const fromSubmodule = 1;');
  4551. git(libDir, 'add', '-A');
  4552. git(libDir, 'commit', '-q', '-m', 'lib init');
  4553. // Build the main repo and add the lib repo as a submodule.
  4554. const mainDir = path.join(tempDir, 'main');
  4555. fs.mkdirSync(mainDir, { recursive: true });
  4556. git(mainDir, 'init', '-q');
  4557. git(mainDir, 'config', 'user.email', 'test@test.com');
  4558. git(mainDir, 'config', 'user.name', 'Test');
  4559. fs.writeFileSync(path.join(mainDir, 'app.ts'), 'export const app = 1;');
  4560. git(mainDir, 'add', '-A');
  4561. git(mainDir, 'commit', '-q', '-m', 'app init');
  4562. // protocol.file.allow=always is required to add a local-path submodule on
  4563. // recent git versions (CVE-2022-39253 mitigation).
  4564. execFileSync(
  4565. 'git',
  4566. ['-c', 'protocol.file.allow=always', 'submodule', 'add', '-q', libDir, 'libs/lib'],
  4567. { cwd: mainDir, stdio: 'pipe' }
  4568. );
  4569. git(mainDir, 'commit', '-q', '-m', 'add submodule');
  4570. const files = scanDirectory(mainDir);
  4571. expect(files).toContain('app.ts');
  4572. expect(files).toContain('libs/lib/lib.ts');
  4573. });
  4574. });
  4575. describe('Nested non-submodule git repos', () => {
  4576. let tempDir: string;
  4577. beforeEach(() => {
  4578. tempDir = createTempDir();
  4579. });
  4580. afterEach(() => {
  4581. cleanupTempDir(tempDir);
  4582. });
  4583. it('should index files in embedded git repos run from a git super-repo (issue #193)', async () => {
  4584. const { execFileSync } = await import('child_process');
  4585. const git = (cwd: string, ...args: string[]) =>
  4586. execFileSync('git', args, { cwd, stdio: 'pipe' });
  4587. // Top-level workspace is itself a git repo, holding no source directly —
  4588. // the CMake "super-repo" layout from the issue.
  4589. const root = path.join(tempDir, 'root');
  4590. fs.mkdirSync(path.join(root, 'coding'), { recursive: true });
  4591. git(root, 'init', '-q');
  4592. git(root, 'config', 'user.email', 'test@test.com');
  4593. git(root, 'config', 'user.name', 'Test');
  4594. fs.writeFileSync(path.join(root, 'CMakeLists.txt'), 'cmake_minimum_required(VERSION 3.10)\n');
  4595. // Two independent clones living inside the workspace (NOT submodules):
  4596. // one with committed source, one with only untracked source.
  4597. const sub1 = path.join(root, 'sub_repo1', 'src');
  4598. fs.mkdirSync(sub1, { recursive: true });
  4599. git(path.join(root, 'sub_repo1'), 'init', '-q');
  4600. git(path.join(root, 'sub_repo1'), 'config', 'user.email', 'test@test.com');
  4601. git(path.join(root, 'sub_repo1'), 'config', 'user.name', 'Test');
  4602. fs.writeFileSync(path.join(sub1, 'one.ts'), 'export const one = 1;');
  4603. git(path.join(root, 'sub_repo1'), 'add', '-A');
  4604. git(path.join(root, 'sub_repo1'), 'commit', '-q', '-m', 'sub1 init');
  4605. const sub2 = path.join(root, 'sub_repo2', 'src');
  4606. fs.mkdirSync(sub2, { recursive: true });
  4607. git(path.join(root, 'sub_repo2'), 'init', '-q');
  4608. fs.writeFileSync(path.join(sub2, 'two.ts'), 'export const two = 2;');
  4609. const files = scanDirectory(root);
  4610. // Both committed and untracked source from the nested repos must be found.
  4611. expect(files).toContain('sub_repo1/src/one.ts');
  4612. expect(files).toContain('sub_repo2/src/two.ts');
  4613. });
  4614. it('should respect each embedded repo\'s own .gitignore', async () => {
  4615. const { execFileSync } = await import('child_process');
  4616. const git = (cwd: string, ...args: string[]) =>
  4617. execFileSync('git', args, { cwd, stdio: 'pipe' });
  4618. const root = path.join(tempDir, 'root');
  4619. fs.mkdirSync(root, { recursive: true });
  4620. git(root, 'init', '-q');
  4621. const sub = path.join(root, 'sub_repo', 'src');
  4622. fs.mkdirSync(sub, { recursive: true });
  4623. git(path.join(root, 'sub_repo'), 'init', '-q');
  4624. fs.writeFileSync(path.join(root, 'sub_repo', '.gitignore'), 'src/generated.ts\n');
  4625. fs.writeFileSync(path.join(sub, 'real.ts'), 'export const real = 1;');
  4626. fs.writeFileSync(path.join(sub, 'generated.ts'), 'export const generated = 1;');
  4627. const files = scanDirectory(root);
  4628. expect(files).toContain('sub_repo/src/real.ts');
  4629. expect(files).not.toContain('sub_repo/src/generated.ts');
  4630. });
  4631. // A .gitignore the `ignore` library can't compile to a regex must not abort
  4632. // the whole scan — the bad pattern is dropped, valid ones still apply (#682).
  4633. it('does not crash on a .gitignore with an uncompilable pattern (#682)', () => {
  4634. fs.mkdirSync(path.join(tempDir, 'src'), { recursive: true });
  4635. fs.mkdirSync(path.join(tempDir, 'build'), { recursive: true });
  4636. fs.writeFileSync(path.join(tempDir, 'src', 'real.ts'), 'export const x = 1;');
  4637. fs.writeFileSync(path.join(tempDir, 'build', 'out.ts'), 'export const y = 2;');
  4638. // `\\[` makes the matcher build an unterminated character class — the throw
  4639. // is lazy (at match time), which is what escaped and killed sync.
  4640. fs.writeFileSync(path.join(tempDir, '.gitignore'), 'build/\n\\\\[\n');
  4641. let files: string[] = [];
  4642. expect(() => {
  4643. files = scanDirectory(tempDir);
  4644. }).not.toThrow();
  4645. expect(files).toContain('src/real.ts');
  4646. // The still-valid `build/` rule is honored; only the bad line was dropped.
  4647. expect(files.some((f) => f.startsWith('build/'))).toBe(false);
  4648. });
  4649. // A .gitignore that isn't valid UTF-8 — e.g. encrypted in place by corporate
  4650. // DLP / endpoint software (UTF-16 header + ciphertext) — is skipped whole,
  4651. // not fed to the matcher as garbage patterns (#682).
  4652. it('does not crash on a non-UTF-8 (DLP-encrypted) .gitignore (#682)', () => {
  4653. fs.mkdirSync(path.join(tempDir, 'src'), { recursive: true });
  4654. fs.writeFileSync(path.join(tempDir, 'src', 'real.ts'), 'export const x = 1;');
  4655. const header = Buffer.concat([
  4656. Buffer.from([0x00, 0x00]),
  4657. Buffer.from('[notice][user]', 'utf16le'),
  4658. ]);
  4659. const junk = Buffer.from([0x5b, 0x99, 0xc3, 0x28, 0x5c, 0x5b, 0xff, 0xfd]);
  4660. fs.writeFileSync(path.join(tempDir, '.gitignore'), Buffer.concat([header, junk]));
  4661. let files: string[] = [];
  4662. expect(() => {
  4663. files = scanDirectory(tempDir);
  4664. }).not.toThrow();
  4665. expect(files).toContain('src/real.ts');
  4666. });
  4667. it('buildDefaultIgnore survives a bad .gitignore and still applies valid rules (#682)', () => {
  4668. fs.writeFileSync(path.join(tempDir, '.gitignore'), 'dist/\n\\\\[\n');
  4669. const ig = buildDefaultIgnore(tempDir);
  4670. expect(() => ig.ignores('src/app.ts')).not.toThrow();
  4671. expect(ig.ignores('dist/')).toBe(true); // valid rule survives
  4672. expect(ig.ignores('src/app.ts')).toBe(false);
  4673. });
  4674. });
  4675. // =============================================================================
  4676. // Scala
  4677. // =============================================================================
  4678. describe('Scala Extraction', () => {
  4679. describe('Language detection', () => {
  4680. it('should detect Scala files', () => {
  4681. expect(detectLanguage('Main.scala')).toBe('scala');
  4682. expect(detectLanguage('script.sc')).toBe('scala');
  4683. expect(detectLanguage('src/UserService.scala')).toBe('scala');
  4684. });
  4685. it('should report Scala as supported', () => {
  4686. expect(isLanguageSupported('scala')).toBe(true);
  4687. expect(getSupportedLanguages()).toContain('scala');
  4688. });
  4689. });
  4690. describe('Class extraction', () => {
  4691. it('should extract class definitions', () => {
  4692. const code = `
  4693. class UserService(private val repo: UserRepository) {
  4694. def findUser(id: String): Option[String] = Some(id)
  4695. }
  4696. `;
  4697. const result = extractFromSource('UserService.scala', code);
  4698. const cls = result.nodes.find((n) => n.kind === 'class' && n.name === 'UserService');
  4699. expect(cls).toBeDefined();
  4700. expect(cls?.language).toBe('scala');
  4701. });
  4702. it('should extract object definitions as class kind', () => {
  4703. const code = `
  4704. object DatabaseConfig {
  4705. val url = "jdbc:postgresql://localhost/mydb"
  4706. }
  4707. `;
  4708. const result = extractFromSource('Config.scala', code);
  4709. const obj = result.nodes.find((n) => n.kind === 'class' && n.name === 'DatabaseConfig');
  4710. expect(obj).toBeDefined();
  4711. });
  4712. it('should extract trait definitions as trait kind', () => {
  4713. const code = `
  4714. trait Repository[A] {
  4715. def findById(id: String): Option[A]
  4716. def save(entity: A): Unit
  4717. }
  4718. `;
  4719. const result = extractFromSource('Repository.scala', code);
  4720. const trait_ = result.nodes.find((n) => n.kind === 'trait' && n.name === 'Repository');
  4721. expect(trait_).toBeDefined();
  4722. });
  4723. });
  4724. describe('Method and function extraction', () => {
  4725. it('should extract method definitions inside a class', () => {
  4726. const code = `
  4727. class Calculator {
  4728. def add(a: Int, b: Int): Int = a + b
  4729. def divide(a: Double, b: Double): Double = a / b
  4730. }
  4731. `;
  4732. const result = extractFromSource('Calculator.scala', code);
  4733. const methods = result.nodes.filter((n) => n.kind === 'method');
  4734. expect(methods.find((m) => m.name === 'add')).toBeDefined();
  4735. expect(methods.find((m) => m.name === 'divide')).toBeDefined();
  4736. });
  4737. it('should extract method signatures', () => {
  4738. const code = `
  4739. class Greeter {
  4740. def greet(name: String): String = s"Hello, \${name}!"
  4741. }
  4742. `;
  4743. const result = extractFromSource('Greeter.scala', code);
  4744. const method = result.nodes.find((n) => n.name === 'greet');
  4745. expect(method?.signature).toContain('name: String');
  4746. expect(method?.signature).toContain('String');
  4747. });
  4748. it('should extract top-level function definitions as functions', () => {
  4749. const code = `
  4750. def factorial(n: Int): Int = if (n <= 1) 1 else n * factorial(n - 1)
  4751. def greet(name: String): String = s"Hello, \${name}!"
  4752. `;
  4753. const result = extractFromSource('utils.scala', code);
  4754. const fns = result.nodes.filter((n) => n.kind === 'function');
  4755. expect(fns.find((f) => f.name === 'factorial')).toBeDefined();
  4756. expect(fns.find((f) => f.name === 'greet')).toBeDefined();
  4757. });
  4758. });
  4759. describe('Val and var extraction', () => {
  4760. it('should extract val inside a class as field', () => {
  4761. const code = `
  4762. class Config {
  4763. val timeout: Int = 30
  4764. val host: String = "localhost"
  4765. }
  4766. `;
  4767. const result = extractFromSource('Config.scala', code);
  4768. const fields = result.nodes.filter((n) => n.kind === 'field');
  4769. expect(fields.find((f) => f.name === 'timeout')).toBeDefined();
  4770. expect(fields.find((f) => f.name === 'host')).toBeDefined();
  4771. });
  4772. it('should extract var inside a class as field', () => {
  4773. const code = `
  4774. class Counter {
  4775. var count: Int = 0
  4776. }
  4777. `;
  4778. const result = extractFromSource('Counter.scala', code);
  4779. const field = result.nodes.find((n) => n.kind === 'field' && n.name === 'count');
  4780. expect(field).toBeDefined();
  4781. });
  4782. it('should extract top-level val as constant', () => {
  4783. const code = `
  4784. val MaxConnections: Int = 100
  4785. val DefaultTimeout = 30
  4786. `;
  4787. const result = extractFromSource('constants.scala', code);
  4788. const consts = result.nodes.filter((n) => n.kind === 'constant');
  4789. expect(consts.find((c) => c.name === 'MaxConnections')).toBeDefined();
  4790. });
  4791. it('should extract top-level var as variable', () => {
  4792. const code = `
  4793. var retries: Int = 3
  4794. `;
  4795. const result = extractFromSource('state.scala', code);
  4796. const v = result.nodes.find((n) => n.kind === 'variable' && n.name === 'retries');
  4797. expect(v).toBeDefined();
  4798. });
  4799. it('should include type in val/var signature', () => {
  4800. const code = `
  4801. class Service {
  4802. val timeout: Int = 30
  4803. }
  4804. `;
  4805. const result = extractFromSource('Service.scala', code);
  4806. const field = result.nodes.find((n) => n.name === 'timeout');
  4807. expect(field?.signature).toContain('timeout');
  4808. expect(field?.signature).toContain('Int');
  4809. });
  4810. });
  4811. describe('Enum extraction', () => {
  4812. it('should extract enum definitions', () => {
  4813. const code = `
  4814. enum Color:
  4815. case Red
  4816. case Green
  4817. case Blue
  4818. `;
  4819. const result = extractFromSource('Color.scala', code);
  4820. const enumNode = result.nodes.find((n) => n.kind === 'enum' && n.name === 'Color');
  4821. expect(enumNode).toBeDefined();
  4822. });
  4823. it('should extract enum cases as enum_member', () => {
  4824. const code = `
  4825. enum Direction:
  4826. case North
  4827. case South
  4828. case East
  4829. case West
  4830. `;
  4831. const result = extractFromSource('Direction.scala', code);
  4832. const members = result.nodes.filter((n) => n.kind === 'enum_member');
  4833. expect(members.find((m) => m.name === 'North')).toBeDefined();
  4834. expect(members.find((m) => m.name === 'South')).toBeDefined();
  4835. expect(members.length).toBeGreaterThanOrEqual(4);
  4836. });
  4837. });
  4838. describe('Type alias extraction', () => {
  4839. it('should extract type aliases', () => {
  4840. const code = `
  4841. type UserId = String
  4842. type UserMap = Map[String, String]
  4843. `;
  4844. const result = extractFromSource('types.scala', code);
  4845. const aliases = result.nodes.filter((n) => n.kind === 'type_alias');
  4846. expect(aliases.find((a) => a.name === 'UserId')).toBeDefined();
  4847. expect(aliases.find((a) => a.name === 'UserMap')).toBeDefined();
  4848. });
  4849. });
  4850. describe('Import extraction', () => {
  4851. it('should extract import declarations', () => {
  4852. const code = `
  4853. import scala.collection.mutable.ListBuffer
  4854. import scala.concurrent.Future
  4855. `;
  4856. const result = extractFromSource('imports.scala', code);
  4857. const imports = result.nodes.filter((n) => n.kind === 'import');
  4858. expect(imports.length).toBeGreaterThanOrEqual(2);
  4859. });
  4860. });
  4861. describe('Visibility modifiers', () => {
  4862. it('should extract private visibility', () => {
  4863. const code = `
  4864. class Service {
  4865. private val secret: String = "abc"
  4866. private def helper(): Unit = {}
  4867. }
  4868. `;
  4869. const result = extractFromSource('Service.scala', code);
  4870. const secretField = result.nodes.find((n) => n.name === 'secret');
  4871. expect(secretField?.visibility).toBe('private');
  4872. const helperMethod = result.nodes.find((n) => n.name === 'helper');
  4873. expect(helperMethod?.visibility).toBe('private');
  4874. });
  4875. it('should extract protected visibility', () => {
  4876. const code = `
  4877. class Base {
  4878. protected def helperMethod(): Unit = {}
  4879. }
  4880. `;
  4881. const result = extractFromSource('Base.scala', code);
  4882. const method = result.nodes.find((n) => n.name === 'helperMethod');
  4883. expect(method?.visibility).toBe('protected');
  4884. });
  4885. it('should default to public visibility', () => {
  4886. const code = `
  4887. class Greeter {
  4888. def hello(): Unit = {}
  4889. }
  4890. `;
  4891. const result = extractFromSource('Greeter.scala', code);
  4892. const method = result.nodes.find((n) => n.name === 'hello');
  4893. expect(method?.visibility).toBe('public');
  4894. });
  4895. });
  4896. describe('Inheritance', () => {
  4897. it('should extract extends relationships', () => {
  4898. const code = `
  4899. class AdminUser extends User {
  4900. def adminAction(): Unit = {}
  4901. }
  4902. `;
  4903. const result = extractFromSource('AdminUser.scala', code);
  4904. const extendsRefs = result.unresolvedReferences.filter((r) => r.referenceKind === 'extends');
  4905. expect(extendsRefs.find((r) => r.referenceName === 'User')).toBeDefined();
  4906. });
  4907. });
  4908. describe('Call extraction', () => {
  4909. it('should extract function call expressions', () => {
  4910. const code = `
  4911. def processData(): Unit = {
  4912. val result = computeResult()
  4913. println(result)
  4914. }
  4915. `;
  4916. const result = extractFromSource('processor.scala', code);
  4917. const calls = result.unresolvedReferences.filter((r) => r.referenceKind === 'calls');
  4918. expect(calls.length).toBeGreaterThan(0);
  4919. });
  4920. });
  4921. });
  4922. describe('Vue Extraction', () => {
  4923. it('should detect Vue files', () => {
  4924. expect(detectLanguage('App.vue')).toBe('vue');
  4925. expect(detectLanguage('components/Button.vue')).toBe('vue');
  4926. expect(isLanguageSupported('vue')).toBe(true);
  4927. });
  4928. it('should extract component node from a Vue SFC', () => {
  4929. const code = `<template>
  4930. <div>{{ message }}</div>
  4931. </template>
  4932. <script>
  4933. export default {
  4934. data() {
  4935. return { message: 'Hello' };
  4936. }
  4937. }
  4938. </script>
  4939. `;
  4940. const result = extractFromSource('HelloWorld.vue', code);
  4941. const componentNode = result.nodes.find((n) => n.kind === 'component');
  4942. expect(componentNode).toBeDefined();
  4943. expect(componentNode?.name).toBe('HelloWorld');
  4944. expect(componentNode?.language).toBe('vue');
  4945. expect(componentNode?.isExported).toBe(true);
  4946. });
  4947. it('should extract functions from <script> block', () => {
  4948. const code = `<template>
  4949. <button @click="handleClick">Click</button>
  4950. </template>
  4951. <script>
  4952. function handleClick() {
  4953. console.log('clicked');
  4954. }
  4955. const count = 0;
  4956. </script>
  4957. `;
  4958. const result = extractFromSource('Button.vue', code);
  4959. const componentNode = result.nodes.find((n) => n.kind === 'component');
  4960. expect(componentNode).toBeDefined();
  4961. expect(componentNode?.name).toBe('Button');
  4962. const funcNode = result.nodes.find((n) => n.kind === 'function' && n.name === 'handleClick');
  4963. expect(funcNode).toBeDefined();
  4964. expect(funcNode?.language).toBe('vue');
  4965. });
  4966. it('should extract from <script setup lang="ts"> block', () => {
  4967. const code = `<template>
  4968. <div>{{ count }}</div>
  4969. </template>
  4970. <script setup lang="ts">
  4971. import { ref } from 'vue';
  4972. const count = ref(0);
  4973. function increment(): void {
  4974. count.value++;
  4975. }
  4976. </script>
  4977. `;
  4978. const result = extractFromSource('Counter.vue', code);
  4979. const componentNode = result.nodes.find((n) => n.kind === 'component');
  4980. expect(componentNode).toBeDefined();
  4981. expect(componentNode?.name).toBe('Counter');
  4982. const funcNode = result.nodes.find((n) => n.kind === 'function' && n.name === 'increment');
  4983. expect(funcNode).toBeDefined();
  4984. expect(funcNode?.language).toBe('vue');
  4985. // All nodes should be marked as vue language
  4986. for (const node of result.nodes) {
  4987. expect(node.language).toBe('vue');
  4988. }
  4989. });
  4990. it('should extract calls from top-level <script setup> initializers', () => {
  4991. const code = `<template>
  4992. <div>{{ token }}</div>
  4993. </template>
  4994. <script setup lang="ts">
  4995. import { getTokenMp } from './api/upload';
  4996. const token = getTokenMp();
  4997. </script>
  4998. `;
  4999. const result = extractFromSource('Issue425Setup.vue', code);
  5000. const call = result.unresolvedReferences.find(
  5001. (ref) => ref.referenceKind === 'calls' && ref.referenceName === 'getTokenMp'
  5002. );
  5003. expect(call).toBeDefined();
  5004. });
  5005. it('should extract calls from Vue Options API object methods', () => {
  5006. const code = `<template>
  5007. <button @click="save">Save</button>
  5008. </template>
  5009. <script>
  5010. import { getTokenMp } from './api/upload';
  5011. export default {
  5012. methods: {
  5013. save() {
  5014. return getTokenMp();
  5015. }
  5016. },
  5017. setup() {
  5018. return getTokenMp();
  5019. }
  5020. }
  5021. </script>
  5022. `;
  5023. const result = extractFromSource('Issue425Options.vue', code);
  5024. const calls = result.unresolvedReferences.filter(
  5025. (ref) => ref.referenceKind === 'calls' && ref.referenceName === 'getTokenMp'
  5026. );
  5027. expect(calls).toHaveLength(2);
  5028. });
  5029. it('should extract component usages from the Vue template (PascalCase + kebab, skipping built-ins) (#629)', () => {
  5030. const code = `<template>
  5031. <div class="wrap">
  5032. <UserCard :user="u" />
  5033. <my-button>Click</my-button>
  5034. <Transition><span>x</span></Transition>
  5035. </div>
  5036. </template>
  5037. <script setup lang="ts">
  5038. import UserCard from './UserCard.vue';
  5039. import MyButton from './MyButton.vue';
  5040. </script>
  5041. `;
  5042. const result = extractFromSource('Host.vue', code);
  5043. const refs = result.unresolvedReferences
  5044. .filter((r) => r.referenceKind === 'references')
  5045. .map((r) => r.referenceName);
  5046. expect(refs).toContain('UserCard'); // PascalCase tag
  5047. expect(refs).toContain('MyButton'); // kebab <my-button> → MyButton
  5048. expect(refs).not.toContain('Transition'); // Vue built-in skipped
  5049. expect(refs).not.toContain('Div'); // native HTML element skipped
  5050. expect(refs).not.toContain('Span');
  5051. });
  5052. it('should extract from both <script> and <script setup> blocks', () => {
  5053. const code = `<template>
  5054. <div>{{ msg }}</div>
  5055. </template>
  5056. <script>
  5057. export default {
  5058. name: 'DualScript'
  5059. }
  5060. </script>
  5061. <script setup>
  5062. const msg = 'hello';
  5063. function greet() {
  5064. return msg;
  5065. }
  5066. </script>
  5067. `;
  5068. const result = extractFromSource('DualScript.vue', code);
  5069. const componentNode = result.nodes.find((n) => n.kind === 'component');
  5070. expect(componentNode).toBeDefined();
  5071. const greetFunc = result.nodes.find((n) => n.kind === 'function' && n.name === 'greet');
  5072. expect(greetFunc).toBeDefined();
  5073. });
  5074. it('should create component node for template-only Vue file', () => {
  5075. const code = `<template>
  5076. <div>Static content</div>
  5077. </template>
  5078. `;
  5079. const result = extractFromSource('Static.vue', code);
  5080. const componentNode = result.nodes.find((n) => n.kind === 'component');
  5081. expect(componentNode).toBeDefined();
  5082. expect(componentNode?.name).toBe('Static');
  5083. expect(componentNode?.language).toBe('vue');
  5084. // Only the component node should exist (no script nodes)
  5085. expect(result.nodes.length).toBe(1);
  5086. });
  5087. it('should create containment edges from component to script nodes', () => {
  5088. const code = `<template>
  5089. <div>{{ value }}</div>
  5090. </template>
  5091. <script setup lang="ts">
  5092. const value = 42;
  5093. </script>
  5094. `;
  5095. const result = extractFromSource('Contained.vue', code);
  5096. const componentNode = result.nodes.find((n) => n.kind === 'component');
  5097. expect(componentNode).toBeDefined();
  5098. // Should have containment edges from component to child nodes
  5099. const containEdges = result.edges.filter(
  5100. (e) => e.source === componentNode!.id && e.kind === 'contains'
  5101. );
  5102. expect(containEdges.length).toBeGreaterThan(0);
  5103. });
  5104. });
  5105. describe('Astro Extraction', () => {
  5106. it('should detect Astro files', () => {
  5107. expect(detectLanguage('src/pages/index.astro')).toBe('astro');
  5108. expect(detectLanguage('Layout.astro')).toBe('astro');
  5109. expect(isLanguageSupported('astro')).toBe(true);
  5110. });
  5111. it('should extract component node from an .astro file', () => {
  5112. const code = `---
  5113. const title = 'Hello';
  5114. ---
  5115. <h1>{title}</h1>
  5116. `;
  5117. const result = extractFromSource('Card.astro', code);
  5118. const componentNode = result.nodes.find((n) => n.kind === 'component');
  5119. expect(componentNode).toBeDefined();
  5120. expect(componentNode?.name).toBe('Card');
  5121. expect(componentNode?.language).toBe('astro');
  5122. expect(componentNode?.isExported).toBe(true);
  5123. });
  5124. it('should extract frontmatter symbols with correct line numbers (#768)', () => {
  5125. const code = `---
  5126. import { formatDate } from '../utils/format';
  5127. function getIconNode(name: string): string {
  5128. return name;
  5129. }
  5130. const { title } = Astro.props;
  5131. ---
  5132. <span>{title}</span>
  5133. `;
  5134. const result = extractFromSource('navs.astro', code);
  5135. // The #768 repro: a function defined in frontmatter must be found
  5136. const fn = result.nodes.find((n) => n.kind === 'function' && n.name === 'getIconNode');
  5137. expect(fn).toBeDefined();
  5138. expect(fn?.language).toBe('astro');
  5139. expect(fn?.startLine).toBe(4);
  5140. const imp = result.nodes.find((n) => n.kind === 'import');
  5141. expect(imp).toBeDefined();
  5142. expect(imp?.startLine).toBe(2);
  5143. });
  5144. it('should extract exported getStaticPaths from frontmatter', () => {
  5145. const code = `---
  5146. export async function getStaticPaths() {
  5147. return [];
  5148. }
  5149. const { slug } = Astro.params;
  5150. ---
  5151. <p>{slug}</p>
  5152. `;
  5153. const result = extractFromSource('[slug].astro', code);
  5154. const fn = result.nodes.find((n) => n.kind === 'function' && n.name === 'getStaticPaths');
  5155. expect(fn).toBeDefined();
  5156. expect(fn?.isExported).toBe(true);
  5157. });
  5158. it('should extract calls from template expressions', () => {
  5159. const code = `---
  5160. import { formatDate } from '../utils/format';
  5161. const date = new Date();
  5162. ---
  5163. <time>{formatDate(date)}</time>
  5164. `;
  5165. const result = extractFromSource('Stamp.astro', code);
  5166. const call = result.unresolvedReferences.find(
  5167. (ref) => ref.referenceKind === 'calls' && ref.referenceName === 'formatDate' && ref.line === 5
  5168. );
  5169. expect(call).toBeDefined();
  5170. });
  5171. it('should extract calls from a multiline expression opening line', () => {
  5172. const code = `---
  5173. const posts = [];
  5174. ---
  5175. <ul>
  5176. {posts.map((post) => (
  5177. <li>{render(post)}</li>
  5178. ))}
  5179. </ul>
  5180. `;
  5181. const result = extractFromSource('List.astro', code);
  5182. const mapCall = result.unresolvedReferences.find(
  5183. (ref) => ref.referenceKind === 'calls' && ref.referenceName === 'posts.map'
  5184. );
  5185. expect(mapCall).toBeDefined();
  5186. const innerCall = result.unresolvedReferences.find(
  5187. (ref) => ref.referenceKind === 'calls' && ref.referenceName === 'render'
  5188. );
  5189. expect(innerCall).toBeDefined();
  5190. });
  5191. it('should extract PascalCase component usages from the template', () => {
  5192. const code = `---
  5193. import Layout from '../layouts/Layout.astro';
  5194. import PostCard from '../components/PostCard.astro';
  5195. ---
  5196. <Layout title="Home">
  5197. <PostCard />
  5198. <Fragment slot="head" />
  5199. <div class="plain-html" />
  5200. </Layout>
  5201. `;
  5202. const result = extractFromSource('index.astro', code);
  5203. const refs = result.unresolvedReferences.filter((r) => r.referenceKind === 'references');
  5204. const names = refs.map((r) => r.referenceName);
  5205. expect(names).toContain('Layout');
  5206. expect(names).toContain('PostCard');
  5207. // Astro built-ins and lowercase HTML are not component references
  5208. expect(names).not.toContain('Fragment');
  5209. expect(names).not.toContain('div');
  5210. });
  5211. it('should not extract template patterns from frontmatter, script, or style content', () => {
  5212. const code = `---
  5213. // <FakeComponent /> inside frontmatter comment
  5214. const x = { y: maybeCall(1) };
  5215. ---
  5216. <div>real</div>
  5217. <script>
  5218. const z = { w: scriptCall(2) };
  5219. </script>
  5220. <style>
  5221. .a { color: red; }
  5222. </style>
  5223. `;
  5224. const result = extractFromSource('Guard.astro', code);
  5225. const templateRefs = result.unresolvedReferences.filter(
  5226. (r) => r.referenceKind === 'references' && r.referenceName === 'FakeComponent'
  5227. );
  5228. expect(templateRefs).toHaveLength(0);
  5229. // maybeCall/scriptCall come from the delegated TS extraction (once),
  5230. // not double-counted by the template scanner
  5231. const maybeCalls = result.unresolvedReferences.filter(
  5232. (r) => r.referenceName === 'maybeCall' && r.referenceKind === 'calls'
  5233. );
  5234. expect(maybeCalls.length).toBeLessThanOrEqual(1);
  5235. });
  5236. it('should extract <script> block symbols with correct line numbers', () => {
  5237. const code = `---
  5238. const a = 1;
  5239. ---
  5240. <div>hi</div>
  5241. <script>
  5242. function trackView(page: string) {
  5243. console.log(page);
  5244. }
  5245. </script>
  5246. `;
  5247. const result = extractFromSource('Tracker.astro', code);
  5248. const fn = result.nodes.find((n) => n.kind === 'function' && n.name === 'trackView');
  5249. expect(fn).toBeDefined();
  5250. expect(fn?.startLine).toBe(6);
  5251. expect(fn?.language).toBe('astro');
  5252. });
  5253. it('should create component node for a frontmatter-less template-only file', () => {
  5254. const code = `<div>Static content</div>
  5255. `;
  5256. const result = extractFromSource('Static.astro', code);
  5257. const componentNode = result.nodes.find((n) => n.kind === 'component');
  5258. expect(componentNode).toBeDefined();
  5259. expect(componentNode?.name).toBe('Static');
  5260. expect(componentNode?.language).toBe('astro');
  5261. });
  5262. it('should treat an unclosed frontmatter fence as no frontmatter', () => {
  5263. const code = `---
  5264. const broken = true;
  5265. <div>never closed</div>
  5266. `;
  5267. const result = extractFromSource('Broken.astro', code);
  5268. // No TS delegation happened (the fence never closes), but the component
  5269. // node still exists and nothing throws.
  5270. const componentNode = result.nodes.find((n) => n.kind === 'component');
  5271. expect(componentNode).toBeDefined();
  5272. expect(result.nodes.find((n) => n.name === 'broken')).toBeUndefined();
  5273. });
  5274. it('should create containment edges from component to frontmatter nodes', () => {
  5275. const code = `---
  5276. const value = 42;
  5277. ---
  5278. <div>{value}</div>
  5279. `;
  5280. const result = extractFromSource('Contained.astro', code);
  5281. const componentNode = result.nodes.find((n) => n.kind === 'component');
  5282. expect(componentNode).toBeDefined();
  5283. const containEdges = result.edges.filter(
  5284. (e) => e.source === componentNode!.id && e.kind === 'contains'
  5285. );
  5286. expect(containEdges.length).toBeGreaterThan(0);
  5287. });
  5288. });
  5289. describe('Instantiates + Decorates edge extraction', () => {
  5290. it('emits an instantiates ref for `new Foo()`', () => {
  5291. const code = `
  5292. class Foo {}
  5293. function bootstrap() { return new Foo(); }
  5294. `;
  5295. const result = extractFromSource('app.ts', code);
  5296. const ref = result.unresolvedReferences.find(
  5297. (r) => r.referenceKind === 'instantiates' && r.referenceName === 'Foo'
  5298. );
  5299. expect(ref).toBeDefined();
  5300. });
  5301. it('strips type-argument suffix from generic constructors', () => {
  5302. const code = `
  5303. class Container<T> { constructor(_: T) {} }
  5304. function go() { return new Container<string>('x'); }
  5305. `;
  5306. const result = extractFromSource('app.ts', code);
  5307. const ref = result.unresolvedReferences.find(
  5308. (r) => r.referenceKind === 'instantiates'
  5309. );
  5310. expect(ref).toBeDefined();
  5311. // Container<string> must be normalised to "Container" — otherwise
  5312. // resolution can never match the class node.
  5313. expect(ref!.referenceName).toBe('Container');
  5314. });
  5315. it('keeps trailing identifier from qualified `new ns.Foo()`', () => {
  5316. const code = `
  5317. const ns = { Foo: class {} };
  5318. function go() { return new ns.Foo(); }
  5319. `;
  5320. const result = extractFromSource('app.ts', code);
  5321. const ref = result.unresolvedReferences.find(
  5322. (r) => r.referenceKind === 'instantiates'
  5323. );
  5324. // We can't always resolve which Foo, but the name should be the
  5325. // simple identifier so name-matching has a chance.
  5326. expect(ref?.referenceName).toBe('Foo');
  5327. });
  5328. it('emits a decorates ref for `@Foo class X {}`', () => {
  5329. const code = `
  5330. function Foo(_arg: string) { return (cls: any) => cls; }
  5331. @Foo('x')
  5332. class X {}
  5333. `;
  5334. const result = extractFromSource('app.ts', code);
  5335. const decorClass = result.unresolvedReferences.find(
  5336. (r) => r.referenceKind === 'decorates' && r.referenceName === 'Foo'
  5337. );
  5338. expect(decorClass).toBeDefined();
  5339. });
  5340. it('does NOT attribute a prior class\'s decorator to the next class', () => {
  5341. // Regression: the sibling-walk must stop at the first non-
  5342. // decorator separator. `@A class Foo {} @B class Bar {}` must
  5343. // produce `decorates(Foo, A)` and `decorates(Bar, B)` — never
  5344. // `decorates(Bar, A)`.
  5345. const code = `
  5346. function A(cls: any) { return cls; }
  5347. function B(cls: any) { return cls; }
  5348. @A
  5349. class Foo {}
  5350. @B
  5351. class Bar {}
  5352. `;
  5353. const result = extractFromSource('app.ts', code);
  5354. const decoratesEdges = result.unresolvedReferences.filter(
  5355. (r) => r.referenceKind === 'decorates'
  5356. );
  5357. // Exactly one decorates ref per decorated class, no cross-attribution.
  5358. const fromBar = decoratesEdges.filter((r) =>
  5359. result.nodes.find((n) => n.id === r.fromNodeId && n.name === 'Bar')
  5360. );
  5361. expect(fromBar.length).toBe(1);
  5362. expect(fromBar[0]!.referenceName).toBe('B');
  5363. });
  5364. it('emits a decorates ref for `@Foo method() {}`', () => {
  5365. const code = `
  5366. function Get(p: string) { return (t: any, k: string) => t; }
  5367. class Svc {
  5368. @Get('/x') method() { return 1; }
  5369. }
  5370. `;
  5371. const result = extractFromSource('app.ts', code);
  5372. const decorMethod = result.unresolvedReferences.find(
  5373. (r) => r.referenceKind === 'decorates' && r.referenceName === 'Get'
  5374. );
  5375. expect(decorMethod).toBeDefined();
  5376. // The decorated symbol must be `method`, not the constructor or class.
  5377. const decoratedNode = result.nodes.find((n) => n.id === decorMethod!.fromNodeId);
  5378. expect(decoratedNode?.name).toBe('method');
  5379. });
  5380. });
  5381. // =============================================================================
  5382. // Lua
  5383. // =============================================================================
  5384. describe('Lua Extraction', () => {
  5385. describe('Language detection', () => {
  5386. it('should detect Lua files', () => {
  5387. expect(detectLanguage('init.lua')).toBe('lua');
  5388. expect(detectLanguage('src/util.lua')).toBe('lua');
  5389. });
  5390. it('should report Lua as supported', () => {
  5391. expect(isLanguageSupported('lua')).toBe(true);
  5392. expect(getSupportedLanguages()).toContain('lua');
  5393. });
  5394. });
  5395. describe('Function extraction', () => {
  5396. it('should extract global and local functions', () => {
  5397. const code = `
  5398. function configure(opts) return opts end
  5399. local function helper(x) return x * 2 end
  5400. `;
  5401. const result = extractFromSource('init.lua', code);
  5402. const funcs = result.nodes.filter((n) => n.kind === 'function').map((n) => n.name);
  5403. expect(funcs).toContain('configure');
  5404. expect(funcs).toContain('helper');
  5405. const configure = result.nodes.find((n) => n.name === 'configure');
  5406. expect(configure?.language).toBe('lua');
  5407. expect(configure?.signature).toBe('(opts)');
  5408. });
  5409. it('should split table/method functions into a receiver and method name', () => {
  5410. const code = `
  5411. function M.connect(host, port) return host end
  5412. function M:send(data) return self end
  5413. `;
  5414. const result = extractFromSource('init.lua', code);
  5415. const methods = result.nodes.filter((n) => n.kind === 'method');
  5416. const connect = methods.find((m) => m.name === 'connect');
  5417. expect(connect?.qualifiedName).toBe('M::connect');
  5418. const send = methods.find((m) => m.name === 'send');
  5419. expect(send?.qualifiedName).toBe('M::send');
  5420. });
  5421. });
  5422. describe('Variable extraction', () => {
  5423. it('should extract local variable declarations', () => {
  5424. const code = `
  5425. local M = {}
  5426. local count = 0
  5427. `;
  5428. const result = extractFromSource('mod.lua', code);
  5429. const vars = result.nodes.filter((n) => n.kind === 'variable').map((n) => n.name);
  5430. expect(vars).toContain('M');
  5431. expect(vars).toContain('count');
  5432. });
  5433. });
  5434. describe('Import extraction (require)', () => {
  5435. it('should extract require() in local declarations and bare calls', () => {
  5436. const code = `
  5437. local socket = require("socket")
  5438. local http = require "resty.http"
  5439. require("side.effect")
  5440. `;
  5441. const result = extractFromSource('net.lua', code);
  5442. const imports = result.nodes.filter((n) => n.kind === 'import').map((n) => n.name);
  5443. expect(imports).toContain('socket');
  5444. expect(imports).toContain('resty.http');
  5445. expect(imports).toContain('side.effect');
  5446. const ref = result.unresolvedReferences.find(
  5447. (r) => r.referenceKind === 'imports' && r.referenceName === 'socket'
  5448. );
  5449. expect(ref).toBeDefined();
  5450. });
  5451. // Regression: the tree-sitter-wasms Lua grammar (ABI 13) corrupts the shared
  5452. // WASM heap under web-tree-sitter 0.25, dropping nested calls/imports on every
  5453. // parse after the first. We vendor the ABI-15 grammar instead — this guards it
  5454. // by extracting several sources in sequence and asserting the LAST still works.
  5455. it('should keep extracting require across many sequential parses', () => {
  5456. let last;
  5457. for (let i = 0; i < 8; i++) {
  5458. last = extractFromSource(`f${i}.lua`, `local m = require("module.${i}")\nreturn m\n`);
  5459. }
  5460. const imports = last!.nodes.filter((n) => n.kind === 'import').map((n) => n.name);
  5461. expect(imports).toContain('module.7');
  5462. });
  5463. });
  5464. describe('Call extraction', () => {
  5465. it('should record intra-file calls as resolvable references', () => {
  5466. const code = `
  5467. local function helper(x) return x end
  5468. local function run(y) return helper(y) end
  5469. `;
  5470. const result = extractFromSource('calls.lua', code);
  5471. const call = result.unresolvedReferences.find(
  5472. (r) => r.referenceKind === 'calls' && r.referenceName === 'helper'
  5473. );
  5474. expect(call).toBeDefined();
  5475. });
  5476. });
  5477. });
  5478. // =============================================================================
  5479. // Luau (typed superset of Lua — https://luau.org)
  5480. // =============================================================================
  5481. describe('Luau Extraction', () => {
  5482. describe('Language detection', () => {
  5483. it('should detect Luau files', () => {
  5484. expect(detectLanguage('init.luau')).toBe('luau');
  5485. expect(detectLanguage('src/Client.luau')).toBe('luau');
  5486. });
  5487. it('should report Luau as supported', () => {
  5488. expect(isLanguageSupported('luau')).toBe(true);
  5489. expect(getSupportedLanguages()).toContain('luau');
  5490. });
  5491. });
  5492. describe('Type aliases', () => {
  5493. it('should extract `type` and `export type` definitions', () => {
  5494. const code = `
  5495. export type Vector = { x: number, y: number }
  5496. type Handler = (msg: string) -> boolean
  5497. `;
  5498. const result = extractFromSource('types.luau', code);
  5499. const aliases = result.nodes.filter((n) => n.kind === 'type_alias');
  5500. const vector = aliases.find((a) => a.name === 'Vector');
  5501. expect(vector).toBeDefined();
  5502. expect(vector?.isExported).toBe(true);
  5503. const handler = aliases.find((a) => a.name === 'Handler');
  5504. expect(handler).toBeDefined();
  5505. expect(handler?.isExported).toBe(false);
  5506. });
  5507. });
  5508. describe('Typed functions and methods', () => {
  5509. it('should capture typed signatures and split methods by receiver', () => {
  5510. const code = `
  5511. function configure(opts: { debug: boolean }): boolean
  5512. return opts.debug
  5513. end
  5514. function Client:fetch(path: string): Response
  5515. return path
  5516. end
  5517. `;
  5518. const result = extractFromSource('client.luau', code);
  5519. const configure = result.nodes.find((n) => n.kind === 'function' && n.name === 'configure');
  5520. expect(configure?.language).toBe('luau');
  5521. expect(configure?.signature).toBe('(opts: { debug: boolean }): boolean');
  5522. const fetch = result.nodes.find((n) => n.kind === 'method' && n.name === 'fetch');
  5523. expect(fetch?.qualifiedName).toBe('Client::fetch');
  5524. });
  5525. });
  5526. describe('Imports and variables', () => {
  5527. it('should extract string and Roblox instance-path require imports', () => {
  5528. const code = `
  5529. local http = require("http")
  5530. local Signal = require(script.Parent.Signal)
  5531. local count = 0
  5532. `;
  5533. const result = extractFromSource('mod.luau', code);
  5534. const imports = result.nodes.filter((n) => n.kind === 'import').map((n) => n.name);
  5535. expect(imports).toContain('http'); // string require
  5536. expect(imports).toContain('Signal'); // Roblox instance-path require
  5537. const vars = result.nodes.filter((n) => n.kind === 'variable').map((n) => n.name);
  5538. expect(vars).toContain('count');
  5539. });
  5540. });
  5541. });
  5542. // =============================================================================
  5543. // Objective-C
  5544. // =============================================================================
  5545. describe('Objective-C Extraction', () => {
  5546. const sample = `
  5547. #import <Foundation/Foundation.h>
  5548. #import "MyClass.h"
  5549. @interface MyClass : NSObject <NSCopying>
  5550. @property (nonatomic, copy) NSString *name;
  5551. - (void)greet;
  5552. - (void)doThing:(id)x with:(id)y;
  5553. + (instancetype)shared;
  5554. @end
  5555. @implementation MyClass
  5556. - (void)greet {
  5557. NSLog(@"Hello");
  5558. [self doWork];
  5559. }
  5560. - (void)doThing:(id)x with:(id)y {
  5561. [self notify:x];
  5562. }
  5563. + (instancetype)shared {
  5564. return [[MyClass alloc] init];
  5565. }
  5566. @end
  5567. void helperFunction(int count) {
  5568. MyClass *obj = [MyClass shared];
  5569. [obj greet];
  5570. }
  5571. `;
  5572. it('should extract classes, methods, functions, and imports', () => {
  5573. const result = extractFromSource('App.m', sample);
  5574. const classes = result.nodes.filter((n) => n.kind === 'class');
  5575. expect(classes.filter((c) => c.name === 'MyClass')).toHaveLength(1);
  5576. const methods = result.nodes.filter((n) => n.kind === 'method');
  5577. expect(methods.map((m) => m.name).sort()).toEqual(['doThing:with:', 'greet', 'shared']);
  5578. const shared = methods.find((m) => m.name === 'shared');
  5579. expect(shared?.isStatic).toBe(true);
  5580. const properties = result.nodes.filter((n) => n.kind === 'property');
  5581. expect(properties.some((p) => p.name === 'name')).toBe(true);
  5582. const functions = result.nodes.filter((n) => n.kind === 'function');
  5583. expect(functions.some((f) => f.name === 'helperFunction')).toBe(true);
  5584. const imports = result.nodes.filter((n) => n.kind === 'import').map((n) => n.name);
  5585. expect(imports).toContain('Foundation/Foundation.h');
  5586. expect(imports).toContain('MyClass.h');
  5587. });
  5588. it('should record inheritance and protocol conformance', () => {
  5589. const result = extractFromSource('App.m', sample);
  5590. const extendsRefs = result.unresolvedReferences.filter((r) => r.referenceKind === 'extends');
  5591. const implementsRefs = result.unresolvedReferences.filter((r) => r.referenceKind === 'implements');
  5592. expect(extendsRefs.map((r) => r.referenceName)).toContain('NSObject');
  5593. expect(implementsRefs.map((r) => r.referenceName)).toContain('NSCopying');
  5594. });
  5595. it('should record message sends and C calls', () => {
  5596. const result = extractFromSource('App.m', sample);
  5597. const calls = result.unresolvedReferences
  5598. .filter((r) => r.referenceKind === 'calls')
  5599. .map((r) => r.referenceName);
  5600. expect(calls).toEqual(expect.arrayContaining(['NSLog', 'doWork', 'MyClass.shared', 'obj.greet']));
  5601. });
  5602. it('should reconstruct multi-keyword selectors at the call site so they resolve to the method definition', () => {
  5603. // Regression for the gap discovered post-#165: message_expression's
  5604. // multi-keyword form `[obj a:1 b:2]` was only emitting the first keyword,
  5605. // so calls never resolved to multi-part method definitions like
  5606. // `GET:parameters:headers:progress:success:failure:`. The call-site name
  5607. // must match the method-definition name with full keywords + trailing colons.
  5608. const code = `
  5609. @implementation Caller
  5610. - (void)demo {
  5611. NSMutableDictionary *d = [NSMutableDictionary new];
  5612. [d setObject:@"v" forKey:@"k"];
  5613. [d setObject:@"v2" forKey:@"k2" withRetry:@YES];
  5614. [self touchesBegan:nil withEvent:nil];
  5615. }
  5616. @end
  5617. `;
  5618. const result = extractFromSource('Caller.m', code);
  5619. const calls = result.unresolvedReferences
  5620. .filter((r) => r.referenceKind === 'calls')
  5621. .map((r) => r.referenceName);
  5622. expect(calls).toEqual(
  5623. expect.arrayContaining([
  5624. 'd.setObject:forKey:',
  5625. 'd.setObject:forKey:withRetry:',
  5626. 'touchesBegan:withEvent:',
  5627. ])
  5628. );
  5629. });
  5630. it('should not classify pure C headers with @end in comments as objc', () => {
  5631. const cHeader = '/* @end of file */\n#ifndef STDIO_H\nvoid printf(const char *);\n#endif\n';
  5632. expect(detectLanguage('stdio.h', cHeader)).toBe('c');
  5633. });
  5634. it('should extract protocol declarations', () => {
  5635. const code = `
  5636. @protocol DataSource <NSObject>
  5637. - (NSInteger)numberOfItems;
  5638. @end
  5639. `;
  5640. const result = extractFromSource('DataSource.h', code);
  5641. const protocol = result.nodes.find((n) => n.kind === 'protocol' && n.name === 'DataSource');
  5642. expect(protocol).toBeDefined();
  5643. });
  5644. it('should report Objective-C as supported', () => {
  5645. expect(isLanguageSupported('objc')).toBe(true);
  5646. expect(getSupportedLanguages()).toContain('objc');
  5647. });
  5648. });
  5649. describe('Regression: issue-specific extraction fixes', () => {
  5650. it('indexes inner functions of an anonymous AMD/CommonJS module wrapper (#528)', () => {
  5651. const code = `
  5652. define(['dep'], function (dep) {
  5653. function innerHelper(x) { return x + 1; }
  5654. function compute(y) { return innerHelper(y); }
  5655. return { compute: compute };
  5656. });
  5657. `;
  5658. const result = extractFromSource('amd-module.js', code);
  5659. const fns = result.nodes.filter((n) => n.kind === 'function').map((n) => n.name);
  5660. expect(fns).toContain('innerHelper');
  5661. expect(fns).toContain('compute');
  5662. });
  5663. it('attaches Go methods on generic receivers to their type (#583)', () => {
  5664. const code = `
  5665. package main
  5666. type Stack[T any] struct { items []T }
  5667. func (s *Stack[T]) Push(v T) { s.items = append(s.items, v) }
  5668. func (s Stack[T]) Len() int { return len(s.items) }
  5669. `;
  5670. const result = extractFromSource('stack.go', code);
  5671. const methods = result.nodes.filter((n) => n.kind === 'method');
  5672. expect(methods.find((m) => m.name === 'Push')?.qualifiedName).toBe('Stack::Push');
  5673. expect(methods.find((m) => m.name === 'Len')?.qualifiedName).toBe('Stack::Len');
  5674. });
  5675. it('indexes new module extensions: .mts/.cts (TS) and .xsjs/.xsjslib (JS) (#366, #556)', () => {
  5676. expect(isSourceFile('mod.mts')).toBe(true);
  5677. expect(isSourceFile('mod.cts')).toBe(true);
  5678. expect(isSourceFile('service.xsjs')).toBe(true);
  5679. expect(isSourceFile('lib.xsjslib')).toBe(true);
  5680. expect(detectLanguage('mod.mts')).toBe('typescript');
  5681. expect(detectLanguage('service.xsjs')).toBe('javascript');
  5682. // End-to-end: a .mts file is parsed as TS, a .xsjs file as JS.
  5683. const ts = extractFromSource('mod.mts', 'export function hello(): number { return 1; }');
  5684. expect(ts.nodes.find((n) => n.name === 'hello' && n.kind === 'function')).toBeDefined();
  5685. const js = extractFromSource('service.xsjs', 'function handleRequest() { return 1; }');
  5686. expect(js.nodes.find((n) => n.name === 'handleRequest' && n.kind === 'function')).toBeDefined();
  5687. });
  5688. });
  5689. describe('Import / re-export dependency linking (blast-radius recall)', () => {
  5690. // An import IS a dependency, but extraction only emits references for calls,
  5691. // instantiations, type annotations, and inheritance — so a symbol imported and
  5692. // then merely re-exported, placed in a registry array, passed as an argument,
  5693. // or used in JSX produced no cross-file edge, leaving the providing file with a
  5694. // false "0 dependents". These tests pin the import/re-export binding linking.
  5695. it('emits an imports reference per named, aliased, and default import binding', () => {
  5696. const code = `
  5697. import { widget, helper as h } from './foo';
  5698. import Thing from './thing';
  5699. import * as NS from './ns';
  5700. export const registry = [widget];
  5701. `;
  5702. const result = extractFromSource('bar.ts', code);
  5703. const names = result.unresolvedReferences
  5704. .filter((r) => r.referenceKind === 'imports')
  5705. .map((r) => r.referenceName);
  5706. expect(names).toContain('widget'); // named import → local name
  5707. expect(names).toContain('h'); // aliased import → local alias
  5708. expect(names).toContain('Thing'); // default import
  5709. expect(names).toContain('NS'); // namespace import → linked to the module file as a dependency
  5710. });
  5711. it('emits an imports reference per re-exported binding', () => {
  5712. const result = extractFromSource('barrel.ts', `export { alpha, beta as b } from './source';`);
  5713. const names = result.unresolvedReferences
  5714. .filter((r) => r.referenceKind === 'imports')
  5715. .map((r) => r.referenceName);
  5716. // Re-export links the SOURCE-side name, not the local alias.
  5717. expect(names).toContain('alpha');
  5718. expect(names).toContain('beta');
  5719. });
  5720. it('a value imported/re-exported but never called still makes the importer a dependent', async () => {
  5721. const dir = createTempDir();
  5722. try {
  5723. fs.mkdirSync(path.join(dir, 'src'), { recursive: true });
  5724. fs.writeFileSync(
  5725. path.join(dir, 'src', 'foo.ts'),
  5726. `export const widget = { n: 1 };\nexport function helper(): void {}\n`
  5727. );
  5728. // bar uses widget ONLY in an array and re-exports helper — neither is
  5729. // called/typed, so before import-linking bar had no edge to foo at all.
  5730. fs.writeFileSync(
  5731. path.join(dir, 'src', 'bar.ts'),
  5732. `import { widget } from './foo';\nexport { helper } from './foo';\nexport const registry = [widget];\n`
  5733. );
  5734. const cg = CodeGraph.initSync(dir, { config: { include: ['src/**/*.ts'], exclude: [] } });
  5735. await cg.indexAll();
  5736. cg.resolveReferences();
  5737. expect(cg.getFileDependents('src/foo.ts')).toContain('src/bar.ts');
  5738. cg.destroy();
  5739. } finally {
  5740. cleanupTempDir(dir);
  5741. }
  5742. });
  5743. it('a namespace import touched only via a value-member read still links the module file', async () => {
  5744. const dir = createTempDir();
  5745. try {
  5746. fs.mkdirSync(path.join(dir, 'src'), { recursive: true });
  5747. fs.writeFileSync(path.join(dir, 'src', 'foo.ts'), `export const SOME_CONST = 42;\n`);
  5748. // `foo` is imported as a namespace and used ONLY via a value-member read
  5749. // (no call, no type) — `foo.helper()` would link on its own, but a bare
  5750. // `foo.SOME_CONST` would not, so the module-import backstop must link it.
  5751. fs.writeFileSync(path.join(dir, 'src', 'bar.ts'), `import * as foo from './foo';\nexport const x = foo.SOME_CONST;\n`);
  5752. const cg = CodeGraph.initSync(dir, { config: { include: ['src/**/*.ts'], exclude: [] } });
  5753. await cg.indexAll();
  5754. cg.resolveReferences();
  5755. expect(cg.getFileDependents('src/foo.ts')).toContain('src/bar.ts');
  5756. cg.destroy();
  5757. } finally {
  5758. cleanupTempDir(dir);
  5759. }
  5760. });
  5761. });
  5762. describe('Python import dependency linking (blast-radius recall)', () => {
  5763. // Same recall gap as TS: Python only linked called/instantiated imports, so a
  5764. // name brought in with `from module import X` and then merely stored, used as
  5765. // a decorator/argument, or re-exported through an `__init__.py` produced no
  5766. // cross-file edge — the providing module showed a false "0 dependents".
  5767. it('emits an imports reference per name in a `from module import ...` (incl. value/aliased)', () => {
  5768. const code = [
  5769. 'from foo import helper, widget',
  5770. 'from foo import Thing as T',
  5771. 'from . import sibling',
  5772. 'from bar import *',
  5773. ].join('\n');
  5774. const names = extractFromSource('mod.py', code)
  5775. .unresolvedReferences.filter((r) => r.referenceKind === 'imports')
  5776. .map((r) => r.referenceName);
  5777. expect(names).toContain('helper');
  5778. expect(names).toContain('widget'); // value import
  5779. expect(names).toContain('T'); // aliased import → local name
  5780. expect(names).toContain('sibling'); // `from . import <name>`
  5781. expect(names).not.toContain('*'); // wildcard import has no names
  5782. });
  5783. it('a Python value imported but never called still makes the importer a dependent', async () => {
  5784. const dir = createTempDir();
  5785. try {
  5786. fs.mkdirSync(path.join(dir, 'pkg'), { recursive: true });
  5787. fs.writeFileSync(path.join(dir, 'pkg', 'foo.py'), `widget = {"n": 1}\ndef helper():\n return 1\n`);
  5788. // bar imports widget+helper but only stores widget in a list — nothing is
  5789. // called, so before import-linking bar had no edge to foo.
  5790. fs.writeFileSync(path.join(dir, 'pkg', 'bar.py'), `from foo import widget, helper\nregistry = [widget]\n`);
  5791. const cg = CodeGraph.initSync(dir, { config: { include: ['pkg/**/*.py'], exclude: [] } });
  5792. await cg.indexAll();
  5793. cg.resolveReferences();
  5794. expect(cg.getFileDependents('pkg/foo.py')).toContain('pkg/bar.py');
  5795. cg.destroy();
  5796. } finally {
  5797. cleanupTempDir(dir);
  5798. }
  5799. });
  5800. it('resolves `from . import submodule` + `submodule.func()` to the submodule', async () => {
  5801. const dir = createTempDir();
  5802. try {
  5803. fs.mkdirSync(path.join(dir, 'pkg'), { recursive: true });
  5804. fs.writeFileSync(path.join(dir, 'pkg', '__init__.py'), '');
  5805. fs.writeFileSync(path.join(dir, 'pkg', 'certs.py'), `def where():\n return "/ca.pem"\n`);
  5806. // certs is an imported MODULE (a file), and certs.where() is a qualified
  5807. // call through it — the receiver isn't a symbol, so plain name-matching
  5808. // can't link it. Also exercises the Python relative-dot path fix (`.certs`).
  5809. fs.writeFileSync(path.join(dir, 'pkg', 'utils.py'), `from . import certs\ndef go():\n return certs.where()\n`);
  5810. const cg = CodeGraph.initSync(dir, { config: { include: ['pkg/**/*.py'], exclude: [] } });
  5811. await cg.indexAll();
  5812. cg.resolveReferences();
  5813. expect(cg.getFileDependents('pkg/certs.py')).toContain('pkg/utils.py');
  5814. cg.destroy();
  5815. } finally {
  5816. cleanupTempDir(dir);
  5817. }
  5818. });
  5819. it('a module import is a dependency even when the used member is re-exported elsewhere', async () => {
  5820. const dir = createTempDir();
  5821. try {
  5822. fs.mkdirSync(path.join(dir, 'pkg'), { recursive: true });
  5823. fs.writeFileSync(path.join(dir, 'pkg', '__init__.py'), '');
  5824. // `where` is NOT defined in certs.py (re-exported from a 3rd-party pkg), so
  5825. // member resolution can't find it — the module-import backstop must still
  5826. // record utils -> certs. (Mirrors requests' real `certs.where`.)
  5827. fs.writeFileSync(path.join(dir, 'pkg', 'certs.py'), `from external_ca import where\n`);
  5828. fs.writeFileSync(path.join(dir, 'pkg', 'utils.py'), `from . import certs\nCA = certs.where()\n`);
  5829. const cg = CodeGraph.initSync(dir, { config: { include: ['pkg/**/*.py'], exclude: [] } });
  5830. await cg.indexAll();
  5831. cg.resolveReferences();
  5832. expect(cg.getFileDependents('pkg/certs.py')).toContain('pkg/utils.py');
  5833. cg.destroy();
  5834. } finally {
  5835. cleanupTempDir(dir);
  5836. }
  5837. });
  5838. });
  5839. describe('Go cross-package composite literals (blast-radius recall)', () => {
  5840. // Go function calls and type references across packages already resolved, but
  5841. // struct composite literals — `render.XML{...}` / `pkga.Widget{...}` — were not
  5842. // extracted at all, so a package whose types are only INSTANTIATED elsewhere
  5843. // (gin's render/binding implementations) showed 0 dependents.
  5844. it('links a cross-package struct composite literal to the defining package', async () => {
  5845. const dir = createTempDir();
  5846. try {
  5847. fs.writeFileSync(path.join(dir, 'go.mod'), 'module example.com/proj\n\ngo 1.21\n');
  5848. fs.mkdirSync(path.join(dir, 'render'), { recursive: true });
  5849. fs.writeFileSync(path.join(dir, 'render', 'xml.go'), `package render\n\ntype XML struct { Data any }\n`);
  5850. fs.writeFileSync(path.join(dir, 'app.go'), `package main\n\nimport "example.com/proj/render"\n\nfunc handle() any { return render.XML{} }\n`);
  5851. const cg = CodeGraph.initSync(dir, { config: { include: ['**/*.go'], exclude: [] } });
  5852. await cg.indexAll();
  5853. cg.resolveReferences();
  5854. expect(cg.getFileDependents('render/xml.go')).toContain('app.go');
  5855. cg.destroy();
  5856. } finally {
  5857. cleanupTempDir(dir);
  5858. }
  5859. });
  5860. it('links a composite literal in a package-level var registry', async () => {
  5861. const dir = createTempDir();
  5862. try {
  5863. fs.writeFileSync(path.join(dir, 'go.mod'), 'module example.com/proj\n\ngo 1.21\n');
  5864. fs.mkdirSync(path.join(dir, 'render'), { recursive: true });
  5865. fs.writeFileSync(path.join(dir, 'render', 'xml.go'), `package render\n\ntype XML struct {}\nfunc (XML) Render() {}\n`);
  5866. // The implementation is registered only in a top-level `var registry = {...}`
  5867. // map literal — the body walker doesn't cover top-level declarations, so this
  5868. // exercises the var-initializer walking added for Go.
  5869. 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`);
  5870. const cg = CodeGraph.initSync(dir, { config: { include: ['**/*.go'], exclude: [] } });
  5871. await cg.indexAll();
  5872. cg.resolveReferences();
  5873. expect(cg.getFileDependents('render/xml.go')).toContain('reg.go');
  5874. cg.destroy();
  5875. } finally {
  5876. cleanupTempDir(dir);
  5877. }
  5878. });
  5879. it('attributes a call inside a top-level closure (cobra RunE) to the var, not the file (#693)', async () => {
  5880. const dir = createTempDir();
  5881. try {
  5882. fs.writeFileSync(path.join(dir, 'go.mod'), 'module example.com/proj\n\ngo 1.21\n');
  5883. // Wire is called ONLY from the anonymous RunE closure inside a top-level
  5884. // `var rootCmd = &Cmd{...}` — previously the call leaked to the file node,
  5885. // so `callers(Wire)` surfaced a file (or read as "no caller"). It must now
  5886. // attribute to the enclosing var.
  5887. fs.writeFileSync(path.join(dir, 'factory.go'), `package main\n\nfunc Wire() error { return nil }\n`);
  5888. fs.writeFileSync(
  5889. path.join(dir, 'root.go'),
  5890. `package main\n\ntype Cmd struct{ RunE func() error }\n\nvar rootCmd = &Cmd{\n\tRunE: func() error { return Wire() },\n}\n`
  5891. );
  5892. const cg = CodeGraph.initSync(dir, { config: { include: ['**/*.go'], exclude: [] } });
  5893. await cg.indexAll();
  5894. cg.resolveReferences();
  5895. const wire = cg.getNodesByName('Wire').find((n) => n.kind === 'function');
  5896. expect(wire).toBeDefined();
  5897. const callers = cg.getCallers(wire!.id).map((c) => c.node);
  5898. expect(callers.some((n) => n.kind === 'variable' && n.name === 'rootCmd')).toBe(true);
  5899. expect(callers.some((n) => n.kind === 'file')).toBe(false);
  5900. cg.destroy();
  5901. } finally {
  5902. cleanupTempDir(dir);
  5903. }
  5904. });
  5905. it('links a parenthesized pointer type conversion `(*T)(x)` to the type', async () => {
  5906. const dir = createTempDir();
  5907. try {
  5908. fs.writeFileSync(path.join(dir, 'go.mod'), 'module example.com/proj\n\ngo 1.21\n');
  5909. fs.writeFileSync(path.join(dir, 'types.go'), `package main\n\ntype Wrapped struct { N int }\n`);
  5910. // `(*Wrapped)(x)` parses as a call whose callee is the parenthesized type
  5911. // `(*Wrapped)` — without normalization it dropped on the floor.
  5912. fs.writeFileSync(path.join(dir, 'use.go'), `package main\n\nfunc run(x *int) { _ = (*Wrapped)(x) }\n`);
  5913. const cg = CodeGraph.initSync(dir, { config: { include: ['**/*.go'], exclude: [] } });
  5914. await cg.indexAll();
  5915. cg.resolveReferences();
  5916. expect(cg.getFileDependents('types.go')).toContain('use.go');
  5917. cg.destroy();
  5918. } finally {
  5919. cleanupTempDir(dir);
  5920. }
  5921. });
  5922. it('links an implementation reached only through a Go interface (implicit satisfaction, #584)', async () => {
  5923. const dir = createTempDir();
  5924. try {
  5925. fs.writeFileSync(path.join(dir, 'go.mod'), 'module example.com/proj\n\ngo 1.21\n');
  5926. fs.mkdirSync(path.join(dir, 'codec'), { recursive: true });
  5927. 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`);
  5928. // jsonApi satisfies Core structurally (no `implements` keyword) and is
  5929. // reached ONLY through the interface (API.Marshal). Without implicit
  5930. // interface satisfaction + dispatch, json.go shows 0 dependents.
  5931. 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`);
  5932. const cg = CodeGraph.initSync(dir, { config: { include: ['**/*.go'], exclude: [] } });
  5933. await cg.indexAll();
  5934. cg.resolveReferences();
  5935. expect(cg.getFileDependents('codec/json.go')).toContain('codec/api.go');
  5936. cg.destroy();
  5937. } finally {
  5938. cleanupTempDir(dir);
  5939. }
  5940. });
  5941. });
  5942. describe('C# records (blast-radius recall)', () => {
  5943. // Records are ubiquitous in modern C# (DTOs, value objects, CQRS messages),
  5944. // but `record` / `record struct` declarations weren't extracted as types — so
  5945. // every reference, generic-type-argument, and `new` of a record dropped on the
  5946. // floor and the defining file showed 0 dependents. (#237)
  5947. it('extracts a record as a graph node (record class + record struct)', () => {
  5948. const r = extractFromSource('r.cs', `namespace P;\npublic record Box(int N);\npublic record struct Pt(int X);\n`);
  5949. expect(r.nodes.find((n) => n.name === 'Box' && (n.kind === 'class' || n.kind === 'struct'))).toBeDefined();
  5950. expect(r.nodes.find((n) => n.name === 'Pt' && (n.kind === 'class' || n.kind === 'struct'))).toBeDefined();
  5951. });
  5952. it('resolves references / instantiations of a record across files', async () => {
  5953. const dir = createTempDir();
  5954. try {
  5955. fs.writeFileSync(path.join(dir, 'types.cs'), `namespace P;\npublic record Box(int N);\n`);
  5956. // Box is used as a generic type argument and instantiated — both require
  5957. // Box to be a node to resolve.
  5958. fs.writeFileSync(
  5959. path.join(dir, 'use.cs'),
  5960. `using System.Collections.Generic;\nnamespace P;\npublic class User {\n public IEnumerable<Box> Boxes { get; }\n public Box Make() => new Box(1);\n}\n`
  5961. );
  5962. const cg = CodeGraph.initSync(dir, { config: { include: ['**/*.cs'], exclude: [] } });
  5963. await cg.indexAll();
  5964. cg.resolveReferences();
  5965. expect(cg.getFileDependents('types.cs')).toContain('use.cs');
  5966. cg.destroy();
  5967. } finally {
  5968. cleanupTempDir(dir);
  5969. }
  5970. });
  5971. });
  5972. describe('Rust cross-module recall', () => {
  5973. function rustProject(files: Record<string, string>): string {
  5974. const dir = createTempDir();
  5975. fs.writeFileSync(path.join(dir, 'Cargo.toml'), '[package]\nname = "proj"\nversion = "0.1.0"\nedition = "2021"\n');
  5976. fs.mkdirSync(path.join(dir, 'src'), { recursive: true });
  5977. for (const [rel, content] of Object.entries(files)) {
  5978. const full = path.join(dir, 'src', rel);
  5979. fs.mkdirSync(path.dirname(full), { recursive: true });
  5980. fs.writeFileSync(full, content);
  5981. }
  5982. return dir;
  5983. }
  5984. it('extracts a struct literal `Foo { .. }` as an instantiation across modules', async () => {
  5985. const dir = rustProject({
  5986. 'lib.rs': 'pub mod types;\npub mod consumer;\n',
  5987. 'types.rs': 'pub struct Widget { pub n: i32 }\n',
  5988. 'consumer.rs': 'use crate::types::Widget;\npub fn build() -> Widget { Widget { n: 1 } }\n',
  5989. });
  5990. try {
  5991. const cg = CodeGraph.initSync(dir, { config: { include: ['src/**/*.rs'], exclude: [] } });
  5992. await cg.indexAll();
  5993. cg.resolveReferences();
  5994. expect(cg.getFileDependents('src/types.rs')).toContain('src/consumer.rs');
  5995. cg.destroy();
  5996. } finally { cleanupTempDir(dir); }
  5997. });
  5998. it('extracts trait method declarations and bridges trait dispatch to the impl', async () => {
  5999. const dir = rustProject({
  6000. 'lib.rs': 'pub mod types;\npub mod consumer;\n',
  6001. 'types.rs': 'pub trait Render { fn render(&self) -> i32; }\n',
  6002. // Mine implements Render structurally; reached via &dyn Render dispatch.
  6003. 'consumer.rs': 'use crate::types::Render;\npub struct Mine { pub x: i32 }\nimpl Render for Mine { fn render(&self) -> i32 { self.x } }\n',
  6004. });
  6005. try {
  6006. const cg = CodeGraph.initSync(dir, { config: { include: ['src/**/*.rs'], exclude: [] } });
  6007. await cg.indexAll();
  6008. cg.resolveReferences();
  6009. // implements edge (Mine -> Render) makes types.rs a dependent of consumer.rs's struct.
  6010. expect(cg.getFileDependents('src/types.rs')).toContain('src/consumer.rs');
  6011. cg.destroy();
  6012. } finally { cleanupTempDir(dir); }
  6013. });
  6014. it('links `pub use` re-export hubs to the modules they re-export', async () => {
  6015. const dir = rustProject({
  6016. 'lib.rs': 'pub mod api;\n',
  6017. 'api/mod.rs': 'mod widget;\npub use self::widget::Widget;\n',
  6018. 'api/widget.rs': 'pub struct Widget { pub n: i32 }\n',
  6019. });
  6020. try {
  6021. const cg = CodeGraph.initSync(dir, { config: { include: ['src/**/*.rs'], exclude: [] } });
  6022. await cg.indexAll();
  6023. cg.resolveReferences();
  6024. // The re-export hub depends on the module it re-exports from.
  6025. expect(cg.getFileDependents('src/api/widget.rs')).toContain('src/api/mod.rs');
  6026. cg.destroy();
  6027. } finally { cleanupTempDir(dir); }
  6028. });
  6029. it('resolves a qualified path to the correct module when the leaf name collides', async () => {
  6030. const dir = rustProject({
  6031. 'lib.rs': 'pub mod fast;\npub mod slow;\npub mod hub;\n',
  6032. 'fast.rs': 'pub fn read() -> i32 { 1 }\n',
  6033. 'slow.rs': 'pub fn read() -> i32 { 2 }\n',
  6034. // `read` exists in BOTH fast.rs and slow.rs — module-path resolution must
  6035. // send this re-export to fast.rs specifically, not name-match either.
  6036. 'hub.rs': 'pub use crate::fast::read;\n',
  6037. });
  6038. try {
  6039. const cg = CodeGraph.initSync(dir, { config: { include: ['src/**/*.rs'], exclude: [] } });
  6040. await cg.indexAll();
  6041. cg.resolveReferences();
  6042. expect(cg.getFileDependents('src/fast.rs')).toContain('src/hub.rs');
  6043. expect(cg.getFileDependents('src/slow.rs')).not.toContain('src/hub.rs');
  6044. cg.destroy();
  6045. } finally { cleanupTempDir(dir); }
  6046. });
  6047. });
  6048. describe('Java annotations (blast-radius recall)', () => {
  6049. it('indexes @interface definitions and links @Annotation usages to them', async () => {
  6050. const dir = createTempDir();
  6051. try {
  6052. fs.mkdirSync(path.join(dir, 'p'), { recursive: true });
  6053. // The annotation DEFINITION must be a node, and the @MyAnno usages (which
  6054. // live inside a `modifiers` node on the class/field/method) must extract.
  6055. fs.writeFileSync(path.join(dir, 'p', 'MyAnno.java'), `package p;\npublic @interface MyAnno { String value() default ""; }\n`);
  6056. fs.writeFileSync(
  6057. path.join(dir, 'p', 'User.java'),
  6058. `package p;\n@MyAnno("c")\npublic class User {\n @MyAnno("f") int field;\n @MyAnno("m") void go() {}\n}\n`
  6059. );
  6060. const cg = CodeGraph.initSync(dir, { config: { include: ['**/*.java'], exclude: [] } });
  6061. await cg.indexAll();
  6062. cg.resolveReferences();
  6063. expect(cg.getFileDependents('p/MyAnno.java')).toContain('p/User.java');
  6064. cg.destroy();
  6065. } finally { cleanupTempDir(dir); }
  6066. });
  6067. });
  6068. describe('Swift property wrappers / attributes (blast-radius recall)', () => {
  6069. it('links a @propertyWrapper usage to the wrapper type', async () => {
  6070. const dir = createTempDir();
  6071. try {
  6072. fs.mkdirSync(path.join(dir, 'Sources', 'M'), { recursive: true });
  6073. fs.writeFileSync(path.join(dir, 'Sources', 'M', 'Wrap.swift'), `@propertyWrapper\npublic struct Argument<T> { public var wrappedValue: T }\n`);
  6074. // `@Argument` is a Swift attribute on a stored property — it lives in the
  6075. // property's `modifiers` and Swift doesn't extract instance properties as
  6076. // their own nodes, so without the fix the wrapper type has no users.
  6077. fs.writeFileSync(path.join(dir, 'Sources', 'M', 'Cmd.swift'), `public struct MyCommand {\n @Argument var name: String\n @Argument var count: Int\n}\n`);
  6078. const cg = CodeGraph.initSync(dir, { config: { include: ['Sources/**/*.swift'], exclude: [] } });
  6079. await cg.indexAll();
  6080. cg.resolveReferences();
  6081. expect(cg.getFileDependents('Sources/M/Wrap.swift')).toContain('Sources/M/Cmd.swift');
  6082. cg.destroy();
  6083. } finally { cleanupTempDir(dir); }
  6084. });
  6085. });
  6086. describe('R Extraction', () => {
  6087. describe('Language detection', () => {
  6088. it('should detect R files (both extension cases)', () => {
  6089. expect(detectLanguage('analysis.R')).toBe('r');
  6090. expect(detectLanguage('scripts/clean.r')).toBe('r');
  6091. });
  6092. it('should report R as supported', () => {
  6093. expect(isLanguageSupported('r')).toBe(true);
  6094. expect(getSupportedLanguages()).toContain('r');
  6095. });
  6096. });
  6097. describe('Function extraction', () => {
  6098. it('extracts every assignment form, lambdas, and nested functions', () => {
  6099. const code = `
  6100. clean_data <- function(df, threshold = 0.5) {
  6101. helper <- function(d) scale(d)
  6102. helper(df)
  6103. }
  6104. normalize = function(v) (v - mean(v)) / sd(v)
  6105. double_it <- \\(x) x * 2
  6106. `;
  6107. const result = extractFromSource('analysis.R', code);
  6108. const funcs = result.nodes.filter((n) => n.kind === 'function').map((n) => n.name);
  6109. expect(funcs).toContain('clean_data');
  6110. expect(funcs).toContain('normalize');
  6111. expect(funcs).toContain('double_it');
  6112. expect(funcs).toContain('helper'); // nested, inside clean_data's scope
  6113. const cleanData = result.nodes.find((n) => n.name === 'clean_data');
  6114. expect(cleanData?.language).toBe('r');
  6115. expect(cleanData?.signature).toBe('(df, threshold = 0.5)');
  6116. });
  6117. it('attributes body calls to the enclosing function', () => {
  6118. const code = `
  6119. prep <- function(d) scale(d)
  6120. fit_model <- function(data) {
  6121. lm(y ~ x, data = prep(data))
  6122. }
  6123. `;
  6124. const result = extractFromSource('models.R', code);
  6125. const prepCall = result.unresolvedReferences.find(
  6126. (r) => r.referenceName === 'prep' && r.referenceKind === 'calls'
  6127. );
  6128. expect(prepCall).toBeDefined();
  6129. const fitModel = result.nodes.find((n) => n.name === 'fit_model');
  6130. expect(prepCall?.fromNodeId).toBe(fitModel?.id);
  6131. });
  6132. });
  6133. describe('Imports', () => {
  6134. it('extracts library/require/source as imports, not calls', () => {
  6135. const code = `
  6136. library(dplyr)
  6137. require(stats)
  6138. requireNamespace("jsonlite")
  6139. source("helpers.R")
  6140. `;
  6141. const result = extractFromSource('main.R', code);
  6142. const imports = result.nodes.filter((n) => n.kind === 'import').map((n) => n.name);
  6143. expect(imports).toContain('dplyr');
  6144. expect(imports).toContain('stats');
  6145. expect(imports).toContain('jsonlite');
  6146. expect(imports).toContain('helpers.R');
  6147. // Claimed by the hook — no call references to the import machinery.
  6148. const libCalls = result.unresolvedReferences.filter(
  6149. (r) => r.referenceKind === 'calls' && (r.referenceName === 'library' || r.referenceName === 'source')
  6150. );
  6151. expect(libCalls).toHaveLength(0);
  6152. });
  6153. });
  6154. describe('Variables and constants', () => {
  6155. it('extracts top-level assignments; ALL_CAPS as constants; right-assign too', () => {
  6156. const code = `
  6157. ALPHA <- 0.05
  6158. max_iter = 100
  6159. compute_stats(df) -> stats_result
  6160. inner <- function() {
  6161. local_var <- 1
  6162. }
  6163. `;
  6164. const result = extractFromSource('config.R', code);
  6165. const constant = result.nodes.find((n) => n.name === 'ALPHA');
  6166. expect(constant?.kind).toBe('constant');
  6167. const variable = result.nodes.find((n) => n.name === 'max_iter');
  6168. expect(variable?.kind).toBe('variable');
  6169. const rightAssigned = result.nodes.find((n) => n.name === 'stats_result');
  6170. expect(rightAssigned?.kind).toBe('variable');
  6171. // Locals inside functions are deliberately NOT extracted.
  6172. expect(result.nodes.find((n) => n.name === 'local_var')).toBeUndefined();
  6173. });
  6174. });
  6175. describe('Classes', () => {
  6176. it('extracts S4/R5/R6 class calls as classes with their list methods', () => {
  6177. const code = `
  6178. setClass("Patient", representation(id = "character"))
  6179. Account <- setRefClass("Account",
  6180. fields = list(balance = "numeric"),
  6181. methods = list(deposit = function(x) { balance <<- balance + x })
  6182. )
  6183. Stack <- R6Class("Stack",
  6184. public = list(push = function(v) invisible(v))
  6185. )
  6186. setGeneric("describe", function(obj) standardGeneric("describe"))
  6187. setMethod("describe", "Patient", function(obj) paste(obj@id))
  6188. `;
  6189. const result = extractFromSource('classes.R', code);
  6190. const classes = result.nodes.filter((n) => n.kind === 'class').map((n) => n.name);
  6191. expect(classes).toContain('Patient');
  6192. expect(classes).toContain('Account');
  6193. expect(classes).toContain('Stack');
  6194. const methods = result.nodes.filter((n) => n.kind === 'method').map((n) => n.name);
  6195. expect(methods).toContain('deposit');
  6196. expect(methods).toContain('push');
  6197. // setGeneric/setMethod produce functions named by their string argument.
  6198. const describes = result.nodes.filter((n) => n.name === 'describe' && n.kind === 'function');
  6199. expect(describes.length).toBeGreaterThanOrEqual(2);
  6200. // The class-assignment idiom must not ALSO produce a variable node.
  6201. expect(result.nodes.find((n) => n.name === 'Account' && n.kind === 'variable')).toBeUndefined();
  6202. });
  6203. it('extracts ggproto classes with direct-arg methods and the parent as extends', () => {
  6204. // ggplot2's OO system — every Geom/Stat/Scale in the ecosystem uses it.
  6205. const code = `
  6206. GeomPoint <- ggproto("GeomPoint", Geom,
  6207. required_aes = c("x", "y"),
  6208. draw_panel = function(data, panel_params, coord) {
  6209. coords <- coord$transform(data, panel_params)
  6210. grid::pointsGrob(coords$x, coords$y)
  6211. },
  6212. draw_key = draw_key_point
  6213. )
  6214. `;
  6215. const result = extractFromSource('geom-point.R', code);
  6216. const cls = result.nodes.find((n) => n.name === 'GeomPoint' && n.kind === 'class');
  6217. expect(cls).toBeDefined();
  6218. const method = result.nodes.find((n) => n.name === 'draw_panel' && n.kind === 'method');
  6219. expect(method).toBeDefined();
  6220. const ext = result.unresolvedReferences.find(
  6221. (r) => r.referenceKind === 'extends' && r.referenceName === 'Geom'
  6222. );
  6223. expect(ext?.fromNodeId).toBe(cls?.id);
  6224. // No twin variable for the assignment.
  6225. expect(result.nodes.find((n) => n.name === 'GeomPoint' && n.kind === 'variable')).toBeUndefined();
  6226. });
  6227. });
  6228. });