1
0

extraction.test.ts 231 KB

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