extraction.test.ts 233 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583
  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. it('should extract include/require (+_once) static paths as imports (#660)', () => {
  1876. const code = `<?php
  1877. require_once("lib.php");
  1878. include 'other.php';
  1879. require 'r.php';
  1880. include_once("io.php");
  1881. `;
  1882. const result = extractFromSource('page.php', code);
  1883. const names = result.nodes.filter((n) => n.kind === 'import').map((n) => n.name);
  1884. expect(names).toContain('lib.php');
  1885. expect(names).toContain('other.php');
  1886. expect(names).toContain('r.php');
  1887. expect(names).toContain('io.php');
  1888. });
  1889. it('should skip dynamic include/require with no static path (#660)', () => {
  1890. const code = `<?php
  1891. require_once(__DIR__ . '/dyn.php');
  1892. include $file;
  1893. include "tpl/{$name}.php";
  1894. `;
  1895. const result = extractFromSource('page.php', code);
  1896. const imports = result.nodes.filter((n) => n.kind === 'import');
  1897. expect(imports).toHaveLength(0);
  1898. });
  1899. it('should extract include alongside namespace use without interference (#660)', () => {
  1900. const code = `<?php
  1901. use App\\Service\\Mailer;
  1902. require_once("bootstrap.php");
  1903. `;
  1904. const result = extractFromSource('page.php', code);
  1905. const names = result.nodes.filter((n) => n.kind === 'import').map((n) => n.name);
  1906. expect(names).toContain('App\\Service\\Mailer');
  1907. expect(names).toContain('bootstrap.php');
  1908. });
  1909. });
  1910. describe('Ruby imports', () => {
  1911. it('should extract require', () => {
  1912. const code = `require 'json'`;
  1913. const result = extractFromSource('app.rb', code);
  1914. const importNode = result.nodes.find((n) => n.kind === 'import');
  1915. expect(importNode).toBeDefined();
  1916. expect(importNode?.name).toBe('json');
  1917. expect(importNode?.signature).toBe("require 'json'");
  1918. });
  1919. it('should extract require with path', () => {
  1920. const code = `require 'active_support/core_ext/string'`;
  1921. const result = extractFromSource('config.rb', code);
  1922. const importNode = result.nodes.find((n) => n.kind === 'import');
  1923. expect(importNode).toBeDefined();
  1924. expect(importNode?.name).toBe('active_support/core_ext/string');
  1925. });
  1926. it('should extract require_relative', () => {
  1927. const code = `require_relative '../test_helper'`;
  1928. const result = extractFromSource('test/my_test.rb', code);
  1929. const importNode = result.nodes.find((n) => n.kind === 'import');
  1930. expect(importNode).toBeDefined();
  1931. expect(importNode?.name).toBe('../test_helper');
  1932. expect(importNode?.signature).toContain('require_relative');
  1933. });
  1934. it('should not extract non-require calls', () => {
  1935. const code = `puts 'hello'`;
  1936. const result = extractFromSource('app.rb', code);
  1937. const importNode = result.nodes.find((n) => n.kind === 'import');
  1938. expect(importNode).toBeUndefined();
  1939. });
  1940. it('should extract multiple requires', () => {
  1941. const code = `
  1942. require 'json'
  1943. require 'yaml'
  1944. require_relative 'helper'
  1945. `;
  1946. const result = extractFromSource('lib.rb', code);
  1947. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1948. expect(importNodes.length).toBe(3);
  1949. const names = importNodes.map((n) => n.name);
  1950. expect(names).toContain('json');
  1951. expect(names).toContain('yaml');
  1952. expect(names).toContain('helper');
  1953. });
  1954. });
  1955. describe('Ruby modules', () => {
  1956. it('should extract module as module node with containment', () => {
  1957. const code = `
  1958. module CachedCounting
  1959. def self.disable
  1960. @enabled = false
  1961. end
  1962. def perform_increment!(key, count)
  1963. write_cache!(key, count)
  1964. end
  1965. end
  1966. `;
  1967. const result = extractFromSource('concerns/cached_counting.rb', code);
  1968. const moduleNode = result.nodes.find((n) => n.kind === 'module' && n.name === 'CachedCounting');
  1969. expect(moduleNode).toBeDefined();
  1970. expect(moduleNode?.qualifiedName).toBe('CachedCounting');
  1971. // Methods inside module should have module-qualified names
  1972. const disableMethod = result.nodes.find((n) => n.name === 'disable' && n.kind === 'method');
  1973. expect(disableMethod).toBeDefined();
  1974. expect(disableMethod?.qualifiedName).toBe('CachedCounting::disable');
  1975. const incrementMethod = result.nodes.find((n) => n.name === 'perform_increment!' && n.kind === 'method');
  1976. expect(incrementMethod).toBeDefined();
  1977. expect(incrementMethod?.qualifiedName).toBe('CachedCounting::perform_increment!');
  1978. // Containment edge from module to methods
  1979. const containsEdges = result.edges.filter((e) => e.source === moduleNode?.id && e.kind === 'contains');
  1980. expect(containsEdges.length).toBeGreaterThanOrEqual(2);
  1981. });
  1982. it('should handle nested modules with classes', () => {
  1983. const code = `
  1984. module Discourse
  1985. module Auth
  1986. class AuthProvider
  1987. def authenticate(params)
  1988. validate(params)
  1989. end
  1990. end
  1991. end
  1992. end
  1993. `;
  1994. const result = extractFromSource('lib/auth.rb', code);
  1995. const discourseModule = result.nodes.find((n) => n.kind === 'module' && n.name === 'Discourse');
  1996. expect(discourseModule).toBeDefined();
  1997. const authModule = result.nodes.find((n) => n.kind === 'module' && n.name === 'Auth');
  1998. expect(authModule).toBeDefined();
  1999. expect(authModule?.qualifiedName).toBe('Discourse::Auth');
  2000. const authProvider = result.nodes.find((n) => n.kind === 'class' && n.name === 'AuthProvider');
  2001. expect(authProvider).toBeDefined();
  2002. expect(authProvider?.qualifiedName).toBe('Discourse::Auth::AuthProvider');
  2003. const authMethod = result.nodes.find((n) => n.name === 'authenticate');
  2004. expect(authMethod).toBeDefined();
  2005. expect(authMethod?.qualifiedName).toBe('Discourse::Auth::AuthProvider::authenticate');
  2006. });
  2007. });
  2008. describe('C/C++ return type capture (#645)', () => {
  2009. it('captures the normalized return type of a C++ method/function', () => {
  2010. const code = `
  2011. struct Widget { void draw(); };
  2012. class Factory { public: static Widget create(); };
  2013. Widget Factory::create() { return Widget(); }
  2014. void doNothing() {}
  2015. `;
  2016. const result = extractFromSource('f.cpp', code);
  2017. const create = result.nodes.find(
  2018. (n) => n.name === 'create' && (n.kind === 'method' || n.kind === 'function')
  2019. );
  2020. expect(create?.returnType).toBe('Widget');
  2021. // A `void` return records no type, so resolution never tries to resolve a
  2022. // method on it.
  2023. const doNothing = result.nodes.find((n) => n.name === 'doNothing');
  2024. expect(doNothing).toBeDefined();
  2025. expect(doNothing?.returnType).toBeUndefined();
  2026. });
  2027. it('unwraps a smart-pointer return type to its pointee', () => {
  2028. const code = `
  2029. #include <memory>
  2030. struct Widget {};
  2031. std::unique_ptr<Widget> makeWidget() { return nullptr; }
  2032. `;
  2033. const result = extractFromSource('f.cpp', code);
  2034. const make = result.nodes.find((n) => n.name === 'makeWidget');
  2035. expect(make?.returnType).toBe('Widget');
  2036. });
  2037. });
  2038. describe('C/C++ imports', () => {
  2039. it('should extract system include', () => {
  2040. const code = `#include <iostream>`;
  2041. const result = extractFromSource('main.cpp', code);
  2042. const importNode = result.nodes.find((n) => n.kind === 'import');
  2043. expect(importNode).toBeDefined();
  2044. expect(importNode?.name).toBe('iostream');
  2045. expect(importNode?.signature).toBe('#include <iostream>');
  2046. });
  2047. it('should extract system include with path', () => {
  2048. const code = `#include <nlohmann/json.hpp>`;
  2049. const result = extractFromSource('app.cpp', code);
  2050. const importNode = result.nodes.find((n) => n.kind === 'import');
  2051. expect(importNode).toBeDefined();
  2052. expect(importNode?.name).toBe('nlohmann/json.hpp');
  2053. });
  2054. it('should extract local include', () => {
  2055. const code = `#include "myheader.h"`;
  2056. const result = extractFromSource('main.cpp', code);
  2057. const importNode = result.nodes.find((n) => n.kind === 'import');
  2058. expect(importNode).toBeDefined();
  2059. expect(importNode?.name).toBe('myheader.h');
  2060. });
  2061. it('should extract C header', () => {
  2062. const code = `#include <stdio.h>`;
  2063. const result = extractFromSource('main.c', code);
  2064. const importNode = result.nodes.find((n) => n.kind === 'import');
  2065. expect(importNode).toBeDefined();
  2066. expect(importNode?.name).toBe('stdio.h');
  2067. });
  2068. it('should extract multiple includes', () => {
  2069. const code = `
  2070. #include <iostream>
  2071. #include <vector>
  2072. #include "config.h"
  2073. `;
  2074. const result = extractFromSource('app.cpp', code);
  2075. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  2076. expect(importNodes.length).toBe(3);
  2077. const names = importNodes.map((n) => n.name);
  2078. expect(names).toContain('iostream');
  2079. expect(names).toContain('vector');
  2080. expect(names).toContain('config.h');
  2081. });
  2082. it('should create unresolved references for local includes', () => {
  2083. const code = `#include "myheader.h"`;
  2084. const result = extractFromSource('main.cpp', code);
  2085. const importRef = result.unresolvedReferences.find(
  2086. (r) => r.referenceKind === 'imports' && r.referenceName === 'myheader.h'
  2087. );
  2088. expect(importRef).toBeDefined();
  2089. expect(importRef?.line).toBe(1);
  2090. });
  2091. it('should create unresolved references for system includes', () => {
  2092. const code = `#include <iostream>`;
  2093. const result = extractFromSource('main.cpp', code);
  2094. const importRef = result.unresolvedReferences.find(
  2095. (r) => r.referenceKind === 'imports' && r.referenceName === 'iostream'
  2096. );
  2097. expect(importRef).toBeDefined();
  2098. });
  2099. });
  2100. describe('Dart imports', () => {
  2101. it('should extract dart: import', () => {
  2102. const code = `import 'dart:async';`;
  2103. const result = extractFromSource('main.dart', code);
  2104. const importNode = result.nodes.find((n) => n.kind === 'import');
  2105. expect(importNode).toBeDefined();
  2106. expect(importNode?.name).toBe('dart:async');
  2107. expect(importNode?.signature).toBe("import 'dart:async';");
  2108. });
  2109. it('should extract package import', () => {
  2110. const code = `import 'package:flutter/material.dart';`;
  2111. const result = extractFromSource('app.dart', code);
  2112. const importNode = result.nodes.find((n) => n.kind === 'import');
  2113. expect(importNode).toBeDefined();
  2114. expect(importNode?.name).toBe('package:flutter/material.dart');
  2115. });
  2116. it('should extract aliased import', () => {
  2117. const code = `import 'package:http/http.dart' as http;`;
  2118. const result = extractFromSource('api.dart', code);
  2119. const importNode = result.nodes.find((n) => n.kind === 'import');
  2120. expect(importNode).toBeDefined();
  2121. expect(importNode?.name).toBe('package:http/http.dart');
  2122. expect(importNode?.signature).toContain('as http');
  2123. });
  2124. it('should extract multiple imports', () => {
  2125. const code = `
  2126. import 'dart:async';
  2127. import 'dart:convert';
  2128. import 'package:flutter/material.dart';
  2129. `;
  2130. const result = extractFromSource('main.dart', code);
  2131. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  2132. expect(importNodes.length).toBe(3);
  2133. const names = importNodes.map((n) => n.name);
  2134. expect(names).toContain('dart:async');
  2135. expect(names).toContain('dart:convert');
  2136. expect(names).toContain('package:flutter/material.dart');
  2137. });
  2138. it('should extract relative import', () => {
  2139. const code = `import '../utils/helpers.dart';`;
  2140. const result = extractFromSource('lib/main.dart', code);
  2141. const importNode = result.nodes.find((n) => n.kind === 'import');
  2142. expect(importNode).toBeDefined();
  2143. expect(importNode?.name).toBe('../utils/helpers.dart');
  2144. });
  2145. });
  2146. describe('Liquid imports', () => {
  2147. it('should extract render tag', () => {
  2148. const code = `{% render 'loading-spinner' %}`;
  2149. const result = extractFromSource('template.liquid', code);
  2150. const importNode = result.nodes.find((n) => n.kind === 'import');
  2151. expect(importNode).toBeDefined();
  2152. expect(importNode?.name).toBe('loading-spinner');
  2153. expect(importNode?.signature).toContain('render');
  2154. });
  2155. it('should extract section tag', () => {
  2156. const code = `{% section 'header' %}`;
  2157. const result = extractFromSource('layout/theme.liquid', code);
  2158. const importNode = result.nodes.find((n) => n.kind === 'import');
  2159. expect(importNode).toBeDefined();
  2160. expect(importNode?.name).toBe('header');
  2161. expect(importNode?.signature).toContain('section');
  2162. });
  2163. it('should extract include tag', () => {
  2164. const code = `{% include 'icon-cart' %}`;
  2165. const result = extractFromSource('snippets/header.liquid', code);
  2166. const importNode = result.nodes.find((n) => n.kind === 'import');
  2167. expect(importNode).toBeDefined();
  2168. expect(importNode?.name).toBe('icon-cart');
  2169. expect(importNode?.signature).toContain('include');
  2170. });
  2171. it('should extract render with whitespace control', () => {
  2172. const code = `{%- render 'price' -%}`;
  2173. const result = extractFromSource('snippets/product.liquid', code);
  2174. const importNode = result.nodes.find((n) => n.kind === 'import');
  2175. expect(importNode).toBeDefined();
  2176. expect(importNode?.name).toBe('price');
  2177. });
  2178. it('should extract multiple imports', () => {
  2179. const code = `
  2180. {% section 'header' %}
  2181. {% render 'loading-spinner' %}
  2182. {% render 'cart-drawer' %}
  2183. `;
  2184. const result = extractFromSource('layout/theme.liquid', code);
  2185. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  2186. expect(importNodes.length).toBe(3);
  2187. const names = importNodes.map((n) => n.name);
  2188. expect(names).toContain('header');
  2189. expect(names).toContain('loading-spinner');
  2190. expect(names).toContain('cart-drawer');
  2191. });
  2192. });
  2193. });
  2194. // =============================================================================
  2195. // Pascal / Delphi Extraction
  2196. // =============================================================================
  2197. describe('Pascal / Delphi Extraction', () => {
  2198. describe('Language detection', () => {
  2199. it('should detect Pascal files', () => {
  2200. expect(detectLanguage('UAuth.pas')).toBe('pascal');
  2201. expect(detectLanguage('App.dpr')).toBe('pascal');
  2202. expect(detectLanguage('Package.dpk')).toBe('pascal');
  2203. expect(detectLanguage('App.lpr')).toBe('pascal');
  2204. expect(detectLanguage('MainForm.dfm')).toBe('pascal');
  2205. expect(detectLanguage('MainForm.fmx')).toBe('pascal');
  2206. });
  2207. it('should report Pascal as supported', () => {
  2208. expect(isLanguageSupported('pascal')).toBe(true);
  2209. expect(getSupportedLanguages()).toContain('pascal');
  2210. });
  2211. });
  2212. describe('Unit extraction', () => {
  2213. it('should extract unit as module', () => {
  2214. const code = `unit MyUnit;\ninterface\nimplementation\nend.`;
  2215. const result = extractFromSource('MyUnit.pas', code);
  2216. const moduleNode = result.nodes.find((n) => n.kind === 'module');
  2217. expect(moduleNode).toBeDefined();
  2218. expect(moduleNode?.name).toBe('MyUnit');
  2219. expect(moduleNode?.language).toBe('pascal');
  2220. });
  2221. it('should extract program as module', () => {
  2222. const code = `program MyApp;\nbegin\nend.`;
  2223. const result = extractFromSource('MyApp.dpr', code);
  2224. const moduleNode = result.nodes.find((n) => n.kind === 'module');
  2225. expect(moduleNode).toBeDefined();
  2226. expect(moduleNode?.name).toBe('MyApp');
  2227. });
  2228. it('should fallback to filename when module name is empty', () => {
  2229. // Some .dpr templates use "program;" without a name
  2230. const code = `program;\nuses SysUtils;\nbegin\nend.`;
  2231. const result = extractFromSource('Console.dpr', code);
  2232. const moduleNode = result.nodes.find((n) => n.kind === 'module');
  2233. expect(moduleNode).toBeDefined();
  2234. expect(moduleNode?.name).toBe('Console');
  2235. });
  2236. });
  2237. describe('Uses clause (imports)', () => {
  2238. it('should extract uses as individual imports', () => {
  2239. const code = `unit Test;\ninterface\nuses\n System.SysUtils,\n System.Classes;\nimplementation\nend.`;
  2240. const result = extractFromSource('Test.pas', code);
  2241. const imports = result.nodes.filter((n) => n.kind === 'import');
  2242. expect(imports.length).toBe(2);
  2243. expect(imports.map((n) => n.name)).toContain('System.SysUtils');
  2244. expect(imports.map((n) => n.name)).toContain('System.Classes');
  2245. });
  2246. it('should create unresolved references for imports', () => {
  2247. const code = `unit Test;\ninterface\nuses\n UAuth;\nimplementation\nend.`;
  2248. const result = extractFromSource('Test.pas', code);
  2249. const importRef = result.unresolvedReferences.find(
  2250. (r) => r.referenceKind === 'imports'
  2251. );
  2252. expect(importRef).toBeDefined();
  2253. expect(importRef?.referenceName).toBe('UAuth');
  2254. });
  2255. });
  2256. describe('Class extraction', () => {
  2257. it('should extract class declarations', () => {
  2258. const code = `unit Test;\ninterface\ntype\n TMyClass = class\n public\n procedure DoSomething;\n end;\nimplementation\nend.`;
  2259. const result = extractFromSource('Test.pas', code);
  2260. const classNode = result.nodes.find((n) => n.kind === 'class');
  2261. expect(classNode).toBeDefined();
  2262. expect(classNode?.name).toBe('TMyClass');
  2263. });
  2264. it('should extract class with inheritance', () => {
  2265. const code = `unit Test;\ninterface\ntype\n TChild = class(TParent)\n end;\nimplementation\nend.`;
  2266. const result = extractFromSource('Test.pas', code);
  2267. const extendsRef = result.unresolvedReferences.find(
  2268. (r) => r.referenceKind === 'extends'
  2269. );
  2270. expect(extendsRef).toBeDefined();
  2271. expect(extendsRef?.referenceName).toBe('TParent');
  2272. });
  2273. it('should extract class with interface implementation', () => {
  2274. const code = `unit Test;\ninterface\ntype\n TService = class(TInterfacedObject, ILogger)\n end;\nimplementation\nend.`;
  2275. const result = extractFromSource('Test.pas', code);
  2276. const extendsRef = result.unresolvedReferences.find(
  2277. (r) => r.referenceKind === 'extends'
  2278. );
  2279. const implementsRef = result.unresolvedReferences.find(
  2280. (r) => r.referenceKind === 'implements'
  2281. );
  2282. expect(extendsRef?.referenceName).toBe('TInterfacedObject');
  2283. expect(implementsRef?.referenceName).toBe('ILogger');
  2284. });
  2285. });
  2286. describe('Record extraction', () => {
  2287. it('should extract records as class nodes', () => {
  2288. const code = `unit Test;\ninterface\ntype\n TPoint = record\n X: Double;\n Y: Double;\n end;\nimplementation\nend.`;
  2289. const result = extractFromSource('Test.pas', code);
  2290. const classNode = result.nodes.find((n) => n.kind === 'class');
  2291. expect(classNode).toBeDefined();
  2292. expect(classNode?.name).toBe('TPoint');
  2293. const fields = result.nodes.filter((n) => n.kind === 'field');
  2294. expect(fields.length).toBe(2);
  2295. expect(fields.map((f) => f.name)).toContain('X');
  2296. expect(fields.map((f) => f.name)).toContain('Y');
  2297. });
  2298. });
  2299. describe('Interface extraction', () => {
  2300. it('should extract interface declarations', () => {
  2301. const code = `unit Test;\ninterface\ntype\n ILogger = interface\n procedure Log(const AMsg: string);\n end;\nimplementation\nend.`;
  2302. const result = extractFromSource('Test.pas', code);
  2303. const ifaceNode = result.nodes.find((n) => n.kind === 'interface');
  2304. expect(ifaceNode).toBeDefined();
  2305. expect(ifaceNode?.name).toBe('ILogger');
  2306. });
  2307. });
  2308. describe('Method extraction', () => {
  2309. it('should extract methods with visibility', () => {
  2310. 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.`;
  2311. const result = extractFromSource('Test.pas', code);
  2312. const methods = result.nodes.filter((n) => n.kind === 'method');
  2313. expect(methods.length).toBe(2);
  2314. const createMethod = methods.find((m) => m.name === 'Create');
  2315. expect(createMethod?.visibility).toBe('public');
  2316. const getValue = methods.find((m) => m.name === 'GetValue');
  2317. expect(getValue?.visibility).toBe('public');
  2318. const fields = result.nodes.filter((n) => n.kind === 'field');
  2319. const fValue = fields.find((f) => f.name === 'FValue');
  2320. expect(fValue?.visibility).toBe('private');
  2321. });
  2322. it('should detect static methods (class methods)', () => {
  2323. const code = `unit Test;\ninterface\ntype\n THelper = class\n public\n class function Create: THelper; static;\n end;\nimplementation\nend.`;
  2324. const result = extractFromSource('Test.pas', code);
  2325. const methods = result.nodes.filter((n) => n.kind === 'method');
  2326. const staticMethod = methods.find((m) => m.name === 'Create');
  2327. expect(staticMethod?.isStatic).toBe(true);
  2328. });
  2329. });
  2330. describe('Enum extraction', () => {
  2331. it('should extract enums with members', () => {
  2332. const code = `unit Test;\ninterface\ntype\n TColor = (clRed, clGreen, clBlue);\nimplementation\nend.`;
  2333. const result = extractFromSource('Test.pas', code);
  2334. const enumNode = result.nodes.find((n) => n.kind === 'enum');
  2335. expect(enumNode).toBeDefined();
  2336. expect(enumNode?.name).toBe('TColor');
  2337. const members = result.nodes.filter((n) => n.kind === 'enum_member');
  2338. expect(members.length).toBe(3);
  2339. expect(members.map((m) => m.name)).toEqual(['clRed', 'clGreen', 'clBlue']);
  2340. });
  2341. });
  2342. describe('Property extraction', () => {
  2343. it('should extract properties', () => {
  2344. const code = `unit Test;\ninterface\ntype\n TObj = class\n public\n property Name: string read FName write FName;\n end;\nimplementation\nend.`;
  2345. const result = extractFromSource('Test.pas', code);
  2346. const propNode = result.nodes.find((n) => n.kind === 'property');
  2347. expect(propNode).toBeDefined();
  2348. expect(propNode?.name).toBe('Name');
  2349. expect(propNode?.visibility).toBe('public');
  2350. });
  2351. });
  2352. describe('Constant extraction', () => {
  2353. it('should extract constants', () => {
  2354. const code = `unit Test;\ninterface\nconst\n MAX_RETRIES = 3;\n APP_NAME = 'MyApp';\nimplementation\nend.`;
  2355. const result = extractFromSource('Test.pas', code);
  2356. const constants = result.nodes.filter((n) => n.kind === 'constant');
  2357. expect(constants.length).toBe(2);
  2358. expect(constants.map((c) => c.name)).toContain('MAX_RETRIES');
  2359. expect(constants.map((c) => c.name)).toContain('APP_NAME');
  2360. });
  2361. });
  2362. describe('Type alias extraction', () => {
  2363. it('should extract type aliases', () => {
  2364. const code = `unit Test;\ninterface\ntype\n TUserName = string;\nimplementation\nend.`;
  2365. const result = extractFromSource('Test.pas', code);
  2366. const aliasNode = result.nodes.find((n) => n.kind === 'type_alias');
  2367. expect(aliasNode).toBeDefined();
  2368. expect(aliasNode?.name).toBe('TUserName');
  2369. });
  2370. });
  2371. describe('Call extraction', () => {
  2372. it('should extract calls from implementation bodies', () => {
  2373. 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.`;
  2374. const result = extractFromSource('Test.pas', code);
  2375. const callRef = result.unresolvedReferences.find(
  2376. (r) => r.referenceKind === 'calls'
  2377. );
  2378. expect(callRef).toBeDefined();
  2379. expect(callRef?.referenceName).toBe('WriteLn');
  2380. });
  2381. });
  2382. describe('Containment edges', () => {
  2383. it('should create contains edges for class members', () => {
  2384. const code = `unit Test;\ninterface\ntype\n TObj = class\n public\n procedure Foo;\n end;\nimplementation\nend.`;
  2385. const result = extractFromSource('Test.pas', code);
  2386. const classNode = result.nodes.find((n) => n.kind === 'class');
  2387. const methodNode = result.nodes.find((n) => n.kind === 'method');
  2388. expect(classNode).toBeDefined();
  2389. expect(methodNode).toBeDefined();
  2390. const containsEdge = result.edges.find(
  2391. (e) => e.source === classNode?.id && e.target === methodNode?.id && e.kind === 'contains'
  2392. );
  2393. expect(containsEdge).toBeDefined();
  2394. });
  2395. });
  2396. describe('Full fixture: UAuth.pas', () => {
  2397. const code = `unit UAuth;
  2398. interface
  2399. uses
  2400. System.SysUtils,
  2401. System.Classes;
  2402. type
  2403. ITokenValidator = interface
  2404. ['{11111111-1111-1111-1111-111111111111}']
  2405. function Validate(const AToken: string): Boolean;
  2406. end;
  2407. TAuthService = class(TInterfacedObject, ITokenValidator)
  2408. private
  2409. FToken: string;
  2410. FLoginCount: Integer;
  2411. procedure IncLoginCount;
  2412. protected
  2413. function GetToken: string;
  2414. public
  2415. constructor Create;
  2416. destructor Destroy; override;
  2417. function Validate(const AToken: string): Boolean;
  2418. function Login(const AUser, APass: string): string;
  2419. property Token: string read GetToken;
  2420. property LoginCount: Integer read FLoginCount;
  2421. end;
  2422. implementation
  2423. constructor TAuthService.Create;
  2424. begin
  2425. inherited Create;
  2426. FToken := '';
  2427. FLoginCount := 0;
  2428. end;
  2429. destructor TAuthService.Destroy;
  2430. begin
  2431. FToken := '';
  2432. inherited Destroy;
  2433. end;
  2434. procedure TAuthService.IncLoginCount;
  2435. begin
  2436. Inc(FLoginCount);
  2437. end;
  2438. function TAuthService.GetToken: string;
  2439. begin
  2440. Result := FToken;
  2441. end;
  2442. function TAuthService.Validate(const AToken: string): Boolean;
  2443. begin
  2444. Result := AToken <> '';
  2445. end;
  2446. function TAuthService.Login(const AUser, APass: string): string;
  2447. begin
  2448. IncLoginCount;
  2449. if Validate(AUser + ':' + APass) then
  2450. begin
  2451. FToken := AUser;
  2452. Result := 'ok';
  2453. end
  2454. else
  2455. Result := '';
  2456. end;
  2457. end.`;
  2458. it('should extract all expected nodes', () => {
  2459. const result = extractFromSource('UAuth.pas', code);
  2460. expect(result.errors).toHaveLength(0);
  2461. // Module
  2462. const moduleNode = result.nodes.find((n) => n.kind === 'module');
  2463. expect(moduleNode?.name).toBe('UAuth');
  2464. // Imports
  2465. const imports = result.nodes.filter((n) => n.kind === 'import');
  2466. expect(imports.length).toBe(2);
  2467. // Interface
  2468. const ifaceNode = result.nodes.find((n) => n.kind === 'interface');
  2469. expect(ifaceNode?.name).toBe('ITokenValidator');
  2470. // Class
  2471. const classNode = result.nodes.find((n) => n.kind === 'class');
  2472. expect(classNode?.name).toBe('TAuthService');
  2473. // Methods
  2474. const methods = result.nodes.filter((n) => n.kind === 'method');
  2475. expect(methods.length).toBeGreaterThanOrEqual(6);
  2476. expect(methods.map((m) => m.name)).toContain('Create');
  2477. expect(methods.map((m) => m.name)).toContain('Destroy');
  2478. expect(methods.map((m) => m.name)).toContain('Login');
  2479. // Fields
  2480. const fields = result.nodes.filter((n) => n.kind === 'field');
  2481. expect(fields.length).toBe(2);
  2482. expect(fields.every((f) => f.visibility === 'private')).toBe(true);
  2483. // Properties
  2484. const props = result.nodes.filter((n) => n.kind === 'property');
  2485. expect(props.length).toBe(2);
  2486. expect(props.map((p) => p.name)).toContain('Token');
  2487. expect(props.map((p) => p.name)).toContain('LoginCount');
  2488. });
  2489. it('should extract inheritance and interface implementation', () => {
  2490. const result = extractFromSource('UAuth.pas', code);
  2491. const extendsRef = result.unresolvedReferences.find(
  2492. (r) => r.referenceKind === 'extends'
  2493. );
  2494. expect(extendsRef?.referenceName).toBe('TInterfacedObject');
  2495. const implementsRef = result.unresolvedReferences.find(
  2496. (r) => r.referenceKind === 'implements'
  2497. );
  2498. expect(implementsRef?.referenceName).toBe('ITokenValidator');
  2499. });
  2500. it('should extract calls from implementation', () => {
  2501. const result = extractFromSource('UAuth.pas', code);
  2502. const callRefs = result.unresolvedReferences.filter(
  2503. (r) => r.referenceKind === 'calls'
  2504. );
  2505. expect(callRefs.map((r) => r.referenceName)).toContain('Inc');
  2506. expect(callRefs.map((r) => r.referenceName)).toContain('Validate');
  2507. });
  2508. });
  2509. describe('Full fixture: UTypes.pas', () => {
  2510. const code = `unit UTypes;
  2511. interface
  2512. uses
  2513. System.SysUtils;
  2514. const
  2515. C_MAX_RETRIES = 3;
  2516. C_DEFAULT_NAME = 'Guest';
  2517. type
  2518. TUserRole = (urAdmin, urEditor, urViewer);
  2519. TPoint2D = record
  2520. X: Double;
  2521. Y: Double;
  2522. end;
  2523. TUserName = string;
  2524. TUserInfo = class
  2525. public
  2526. type
  2527. TAddress = record
  2528. Street: string;
  2529. City: string;
  2530. Zip: string;
  2531. end;
  2532. private
  2533. FName: TUserName;
  2534. FRole: TUserRole;
  2535. FAddress: TAddress;
  2536. public
  2537. constructor Create(const AName: TUserName; ARole: TUserRole);
  2538. function GetDisplayName: string;
  2539. class function CreateAdmin(const AName: TUserName): TUserInfo; static;
  2540. property Name: TUserName read FName write FName;
  2541. property Role: TUserRole read FRole;
  2542. property Address: TAddress read FAddress write FAddress;
  2543. end;
  2544. implementation
  2545. constructor TUserInfo.Create(const AName: TUserName; ARole: TUserRole);
  2546. begin
  2547. FName := AName;
  2548. FRole := ARole;
  2549. end;
  2550. function TUserInfo.GetDisplayName: string;
  2551. begin
  2552. if FRole = urAdmin then
  2553. Result := '[Admin] ' + FName
  2554. else
  2555. Result := FName;
  2556. end;
  2557. class function TUserInfo.CreateAdmin(const AName: TUserName): TUserInfo;
  2558. begin
  2559. Result := TUserInfo.Create(AName, urAdmin);
  2560. end;
  2561. end.`;
  2562. it('should extract enums with members', () => {
  2563. const result = extractFromSource('UTypes.pas', code);
  2564. const enumNode = result.nodes.find((n) => n.kind === 'enum');
  2565. expect(enumNode?.name).toBe('TUserRole');
  2566. const members = result.nodes.filter((n) => n.kind === 'enum_member');
  2567. expect(members.length).toBe(3);
  2568. expect(members.map((m) => m.name)).toEqual(['urAdmin', 'urEditor', 'urViewer']);
  2569. });
  2570. it('should extract constants', () => {
  2571. const result = extractFromSource('UTypes.pas', code);
  2572. const constants = result.nodes.filter((n) => n.kind === 'constant');
  2573. expect(constants.length).toBe(2);
  2574. expect(constants.map((c) => c.name)).toContain('C_MAX_RETRIES');
  2575. expect(constants.map((c) => c.name)).toContain('C_DEFAULT_NAME');
  2576. });
  2577. it('should extract type aliases', () => {
  2578. const result = extractFromSource('UTypes.pas', code);
  2579. const aliases = result.nodes.filter((n) => n.kind === 'type_alias');
  2580. expect(aliases.map((a) => a.name)).toContain('TUserName');
  2581. });
  2582. it('should extract records as classes with fields', () => {
  2583. const result = extractFromSource('UTypes.pas', code);
  2584. const classes = result.nodes.filter((n) => n.kind === 'class');
  2585. expect(classes.map((c) => c.name)).toContain('TPoint2D');
  2586. // TPoint2D fields
  2587. const fields = result.nodes.filter((n) => n.kind === 'field');
  2588. expect(fields.map((f) => f.name)).toContain('X');
  2589. expect(fields.map((f) => f.name)).toContain('Y');
  2590. });
  2591. it('should extract static class methods', () => {
  2592. const result = extractFromSource('UTypes.pas', code);
  2593. const methods = result.nodes.filter((n) => n.kind === 'method');
  2594. const staticMethod = methods.find((m) => m.name === 'CreateAdmin');
  2595. expect(staticMethod).toBeDefined();
  2596. expect(staticMethod?.isStatic).toBe(true);
  2597. });
  2598. it('should extract nested types', () => {
  2599. const result = extractFromSource('UTypes.pas', code);
  2600. const classes = result.nodes.filter((n) => n.kind === 'class');
  2601. expect(classes.map((c) => c.name)).toContain('TAddress');
  2602. });
  2603. });
  2604. });
  2605. // =============================================================================
  2606. // DFM/FMX Extraction
  2607. // =============================================================================
  2608. describe('DFM/FMX Extraction', () => {
  2609. it('should extract components from DFM', () => {
  2610. const code = `object Form1: TForm1
  2611. Left = 0
  2612. Top = 0
  2613. Caption = 'My Form'
  2614. object Button1: TButton
  2615. Left = 10
  2616. Top = 10
  2617. Caption = 'Click Me'
  2618. end
  2619. end`;
  2620. const result = extractFromSource('Form1.dfm', code);
  2621. const components = result.nodes.filter((n) => n.kind === 'component');
  2622. expect(components.length).toBe(2);
  2623. expect(components.map((c) => c.name)).toContain('Form1');
  2624. expect(components.map((c) => c.name)).toContain('Button1');
  2625. const button = components.find((c) => c.name === 'Button1');
  2626. expect(button?.signature).toBe('TButton');
  2627. });
  2628. it('should extract nested component hierarchy', () => {
  2629. const code = `object Form1: TForm1
  2630. object Panel1: TPanel
  2631. object Label1: TLabel
  2632. Caption = 'Hello'
  2633. end
  2634. end
  2635. end`;
  2636. const result = extractFromSource('Form1.dfm', code);
  2637. const components = result.nodes.filter((n) => n.kind === 'component');
  2638. expect(components.length).toBe(3);
  2639. // Check nesting: Panel1 contains Label1
  2640. const panel = components.find((c) => c.name === 'Panel1');
  2641. const label = components.find((c) => c.name === 'Label1');
  2642. const containsEdge = result.edges.find(
  2643. (e) => e.source === panel?.id && e.target === label?.id && e.kind === 'contains'
  2644. );
  2645. expect(containsEdge).toBeDefined();
  2646. });
  2647. it('should extract event handler references', () => {
  2648. const code = `object Form1: TForm1
  2649. OnCreate = FormCreate
  2650. OnDestroy = FormDestroy
  2651. object Button1: TButton
  2652. OnClick = Button1Click
  2653. end
  2654. end`;
  2655. const result = extractFromSource('Form1.dfm', code);
  2656. const refs = result.unresolvedReferences;
  2657. expect(refs.length).toBe(3);
  2658. expect(refs.map((r) => r.referenceName)).toContain('FormCreate');
  2659. expect(refs.map((r) => r.referenceName)).toContain('FormDestroy');
  2660. expect(refs.map((r) => r.referenceName)).toContain('Button1Click');
  2661. expect(refs.every((r) => r.referenceKind === 'references')).toBe(true);
  2662. });
  2663. it('should handle multi-line properties', () => {
  2664. const code = `object Form1: TForm1
  2665. SQL.Strings = (
  2666. 'SELECT * FROM users'
  2667. 'WHERE active = 1')
  2668. object Button1: TButton
  2669. OnClick = Button1Click
  2670. end
  2671. end`;
  2672. const result = extractFromSource('Form1.dfm', code);
  2673. const components = result.nodes.filter((n) => n.kind === 'component');
  2674. expect(components.length).toBe(2);
  2675. const refs = result.unresolvedReferences;
  2676. expect(refs.length).toBe(1);
  2677. expect(refs[0]?.referenceName).toBe('Button1Click');
  2678. });
  2679. it('should handle inherited keyword', () => {
  2680. const code = `inherited Form1: TForm1
  2681. Caption = 'Inherited Form'
  2682. object Button1: TButton
  2683. OnClick = Button1Click
  2684. end
  2685. end`;
  2686. const result = extractFromSource('Form1.dfm', code);
  2687. const components = result.nodes.filter((n) => n.kind === 'component');
  2688. expect(components.length).toBe(2);
  2689. expect(components.map((c) => c.name)).toContain('Form1');
  2690. });
  2691. it('should handle item collection properties', () => {
  2692. const code = `object Form1: TForm1
  2693. object StatusBar1: TStatusBar
  2694. Panels = <
  2695. item
  2696. Width = 200
  2697. end
  2698. item
  2699. Width = 200
  2700. end>
  2701. end
  2702. end`;
  2703. const result = extractFromSource('Form1.dfm', code);
  2704. const components = result.nodes.filter((n) => n.kind === 'component');
  2705. expect(components.length).toBe(2);
  2706. });
  2707. describe('Full fixture: MainForm.dfm', () => {
  2708. const code = `object frmMain: TfrmMain
  2709. Left = 0
  2710. Top = 0
  2711. Caption = 'CodeGraph DFM Fixture'
  2712. ClientHeight = 480
  2713. ClientWidth = 640
  2714. OnCreate = FormCreate
  2715. OnDestroy = FormDestroy
  2716. object pnlTop: TPanel
  2717. Left = 0
  2718. Top = 0
  2719. Width = 640
  2720. Height = 50
  2721. object lblTitle: TLabel
  2722. Left = 16
  2723. Top = 16
  2724. Caption = 'Authentication Service'
  2725. end
  2726. object btnLogin: TButton
  2727. Left = 540
  2728. Top = 12
  2729. OnClick = btnLoginClick
  2730. end
  2731. end
  2732. object pnlContent: TPanel
  2733. Left = 0
  2734. Top = 50
  2735. object edtUsername: TEdit
  2736. Left = 16
  2737. Top = 16
  2738. OnChange = edtUsernameChange
  2739. end
  2740. object edtPassword: TEdit
  2741. Left = 16
  2742. Top = 48
  2743. OnKeyPress = edtPasswordKeyPress
  2744. end
  2745. object mmoLog: TMemo
  2746. Left = 16
  2747. Top = 88
  2748. end
  2749. end
  2750. object pnlStatus: TStatusBar
  2751. Left = 0
  2752. Top = 440
  2753. Panels = <
  2754. item
  2755. Width = 200
  2756. end
  2757. item
  2758. Width = 200
  2759. end>
  2760. end
  2761. end`;
  2762. it('should extract all components', () => {
  2763. const result = extractFromSource('MainForm.dfm', code);
  2764. const components = result.nodes.filter((n) => n.kind === 'component');
  2765. expect(components.length).toBe(9);
  2766. expect(components.map((c) => c.name)).toEqual(
  2767. expect.arrayContaining([
  2768. 'frmMain', 'pnlTop', 'lblTitle', 'btnLogin',
  2769. 'pnlContent', 'edtUsername', 'edtPassword', 'mmoLog', 'pnlStatus',
  2770. ])
  2771. );
  2772. });
  2773. it('should extract all event handlers', () => {
  2774. const result = extractFromSource('MainForm.dfm', code);
  2775. const refs = result.unresolvedReferences;
  2776. expect(refs.length).toBe(5);
  2777. expect(refs.map((r) => r.referenceName)).toEqual(
  2778. expect.arrayContaining([
  2779. 'FormCreate', 'FormDestroy', 'btnLoginClick',
  2780. 'edtUsernameChange', 'edtPasswordKeyPress',
  2781. ])
  2782. );
  2783. });
  2784. });
  2785. });
  2786. describe('Kotlin Multiplatform expect/actual', () => {
  2787. let tempDir: string;
  2788. let cg: CodeGraph;
  2789. beforeEach(() => {
  2790. tempDir = createTempDir();
  2791. });
  2792. afterEach(() => {
  2793. if (cg) cg.close();
  2794. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  2795. });
  2796. it('links expect declarations to platform actual implementations and surfaces them in impact', async () => {
  2797. const common = path.join(tempDir, 'src', 'commonMain');
  2798. const jvm = path.join(tempDir, 'src', 'jvmMain');
  2799. fs.mkdirSync(common, { recursive: true });
  2800. fs.mkdirSync(jvm, { recursive: true });
  2801. // common source set: expect declarations + a caller that uses them
  2802. fs.writeFileSync(
  2803. path.join(common, 'SystemProps.kt'),
  2804. `package demo.internal
  2805. expect fun systemProp(name: String): String?
  2806. expect class Platform {
  2807. fun describe(): String
  2808. }
  2809. `
  2810. );
  2811. fs.writeFileSync(
  2812. path.join(common, 'Caller.kt'),
  2813. `package demo
  2814. import demo.internal.systemProp
  2815. import demo.internal.Platform
  2816. fun useIt(): String {
  2817. val v = systemProp("os.name")
  2818. return Platform().describe() + v
  2819. }
  2820. `
  2821. );
  2822. // jvm source set: actual implementations
  2823. fs.writeFileSync(
  2824. path.join(jvm, 'SystemProps.kt'),
  2825. `package demo.internal
  2826. actual fun systemProp(name: String): String? = System.getProperty(name)
  2827. actual class Platform {
  2828. actual fun describe(): String = "JVM"
  2829. }
  2830. `
  2831. );
  2832. cg = CodeGraph.initSync(tempDir);
  2833. await cg.indexAll();
  2834. cg.resolveReferences();
  2835. // The expect/actual markers are captured onto the node's decorators.
  2836. const fns = cg.getNodesByKind('function');
  2837. const actualFn = fns.find(
  2838. (n) => n.name === 'systemProp' && n.decorators?.includes('actual')
  2839. );
  2840. const expectFn = fns.find(
  2841. (n) => n.name === 'systemProp' && n.decorators?.includes('expect')
  2842. );
  2843. expect(actualFn).toBeDefined();
  2844. expect(expectFn).toBeDefined();
  2845. expect(actualFn!.filePath).not.toBe(expectFn!.filePath);
  2846. // Editing the JVM actual must surface the common expect AND its caller —
  2847. // before the expect/actual bridge the actual had zero dependents.
  2848. const impact = cg.getImpactRadius(actualFn!.id, 3);
  2849. const impacted = [...impact.nodes.values()].map((n) => n.name);
  2850. expect(impacted).toContain('systemProp'); // the common expect
  2851. expect(impacted).toContain('useIt'); // the caller, reached transitively
  2852. // The bridging edge is a heuristic `calls` edge tagged by the synthesizer.
  2853. const bridge = impact.edges.find(
  2854. (e) =>
  2855. e.target === actualFn!.id &&
  2856. e.provenance === 'heuristic' &&
  2857. (e.metadata as { synthesizedBy?: string } | undefined)?.synthesizedBy ===
  2858. 'kotlin-expect-actual'
  2859. );
  2860. expect(bridge).toBeDefined();
  2861. expect(bridge!.source).toBe(expectFn!.id);
  2862. });
  2863. it('links an expect class to an actual typealias (different node kinds)', async () => {
  2864. const common = path.join(tempDir, 'src', 'commonMain');
  2865. const jvm = path.join(tempDir, 'src', 'jvmMain');
  2866. fs.mkdirSync(common, { recursive: true });
  2867. fs.mkdirSync(jvm, { recursive: true });
  2868. fs.writeFileSync(
  2869. path.join(common, 'Lock.kt'),
  2870. `package demo
  2871. expect class Lock {
  2872. fun acquire()
  2873. }
  2874. `
  2875. );
  2876. fs.writeFileSync(
  2877. path.join(jvm, 'Lock.kt'),
  2878. `package demo
  2879. actual typealias Lock = java.util.concurrent.locks.ReentrantLock
  2880. `
  2881. );
  2882. cg = CodeGraph.initSync(tempDir);
  2883. await cg.indexAll();
  2884. cg.resolveReferences();
  2885. const aliasNode = cg
  2886. .getNodesByKind('type_alias')
  2887. .find((n) => n.name === 'Lock' && n.decorators?.includes('actual'));
  2888. expect(aliasNode).toBeDefined();
  2889. // The actual typealias is now a cross-file dependency target (linked from
  2890. // the expect class), so it participates in impact rather than being orphaned.
  2891. const impact = cg.getImpactRadius(aliasNode!.id, 3);
  2892. const bridge = impact.edges.find(
  2893. (e) =>
  2894. e.target === aliasNode!.id &&
  2895. (e.metadata as { synthesizedBy?: string } | undefined)?.synthesizedBy ===
  2896. 'kotlin-expect-actual'
  2897. );
  2898. expect(bridge).toBeDefined();
  2899. });
  2900. });
  2901. describe('Scala cross-file dependencies', () => {
  2902. let tempDir: string;
  2903. let cg: CodeGraph;
  2904. beforeEach(() => {
  2905. tempDir = createTempDir();
  2906. });
  2907. afterEach(() => {
  2908. if (cg) cg.close();
  2909. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  2910. });
  2911. it('links parameterized supertypes, type annotations, and implicit params across files', async () => {
  2912. const src = path.join(tempDir, 'src', 'main', 'scala', 'demo');
  2913. fs.mkdirSync(src, { recursive: true });
  2914. fs.writeFileSync(
  2915. path.join(src, 'Semigroup.scala'),
  2916. `package demo
  2917. trait Semigroup[A] {
  2918. def combine(x: A, y: A): A
  2919. }
  2920. `
  2921. );
  2922. fs.writeFileSync(
  2923. path.join(src, 'Monoid.scala'),
  2924. `package demo
  2925. trait Monoid[A] extends Semigroup[A] {
  2926. def empty: A
  2927. }
  2928. `
  2929. );
  2930. fs.writeFileSync(
  2931. path.join(src, 'Instances.scala'),
  2932. `package demo
  2933. object Instances {
  2934. implicit val intMonoid: Monoid[Int] = new Monoid[Int] {
  2935. def empty: Int = 0
  2936. def combine(x: Int, y: Int): Int = x + y
  2937. }
  2938. }
  2939. `
  2940. );
  2941. fs.writeFileSync(
  2942. path.join(src, 'Folding.scala'),
  2943. `package demo
  2944. object Folding {
  2945. def fold[A](xs: List[A])(implicit M: Monoid[A]): A =
  2946. xs.foldLeft(M.empty)(M.combine)
  2947. }
  2948. `
  2949. );
  2950. cg = CodeGraph.initSync(tempDir);
  2951. await cg.indexAll();
  2952. cg.resolveReferences();
  2953. const monoid = cg.getNodesByKind('trait').find((n) => n.name === 'Monoid');
  2954. const semigroup = cg.getNodesByKind('trait').find((n) => n.name === 'Semigroup');
  2955. expect(monoid).toBeDefined();
  2956. expect(semigroup).toBeDefined();
  2957. expect(monoid!.filePath).not.toBe(semigroup!.filePath);
  2958. // Parameterized supertype `extends Semigroup[A]` must create an extends edge —
  2959. // the whole point of the fix (the `[A]` used to defeat name matching).
  2960. const semaImpact = cg.getImpactRadius(semigroup!.id, 3);
  2961. expect([...semaImpact.nodes.values()].map((n) => n.name)).toContain('Monoid');
  2962. // Editing Monoid surfaces the cross-file users: the instance val typed
  2963. // `Monoid[Int]` and the method taking it as an implicit (curried) param.
  2964. const impacted = [...cg.getImpactRadius(monoid!.id, 3).nodes.values()].map((n) => n.name);
  2965. expect(impacted).toContain('intMonoid'); // field type annotation
  2966. expect(impacted).toContain('fold'); // trailing implicit parameter list
  2967. });
  2968. });
  2969. describe('PHP namespace + import resolution', () => {
  2970. let tempDir: string;
  2971. let cg: CodeGraph;
  2972. beforeEach(() => {
  2973. tempDir = createTempDir();
  2974. });
  2975. afterEach(() => {
  2976. if (cg) cg.close();
  2977. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  2978. });
  2979. it('resolves `use` imports to the namespace-qualified definition and type-hints across files', async () => {
  2980. const src = path.join(tempDir, 'src');
  2981. // Two interfaces with the SAME simple name in different namespaces — the
  2982. // exact ambiguity (Laravel has 7+ `Factory`) that bare-name matching can't
  2983. // resolve. The namespace qualifies them; the `use` import disambiguates.
  2984. fs.mkdirSync(path.join(src, 'Cache'), { recursive: true });
  2985. fs.mkdirSync(path.join(src, 'Mail'), { recursive: true });
  2986. fs.mkdirSync(path.join(src, 'App'), { recursive: true });
  2987. fs.writeFileSync(
  2988. path.join(src, 'Cache', 'Factory.php'),
  2989. `<?php
  2990. namespace Contracts\\Cache;
  2991. interface Factory {
  2992. public function store(): object;
  2993. }
  2994. `
  2995. );
  2996. fs.writeFileSync(
  2997. path.join(src, 'Mail', 'Factory.php'),
  2998. `<?php
  2999. namespace Contracts\\Mail;
  3000. interface Factory {
  3001. public function mailer(): object;
  3002. }
  3003. `
  3004. );
  3005. fs.writeFileSync(
  3006. path.join(src, 'App', 'Service.php'),
  3007. `<?php
  3008. namespace App;
  3009. use Contracts\\Cache\\Factory;
  3010. class Service {
  3011. public function make(): Factory {
  3012. return resolve(Factory::class);
  3013. }
  3014. }
  3015. `
  3016. );
  3017. cg = CodeGraph.initSync(tempDir);
  3018. await cg.indexAll();
  3019. cg.resolveReferences();
  3020. // The PHP namespace is captured into the qualified name, so the two
  3021. // same-named interfaces are distinguishable.
  3022. const cacheFactory = cg
  3023. .getNodesByKind('interface')
  3024. .find((n) => n.qualifiedName === 'Contracts\\Cache::Factory');
  3025. const mailFactory = cg
  3026. .getNodesByKind('interface')
  3027. .find((n) => n.qualifiedName === 'Contracts\\Mail::Factory');
  3028. expect(cacheFactory).toBeDefined();
  3029. expect(mailFactory).toBeDefined();
  3030. // Service `use`s Contracts\Cache\Factory, so editing THAT interface reaches
  3031. // Service.php — and editing the same-named Contracts\Mail\Factory must NOT
  3032. // (the import resolved to the right namespace, not an arbitrary `Factory`).
  3033. const serviceFile = 'src/App/Service.php';
  3034. const cacheReaches = [...cg.getImpactRadius(cacheFactory!.id, 3).nodes.values()].some(
  3035. (n) => (n.filePath ?? '').endsWith(serviceFile)
  3036. );
  3037. const mailReaches = [...cg.getImpactRadius(mailFactory!.id, 3).nodes.values()].some(
  3038. (n) => (n.filePath ?? '').endsWith(serviceFile)
  3039. );
  3040. expect(cacheReaches).toBe(true);
  3041. expect(mailReaches).toBe(false);
  3042. });
  3043. });
  3044. describe('Ruby mixins (include/extend/prepend)', () => {
  3045. let tempDir: string;
  3046. let cg: CodeGraph;
  3047. beforeEach(() => {
  3048. tempDir = createTempDir();
  3049. });
  3050. afterEach(() => {
  3051. if (cg) cg.close();
  3052. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  3053. });
  3054. it('links include/extend/prepend to the mixed-in module across files', async () => {
  3055. const lib = path.join(tempDir, 'lib');
  3056. fs.mkdirSync(lib, { recursive: true });
  3057. fs.writeFileSync(
  3058. path.join(lib, 'concerns.rb'),
  3059. `module Trackable
  3060. def track; end
  3061. end
  3062. module Cacheable
  3063. def cache; end
  3064. end
  3065. module Loggable
  3066. def log; end
  3067. end
  3068. `
  3069. );
  3070. fs.writeFileSync(
  3071. path.join(lib, 'model.rb'),
  3072. `class Model
  3073. include Trackable
  3074. prepend Cacheable
  3075. extend Loggable
  3076. end
  3077. `
  3078. );
  3079. cg = CodeGraph.initSync(tempDir);
  3080. await cg.indexAll();
  3081. cg.resolveReferences();
  3082. const model = cg.getNodesByKind('class').find((n) => n.name === 'Model');
  3083. expect(model).toBeDefined();
  3084. // All three mixin forms create an `implements` edge Model → module, so
  3085. // editing a concern surfaces every class that mixes it in (across files).
  3086. for (const moduleName of ['Trackable', 'Cacheable', 'Loggable']) {
  3087. const mod = cg.getNodesByKind('module').find((n) => n.name === moduleName);
  3088. expect(mod, moduleName).toBeDefined();
  3089. const impacted = [...cg.getImpactRadius(mod!.id, 3).nodes.values()].map((n) => n.name);
  3090. expect(impacted, `${moduleName} should be depended on by Model`).toContain('Model');
  3091. }
  3092. });
  3093. it('resolves require / require_relative to the required file', async () => {
  3094. const lib = path.join(tempDir, 'lib');
  3095. fs.mkdirSync(path.join(lib, 'app'), { recursive: true });
  3096. // A leaf file whose class is referenced only dynamically — so without
  3097. // require resolution it would look like nothing depends on it.
  3098. fs.writeFileSync(
  3099. path.join(lib, 'app', 'fetcher.rb'),
  3100. `module App
  3101. class Fetcher
  3102. def fetch; end
  3103. end
  3104. end
  3105. `
  3106. );
  3107. // Pulled in by a load-path `require` …
  3108. fs.writeFileSync(
  3109. path.join(lib, 'app', 'worker.rb'),
  3110. `require "app/fetcher"
  3111. module App
  3112. class Worker; end
  3113. end
  3114. `
  3115. );
  3116. // … and a sibling pulled in by `require_relative`.
  3117. fs.writeFileSync(
  3118. path.join(lib, 'app', 'boot.rb'),
  3119. `require_relative "fetcher"
  3120. `
  3121. );
  3122. cg = CodeGraph.initSync(tempDir);
  3123. await cg.indexAll();
  3124. cg.resolveReferences();
  3125. // The require edges target fetcher.rb's FILE node. Editing it should reach
  3126. // BOTH the load-path requirer (worker.rb) and the require_relative one
  3127. // (boot.rb) — without require resolution its file would have no dependents.
  3128. const fetcher = cg.getNodesByKind('file').find((n) => n.filePath.endsWith('app/fetcher.rb'));
  3129. expect(fetcher, 'fetcher.rb indexed').toBeDefined();
  3130. const reached = [...cg.getImpactRadius(fetcher!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3131. expect(reached.some((p) => p.endsWith('app/worker.rb'))).toBe(true);
  3132. expect(reached.some((p) => p.endsWith('app/boot.rb'))).toBe(true);
  3133. });
  3134. });
  3135. describe('C++ free-function name extraction', () => {
  3136. let tempDir: string;
  3137. let cg: CodeGraph;
  3138. beforeEach(() => {
  3139. tempDir = createTempDir();
  3140. });
  3141. afterEach(() => {
  3142. if (cg) cg.close();
  3143. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  3144. });
  3145. it('names a free function correctly when it has qualified-type params or a trailing return type', async () => {
  3146. const src = path.join(tempDir, 'src');
  3147. fs.mkdirSync(src, { recursive: true });
  3148. // TableFileName has a `const std::string&` parameter; BuildName uses an
  3149. // `auto … -> std::string` trailing return type. Both used to be named
  3150. // `string` (picked up from the parameter / return type), so callers never
  3151. // resolved and the defining file looked like nothing depended on it.
  3152. fs.writeFileSync(
  3153. path.join(src, 'names.cc'),
  3154. `#include <string>
  3155. std::string TableFileName(const std::string& dbname, int number) {
  3156. return dbname;
  3157. }
  3158. auto BuildName(const std::string& a) -> std::string {
  3159. return a;
  3160. }
  3161. `
  3162. );
  3163. fs.writeFileSync(
  3164. path.join(src, 'user.cc'),
  3165. `#include <string>
  3166. std::string use() {
  3167. return TableFileName("db", 1) + BuildName("x");
  3168. }
  3169. `
  3170. );
  3171. cg = CodeGraph.initSync(tempDir);
  3172. await cg.indexAll();
  3173. cg.resolveReferences();
  3174. // The functions are extracted under their real names, not `string`.
  3175. const fns = cg.getNodesByKind('function');
  3176. const tableFn = fns.find((n) => n.name === 'TableFileName');
  3177. const buildFn = fns.find((n) => n.name === 'BuildName');
  3178. expect(tableFn, 'TableFileName extracted (not "string")').toBeDefined();
  3179. expect(buildFn, 'BuildName extracted (not "string")').toBeDefined();
  3180. // And the cross-file calls resolve to them, so editing names.cc surfaces user.cc.
  3181. for (const fn of [tableFn!, buildFn!]) {
  3182. const reached = [...cg.getImpactRadius(fn.id, 3).nodes.values()].map((n) => n.filePath ?? '');
  3183. expect(reached.some((p) => p.endsWith('user.cc')), `${fn.name} should be called from user.cc`).toBe(true);
  3184. }
  3185. });
  3186. });
  3187. describe('Dart mixins and type references', () => {
  3188. let tempDir: string;
  3189. let cg: CodeGraph;
  3190. beforeEach(() => {
  3191. tempDir = createTempDir();
  3192. });
  3193. afterEach(() => {
  3194. if (cg) cg.close();
  3195. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  3196. });
  3197. it('links `with` mixins and method parameter/return types across files', async () => {
  3198. const lib = path.join(tempDir, 'lib');
  3199. fs.mkdirSync(lib, { recursive: true });
  3200. fs.writeFileSync(
  3201. path.join(lib, 'models.dart'),
  3202. `class User {
  3203. final String name;
  3204. User(this.name);
  3205. }
  3206. mixin Loggable {
  3207. void log() {}
  3208. }
  3209. abstract class Repository {
  3210. User find(int id);
  3211. }
  3212. `
  3213. );
  3214. fs.writeFileSync(
  3215. path.join(lib, 'service.dart'),
  3216. `import 'models.dart';
  3217. class UserService extends Repository with Loggable {
  3218. @override
  3219. User find(int id) => User('x');
  3220. List<User> all() => [];
  3221. }
  3222. `
  3223. );
  3224. cg = CodeGraph.initSync(tempDir);
  3225. await cg.indexAll();
  3226. cg.resolveReferences();
  3227. const inModels = (name: string) =>
  3228. cg.getNodesByKind('class').concat(cg.getNodesByKind('module'))
  3229. .find((n) => n.name === name && n.filePath.endsWith('models.dart'));
  3230. // The `with Loggable` mixin records a dependency — editing the mixin surfaces
  3231. // the class that mixes it in (across files). Loggable is a `mixin`, indexed
  3232. // as a class-like node.
  3233. const loggable = cg.getNodesByKind('class').find((n) => n.name === 'Loggable')
  3234. ?? cg.getNodesByKind('module').find((n) => n.name === 'Loggable');
  3235. expect(loggable, 'Loggable mixin indexed').toBeDefined();
  3236. const mixinUsers = [...cg.getImpactRadius(loggable!.id, 3).nodes.values()].map((n) => n.name);
  3237. expect(mixinUsers).toContain('UserService');
  3238. // `User` is used only as a method parameter/return type in service.dart —
  3239. // editing it must still surface service.dart via the type references.
  3240. const user = inModels('User') ?? cg.getNodesByKind('class').find((n) => n.name === 'User');
  3241. expect(user, 'User indexed').toBeDefined();
  3242. const userDeps = [...cg.getImpactRadius(user!.id, 3).nodes.values()].map((n) => n.filePath ?? '');
  3243. expect(userDeps.some((p) => p.endsWith('service.dart'))).toBe(true);
  3244. });
  3245. });
  3246. describe('Static-member / value-read references', () => {
  3247. let tempDir: string;
  3248. let cg: CodeGraph;
  3249. beforeEach(() => {
  3250. tempDir = createTempDir();
  3251. });
  3252. afterEach(() => {
  3253. if (cg) cg.close();
  3254. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  3255. });
  3256. it('links a type referenced only via a static field / enum value (and ignores lowercase receivers)', async () => {
  3257. fs.writeFileSync(
  3258. path.join(tempDir, 'JsonScope.java'),
  3259. `class JsonScope {
  3260. static final int EMPTY_DOCUMENT = 1;
  3261. }
  3262. `
  3263. );
  3264. fs.writeFileSync(
  3265. path.join(tempDir, 'Reader.java'),
  3266. `class Reader {
  3267. private int helper;
  3268. int peek() {
  3269. return JsonScope.EMPTY_DOCUMENT;
  3270. }
  3271. int noop() {
  3272. return this.helper;
  3273. }
  3274. }
  3275. `
  3276. );
  3277. cg = CodeGraph.initSync(tempDir);
  3278. await cg.indexAll();
  3279. cg.resolveReferences();
  3280. // JsonScope is used ONLY as `JsonScope.EMPTY_DOCUMENT` (a static-field value
  3281. // read — never constructed or called), so before the static-member pass it
  3282. // had no dependents. Editing it now surfaces Reader.java.
  3283. const scope = cg.getNodesByKind('class').find((n) => n.name === 'JsonScope');
  3284. expect(scope, 'JsonScope indexed').toBeDefined();
  3285. const reached = [...cg.getImpactRadius(scope!.id, 3).nodes.values()].map((n) => n.filePath ?? '');
  3286. expect(reached.some((p) => p.endsWith('Reader.java'))).toBe(true);
  3287. // A lowercase receiver (`this.helper`) must NOT be emitted as a type ref —
  3288. // only Capitalized receivers (types) are. No node named `this`/`helper`
  3289. // should appear as a reference target from peek/noop beyond JsonScope.
  3290. const refTargets = cg
  3291. .getNodesByKind('class')
  3292. .filter((n) => n.name === 'this' || n.name === 'helper');
  3293. expect(refTargets.length).toBe(0);
  3294. });
  3295. it('does not link a static-member read across language families (coincidental name)', async () => {
  3296. // A native (Kotlin) `Build.VERSION` reads the Android system class — it must
  3297. // NOT link to a coincidentally same-named TS class (the cross-language false
  3298. // positive that name-matching produces; `references` edges are language-local).
  3299. fs.writeFileSync(
  3300. path.join(tempDir, 'Build.ts'),
  3301. `export class Build {\n static version = 1;\n}\n`
  3302. );
  3303. fs.writeFileSync(
  3304. path.join(tempDir, 'Device.kt'),
  3305. `package app\nclass Device {\n fun sdk(): Int = Build.VERSION\n}\n`
  3306. );
  3307. cg = CodeGraph.initSync(tempDir);
  3308. await cg.indexAll();
  3309. cg.resolveReferences();
  3310. const tsBuild = cg.getNodesByKind('class').find((n) => n.name === 'Build' && n.filePath.endsWith('Build.ts'));
  3311. expect(tsBuild).toBeDefined();
  3312. // The Kotlin file is `app/Device.kt`; the TS Build must have NO dependent there.
  3313. const deps = [...cg.getImpactRadius(tsBuild!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3314. expect(deps.some((p) => p.endsWith('Device.kt'))).toBe(false);
  3315. });
  3316. });
  3317. describe('Cross-language type/import gate (RN name collisions)', () => {
  3318. let tempDir: string;
  3319. let cg: CodeGraph;
  3320. beforeEach(() => {
  3321. tempDir = createTempDir();
  3322. });
  3323. afterEach(() => {
  3324. if (cg) cg.close();
  3325. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  3326. });
  3327. it('a TS PascalCase type ref lands on the TS type, never a same-named native class', async () => {
  3328. // react-native-async-storage's example app has a TS `type TestRunner` AND a
  3329. // Kotlin `class TestRunner`. The React PascalCase resolver name-matched the
  3330. // Kotlin `class` (its COMPONENT_KINDS includes `class`) with no language
  3331. // check at confidence 0.8, outranking the (cross-language-penalized 0.5)
  3332. // TS name-match — so a TS ref to `TestRunner` crossed web→jvm. The ref here
  3333. // is intentionally NOT imported: a clean relative import would mask the bug
  3334. // by resolving via the import map before the framework strategy can win.
  3335. fs.writeFileSync(
  3336. path.join(tempDir, 'package.json'),
  3337. JSON.stringify({ dependencies: { 'react-native': '*' } })
  3338. );
  3339. fs.writeFileSync(
  3340. path.join(tempDir, 'useTests.ts'),
  3341. `export type TestRunner = { run: () => void };\n`
  3342. );
  3343. fs.writeFileSync(
  3344. path.join(tempDir, 'basic.tsx'),
  3345. `export function useBasicTest(r: TestRunner): TestRunner {\n return r;\n}\n`
  3346. );
  3347. fs.writeFileSync(
  3348. path.join(tempDir, 'TestUtils.kt'),
  3349. `package app\nclass TestRunner {\n fun run() {}\n}\n`
  3350. );
  3351. cg = CodeGraph.initSync(tempDir);
  3352. await cg.indexAll();
  3353. cg.resolveReferences();
  3354. const ktRunner = cg
  3355. .getNodesByKind('class')
  3356. .find((n) => n.name === 'TestRunner' && n.filePath.endsWith('TestUtils.kt'));
  3357. expect(ktRunner, 'Kotlin TestRunner class').toBeDefined();
  3358. const ktDeps = [...cg.getImpactRadius(ktRunner!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3359. expect(ktDeps.some((p) => p.endsWith('basic.tsx')), 'Kotlin class has NO TS dependent').toBe(false);
  3360. const tsRunner = cg.getNodesByKind('type_alias').find((n) => n.name === 'TestRunner');
  3361. expect(tsRunner, 'TS TestRunner type_alias').toBeDefined();
  3362. const tsDeps = [...cg.getImpactRadius(tsRunner!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3363. expect(tsDeps.some((p) => p.endsWith('basic.tsx')), 'TS type captured the ref (re-pointed)').toBe(true);
  3364. });
  3365. it('gates a cross-family import name collision but keeps same-family imports', async () => {
  3366. // A TS `import { Widget }` that only matches a Swift `class Widget` must not
  3367. // create a web→apple dependency — but a sibling TS module imported by
  3368. // another TS file (same family) must still resolve (no over-gating).
  3369. fs.writeFileSync(path.join(tempDir, 'Widget.swift'), `class Widget {\n func render() {}\n}\n`);
  3370. fs.writeFileSync(
  3371. path.join(tempDir, 'widget.ts'),
  3372. `import { Widget } from './native';\nexport function mount(w: Widget) {}\n`
  3373. );
  3374. fs.writeFileSync(path.join(tempDir, 'util.ts'), `export class Helper {}\n`);
  3375. fs.writeFileSync(
  3376. path.join(tempDir, 'app.ts'),
  3377. `import { Helper } from './util';\nexport const h = new Helper();\n`
  3378. );
  3379. cg = CodeGraph.initSync(tempDir);
  3380. await cg.indexAll();
  3381. cg.resolveReferences();
  3382. const swiftWidget = cg
  3383. .getNodesByKind('class')
  3384. .find((n) => n.name === 'Widget' && n.filePath.endsWith('.swift'));
  3385. expect(swiftWidget, 'Swift Widget class').toBeDefined();
  3386. const wDeps = [...cg.getImpactRadius(swiftWidget!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3387. expect(wDeps.some((p) => p.endsWith('widget.ts')), 'Swift class has NO TS dependent').toBe(false);
  3388. // Same-family control — the TS Helper must still see its TS dependent.
  3389. const helper = cg.getNodesByKind('class').find((n) => n.name === 'Helper');
  3390. expect(helper, 'TS Helper class').toBeDefined();
  3391. const hDeps = [...cg.getImpactRadius(helper!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3392. expect(hDeps.some((p) => p.endsWith('app.ts')), 'same-family TS import preserved').toBe(true);
  3393. });
  3394. });
  3395. describe('Python absolute module import resolution', () => {
  3396. let tempDir: string;
  3397. let cg: CodeGraph;
  3398. beforeEach(() => {
  3399. tempDir = createTempDir();
  3400. });
  3401. afterEach(() => {
  3402. if (cg) cg.close();
  3403. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  3404. });
  3405. it('links a bare `import pkg.module` of an internal module to its file', async () => {
  3406. // `import conduit.apps.signals` (a Django-style side-effect import, and any
  3407. // dotted absolute module import) had no edge to the module file — only
  3408. // `from x import y` was linked — so a module imported by its dotted path
  3409. // looked like nothing depended on it.
  3410. fs.mkdirSync(path.join(tempDir, 'conduit/apps'), { recursive: true });
  3411. fs.writeFileSync(path.join(tempDir, 'conduit/__init__.py'), '');
  3412. fs.writeFileSync(path.join(tempDir, 'conduit/apps/__init__.py'), '');
  3413. fs.writeFileSync(path.join(tempDir, 'conduit/apps/signals.py'), `def handler():\n pass\n`);
  3414. fs.writeFileSync(
  3415. path.join(tempDir, 'conduit/apps/app.py'),
  3416. `import conduit.apps.signals\nimport os\n\nVALUE = 1\n`
  3417. );
  3418. cg = CodeGraph.initSync(tempDir);
  3419. await cg.indexAll();
  3420. cg.resolveReferences();
  3421. const signals = cg.getNodesByKind('file').find((n) => n.filePath.endsWith('conduit/apps/signals.py'));
  3422. expect(signals, 'signals.py indexed').toBeDefined();
  3423. const deps = [...cg.getImpactRadius(signals!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3424. expect(deps.some((p) => p.endsWith('app.py')), 'importer depends on the module').toBe(true);
  3425. // `import os` (stdlib) must NOT fabricate an edge — no os.py file in the repo.
  3426. const osNode = cg.getNodesByKind('file').find((n) => n.filePath.endsWith('/os.py'));
  3427. expect(osNode, 'no stdlib os.py node').toBeUndefined();
  3428. });
  3429. it('Django include() links the root URLconf to the included app urls module', async () => {
  3430. // `url(r'^api/', include('app.urls'))` should record a dependency from the
  3431. // root urlconf onto the included app's `urls.py` — so editing an app's routes
  3432. // surfaces the project urlconf that mounts them.
  3433. fs.mkdirSync(path.join(tempDir, 'app'), { recursive: true });
  3434. fs.writeFileSync(path.join(tempDir, 'requirements.txt'), `django==4.0\n`);
  3435. fs.writeFileSync(path.join(tempDir, 'app/__init__.py'), '');
  3436. fs.writeFileSync(path.join(tempDir, 'app/views.py'), `def home(request):\n return None\n`);
  3437. fs.writeFileSync(
  3438. path.join(tempDir, 'app/urls.py'),
  3439. `from django.conf.urls import url\nfrom . import views\nurlpatterns = [url(r'^$', views.home)]\n`
  3440. );
  3441. fs.writeFileSync(
  3442. path.join(tempDir, 'urls.py'),
  3443. `from django.conf.urls import include, url\nurlpatterns = [url(r'^app/', include('app.urls'))]\n`
  3444. );
  3445. cg = CodeGraph.initSync(tempDir);
  3446. await cg.indexAll();
  3447. cg.resolveReferences();
  3448. const appUrls = cg.getNodesByKind('file').find((n) => n.filePath.endsWith('app/urls.py'));
  3449. expect(appUrls, 'app/urls.py indexed').toBeDefined();
  3450. const deps = [...cg.getImpactRadius(appUrls!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3451. expect(deps.some((p) => p.endsWith('urls.py') && !p.endsWith('app/urls.py')), 'root urlconf depends on the included app urls').toBe(true);
  3452. });
  3453. it('resolves `from pkg import submodule` to the submodule under that package, not a same-named one', async () => {
  3454. // FastAPI router-aggregator pattern: `from app.api.routes import authentication`
  3455. // with same-named modules in sibling packages must resolve via the import's
  3456. // SOURCE (the package), not a coincidental same-basename file elsewhere.
  3457. fs.mkdirSync(path.join(tempDir, 'app/api/routes'), { recursive: true });
  3458. fs.mkdirSync(path.join(tempDir, 'app/api/dependencies'), { recursive: true });
  3459. for (const p of ['app/__init__.py', 'app/api/__init__.py', 'app/api/routes/__init__.py', 'app/api/dependencies/__init__.py']) {
  3460. fs.writeFileSync(path.join(tempDir, p), '');
  3461. }
  3462. fs.writeFileSync(path.join(tempDir, 'app/api/routes/authentication.py'), `def login():\n pass\n`);
  3463. fs.writeFileSync(path.join(tempDir, 'app/api/dependencies/authentication.py'), `def get_user():\n pass\n`);
  3464. fs.writeFileSync(
  3465. path.join(tempDir, 'app/api/routes/api.py'),
  3466. `from app.api.routes import authentication\n\nROUTER = authentication\n`
  3467. );
  3468. cg = CodeGraph.initSync(tempDir);
  3469. await cg.indexAll();
  3470. cg.resolveReferences();
  3471. const routesAuth = cg.getNodesByKind('file').find((n) => n.filePath.endsWith('routes/authentication.py'));
  3472. const depsAuth = cg.getNodesByKind('file').find((n) => n.filePath.endsWith('dependencies/authentication.py'));
  3473. expect(routesAuth && depsAuth).toBeTruthy();
  3474. const routesDeps = [...cg.getImpactRadius(routesAuth!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3475. const depsDeps = [...cg.getImpactRadius(depsAuth!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3476. expect(routesDeps.some((p) => p.endsWith('routes/api.py')), 'submodule under the imported package is the dependent').toBe(true);
  3477. expect(depsDeps.some((p) => p.endsWith('routes/api.py')), 'same-named module in a sibling package is NOT').toBe(false);
  3478. });
  3479. });
  3480. describe('Razor / Blazor markup extraction', () => {
  3481. let tempDir: string;
  3482. let cg: CodeGraph;
  3483. beforeEach(() => {
  3484. tempDir = createTempDir();
  3485. });
  3486. afterEach(() => {
  3487. if (cg) cg.close();
  3488. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  3489. });
  3490. it('links @model and Blazor component tags to their C# types; ignores HTML elements', async () => {
  3491. fs.mkdirSync(path.join(tempDir, 'Views'), { recursive: true });
  3492. fs.writeFileSync(
  3493. path.join(tempDir, 'LoginViewModel.cs'),
  3494. `namespace App { public class LoginViewModel { public string Email { get; set; } } }`
  3495. );
  3496. fs.writeFileSync(
  3497. path.join(tempDir, 'ToastComponent.cs'),
  3498. `namespace App { public class ToastComponent { } }`
  3499. );
  3500. fs.writeFileSync(
  3501. path.join(tempDir, 'Views/Login.cshtml'),
  3502. `@model LoginViewModel\n<div class="form">\n <input asp-for="Email" />\n</div>\n`
  3503. );
  3504. fs.writeFileSync(
  3505. path.join(tempDir, 'Index.razor'),
  3506. `<div>\n <ToastComponent />\n</div>\n`
  3507. );
  3508. cg = CodeGraph.initSync(tempDir);
  3509. await cg.indexAll();
  3510. cg.resolveReferences();
  3511. // `@model LoginViewModel` → the view-model class.
  3512. const vm = cg.getNodesByKind('class').find((n) => n.name === 'LoginViewModel');
  3513. expect(vm, 'LoginViewModel class').toBeDefined();
  3514. const vmDeps = [...cg.getImpactRadius(vm!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3515. expect(vmDeps.some((p) => p.endsWith('Login.cshtml')), '@model links the view').toBe(true);
  3516. // `<ToastComponent />` → the component class.
  3517. const toast = cg.getNodesByKind('class').find((n) => n.name === 'ToastComponent');
  3518. expect(toast, 'ToastComponent class').toBeDefined();
  3519. const toastDeps = [...cg.getImpactRadius(toast!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3520. expect(toastDeps.some((p) => p.endsWith('Index.razor')), 'Blazor tag links the component').toBe(true);
  3521. // HTML elements (`<div>`, `<input>`) must NOT become component references.
  3522. const htmlNodes = cg.getNodesByKind('class').filter((n) => n.name === 'div' || n.name === 'input');
  3523. expect(htmlNodes.length, 'no node for HTML elements').toBe(0);
  3524. });
  3525. it('C# namespaces qualify type names so same-named types are distinct', async () => {
  3526. fs.writeFileSync(path.join(tempDir, 'entity.cs'), `namespace App.Entities { public class CatalogBrand { } }`);
  3527. fs.writeFileSync(path.join(tempDir, 'dto.cs'), `namespace App.Models { public class CatalogBrand { } }`);
  3528. cg = CodeGraph.initSync(tempDir);
  3529. await cg.indexAll();
  3530. const brands = cg.getNodesByKind('class').filter((n) => n.name === 'CatalogBrand');
  3531. expect(brands.length, 'both CatalogBrand classes indexed').toBe(2);
  3532. const qns = brands.map((b) => b.qualifiedName).sort();
  3533. expect(qns[0]).not.toBe(qns[1]); // distinct qualified names (namespace-scoped)
  3534. expect(qns.some((q) => q.includes('Entities') && q.endsWith('CatalogBrand'))).toBe(true);
  3535. expect(qns.some((q) => q.includes('Models') && q.endsWith('CatalogBrand'))).toBe(true);
  3536. });
  3537. it('disambiguates a Razor type ref via @using (incl. folder _Imports.razor)', async () => {
  3538. // `CatalogBrand` exists as both a domain entity and a DTO; the component
  3539. // `@using`s the DTO's namespace (here via the folder _Imports.razor), so the
  3540. // ref must resolve to the DTO, not the same-named entity.
  3541. fs.mkdirSync(path.join(tempDir, 'Models'), { recursive: true });
  3542. fs.mkdirSync(path.join(tempDir, 'Entities'), { recursive: true });
  3543. fs.mkdirSync(path.join(tempDir, 'Pages'), { recursive: true });
  3544. fs.writeFileSync(path.join(tempDir, 'Models/CatalogBrand.cs'), `namespace App.Models { public class CatalogBrand { public int Id { get; set; } } }`);
  3545. fs.writeFileSync(path.join(tempDir, 'Entities/CatalogBrand.cs'), `namespace App.Entities { public class CatalogBrand { public int Id { get; set; } } }`);
  3546. fs.writeFileSync(path.join(tempDir, 'Pages/_Imports.razor'), `@using App.Models\n`);
  3547. fs.writeFileSync(
  3548. path.join(tempDir, 'Pages/List.razor'),
  3549. `<h1>List</h1>\n@code {\n private CatalogBrand _b = new CatalogBrand();\n}\n`
  3550. );
  3551. cg = CodeGraph.initSync(tempDir);
  3552. await cg.indexAll();
  3553. cg.resolveReferences();
  3554. const dto = cg.getNodesByKind('class').find((n) => n.qualifiedName === 'App.Models::CatalogBrand');
  3555. const entity = cg.getNodesByKind('class').find((n) => n.qualifiedName === 'App.Entities::CatalogBrand');
  3556. expect(dto && entity, 'both CatalogBrand classes').toBeTruthy();
  3557. const dtoDeps = [...cg.getImpactRadius(dto!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3558. const entityDeps = [...cg.getImpactRadius(entity!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3559. expect(dtoDeps.some((p) => p.endsWith('List.razor')), 'resolves to the @using\'d DTO').toBe(true);
  3560. expect(entityDeps.some((p) => p.endsWith('List.razor')), 'NOT the same-named entity').toBe(false);
  3561. });
  3562. it('delegates Blazor @code block C# to cover types used in component logic', async () => {
  3563. fs.writeFileSync(
  3564. path.join(tempDir, 'CatalogService.cs'),
  3565. `namespace App { public class CatalogService { public void Load() { } } }`
  3566. );
  3567. fs.writeFileSync(
  3568. path.join(tempDir, 'List.razor'),
  3569. `<h1>Catalog</h1>\n\n@code {\n private CatalogService _svc = new CatalogService();\n void Refresh() { _svc.Load(); }\n}\n`
  3570. );
  3571. cg = CodeGraph.initSync(tempDir);
  3572. await cg.indexAll();
  3573. cg.resolveReferences();
  3574. const svc = cg.getNodesByKind('class').find((n) => n.name === 'CatalogService');
  3575. expect(svc, 'CatalogService class').toBeDefined();
  3576. const deps = [...cg.getImpactRadius(svc!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3577. expect(deps.some((p) => p.endsWith('List.razor')), '@code usage links the component to the service').toBe(true);
  3578. });
  3579. });
  3580. describe('Default import resolution (renamed default export)', () => {
  3581. let tempDir: string;
  3582. let cg: CodeGraph;
  3583. beforeEach(() => {
  3584. tempDir = createTempDir();
  3585. });
  3586. afterEach(() => {
  3587. if (cg) cg.close();
  3588. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  3589. });
  3590. it('links a renamed default import to the module file', async () => {
  3591. // Express route aggregator: `import articlesController from './controller'`
  3592. // where the module does `export default router`. The renamed local can't be
  3593. // found as a symbol, so the controller file had no dependent — the dependency
  3594. // is on the module file regardless of the default export's name.
  3595. fs.mkdirSync(path.join(tempDir, 'app'), { recursive: true });
  3596. fs.writeFileSync(path.join(tempDir, 'app/controller.ts'), `const router = { get() {} };\nexport default router;\n`);
  3597. fs.writeFileSync(path.join(tempDir, 'app/routes.ts'), `import myController from './controller';\nexport const api = myController;\n`);
  3598. cg = CodeGraph.initSync(tempDir);
  3599. await cg.indexAll();
  3600. cg.resolveReferences();
  3601. const controller = cg.getNodesByKind('file').find((n) => n.filePath.endsWith('app/controller.ts'));
  3602. expect(controller, 'controller.ts indexed').toBeDefined();
  3603. const deps = [...cg.getImpactRadius(controller!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3604. expect(deps.some((p) => p.endsWith('routes.ts')), 'importer depends on the default-exporting module').toBe(true);
  3605. });
  3606. });
  3607. describe('Chained method-call resolution (C# extension methods)', () => {
  3608. let tempDir: string;
  3609. let cg: CodeGraph;
  3610. beforeEach(() => {
  3611. tempDir = createTempDir();
  3612. });
  3613. afterEach(() => {
  3614. if (cg) cg.close();
  3615. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  3616. });
  3617. it('resolves a chained extension-method call (a.b.Method()) to its definition', async () => {
  3618. // ASP.NET DI registration: `builder.Services.AddCoreServices(...)` calls a
  3619. // static extension method elsewhere. A multi-dot receiver chain matched no
  3620. // method-call pattern before, so the extension method had no caller.
  3621. fs.mkdirSync(path.join(tempDir, 'cfg'), { recursive: true });
  3622. fs.writeFileSync(
  3623. path.join(tempDir, 'cfg/Ext.cs'),
  3624. `namespace App {\n public static class Ext {\n public static object AddCoreServices(this object services, int x) { return services; }\n }\n}\n`
  3625. );
  3626. fs.writeFileSync(
  3627. path.join(tempDir, 'Program.cs'),
  3628. `namespace App {\n public class Program {\n public void Run(object builder) {\n builder.Services.AddCoreServices(1);\n }\n }\n}\n`
  3629. );
  3630. cg = CodeGraph.initSync(tempDir);
  3631. await cg.indexAll();
  3632. cg.resolveReferences();
  3633. const ext = cg
  3634. .getNodesByKind('method')
  3635. .find((n) => n.name === 'AddCoreServices')
  3636. ?? cg.getNodesByKind('function').find((n) => n.name === 'AddCoreServices');
  3637. expect(ext, 'AddCoreServices defined').toBeDefined();
  3638. const callers = [...cg.getImpactRadius(ext!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3639. expect(callers.some((p) => p.endsWith('Program.cs')), 'chained extension call resolves to its definition').toBe(true);
  3640. });
  3641. });
  3642. describe('Same-directory include + KMP import resolution', () => {
  3643. let tempDir: string;
  3644. let cg: CodeGraph;
  3645. beforeEach(() => {
  3646. tempDir = createTempDir();
  3647. });
  3648. afterEach(() => {
  3649. if (cg) cg.close();
  3650. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  3651. });
  3652. it('a C/C++ #include resolves to the same-directory header, not a same-named one elsewhere', async () => {
  3653. // A multi-platform native module has a header of the same basename per
  3654. // platform. `windows/Provider.cpp`'s `#include "Storage.h"` means its OWN
  3655. // sibling header — not `apple/Storage.h` (which sorts first and so was
  3656. // picked arbitrarily before, leaving the real local header with 0 deps).
  3657. fs.mkdirSync(path.join(tempDir, 'apple'), { recursive: true });
  3658. fs.mkdirSync(path.join(tempDir, 'windows'), { recursive: true });
  3659. fs.writeFileSync(path.join(tempDir, 'apple', 'Storage.h'), `#pragma once\nstruct Storage { int n; };\n`);
  3660. fs.writeFileSync(path.join(tempDir, 'windows', 'Storage.h'), `#pragma once\nstruct Storage { int n; };\n`);
  3661. fs.writeFileSync(
  3662. path.join(tempDir, 'windows', 'Provider.cpp'),
  3663. `#include "Storage.h"\nint use() { Storage s; return s.n; }\n`
  3664. );
  3665. cg = CodeGraph.initSync(tempDir);
  3666. await cg.indexAll();
  3667. cg.resolveReferences();
  3668. const winHeader = cg.getNodesByKind('file').find((n) => n.filePath.endsWith('windows/Storage.h'));
  3669. const appleHeader = cg.getNodesByKind('file').find((n) => n.filePath.endsWith('apple/Storage.h'));
  3670. expect(winHeader, 'windows/Storage.h indexed').toBeDefined();
  3671. expect(appleHeader, 'apple/Storage.h indexed').toBeDefined();
  3672. const winDeps = [...cg.getImpactRadius(winHeader!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3673. const appleDeps = [...cg.getImpactRadius(appleHeader!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3674. expect(winDeps.some((p) => p.endsWith('Provider.cpp')), 'same-dir header gets the includer').toBe(true);
  3675. expect(appleDeps.some((p) => p.endsWith('Provider.cpp')), 'other-platform header does NOT').toBe(false);
  3676. });
  3677. it('a Kotlin Multiplatform commonMain import resolves to the expect, not a platform actual', async () => {
  3678. const common = path.join(tempDir, 'src/commonMain/kotlin/app');
  3679. const android = path.join(tempDir, 'src/androidMain/kotlin/app');
  3680. fs.mkdirSync(common, { recursive: true });
  3681. fs.mkdirSync(android, { recursive: true });
  3682. fs.writeFileSync(path.join(common, 'Platform.kt'), `package app\nexpect class PlatformContext\n`);
  3683. fs.writeFileSync(path.join(android, 'Platform.android.kt'), `package app\nactual class PlatformContext\n`);
  3684. fs.writeFileSync(
  3685. path.join(common, 'Db.kt'),
  3686. `package app\nimport app.PlatformContext\nclass Db {\n fun open(ctx: PlatformContext) {}\n}\n`
  3687. );
  3688. cg = CodeGraph.initSync(tempDir);
  3689. await cg.indexAll();
  3690. cg.resolveReferences();
  3691. const expectCtx = cg
  3692. .getNodesByKind('class')
  3693. .find((n) => n.name === 'PlatformContext' && n.filePath.endsWith('commonMain/kotlin/app/Platform.kt'));
  3694. expect(expectCtx, 'commonMain expect PlatformContext').toBeDefined();
  3695. const deps = [...cg.getImpactRadius(expectCtx!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3696. expect(deps.some((p) => p.endsWith('Db.kt')), 'commonMain import lands on the expect, not the actual').toBe(true);
  3697. });
  3698. });
  3699. describe('Delphi form code-behind pairing', () => {
  3700. let tempDir: string;
  3701. let cg: CodeGraph;
  3702. beforeEach(() => {
  3703. tempDir = createTempDir();
  3704. });
  3705. afterEach(() => {
  3706. if (cg) cg.close();
  3707. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  3708. });
  3709. it('links a `.dfm` form to its sibling `.pas` code-behind unit', async () => {
  3710. // A Delphi form unit owns its visual form definition via `{$R *.dfm}`, not a
  3711. // `uses` clause — so a `.dfm` used only as a form definition looked orphaned.
  3712. fs.writeFileSync(path.join(tempDir, 'UFRMAbout.dfm'),
  3713. `object FRMAbout: TFRMAbout\n Caption = 'About'\nend\n`);
  3714. fs.writeFileSync(path.join(tempDir, 'UFRMAbout.pas'),
  3715. `unit UFRMAbout;\ninterface\nuses Forms;\ntype\n TFRMAbout = class(TForm)\n end;\nimplementation\n{$R *.dfm}\nend.\n`);
  3716. cg = CodeGraph.initSync(tempDir);
  3717. await cg.indexAll();
  3718. cg.resolveReferences();
  3719. const dfm = cg.getNodesByKind('file').find((n) => n.filePath.endsWith('UFRMAbout.dfm'));
  3720. expect(dfm, 'UFRMAbout.dfm file node').toBeDefined();
  3721. const deps = cg.getFileDependents(dfm!.filePath);
  3722. expect(deps.some((p) => p.endsWith('UFRMAbout.pas')), 'the .pas unit links its .dfm form').toBe(true);
  3723. });
  3724. });
  3725. describe('Liquid Shopify JSON template section resolution', () => {
  3726. let tempDir: string;
  3727. let cg: CodeGraph;
  3728. beforeEach(() => {
  3729. tempDir = createTempDir();
  3730. });
  3731. afterEach(() => {
  3732. if (cg) cg.close();
  3733. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  3734. });
  3735. it('links a Shopify JSON template section `type` to its sections/<type>.liquid', async () => {
  3736. // Shopify OS 2.0 templates are JSON, referencing sections by `type` — not
  3737. // a `{% section %}` Liquid tag — so a section used only from a JSON template
  3738. // looked unused. The JSON is now indexed and its `type`s linked.
  3739. fs.mkdirSync(path.join(tempDir, 'sections'), { recursive: true });
  3740. fs.mkdirSync(path.join(tempDir, 'templates/customers'), { recursive: true });
  3741. fs.writeFileSync(path.join(tempDir, 'sections/main-product.liquid'), `<div>{{ product.title }}</div>\n`);
  3742. fs.writeFileSync(path.join(tempDir, 'sections/main-login.liquid'), `<form>{{ 'customer.login' | t }}</form>\n`);
  3743. fs.writeFileSync(path.join(tempDir, 'templates/product.json'), JSON.stringify({ sections: { main: { type: 'main-product' } }, order: ['main'] }));
  3744. // Nested template dir (templates/customers/login.json) must resolve too.
  3745. fs.writeFileSync(path.join(tempDir, 'templates/customers/login.json'), JSON.stringify({ sections: { main: { type: 'main-login' } }, order: ['main'] }));
  3746. cg = CodeGraph.initSync(tempDir);
  3747. await cg.indexAll();
  3748. cg.resolveReferences();
  3749. const product = cg.getNodesByKind('file').find((n) => n.filePath.endsWith('sections/main-product.liquid'));
  3750. const login = cg.getNodesByKind('file').find((n) => n.filePath.endsWith('sections/main-login.liquid'));
  3751. expect(product, 'main-product section').toBeDefined();
  3752. expect(login, 'main-login section').toBeDefined();
  3753. expect(cg.getFileDependents(product!.filePath).some((p) => p.endsWith('templates/product.json')), 'top-level JSON template links its section').toBe(true);
  3754. expect(cg.getFileDependents(login!.filePath).some((p) => p.endsWith('customers/login.json')), 'nested JSON template links its section').toBe(true);
  3755. });
  3756. });
  3757. describe('Lua/Luau require resolution', () => {
  3758. let tempDir: string;
  3759. let cg: CodeGraph;
  3760. beforeEach(() => {
  3761. tempDir = createTempDir();
  3762. });
  3763. afterEach(() => {
  3764. if (cg) cg.close();
  3765. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  3766. });
  3767. it('resolves a dotted Lua require and an instance-path Luau require to their module files', async () => {
  3768. // The require is the ONLY link (no method call), so coverage here proves the
  3769. // require resolver specifically, not method-call name-matching.
  3770. // Lua dotted module path: require("myapp.config") → lua/myapp/config.lua.
  3771. fs.mkdirSync(path.join(tempDir, 'lua/myapp'), { recursive: true });
  3772. fs.writeFileSync(path.join(tempDir, 'lua/myapp/config.lua'), `local M = {}\nfunction M.setup() end\nreturn M\n`);
  3773. fs.writeFileSync(path.join(tempDir, 'lua/myapp/init.lua'), `local config = require("myapp.config")\nreturn config\n`);
  3774. // Luau Roblox instance-path require (only the leaf survives extraction):
  3775. // require(script.Util.helper) → src/Util/helper.luau.
  3776. fs.mkdirSync(path.join(tempDir, 'src/Util'), { recursive: true });
  3777. fs.writeFileSync(path.join(tempDir, 'src/Util/helper.luau'), `local H = {}\nfunction H.go() end\nreturn H\n`);
  3778. fs.writeFileSync(path.join(tempDir, 'src/init.luau'), `local helper = require(script.Util.helper)\nreturn helper\n`);
  3779. cg = CodeGraph.initSync(tempDir);
  3780. await cg.indexAll();
  3781. cg.resolveReferences();
  3782. const config = cg.getNodesByKind('file').find((n) => n.filePath.endsWith('myapp/config.lua'));
  3783. const helper = cg.getNodesByKind('file').find((n) => n.filePath.endsWith('Util/helper.luau'));
  3784. expect(config, 'config.lua file node').toBeDefined();
  3785. expect(helper, 'helper.luau file node').toBeDefined();
  3786. const cfgDeps = cg.getFileDependents(config!.filePath);
  3787. const helpDeps = cg.getFileDependents(helper!.filePath);
  3788. expect(cfgDeps.some((p) => p.endsWith('myapp/init.lua')), 'dotted Lua require resolves to the module').toBe(true);
  3789. expect(helpDeps.some((p) => p.endsWith('src/init.luau')), 'instance-path Luau require resolves to the module').toBe(true);
  3790. });
  3791. });
  3792. describe('Rust module-path call resolution', () => {
  3793. let tempDir: string;
  3794. let cg: CodeGraph;
  3795. beforeEach(() => {
  3796. tempDir = createTempDir();
  3797. });
  3798. afterEach(() => {
  3799. if (cg) cg.close();
  3800. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  3801. });
  3802. it('a bare submodule call (`users::router()`) resolves self-relative to the submodule fn', async () => {
  3803. // The canonical Axum router-assembly pattern: a parent module calls each
  3804. // submodule's `router()`. `users::` / `profiles::` are SELF-relative
  3805. // submodule prefixes (2018 edition) — `mod users;` makes `users` a child of
  3806. // the CURRENT module, NOT `crate::users`. Before the fix the bare prefix was
  3807. // resolved crate-relative only (looking for `src/users.rs`), so it found
  3808. // nothing and the handler modules looked dependent-less.
  3809. const http = path.join(tempDir, 'src/http');
  3810. fs.mkdirSync(http, { recursive: true });
  3811. fs.writeFileSync(path.join(tempDir, 'src/lib.rs'), `pub mod http;\n`);
  3812. fs.writeFileSync(
  3813. path.join(http, 'mod.rs'),
  3814. `mod users;\nmod profiles;\npub fn api_router() {\n users::router();\n profiles::router();\n}\n`
  3815. );
  3816. fs.writeFileSync(path.join(http, 'users.rs'), `pub fn router() -> i32 { 1 }\n`);
  3817. fs.writeFileSync(path.join(http, 'profiles.rs'), `pub fn router() -> i32 { 2 }\n`);
  3818. cg = CodeGraph.initSync(tempDir);
  3819. await cg.indexAll();
  3820. cg.resolveReferences();
  3821. // Each submodule's same-named `router` fn must get mod.rs as a dependent —
  3822. // proving the bare prefix resolved self-relative AND disambiguated the
  3823. // colliding `router` name to the correct file (not an arbitrary one).
  3824. const routers = cg.getNodesByKind('function').filter((n) => n.name === 'router');
  3825. const usersRouter = routers.find((n) => n.filePath.endsWith('http/users.rs'));
  3826. const profilesRouter = routers.find((n) => n.filePath.endsWith('http/profiles.rs'));
  3827. expect(usersRouter, 'users.rs router fn').toBeDefined();
  3828. expect(profilesRouter, 'profiles.rs router fn').toBeDefined();
  3829. const usersDeps = [...cg.getImpactRadius(usersRouter!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3830. const profilesDeps = [...cg.getImpactRadius(profilesRouter!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3831. expect(usersDeps.some((p) => p.endsWith('http/mod.rs')), 'users::router() lands on users.rs').toBe(true);
  3832. expect(profilesDeps.some((p) => p.endsWith('http/mod.rs')), 'profiles::router() lands on profiles.rs').toBe(true);
  3833. });
  3834. it('a 3-segment module-path call (`database::profiles::find()`) resolves to the leaf fn', async () => {
  3835. // A 2-level module path — the common `db.run(move |c| database::profiles::find(c))`
  3836. // / `crate::a::b::func()` shape. The reference-resolver pre-filter used to drop any
  3837. // `a::b::c` whose leaf it never checked (it tested only the first segment and the
  3838. // `b::c` remainder, neither of which names a symbol), so the call never reached the
  3839. // Rust path resolver and the leaf module looked dependent-less.
  3840. const routes = path.join(tempDir, 'src/routes');
  3841. const database = path.join(tempDir, 'src/database');
  3842. fs.mkdirSync(routes, { recursive: true });
  3843. fs.mkdirSync(database, { recursive: true });
  3844. fs.writeFileSync(path.join(tempDir, 'src/lib.rs'), `pub mod routes;\npub mod database;\n`);
  3845. fs.writeFileSync(path.join(database, 'mod.rs'), `pub mod profiles;\n`);
  3846. fs.writeFileSync(path.join(database, 'profiles.rs'), `pub fn find(id: i32) -> i32 { id }\n`);
  3847. fs.writeFileSync(
  3848. path.join(routes, 'mod.rs'),
  3849. `use crate::database;\npub fn get_profile(id: i32) -> i32 {\n database::profiles::find(id)\n}\n`
  3850. );
  3851. cg = CodeGraph.initSync(tempDir);
  3852. await cg.indexAll();
  3853. cg.resolveReferences();
  3854. const find = cg
  3855. .getNodesByKind('function')
  3856. .find((n) => n.name === 'find' && n.filePath.endsWith('database/profiles.rs'));
  3857. expect(find, 'database/profiles.rs find fn').toBeDefined();
  3858. const deps = [...cg.getImpactRadius(find!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3859. expect(deps.some((p) => p.endsWith('routes/mod.rs')), 'database::profiles::find() resolves to the leaf fn').toBe(true);
  3860. });
  3861. it('Rocket `routes![…]` / `catchers![…]` macros link the mount to the handler fns', async () => {
  3862. // Tree-sitter leaves the macro body as a raw token tree, so the handler
  3863. // paths inside `routes![a::b::handler, …]` are invisible to the call walker
  3864. // and the handlers — mounted by Rocket at runtime, not called in-repo — look
  3865. // like they have no caller. The route-macro extractor reconstructs each path
  3866. // and emits a reference, which the Rust path resolver links to the handler.
  3867. const routes = path.join(tempDir, 'src/routes');
  3868. fs.mkdirSync(routes, { recursive: true });
  3869. fs.writeFileSync(path.join(tempDir, 'src/lib.rs'),
  3870. `mod routes;\nfn not_found() {}\npub fn rocket() {\n` +
  3871. ` rocket::build()\n` +
  3872. ` .mount("/api", routes![routes::users::post_users, routes::users::get_user])\n` +
  3873. ` .register("/", catchers![not_found]);\n}\n`);
  3874. fs.writeFileSync(path.join(routes, 'mod.rs'), `pub mod users;\n`);
  3875. fs.writeFileSync(path.join(routes, 'users.rs'), `pub fn post_users() {}\npub fn get_user() {}\n`);
  3876. cg = CodeGraph.initSync(tempDir);
  3877. await cg.indexAll();
  3878. cg.resolveReferences();
  3879. const handlers = cg.getNodesByKind('function').filter((n) => n.filePath.endsWith('routes/users.rs'));
  3880. expect(handlers.length, 'both handler fns indexed').toBe(2);
  3881. for (const h of handlers) {
  3882. const deps = [...cg.getImpactRadius(h.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3883. expect(deps.some((p) => p.endsWith('lib.rs')), `routes![] links ${h.name} to its mount in lib.rs`).toBe(true);
  3884. }
  3885. });
  3886. });
  3887. describe('SvelteKit load → page synthesizer', () => {
  3888. let tempDir: string;
  3889. let cg: CodeGraph;
  3890. beforeEach(() => {
  3891. tempDir = createTempDir();
  3892. });
  3893. afterEach(() => {
  3894. if (cg) cg.close();
  3895. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  3896. });
  3897. it('links a +page.svelte to its OWN directory\'s +page.server.js load, not another route\'s', async () => {
  3898. // SvelteKit wires +page.server.js's `load` to +page.svelte's `data` BY FILE
  3899. // PATH — there is no static import — so editing a loader showed no impact on
  3900. // the page it feeds. The synthesizer links each page component to the `load`
  3901. // in its OWN directory (path-deterministic, so it never crosses routes).
  3902. const login = path.join(tempDir, 'src/routes/login');
  3903. const register = path.join(tempDir, 'src/routes/register');
  3904. fs.mkdirSync(login, { recursive: true });
  3905. fs.mkdirSync(register, { recursive: true });
  3906. fs.writeFileSync(path.join(login, '+page.svelte'), `<script>export let data;</script>\n<h1>Login {data.x}</h1>\n`);
  3907. fs.writeFileSync(path.join(login, '+page.server.js'), `export function load() { return { x: 1 }; }\n`);
  3908. fs.writeFileSync(path.join(register, '+page.svelte'), `<script>export let data;</script>\n<h1>Register</h1>\n`);
  3909. fs.writeFileSync(path.join(register, '+page.server.js'), `export function load() { return { y: 2 }; }\n`);
  3910. cg = CodeGraph.initSync(tempDir);
  3911. await cg.indexAll();
  3912. cg.resolveReferences();
  3913. const loginLoad = cg
  3914. .getNodesByKind('function')
  3915. .find((n) => n.name === 'load' && n.filePath.endsWith('login/+page.server.js'));
  3916. expect(loginLoad, 'login load fn').toBeDefined();
  3917. const impacted = [...cg.getImpactRadius(loginLoad!.id, 3).nodes.values()].map((n) => n.filePath ?? '');
  3918. // editing login's load surfaces login's page (the framework-wired data flow)…
  3919. expect(impacted.some((p) => p.endsWith('login/+page.svelte')), 'load links to its own page').toBe(true);
  3920. // …but never register's page (same-directory only).
  3921. expect(impacted.some((p) => p.endsWith('register/+page.svelte')), 'does not cross routes').toBe(false);
  3922. });
  3923. });
  3924. describe('Nuxt nested auto-imported component resolution', () => {
  3925. let tempDir: string;
  3926. let cg: CodeGraph;
  3927. beforeEach(() => {
  3928. tempDir = createTempDir();
  3929. });
  3930. afterEach(() => {
  3931. if (cg) cg.close();
  3932. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  3933. });
  3934. it('links a `<MediaCard/>` usage to components/media/Card.vue (Nuxt dir-prefixed auto-import)', async () => {
  3935. // Nuxt auto-imports a nested component by a DIRECTORY-PREFIXED name —
  3936. // components/media/Card.vue is used as <MediaCard/>, not <Card/> — but the
  3937. // component node is named by basename (`Card`), so the PascalCase usage
  3938. // didn't resolve and the nested component looked unused.
  3939. const media = path.join(tempDir, 'components/media');
  3940. fs.mkdirSync(media, { recursive: true });
  3941. fs.writeFileSync(path.join(media, 'Card.vue'), `<template><div>card</div></template>\n<script setup>defineProps(['item'])</script>\n`);
  3942. fs.writeFileSync(
  3943. path.join(tempDir, 'components/Grid.vue'),
  3944. `<template>\n <div><MediaCard :item="i" /></div>\n</template>\n<script setup>const i = {}</script>\n`
  3945. );
  3946. cg = CodeGraph.initSync(tempDir);
  3947. await cg.indexAll();
  3948. cg.resolveReferences();
  3949. const card = cg.getNodesByKind('component').find((n) => n.filePath.endsWith('media/Card.vue'));
  3950. expect(card, 'media/Card.vue component').toBeDefined();
  3951. const deps = [...cg.getImpactRadius(card!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3952. expect(deps.some((p) => p.endsWith('components/Grid.vue')), '<MediaCard> links Grid to media/Card.vue').toBe(true);
  3953. });
  3954. });
  3955. describe('Swift property-wrapper attribute type references', () => {
  3956. let tempDir: string;
  3957. let cg: CodeGraph;
  3958. beforeEach(() => {
  3959. tempDir = createTempDir();
  3960. });
  3961. afterEach(() => {
  3962. if (cg) cg.close();
  3963. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  3964. });
  3965. it('a Fluent `@Siblings(through: Pivot.self)` links the model to the pivot type', async () => {
  3966. // A many-to-many pivot/join model is referenced ONLY through the relationship
  3967. // property wrapper's metatype argument (`Pivot.self`), never by a controller
  3968. // query. The wrapper type was captured but the argument expression wasn't
  3969. // walked, so the pivot model looked like nothing depended on it.
  3970. fs.writeFileSync(path.join(tempDir, 'Pivot.swift'),
  3971. `import Fluent\nfinal class AcronymCategoryPivot: Model {\n static let schema = "acronym-category"\n}\n`);
  3972. fs.writeFileSync(path.join(tempDir, 'Acronym.swift'),
  3973. `import Fluent\nfinal class Acronym: Model {\n` +
  3974. ` @Siblings(through: AcronymCategoryPivot.self, from: \\.$acronym, to: \\.$category)\n` +
  3975. ` var categories: [Category]\n}\n`);
  3976. cg = CodeGraph.initSync(tempDir);
  3977. await cg.indexAll();
  3978. cg.resolveReferences();
  3979. const pivot = cg.getNodesByKind('class').find((n) => n.name === 'AcronymCategoryPivot');
  3980. expect(pivot, 'pivot model class').toBeDefined();
  3981. const deps = [...cg.getImpactRadius(pivot!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3982. expect(deps.some((p) => p.endsWith('Acronym.swift')), '@Siblings metatype arg links Acronym to the pivot').toBe(true);
  3983. });
  3984. });
  3985. describe('Objective-C messages, class receivers, and #import', () => {
  3986. let tempDir: string;
  3987. let cg: CodeGraph;
  3988. beforeEach(() => {
  3989. tempDir = createTempDir();
  3990. });
  3991. afterEach(() => {
  3992. if (cg) cg.close();
  3993. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  3994. });
  3995. it('resolves single-arg selectors, class-message receivers, and #import headers', async () => {
  3996. fs.writeFileSync(
  3997. path.join(tempDir, 'SDImageCache.h'),
  3998. `#import <Foundation/Foundation.h>
  3999. @interface SDImageCache : NSObject
  4000. + (instancetype)sharedCache;
  4001. + (void)storeImage:(NSString *)key;
  4002. @end
  4003. `
  4004. );
  4005. fs.writeFileSync(
  4006. path.join(tempDir, 'SDImageCache.m'),
  4007. `#import "SDImageCache.h"
  4008. @implementation SDImageCache
  4009. + (instancetype)sharedCache { return nil; }
  4010. + (void)storeImage:(NSString *)key { }
  4011. @end
  4012. `
  4013. );
  4014. fs.writeFileSync(
  4015. path.join(tempDir, 'SDManager.m'),
  4016. `#import "SDImageCache.h"
  4017. @interface SDManager : NSObject
  4018. @end
  4019. @implementation SDManager
  4020. - (void)run {
  4021. [SDImageCache sharedCache];
  4022. [SDImageCache storeImage:@"k"];
  4023. }
  4024. @end
  4025. `
  4026. );
  4027. cg = CodeGraph.initSync(tempDir);
  4028. await cg.indexAll();
  4029. cg.resolveReferences();
  4030. // 1. The single-argument selector `[SDImageCache storeImage:@"k"]` resolves
  4031. // to the `storeImage:` method — named WITH its colon both at the call site
  4032. // and the definition (before the fix the call site dropped the colon).
  4033. const storeImage = cg.getNodesByKind('method').find((n) => n.name === 'storeImage:');
  4034. expect(storeImage, 'storeImage: method').toBeDefined();
  4035. const storeCallers = [...cg.getImpactRadius(storeImage!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  4036. expect(storeCallers.some((p) => p.endsWith('SDManager.m'))).toBe(true);
  4037. // 2. The class-message receiver `[SDImageCache sharedCache]` references the
  4038. // SDImageCache class (whose @interface lives in the header).
  4039. const cache = cg.getNodesByKind('class').find((n) => n.name === 'SDImageCache');
  4040. expect(cache, 'SDImageCache class').toBeDefined();
  4041. const classDeps = [...cg.getImpactRadius(cache!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  4042. expect(classDeps.some((p) => p.endsWith('SDManager.m'))).toBe(true);
  4043. // 3. `#import "SDImageCache.h"` resolves to the header FILE — editing it
  4044. // surfaces both importers.
  4045. const header = cg.getNodesByKind('file').find((n) => n.filePath.endsWith('SDImageCache.h'));
  4046. expect(header, 'SDImageCache.h indexed').toBeDefined();
  4047. const importers = [...cg.getImpactRadius(header!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  4048. expect(importers.some((p) => p.endsWith('SDManager.m'))).toBe(true);
  4049. });
  4050. });
  4051. describe('Full Indexing', () => {
  4052. let tempDir: string;
  4053. beforeEach(() => {
  4054. tempDir = createTempDir();
  4055. });
  4056. afterEach(() => {
  4057. cleanupTempDir(tempDir);
  4058. });
  4059. it('should index a TypeScript file', async () => {
  4060. // Create test file
  4061. const srcDir = path.join(tempDir, 'src');
  4062. fs.mkdirSync(srcDir);
  4063. fs.writeFileSync(
  4064. path.join(srcDir, 'utils.ts'),
  4065. `
  4066. export function add(a: number, b: number): number {
  4067. return a + b;
  4068. }
  4069. export function multiply(a: number, b: number): number {
  4070. return a * b;
  4071. }
  4072. `
  4073. );
  4074. // Initialize and index
  4075. const cg = CodeGraph.initSync(tempDir);
  4076. const result = await cg.indexAll();
  4077. expect(result.success).toBe(true);
  4078. expect(result.filesIndexed).toBe(1);
  4079. expect(result.nodesCreated).toBeGreaterThanOrEqual(2);
  4080. // Check nodes were stored
  4081. const nodes = cg.getNodesInFile('src/utils.ts');
  4082. expect(nodes.length).toBeGreaterThanOrEqual(2);
  4083. const addFunc = nodes.find((n) => n.name === 'add');
  4084. expect(addFunc).toBeDefined();
  4085. expect(addFunc?.kind).toBe('function');
  4086. cg.close();
  4087. });
  4088. it('should index multiple files', async () => {
  4089. // Create test files
  4090. const srcDir = path.join(tempDir, 'src');
  4091. fs.mkdirSync(srcDir);
  4092. fs.writeFileSync(
  4093. path.join(srcDir, 'math.ts'),
  4094. `export function add(a: number, b: number) { return a + b; }`
  4095. );
  4096. fs.writeFileSync(
  4097. path.join(srcDir, 'string.ts'),
  4098. `export function capitalize(s: string) { return s.toUpperCase(); }`
  4099. );
  4100. // Initialize and index
  4101. const cg = CodeGraph.initSync(tempDir);
  4102. const result = await cg.indexAll();
  4103. expect(result.success).toBe(true);
  4104. expect(result.filesIndexed).toBe(2);
  4105. const files = cg.getFiles();
  4106. expect(files.length).toBe(2);
  4107. cg.close();
  4108. });
  4109. it('should track file hashes for incremental updates', async () => {
  4110. // Create initial file
  4111. const srcDir = path.join(tempDir, 'src');
  4112. fs.mkdirSync(srcDir);
  4113. fs.writeFileSync(path.join(srcDir, 'main.ts'), `export const x = 1;`);
  4114. // Initialize and index
  4115. const cg = CodeGraph.initSync(tempDir);
  4116. await cg.indexAll();
  4117. // Check file is tracked
  4118. const file = cg.getFile('src/main.ts');
  4119. expect(file).toBeDefined();
  4120. expect(file?.contentHash).toBeDefined();
  4121. // Modify file
  4122. fs.writeFileSync(path.join(srcDir, 'main.ts'), `export const x = 2;`);
  4123. // Check for changes
  4124. const changes = cg.getChangedFiles();
  4125. expect(changes.modified).toContain('src/main.ts');
  4126. cg.close();
  4127. });
  4128. it('should sync and detect changes', async () => {
  4129. // Create initial file
  4130. const srcDir = path.join(tempDir, 'src');
  4131. fs.mkdirSync(srcDir);
  4132. fs.writeFileSync(
  4133. path.join(srcDir, 'main.ts'),
  4134. `export function original() { return 1; }`
  4135. );
  4136. // Initialize and index
  4137. const cg = CodeGraph.initSync(tempDir);
  4138. await cg.indexAll();
  4139. const initialNodes = cg.getNodesInFile('src/main.ts');
  4140. expect(initialNodes.some((n) => n.name === 'original')).toBe(true);
  4141. // Modify file
  4142. fs.writeFileSync(
  4143. path.join(srcDir, 'main.ts'),
  4144. `export function updated() { return 2; }`
  4145. );
  4146. // Sync
  4147. const syncResult = await cg.sync();
  4148. expect(syncResult.filesModified).toBe(1);
  4149. // Check nodes were updated
  4150. const updatedNodes = cg.getNodesInFile('src/main.ts');
  4151. expect(updatedNodes.some((n) => n.name === 'updated')).toBe(true);
  4152. expect(updatedNodes.some((n) => n.name === 'original')).toBe(false);
  4153. cg.close();
  4154. });
  4155. it('should count file-level tracked YAML files as indexed', async () => {
  4156. fs.writeFileSync(path.join(tempDir, 'app.yaml'), 'name: test\n');
  4157. fs.writeFileSync(path.join(tempDir, 'routes.yml'), 'route: value\n');
  4158. const cg = CodeGraph.initSync(tempDir);
  4159. const result = await cg.indexAll();
  4160. expect(result.success).toBe(true);
  4161. expect(result.filesIndexed).toBe(2);
  4162. expect(result.filesSkipped).toBe(0);
  4163. expect(cg.getFiles().map((f) => f.path).sort()).toEqual(['app.yaml', 'routes.yml']);
  4164. cg.close();
  4165. });
  4166. it('should count file-level tracked YAML/Twig files as indexed in indexFiles()', async () => {
  4167. fs.writeFileSync(path.join(tempDir, 'app.yaml'), 'name: test\n');
  4168. fs.writeFileSync(path.join(tempDir, 'view.twig'), '{{ title }}\n');
  4169. const cg = CodeGraph.initSync(tempDir);
  4170. const result = await cg.indexFiles(['app.yaml', 'view.twig']);
  4171. expect(result.success).toBe(true);
  4172. expect(result.filesIndexed).toBe(2);
  4173. expect(result.filesSkipped).toBe(0);
  4174. const tracked = cg.getFiles().map((f) => `${f.path}:${f.language}`).sort();
  4175. expect(tracked).toEqual(['app.yaml:yaml', 'view.twig:twig']);
  4176. cg.close();
  4177. });
  4178. it('should count file-level tracked .properties files as indexed', async () => {
  4179. fs.writeFileSync(path.join(tempDir, 'application.properties'), 'server.port=8080\n');
  4180. fs.writeFileSync(path.join(tempDir, 'log.properties'), 'log.level=INFO\n');
  4181. const cg = CodeGraph.initSync(tempDir);
  4182. const result = await cg.indexAll();
  4183. expect(result.success).toBe(true);
  4184. expect(result.filesIndexed).toBe(2);
  4185. expect(result.filesSkipped).toBe(0);
  4186. cg.close();
  4187. });
  4188. it('should count the full file-level tracked class (yaml/twig/properties) in indexFiles()', async () => {
  4189. fs.writeFileSync(path.join(tempDir, 'app.yaml'), 'name: test\n');
  4190. fs.writeFileSync(path.join(tempDir, 'view.twig'), '{{ title }}\n');
  4191. fs.writeFileSync(path.join(tempDir, 'application.properties'), 'server.port=8080\n');
  4192. const cg = CodeGraph.initSync(tempDir);
  4193. const result = await cg.indexFiles(['app.yaml', 'view.twig', 'application.properties']);
  4194. expect(result.success).toBe(true);
  4195. expect(result.filesIndexed).toBe(3);
  4196. expect(result.filesSkipped).toBe(0);
  4197. const tracked = cg.getFiles().map((f) => `${f.path}:${f.language}`).sort();
  4198. expect(tracked).toEqual(['app.yaml:yaml', 'application.properties:properties', 'view.twig:twig']);
  4199. cg.close();
  4200. });
  4201. });
  4202. describe('Path Normalization', () => {
  4203. it('should convert backslashes to forward slashes', () => {
  4204. expect(normalizePath('gui\\node_modules\\foo')).toBe('gui/node_modules/foo');
  4205. expect(normalizePath('src\\components\\Button.tsx')).toBe('src/components/Button.tsx');
  4206. });
  4207. it('should leave forward-slash paths unchanged', () => {
  4208. expect(normalizePath('src/components/Button.tsx')).toBe('src/components/Button.tsx');
  4209. });
  4210. it('should handle empty string', () => {
  4211. expect(normalizePath('')).toBe('');
  4212. });
  4213. });
  4214. describe('Directory Exclusion', () => {
  4215. let tempDir: string;
  4216. beforeEach(() => {
  4217. tempDir = createTempDir();
  4218. });
  4219. afterEach(() => {
  4220. cleanupTempDir(tempDir);
  4221. });
  4222. it('should exclude directories listed in .gitignore', () => {
  4223. // Create structure: src/index.ts + node_modules/pkg/index.js, gitignore node_modules
  4224. const srcDir = path.join(tempDir, 'src');
  4225. const nmDir = path.join(tempDir, 'node_modules', 'pkg');
  4226. fs.mkdirSync(srcDir, { recursive: true });
  4227. fs.mkdirSync(nmDir, { recursive: true });
  4228. fs.writeFileSync(path.join(srcDir, 'index.ts'), 'export const x = 1;');
  4229. fs.writeFileSync(path.join(nmDir, 'index.js'), 'module.exports = {};');
  4230. fs.writeFileSync(path.join(tempDir, '.gitignore'), 'node_modules/\n');
  4231. const files = scanDirectory(tempDir);
  4232. expect(files).toContain('src/index.ts');
  4233. expect(files.every((f) => !f.includes('node_modules'))).toBe(true);
  4234. });
  4235. it('should exclude nested node_modules via a root .gitignore', () => {
  4236. // A trailing-slash pattern with no leading slash matches at any depth.
  4237. const srcDir = path.join(tempDir, 'packages', 'app', 'src');
  4238. const nmDir = path.join(tempDir, 'packages', 'app', 'node_modules', 'pkg');
  4239. fs.mkdirSync(srcDir, { recursive: true });
  4240. fs.mkdirSync(nmDir, { recursive: true });
  4241. fs.writeFileSync(path.join(srcDir, 'index.ts'), 'export const x = 1;');
  4242. fs.writeFileSync(path.join(nmDir, 'index.js'), 'module.exports = {};');
  4243. fs.writeFileSync(path.join(tempDir, '.gitignore'), 'node_modules/\n');
  4244. const files = scanDirectory(tempDir);
  4245. expect(files).toContain('packages/app/src/index.ts');
  4246. expect(files.every((f) => !f.includes('node_modules'))).toBe(true);
  4247. });
  4248. it('should apply a nested .gitignore only to its own subtree', () => {
  4249. const appSrc = path.join(tempDir, 'app', 'src');
  4250. fs.mkdirSync(appSrc, { recursive: true });
  4251. fs.writeFileSync(path.join(appSrc, 'keep.ts'), 'export const a = 1;');
  4252. fs.writeFileSync(path.join(appSrc, 'skip.ts'), 'export const b = 2;');
  4253. fs.writeFileSync(path.join(tempDir, 'app', '.gitignore'), 'src/skip.ts\n');
  4254. // A sibling with the same name outside app/ must NOT be ignored.
  4255. const otherDir = path.join(tempDir, 'other', 'src');
  4256. fs.mkdirSync(otherDir, { recursive: true });
  4257. fs.writeFileSync(path.join(otherDir, 'skip.ts'), 'export const c = 3;');
  4258. const files = scanDirectory(tempDir);
  4259. expect(files).toContain('app/src/keep.ts');
  4260. expect(files).not.toContain('app/src/skip.ts');
  4261. expect(files).toContain('other/src/skip.ts');
  4262. });
  4263. it('should always skip .git directories', () => {
  4264. const srcDir = path.join(tempDir, 'src');
  4265. const gitDir = path.join(tempDir, '.git', 'objects');
  4266. fs.mkdirSync(srcDir, { recursive: true });
  4267. fs.mkdirSync(gitDir, { recursive: true });
  4268. fs.writeFileSync(path.join(srcDir, 'index.ts'), 'export const x = 1;');
  4269. fs.writeFileSync(path.join(gitDir, 'pack.ts'), 'export const y = 2;');
  4270. const files = scanDirectory(tempDir);
  4271. expect(files).toContain('src/index.ts');
  4272. expect(files.every((f) => !f.includes('.git'))).toBe(true);
  4273. });
  4274. it('should return forward-slash paths on all platforms', () => {
  4275. const srcDir = path.join(tempDir, 'src', 'components');
  4276. fs.mkdirSync(srcDir, { recursive: true });
  4277. fs.writeFileSync(path.join(srcDir, 'Button.tsx'), 'export function Button() {}');
  4278. const files = scanDirectory(tempDir);
  4279. expect(files.length).toBe(1);
  4280. expect(files[0]).toBe('src/components/Button.tsx');
  4281. expect(files[0]).not.toContain('\\');
  4282. });
  4283. });
  4284. describe('Git Submodules', () => {
  4285. let tempDir: string;
  4286. beforeEach(() => {
  4287. tempDir = createTempDir();
  4288. });
  4289. afterEach(() => {
  4290. cleanupTempDir(tempDir);
  4291. });
  4292. it('should index files inside git submodules (issue #147)', async () => {
  4293. const { execFileSync } = await import('child_process');
  4294. const git = (cwd: string, ...args: string[]) =>
  4295. execFileSync('git', args, { cwd, stdio: 'pipe' });
  4296. // Build a separate "library" repo to use as a submodule source.
  4297. const libDir = path.join(tempDir, '_lib');
  4298. fs.mkdirSync(libDir, { recursive: true });
  4299. git(libDir, 'init', '-q');
  4300. git(libDir, 'config', 'user.email', 'test@test.com');
  4301. git(libDir, 'config', 'user.name', 'Test');
  4302. fs.writeFileSync(path.join(libDir, 'lib.ts'), 'export const fromSubmodule = 1;');
  4303. git(libDir, 'add', '-A');
  4304. git(libDir, 'commit', '-q', '-m', 'lib init');
  4305. // Build the main repo and add the lib repo as a submodule.
  4306. const mainDir = path.join(tempDir, 'main');
  4307. fs.mkdirSync(mainDir, { recursive: true });
  4308. git(mainDir, 'init', '-q');
  4309. git(mainDir, 'config', 'user.email', 'test@test.com');
  4310. git(mainDir, 'config', 'user.name', 'Test');
  4311. fs.writeFileSync(path.join(mainDir, 'app.ts'), 'export const app = 1;');
  4312. git(mainDir, 'add', '-A');
  4313. git(mainDir, 'commit', '-q', '-m', 'app init');
  4314. // protocol.file.allow=always is required to add a local-path submodule on
  4315. // recent git versions (CVE-2022-39253 mitigation).
  4316. execFileSync(
  4317. 'git',
  4318. ['-c', 'protocol.file.allow=always', 'submodule', 'add', '-q', libDir, 'libs/lib'],
  4319. { cwd: mainDir, stdio: 'pipe' }
  4320. );
  4321. git(mainDir, 'commit', '-q', '-m', 'add submodule');
  4322. const files = scanDirectory(mainDir);
  4323. expect(files).toContain('app.ts');
  4324. expect(files).toContain('libs/lib/lib.ts');
  4325. });
  4326. });
  4327. describe('Nested non-submodule git repos', () => {
  4328. let tempDir: string;
  4329. beforeEach(() => {
  4330. tempDir = createTempDir();
  4331. });
  4332. afterEach(() => {
  4333. cleanupTempDir(tempDir);
  4334. });
  4335. it('should index files in embedded git repos run from a git super-repo (issue #193)', async () => {
  4336. const { execFileSync } = await import('child_process');
  4337. const git = (cwd: string, ...args: string[]) =>
  4338. execFileSync('git', args, { cwd, stdio: 'pipe' });
  4339. // Top-level workspace is itself a git repo, holding no source directly —
  4340. // the CMake "super-repo" layout from the issue.
  4341. const root = path.join(tempDir, 'root');
  4342. fs.mkdirSync(path.join(root, 'coding'), { recursive: true });
  4343. git(root, 'init', '-q');
  4344. git(root, 'config', 'user.email', 'test@test.com');
  4345. git(root, 'config', 'user.name', 'Test');
  4346. fs.writeFileSync(path.join(root, 'CMakeLists.txt'), 'cmake_minimum_required(VERSION 3.10)\n');
  4347. // Two independent clones living inside the workspace (NOT submodules):
  4348. // one with committed source, one with only untracked source.
  4349. const sub1 = path.join(root, 'sub_repo1', 'src');
  4350. fs.mkdirSync(sub1, { recursive: true });
  4351. git(path.join(root, 'sub_repo1'), 'init', '-q');
  4352. git(path.join(root, 'sub_repo1'), 'config', 'user.email', 'test@test.com');
  4353. git(path.join(root, 'sub_repo1'), 'config', 'user.name', 'Test');
  4354. fs.writeFileSync(path.join(sub1, 'one.ts'), 'export const one = 1;');
  4355. git(path.join(root, 'sub_repo1'), 'add', '-A');
  4356. git(path.join(root, 'sub_repo1'), 'commit', '-q', '-m', 'sub1 init');
  4357. const sub2 = path.join(root, 'sub_repo2', 'src');
  4358. fs.mkdirSync(sub2, { recursive: true });
  4359. git(path.join(root, 'sub_repo2'), 'init', '-q');
  4360. fs.writeFileSync(path.join(sub2, 'two.ts'), 'export const two = 2;');
  4361. const files = scanDirectory(root);
  4362. // Both committed and untracked source from the nested repos must be found.
  4363. expect(files).toContain('sub_repo1/src/one.ts');
  4364. expect(files).toContain('sub_repo2/src/two.ts');
  4365. });
  4366. it('should respect each embedded repo\'s own .gitignore', async () => {
  4367. const { execFileSync } = await import('child_process');
  4368. const git = (cwd: string, ...args: string[]) =>
  4369. execFileSync('git', args, { cwd, stdio: 'pipe' });
  4370. const root = path.join(tempDir, 'root');
  4371. fs.mkdirSync(root, { recursive: true });
  4372. git(root, 'init', '-q');
  4373. const sub = path.join(root, 'sub_repo', 'src');
  4374. fs.mkdirSync(sub, { recursive: true });
  4375. git(path.join(root, 'sub_repo'), 'init', '-q');
  4376. fs.writeFileSync(path.join(root, 'sub_repo', '.gitignore'), 'src/generated.ts\n');
  4377. fs.writeFileSync(path.join(sub, 'real.ts'), 'export const real = 1;');
  4378. fs.writeFileSync(path.join(sub, 'generated.ts'), 'export const generated = 1;');
  4379. const files = scanDirectory(root);
  4380. expect(files).toContain('sub_repo/src/real.ts');
  4381. expect(files).not.toContain('sub_repo/src/generated.ts');
  4382. });
  4383. });
  4384. // =============================================================================
  4385. // Scala
  4386. // =============================================================================
  4387. describe('Scala Extraction', () => {
  4388. describe('Language detection', () => {
  4389. it('should detect Scala files', () => {
  4390. expect(detectLanguage('Main.scala')).toBe('scala');
  4391. expect(detectLanguage('script.sc')).toBe('scala');
  4392. expect(detectLanguage('src/UserService.scala')).toBe('scala');
  4393. });
  4394. it('should report Scala as supported', () => {
  4395. expect(isLanguageSupported('scala')).toBe(true);
  4396. expect(getSupportedLanguages()).toContain('scala');
  4397. });
  4398. });
  4399. describe('Class extraction', () => {
  4400. it('should extract class definitions', () => {
  4401. const code = `
  4402. class UserService(private val repo: UserRepository) {
  4403. def findUser(id: String): Option[String] = Some(id)
  4404. }
  4405. `;
  4406. const result = extractFromSource('UserService.scala', code);
  4407. const cls = result.nodes.find((n) => n.kind === 'class' && n.name === 'UserService');
  4408. expect(cls).toBeDefined();
  4409. expect(cls?.language).toBe('scala');
  4410. });
  4411. it('should extract object definitions as class kind', () => {
  4412. const code = `
  4413. object DatabaseConfig {
  4414. val url = "jdbc:postgresql://localhost/mydb"
  4415. }
  4416. `;
  4417. const result = extractFromSource('Config.scala', code);
  4418. const obj = result.nodes.find((n) => n.kind === 'class' && n.name === 'DatabaseConfig');
  4419. expect(obj).toBeDefined();
  4420. });
  4421. it('should extract trait definitions as trait kind', () => {
  4422. const code = `
  4423. trait Repository[A] {
  4424. def findById(id: String): Option[A]
  4425. def save(entity: A): Unit
  4426. }
  4427. `;
  4428. const result = extractFromSource('Repository.scala', code);
  4429. const trait_ = result.nodes.find((n) => n.kind === 'trait' && n.name === 'Repository');
  4430. expect(trait_).toBeDefined();
  4431. });
  4432. });
  4433. describe('Method and function extraction', () => {
  4434. it('should extract method definitions inside a class', () => {
  4435. const code = `
  4436. class Calculator {
  4437. def add(a: Int, b: Int): Int = a + b
  4438. def divide(a: Double, b: Double): Double = a / b
  4439. }
  4440. `;
  4441. const result = extractFromSource('Calculator.scala', code);
  4442. const methods = result.nodes.filter((n) => n.kind === 'method');
  4443. expect(methods.find((m) => m.name === 'add')).toBeDefined();
  4444. expect(methods.find((m) => m.name === 'divide')).toBeDefined();
  4445. });
  4446. it('should extract method signatures', () => {
  4447. const code = `
  4448. class Greeter {
  4449. def greet(name: String): String = s"Hello, \${name}!"
  4450. }
  4451. `;
  4452. const result = extractFromSource('Greeter.scala', code);
  4453. const method = result.nodes.find((n) => n.name === 'greet');
  4454. expect(method?.signature).toContain('name: String');
  4455. expect(method?.signature).toContain('String');
  4456. });
  4457. it('should extract top-level function definitions as functions', () => {
  4458. const code = `
  4459. def factorial(n: Int): Int = if (n <= 1) 1 else n * factorial(n - 1)
  4460. def greet(name: String): String = s"Hello, \${name}!"
  4461. `;
  4462. const result = extractFromSource('utils.scala', code);
  4463. const fns = result.nodes.filter((n) => n.kind === 'function');
  4464. expect(fns.find((f) => f.name === 'factorial')).toBeDefined();
  4465. expect(fns.find((f) => f.name === 'greet')).toBeDefined();
  4466. });
  4467. });
  4468. describe('Val and var extraction', () => {
  4469. it('should extract val inside a class as field', () => {
  4470. const code = `
  4471. class Config {
  4472. val timeout: Int = 30
  4473. val host: String = "localhost"
  4474. }
  4475. `;
  4476. const result = extractFromSource('Config.scala', code);
  4477. const fields = result.nodes.filter((n) => n.kind === 'field');
  4478. expect(fields.find((f) => f.name === 'timeout')).toBeDefined();
  4479. expect(fields.find((f) => f.name === 'host')).toBeDefined();
  4480. });
  4481. it('should extract var inside a class as field', () => {
  4482. const code = `
  4483. class Counter {
  4484. var count: Int = 0
  4485. }
  4486. `;
  4487. const result = extractFromSource('Counter.scala', code);
  4488. const field = result.nodes.find((n) => n.kind === 'field' && n.name === 'count');
  4489. expect(field).toBeDefined();
  4490. });
  4491. it('should extract top-level val as constant', () => {
  4492. const code = `
  4493. val MaxConnections: Int = 100
  4494. val DefaultTimeout = 30
  4495. `;
  4496. const result = extractFromSource('constants.scala', code);
  4497. const consts = result.nodes.filter((n) => n.kind === 'constant');
  4498. expect(consts.find((c) => c.name === 'MaxConnections')).toBeDefined();
  4499. });
  4500. it('should extract top-level var as variable', () => {
  4501. const code = `
  4502. var retries: Int = 3
  4503. `;
  4504. const result = extractFromSource('state.scala', code);
  4505. const v = result.nodes.find((n) => n.kind === 'variable' && n.name === 'retries');
  4506. expect(v).toBeDefined();
  4507. });
  4508. it('should include type in val/var signature', () => {
  4509. const code = `
  4510. class Service {
  4511. val timeout: Int = 30
  4512. }
  4513. `;
  4514. const result = extractFromSource('Service.scala', code);
  4515. const field = result.nodes.find((n) => n.name === 'timeout');
  4516. expect(field?.signature).toContain('timeout');
  4517. expect(field?.signature).toContain('Int');
  4518. });
  4519. });
  4520. describe('Enum extraction', () => {
  4521. it('should extract enum definitions', () => {
  4522. const code = `
  4523. enum Color:
  4524. case Red
  4525. case Green
  4526. case Blue
  4527. `;
  4528. const result = extractFromSource('Color.scala', code);
  4529. const enumNode = result.nodes.find((n) => n.kind === 'enum' && n.name === 'Color');
  4530. expect(enumNode).toBeDefined();
  4531. });
  4532. it('should extract enum cases as enum_member', () => {
  4533. const code = `
  4534. enum Direction:
  4535. case North
  4536. case South
  4537. case East
  4538. case West
  4539. `;
  4540. const result = extractFromSource('Direction.scala', code);
  4541. const members = result.nodes.filter((n) => n.kind === 'enum_member');
  4542. expect(members.find((m) => m.name === 'North')).toBeDefined();
  4543. expect(members.find((m) => m.name === 'South')).toBeDefined();
  4544. expect(members.length).toBeGreaterThanOrEqual(4);
  4545. });
  4546. });
  4547. describe('Type alias extraction', () => {
  4548. it('should extract type aliases', () => {
  4549. const code = `
  4550. type UserId = String
  4551. type UserMap = Map[String, String]
  4552. `;
  4553. const result = extractFromSource('types.scala', code);
  4554. const aliases = result.nodes.filter((n) => n.kind === 'type_alias');
  4555. expect(aliases.find((a) => a.name === 'UserId')).toBeDefined();
  4556. expect(aliases.find((a) => a.name === 'UserMap')).toBeDefined();
  4557. });
  4558. });
  4559. describe('Import extraction', () => {
  4560. it('should extract import declarations', () => {
  4561. const code = `
  4562. import scala.collection.mutable.ListBuffer
  4563. import scala.concurrent.Future
  4564. `;
  4565. const result = extractFromSource('imports.scala', code);
  4566. const imports = result.nodes.filter((n) => n.kind === 'import');
  4567. expect(imports.length).toBeGreaterThanOrEqual(2);
  4568. });
  4569. });
  4570. describe('Visibility modifiers', () => {
  4571. it('should extract private visibility', () => {
  4572. const code = `
  4573. class Service {
  4574. private val secret: String = "abc"
  4575. private def helper(): Unit = {}
  4576. }
  4577. `;
  4578. const result = extractFromSource('Service.scala', code);
  4579. const secretField = result.nodes.find((n) => n.name === 'secret');
  4580. expect(secretField?.visibility).toBe('private');
  4581. const helperMethod = result.nodes.find((n) => n.name === 'helper');
  4582. expect(helperMethod?.visibility).toBe('private');
  4583. });
  4584. it('should extract protected visibility', () => {
  4585. const code = `
  4586. class Base {
  4587. protected def helperMethod(): Unit = {}
  4588. }
  4589. `;
  4590. const result = extractFromSource('Base.scala', code);
  4591. const method = result.nodes.find((n) => n.name === 'helperMethod');
  4592. expect(method?.visibility).toBe('protected');
  4593. });
  4594. it('should default to public visibility', () => {
  4595. const code = `
  4596. class Greeter {
  4597. def hello(): Unit = {}
  4598. }
  4599. `;
  4600. const result = extractFromSource('Greeter.scala', code);
  4601. const method = result.nodes.find((n) => n.name === 'hello');
  4602. expect(method?.visibility).toBe('public');
  4603. });
  4604. });
  4605. describe('Inheritance', () => {
  4606. it('should extract extends relationships', () => {
  4607. const code = `
  4608. class AdminUser extends User {
  4609. def adminAction(): Unit = {}
  4610. }
  4611. `;
  4612. const result = extractFromSource('AdminUser.scala', code);
  4613. const extendsRefs = result.unresolvedReferences.filter((r) => r.referenceKind === 'extends');
  4614. expect(extendsRefs.find((r) => r.referenceName === 'User')).toBeDefined();
  4615. });
  4616. });
  4617. describe('Call extraction', () => {
  4618. it('should extract function call expressions', () => {
  4619. const code = `
  4620. def processData(): Unit = {
  4621. val result = computeResult()
  4622. println(result)
  4623. }
  4624. `;
  4625. const result = extractFromSource('processor.scala', code);
  4626. const calls = result.unresolvedReferences.filter((r) => r.referenceKind === 'calls');
  4627. expect(calls.length).toBeGreaterThan(0);
  4628. });
  4629. });
  4630. });
  4631. describe('Vue Extraction', () => {
  4632. it('should detect Vue files', () => {
  4633. expect(detectLanguage('App.vue')).toBe('vue');
  4634. expect(detectLanguage('components/Button.vue')).toBe('vue');
  4635. expect(isLanguageSupported('vue')).toBe(true);
  4636. });
  4637. it('should extract component node from a Vue SFC', () => {
  4638. const code = `<template>
  4639. <div>{{ message }}</div>
  4640. </template>
  4641. <script>
  4642. export default {
  4643. data() {
  4644. return { message: 'Hello' };
  4645. }
  4646. }
  4647. </script>
  4648. `;
  4649. const result = extractFromSource('HelloWorld.vue', code);
  4650. const componentNode = result.nodes.find((n) => n.kind === 'component');
  4651. expect(componentNode).toBeDefined();
  4652. expect(componentNode?.name).toBe('HelloWorld');
  4653. expect(componentNode?.language).toBe('vue');
  4654. expect(componentNode?.isExported).toBe(true);
  4655. });
  4656. it('should extract functions from <script> block', () => {
  4657. const code = `<template>
  4658. <button @click="handleClick">Click</button>
  4659. </template>
  4660. <script>
  4661. function handleClick() {
  4662. console.log('clicked');
  4663. }
  4664. const count = 0;
  4665. </script>
  4666. `;
  4667. const result = extractFromSource('Button.vue', code);
  4668. const componentNode = result.nodes.find((n) => n.kind === 'component');
  4669. expect(componentNode).toBeDefined();
  4670. expect(componentNode?.name).toBe('Button');
  4671. const funcNode = result.nodes.find((n) => n.kind === 'function' && n.name === 'handleClick');
  4672. expect(funcNode).toBeDefined();
  4673. expect(funcNode?.language).toBe('vue');
  4674. });
  4675. it('should extract from <script setup lang="ts"> block', () => {
  4676. const code = `<template>
  4677. <div>{{ count }}</div>
  4678. </template>
  4679. <script setup lang="ts">
  4680. import { ref } from 'vue';
  4681. const count = ref(0);
  4682. function increment(): void {
  4683. count.value++;
  4684. }
  4685. </script>
  4686. `;
  4687. const result = extractFromSource('Counter.vue', code);
  4688. const componentNode = result.nodes.find((n) => n.kind === 'component');
  4689. expect(componentNode).toBeDefined();
  4690. expect(componentNode?.name).toBe('Counter');
  4691. const funcNode = result.nodes.find((n) => n.kind === 'function' && n.name === 'increment');
  4692. expect(funcNode).toBeDefined();
  4693. expect(funcNode?.language).toBe('vue');
  4694. // All nodes should be marked as vue language
  4695. for (const node of result.nodes) {
  4696. expect(node.language).toBe('vue');
  4697. }
  4698. });
  4699. it('should extract calls from top-level <script setup> initializers', () => {
  4700. const code = `<template>
  4701. <div>{{ token }}</div>
  4702. </template>
  4703. <script setup lang="ts">
  4704. import { getTokenMp } from './api/upload';
  4705. const token = getTokenMp();
  4706. </script>
  4707. `;
  4708. const result = extractFromSource('Issue425Setup.vue', code);
  4709. const call = result.unresolvedReferences.find(
  4710. (ref) => ref.referenceKind === 'calls' && ref.referenceName === 'getTokenMp'
  4711. );
  4712. expect(call).toBeDefined();
  4713. });
  4714. it('should extract calls from Vue Options API object methods', () => {
  4715. const code = `<template>
  4716. <button @click="save">Save</button>
  4717. </template>
  4718. <script>
  4719. import { getTokenMp } from './api/upload';
  4720. export default {
  4721. methods: {
  4722. save() {
  4723. return getTokenMp();
  4724. }
  4725. },
  4726. setup() {
  4727. return getTokenMp();
  4728. }
  4729. }
  4730. </script>
  4731. `;
  4732. const result = extractFromSource('Issue425Options.vue', code);
  4733. const calls = result.unresolvedReferences.filter(
  4734. (ref) => ref.referenceKind === 'calls' && ref.referenceName === 'getTokenMp'
  4735. );
  4736. expect(calls).toHaveLength(2);
  4737. });
  4738. it('should extract component usages from the Vue template (PascalCase + kebab, skipping built-ins) (#629)', () => {
  4739. const code = `<template>
  4740. <div class="wrap">
  4741. <UserCard :user="u" />
  4742. <my-button>Click</my-button>
  4743. <Transition><span>x</span></Transition>
  4744. </div>
  4745. </template>
  4746. <script setup lang="ts">
  4747. import UserCard from './UserCard.vue';
  4748. import MyButton from './MyButton.vue';
  4749. </script>
  4750. `;
  4751. const result = extractFromSource('Host.vue', code);
  4752. const refs = result.unresolvedReferences
  4753. .filter((r) => r.referenceKind === 'references')
  4754. .map((r) => r.referenceName);
  4755. expect(refs).toContain('UserCard'); // PascalCase tag
  4756. expect(refs).toContain('MyButton'); // kebab <my-button> → MyButton
  4757. expect(refs).not.toContain('Transition'); // Vue built-in skipped
  4758. expect(refs).not.toContain('Div'); // native HTML element skipped
  4759. expect(refs).not.toContain('Span');
  4760. });
  4761. it('should extract from both <script> and <script setup> blocks', () => {
  4762. const code = `<template>
  4763. <div>{{ msg }}</div>
  4764. </template>
  4765. <script>
  4766. export default {
  4767. name: 'DualScript'
  4768. }
  4769. </script>
  4770. <script setup>
  4771. const msg = 'hello';
  4772. function greet() {
  4773. return msg;
  4774. }
  4775. </script>
  4776. `;
  4777. const result = extractFromSource('DualScript.vue', code);
  4778. const componentNode = result.nodes.find((n) => n.kind === 'component');
  4779. expect(componentNode).toBeDefined();
  4780. const greetFunc = result.nodes.find((n) => n.kind === 'function' && n.name === 'greet');
  4781. expect(greetFunc).toBeDefined();
  4782. });
  4783. it('should create component node for template-only Vue file', () => {
  4784. const code = `<template>
  4785. <div>Static content</div>
  4786. </template>
  4787. `;
  4788. const result = extractFromSource('Static.vue', code);
  4789. const componentNode = result.nodes.find((n) => n.kind === 'component');
  4790. expect(componentNode).toBeDefined();
  4791. expect(componentNode?.name).toBe('Static');
  4792. expect(componentNode?.language).toBe('vue');
  4793. // Only the component node should exist (no script nodes)
  4794. expect(result.nodes.length).toBe(1);
  4795. });
  4796. it('should create containment edges from component to script nodes', () => {
  4797. const code = `<template>
  4798. <div>{{ value }}</div>
  4799. </template>
  4800. <script setup lang="ts">
  4801. const value = 42;
  4802. </script>
  4803. `;
  4804. const result = extractFromSource('Contained.vue', code);
  4805. const componentNode = result.nodes.find((n) => n.kind === 'component');
  4806. expect(componentNode).toBeDefined();
  4807. // Should have containment edges from component to child nodes
  4808. const containEdges = result.edges.filter(
  4809. (e) => e.source === componentNode!.id && e.kind === 'contains'
  4810. );
  4811. expect(containEdges.length).toBeGreaterThan(0);
  4812. });
  4813. });
  4814. describe('Instantiates + Decorates edge extraction', () => {
  4815. it('emits an instantiates ref for `new Foo()`', () => {
  4816. const code = `
  4817. class Foo {}
  4818. function bootstrap() { return new Foo(); }
  4819. `;
  4820. const result = extractFromSource('app.ts', code);
  4821. const ref = result.unresolvedReferences.find(
  4822. (r) => r.referenceKind === 'instantiates' && r.referenceName === 'Foo'
  4823. );
  4824. expect(ref).toBeDefined();
  4825. });
  4826. it('strips type-argument suffix from generic constructors', () => {
  4827. const code = `
  4828. class Container<T> { constructor(_: T) {} }
  4829. function go() { return new Container<string>('x'); }
  4830. `;
  4831. const result = extractFromSource('app.ts', code);
  4832. const ref = result.unresolvedReferences.find(
  4833. (r) => r.referenceKind === 'instantiates'
  4834. );
  4835. expect(ref).toBeDefined();
  4836. // Container<string> must be normalised to "Container" — otherwise
  4837. // resolution can never match the class node.
  4838. expect(ref!.referenceName).toBe('Container');
  4839. });
  4840. it('keeps trailing identifier from qualified `new ns.Foo()`', () => {
  4841. const code = `
  4842. const ns = { Foo: class {} };
  4843. function go() { return new ns.Foo(); }
  4844. `;
  4845. const result = extractFromSource('app.ts', code);
  4846. const ref = result.unresolvedReferences.find(
  4847. (r) => r.referenceKind === 'instantiates'
  4848. );
  4849. // We can't always resolve which Foo, but the name should be the
  4850. // simple identifier so name-matching has a chance.
  4851. expect(ref?.referenceName).toBe('Foo');
  4852. });
  4853. it('emits a decorates ref for `@Foo class X {}`', () => {
  4854. const code = `
  4855. function Foo(_arg: string) { return (cls: any) => cls; }
  4856. @Foo('x')
  4857. class X {}
  4858. `;
  4859. const result = extractFromSource('app.ts', code);
  4860. const decorClass = result.unresolvedReferences.find(
  4861. (r) => r.referenceKind === 'decorates' && r.referenceName === 'Foo'
  4862. );
  4863. expect(decorClass).toBeDefined();
  4864. });
  4865. it('does NOT attribute a prior class\'s decorator to the next class', () => {
  4866. // Regression: the sibling-walk must stop at the first non-
  4867. // decorator separator. `@A class Foo {} @B class Bar {}` must
  4868. // produce `decorates(Foo, A)` and `decorates(Bar, B)` — never
  4869. // `decorates(Bar, A)`.
  4870. const code = `
  4871. function A(cls: any) { return cls; }
  4872. function B(cls: any) { return cls; }
  4873. @A
  4874. class Foo {}
  4875. @B
  4876. class Bar {}
  4877. `;
  4878. const result = extractFromSource('app.ts', code);
  4879. const decoratesEdges = result.unresolvedReferences.filter(
  4880. (r) => r.referenceKind === 'decorates'
  4881. );
  4882. // Exactly one decorates ref per decorated class, no cross-attribution.
  4883. const fromBar = decoratesEdges.filter((r) =>
  4884. result.nodes.find((n) => n.id === r.fromNodeId && n.name === 'Bar')
  4885. );
  4886. expect(fromBar.length).toBe(1);
  4887. expect(fromBar[0]!.referenceName).toBe('B');
  4888. });
  4889. it('emits a decorates ref for `@Foo method() {}`', () => {
  4890. const code = `
  4891. function Get(p: string) { return (t: any, k: string) => t; }
  4892. class Svc {
  4893. @Get('/x') method() { return 1; }
  4894. }
  4895. `;
  4896. const result = extractFromSource('app.ts', code);
  4897. const decorMethod = result.unresolvedReferences.find(
  4898. (r) => r.referenceKind === 'decorates' && r.referenceName === 'Get'
  4899. );
  4900. expect(decorMethod).toBeDefined();
  4901. // The decorated symbol must be `method`, not the constructor or class.
  4902. const decoratedNode = result.nodes.find((n) => n.id === decorMethod!.fromNodeId);
  4903. expect(decoratedNode?.name).toBe('method');
  4904. });
  4905. });
  4906. // =============================================================================
  4907. // Lua
  4908. // =============================================================================
  4909. describe('Lua Extraction', () => {
  4910. describe('Language detection', () => {
  4911. it('should detect Lua files', () => {
  4912. expect(detectLanguage('init.lua')).toBe('lua');
  4913. expect(detectLanguage('src/util.lua')).toBe('lua');
  4914. });
  4915. it('should report Lua as supported', () => {
  4916. expect(isLanguageSupported('lua')).toBe(true);
  4917. expect(getSupportedLanguages()).toContain('lua');
  4918. });
  4919. });
  4920. describe('Function extraction', () => {
  4921. it('should extract global and local functions', () => {
  4922. const code = `
  4923. function configure(opts) return opts end
  4924. local function helper(x) return x * 2 end
  4925. `;
  4926. const result = extractFromSource('init.lua', code);
  4927. const funcs = result.nodes.filter((n) => n.kind === 'function').map((n) => n.name);
  4928. expect(funcs).toContain('configure');
  4929. expect(funcs).toContain('helper');
  4930. const configure = result.nodes.find((n) => n.name === 'configure');
  4931. expect(configure?.language).toBe('lua');
  4932. expect(configure?.signature).toBe('(opts)');
  4933. });
  4934. it('should split table/method functions into a receiver and method name', () => {
  4935. const code = `
  4936. function M.connect(host, port) return host end
  4937. function M:send(data) return self end
  4938. `;
  4939. const result = extractFromSource('init.lua', code);
  4940. const methods = result.nodes.filter((n) => n.kind === 'method');
  4941. const connect = methods.find((m) => m.name === 'connect');
  4942. expect(connect?.qualifiedName).toBe('M::connect');
  4943. const send = methods.find((m) => m.name === 'send');
  4944. expect(send?.qualifiedName).toBe('M::send');
  4945. });
  4946. });
  4947. describe('Variable extraction', () => {
  4948. it('should extract local variable declarations', () => {
  4949. const code = `
  4950. local M = {}
  4951. local count = 0
  4952. `;
  4953. const result = extractFromSource('mod.lua', code);
  4954. const vars = result.nodes.filter((n) => n.kind === 'variable').map((n) => n.name);
  4955. expect(vars).toContain('M');
  4956. expect(vars).toContain('count');
  4957. });
  4958. });
  4959. describe('Import extraction (require)', () => {
  4960. it('should extract require() in local declarations and bare calls', () => {
  4961. const code = `
  4962. local socket = require("socket")
  4963. local http = require "resty.http"
  4964. require("side.effect")
  4965. `;
  4966. const result = extractFromSource('net.lua', code);
  4967. const imports = result.nodes.filter((n) => n.kind === 'import').map((n) => n.name);
  4968. expect(imports).toContain('socket');
  4969. expect(imports).toContain('resty.http');
  4970. expect(imports).toContain('side.effect');
  4971. const ref = result.unresolvedReferences.find(
  4972. (r) => r.referenceKind === 'imports' && r.referenceName === 'socket'
  4973. );
  4974. expect(ref).toBeDefined();
  4975. });
  4976. // Regression: the tree-sitter-wasms Lua grammar (ABI 13) corrupts the shared
  4977. // WASM heap under web-tree-sitter 0.25, dropping nested calls/imports on every
  4978. // parse after the first. We vendor the ABI-15 grammar instead — this guards it
  4979. // by extracting several sources in sequence and asserting the LAST still works.
  4980. it('should keep extracting require across many sequential parses', () => {
  4981. let last;
  4982. for (let i = 0; i < 8; i++) {
  4983. last = extractFromSource(`f${i}.lua`, `local m = require("module.${i}")\nreturn m\n`);
  4984. }
  4985. const imports = last!.nodes.filter((n) => n.kind === 'import').map((n) => n.name);
  4986. expect(imports).toContain('module.7');
  4987. });
  4988. });
  4989. describe('Call extraction', () => {
  4990. it('should record intra-file calls as resolvable references', () => {
  4991. const code = `
  4992. local function helper(x) return x end
  4993. local function run(y) return helper(y) end
  4994. `;
  4995. const result = extractFromSource('calls.lua', code);
  4996. const call = result.unresolvedReferences.find(
  4997. (r) => r.referenceKind === 'calls' && r.referenceName === 'helper'
  4998. );
  4999. expect(call).toBeDefined();
  5000. });
  5001. });
  5002. });
  5003. // =============================================================================
  5004. // Luau (typed superset of Lua — https://luau.org)
  5005. // =============================================================================
  5006. describe('Luau Extraction', () => {
  5007. describe('Language detection', () => {
  5008. it('should detect Luau files', () => {
  5009. expect(detectLanguage('init.luau')).toBe('luau');
  5010. expect(detectLanguage('src/Client.luau')).toBe('luau');
  5011. });
  5012. it('should report Luau as supported', () => {
  5013. expect(isLanguageSupported('luau')).toBe(true);
  5014. expect(getSupportedLanguages()).toContain('luau');
  5015. });
  5016. });
  5017. describe('Type aliases', () => {
  5018. it('should extract `type` and `export type` definitions', () => {
  5019. const code = `
  5020. export type Vector = { x: number, y: number }
  5021. type Handler = (msg: string) -> boolean
  5022. `;
  5023. const result = extractFromSource('types.luau', code);
  5024. const aliases = result.nodes.filter((n) => n.kind === 'type_alias');
  5025. const vector = aliases.find((a) => a.name === 'Vector');
  5026. expect(vector).toBeDefined();
  5027. expect(vector?.isExported).toBe(true);
  5028. const handler = aliases.find((a) => a.name === 'Handler');
  5029. expect(handler).toBeDefined();
  5030. expect(handler?.isExported).toBe(false);
  5031. });
  5032. });
  5033. describe('Typed functions and methods', () => {
  5034. it('should capture typed signatures and split methods by receiver', () => {
  5035. const code = `
  5036. function configure(opts: { debug: boolean }): boolean
  5037. return opts.debug
  5038. end
  5039. function Client:fetch(path: string): Response
  5040. return path
  5041. end
  5042. `;
  5043. const result = extractFromSource('client.luau', code);
  5044. const configure = result.nodes.find((n) => n.kind === 'function' && n.name === 'configure');
  5045. expect(configure?.language).toBe('luau');
  5046. expect(configure?.signature).toBe('(opts: { debug: boolean }): boolean');
  5047. const fetch = result.nodes.find((n) => n.kind === 'method' && n.name === 'fetch');
  5048. expect(fetch?.qualifiedName).toBe('Client::fetch');
  5049. });
  5050. });
  5051. describe('Imports and variables', () => {
  5052. it('should extract string and Roblox instance-path require imports', () => {
  5053. const code = `
  5054. local http = require("http")
  5055. local Signal = require(script.Parent.Signal)
  5056. local count = 0
  5057. `;
  5058. const result = extractFromSource('mod.luau', code);
  5059. const imports = result.nodes.filter((n) => n.kind === 'import').map((n) => n.name);
  5060. expect(imports).toContain('http'); // string require
  5061. expect(imports).toContain('Signal'); // Roblox instance-path require
  5062. const vars = result.nodes.filter((n) => n.kind === 'variable').map((n) => n.name);
  5063. expect(vars).toContain('count');
  5064. });
  5065. });
  5066. });
  5067. // =============================================================================
  5068. // Objective-C
  5069. // =============================================================================
  5070. describe('Objective-C Extraction', () => {
  5071. const sample = `
  5072. #import <Foundation/Foundation.h>
  5073. #import "MyClass.h"
  5074. @interface MyClass : NSObject <NSCopying>
  5075. @property (nonatomic, copy) NSString *name;
  5076. - (void)greet;
  5077. - (void)doThing:(id)x with:(id)y;
  5078. + (instancetype)shared;
  5079. @end
  5080. @implementation MyClass
  5081. - (void)greet {
  5082. NSLog(@"Hello");
  5083. [self doWork];
  5084. }
  5085. - (void)doThing:(id)x with:(id)y {
  5086. [self notify:x];
  5087. }
  5088. + (instancetype)shared {
  5089. return [[MyClass alloc] init];
  5090. }
  5091. @end
  5092. void helperFunction(int count) {
  5093. MyClass *obj = [MyClass shared];
  5094. [obj greet];
  5095. }
  5096. `;
  5097. it('should extract classes, methods, functions, and imports', () => {
  5098. const result = extractFromSource('App.m', sample);
  5099. const classes = result.nodes.filter((n) => n.kind === 'class');
  5100. expect(classes.filter((c) => c.name === 'MyClass')).toHaveLength(1);
  5101. const methods = result.nodes.filter((n) => n.kind === 'method');
  5102. expect(methods.map((m) => m.name).sort()).toEqual(['doThing:with:', 'greet', 'shared']);
  5103. const shared = methods.find((m) => m.name === 'shared');
  5104. expect(shared?.isStatic).toBe(true);
  5105. const properties = result.nodes.filter((n) => n.kind === 'property');
  5106. expect(properties.some((p) => p.name === 'name')).toBe(true);
  5107. const functions = result.nodes.filter((n) => n.kind === 'function');
  5108. expect(functions.some((f) => f.name === 'helperFunction')).toBe(true);
  5109. const imports = result.nodes.filter((n) => n.kind === 'import').map((n) => n.name);
  5110. expect(imports).toContain('Foundation/Foundation.h');
  5111. expect(imports).toContain('MyClass.h');
  5112. });
  5113. it('should record inheritance and protocol conformance', () => {
  5114. const result = extractFromSource('App.m', sample);
  5115. const extendsRefs = result.unresolvedReferences.filter((r) => r.referenceKind === 'extends');
  5116. const implementsRefs = result.unresolvedReferences.filter((r) => r.referenceKind === 'implements');
  5117. expect(extendsRefs.map((r) => r.referenceName)).toContain('NSObject');
  5118. expect(implementsRefs.map((r) => r.referenceName)).toContain('NSCopying');
  5119. });
  5120. it('should record message sends and C calls', () => {
  5121. const result = extractFromSource('App.m', sample);
  5122. const calls = result.unresolvedReferences
  5123. .filter((r) => r.referenceKind === 'calls')
  5124. .map((r) => r.referenceName);
  5125. expect(calls).toEqual(expect.arrayContaining(['NSLog', 'doWork', 'MyClass.shared', 'obj.greet']));
  5126. });
  5127. it('should reconstruct multi-keyword selectors at the call site so they resolve to the method definition', () => {
  5128. // Regression for the gap discovered post-#165: message_expression's
  5129. // multi-keyword form `[obj a:1 b:2]` was only emitting the first keyword,
  5130. // so calls never resolved to multi-part method definitions like
  5131. // `GET:parameters:headers:progress:success:failure:`. The call-site name
  5132. // must match the method-definition name with full keywords + trailing colons.
  5133. const code = `
  5134. @implementation Caller
  5135. - (void)demo {
  5136. NSMutableDictionary *d = [NSMutableDictionary new];
  5137. [d setObject:@"v" forKey:@"k"];
  5138. [d setObject:@"v2" forKey:@"k2" withRetry:@YES];
  5139. [self touchesBegan:nil withEvent:nil];
  5140. }
  5141. @end
  5142. `;
  5143. const result = extractFromSource('Caller.m', code);
  5144. const calls = result.unresolvedReferences
  5145. .filter((r) => r.referenceKind === 'calls')
  5146. .map((r) => r.referenceName);
  5147. expect(calls).toEqual(
  5148. expect.arrayContaining([
  5149. 'd.setObject:forKey:',
  5150. 'd.setObject:forKey:withRetry:',
  5151. 'touchesBegan:withEvent:',
  5152. ])
  5153. );
  5154. });
  5155. it('should not classify pure C headers with @end in comments as objc', () => {
  5156. const cHeader = '/* @end of file */\n#ifndef STDIO_H\nvoid printf(const char *);\n#endif\n';
  5157. expect(detectLanguage('stdio.h', cHeader)).toBe('c');
  5158. });
  5159. it('should extract protocol declarations', () => {
  5160. const code = `
  5161. @protocol DataSource <NSObject>
  5162. - (NSInteger)numberOfItems;
  5163. @end
  5164. `;
  5165. const result = extractFromSource('DataSource.h', code);
  5166. const protocol = result.nodes.find((n) => n.kind === 'protocol' && n.name === 'DataSource');
  5167. expect(protocol).toBeDefined();
  5168. });
  5169. it('should report Objective-C as supported', () => {
  5170. expect(isLanguageSupported('objc')).toBe(true);
  5171. expect(getSupportedLanguages()).toContain('objc');
  5172. });
  5173. });
  5174. describe('Regression: issue-specific extraction fixes', () => {
  5175. it('indexes inner functions of an anonymous AMD/CommonJS module wrapper (#528)', () => {
  5176. const code = `
  5177. define(['dep'], function (dep) {
  5178. function innerHelper(x) { return x + 1; }
  5179. function compute(y) { return innerHelper(y); }
  5180. return { compute: compute };
  5181. });
  5182. `;
  5183. const result = extractFromSource('amd-module.js', code);
  5184. const fns = result.nodes.filter((n) => n.kind === 'function').map((n) => n.name);
  5185. expect(fns).toContain('innerHelper');
  5186. expect(fns).toContain('compute');
  5187. });
  5188. it('attaches Go methods on generic receivers to their type (#583)', () => {
  5189. const code = `
  5190. package main
  5191. type Stack[T any] struct { items []T }
  5192. func (s *Stack[T]) Push(v T) { s.items = append(s.items, v) }
  5193. func (s Stack[T]) Len() int { return len(s.items) }
  5194. `;
  5195. const result = extractFromSource('stack.go', code);
  5196. const methods = result.nodes.filter((n) => n.kind === 'method');
  5197. expect(methods.find((m) => m.name === 'Push')?.qualifiedName).toBe('Stack::Push');
  5198. expect(methods.find((m) => m.name === 'Len')?.qualifiedName).toBe('Stack::Len');
  5199. });
  5200. it('indexes new module extensions: .mts/.cts (TS) and .xsjs/.xsjslib (JS) (#366, #556)', () => {
  5201. expect(isSourceFile('mod.mts')).toBe(true);
  5202. expect(isSourceFile('mod.cts')).toBe(true);
  5203. expect(isSourceFile('service.xsjs')).toBe(true);
  5204. expect(isSourceFile('lib.xsjslib')).toBe(true);
  5205. expect(detectLanguage('mod.mts')).toBe('typescript');
  5206. expect(detectLanguage('service.xsjs')).toBe('javascript');
  5207. // End-to-end: a .mts file is parsed as TS, a .xsjs file as JS.
  5208. const ts = extractFromSource('mod.mts', 'export function hello(): number { return 1; }');
  5209. expect(ts.nodes.find((n) => n.name === 'hello' && n.kind === 'function')).toBeDefined();
  5210. const js = extractFromSource('service.xsjs', 'function handleRequest() { return 1; }');
  5211. expect(js.nodes.find((n) => n.name === 'handleRequest' && n.kind === 'function')).toBeDefined();
  5212. });
  5213. });
  5214. describe('Import / re-export dependency linking (blast-radius recall)', () => {
  5215. // An import IS a dependency, but extraction only emits references for calls,
  5216. // instantiations, type annotations, and inheritance — so a symbol imported and
  5217. // then merely re-exported, placed in a registry array, passed as an argument,
  5218. // or used in JSX produced no cross-file edge, leaving the providing file with a
  5219. // false "0 dependents". These tests pin the import/re-export binding linking.
  5220. it('emits an imports reference per named, aliased, and default import binding', () => {
  5221. const code = `
  5222. import { widget, helper as h } from './foo';
  5223. import Thing from './thing';
  5224. import * as NS from './ns';
  5225. export const registry = [widget];
  5226. `;
  5227. const result = extractFromSource('bar.ts', code);
  5228. const names = result.unresolvedReferences
  5229. .filter((r) => r.referenceKind === 'imports')
  5230. .map((r) => r.referenceName);
  5231. expect(names).toContain('widget'); // named import → local name
  5232. expect(names).toContain('h'); // aliased import → local alias
  5233. expect(names).toContain('Thing'); // default import
  5234. expect(names).toContain('NS'); // namespace import → linked to the module file as a dependency
  5235. });
  5236. it('emits an imports reference per re-exported binding', () => {
  5237. const result = extractFromSource('barrel.ts', `export { alpha, beta as b } from './source';`);
  5238. const names = result.unresolvedReferences
  5239. .filter((r) => r.referenceKind === 'imports')
  5240. .map((r) => r.referenceName);
  5241. // Re-export links the SOURCE-side name, not the local alias.
  5242. expect(names).toContain('alpha');
  5243. expect(names).toContain('beta');
  5244. });
  5245. it('a value imported/re-exported but never called still makes the importer a dependent', async () => {
  5246. const dir = createTempDir();
  5247. try {
  5248. fs.mkdirSync(path.join(dir, 'src'), { recursive: true });
  5249. fs.writeFileSync(
  5250. path.join(dir, 'src', 'foo.ts'),
  5251. `export const widget = { n: 1 };\nexport function helper(): void {}\n`
  5252. );
  5253. // bar uses widget ONLY in an array and re-exports helper — neither is
  5254. // called/typed, so before import-linking bar had no edge to foo at all.
  5255. fs.writeFileSync(
  5256. path.join(dir, 'src', 'bar.ts'),
  5257. `import { widget } from './foo';\nexport { helper } from './foo';\nexport const registry = [widget];\n`
  5258. );
  5259. const cg = CodeGraph.initSync(dir, { config: { include: ['src/**/*.ts'], exclude: [] } });
  5260. await cg.indexAll();
  5261. cg.resolveReferences();
  5262. expect(cg.getFileDependents('src/foo.ts')).toContain('src/bar.ts');
  5263. cg.destroy();
  5264. } finally {
  5265. cleanupTempDir(dir);
  5266. }
  5267. });
  5268. it('a namespace import touched only via a value-member read still links the module file', async () => {
  5269. const dir = createTempDir();
  5270. try {
  5271. fs.mkdirSync(path.join(dir, 'src'), { recursive: true });
  5272. fs.writeFileSync(path.join(dir, 'src', 'foo.ts'), `export const SOME_CONST = 42;\n`);
  5273. // `foo` is imported as a namespace and used ONLY via a value-member read
  5274. // (no call, no type) — `foo.helper()` would link on its own, but a bare
  5275. // `foo.SOME_CONST` would not, so the module-import backstop must link it.
  5276. fs.writeFileSync(path.join(dir, 'src', 'bar.ts'), `import * as foo from './foo';\nexport const x = foo.SOME_CONST;\n`);
  5277. const cg = CodeGraph.initSync(dir, { config: { include: ['src/**/*.ts'], exclude: [] } });
  5278. await cg.indexAll();
  5279. cg.resolveReferences();
  5280. expect(cg.getFileDependents('src/foo.ts')).toContain('src/bar.ts');
  5281. cg.destroy();
  5282. } finally {
  5283. cleanupTempDir(dir);
  5284. }
  5285. });
  5286. });
  5287. describe('Python import dependency linking (blast-radius recall)', () => {
  5288. // Same recall gap as TS: Python only linked called/instantiated imports, so a
  5289. // name brought in with `from module import X` and then merely stored, used as
  5290. // a decorator/argument, or re-exported through an `__init__.py` produced no
  5291. // cross-file edge — the providing module showed a false "0 dependents".
  5292. it('emits an imports reference per name in a `from module import ...` (incl. value/aliased)', () => {
  5293. const code = [
  5294. 'from foo import helper, widget',
  5295. 'from foo import Thing as T',
  5296. 'from . import sibling',
  5297. 'from bar import *',
  5298. ].join('\n');
  5299. const names = extractFromSource('mod.py', code)
  5300. .unresolvedReferences.filter((r) => r.referenceKind === 'imports')
  5301. .map((r) => r.referenceName);
  5302. expect(names).toContain('helper');
  5303. expect(names).toContain('widget'); // value import
  5304. expect(names).toContain('T'); // aliased import → local name
  5305. expect(names).toContain('sibling'); // `from . import <name>`
  5306. expect(names).not.toContain('*'); // wildcard import has no names
  5307. });
  5308. it('a Python value imported but never called still makes the importer a dependent', async () => {
  5309. const dir = createTempDir();
  5310. try {
  5311. fs.mkdirSync(path.join(dir, 'pkg'), { recursive: true });
  5312. fs.writeFileSync(path.join(dir, 'pkg', 'foo.py'), `widget = {"n": 1}\ndef helper():\n return 1\n`);
  5313. // bar imports widget+helper but only stores widget in a list — nothing is
  5314. // called, so before import-linking bar had no edge to foo.
  5315. fs.writeFileSync(path.join(dir, 'pkg', 'bar.py'), `from foo import widget, helper\nregistry = [widget]\n`);
  5316. const cg = CodeGraph.initSync(dir, { config: { include: ['pkg/**/*.py'], exclude: [] } });
  5317. await cg.indexAll();
  5318. cg.resolveReferences();
  5319. expect(cg.getFileDependents('pkg/foo.py')).toContain('pkg/bar.py');
  5320. cg.destroy();
  5321. } finally {
  5322. cleanupTempDir(dir);
  5323. }
  5324. });
  5325. it('resolves `from . import submodule` + `submodule.func()` to the submodule', async () => {
  5326. const dir = createTempDir();
  5327. try {
  5328. fs.mkdirSync(path.join(dir, 'pkg'), { recursive: true });
  5329. fs.writeFileSync(path.join(dir, 'pkg', '__init__.py'), '');
  5330. fs.writeFileSync(path.join(dir, 'pkg', 'certs.py'), `def where():\n return "/ca.pem"\n`);
  5331. // certs is an imported MODULE (a file), and certs.where() is a qualified
  5332. // call through it — the receiver isn't a symbol, so plain name-matching
  5333. // can't link it. Also exercises the Python relative-dot path fix (`.certs`).
  5334. fs.writeFileSync(path.join(dir, 'pkg', 'utils.py'), `from . import certs\ndef go():\n return certs.where()\n`);
  5335. const cg = CodeGraph.initSync(dir, { config: { include: ['pkg/**/*.py'], exclude: [] } });
  5336. await cg.indexAll();
  5337. cg.resolveReferences();
  5338. expect(cg.getFileDependents('pkg/certs.py')).toContain('pkg/utils.py');
  5339. cg.destroy();
  5340. } finally {
  5341. cleanupTempDir(dir);
  5342. }
  5343. });
  5344. it('a module import is a dependency even when the used member is re-exported elsewhere', async () => {
  5345. const dir = createTempDir();
  5346. try {
  5347. fs.mkdirSync(path.join(dir, 'pkg'), { recursive: true });
  5348. fs.writeFileSync(path.join(dir, 'pkg', '__init__.py'), '');
  5349. // `where` is NOT defined in certs.py (re-exported from a 3rd-party pkg), so
  5350. // member resolution can't find it — the module-import backstop must still
  5351. // record utils -> certs. (Mirrors requests' real `certs.where`.)
  5352. fs.writeFileSync(path.join(dir, 'pkg', 'certs.py'), `from external_ca import where\n`);
  5353. fs.writeFileSync(path.join(dir, 'pkg', 'utils.py'), `from . import certs\nCA = certs.where()\n`);
  5354. const cg = CodeGraph.initSync(dir, { config: { include: ['pkg/**/*.py'], exclude: [] } });
  5355. await cg.indexAll();
  5356. cg.resolveReferences();
  5357. expect(cg.getFileDependents('pkg/certs.py')).toContain('pkg/utils.py');
  5358. cg.destroy();
  5359. } finally {
  5360. cleanupTempDir(dir);
  5361. }
  5362. });
  5363. });
  5364. describe('Go cross-package composite literals (blast-radius recall)', () => {
  5365. // Go function calls and type references across packages already resolved, but
  5366. // struct composite literals — `render.XML{...}` / `pkga.Widget{...}` — were not
  5367. // extracted at all, so a package whose types are only INSTANTIATED elsewhere
  5368. // (gin's render/binding implementations) showed 0 dependents.
  5369. it('links a cross-package struct composite literal to the defining package', async () => {
  5370. const dir = createTempDir();
  5371. try {
  5372. fs.writeFileSync(path.join(dir, 'go.mod'), 'module example.com/proj\n\ngo 1.21\n');
  5373. fs.mkdirSync(path.join(dir, 'render'), { recursive: true });
  5374. fs.writeFileSync(path.join(dir, 'render', 'xml.go'), `package render\n\ntype XML struct { Data any }\n`);
  5375. fs.writeFileSync(path.join(dir, 'app.go'), `package main\n\nimport "example.com/proj/render"\n\nfunc handle() any { return render.XML{} }\n`);
  5376. const cg = CodeGraph.initSync(dir, { config: { include: ['**/*.go'], exclude: [] } });
  5377. await cg.indexAll();
  5378. cg.resolveReferences();
  5379. expect(cg.getFileDependents('render/xml.go')).toContain('app.go');
  5380. cg.destroy();
  5381. } finally {
  5382. cleanupTempDir(dir);
  5383. }
  5384. });
  5385. it('links a composite literal in a package-level var registry', async () => {
  5386. const dir = createTempDir();
  5387. try {
  5388. fs.writeFileSync(path.join(dir, 'go.mod'), 'module example.com/proj\n\ngo 1.21\n');
  5389. fs.mkdirSync(path.join(dir, 'render'), { recursive: true });
  5390. fs.writeFileSync(path.join(dir, 'render', 'xml.go'), `package render\n\ntype XML struct {}\nfunc (XML) Render() {}\n`);
  5391. // The implementation is registered only in a top-level `var registry = {...}`
  5392. // map literal — the body walker doesn't cover top-level declarations, so this
  5393. // exercises the var-initializer walking added for Go.
  5394. 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`);
  5395. const cg = CodeGraph.initSync(dir, { config: { include: ['**/*.go'], exclude: [] } });
  5396. await cg.indexAll();
  5397. cg.resolveReferences();
  5398. expect(cg.getFileDependents('render/xml.go')).toContain('reg.go');
  5399. cg.destroy();
  5400. } finally {
  5401. cleanupTempDir(dir);
  5402. }
  5403. });
  5404. it('links a parenthesized pointer type conversion `(*T)(x)` to the type', async () => {
  5405. const dir = createTempDir();
  5406. try {
  5407. fs.writeFileSync(path.join(dir, 'go.mod'), 'module example.com/proj\n\ngo 1.21\n');
  5408. fs.writeFileSync(path.join(dir, 'types.go'), `package main\n\ntype Wrapped struct { N int }\n`);
  5409. // `(*Wrapped)(x)` parses as a call whose callee is the parenthesized type
  5410. // `(*Wrapped)` — without normalization it dropped on the floor.
  5411. fs.writeFileSync(path.join(dir, 'use.go'), `package main\n\nfunc run(x *int) { _ = (*Wrapped)(x) }\n`);
  5412. const cg = CodeGraph.initSync(dir, { config: { include: ['**/*.go'], exclude: [] } });
  5413. await cg.indexAll();
  5414. cg.resolveReferences();
  5415. expect(cg.getFileDependents('types.go')).toContain('use.go');
  5416. cg.destroy();
  5417. } finally {
  5418. cleanupTempDir(dir);
  5419. }
  5420. });
  5421. it('links an implementation reached only through a Go interface (implicit satisfaction, #584)', async () => {
  5422. const dir = createTempDir();
  5423. try {
  5424. fs.writeFileSync(path.join(dir, 'go.mod'), 'module example.com/proj\n\ngo 1.21\n');
  5425. fs.mkdirSync(path.join(dir, 'codec'), { recursive: true });
  5426. 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`);
  5427. // jsonApi satisfies Core structurally (no `implements` keyword) and is
  5428. // reached ONLY through the interface (API.Marshal). Without implicit
  5429. // interface satisfaction + dispatch, json.go shows 0 dependents.
  5430. 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`);
  5431. const cg = CodeGraph.initSync(dir, { config: { include: ['**/*.go'], exclude: [] } });
  5432. await cg.indexAll();
  5433. cg.resolveReferences();
  5434. expect(cg.getFileDependents('codec/json.go')).toContain('codec/api.go');
  5435. cg.destroy();
  5436. } finally {
  5437. cleanupTempDir(dir);
  5438. }
  5439. });
  5440. });
  5441. describe('C# records (blast-radius recall)', () => {
  5442. // Records are ubiquitous in modern C# (DTOs, value objects, CQRS messages),
  5443. // but `record` / `record struct` declarations weren't extracted as types — so
  5444. // every reference, generic-type-argument, and `new` of a record dropped on the
  5445. // floor and the defining file showed 0 dependents. (#237)
  5446. it('extracts a record as a graph node (record class + record struct)', () => {
  5447. const r = extractFromSource('r.cs', `namespace P;\npublic record Box(int N);\npublic record struct Pt(int X);\n`);
  5448. expect(r.nodes.find((n) => n.name === 'Box' && (n.kind === 'class' || n.kind === 'struct'))).toBeDefined();
  5449. expect(r.nodes.find((n) => n.name === 'Pt' && (n.kind === 'class' || n.kind === 'struct'))).toBeDefined();
  5450. });
  5451. it('resolves references / instantiations of a record across files', async () => {
  5452. const dir = createTempDir();
  5453. try {
  5454. fs.writeFileSync(path.join(dir, 'types.cs'), `namespace P;\npublic record Box(int N);\n`);
  5455. // Box is used as a generic type argument and instantiated — both require
  5456. // Box to be a node to resolve.
  5457. fs.writeFileSync(
  5458. path.join(dir, 'use.cs'),
  5459. `using System.Collections.Generic;\nnamespace P;\npublic class User {\n public IEnumerable<Box> Boxes { get; }\n public Box Make() => new Box(1);\n}\n`
  5460. );
  5461. const cg = CodeGraph.initSync(dir, { config: { include: ['**/*.cs'], exclude: [] } });
  5462. await cg.indexAll();
  5463. cg.resolveReferences();
  5464. expect(cg.getFileDependents('types.cs')).toContain('use.cs');
  5465. cg.destroy();
  5466. } finally {
  5467. cleanupTempDir(dir);
  5468. }
  5469. });
  5470. });
  5471. describe('Rust cross-module recall', () => {
  5472. function rustProject(files: Record<string, string>): string {
  5473. const dir = createTempDir();
  5474. fs.writeFileSync(path.join(dir, 'Cargo.toml'), '[package]\nname = "proj"\nversion = "0.1.0"\nedition = "2021"\n');
  5475. fs.mkdirSync(path.join(dir, 'src'), { recursive: true });
  5476. for (const [rel, content] of Object.entries(files)) {
  5477. const full = path.join(dir, 'src', rel);
  5478. fs.mkdirSync(path.dirname(full), { recursive: true });
  5479. fs.writeFileSync(full, content);
  5480. }
  5481. return dir;
  5482. }
  5483. it('extracts a struct literal `Foo { .. }` as an instantiation across modules', async () => {
  5484. const dir = rustProject({
  5485. 'lib.rs': 'pub mod types;\npub mod consumer;\n',
  5486. 'types.rs': 'pub struct Widget { pub n: i32 }\n',
  5487. 'consumer.rs': 'use crate::types::Widget;\npub fn build() -> Widget { Widget { n: 1 } }\n',
  5488. });
  5489. try {
  5490. const cg = CodeGraph.initSync(dir, { config: { include: ['src/**/*.rs'], exclude: [] } });
  5491. await cg.indexAll();
  5492. cg.resolveReferences();
  5493. expect(cg.getFileDependents('src/types.rs')).toContain('src/consumer.rs');
  5494. cg.destroy();
  5495. } finally { cleanupTempDir(dir); }
  5496. });
  5497. it('extracts trait method declarations and bridges trait dispatch to the impl', async () => {
  5498. const dir = rustProject({
  5499. 'lib.rs': 'pub mod types;\npub mod consumer;\n',
  5500. 'types.rs': 'pub trait Render { fn render(&self) -> i32; }\n',
  5501. // Mine implements Render structurally; reached via &dyn Render dispatch.
  5502. 'consumer.rs': 'use crate::types::Render;\npub struct Mine { pub x: i32 }\nimpl Render for Mine { fn render(&self) -> i32 { self.x } }\n',
  5503. });
  5504. try {
  5505. const cg = CodeGraph.initSync(dir, { config: { include: ['src/**/*.rs'], exclude: [] } });
  5506. await cg.indexAll();
  5507. cg.resolveReferences();
  5508. // implements edge (Mine -> Render) makes types.rs a dependent of consumer.rs's struct.
  5509. expect(cg.getFileDependents('src/types.rs')).toContain('src/consumer.rs');
  5510. cg.destroy();
  5511. } finally { cleanupTempDir(dir); }
  5512. });
  5513. it('links `pub use` re-export hubs to the modules they re-export', async () => {
  5514. const dir = rustProject({
  5515. 'lib.rs': 'pub mod api;\n',
  5516. 'api/mod.rs': 'mod widget;\npub use self::widget::Widget;\n',
  5517. 'api/widget.rs': 'pub struct Widget { pub n: i32 }\n',
  5518. });
  5519. try {
  5520. const cg = CodeGraph.initSync(dir, { config: { include: ['src/**/*.rs'], exclude: [] } });
  5521. await cg.indexAll();
  5522. cg.resolveReferences();
  5523. // The re-export hub depends on the module it re-exports from.
  5524. expect(cg.getFileDependents('src/api/widget.rs')).toContain('src/api/mod.rs');
  5525. cg.destroy();
  5526. } finally { cleanupTempDir(dir); }
  5527. });
  5528. it('resolves a qualified path to the correct module when the leaf name collides', async () => {
  5529. const dir = rustProject({
  5530. 'lib.rs': 'pub mod fast;\npub mod slow;\npub mod hub;\n',
  5531. 'fast.rs': 'pub fn read() -> i32 { 1 }\n',
  5532. 'slow.rs': 'pub fn read() -> i32 { 2 }\n',
  5533. // `read` exists in BOTH fast.rs and slow.rs — module-path resolution must
  5534. // send this re-export to fast.rs specifically, not name-match either.
  5535. 'hub.rs': 'pub use crate::fast::read;\n',
  5536. });
  5537. try {
  5538. const cg = CodeGraph.initSync(dir, { config: { include: ['src/**/*.rs'], exclude: [] } });
  5539. await cg.indexAll();
  5540. cg.resolveReferences();
  5541. expect(cg.getFileDependents('src/fast.rs')).toContain('src/hub.rs');
  5542. expect(cg.getFileDependents('src/slow.rs')).not.toContain('src/hub.rs');
  5543. cg.destroy();
  5544. } finally { cleanupTempDir(dir); }
  5545. });
  5546. });
  5547. describe('Java annotations (blast-radius recall)', () => {
  5548. it('indexes @interface definitions and links @Annotation usages to them', async () => {
  5549. const dir = createTempDir();
  5550. try {
  5551. fs.mkdirSync(path.join(dir, 'p'), { recursive: true });
  5552. // The annotation DEFINITION must be a node, and the @MyAnno usages (which
  5553. // live inside a `modifiers` node on the class/field/method) must extract.
  5554. fs.writeFileSync(path.join(dir, 'p', 'MyAnno.java'), `package p;\npublic @interface MyAnno { String value() default ""; }\n`);
  5555. fs.writeFileSync(
  5556. path.join(dir, 'p', 'User.java'),
  5557. `package p;\n@MyAnno("c")\npublic class User {\n @MyAnno("f") int field;\n @MyAnno("m") void go() {}\n}\n`
  5558. );
  5559. const cg = CodeGraph.initSync(dir, { config: { include: ['**/*.java'], exclude: [] } });
  5560. await cg.indexAll();
  5561. cg.resolveReferences();
  5562. expect(cg.getFileDependents('p/MyAnno.java')).toContain('p/User.java');
  5563. cg.destroy();
  5564. } finally { cleanupTempDir(dir); }
  5565. });
  5566. });
  5567. describe('Swift property wrappers / attributes (blast-radius recall)', () => {
  5568. it('links a @propertyWrapper usage to the wrapper type', async () => {
  5569. const dir = createTempDir();
  5570. try {
  5571. fs.mkdirSync(path.join(dir, 'Sources', 'M'), { recursive: true });
  5572. fs.writeFileSync(path.join(dir, 'Sources', 'M', 'Wrap.swift'), `@propertyWrapper\npublic struct Argument<T> { public var wrappedValue: T }\n`);
  5573. // `@Argument` is a Swift attribute on a stored property — it lives in the
  5574. // property's `modifiers` and Swift doesn't extract instance properties as
  5575. // their own nodes, so without the fix the wrapper type has no users.
  5576. fs.writeFileSync(path.join(dir, 'Sources', 'M', 'Cmd.swift'), `public struct MyCommand {\n @Argument var name: String\n @Argument var count: Int\n}\n`);
  5577. const cg = CodeGraph.initSync(dir, { config: { include: ['Sources/**/*.swift'], exclude: [] } });
  5578. await cg.indexAll();
  5579. cg.resolveReferences();
  5580. expect(cg.getFileDependents('Sources/M/Wrap.swift')).toContain('Sources/M/Cmd.swift');
  5581. cg.destroy();
  5582. } finally { cleanupTempDir(dir); }
  5583. });
  5584. });