extraction.test.ts 247 KB

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