extraction.test.ts 238 KB

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