extraction.test.ts 230 KB

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