node.js 1.2 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785
  1. import { a as __toCommonJS, i as __require, n as __esmMin, o as __toESM, r as __exportAll, t as __commonJSMin } from "./chunk.js";
  2. import { A as OPTIMIZABLE_ENTRY_RE, C as ERR_FILE_NOT_FOUND_IN_OPTIMIZED_DEP_DIR, D as JS_TYPES_RE, E as FS_PREFIX, F as defaultAllowedOrigins, I as loopbackHosts, L as wildcardHosts, M as SPECIAL_QUERY_RE, N as VERSION, O as KNOWN_ASSET_TYPES, P as VITE_PACKAGE_DIR, R as require_picocolors, S as ENV_PUBLIC_PATH, T as ESBUILD_BASELINE_WIDELY_AVAILABLE_TARGET, _ as DEFAULT_SERVER_CONDITIONS, a as CLIENT_ENTRY, b as DEV_PROD_CONDITION, c as DEFAULT_ASSETS_INLINE_LIMIT, d as DEFAULT_CLIENT_MAIN_FIELDS, f as DEFAULT_CONFIG_FILES, g as DEFAULT_PREVIEW_PORT, h as DEFAULT_EXTERNAL_CONDITIONS, i as CLIENT_DIR, j as ROLLUP_HOOKS, k as METADATA_FILENAME, l as DEFAULT_ASSETS_RE, m as DEFAULT_EXTENSIONS, n as createLogger, o as CLIENT_PUBLIC_PATH, p as DEFAULT_DEV_PORT, r as printServerUrls, s as CSS_LANGS_RE, t as LogLevels, u as DEFAULT_CLIENT_CONDITIONS, v as DEFAULT_SERVER_MAIN_FIELDS, w as ERR_OPTIMIZE_DEPS_PROCESSING_ERROR, x as ENV_ENTRY, y as DEP_VERSION_RE } from "./logger.js";
  3. import { builtinModules, createRequire } from "node:module";
  4. import { parseAst, parseAstAsync } from "rolldown/parseAst";
  5. import { esmExternalRequirePlugin, esmExternalRequirePlugin as esmExternalRequirePlugin$1 } from "rolldown/plugins";
  6. import { TsconfigCache, Visitor, minify, minifySync, parse, parseSync, transformSync } from "rolldown/utils";
  7. import * as fs$1 from "node:fs";
  8. import fs, { existsSync, readFileSync } from "node:fs";
  9. import path, { basename, dirname, extname, isAbsolute, join, normalize, posix, relative, resolve, sep } from "node:path";
  10. import fsp, { constants } from "node:fs/promises";
  11. import { URL as URL$1, fileURLToPath, pathToFileURL } from "node:url";
  12. import { format, formatWithOptions, inspect, parseEnv, promisify, stripVTControlCharacters } from "node:util";
  13. import { performance as performance$1 } from "node:perf_hooks";
  14. import crypto, { randomUUID } from "node:crypto";
  15. import picomatch from "picomatch";
  16. import { VERSION as rolldownVersion, rolldown } from "rolldown";
  17. import os from "node:os";
  18. import net from "node:net";
  19. import childProcess, { exec, execFile, execSync } from "node:child_process";
  20. import { promises } from "node:dns";
  21. import { isatty } from "node:tty";
  22. import path$1, { isAbsolute as isAbsolute$1, join as join$1, posix as posix$1, resolve as resolve$1, win32 } from "path";
  23. import { exactRegex, makeIdFiltersToMatchWithQuery, prefixRegex, withFilter } from "rolldown/filter";
  24. import { dev, oxcRuntimePlugin, resolveTsconfig, scan, viteAliasPlugin, viteBuildImportAnalysisPlugin, viteDynamicImportVarsPlugin, viteImportGlobPlugin, viteJsonPlugin, viteLoadFallbackPlugin, viteManifestPlugin, viteModulePreloadPolyfillPlugin, viteReporterPlugin, viteResolvePlugin, viteTransformPlugin, viteWasmFallbackPlugin, viteWebWorkerPostPlugin } from "rolldown/experimental";
  25. import readline from "node:readline";
  26. import { MessageChannel, Worker } from "node:worker_threads";
  27. import isModuleSyncConditionEnabled from "#module-sync-enabled";
  28. import assert from "node:assert";
  29. import process$1 from "node:process";
  30. import v8 from "node:v8";
  31. import { escapePath, glob, globSync, isDynamicPattern } from "tinyglobby";
  32. import { EventEmitter } from "node:events";
  33. import { STATUS_CODES, createServer, get } from "node:http";
  34. import { createServer as createServer$1, get as get$1 } from "node:https";
  35. import { readdirSync, statSync } from "fs";
  36. import { ESModulesEvaluator, ModuleRunner, createNodeImportMeta } from "vite/module-runner";
  37. import { Buffer as Buffer$1 } from "node:buffer";
  38. import zlib from "zlib";
  39. import { setTimeout as setTimeout$1 } from "node:timers/promises";
  40. import * as qs from "node:querystring";
  41. //#region src/shared/constants.ts
  42. /**
  43. * Prefix for resolved Ids that are not valid browser import specifiers
  44. */
  45. const VALID_ID_PREFIX = `/@id/`;
  46. /**
  47. * Plugins that use 'virtual modules' (e.g. for helper functions), prefix the
  48. * module ID with `\0`, a convention from the rollup ecosystem.
  49. * This prevents other plugins from trying to process the id (like node resolution),
  50. * and core features like sourcemaps can use this info to differentiate between
  51. * virtual modules and regular files.
  52. * `\0` is not a permitted char in import URLs so we have to replace them during
  53. * import analysis. The id will be decoded back before entering the plugins pipeline.
  54. * These encoded virtual ids are also prefixed by the VALID_ID_PREFIX, so virtual
  55. * modules in the browser end up encoded as `/@id/__x00__{id}`
  56. */
  57. const NULL_BYTE_PLACEHOLDER = `__x00__`;
  58. let SOURCEMAPPING_URL = "sourceMa";
  59. SOURCEMAPPING_URL += "ppingURL";
  60. const MODULE_RUNNER_SOURCEMAPPING_SOURCE = "//# sourceMappingSource=vite-generated";
  61. const ERR_OUTDATED_OPTIMIZED_DEP = "ERR_OUTDATED_OPTIMIZED_DEP";
  62. //#endregion
  63. //#region src/shared/utils.ts
  64. const isWindows = typeof process !== "undefined" && process.platform === "win32";
  65. /**
  66. * Prepend `/@id/` and replace null byte so the id is URL-safe.
  67. * This is prepended to resolved ids that are not valid browser
  68. * import specifiers by the importAnalysis plugin.
  69. */
  70. function wrapId(id) {
  71. return id.startsWith(VALID_ID_PREFIX) ? id : VALID_ID_PREFIX + id.replace("\0", NULL_BYTE_PLACEHOLDER);
  72. }
  73. /**
  74. * Undo {@link wrapId}'s `/@id/` and null byte replacements.
  75. */
  76. function unwrapId(id) {
  77. return id.startsWith(VALID_ID_PREFIX) ? id.slice(VALID_ID_PREFIX.length).replace(NULL_BYTE_PLACEHOLDER, "\0") : id;
  78. }
  79. const windowsSlashRE = /\\/g;
  80. function slash(p) {
  81. return p.replace(windowsSlashRE, "/");
  82. }
  83. const postfixRE = /[?#].*$/;
  84. function cleanUrl(url) {
  85. return url.replace(postfixRE, "");
  86. }
  87. function splitFileAndPostfix(path) {
  88. const file = cleanUrl(path);
  89. return {
  90. file,
  91. postfix: path.slice(file.length)
  92. };
  93. }
  94. function withTrailingSlash(path) {
  95. if (path[path.length - 1] !== "/") return `${path}/`;
  96. return path;
  97. }
  98. function promiseWithResolvers() {
  99. let resolve;
  100. let reject;
  101. return {
  102. promise: new Promise((_resolve, _reject) => {
  103. resolve = _resolve;
  104. reject = _reject;
  105. }),
  106. resolve,
  107. reject
  108. };
  109. }
  110. //#endregion
  111. //#region src/module-runner/importMetaResolver.ts
  112. const customizationHookNamespace = "vite-module-runner:import-meta-resolve/v1/";
  113. const customizationHooksModule = `
  114. export async function resolve(specifier, context, nextResolve) {
  115. if (specifier.startsWith(${JSON.stringify(customizationHookNamespace)})) {
  116. const data = specifier.slice(${JSON.stringify(customizationHookNamespace)}.length)
  117. const [parsedSpecifier, parsedImporter] = JSON.parse(data)
  118. specifier = parsedSpecifier
  119. context.parentURL = parsedImporter
  120. }
  121. return nextResolve(specifier, context)
  122. }
  123. `;
  124. function customizationHookResolve(specifier, context, nextResolve) {
  125. if (specifier.startsWith(customizationHookNamespace)) {
  126. const data = specifier.slice(42);
  127. const [parsedSpecifier, parsedImporter] = JSON.parse(data);
  128. specifier = parsedSpecifier;
  129. context.parentURL = parsedImporter;
  130. }
  131. return nextResolve(specifier, context);
  132. }
  133. let isHookRegistered = false;
  134. function createImportMetaResolver() {
  135. if (isHookRegistered) return importMetaResolveWithCustomHook;
  136. let module;
  137. try {
  138. module = typeof process !== "undefined" ? process.getBuiltinModule("node:module").Module : void 0;
  139. } catch {
  140. return;
  141. }
  142. if (!module) return;
  143. if (module.registerHooks) {
  144. module.registerHooks({ resolve: customizationHookResolve });
  145. isHookRegistered = true;
  146. return importMetaResolveWithCustomHook;
  147. }
  148. if (!module.register) return;
  149. try {
  150. const hookModuleContent = `data:text/javascript,${encodeURI(customizationHooksModule)}`;
  151. module.register(hookModuleContent);
  152. } catch (e) {
  153. if ("code" in e && e.code === "ERR_NETWORK_IMPORT_DISALLOWED") return;
  154. throw e;
  155. }
  156. isHookRegistered = true;
  157. return importMetaResolveWithCustomHook;
  158. }
  159. function importMetaResolveWithCustomHook(specifier, importer) {
  160. return import.meta.resolve(`${customizationHookNamespace}${JSON.stringify([specifier, importer])}`);
  161. }
  162. const importMetaResolveWithCustomHookString = `
  163. (() => {
  164. const resolve = 'resolve'
  165. return (specifier, importer) =>
  166. import.meta[resolve](
  167. \`${customizationHookNamespace}\${JSON.stringify([specifier, importer])}\`,
  168. )
  169. })()
  170. `;
  171. //#endregion
  172. //#region ../../node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.5/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs
  173. var comma$1 = ",".charCodeAt(0);
  174. var semicolon = ";".charCodeAt(0);
  175. var chars$1 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  176. var intToChar$1 = new Uint8Array(64);
  177. var charToInt$1 = new Uint8Array(128);
  178. for (let i = 0; i < chars$1.length; i++) {
  179. const c = chars$1.charCodeAt(i);
  180. intToChar$1[i] = c;
  181. charToInt$1[c] = i;
  182. }
  183. function decodeInteger$1(reader, relative) {
  184. let value = 0;
  185. let shift = 0;
  186. let integer = 0;
  187. do {
  188. integer = charToInt$1[reader.next()];
  189. value |= (integer & 31) << shift;
  190. shift += 5;
  191. } while (integer & 32);
  192. const shouldNegate = value & 1;
  193. value >>>= 1;
  194. if (shouldNegate) value = -2147483648 | -value;
  195. return relative + value;
  196. }
  197. function encodeInteger(builder, num, relative) {
  198. let delta = num - relative;
  199. delta = delta < 0 ? -delta << 1 | 1 : delta << 1;
  200. do {
  201. let clamped = delta & 31;
  202. delta >>>= 5;
  203. if (delta > 0) clamped |= 32;
  204. builder.write(intToChar$1[clamped]);
  205. } while (delta > 0);
  206. return num;
  207. }
  208. function hasMoreVlq$1(reader, max) {
  209. if (reader.pos >= max) return false;
  210. return reader.peek() !== comma$1;
  211. }
  212. var bufLength = 1024 * 16;
  213. var td = typeof TextDecoder !== "undefined" ? /* @__PURE__ */ new TextDecoder() : typeof Buffer !== "undefined" ? { decode(buf) {
  214. return Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength).toString();
  215. } } : { decode(buf) {
  216. let out = "";
  217. for (let i = 0; i < buf.length; i++) out += String.fromCharCode(buf[i]);
  218. return out;
  219. } };
  220. var StringWriter = class {
  221. constructor() {
  222. this.pos = 0;
  223. this.out = "";
  224. this.buffer = new Uint8Array(bufLength);
  225. }
  226. write(v) {
  227. const { buffer } = this;
  228. buffer[this.pos++] = v;
  229. if (this.pos === bufLength) {
  230. this.out += td.decode(buffer);
  231. this.pos = 0;
  232. }
  233. }
  234. flush() {
  235. const { buffer, out, pos } = this;
  236. return pos > 0 ? out + td.decode(buffer.subarray(0, pos)) : out;
  237. }
  238. };
  239. var StringReader$1 = class {
  240. constructor(buffer) {
  241. this.pos = 0;
  242. this.buffer = buffer;
  243. }
  244. next() {
  245. return this.buffer.charCodeAt(this.pos++);
  246. }
  247. peek() {
  248. return this.buffer.charCodeAt(this.pos);
  249. }
  250. indexOf(char) {
  251. const { buffer, pos } = this;
  252. const idx = buffer.indexOf(char, pos);
  253. return idx === -1 ? buffer.length : idx;
  254. }
  255. };
  256. function decode$1(mappings) {
  257. const { length } = mappings;
  258. const reader = new StringReader$1(mappings);
  259. const decoded = [];
  260. let genColumn = 0;
  261. let sourcesIndex = 0;
  262. let sourceLine = 0;
  263. let sourceColumn = 0;
  264. let namesIndex = 0;
  265. do {
  266. const semi = reader.indexOf(";");
  267. const line = [];
  268. let sorted = true;
  269. let lastCol = 0;
  270. genColumn = 0;
  271. while (reader.pos < semi) {
  272. let seg;
  273. genColumn = decodeInteger$1(reader, genColumn);
  274. if (genColumn < lastCol) sorted = false;
  275. lastCol = genColumn;
  276. if (hasMoreVlq$1(reader, semi)) {
  277. sourcesIndex = decodeInteger$1(reader, sourcesIndex);
  278. sourceLine = decodeInteger$1(reader, sourceLine);
  279. sourceColumn = decodeInteger$1(reader, sourceColumn);
  280. if (hasMoreVlq$1(reader, semi)) {
  281. namesIndex = decodeInteger$1(reader, namesIndex);
  282. seg = [
  283. genColumn,
  284. sourcesIndex,
  285. sourceLine,
  286. sourceColumn,
  287. namesIndex
  288. ];
  289. } else seg = [
  290. genColumn,
  291. sourcesIndex,
  292. sourceLine,
  293. sourceColumn
  294. ];
  295. } else seg = [genColumn];
  296. line.push(seg);
  297. reader.pos++;
  298. }
  299. if (!sorted) sort$1(line);
  300. decoded.push(line);
  301. reader.pos = semi + 1;
  302. } while (reader.pos <= length);
  303. return decoded;
  304. }
  305. function sort$1(line) {
  306. line.sort(sortComparator$2);
  307. }
  308. function sortComparator$2(a, b) {
  309. return a[0] - b[0];
  310. }
  311. function encode$1(decoded) {
  312. const writer = new StringWriter();
  313. let sourcesIndex = 0;
  314. let sourceLine = 0;
  315. let sourceColumn = 0;
  316. let namesIndex = 0;
  317. for (let i = 0; i < decoded.length; i++) {
  318. const line = decoded[i];
  319. if (i > 0) writer.write(semicolon);
  320. if (line.length === 0) continue;
  321. let genColumn = 0;
  322. for (let j = 0; j < line.length; j++) {
  323. const segment = line[j];
  324. if (j > 0) writer.write(comma$1);
  325. genColumn = encodeInteger(writer, segment[0], genColumn);
  326. if (segment.length === 1) continue;
  327. sourcesIndex = encodeInteger(writer, segment[1], sourcesIndex);
  328. sourceLine = encodeInteger(writer, segment[2], sourceLine);
  329. sourceColumn = encodeInteger(writer, segment[3], sourceColumn);
  330. if (segment.length === 4) continue;
  331. namesIndex = encodeInteger(writer, segment[4], namesIndex);
  332. }
  333. }
  334. return writer.flush();
  335. }
  336. //#endregion
  337. //#region ../../node_modules/.pnpm/@jridgewell+resolve-uri@3.1.2/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.mjs
  338. const schemeRegex = /^[\w+.-]+:\/\//;
  339. /**
  340. * Matches the parts of a URL:
  341. * 1. Scheme, including ":", guaranteed.
  342. * 2. User/password, including "@", optional.
  343. * 3. Host, guaranteed.
  344. * 4. Port, including ":", optional.
  345. * 5. Path, including "/", optional.
  346. * 6. Query, including "?", optional.
  347. * 7. Hash, including "#", optional.
  348. */
  349. const urlRegex = /^([\w+.-]+:)\/\/([^@/#?]*@)?([^:/#?]*)(:\d+)?(\/[^#?]*)?(\?[^#]*)?(#.*)?/;
  350. /**
  351. * File URLs are weird. They dont' need the regular `//` in the scheme, they may or may not start
  352. * with a leading `/`, they can have a domain (but only if they don't start with a Windows drive).
  353. *
  354. * 1. Host, optional.
  355. * 2. Path, which may include "/", guaranteed.
  356. * 3. Query, including "?", optional.
  357. * 4. Hash, including "#", optional.
  358. */
  359. const fileRegex = /^file:(?:\/\/((?![a-z]:)[^/#?]*)?)?(\/?[^#?]*)(\?[^#]*)?(#.*)?/i;
  360. function isAbsoluteUrl(input) {
  361. return schemeRegex.test(input);
  362. }
  363. function isSchemeRelativeUrl(input) {
  364. return input.startsWith("//");
  365. }
  366. function isAbsolutePath(input) {
  367. return input.startsWith("/");
  368. }
  369. function isFileUrl(input) {
  370. return input.startsWith("file:");
  371. }
  372. function isRelative(input) {
  373. return /^[.?#]/.test(input);
  374. }
  375. function parseAbsoluteUrl(input) {
  376. const match = urlRegex.exec(input);
  377. return makeUrl(match[1], match[2] || "", match[3], match[4] || "", match[5] || "/", match[6] || "", match[7] || "");
  378. }
  379. function parseFileUrl(input) {
  380. const match = fileRegex.exec(input);
  381. const path = match[2];
  382. return makeUrl("file:", "", match[1] || "", "", isAbsolutePath(path) ? path : "/" + path, match[3] || "", match[4] || "");
  383. }
  384. function makeUrl(scheme, user, host, port, path, query, hash) {
  385. return {
  386. scheme,
  387. user,
  388. host,
  389. port,
  390. path,
  391. query,
  392. hash,
  393. type: 7
  394. };
  395. }
  396. function parseUrl(input) {
  397. if (isSchemeRelativeUrl(input)) {
  398. const url = parseAbsoluteUrl("http:" + input);
  399. url.scheme = "";
  400. url.type = 6;
  401. return url;
  402. }
  403. if (isAbsolutePath(input)) {
  404. const url = parseAbsoluteUrl("http://foo.com" + input);
  405. url.scheme = "";
  406. url.host = "";
  407. url.type = 5;
  408. return url;
  409. }
  410. if (isFileUrl(input)) return parseFileUrl(input);
  411. if (isAbsoluteUrl(input)) return parseAbsoluteUrl(input);
  412. const url = parseAbsoluteUrl("http://foo.com/" + input);
  413. url.scheme = "";
  414. url.host = "";
  415. url.type = input ? input.startsWith("?") ? 3 : input.startsWith("#") ? 2 : 4 : 1;
  416. return url;
  417. }
  418. function stripPathFilename(path) {
  419. if (path.endsWith("/..")) return path;
  420. const index = path.lastIndexOf("/");
  421. return path.slice(0, index + 1);
  422. }
  423. function mergePaths(url, base) {
  424. normalizePath$2(base, base.type);
  425. if (url.path === "/") url.path = base.path;
  426. else url.path = stripPathFilename(base.path) + url.path;
  427. }
  428. /**
  429. * The path can have empty directories "//", unneeded parents "foo/..", or current directory
  430. * "foo/.". We need to normalize to a standard representation.
  431. */
  432. function normalizePath$2(url, type) {
  433. const rel = type <= 4;
  434. const pieces = url.path.split("/");
  435. let pointer = 1;
  436. let positive = 0;
  437. let addTrailingSlash = false;
  438. for (let i = 1; i < pieces.length; i++) {
  439. const piece = pieces[i];
  440. if (!piece) {
  441. addTrailingSlash = true;
  442. continue;
  443. }
  444. addTrailingSlash = false;
  445. if (piece === ".") continue;
  446. if (piece === "..") {
  447. if (positive) {
  448. addTrailingSlash = true;
  449. positive--;
  450. pointer--;
  451. } else if (rel) pieces[pointer++] = piece;
  452. continue;
  453. }
  454. pieces[pointer++] = piece;
  455. positive++;
  456. }
  457. let path = "";
  458. for (let i = 1; i < pointer; i++) path += "/" + pieces[i];
  459. if (!path || addTrailingSlash && !path.endsWith("/..")) path += "/";
  460. url.path = path;
  461. }
  462. /**
  463. * Attempts to resolve `input` URL/path relative to `base`.
  464. */
  465. function resolve$4(input, base) {
  466. if (!input && !base) return "";
  467. const url = parseUrl(input);
  468. let inputType = url.type;
  469. if (base && inputType !== 7) {
  470. const baseUrl = parseUrl(base);
  471. const baseType = baseUrl.type;
  472. switch (inputType) {
  473. case 1: url.hash = baseUrl.hash;
  474. case 2: url.query = baseUrl.query;
  475. case 3:
  476. case 4: mergePaths(url, baseUrl);
  477. case 5:
  478. url.user = baseUrl.user;
  479. url.host = baseUrl.host;
  480. url.port = baseUrl.port;
  481. case 6: url.scheme = baseUrl.scheme;
  482. }
  483. if (baseType > inputType) inputType = baseType;
  484. }
  485. normalizePath$2(url, inputType);
  486. const queryHash = url.query + url.hash;
  487. switch (inputType) {
  488. case 2:
  489. case 3: return queryHash;
  490. case 4: {
  491. const path = url.path.slice(1);
  492. if (!path) return queryHash || ".";
  493. if (isRelative(base || input) && !isRelative(path)) return "./" + path + queryHash;
  494. return path + queryHash;
  495. }
  496. case 5: return url.path + queryHash;
  497. default: return url.scheme + "//" + url.user + url.host + url.port + url.path + queryHash;
  498. }
  499. }
  500. //#endregion
  501. //#region ../../node_modules/.pnpm/@jridgewell+trace-mapping@0.3.31/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.mjs
  502. function stripFilename(path) {
  503. if (!path) return "";
  504. const index = path.lastIndexOf("/");
  505. return path.slice(0, index + 1);
  506. }
  507. function resolver(mapUrl, sourceRoot) {
  508. const from = stripFilename(mapUrl);
  509. const prefix = sourceRoot ? sourceRoot + "/" : "";
  510. return (source) => resolve$4(prefix + (source || ""), from);
  511. }
  512. var COLUMN$2 = 0;
  513. var SOURCES_INDEX$2 = 1;
  514. var SOURCE_LINE$2 = 2;
  515. var SOURCE_COLUMN$2 = 3;
  516. var NAMES_INDEX$2 = 4;
  517. function maybeSort(mappings, owned) {
  518. const unsortedIndex = nextUnsortedSegmentLine(mappings, 0);
  519. if (unsortedIndex === mappings.length) return mappings;
  520. if (!owned) mappings = mappings.slice();
  521. for (let i = unsortedIndex; i < mappings.length; i = nextUnsortedSegmentLine(mappings, i + 1)) mappings[i] = sortSegments(mappings[i], owned);
  522. return mappings;
  523. }
  524. function nextUnsortedSegmentLine(mappings, start) {
  525. for (let i = start; i < mappings.length; i++) if (!isSorted(mappings[i])) return i;
  526. return mappings.length;
  527. }
  528. function isSorted(line) {
  529. for (let j = 1; j < line.length; j++) if (line[j][COLUMN$2] < line[j - 1][COLUMN$2]) return false;
  530. return true;
  531. }
  532. function sortSegments(line, owned) {
  533. if (!owned) line = line.slice();
  534. return line.sort(sortComparator$1);
  535. }
  536. function sortComparator$1(a, b) {
  537. return a[COLUMN$2] - b[COLUMN$2];
  538. }
  539. var found$1 = false;
  540. function binarySearch$1(haystack, needle, low, high) {
  541. while (low <= high) {
  542. const mid = low + (high - low >> 1);
  543. const cmp = haystack[mid][COLUMN$2] - needle;
  544. if (cmp === 0) {
  545. found$1 = true;
  546. return mid;
  547. }
  548. if (cmp < 0) low = mid + 1;
  549. else high = mid - 1;
  550. }
  551. found$1 = false;
  552. return low - 1;
  553. }
  554. function upperBound$1(haystack, needle, index) {
  555. for (let i = index + 1; i < haystack.length; index = i++) if (haystack[i][COLUMN$2] !== needle) break;
  556. return index;
  557. }
  558. function lowerBound$1(haystack, needle, index) {
  559. for (let i = index - 1; i >= 0; index = i--) if (haystack[i][COLUMN$2] !== needle) break;
  560. return index;
  561. }
  562. function memoizedState$1() {
  563. return {
  564. lastKey: -1,
  565. lastNeedle: -1,
  566. lastIndex: -1
  567. };
  568. }
  569. function memoizedBinarySearch$1(haystack, needle, state, key) {
  570. const { lastKey, lastNeedle, lastIndex } = state;
  571. let low = 0;
  572. let high = haystack.length - 1;
  573. if (key === lastKey) {
  574. if (needle === lastNeedle) {
  575. found$1 = lastIndex !== -1 && haystack[lastIndex][COLUMN$2] === needle;
  576. return lastIndex;
  577. }
  578. if (needle >= lastNeedle) low = lastIndex === -1 ? 0 : lastIndex;
  579. else high = lastIndex;
  580. }
  581. state.lastKey = key;
  582. state.lastNeedle = needle;
  583. return state.lastIndex = binarySearch$1(haystack, needle, low, high);
  584. }
  585. function parse$3(map) {
  586. return typeof map === "string" ? JSON.parse(map) : map;
  587. }
  588. var LINE_GTR_ZERO$1 = "`line` must be greater than 0 (lines start at line 1)";
  589. var COL_GTR_EQ_ZERO$1 = "`column` must be greater than or equal to 0 (columns start at column 0)";
  590. var TraceMap = class {
  591. constructor(map, mapUrl) {
  592. const isString = typeof map === "string";
  593. if (!isString && map._decodedMemo) return map;
  594. const parsed = parse$3(map);
  595. const { version, file, names, sourceRoot, sources, sourcesContent } = parsed;
  596. this.version = version;
  597. this.file = file;
  598. this.names = names || [];
  599. this.sourceRoot = sourceRoot;
  600. this.sources = sources;
  601. this.sourcesContent = sourcesContent;
  602. this.ignoreList = parsed.ignoreList || parsed.x_google_ignoreList || void 0;
  603. const resolve = resolver(mapUrl, sourceRoot);
  604. this.resolvedSources = sources.map(resolve);
  605. const { mappings } = parsed;
  606. if (typeof mappings === "string") {
  607. this._encoded = mappings;
  608. this._decoded = void 0;
  609. } else if (Array.isArray(mappings)) {
  610. this._encoded = void 0;
  611. this._decoded = maybeSort(mappings, isString);
  612. } else if (parsed.sections) throw new Error(`TraceMap passed sectioned source map, please use FlattenMap export instead`);
  613. else throw new Error(`invalid source map: ${JSON.stringify(parsed)}`);
  614. this._decodedMemo = memoizedState$1();
  615. this._bySources = void 0;
  616. this._bySourceMemos = void 0;
  617. }
  618. };
  619. function cast$2(map) {
  620. return map;
  621. }
  622. function decodedMappings$1(map) {
  623. var _a;
  624. return (_a = cast$2(map))._decoded || (_a._decoded = decode$1(cast$2(map)._encoded));
  625. }
  626. function traceSegment(map, line, column) {
  627. const decoded = decodedMappings$1(map);
  628. if (line >= decoded.length) return null;
  629. const segments = decoded[line];
  630. const index = traceSegmentInternal$1(segments, cast$2(map)._decodedMemo, line, column, 1);
  631. return index === -1 ? null : segments[index];
  632. }
  633. function originalPositionFor$2(map, needle) {
  634. let { line, column, bias } = needle;
  635. line--;
  636. if (line < 0) throw new Error(LINE_GTR_ZERO$1);
  637. if (column < 0) throw new Error(COL_GTR_EQ_ZERO$1);
  638. const decoded = decodedMappings$1(map);
  639. if (line >= decoded.length) return OMapping$1(null, null, null, null);
  640. const segments = decoded[line];
  641. const index = traceSegmentInternal$1(segments, cast$2(map)._decodedMemo, line, column, bias || 1);
  642. if (index === -1) return OMapping$1(null, null, null, null);
  643. const segment = segments[index];
  644. if (segment.length === 1) return OMapping$1(null, null, null, null);
  645. const { names, resolvedSources } = map;
  646. return OMapping$1(resolvedSources[segment[SOURCES_INDEX$2]], segment[SOURCE_LINE$2] + 1, segment[SOURCE_COLUMN$2], segment.length === 5 ? names[segment[NAMES_INDEX$2]] : null);
  647. }
  648. function OMapping$1(source, line, column, name) {
  649. return {
  650. source,
  651. line,
  652. column,
  653. name
  654. };
  655. }
  656. function traceSegmentInternal$1(segments, memo, line, column, bias) {
  657. let index = memoizedBinarySearch$1(segments, column, memo, line);
  658. if (found$1) index = (bias === -1 ? upperBound$1 : lowerBound$1)(segments, column, index);
  659. else if (bias === -1) index++;
  660. if (index === -1 || index === segments.length) return -1;
  661. return index;
  662. }
  663. //#endregion
  664. //#region ../../node_modules/.pnpm/@jridgewell+gen-mapping@0.3.13/node_modules/@jridgewell/gen-mapping/dist/gen-mapping.mjs
  665. var SetArray = class {
  666. constructor() {
  667. this._indexes = { __proto__: null };
  668. this.array = [];
  669. }
  670. };
  671. function cast$1(set) {
  672. return set;
  673. }
  674. function get$2(setarr, key) {
  675. return cast$1(setarr)._indexes[key];
  676. }
  677. function put(setarr, key) {
  678. const index = get$2(setarr, key);
  679. if (index !== void 0) return index;
  680. const { array, _indexes: indexes } = cast$1(setarr);
  681. return indexes[key] = array.push(key) - 1;
  682. }
  683. function remove(setarr, key) {
  684. const index = get$2(setarr, key);
  685. if (index === void 0) return;
  686. const { array, _indexes: indexes } = cast$1(setarr);
  687. for (let i = index + 1; i < array.length; i++) {
  688. const k = array[i];
  689. array[i - 1] = k;
  690. indexes[k]--;
  691. }
  692. indexes[key] = void 0;
  693. array.pop();
  694. }
  695. var COLUMN$1 = 0;
  696. var SOURCES_INDEX$1 = 1;
  697. var SOURCE_LINE$1 = 2;
  698. var SOURCE_COLUMN$1 = 3;
  699. var NAMES_INDEX$1 = 4;
  700. var NO_NAME = -1;
  701. var GenMapping = class {
  702. constructor({ file, sourceRoot } = {}) {
  703. this._names = new SetArray();
  704. this._sources = new SetArray();
  705. this._sourcesContent = [];
  706. this._mappings = [];
  707. this.file = file;
  708. this.sourceRoot = sourceRoot;
  709. this._ignoreList = new SetArray();
  710. }
  711. };
  712. function cast2(map) {
  713. return map;
  714. }
  715. var maybeAddSegment = (map, genLine, genColumn, source, sourceLine, sourceColumn, name, content) => {
  716. return addSegmentInternal(true, map, genLine, genColumn, source, sourceLine, sourceColumn, name, content);
  717. };
  718. function setSourceContent(map, source, content) {
  719. const { _sources: sources, _sourcesContent: sourcesContent } = cast2(map);
  720. const index = put(sources, source);
  721. sourcesContent[index] = content;
  722. }
  723. function setIgnore(map, source, ignore = true) {
  724. const { _sources: sources, _sourcesContent: sourcesContent, _ignoreList: ignoreList } = cast2(map);
  725. const index = put(sources, source);
  726. if (index === sourcesContent.length) sourcesContent[index] = null;
  727. if (ignore) put(ignoreList, index);
  728. else remove(ignoreList, index);
  729. }
  730. function toDecodedMap(map) {
  731. const { _mappings: mappings, _sources: sources, _sourcesContent: sourcesContent, _names: names, _ignoreList: ignoreList } = cast2(map);
  732. removeEmptyFinalLines(mappings);
  733. return {
  734. version: 3,
  735. file: map.file || void 0,
  736. names: names.array,
  737. sourceRoot: map.sourceRoot || void 0,
  738. sources: sources.array,
  739. sourcesContent,
  740. mappings,
  741. ignoreList: ignoreList.array
  742. };
  743. }
  744. function toEncodedMap(map) {
  745. const decoded = toDecodedMap(map);
  746. return Object.assign({}, decoded, { mappings: encode$1(decoded.mappings) });
  747. }
  748. function addSegmentInternal(skipable, map, genLine, genColumn, source, sourceLine, sourceColumn, name, content) {
  749. const { _mappings: mappings, _sources: sources, _sourcesContent: sourcesContent, _names: names } = cast2(map);
  750. const line = getIndex(mappings, genLine);
  751. const index = getColumnIndex(line, genColumn);
  752. if (!source) {
  753. if (skipable && skipSourceless(line, index)) return;
  754. return insert(line, index, [genColumn]);
  755. }
  756. assert$2(sourceLine);
  757. assert$2(sourceColumn);
  758. const sourcesIndex = put(sources, source);
  759. const namesIndex = name ? put(names, name) : NO_NAME;
  760. if (sourcesIndex === sourcesContent.length) sourcesContent[sourcesIndex] = content != null ? content : null;
  761. if (skipable && skipSource(line, index, sourcesIndex, sourceLine, sourceColumn, namesIndex)) return;
  762. return insert(line, index, name ? [
  763. genColumn,
  764. sourcesIndex,
  765. sourceLine,
  766. sourceColumn,
  767. namesIndex
  768. ] : [
  769. genColumn,
  770. sourcesIndex,
  771. sourceLine,
  772. sourceColumn
  773. ]);
  774. }
  775. function assert$2(_val) {}
  776. function getIndex(arr, index) {
  777. for (let i = arr.length; i <= index; i++) arr[i] = [];
  778. return arr[index];
  779. }
  780. function getColumnIndex(line, genColumn) {
  781. let index = line.length;
  782. for (let i = index - 1; i >= 0; index = i--) if (genColumn >= line[i][COLUMN$1]) break;
  783. return index;
  784. }
  785. function insert(array, index, value) {
  786. for (let i = array.length; i > index; i--) array[i] = array[i - 1];
  787. array[index] = value;
  788. }
  789. function removeEmptyFinalLines(mappings) {
  790. const { length } = mappings;
  791. let len = length;
  792. for (let i = len - 1; i >= 0; len = i, i--) if (mappings[i].length > 0) break;
  793. if (len < length) mappings.length = len;
  794. }
  795. function skipSourceless(line, index) {
  796. if (index === 0) return true;
  797. return line[index - 1].length === 1;
  798. }
  799. function skipSource(line, index, sourcesIndex, sourceLine, sourceColumn, namesIndex) {
  800. if (index === 0) return false;
  801. const prev = line[index - 1];
  802. if (prev.length === 1) return false;
  803. return sourcesIndex === prev[SOURCES_INDEX$1] && sourceLine === prev[SOURCE_LINE$1] && sourceColumn === prev[SOURCE_COLUMN$1] && namesIndex === (prev.length === 5 ? prev[NAMES_INDEX$1] : NO_NAME);
  804. }
  805. //#endregion
  806. //#region ../../node_modules/.pnpm/@jridgewell+remapping@2.3.5/node_modules/@jridgewell/remapping/dist/remapping.mjs
  807. var SOURCELESS_MAPPING = /* @__PURE__ */ SegmentObject("", -1, -1, "", null, false);
  808. var EMPTY_SOURCES = [];
  809. function SegmentObject(source, line, column, name, content, ignore) {
  810. return {
  811. source,
  812. line,
  813. column,
  814. name,
  815. content,
  816. ignore
  817. };
  818. }
  819. function Source(map, sources, source, content, ignore) {
  820. return {
  821. map,
  822. sources,
  823. source,
  824. content,
  825. ignore
  826. };
  827. }
  828. function MapSource(map, sources) {
  829. return Source(map, sources, "", null, false);
  830. }
  831. function OriginalSource(source, content, ignore) {
  832. return Source(null, EMPTY_SOURCES, source, content, ignore);
  833. }
  834. function traceMappings(tree) {
  835. const gen = new GenMapping({ file: tree.map.file });
  836. const { sources: rootSources, map } = tree;
  837. const rootNames = map.names;
  838. const rootMappings = decodedMappings$1(map);
  839. for (let i = 0; i < rootMappings.length; i++) {
  840. const segments = rootMappings[i];
  841. for (let j = 0; j < segments.length; j++) {
  842. const segment = segments[j];
  843. const genCol = segment[0];
  844. let traced = SOURCELESS_MAPPING;
  845. if (segment.length !== 1) {
  846. const source2 = rootSources[segment[1]];
  847. traced = originalPositionFor$1(source2, segment[2], segment[3], segment.length === 5 ? rootNames[segment[4]] : "");
  848. if (traced == null) continue;
  849. }
  850. const { column, line, name, content, source, ignore } = traced;
  851. maybeAddSegment(gen, i, genCol, source, line, column, name);
  852. if (source && content != null) setSourceContent(gen, source, content);
  853. if (ignore) setIgnore(gen, source, true);
  854. }
  855. }
  856. return gen;
  857. }
  858. function originalPositionFor$1(source, line, column, name) {
  859. if (!source.map) return SegmentObject(source.source, line, column, name, source.content, source.ignore);
  860. const segment = traceSegment(source.map, line, column);
  861. if (segment == null) return null;
  862. if (segment.length === 1) return SOURCELESS_MAPPING;
  863. return originalPositionFor$1(source.sources[segment[1]], segment[2], segment[3], segment.length === 5 ? source.map.names[segment[4]] : name);
  864. }
  865. function asArray(value) {
  866. if (Array.isArray(value)) return value;
  867. return [value];
  868. }
  869. function buildSourceMapTree(input, loader) {
  870. const maps = asArray(input).map((m) => new TraceMap(m, ""));
  871. const map = maps.pop();
  872. for (let i = 0; i < maps.length; i++) if (maps[i].sources.length > 1) throw new Error(`Transformation map ${i} must have exactly one source file.
  873. Did you specify these with the most recent transformation maps first?`);
  874. let tree = build$1(map, loader, "", 0);
  875. for (let i = maps.length - 1; i >= 0; i--) tree = MapSource(maps[i], [tree]);
  876. return tree;
  877. }
  878. function build$1(map, loader, importer, importerDepth) {
  879. const { resolvedSources, sourcesContent, ignoreList } = map;
  880. const depth = importerDepth + 1;
  881. return MapSource(map, resolvedSources.map((sourceFile, i) => {
  882. const ctx = {
  883. importer,
  884. depth,
  885. source: sourceFile || "",
  886. content: void 0,
  887. ignore: void 0
  888. };
  889. const sourceMap = loader(ctx.source, ctx);
  890. const { source, content, ignore } = ctx;
  891. if (sourceMap) return build$1(new TraceMap(sourceMap, source), loader, source, depth);
  892. return OriginalSource(source, content !== void 0 ? content : sourcesContent ? sourcesContent[i] : null, ignore !== void 0 ? ignore : ignoreList ? ignoreList.includes(i) : false);
  893. }));
  894. }
  895. var SourceMap$1 = class {
  896. constructor(map, options) {
  897. const out = options.decodedMappings ? toDecodedMap(map) : toEncodedMap(map);
  898. this.version = out.version;
  899. this.file = out.file;
  900. this.mappings = out.mappings;
  901. this.names = out.names;
  902. this.ignoreList = out.ignoreList;
  903. this.sourceRoot = out.sourceRoot;
  904. this.sources = out.sources;
  905. if (!options.excludeContent) this.sourcesContent = out.sourcesContent;
  906. }
  907. toString() {
  908. return JSON.stringify(this);
  909. }
  910. };
  911. function remapping(input, loader, options) {
  912. const opts = typeof options === "object" ? options : {
  913. excludeContent: !!options,
  914. decodedMappings: false
  915. };
  916. return new SourceMap$1(traceMappings(buildSourceMapTree(input, loader)), opts);
  917. }
  918. //#endregion
  919. //#region ../../node_modules/.pnpm/obug@1.0.2_ms@2.1.3/node_modules/obug/dist/core.js
  920. function coerce(value) {
  921. if (value instanceof Error) return value.stack || value.message;
  922. return value;
  923. }
  924. function selectColor(colors, namespace) {
  925. let hash = 0;
  926. for (let i = 0; i < namespace.length; i++) {
  927. hash = (hash << 5) - hash + namespace.charCodeAt(i);
  928. hash |= 0;
  929. }
  930. return colors[Math.abs(hash) % colors.length];
  931. }
  932. function matchesTemplate(search, template) {
  933. let searchIndex = 0;
  934. let templateIndex = 0;
  935. let starIndex = -1;
  936. let matchIndex = 0;
  937. while (searchIndex < search.length) if (templateIndex < template.length && (template[templateIndex] === search[searchIndex] || template[templateIndex] === "*")) if (template[templateIndex] === "*") {
  938. starIndex = templateIndex;
  939. matchIndex = searchIndex;
  940. templateIndex++;
  941. } else {
  942. searchIndex++;
  943. templateIndex++;
  944. }
  945. else if (starIndex !== -1) {
  946. templateIndex = starIndex + 1;
  947. matchIndex++;
  948. searchIndex = matchIndex;
  949. } else return false;
  950. while (templateIndex < template.length && template[templateIndex] === "*") templateIndex++;
  951. return templateIndex === template.length;
  952. }
  953. function humanize(value) {
  954. if (value >= 1e3) return `${(value / 1e3).toFixed(1)}s`;
  955. return `${value}ms`;
  956. }
  957. function setup(useColors, colors, log, load, save, formatArgs, init) {
  958. const createDebug = (namespace) => {
  959. let prevTime;
  960. let enableOverride;
  961. let namespacesCache;
  962. let enabledCache;
  963. const debug = (...args) => {
  964. if (!debug.enabled) return;
  965. const curr = Date.now();
  966. debug.diff = curr - (prevTime || curr);
  967. debug.prev = prevTime;
  968. debug.curr = curr;
  969. prevTime = curr;
  970. args[0] = coerce(args[0]);
  971. if (typeof args[0] !== "string") args.unshift("%O");
  972. let index = 0;
  973. args[0] = args[0].replace(/%([a-z%])/gi, (match, format) => {
  974. if (match === "%%") return "%";
  975. index++;
  976. const formatter = createDebug.formatters[format];
  977. if (typeof formatter === "function") {
  978. match = formatter.call(debug, args[index]);
  979. args.splice(index, 1);
  980. index--;
  981. }
  982. return match;
  983. });
  984. createDebug.formatArgs.call(debug, args);
  985. (debug.log || createDebug.log).apply(debug, args);
  986. };
  987. function extend(namespace$1, delimiter = ":") {
  988. const newDebug = createDebug(this.namespace + delimiter + namespace$1);
  989. newDebug.log = this.log;
  990. return newDebug;
  991. }
  992. debug.namespace = namespace;
  993. debug.useColors = useColors;
  994. debug.color = selectColor(colors, namespace);
  995. debug.extend = extend;
  996. debug.log = log;
  997. Object.defineProperty(debug, "enabled", {
  998. enumerable: true,
  999. configurable: false,
  1000. get: () => {
  1001. if (enableOverride != null) return enableOverride;
  1002. if (namespacesCache !== createDebug.namespaces) {
  1003. namespacesCache = createDebug.namespaces;
  1004. enabledCache = createDebug.enabled(namespace);
  1005. }
  1006. return enabledCache;
  1007. },
  1008. set: (v) => {
  1009. enableOverride = v;
  1010. }
  1011. });
  1012. init && init(debug);
  1013. return debug;
  1014. };
  1015. function enable(namespaces) {
  1016. save(namespaces);
  1017. createDebug.namespaces = namespaces;
  1018. createDebug.names = [];
  1019. createDebug.skips = [];
  1020. const split = namespaces.trim().replace(/\s+/g, ",").split(",").filter(Boolean);
  1021. for (const ns of split) if (ns[0] === "-") createDebug.skips.push(ns.slice(1));
  1022. else createDebug.names.push(ns);
  1023. }
  1024. function disable() {
  1025. const namespaces = [...createDebug.names, ...createDebug.skips.map((namespace) => `-${namespace}`)].join(",");
  1026. createDebug.enable("");
  1027. return namespaces;
  1028. }
  1029. function enabled(name) {
  1030. for (const skip of createDebug.skips) if (matchesTemplate(name, skip)) return false;
  1031. for (const ns of createDebug.names) if (matchesTemplate(name, ns)) return true;
  1032. return false;
  1033. }
  1034. createDebug.namespaces = "";
  1035. createDebug.formatters = {};
  1036. createDebug.enable = enable;
  1037. createDebug.disable = disable;
  1038. createDebug.enabled = enabled;
  1039. createDebug.names = [];
  1040. createDebug.skips = [];
  1041. createDebug.selectColor = (ns) => selectColor(colors, ns);
  1042. createDebug.formatArgs = formatArgs;
  1043. createDebug.log = log;
  1044. createDebug.enable(load());
  1045. return createDebug;
  1046. }
  1047. var init_core = __esmMin((() => {}));
  1048. //#endregion
  1049. //#region ../../node_modules/.pnpm/obug@1.0.2_ms@2.1.3/node_modules/obug/dist/node.js
  1050. var node_exports = /* @__PURE__ */ __exportAll({
  1051. createDebug: () => createDebug,
  1052. default: () => node_default,
  1053. formatArgs: () => formatArgs,
  1054. log: () => log,
  1055. "module.exports": () => createDebug
  1056. });
  1057. function log(...args) {
  1058. process.stderr.write(`${formatWithOptions(inspectOpts, ...args)}\n`);
  1059. }
  1060. function load() {
  1061. return process.env.DEBUG || "";
  1062. }
  1063. function save(namespaces) {
  1064. if (namespaces) process.env.DEBUG = namespaces;
  1065. else delete process.env.DEBUG;
  1066. }
  1067. function useColors() {
  1068. return "colors" in inspectOpts ? Boolean(inspectOpts.colors) : isatty(process.stderr.fd);
  1069. }
  1070. function formatArgs(args) {
  1071. const { namespace: name, useColors: useColors$1 } = this;
  1072. if (useColors$1) {
  1073. const c = this.color;
  1074. const colorCode = `\u001B[3${c < 8 ? c : `8;5;${c}`}`;
  1075. const prefix = ` ${colorCode};1m${name} \u001B[0m`;
  1076. args[0] = prefix + args[0].split("\n").join(`\n${prefix}`);
  1077. args.push(`${colorCode}m+${humanize$1(this.diff)}\u001B[0m`);
  1078. } else args[0] = `${getDate()}${name} ${args[0]}`;
  1079. }
  1080. function getDate() {
  1081. if (inspectOpts.hideDate) return "";
  1082. return `${(/* @__PURE__ */ new Date()).toISOString()} `;
  1083. }
  1084. function init$1(debug) {
  1085. debug.inspectOpts = Object.assign({}, inspectOpts);
  1086. }
  1087. var require$1, colors$37, inspectOpts, humanize$1, createDebug, node_default;
  1088. var init_node = __esmMin((() => {
  1089. init_core();
  1090. require$1 = createRequire(import.meta.url);
  1091. colors$37 = process.stderr.getColorDepth && process.stderr.getColorDepth() > 2 ? [
  1092. 20,
  1093. 21,
  1094. 26,
  1095. 27,
  1096. 32,
  1097. 33,
  1098. 38,
  1099. 39,
  1100. 40,
  1101. 41,
  1102. 42,
  1103. 43,
  1104. 44,
  1105. 45,
  1106. 56,
  1107. 57,
  1108. 62,
  1109. 63,
  1110. 68,
  1111. 69,
  1112. 74,
  1113. 75,
  1114. 76,
  1115. 77,
  1116. 78,
  1117. 79,
  1118. 80,
  1119. 81,
  1120. 92,
  1121. 93,
  1122. 98,
  1123. 99,
  1124. 112,
  1125. 113,
  1126. 128,
  1127. 129,
  1128. 134,
  1129. 135,
  1130. 148,
  1131. 149,
  1132. 160,
  1133. 161,
  1134. 162,
  1135. 163,
  1136. 164,
  1137. 165,
  1138. 166,
  1139. 167,
  1140. 168,
  1141. 169,
  1142. 170,
  1143. 171,
  1144. 172,
  1145. 173,
  1146. 178,
  1147. 179,
  1148. 184,
  1149. 185,
  1150. 196,
  1151. 197,
  1152. 198,
  1153. 199,
  1154. 200,
  1155. 201,
  1156. 202,
  1157. 203,
  1158. 204,
  1159. 205,
  1160. 206,
  1161. 207,
  1162. 208,
  1163. 209,
  1164. 214,
  1165. 215,
  1166. 220,
  1167. 221
  1168. ] : [
  1169. 6,
  1170. 2,
  1171. 3,
  1172. 4,
  1173. 5,
  1174. 1
  1175. ];
  1176. inspectOpts = Object.keys(process.env).filter((key) => {
  1177. return /^debug_/i.test(key);
  1178. }).reduce((obj, key) => {
  1179. const prop = key.slice(6).toLowerCase().replace(/_([a-z])/g, (_, k) => k.toUpperCase());
  1180. let value = process.env[key];
  1181. if (value === "null") value = null;
  1182. else if (/^yes|on|true|enabled$/i.test(value)) value = true;
  1183. else if (/^no|off|false|disabled$/i.test(value)) value = false;
  1184. else value = Number(value);
  1185. obj[prop] = value;
  1186. return obj;
  1187. }, {});
  1188. try {
  1189. humanize$1 = require$1("ms");
  1190. } catch (_unused) {
  1191. humanize$1 = humanize;
  1192. }
  1193. createDebug = setup(useColors(), colors$37, log, load, save, formatArgs, init$1);
  1194. createDebug.inspectOpts = inspectOpts;
  1195. createDebug.formatters.o = function(v) {
  1196. this.inspectOpts.colors = this.useColors;
  1197. return inspect(v, this.inspectOpts).split("\n").map((str) => str.trim()).join(" ");
  1198. };
  1199. createDebug.formatters.O = function(v) {
  1200. this.inspectOpts.colors = this.useColors;
  1201. return inspect(v, this.inspectOpts);
  1202. };
  1203. node_default = createDebug;
  1204. createDebug.default = createDebug;
  1205. createDebug.debug = createDebug;
  1206. }));
  1207. //#endregion
  1208. //#region ../../node_modules/.pnpm/@rollup+pluginutils@5.3.0_rollup@4.59.0/node_modules/@rollup/pluginutils/dist/es/index.js
  1209. function isArray(arg) {
  1210. return Array.isArray(arg);
  1211. }
  1212. function ensureArray(thing) {
  1213. if (isArray(thing)) return thing;
  1214. if (thing == null) return [];
  1215. return [thing];
  1216. }
  1217. const normalizePathRegExp = new RegExp(`\\${win32.sep}`, "g");
  1218. const normalizePath$1 = function normalizePath(filename) {
  1219. return filename.replace(normalizePathRegExp, posix$1.sep);
  1220. };
  1221. function getMatcherString$1(id, resolutionBase) {
  1222. if (resolutionBase === false || isAbsolute$1(id) || id.startsWith("**")) return normalizePath$1(id);
  1223. const basePath = normalizePath$1(resolve$1(resolutionBase || "")).replace(/[-^$*+?.()|[\]{}]/g, "\\$&");
  1224. return posix$1.join(basePath, normalizePath$1(id));
  1225. }
  1226. const createFilter$2 = function createFilter(include, exclude, options) {
  1227. const resolutionBase = options && options.resolve;
  1228. const getMatcher = (id) => id instanceof RegExp ? id : { test: (what) => {
  1229. return picomatch(getMatcherString$1(id, resolutionBase), { dot: true })(what);
  1230. } };
  1231. const includeMatchers = ensureArray(include).map(getMatcher);
  1232. const excludeMatchers = ensureArray(exclude).map(getMatcher);
  1233. if (!includeMatchers.length && !excludeMatchers.length) return (id) => typeof id === "string" && !id.includes("\0");
  1234. return function result(id) {
  1235. if (typeof id !== "string") return false;
  1236. if (id.includes("\0")) return false;
  1237. const pathId = normalizePath$1(id);
  1238. for (let i = 0; i < excludeMatchers.length; ++i) {
  1239. const matcher = excludeMatchers[i];
  1240. if (matcher instanceof RegExp) matcher.lastIndex = 0;
  1241. if (matcher.test(pathId)) return false;
  1242. }
  1243. for (let i = 0; i < includeMatchers.length; ++i) {
  1244. const matcher = includeMatchers[i];
  1245. if (matcher instanceof RegExp) matcher.lastIndex = 0;
  1246. if (matcher.test(pathId)) return true;
  1247. }
  1248. return !includeMatchers.length;
  1249. };
  1250. };
  1251. const forbiddenIdentifiers = new Set(`break case class catch const continue debugger default delete do else export extends finally for function if import in instanceof let new return super switch this throw try typeof var void while with yield enum await implements package protected static interface private public arguments Infinity NaN undefined null true false eval uneval isFinite isNaN parseFloat parseInt decodeURI decodeURIComponent encodeURI encodeURIComponent escape unescape Object Function Boolean Symbol Error EvalError InternalError RangeError ReferenceError SyntaxError TypeError URIError Number Math Date String RegExp Array Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array Map Set WeakMap WeakSet SIMD ArrayBuffer DataView JSON Promise Generator GeneratorFunction Reflect Proxy Intl`.split(" "));
  1252. forbiddenIdentifiers.add("");
  1253. const makeLegalIdentifier = function makeLegalIdentifier(str) {
  1254. let identifier = str.replace(/-(\w)/g, (_, letter) => letter.toUpperCase()).replace(/[^$_a-zA-Z0-9]/g, "_");
  1255. if (/\d/.test(identifier[0]) || forbiddenIdentifiers.has(identifier)) identifier = `_${identifier}`;
  1256. return identifier || "_";
  1257. };
  1258. function stringify(obj) {
  1259. return (JSON.stringify(obj) || "undefined").replace(/[\u2028\u2029]/g, (char) => `\\u${`000${char.charCodeAt(0).toString(16)}`.slice(-4)}`);
  1260. }
  1261. function serializeArray(arr, indent, baseIndent) {
  1262. let output = "[";
  1263. const separator = indent ? `\n${baseIndent}${indent}` : "";
  1264. for (let i = 0; i < arr.length; i++) {
  1265. const key = arr[i];
  1266. output += `${i > 0 ? "," : ""}${separator}${serialize(key, indent, baseIndent + indent)}`;
  1267. }
  1268. return `${output}${indent ? `\n${baseIndent}` : ""}]`;
  1269. }
  1270. function serializeObject(obj, indent, baseIndent) {
  1271. let output = "{";
  1272. const separator = indent ? `\n${baseIndent}${indent}` : "";
  1273. const entries = Object.entries(obj);
  1274. for (let i = 0; i < entries.length; i++) {
  1275. const [key, value] = entries[i];
  1276. const stringKey = makeLegalIdentifier(key) === key ? key : stringify(key);
  1277. output += `${i > 0 ? "," : ""}${separator}${stringKey}:${indent ? " " : ""}${serialize(value, indent, baseIndent + indent)}`;
  1278. }
  1279. return `${output}${indent ? `\n${baseIndent}` : ""}}`;
  1280. }
  1281. function serialize(obj, indent, baseIndent) {
  1282. if (typeof obj === "object" && obj !== null) {
  1283. if (Array.isArray(obj)) return serializeArray(obj, indent, baseIndent);
  1284. if (obj instanceof Date) return `new Date(${obj.getTime()})`;
  1285. if (obj instanceof RegExp) return obj.toString();
  1286. return serializeObject(obj, indent, baseIndent);
  1287. }
  1288. if (typeof obj === "number") {
  1289. if (obj === Infinity) return "Infinity";
  1290. if (obj === -Infinity) return "-Infinity";
  1291. if (obj === 0) return 1 / obj === Infinity ? "0" : "-0";
  1292. if (obj !== obj) return "NaN";
  1293. }
  1294. if (typeof obj === "symbol") {
  1295. const key = Symbol.keyFor(obj);
  1296. if (key !== void 0) return `Symbol.for(${stringify(key)})`;
  1297. }
  1298. if (typeof obj === "bigint") return `${obj}n`;
  1299. return stringify(obj);
  1300. }
  1301. const hasStringIsWellFormed = "isWellFormed" in String.prototype;
  1302. function isWellFormedString(input) {
  1303. if (hasStringIsWellFormed) return input.isWellFormed();
  1304. return !/\p{Surrogate}/u.test(input);
  1305. }
  1306. const dataToEsm = function dataToEsm(data, options = {}) {
  1307. var _a, _b;
  1308. const t = options.compact ? "" : "indent" in options ? options.indent : " ";
  1309. const _ = options.compact ? "" : " ";
  1310. const n = options.compact ? "" : "\n";
  1311. const declarationType = options.preferConst ? "const" : "var";
  1312. if (options.namedExports === false || typeof data !== "object" || Array.isArray(data) || data instanceof Date || data instanceof RegExp || data === null) {
  1313. const code = serialize(data, options.compact ? null : t, "");
  1314. return `export default${_ || (/^[{[\-\/]/.test(code) ? "" : " ")}${code};`;
  1315. }
  1316. let maxUnderbarPrefixLength = 0;
  1317. for (const key of Object.keys(data)) {
  1318. const underbarPrefixLength = (_b = (_a = /^(_+)/.exec(key)) === null || _a === void 0 ? void 0 : _a[0].length) !== null && _b !== void 0 ? _b : 0;
  1319. if (underbarPrefixLength > maxUnderbarPrefixLength) maxUnderbarPrefixLength = underbarPrefixLength;
  1320. }
  1321. const arbitraryNamePrefix = `${"_".repeat(maxUnderbarPrefixLength + 1)}arbitrary`;
  1322. let namedExportCode = "";
  1323. const defaultExportRows = [];
  1324. const arbitraryNameExportRows = [];
  1325. for (const [key, value] of Object.entries(data)) if (key === makeLegalIdentifier(key)) {
  1326. if (options.objectShorthand) defaultExportRows.push(key);
  1327. else defaultExportRows.push(`${key}:${_}${key}`);
  1328. namedExportCode += `export ${declarationType} ${key}${_}=${_}${serialize(value, options.compact ? null : t, "")};${n}`;
  1329. } else {
  1330. defaultExportRows.push(`${stringify(key)}:${_}${serialize(value, options.compact ? null : t, "")}`);
  1331. if (options.includeArbitraryNames && isWellFormedString(key)) {
  1332. const variableName = `${arbitraryNamePrefix}${arbitraryNameExportRows.length}`;
  1333. namedExportCode += `${declarationType} ${variableName}${_}=${_}${serialize(value, options.compact ? null : t, "")};${n}`;
  1334. arbitraryNameExportRows.push(`${variableName} as ${JSON.stringify(key)}`);
  1335. }
  1336. }
  1337. const arbitraryExportCode = arbitraryNameExportRows.length > 0 ? `export${_}{${n}${t}${arbitraryNameExportRows.join(`,${n}${t}`)}${n}};${n}` : "";
  1338. const defaultExportCode = `export default${_}{${n}${t}${defaultExportRows.join(`,${n}${t}`)}${n}};${n}`;
  1339. return `${namedExportCode}${arbitraryExportCode}${defaultExportCode}`;
  1340. };
  1341. //#endregion
  1342. //#region src/shared/builtin.ts
  1343. function createIsBuiltin(builtins) {
  1344. const plainBuiltinsSet = new Set(builtins.filter((builtin) => typeof builtin === "string"));
  1345. const regexBuiltins = builtins.filter((builtin) => typeof builtin !== "string");
  1346. return (id) => plainBuiltinsSet.has(id) || regexBuiltins.some((regexp) => regexp.test(id));
  1347. }
  1348. //#endregion
  1349. //#region src/node/packages.ts
  1350. let pnp;
  1351. if (process.versions.pnp) try {
  1352. pnp = createRequire(
  1353. /** #__KEEP__ */
  1354. import.meta.url
  1355. )("pnpapi");
  1356. } catch {}
  1357. function invalidatePackageData(packageCache, pkgPath) {
  1358. const pkgDir = normalizePath(path.dirname(pkgPath));
  1359. packageCache.forEach((pkg, cacheKey) => {
  1360. if (pkg.dir === pkgDir) packageCache.delete(cacheKey);
  1361. });
  1362. }
  1363. function resolvePackageData(pkgName, basedir, preserveSymlinks = false, packageCache) {
  1364. if (pnp) {
  1365. const cacheKey = getRpdCacheKey(pkgName, basedir, preserveSymlinks);
  1366. if (packageCache?.has(cacheKey)) return packageCache.get(cacheKey);
  1367. try {
  1368. const pkg = pnp.resolveToUnqualified(pkgName, basedir, { considerBuiltins: false });
  1369. if (!pkg) return null;
  1370. const pkgData = loadPackageData(path.join(pkg, "package.json"));
  1371. packageCache?.set(cacheKey, pkgData);
  1372. return pkgData;
  1373. } catch {
  1374. return null;
  1375. }
  1376. }
  1377. const originalBasedir = basedir;
  1378. while (basedir) {
  1379. if (packageCache) {
  1380. const cached = getRpdCache(packageCache, pkgName, basedir, originalBasedir, preserveSymlinks);
  1381. if (cached) return cached;
  1382. }
  1383. const pkg = path.join(basedir, "node_modules", pkgName, "package.json");
  1384. try {
  1385. if (fs.existsSync(pkg)) {
  1386. const pkgData = loadPackageData(preserveSymlinks ? pkg : safeRealpathSync(pkg));
  1387. if (packageCache) setRpdCache(packageCache, pkgData, pkgName, basedir, originalBasedir, preserveSymlinks);
  1388. return pkgData;
  1389. }
  1390. } catch {}
  1391. const nextBasedir = path.dirname(basedir);
  1392. if (nextBasedir === basedir) break;
  1393. basedir = nextBasedir;
  1394. }
  1395. return null;
  1396. }
  1397. function findNearestPackageData(basedir, packageCache) {
  1398. const originalBasedir = basedir;
  1399. while (basedir) {
  1400. if (packageCache) {
  1401. const cached = getFnpdCache(packageCache, basedir, originalBasedir);
  1402. if (cached) return cached;
  1403. }
  1404. const pkgPath = path.join(basedir, "package.json");
  1405. if (tryStatSync(pkgPath)?.isFile()) try {
  1406. const pkgData = loadPackageData(pkgPath);
  1407. if (packageCache) setFnpdCache(packageCache, pkgData, basedir, originalBasedir);
  1408. return pkgData;
  1409. } catch {}
  1410. const nextBasedir = path.dirname(basedir);
  1411. if (nextBasedir === basedir) break;
  1412. basedir = nextBasedir;
  1413. }
  1414. return null;
  1415. }
  1416. function findNearestMainPackageData(basedir, packageCache) {
  1417. const nearestPackage = findNearestPackageData(basedir, packageCache);
  1418. return nearestPackage && (nearestPackage.data.name ? nearestPackage : findNearestMainPackageData(path.dirname(nearestPackage.dir), packageCache));
  1419. }
  1420. function loadPackageData(pkgPath) {
  1421. const data = JSON.parse(stripBomTag(fs.readFileSync(pkgPath, "utf-8")));
  1422. const pkgDir = normalizePath(path.dirname(pkgPath));
  1423. const { sideEffects } = data;
  1424. let hasSideEffects;
  1425. if (typeof sideEffects === "boolean") hasSideEffects = () => sideEffects;
  1426. else if (Array.isArray(sideEffects)) if (sideEffects.length <= 0) hasSideEffects = () => false;
  1427. else hasSideEffects = createFilter$1(sideEffects.map((sideEffect) => {
  1428. if (sideEffect.includes("/")) return sideEffect;
  1429. return `**/${sideEffect}`;
  1430. }), null, { resolve: pkgDir });
  1431. else hasSideEffects = () => null;
  1432. const resolvedCache = {};
  1433. return {
  1434. dir: pkgDir,
  1435. data,
  1436. hasSideEffects,
  1437. setResolvedCache(key, entry, options) {
  1438. resolvedCache[getResolveCacheKey(key, options)] = entry;
  1439. },
  1440. getResolvedCache(key, options) {
  1441. return resolvedCache[getResolveCacheKey(key, options)];
  1442. }
  1443. };
  1444. }
  1445. function getResolveCacheKey(key, options) {
  1446. return [
  1447. key,
  1448. options.isRequire ? "1" : "0",
  1449. options.conditions.join("_"),
  1450. options.extensions.join("_"),
  1451. options.mainFields.join("_")
  1452. ].join("|");
  1453. }
  1454. function findNearestNodeModules(basedir) {
  1455. while (basedir) {
  1456. const pkgPath = path.join(basedir, "node_modules");
  1457. if (tryStatSync(pkgPath)?.isDirectory()) return pkgPath;
  1458. const nextBasedir = path.dirname(basedir);
  1459. if (nextBasedir === basedir) break;
  1460. basedir = nextBasedir;
  1461. }
  1462. return null;
  1463. }
  1464. function watchPackageDataPlugin(packageCache) {
  1465. const watchQueue = /* @__PURE__ */ new Set();
  1466. const watchedDirs = /* @__PURE__ */ new Set();
  1467. const watchFileStub = (id) => {
  1468. watchQueue.add(id);
  1469. };
  1470. let watchFile = watchFileStub;
  1471. const setPackageData = packageCache.set.bind(packageCache);
  1472. packageCache.set = (id, pkg) => {
  1473. if (!isInNodeModules(pkg.dir) && !watchedDirs.has(pkg.dir)) {
  1474. watchedDirs.add(pkg.dir);
  1475. watchFile(path.join(pkg.dir, "package.json"));
  1476. }
  1477. return setPackageData(id, pkg);
  1478. };
  1479. return {
  1480. name: "vite:watch-package-data",
  1481. buildStart() {
  1482. watchFile = this.addWatchFile.bind(this);
  1483. watchQueue.forEach(watchFile);
  1484. watchQueue.clear();
  1485. },
  1486. buildEnd() {
  1487. watchFile = watchFileStub;
  1488. },
  1489. watchChange(id) {
  1490. if (id.endsWith("/package.json")) invalidatePackageData(packageCache, path.normalize(id));
  1491. }
  1492. };
  1493. }
  1494. /**
  1495. * Get cached `resolvePackageData` value based on `basedir`. When one is found,
  1496. * and we've already traversed some directories between `basedir` and `originalBasedir`,
  1497. * we cache the value for those in-between directories as well.
  1498. *
  1499. * This makes it so the fs is only read once for a shared `basedir`.
  1500. */
  1501. function getRpdCache(packageCache, pkgName, basedir, originalBasedir, preserveSymlinks) {
  1502. const cacheKey = getRpdCacheKey(pkgName, basedir, preserveSymlinks);
  1503. const pkgData = packageCache.get(cacheKey);
  1504. if (pkgData) {
  1505. traverseBetweenDirs(originalBasedir, basedir, (dir) => {
  1506. packageCache.set(getRpdCacheKey(pkgName, dir, preserveSymlinks), pkgData);
  1507. });
  1508. return pkgData;
  1509. }
  1510. }
  1511. function setRpdCache(packageCache, pkgData, pkgName, basedir, originalBasedir, preserveSymlinks) {
  1512. packageCache.set(getRpdCacheKey(pkgName, basedir, preserveSymlinks), pkgData);
  1513. traverseBetweenDirs(originalBasedir, basedir, (dir) => {
  1514. packageCache.set(getRpdCacheKey(pkgName, dir, preserveSymlinks), pkgData);
  1515. });
  1516. }
  1517. function getRpdCacheKey(pkgName, basedir, preserveSymlinks) {
  1518. return `rpd_${pkgName}_${basedir}_${preserveSymlinks}`;
  1519. }
  1520. /**
  1521. * Get cached `findNearestPackageData` value based on `basedir`. When one is found,
  1522. * and we've already traversed some directories between `basedir` and `originalBasedir`,
  1523. * we cache the value for those in-between directories as well.
  1524. *
  1525. * This makes it so the fs is only read once for a shared `basedir`.
  1526. */
  1527. function getFnpdCache(packageCache, basedir, originalBasedir) {
  1528. const cacheKey = getFnpdCacheKey(basedir);
  1529. const pkgData = packageCache.get(cacheKey);
  1530. if (pkgData) {
  1531. traverseBetweenDirs(originalBasedir, basedir, (dir) => {
  1532. packageCache.set(getFnpdCacheKey(dir), pkgData);
  1533. });
  1534. return pkgData;
  1535. }
  1536. }
  1537. function setFnpdCache(packageCache, pkgData, basedir, originalBasedir) {
  1538. packageCache.set(getFnpdCacheKey(basedir), pkgData);
  1539. traverseBetweenDirs(originalBasedir, basedir, (dir) => {
  1540. packageCache.set(getFnpdCacheKey(dir), pkgData);
  1541. });
  1542. }
  1543. function getFnpdCacheKey(basedir) {
  1544. return `fnpd_${basedir}`;
  1545. }
  1546. /**
  1547. * Traverse between `longerDir` (inclusive) and `shorterDir` (exclusive) and call `cb` for each dir.
  1548. * @param longerDir Longer dir path, e.g. `/User/foo/bar/baz`
  1549. * @param shorterDir Shorter dir path, e.g. `/User/foo`
  1550. */
  1551. function traverseBetweenDirs(longerDir, shorterDir, cb) {
  1552. while (longerDir !== shorterDir) {
  1553. cb(longerDir);
  1554. longerDir = path.dirname(longerDir);
  1555. }
  1556. }
  1557. //#endregion
  1558. //#region src/node/utils.ts
  1559. var import_picocolors = /* @__PURE__ */ __toESM(require_picocolors(), 1);
  1560. init_node();
  1561. const createFilter$1 = createFilter$2;
  1562. const replaceSlashOrColonRE = /[/:]/g;
  1563. const replaceDotRE = /\./g;
  1564. const replaceNestedIdRE = /\s*>\s*/g;
  1565. const replaceHashRE = /#/g;
  1566. const replacePlusRE = /\+/g;
  1567. const flattenId = (id) => {
  1568. return limitFlattenIdLength(id.replace(replaceSlashOrColonRE, "_").replace(replaceDotRE, "__").replace(replaceNestedIdRE, "___").replace(replaceHashRE, "____").replace(replacePlusRE, "_____"));
  1569. };
  1570. const FLATTEN_ID_HASH_LENGTH = 8;
  1571. const FLATTEN_ID_MAX_FILE_LENGTH = 170;
  1572. const limitFlattenIdLength = (id, limit = FLATTEN_ID_MAX_FILE_LENGTH) => {
  1573. if (id.length <= limit) return id;
  1574. return id.slice(0, limit - (FLATTEN_ID_HASH_LENGTH + 1)) + "_" + getHash(id);
  1575. };
  1576. const normalizeId = (id) => id.replace(replaceNestedIdRE, " > ");
  1577. const NODE_BUILTIN_NAMESPACE = "node:";
  1578. const BUN_BUILTIN_NAMESPACE = "bun:";
  1579. const nodeBuiltins = builtinModules.filter((id) => !id.includes(":"));
  1580. const isBuiltinCache = /* @__PURE__ */ new WeakMap();
  1581. function isBuiltin(builtins, id) {
  1582. let isBuiltin = isBuiltinCache.get(builtins);
  1583. if (!isBuiltin) {
  1584. isBuiltin = createIsBuiltin(builtins);
  1585. isBuiltinCache.set(builtins, isBuiltin);
  1586. }
  1587. return isBuiltin(id);
  1588. }
  1589. const nodeLikeBuiltins = [
  1590. ...nodeBuiltins,
  1591. new RegExp(`^${NODE_BUILTIN_NAMESPACE}`),
  1592. new RegExp(`^${BUN_BUILTIN_NAMESPACE}`)
  1593. ];
  1594. function isNodeLikeBuiltin(id) {
  1595. return isBuiltin(nodeLikeBuiltins, id);
  1596. }
  1597. function isNodeBuiltin(id) {
  1598. if (id.startsWith(NODE_BUILTIN_NAMESPACE)) return true;
  1599. return nodeBuiltins.includes(id);
  1600. }
  1601. function isInNodeModules(id) {
  1602. return id.includes("node_modules");
  1603. }
  1604. function moduleListContains(moduleList, id) {
  1605. return moduleList?.some((m) => m === id || id.startsWith(withTrailingSlash(m)));
  1606. }
  1607. function isOptimizable(id, optimizeDeps) {
  1608. const { extensions } = optimizeDeps;
  1609. return OPTIMIZABLE_ENTRY_RE.test(id) || (extensions?.some((ext) => id.endsWith(ext)) ?? false);
  1610. }
  1611. const bareImportRE = /^(?![a-zA-Z]:)[\w@](?!.*:\/\/)/;
  1612. const deepImportRE = /^([^@][^/]*)\/|^(@[^/]+\/[^/]+)\//;
  1613. const _dirname = path.dirname(fileURLToPath(
  1614. /** #__KEEP__ */
  1615. import.meta.url
  1616. ));
  1617. const rollupVersion = "4.23.0";
  1618. const filter = process.env.VITE_DEBUG_FILTER;
  1619. const DEBUG = process.env.DEBUG;
  1620. function createDebugger(namespace, options = {}) {
  1621. const log = node_default(namespace);
  1622. const { onlyWhenFocused, depth } = options;
  1623. if (depth && log.inspectOpts && log.inspectOpts.depth == null) log.inspectOpts.depth = options.depth;
  1624. let enabled = log.enabled;
  1625. if (enabled && onlyWhenFocused) enabled = !!DEBUG?.includes(typeof onlyWhenFocused === "string" ? onlyWhenFocused : namespace);
  1626. if (enabled) return (...args) => {
  1627. if (!filter || args.some((a) => a?.includes?.(filter))) log(...args);
  1628. };
  1629. }
  1630. function testCaseInsensitiveFS() {
  1631. if (!CLIENT_ENTRY.endsWith("client.mjs")) throw new Error(`cannot test case insensitive FS, CLIENT_ENTRY const doesn't contain client.mjs`);
  1632. if (!fs.existsSync(CLIENT_ENTRY)) throw new Error("cannot test case insensitive FS, CLIENT_ENTRY does not point to an existing file: " + CLIENT_ENTRY);
  1633. return fs.existsSync(CLIENT_ENTRY.replace("client.mjs", "cLiEnT.mjs"));
  1634. }
  1635. const isCaseInsensitiveFS = testCaseInsensitiveFS();
  1636. const VOLUME_RE = /^[A-Z]:/i;
  1637. function normalizePath(id) {
  1638. return path.posix.normalize(isWindows ? slash(id) : id);
  1639. }
  1640. function fsPathFromId(id) {
  1641. const fsPath = normalizePath(id.startsWith(FS_PREFIX) ? id.slice(FS_PREFIX.length) : id);
  1642. return fsPath[0] === "/" || VOLUME_RE.test(fsPath) ? fsPath : `/${fsPath}`;
  1643. }
  1644. function fsPathFromUrl(url) {
  1645. return fsPathFromId(cleanUrl(url));
  1646. }
  1647. /**
  1648. * Check if dir is a parent of file
  1649. *
  1650. * Warning: parameters are not validated, only works with normalized absolute paths
  1651. *
  1652. * @param dir - normalized absolute path
  1653. * @param file - normalized absolute path
  1654. * @returns true if dir is a parent of file
  1655. */
  1656. function isParentDirectory(dir, file) {
  1657. dir = withTrailingSlash(dir);
  1658. return file.startsWith(dir) || isCaseInsensitiveFS && file.toLowerCase().startsWith(dir.toLowerCase());
  1659. }
  1660. /**
  1661. * Check if 2 file name are identical
  1662. *
  1663. * Warning: parameters are not validated, only works with normalized absolute paths
  1664. *
  1665. * @param file1 - normalized absolute path
  1666. * @param file2 - normalized absolute path
  1667. * @returns true if both files url are identical
  1668. */
  1669. function isSameFilePath(file1, file2) {
  1670. return file1 === file2 || isCaseInsensitiveFS && file1.toLowerCase() === file2.toLowerCase();
  1671. }
  1672. const externalRE = /^([a-z]+:)?\/\//;
  1673. const isExternalUrl = (url) => externalRE.test(url);
  1674. const dataUrlRE = /^\s*data:/i;
  1675. const isDataUrl = (url) => dataUrlRE.test(url);
  1676. const virtualModuleRE = /^virtual-module:.*/;
  1677. const virtualModulePrefix = "virtual-module:";
  1678. const knownJsSrcRE = /\.(?:[jt]sx?|m[jt]s|vue|marko|svelte|astro|imba|mdx)(?:$|\?)/;
  1679. const isJSRequest = (url) => {
  1680. url = cleanUrl(url);
  1681. if (knownJsSrcRE.test(url)) return true;
  1682. if (!path.extname(url) && url[url.length - 1] !== "/") return true;
  1683. return false;
  1684. };
  1685. const isCSSRequest = (request) => CSS_LANGS_RE.test(request);
  1686. const importQueryRE = /(\?|&)import=?(?:&|$)/;
  1687. const directRequestRE$1 = /(\?|&)direct=?(?:&|$)/;
  1688. const InternalPrefixRE = new RegExp(`^(?:${[
  1689. FS_PREFIX,
  1690. VALID_ID_PREFIX,
  1691. CLIENT_PUBLIC_PATH,
  1692. ENV_PUBLIC_PATH
  1693. ].join("|")})`);
  1694. const trailingSeparatorRE = /[?&]$/;
  1695. const isImportRequest = (url) => importQueryRE.test(url);
  1696. const isInternalRequest = (url) => InternalPrefixRE.test(url);
  1697. function removeImportQuery(url) {
  1698. return url.replace(importQueryRE, "$1").replace(trailingSeparatorRE, "");
  1699. }
  1700. function removeDirectQuery(url) {
  1701. return url.replace(directRequestRE$1, "$1").replace(trailingSeparatorRE, "");
  1702. }
  1703. const urlRE$1 = /(\?|&)url(?:&|$)/;
  1704. const rawRE$1 = /(\?|&)raw(?:&|$)/;
  1705. function removeUrlQuery(url) {
  1706. return url.replace(urlRE$1, "$1").replace(trailingSeparatorRE, "");
  1707. }
  1708. function injectQuery(url, queryToInject) {
  1709. const { file, postfix } = splitFileAndPostfix(url);
  1710. return `${isWindows ? slash(file) : file}?${queryToInject}${postfix[0] === "?" ? `&${postfix.slice(1)}` : postfix}`;
  1711. }
  1712. const timestampRE = /\bt=\d{13}&?\b/;
  1713. function removeTimestampQuery(url) {
  1714. return url.replace(timestampRE, "").replace(trailingSeparatorRE, "");
  1715. }
  1716. async function asyncReplace(input, re, replacer) {
  1717. let match;
  1718. let remaining = input;
  1719. let rewritten = "";
  1720. while (match = re.exec(remaining)) {
  1721. rewritten += remaining.slice(0, match.index);
  1722. rewritten += await replacer(match);
  1723. remaining = remaining.slice(match.index + match[0].length);
  1724. }
  1725. rewritten += remaining;
  1726. return rewritten;
  1727. }
  1728. function timeFrom(start, subtract = 0) {
  1729. const time = performance$1.now() - start - subtract;
  1730. const timeString = (time.toFixed(2) + `ms`).padEnd(5, " ");
  1731. if (time < 10) return import_picocolors.default.green(timeString);
  1732. else if (time < 50) return import_picocolors.default.yellow(timeString);
  1733. else return import_picocolors.default.red(timeString);
  1734. }
  1735. /**
  1736. * pretty url for logging.
  1737. */
  1738. function prettifyUrl(url, root) {
  1739. url = removeTimestampQuery(url);
  1740. const isAbsoluteFile = url.startsWith(root);
  1741. if (isAbsoluteFile || url.startsWith(FS_PREFIX)) {
  1742. const file = path.posix.relative(root, isAbsoluteFile ? url : fsPathFromId(url));
  1743. return import_picocolors.default.dim(file);
  1744. } else return import_picocolors.default.dim(url);
  1745. }
  1746. function isObject$1(value) {
  1747. return Object.prototype.toString.call(value) === "[object Object]";
  1748. }
  1749. function isDefined(value) {
  1750. return value != null;
  1751. }
  1752. function tryStatSync(file) {
  1753. try {
  1754. return fs.statSync(file, { throwIfNoEntry: false });
  1755. } catch {}
  1756. }
  1757. function lookupFile(dir, fileNames) {
  1758. while (dir) {
  1759. for (const fileName of fileNames) {
  1760. const fullPath = path.join(dir, fileName);
  1761. if (tryStatSync(fullPath)?.isFile()) return fullPath;
  1762. }
  1763. const parentDir = path.dirname(dir);
  1764. if (parentDir === dir) return;
  1765. dir = parentDir;
  1766. }
  1767. }
  1768. function isFilePathESM(filePath, packageCache) {
  1769. if (/\.m[jt]s$/.test(filePath)) return true;
  1770. else if (/\.c[jt]s$/.test(filePath)) return false;
  1771. else try {
  1772. return findNearestPackageData(path.dirname(filePath), packageCache)?.data.type === "module";
  1773. } catch {
  1774. return false;
  1775. }
  1776. }
  1777. const splitRE = /\r?\n/g;
  1778. const range = 2;
  1779. function pad(source, n = 2) {
  1780. return source.split(splitRE).map((l) => ` `.repeat(n) + l).join(`\n`);
  1781. }
  1782. function posToNumber(source, pos) {
  1783. if (typeof pos === "number") return pos;
  1784. const lines = source.split(splitRE);
  1785. const { line, column } = pos;
  1786. let start = 0;
  1787. for (let i = 0; i < line - 1 && i < lines.length; i++) start += lines[i].length + 1;
  1788. return start + column;
  1789. }
  1790. function numberToPos(source, offset) {
  1791. if (typeof offset !== "number") return offset;
  1792. if (offset > source.length) throw new Error(`offset is longer than source length! offset ${offset} > length ${source.length}`);
  1793. const lines = source.slice(0, offset).split(splitRE);
  1794. return {
  1795. line: lines.length,
  1796. column: lines[lines.length - 1].length
  1797. };
  1798. }
  1799. const MAX_DISPLAY_LEN = 120;
  1800. const ELLIPSIS = "...";
  1801. function generateCodeFrame(source, start = 0, end) {
  1802. start = Math.max(posToNumber(source, start), 0);
  1803. end = Math.min(end !== void 0 ? posToNumber(source, end) : start, source.length);
  1804. const lastPosLine = end !== void 0 ? numberToPos(source, end).line : numberToPos(source, start).line + range;
  1805. const lineNumberWidth = Math.max(3, String(lastPosLine).length + 1);
  1806. const lines = source.split(splitRE);
  1807. let count = 0;
  1808. const res = [];
  1809. for (let i = 0; i < lines.length; i++) {
  1810. count += lines[i].length;
  1811. if (count >= start) {
  1812. for (let j = i - range; j <= i + range || end > count; j++) {
  1813. if (j < 0 || j >= lines.length) continue;
  1814. const line = j + 1;
  1815. const lineLength = lines[j].length;
  1816. const pad = Math.max(start - (count - lineLength), 0);
  1817. const underlineLength = Math.max(1, end > count ? lineLength - pad : end - start);
  1818. let displayLine = lines[j];
  1819. let underlinePad = pad;
  1820. if (lineLength > MAX_DISPLAY_LEN) {
  1821. let startIdx = 0;
  1822. if (j === i) {
  1823. if (underlineLength > MAX_DISPLAY_LEN) startIdx = pad;
  1824. else {
  1825. const center = pad + Math.floor(underlineLength / 2);
  1826. startIdx = Math.max(0, center - Math.floor(MAX_DISPLAY_LEN / 2));
  1827. }
  1828. underlinePad = Math.max(0, pad - startIdx) + (startIdx > 0 ? 3 : 0);
  1829. }
  1830. const prefix = startIdx > 0 ? ELLIPSIS : "";
  1831. const suffix = lineLength - startIdx > MAX_DISPLAY_LEN ? ELLIPSIS : "";
  1832. const sliceLen = MAX_DISPLAY_LEN - prefix.length - suffix.length;
  1833. displayLine = prefix + displayLine.slice(startIdx, startIdx + sliceLen) + suffix;
  1834. }
  1835. res.push(`${line}${" ".repeat(lineNumberWidth - String(line).length)}| ${displayLine}`);
  1836. if (j === i) {
  1837. const underline = "^".repeat(Math.min(underlineLength, MAX_DISPLAY_LEN));
  1838. res.push(`${" ".repeat(lineNumberWidth)}| ` + " ".repeat(underlinePad) + underline);
  1839. } else if (j > i) {
  1840. if (end > count) {
  1841. const length = Math.max(Math.min(end - count, lineLength), 1);
  1842. const underline = "^".repeat(Math.min(length, MAX_DISPLAY_LEN));
  1843. res.push(`${" ".repeat(lineNumberWidth)}| ` + underline);
  1844. }
  1845. count += lineLength + 1;
  1846. }
  1847. }
  1848. break;
  1849. }
  1850. count++;
  1851. }
  1852. return res.join("\n");
  1853. }
  1854. function isFileReadable(filename) {
  1855. if (!tryStatSync(filename)) return false;
  1856. try {
  1857. fs.accessSync(filename, fs.constants.R_OK);
  1858. return true;
  1859. } catch {
  1860. return false;
  1861. }
  1862. }
  1863. const splitFirstDirRE = /(.+?)[\\/](.+)/;
  1864. /**
  1865. * Delete every file and subdirectory. **The given directory must exist.**
  1866. * Pass an optional `skip` array to preserve files under the root directory.
  1867. */
  1868. function emptyDir(dir, skip) {
  1869. const skipInDir = [];
  1870. let nested = null;
  1871. if (skip?.length) for (const file of skip) if (path.dirname(file) !== ".") {
  1872. const matched = splitFirstDirRE.exec(file);
  1873. if (matched) {
  1874. nested ??= /* @__PURE__ */ new Map();
  1875. const [, nestedDir, skipPath] = matched;
  1876. let nestedSkip = nested.get(nestedDir);
  1877. if (!nestedSkip) {
  1878. nestedSkip = [];
  1879. nested.set(nestedDir, nestedSkip);
  1880. }
  1881. if (!nestedSkip.includes(skipPath)) nestedSkip.push(skipPath);
  1882. }
  1883. } else skipInDir.push(file);
  1884. for (const file of fs.readdirSync(dir)) {
  1885. if (skipInDir.includes(file)) continue;
  1886. if (nested?.has(file)) emptyDir(path.resolve(dir, file), nested.get(file));
  1887. else fs.rmSync(path.resolve(dir, file), {
  1888. recursive: true,
  1889. force: true
  1890. });
  1891. }
  1892. }
  1893. function copyDir(srcDir, destDir) {
  1894. fs.mkdirSync(destDir, { recursive: true });
  1895. for (const file of fs.readdirSync(srcDir)) {
  1896. const srcFile = path.resolve(srcDir, file);
  1897. if (srcFile === destDir) continue;
  1898. const destFile = path.resolve(destDir, file);
  1899. if (fs.statSync(srcFile).isDirectory()) copyDir(srcFile, destFile);
  1900. else fs.copyFileSync(srcFile, destFile);
  1901. }
  1902. }
  1903. const ERR_SYMLINK_IN_RECURSIVE_READDIR = "ERR_SYMLINK_IN_RECURSIVE_READDIR";
  1904. async function recursiveReaddir(dir) {
  1905. if (!fs.existsSync(dir)) return [];
  1906. let dirents;
  1907. try {
  1908. dirents = await fsp.readdir(dir, { withFileTypes: true });
  1909. } catch (e) {
  1910. if (e.code === "EACCES") return [];
  1911. throw e;
  1912. }
  1913. if (dirents.some((dirent) => dirent.isSymbolicLink())) {
  1914. const err = /* @__PURE__ */ new Error("Symbolic links are not supported in recursiveReaddir");
  1915. err.code = ERR_SYMLINK_IN_RECURSIVE_READDIR;
  1916. throw err;
  1917. }
  1918. return (await Promise.all(dirents.map((dirent) => {
  1919. const res = path.resolve(dir, dirent.name);
  1920. return dirent.isDirectory() ? recursiveReaddir(res) : normalizePath(res);
  1921. }))).flat(1);
  1922. }
  1923. let safeRealpathSync = isWindows ? windowsSafeRealPathSync : fs.realpathSync.native;
  1924. const windowsNetworkMap = /* @__PURE__ */ new Map();
  1925. function windowsMappedRealpathSync(path) {
  1926. const realPath = fs.realpathSync.native(path);
  1927. if (realPath.startsWith("\\\\")) {
  1928. for (const [network, volume] of windowsNetworkMap) if (realPath.startsWith(network)) return realPath.replace(network, volume);
  1929. }
  1930. return realPath;
  1931. }
  1932. const parseNetUseRE = /^\w* +(\w:) +([^ ]+)\s/;
  1933. let firstSafeRealPathSyncRun = false;
  1934. function windowsSafeRealPathSync(path) {
  1935. if (!firstSafeRealPathSyncRun) {
  1936. optimizeSafeRealPathSync();
  1937. firstSafeRealPathSyncRun = true;
  1938. }
  1939. return fs.realpathSync(path);
  1940. }
  1941. function optimizeSafeRealPathSync() {
  1942. try {
  1943. fs.realpathSync.native(path.resolve("./"));
  1944. } catch (error) {
  1945. if (error.message.includes("EISDIR: illegal operation on a directory")) {
  1946. safeRealpathSync = fs.realpathSync;
  1947. return;
  1948. }
  1949. }
  1950. exec("net use", (error, stdout) => {
  1951. if (error) return;
  1952. const lines = stdout.split("\n");
  1953. for (const line of lines) {
  1954. const m = parseNetUseRE.exec(line);
  1955. if (m) windowsNetworkMap.set(m[2], m[1]);
  1956. }
  1957. if (windowsNetworkMap.size === 0) safeRealpathSync = fs.realpathSync.native;
  1958. else safeRealpathSync = windowsMappedRealpathSync;
  1959. });
  1960. }
  1961. function ensureWatchedFile(watcher, file, root) {
  1962. if (file && !file.startsWith(withTrailingSlash(root)) && !file.includes("\0") && fs.existsSync(file)) watcher.add(path.resolve(file));
  1963. }
  1964. function joinSrcset(ret) {
  1965. return ret.map(({ url, descriptor }) => url + (descriptor ? ` ${descriptor}` : "")).join(", ");
  1966. }
  1967. /**
  1968. This regex represents a loose rule of an “image candidate string” and "image set options".
  1969. @see https://html.spec.whatwg.org/multipage/images.html#srcset-attribute
  1970. @see https://drafts.csswg.org/css-images-4/#image-set-notation
  1971. The Regex has named capturing groups `url` and `descriptor`.
  1972. The `url` group can be:
  1973. * any CSS function
  1974. * CSS string (single or double-quoted)
  1975. * URL string (unquoted)
  1976. The `descriptor` is anything after the space and before the comma.
  1977. */
  1978. const imageCandidateRegex = /(?:^|\s|(?<=,))(?<url>[\w-]+\([^)]*\)|"[^"]*"|'[^']*'|[^,]\S*[^,])\s*(?:\s(?<descriptor>\w[^,]+))?(?:,|$)/g;
  1979. const escapedSpaceCharacters = /(?: |\\t|\\n|\\f|\\r)+/g;
  1980. function parseSrcset(string) {
  1981. const matches = string.trim().replace(escapedSpaceCharacters, " ").replace(/\r?\n/, "").replace(/,\s+/, ", ").replaceAll(/\s+/g, " ").matchAll(imageCandidateRegex);
  1982. return Array.from(matches, ({ groups }) => ({
  1983. url: groups?.url?.trim() ?? "",
  1984. descriptor: groups?.descriptor?.trim() ?? ""
  1985. })).filter(({ url }) => !!url);
  1986. }
  1987. function processSrcSet(srcs, replacer) {
  1988. return Promise.all(parseSrcset(srcs).map(async ({ url, descriptor }) => ({
  1989. url: await replacer({
  1990. url,
  1991. descriptor
  1992. }),
  1993. descriptor
  1994. }))).then(joinSrcset);
  1995. }
  1996. function processSrcSetSync(srcs, replacer) {
  1997. return joinSrcset(parseSrcset(srcs).map(({ url, descriptor }) => ({
  1998. url: replacer({
  1999. url,
  2000. descriptor
  2001. }),
  2002. descriptor
  2003. })));
  2004. }
  2005. const windowsDriveRE = /^[A-Z]:/;
  2006. const replaceWindowsDriveRE = /^([A-Z]):\//;
  2007. const linuxAbsolutePathRE = /^\/[^/]/;
  2008. function escapeToLinuxLikePath(path) {
  2009. if (windowsDriveRE.test(path)) return path.replace(replaceWindowsDriveRE, "/windows/$1/");
  2010. if (linuxAbsolutePathRE.test(path)) return `/linux${path}`;
  2011. return path;
  2012. }
  2013. const revertWindowsDriveRE = /^\/windows\/([A-Z])\//;
  2014. function unescapeToLinuxLikePath(path) {
  2015. if (path.startsWith("/linux/")) return path.slice(6);
  2016. if (path.startsWith("/windows/")) return path.replace(revertWindowsDriveRE, "$1:/");
  2017. return path;
  2018. }
  2019. const nullSourceMap = {
  2020. names: [],
  2021. sources: [],
  2022. mappings: "",
  2023. version: 3
  2024. };
  2025. /**
  2026. * Combines multiple sourcemaps into a single sourcemap.
  2027. * Note that the length of sourcemapList must be 2.
  2028. */
  2029. function combineSourcemaps(filename, sourcemapList) {
  2030. if (sourcemapList.length === 0 || sourcemapList.every((m) => m.sources.length === 0)) return { ...nullSourceMap };
  2031. sourcemapList = sourcemapList.map((sourcemap) => {
  2032. const newSourcemaps = { ...sourcemap };
  2033. newSourcemaps.sources = sourcemap.sources.map((source) => source ? escapeToLinuxLikePath(source) : null);
  2034. if (sourcemap.sourceRoot) newSourcemaps.sourceRoot = escapeToLinuxLikePath(sourcemap.sourceRoot);
  2035. return newSourcemaps;
  2036. });
  2037. const escapedFilename = escapeToLinuxLikePath(filename);
  2038. let map;
  2039. let mapIndex = 1;
  2040. if (sourcemapList.slice(0, -1).find((m) => m.sources.length !== 1) === void 0) map = remapping(sourcemapList, () => null);
  2041. else map = remapping(sourcemapList[0], function loader(sourcefile) {
  2042. if (sourcefile === escapedFilename && sourcemapList[mapIndex]) return sourcemapList[mapIndex++];
  2043. else return null;
  2044. });
  2045. if (!map.file) delete map.file;
  2046. map.sources = map.sources.map((source) => source ? unescapeToLinuxLikePath(source) : source);
  2047. map.file = filename;
  2048. return map;
  2049. }
  2050. function unique(arr) {
  2051. return Array.from(new Set(arr));
  2052. }
  2053. /**
  2054. * Returns resolved localhost address when `dns.lookup` result differs from DNS
  2055. *
  2056. * `dns.lookup` result is same when defaultResultOrder is `verbatim`.
  2057. * Even if defaultResultOrder is `ipv4first`, `dns.lookup` result maybe same.
  2058. * For example, when IPv6 is not supported on that machine/network.
  2059. */
  2060. function getLocalhostAddressIfDiffersFromDNS() {
  2061. if (promises.getDefaultResultOrder && promises.getDefaultResultOrder() === "verbatim") return;
  2062. return Promise.all([promises.lookup("localhost"), promises.lookup("localhost", { verbatim: true })]).then(([nodeResult, dnsResult]) => {
  2063. return nodeResult.family === dnsResult.family && nodeResult.address === dnsResult.address ? void 0 : nodeResult.address;
  2064. });
  2065. }
  2066. function diffDnsOrderChange(oldUrls, newUrls) {
  2067. return !(oldUrls === newUrls || oldUrls && newUrls && arrayEqual(oldUrls.local, newUrls.local) && arrayEqual(oldUrls.network, newUrls.network));
  2068. }
  2069. async function resolveHostname(optionsHost) {
  2070. let host;
  2071. if (optionsHost === void 0 || optionsHost === false) host = "localhost";
  2072. else if (optionsHost === true) host = void 0;
  2073. else host = optionsHost;
  2074. let name = host === void 0 || wildcardHosts.has(host) ? "localhost" : host;
  2075. if (host === "localhost") {
  2076. const localhostAddr = await getLocalhostAddressIfDiffersFromDNS();
  2077. if (localhostAddr) name = localhostAddr;
  2078. }
  2079. return {
  2080. host,
  2081. name
  2082. };
  2083. }
  2084. function extractHostnamesFromCerts(certs) {
  2085. const certList = certs ? arraify(certs) : [];
  2086. if (certList.length === 0) return [];
  2087. return unique(certList.map((cert) => {
  2088. try {
  2089. return new crypto.X509Certificate(cert);
  2090. } catch {
  2091. return null;
  2092. }
  2093. }).flatMap((cert) => cert?.subjectAltName ? extractHostnamesFromSubjectAltName(cert.subjectAltName) : []));
  2094. }
  2095. function resolveServerUrls(server, options, hostname, httpsOptions, config) {
  2096. const address = server.address();
  2097. const isAddressInfo = (x) => x?.address;
  2098. if (!isAddressInfo(address)) return {
  2099. local: [],
  2100. network: []
  2101. };
  2102. const local = [];
  2103. const network = [];
  2104. const protocol = options.https ? "https" : "http";
  2105. const port = address.port;
  2106. const base = config.rawBase === "./" || config.rawBase === "" ? "/" : config.rawBase;
  2107. if (hostname.host !== void 0 && !wildcardHosts.has(hostname.host)) {
  2108. let hostnameName = hostname.name;
  2109. if (hostnameName.includes(":")) hostnameName = `[${hostnameName}]`;
  2110. const address = `${protocol}://${hostnameName}:${port}${base}`;
  2111. if (loopbackHosts.has(hostname.host)) local.push(address);
  2112. else network.push(address);
  2113. } else Object.values(os.networkInterfaces()).flatMap((nInterface) => nInterface ?? []).filter((detail) => detail.address && detail.family === "IPv4").forEach((detail) => {
  2114. let host = detail.address.replace("127.0.0.1", hostname.name);
  2115. if (host.includes(":")) host = `[${host}]`;
  2116. const url = `${protocol}://${host}:${port}${base}`;
  2117. if (detail.address.includes("127.0.0.1")) local.push(url);
  2118. else network.push(url);
  2119. });
  2120. const hostnamesFromCert = extractHostnamesFromCerts(httpsOptions?.cert);
  2121. if (hostnamesFromCert.length > 0) {
  2122. const existings = new Set([...local, ...network]);
  2123. local.push(...hostnamesFromCert.map((hostname) => `${protocol}://${hostname}:${port}${base}`).filter((url) => !existings.has(url)));
  2124. }
  2125. return {
  2126. local,
  2127. network
  2128. };
  2129. }
  2130. function extractHostnamesFromSubjectAltName(subjectAltName) {
  2131. const hostnames = [];
  2132. let remaining = subjectAltName;
  2133. while (remaining) {
  2134. const nameEndIndex = remaining.indexOf(":");
  2135. const name = remaining.slice(0, nameEndIndex);
  2136. remaining = remaining.slice(nameEndIndex + 1);
  2137. if (!remaining) break;
  2138. const isQuoted = remaining[0] === "\"";
  2139. let value;
  2140. if (isQuoted) {
  2141. const endQuoteIndex = remaining.indexOf("\"", 1);
  2142. value = JSON.parse(remaining.slice(0, endQuoteIndex + 1));
  2143. remaining = remaining.slice(endQuoteIndex + 1);
  2144. } else {
  2145. const maybeEndIndex = remaining.indexOf(",");
  2146. const endIndex = maybeEndIndex === -1 ? remaining.length : maybeEndIndex;
  2147. value = remaining.slice(0, endIndex);
  2148. remaining = remaining.slice(endIndex);
  2149. }
  2150. remaining = remaining.slice(1).trimStart();
  2151. if (name === "DNS" && value !== "[::1]" && !(value.startsWith("*.") && net.isIPv4(value.slice(2)))) hostnames.push(value.replace("*", "vite"));
  2152. }
  2153. return hostnames;
  2154. }
  2155. function arraify(target) {
  2156. return Array.isArray(target) ? target : [target];
  2157. }
  2158. const multilineCommentsRE = /\/\*[^*]*\*+(?:[^/*][^*]*\*+)*\//g;
  2159. const singlelineCommentsRE = /\/\/.*/g;
  2160. const requestQuerySplitRE = /\?(?!.*[/|}])/;
  2161. const requestQueryMaybeEscapedSplitRE = /\\?\?(?!.*[/|}])/;
  2162. const blankReplacer = (match) => " ".repeat(match.length);
  2163. function getHash(text, length = 8) {
  2164. const h = crypto.hash("sha256", text, "hex").substring(0, length);
  2165. if (length <= 64) return h;
  2166. return h.padEnd(length, "_");
  2167. }
  2168. function emptyCssComments(raw) {
  2169. return raw.replace(multilineCommentsRE, blankReplacer);
  2170. }
  2171. function backwardCompatibleWorkerPlugins(plugins) {
  2172. if (Array.isArray(plugins)) return plugins;
  2173. if (typeof plugins === "function") return plugins();
  2174. return [];
  2175. }
  2176. function deepClone(value) {
  2177. if (Array.isArray(value)) return value.map((v) => deepClone(v));
  2178. if (isObject$1(value)) {
  2179. const cloned = {};
  2180. for (const key in value) cloned[key] = deepClone(value[key]);
  2181. return cloned;
  2182. }
  2183. if (typeof value === "function") return value;
  2184. if (value instanceof RegExp) return new RegExp(value);
  2185. if (typeof value === "object" && value != null) throw new Error("Cannot deep clone non-plain object");
  2186. return value;
  2187. }
  2188. function mergeWithDefaultsRecursively(defaults, values) {
  2189. const merged = defaults;
  2190. for (const key in values) {
  2191. const value = values[key];
  2192. if (value === void 0) continue;
  2193. const existing = merged[key];
  2194. if (existing === void 0) {
  2195. merged[key] = value;
  2196. continue;
  2197. }
  2198. if (isObject$1(existing) && isObject$1(value)) {
  2199. merged[key] = mergeWithDefaultsRecursively(existing, value);
  2200. continue;
  2201. }
  2202. merged[key] = value;
  2203. }
  2204. return merged;
  2205. }
  2206. const environmentPathRE = /^environments\.[^.]+$/;
  2207. function mergeWithDefaults(defaults, values) {
  2208. return mergeWithDefaultsRecursively(deepClone(defaults), values);
  2209. }
  2210. const runtimeDeprecatedPath = new Set(["optimizeDeps", "ssr.optimizeDeps"]);
  2211. const rollupOptionsDeprecationCall = () => {
  2212. const method = process.env.VITE_DEPRECATION_TRACE ? "trace" : "warn";
  2213. console[method]("`optimizeDeps.rollupOptions` / `ssr.optimizeDeps.rollupOptions` is deprecated. Use `optimizeDeps.rolldownOptions` instead. Note that this option may be set by a plugin. " + (method === "trace" ? "Showing trace because VITE_DEPRECATION_TRACE is set." : "Set VITE_DEPRECATION_TRACE=1 to see where it is called."));
  2214. };
  2215. function setupRollupOptionCompat(buildConfig, path) {
  2216. buildConfig.rolldownOptions ??= buildConfig.rollupOptions;
  2217. if (runtimeDeprecatedPath.has(path) && buildConfig.rollupOptions && buildConfig.rolldownOptions !== buildConfig.rollupOptions) rollupOptionsDeprecationCall();
  2218. Object.defineProperty(buildConfig, "rollupOptions", {
  2219. get() {
  2220. return buildConfig.rolldownOptions;
  2221. },
  2222. set(newValue) {
  2223. if (runtimeDeprecatedPath.has(path)) rollupOptionsDeprecationCall();
  2224. buildConfig.rolldownOptions = newValue;
  2225. },
  2226. configurable: true,
  2227. enumerable: true
  2228. });
  2229. }
  2230. const rollupOptionsRootPaths = new Set([
  2231. "build",
  2232. "worker",
  2233. "optimizeDeps",
  2234. "ssr.optimizeDeps"
  2235. ]);
  2236. /**
  2237. * Sets up `rollupOptions` compat proxies for an environment.
  2238. */
  2239. function setupRollupOptionCompatForEnvironment(environment) {
  2240. if (!isObject$1(environment)) return environment;
  2241. const merged = { ...environment };
  2242. if (isObject$1(merged.build)) setupRollupOptionCompat(merged.build, "build");
  2243. return merged;
  2244. }
  2245. function hasBothRollupOptionsAndRolldownOptions(options) {
  2246. for (const opt of [
  2247. options.build,
  2248. options.worker,
  2249. options.optimizeDeps,
  2250. options.ssr?.optimizeDeps
  2251. ]) if (opt != null && opt.rollupOptions != null && opt.rolldownOptions != null && opt.rollupOptions !== opt.rolldownOptions) return true;
  2252. return false;
  2253. }
  2254. function mergeConfigRecursively(defaults, overrides, rootPath) {
  2255. const merged = { ...defaults };
  2256. if (rollupOptionsRootPaths.has(rootPath)) setupRollupOptionCompat(merged, rootPath);
  2257. for (const key in overrides) {
  2258. const value = overrides[key];
  2259. if (value == null) continue;
  2260. let existing = merged[key];
  2261. if (key === "rollupOptions" && rollupOptionsRootPaths.has(rootPath)) {
  2262. if (overrides.rolldownOptions) continue;
  2263. existing = merged.rolldownOptions;
  2264. }
  2265. if (existing == null) {
  2266. if (rootPath === "" && key === "environments" && isObject$1(value)) {
  2267. const environments = { ...value };
  2268. for (const envName in environments) environments[envName] = setupRollupOptionCompatForEnvironment(environments[envName]);
  2269. merged[key] = environments;
  2270. } else if (rootPath === "environments") merged[key] = setupRollupOptionCompatForEnvironment(value);
  2271. else merged[key] = value;
  2272. continue;
  2273. }
  2274. if (key === "alias" && (rootPath === "resolve" || rootPath === "")) {
  2275. merged[key] = mergeAlias(existing, value);
  2276. continue;
  2277. } else if (key === "assetsInclude" && rootPath === "") {
  2278. merged[key] = [].concat(existing, value);
  2279. continue;
  2280. } else if (((key === "noExternal" || key === "external") && (rootPath === "ssr" || rootPath === "resolve") || key === "allowedHosts" && rootPath === "server") && (existing === true || value === true)) {
  2281. merged[key] = true;
  2282. continue;
  2283. } else if (key === "plugins" && rootPath === "worker") {
  2284. merged[key] = () => [...backwardCompatibleWorkerPlugins(existing), ...backwardCompatibleWorkerPlugins(value)];
  2285. continue;
  2286. } else if (key === "server" && rootPath === "server.hmr") {
  2287. merged[key] = value;
  2288. continue;
  2289. }
  2290. if (Array.isArray(existing) || Array.isArray(value)) {
  2291. merged[key] = [...arraify(existing), ...arraify(value)];
  2292. continue;
  2293. }
  2294. if (isObject$1(existing) && isObject$1(value)) {
  2295. merged[key] = mergeConfigRecursively(existing, value, rootPath && !environmentPathRE.test(rootPath) ? `${rootPath}.${key}` : key);
  2296. continue;
  2297. }
  2298. merged[key] = value;
  2299. }
  2300. return merged;
  2301. }
  2302. function mergeConfig(defaults, overrides, isRoot = true) {
  2303. if (typeof defaults === "function" || typeof overrides === "function") throw new Error(`Cannot merge config in form of callback`);
  2304. return mergeConfigRecursively(defaults, overrides, isRoot ? "" : ".");
  2305. }
  2306. function mergeAlias(a, b) {
  2307. if (!a) return b;
  2308. if (!b) return a;
  2309. if (isObject$1(a) && isObject$1(b)) return {
  2310. ...a,
  2311. ...b
  2312. };
  2313. return [...normalizeAlias(b), ...normalizeAlias(a)];
  2314. }
  2315. function normalizeAlias(o = []) {
  2316. return Array.isArray(o) ? o.map(normalizeSingleAlias) : Object.keys(o).map((find) => normalizeSingleAlias({
  2317. find,
  2318. replacement: o[find]
  2319. }));
  2320. }
  2321. function normalizeSingleAlias({ find, replacement, customResolver }) {
  2322. if (typeof find === "string" && find.endsWith("/") && replacement.endsWith("/")) {
  2323. find = find.slice(0, find.length - 1);
  2324. replacement = replacement.slice(0, replacement.length - 1);
  2325. }
  2326. const alias = {
  2327. find,
  2328. replacement
  2329. };
  2330. if (customResolver) alias.customResolver = customResolver;
  2331. return alias;
  2332. }
  2333. /**
  2334. * Transforms transpiled code result where line numbers aren't altered,
  2335. * so we can skip sourcemap generation during dev
  2336. */
  2337. function transformStableResult(s, id, config) {
  2338. return {
  2339. code: s.toString(),
  2340. map: config.command === "build" && config.build.sourcemap ? s.generateMap({
  2341. hires: "boundary",
  2342. source: id
  2343. }) : null
  2344. };
  2345. }
  2346. async function asyncFlatten(arr) {
  2347. do
  2348. arr = (await Promise.all(arr)).flat(Infinity);
  2349. while (arr.some((v) => v?.then));
  2350. return arr;
  2351. }
  2352. function stripBomTag(content) {
  2353. if (content.charCodeAt(0) === 65279) return content.slice(1);
  2354. return content;
  2355. }
  2356. /**
  2357. * Determine if a file is being requested with the correct case, to ensure
  2358. * consistent behavior between dev and prod and across operating systems.
  2359. */
  2360. function shouldServeFile(filePath, root) {
  2361. if (!isCaseInsensitiveFS) return true;
  2362. return hasCorrectCase(filePath, root);
  2363. }
  2364. /**
  2365. * Note that we can't use realpath here, because we don't want to follow
  2366. * symlinks.
  2367. */
  2368. function hasCorrectCase(file, assets) {
  2369. if (file === assets) return true;
  2370. const parent = path.dirname(file);
  2371. if (fs.readdirSync(parent).includes(path.basename(file))) return hasCorrectCase(parent, assets);
  2372. return false;
  2373. }
  2374. function joinUrlSegments(a, b) {
  2375. if (!a || !b) return a || b || "";
  2376. if (a.endsWith("/")) a = a.substring(0, a.length - 1);
  2377. if (b[0] !== "/") b = "/" + b;
  2378. return a + b;
  2379. }
  2380. function removeLeadingSlash(str) {
  2381. return str[0] === "/" ? str.slice(1) : str;
  2382. }
  2383. function stripBase(path, base) {
  2384. if (path === base) return "/";
  2385. const devBase = withTrailingSlash(base);
  2386. return path.startsWith(devBase) ? path.slice(devBase.length - 1) : path;
  2387. }
  2388. function arrayEqual(a, b) {
  2389. if (a === b) return true;
  2390. if (a.length !== b.length) return false;
  2391. for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;
  2392. return true;
  2393. }
  2394. function evalValue(rawValue) {
  2395. return new Function(`
  2396. var console, exports, global, module, process, require
  2397. return (\n${rawValue}\n)
  2398. `)();
  2399. }
  2400. function getNpmPackageName(importPath) {
  2401. const parts = importPath.split("/");
  2402. if (parts[0][0] === "@") {
  2403. if (!parts[1]) return null;
  2404. return `${parts[0]}/${parts[1]}`;
  2405. } else return parts[0];
  2406. }
  2407. function getPkgName(name) {
  2408. return name[0] === "@" ? name.split("/")[1] : name;
  2409. }
  2410. const escapeRegexRE = /[-/\\^$*+?.()|[\]{}]/g;
  2411. function escapeRegex(str) {
  2412. return str.replace(escapeRegexRE, "\\$&");
  2413. }
  2414. function getPackageManagerCommand(type = "install") {
  2415. const packageManager = process.env.npm_config_user_agent?.split(" ")[0].split("/")[0] || "npm";
  2416. switch (type) {
  2417. case "install": return packageManager === "npm" ? "npm install" : `${packageManager} add`;
  2418. case "uninstall": return packageManager === "npm" ? "npm uninstall" : `${packageManager} remove`;
  2419. case "update": return packageManager === "yarn" ? "yarn upgrade" : `${packageManager} update`;
  2420. default: throw new TypeError(`Unknown command type: ${type}`);
  2421. }
  2422. }
  2423. function isDevServer(server) {
  2424. return "pluginContainer" in server;
  2425. }
  2426. function createSerialPromiseQueue() {
  2427. let previousTask;
  2428. return { async run(f) {
  2429. const thisTask = f();
  2430. const depTasks = Promise.all([previousTask, thisTask]);
  2431. previousTask = depTasks;
  2432. const [, result] = await depTasks;
  2433. if (previousTask === depTasks) previousTask = void 0;
  2434. return result;
  2435. } };
  2436. }
  2437. function sortObjectKeys(obj) {
  2438. const sorted = {};
  2439. for (const key of Object.keys(obj).sort()) sorted[key] = obj[key];
  2440. return sorted;
  2441. }
  2442. function displayTime(time) {
  2443. if (time < 1e3) return `${time}ms`;
  2444. time = time / 1e3;
  2445. if (time < 60) return `${time.toFixed(2)}s`;
  2446. const mins = Math.floor(time / 60);
  2447. const seconds = Math.round(time % 60);
  2448. if (seconds === 60) return `${mins + 1}m`;
  2449. return `${mins}m${seconds < 1 ? "" : ` ${seconds}s`}`;
  2450. }
  2451. /**
  2452. * Encodes the URI path portion (ignores part after ? or #)
  2453. */
  2454. function encodeURIPath(uri) {
  2455. if (uri.startsWith("data:")) return uri;
  2456. const filePath = cleanUrl(uri);
  2457. const postfix = filePath !== uri ? uri.slice(filePath.length) : "";
  2458. return encodeURI(filePath) + postfix;
  2459. }
  2460. /**
  2461. * Like `encodeURIPath`, but only replacing `%` as `%25`. This is useful for environments
  2462. * that can handle un-encoded URIs, where `%` is the only ambiguous character.
  2463. */
  2464. function partialEncodeURIPath(uri) {
  2465. if (uri.startsWith("data:")) return uri;
  2466. const filePath = cleanUrl(uri);
  2467. const postfix = filePath !== uri ? uri.slice(filePath.length) : "";
  2468. return filePath.replaceAll("%", "%25") + postfix;
  2469. }
  2470. function decodeURIIfPossible(input) {
  2471. try {
  2472. return decodeURI(input);
  2473. } catch {
  2474. return;
  2475. }
  2476. }
  2477. const sigtermCallbacks = /* @__PURE__ */ new Set();
  2478. const parentSigtermCallback = async (signal, exitCode) => {
  2479. await Promise.all([...sigtermCallbacks].map((cb) => cb(signal, exitCode)));
  2480. };
  2481. const setupSIGTERMListener = (callback) => {
  2482. if (sigtermCallbacks.size === 0) {
  2483. process.once("SIGTERM", parentSigtermCallback);
  2484. if (process.env.CI !== "true") process.stdin.on("end", parentSigtermCallback);
  2485. }
  2486. sigtermCallbacks.add(callback);
  2487. };
  2488. const teardownSIGTERMListener = (callback) => {
  2489. sigtermCallbacks.delete(callback);
  2490. if (sigtermCallbacks.size === 0) {
  2491. process.off("SIGTERM", parentSigtermCallback);
  2492. if (process.env.CI !== "true") process.stdin.off("end", parentSigtermCallback);
  2493. }
  2494. };
  2495. function getServerUrlByHost(resolvedUrls, host) {
  2496. if (typeof host === "string") {
  2497. const matchedUrl = [...resolvedUrls?.local ?? [], ...resolvedUrls?.network ?? []].find((url) => url.includes(host));
  2498. if (matchedUrl) return matchedUrl;
  2499. }
  2500. return resolvedUrls?.local[0] ?? resolvedUrls?.network[0];
  2501. }
  2502. let lastDateNow = 0;
  2503. /**
  2504. * Similar to `Date.now()`, but strictly monotonically increasing.
  2505. *
  2506. * This function will never return the same value.
  2507. * Thus, the value may differ from the actual time.
  2508. *
  2509. * related: https://github.com/vitejs/vite/issues/19804
  2510. */
  2511. function monotonicDateNow() {
  2512. const now = Date.now();
  2513. if (now > lastDateNow) {
  2514. lastDateNow = now;
  2515. return lastDateNow;
  2516. }
  2517. lastDateNow++;
  2518. return lastDateNow;
  2519. }
  2520. function formatAndTruncateFileList(files) {
  2521. const MAX_LOG_LENGTH = 500;
  2522. let log = "";
  2523. let truncated = false;
  2524. for (let i = 0; i < files.length; i++) {
  2525. const file = files[i];
  2526. if (log === "") log = file;
  2527. else if (log.length + 2 + file.length < MAX_LOG_LENGTH) log += ", " + file;
  2528. else {
  2529. log += ` and ${files.length - i} more`;
  2530. truncated = true;
  2531. break;
  2532. }
  2533. }
  2534. return {
  2535. formatted: log,
  2536. truncated
  2537. };
  2538. }
  2539. const hashbangRE = /^#!.*\n/;
  2540. function getFileStartIndex(code) {
  2541. return hashbangRE.exec(code)?.[0].length ?? 0;
  2542. }
  2543. //#endregion
  2544. //#region src/node/plugin.ts
  2545. async function resolveEnvironmentPlugins(environment) {
  2546. const environmentPlugins = [];
  2547. for (const plugin of environment.getTopLevelConfig().plugins) {
  2548. if (plugin.applyToEnvironment) {
  2549. const applied = await plugin.applyToEnvironment(environment);
  2550. if (!applied) continue;
  2551. if (applied !== true) {
  2552. environmentPlugins.push(...(await asyncFlatten(arraify(applied))).filter(Boolean));
  2553. continue;
  2554. }
  2555. }
  2556. environmentPlugins.push(plugin);
  2557. }
  2558. return environmentPlugins;
  2559. }
  2560. /**
  2561. * @experimental
  2562. */
  2563. function perEnvironmentPlugin(name, applyToEnvironment) {
  2564. return {
  2565. name,
  2566. applyToEnvironment
  2567. };
  2568. }
  2569. //#endregion
  2570. //#region src/node/plugins/reporter.ts
  2571. function buildReporterPlugin(config) {
  2572. return perEnvironmentPlugin("native:reporter", (env) => {
  2573. const tty = process.stdout.isTTY && !process.env.CI;
  2574. const shouldLogInfo = LogLevels[config.logLevel || "info"] >= LogLevels.info;
  2575. const assetsDir = path.join(env.config.build.assetsDir, "/");
  2576. return viteReporterPlugin({
  2577. root: env.config.root,
  2578. isTty: !!tty,
  2579. isLib: !!env.config.build.lib,
  2580. assetsDir,
  2581. chunkLimit: env.config.build.chunkSizeWarningLimit,
  2582. logInfo: shouldLogInfo ? (msg) => env.logger.info(msg) : void 0,
  2583. reportCompressedSize: env.config.build.reportCompressedSize,
  2584. warnLargeChunks: env.config.build.minify && !env.config.build.lib && env.config.consumer === "client"
  2585. });
  2586. });
  2587. }
  2588. //#endregion
  2589. //#region src/node/plugins/esbuild.ts
  2590. const debug$14 = createDebugger("vite:esbuild");
  2591. const IIFE_BEGIN_RE$1 = /(?:const|var)\s+\S+\s*=\s*\(?function\([^()]*\)\s*\{\s*"use strict";/;
  2592. const validExtensionRE$1 = /\.\w+$/;
  2593. const defaultEsbuildSupported = {
  2594. "dynamic-import": true,
  2595. "import-meta": true
  2596. };
  2597. let esbuild;
  2598. const importEsbuild$1 = () => {
  2599. esbuild ||= import("esbuild");
  2600. return esbuild;
  2601. };
  2602. let warnedTransformWithEsbuild = false;
  2603. const warnTransformWithEsbuildUsageOnce = () => {
  2604. if (warnedTransformWithEsbuild) return;
  2605. warnedTransformWithEsbuild = true;
  2606. console.warn(import_picocolors.default.yellow("`transformWithEsbuild` is deprecated and will be removed in the future. Please migrate to `transformWithOxc`."));
  2607. };
  2608. async function transformWithEsbuild(code, filename, options, inMap, config, watcher, ignoreEsbuildWarning = false) {
  2609. let loader = options?.loader;
  2610. if (!loader) {
  2611. const ext = path.extname(validExtensionRE$1.test(filename) ? filename : cleanUrl(filename)).slice(1);
  2612. if (ext === "cjs" || ext === "mjs") loader = "js";
  2613. else if (ext === "cts" || ext === "mts") loader = "ts";
  2614. else loader = ext;
  2615. }
  2616. let tsconfigRaw = options?.tsconfigRaw;
  2617. if (typeof tsconfigRaw !== "string") {
  2618. const meaningfulFields = [
  2619. "alwaysStrict",
  2620. "experimentalDecorators",
  2621. "importsNotUsedAsValues",
  2622. "jsx",
  2623. "jsxFactory",
  2624. "jsxFragmentFactory",
  2625. "jsxImportSource",
  2626. "preserveValueImports",
  2627. "target",
  2628. "useDefineForClassFields",
  2629. "verbatimModuleSyntax"
  2630. ];
  2631. const compilerOptionsForFile = {};
  2632. if (loader === "ts" || loader === "tsx") {
  2633. const result = resolveTsconfig(filename, getTSConfigResolutionCache(config));
  2634. if (result) {
  2635. const { tsconfig: loadedTsconfig, tsconfigFilePaths } = result;
  2636. if (watcher && config) for (const tsconfigFile of tsconfigFilePaths) ensureWatchedFile(watcher, tsconfigFile, config.root);
  2637. const loadedCompilerOptions = loadedTsconfig.compilerOptions ?? {};
  2638. for (const field of meaningfulFields) if (field in loadedCompilerOptions) compilerOptionsForFile[field] = loadedCompilerOptions[field];
  2639. }
  2640. }
  2641. const compilerOptions = {
  2642. ...compilerOptionsForFile,
  2643. ...tsconfigRaw?.compilerOptions
  2644. };
  2645. if (compilerOptions.useDefineForClassFields === void 0 && compilerOptions.target === void 0) compilerOptions.useDefineForClassFields = false;
  2646. if (options) {
  2647. if (options.jsx) compilerOptions.jsx = void 0;
  2648. if (options.jsxFactory) compilerOptions.jsxFactory = void 0;
  2649. if (options.jsxFragment) compilerOptions.jsxFragmentFactory = void 0;
  2650. if (options.jsxImportSource) compilerOptions.jsxImportSource = void 0;
  2651. }
  2652. tsconfigRaw = {
  2653. ...tsconfigRaw,
  2654. compilerOptions
  2655. };
  2656. }
  2657. const resolvedOptions = {
  2658. sourcemap: true,
  2659. sourcefile: filename,
  2660. ...options,
  2661. loader,
  2662. tsconfigRaw
  2663. };
  2664. delete resolvedOptions.include;
  2665. delete resolvedOptions.exclude;
  2666. delete resolvedOptions.jsxInject;
  2667. let transform;
  2668. try {
  2669. transform = (await importEsbuild$1()).transform;
  2670. } catch (e) {
  2671. throw new Error("Failed to load `transformWithEsbuild`. It is deprecated and it now requires esbuild to be installed separately. If you are a package author, please migrate to `transformWithOxc` instead.", { cause: e });
  2672. }
  2673. if (!ignoreEsbuildWarning) warnTransformWithEsbuildUsageOnce();
  2674. try {
  2675. const result = await transform(code, resolvedOptions);
  2676. let map;
  2677. if (inMap && resolvedOptions.sourcemap) {
  2678. const nextMap = JSON.parse(result.map);
  2679. nextMap.sourcesContent = [];
  2680. map = combineSourcemaps(filename, [nextMap, inMap]);
  2681. } else map = resolvedOptions.sourcemap && resolvedOptions.sourcemap !== "inline" ? JSON.parse(result.map) : { mappings: "" };
  2682. return {
  2683. ...result,
  2684. map
  2685. };
  2686. } catch (e) {
  2687. debug$14?.(`esbuild error with options used: `, resolvedOptions);
  2688. if (e.errors) {
  2689. e.frame = "";
  2690. e.errors.forEach((m) => {
  2691. if (m.text === "Experimental decorators are not currently enabled" || m.text === "Parameter decorators only work when experimental decorators are enabled") m.text += ". Vite 5 now uses esbuild 0.18 and you need to enable them by adding \"experimentalDecorators\": true in your \"tsconfig.json\" file.";
  2692. e.frame += `\n` + prettifyMessage(m, code);
  2693. });
  2694. e.loc = e.errors[0].location;
  2695. }
  2696. throw e;
  2697. }
  2698. }
  2699. const rollupToEsbuildFormatMap = {
  2700. es: "esm",
  2701. cjs: "cjs",
  2702. iife: void 0
  2703. };
  2704. const injectEsbuildHelpers = (esbuildCode, format) => {
  2705. const contentIndex = format === "iife" ? Math.max(esbuildCode.search(IIFE_BEGIN_RE$1), 0) : format === "umd" ? esbuildCode.indexOf(`(function(`) : 0;
  2706. if (contentIndex > 0) {
  2707. const esbuildHelpers = esbuildCode.slice(0, contentIndex);
  2708. return esbuildCode.slice(contentIndex).replace("\"use strict\";", (m) => m + esbuildHelpers);
  2709. }
  2710. return esbuildCode;
  2711. };
  2712. const buildEsbuildPlugin = () => {
  2713. return {
  2714. name: "vite:esbuild-transpile",
  2715. applyToEnvironment(environment) {
  2716. return environment.config.esbuild !== false;
  2717. },
  2718. async renderChunk(code, chunk, opts) {
  2719. if (this.environment.config.isOutputOptionsForLegacyChunks?.(opts)) return null;
  2720. const config = this.environment.config;
  2721. const options = resolveEsbuildTranspileOptions(config, opts.format);
  2722. if (!options) return null;
  2723. const res = await transformWithEsbuild(code, chunk.fileName, options, void 0, config, void 0, true);
  2724. if (config.build.lib) res.code = injectEsbuildHelpers(res.code, opts.format);
  2725. return res;
  2726. }
  2727. };
  2728. };
  2729. function resolveEsbuildTranspileOptions(config, format) {
  2730. const target = config.build.target;
  2731. const minify = config.build.minify === "esbuild";
  2732. if ((!target || target === "esnext") && !minify) return null;
  2733. const isEsLibBuild = config.build.lib && format === "es";
  2734. const esbuildOptions = config.esbuild || {};
  2735. const options = {
  2736. ...esbuildOptions,
  2737. loader: "js",
  2738. target: target || void 0,
  2739. format: rollupToEsbuildFormatMap[format],
  2740. supported: {
  2741. ...defaultEsbuildSupported,
  2742. ...esbuildOptions.supported
  2743. }
  2744. };
  2745. if (!minify) return {
  2746. ...options,
  2747. minify: false,
  2748. minifyIdentifiers: false,
  2749. minifySyntax: false,
  2750. minifyWhitespace: false,
  2751. treeShaking: false
  2752. };
  2753. if (options.minifyIdentifiers != null || options.minifySyntax != null || options.minifyWhitespace != null) if (isEsLibBuild) return {
  2754. ...options,
  2755. minify: false,
  2756. minifyIdentifiers: options.minifyIdentifiers ?? true,
  2757. minifySyntax: options.minifySyntax ?? true,
  2758. minifyWhitespace: false,
  2759. treeShaking: true
  2760. };
  2761. else return {
  2762. ...options,
  2763. minify: false,
  2764. minifyIdentifiers: options.minifyIdentifiers ?? true,
  2765. minifySyntax: options.minifySyntax ?? true,
  2766. minifyWhitespace: options.minifyWhitespace ?? true,
  2767. treeShaking: true
  2768. };
  2769. if (isEsLibBuild) return {
  2770. ...options,
  2771. minify: false,
  2772. minifyIdentifiers: true,
  2773. minifySyntax: true,
  2774. minifyWhitespace: false,
  2775. treeShaking: true
  2776. };
  2777. else return {
  2778. ...options,
  2779. minify: true,
  2780. treeShaking: true
  2781. };
  2782. }
  2783. function prettifyMessage(m, code) {
  2784. let res = import_picocolors.default.yellow(m.text);
  2785. if (m.location) res += `\n` + generateCodeFrame(code, m.location);
  2786. return res + `\n`;
  2787. }
  2788. let globalTSConfigResolutionCache;
  2789. const tsconfigResolutionCacheMap = /* @__PURE__ */ new WeakMap();
  2790. function getTSConfigResolutionCache(config) {
  2791. if (!config) return globalTSConfigResolutionCache ??= new TsconfigCache();
  2792. let cache = tsconfigResolutionCacheMap.get(config);
  2793. if (!cache) {
  2794. cache = new TsconfigCache();
  2795. tsconfigResolutionCacheMap.set(config, cache);
  2796. }
  2797. return cache;
  2798. }
  2799. async function reloadOnTsconfigChange(server, changedFile) {
  2800. if (changedFile.endsWith(".json")) {
  2801. const cache = getTSConfigResolutionCache(server.config);
  2802. if (changedFile.endsWith("/tsconfig.json")) {
  2803. server.config.logger.info(`changed tsconfig file detected: ${changedFile} - Clearing cache and forcing full-reload to ensure TypeScript is compiled with updated config values.`, {
  2804. clear: server.config.clearScreen,
  2805. timestamp: true
  2806. });
  2807. for (const environment of Object.values(server.environments)) environment.moduleGraph.invalidateAll();
  2808. cache.clear();
  2809. for (const environment of Object.values(server.environments)) environment.hot.send({
  2810. type: "full-reload",
  2811. path: "*"
  2812. });
  2813. }
  2814. }
  2815. }
  2816. //#endregion
  2817. //#region ../../node_modules/.pnpm/artichokie@0.4.3/node_modules/artichokie/dist/index.js
  2818. const AsyncFunction = async function() {}.constructor;
  2819. const codeToDataUrl = (code) => `data:application/javascript,${encodeURIComponent(code + "\n//# sourceURL=[worker-eval(artichokie)]")}`;
  2820. const viteSsrDynamicImport = "__vite_ssr_dynamic_import__";
  2821. const stackBlitzImport = "𝐢𝐦𝐩𝐨𝐫𝐭";
  2822. var Worker$1 = class {
  2823. /** @internal */
  2824. _isModule;
  2825. /** @internal */
  2826. _code;
  2827. /** @internal */
  2828. _parentFunctions;
  2829. /** @internal */
  2830. _max;
  2831. /** @internal */
  2832. _pool;
  2833. /** @internal */
  2834. _idlePool;
  2835. /** @internal */
  2836. _queue;
  2837. constructor(fn, options = {}) {
  2838. this._isModule = options.type === "module";
  2839. this._code = genWorkerCode(fn, this._isModule, 5 * 1e3, options.parentFunctions ?? {});
  2840. this._parentFunctions = options.parentFunctions ?? {};
  2841. const defaultMax = Math.max(1, (os.availableParallelism?.() ?? os.cpus().length) - 1);
  2842. this._max = options.max || defaultMax;
  2843. this._pool = [];
  2844. this._idlePool = [];
  2845. this._queue = [];
  2846. }
  2847. async run(...args) {
  2848. const worker = await this._getAvailableWorker();
  2849. return new Promise((resolve, reject) => {
  2850. worker.currentResolve = resolve;
  2851. worker.currentReject = reject;
  2852. worker.postMessage({ args });
  2853. });
  2854. }
  2855. stop() {
  2856. this._pool.forEach((w) => w.unref());
  2857. this._queue.forEach(([, reject]) => reject(/* @__PURE__ */ new Error("Main worker pool stopped before a worker was available.")));
  2858. this._pool = [];
  2859. this._idlePool = [];
  2860. this._queue = [];
  2861. }
  2862. /** @internal */
  2863. _createWorker(parentFunctionSyncMessagePort, parentFunctionAsyncMessagePort, lockState) {
  2864. const options = {
  2865. workerData: [
  2866. parentFunctionSyncMessagePort,
  2867. parentFunctionAsyncMessagePort,
  2868. lockState
  2869. ],
  2870. transferList: [parentFunctionSyncMessagePort, parentFunctionAsyncMessagePort]
  2871. };
  2872. if (this._isModule) return new Worker(new URL(codeToDataUrl(this._code)), options);
  2873. return new Worker(this._code, {
  2874. ...options,
  2875. eval: true
  2876. });
  2877. }
  2878. /** @internal */
  2879. async _getAvailableWorker() {
  2880. if (this._idlePool.length) return this._idlePool.shift();
  2881. if (this._pool.length < this._max) {
  2882. const parentFunctionResponder = createParentFunctionResponder(this._parentFunctions);
  2883. const worker = this._createWorker(parentFunctionResponder.workerPorts.sync, parentFunctionResponder.workerPorts.async, parentFunctionResponder.lockState);
  2884. worker.on("message", async (args) => {
  2885. if ("result" in args) {
  2886. worker.currentResolve?.(args.result);
  2887. worker.currentResolve = null;
  2888. } else {
  2889. if (args.error instanceof ReferenceError) args.error.message += ". Maybe you forgot to pass the function to parentFunction?";
  2890. worker.currentReject?.(args.error);
  2891. worker.currentReject = null;
  2892. }
  2893. this._assignDoneWorker(worker);
  2894. });
  2895. worker.on("error", (err) => {
  2896. worker.currentReject?.(err);
  2897. worker.currentReject = null;
  2898. parentFunctionResponder.close();
  2899. });
  2900. worker.on("exit", (code) => {
  2901. const i = this._pool.indexOf(worker);
  2902. if (i > -1) this._pool.splice(i, 1);
  2903. if (code !== 0 && worker.currentReject) {
  2904. worker.currentReject(/* @__PURE__ */ new Error(`Worker stopped with non-0 exit code ${code}`));
  2905. worker.currentReject = null;
  2906. parentFunctionResponder.close();
  2907. }
  2908. });
  2909. this._pool.push(worker);
  2910. return worker;
  2911. }
  2912. let resolve;
  2913. let reject;
  2914. const onWorkerAvailablePromise = new Promise((r, rj) => {
  2915. resolve = r;
  2916. reject = rj;
  2917. });
  2918. this._queue.push([resolve, reject]);
  2919. return onWorkerAvailablePromise;
  2920. }
  2921. /** @internal */
  2922. _assignDoneWorker(worker) {
  2923. if (this._queue.length) {
  2924. const [resolve] = this._queue.shift();
  2925. resolve(worker);
  2926. return;
  2927. }
  2928. this._idlePool.push(worker);
  2929. }
  2930. };
  2931. function createParentFunctionResponder(parentFunctions) {
  2932. const lockState = new Int32Array(new SharedArrayBuffer(4));
  2933. const unlock = () => {
  2934. Atomics.store(lockState, 0, 0);
  2935. Atomics.notify(lockState, 0);
  2936. };
  2937. const parentFunctionSyncMessageChannel = new MessageChannel();
  2938. const parentFunctionAsyncMessageChannel = new MessageChannel();
  2939. const parentFunctionSyncMessagePort = parentFunctionSyncMessageChannel.port1;
  2940. const parentFunctionAsyncMessagePort = parentFunctionAsyncMessageChannel.port1;
  2941. const syncResponse = (data) => {
  2942. parentFunctionSyncMessagePort.postMessage(data);
  2943. unlock();
  2944. };
  2945. parentFunctionSyncMessagePort.on("message", async (args) => {
  2946. let syncResult;
  2947. try {
  2948. syncResult = parentFunctions[args.name](...args.args);
  2949. } catch (error) {
  2950. syncResponse({
  2951. id: args.id,
  2952. error
  2953. });
  2954. return;
  2955. }
  2956. if (!(typeof syncResult === "object" && syncResult !== null && "then" in syncResult && typeof syncResult.then === "function")) {
  2957. syncResponse({
  2958. id: args.id,
  2959. result: syncResult
  2960. });
  2961. return;
  2962. }
  2963. syncResponse({
  2964. id: args.id,
  2965. isAsync: true
  2966. });
  2967. try {
  2968. const result = await syncResult;
  2969. parentFunctionAsyncMessagePort.postMessage({
  2970. id: args.id,
  2971. result
  2972. });
  2973. } catch (error) {
  2974. parentFunctionAsyncMessagePort.postMessage({
  2975. id: args.id,
  2976. error
  2977. });
  2978. }
  2979. });
  2980. parentFunctionSyncMessagePort.unref();
  2981. return {
  2982. close: () => {
  2983. parentFunctionSyncMessagePort.close();
  2984. parentFunctionAsyncMessagePort.close();
  2985. },
  2986. lockState,
  2987. workerPorts: {
  2988. sync: parentFunctionSyncMessageChannel.port2,
  2989. async: parentFunctionAsyncMessageChannel.port2
  2990. }
  2991. };
  2992. }
  2993. function genWorkerCode(fn, isModule, waitTimeout, parentFunctions) {
  2994. const createLock = (performance, lockState) => {
  2995. return {
  2996. lock: () => {
  2997. Atomics.store(lockState, 0, 1);
  2998. },
  2999. waitUnlock: () => {
  3000. let utilizationBefore;
  3001. while (true) {
  3002. const status = Atomics.wait(lockState, 0, 1, waitTimeout);
  3003. if (status === "timed-out") {
  3004. if (utilizationBefore === void 0) {
  3005. utilizationBefore = performance.eventLoopUtilization();
  3006. continue;
  3007. }
  3008. utilizationBefore = performance.eventLoopUtilization(utilizationBefore);
  3009. if (utilizationBefore.utilization > .9) continue;
  3010. throw new Error(status);
  3011. }
  3012. break;
  3013. }
  3014. }
  3015. };
  3016. };
  3017. const createParentFunctionRequester = (syncPort, asyncPort, receive, lock) => {
  3018. let id = 0;
  3019. const resolvers = /* @__PURE__ */ new Map();
  3020. const call = (key) => (...args) => {
  3021. id++;
  3022. lock.lock();
  3023. syncPort.postMessage({
  3024. id,
  3025. name: key,
  3026. args
  3027. });
  3028. lock.waitUnlock();
  3029. const resArgs = receive(syncPort).message;
  3030. if (resArgs.isAsync) {
  3031. let resolve, reject;
  3032. const promise = new Promise((res, rej) => {
  3033. resolve = res;
  3034. reject = rej;
  3035. });
  3036. resolvers.set(id, {
  3037. resolve,
  3038. reject
  3039. });
  3040. return promise;
  3041. }
  3042. if ("error" in resArgs) throw resArgs.error;
  3043. else return resArgs.result;
  3044. };
  3045. asyncPort.on("message", (args) => {
  3046. const id = args.id;
  3047. if (resolvers.has(id)) {
  3048. const { resolve, reject } = resolvers.get(id);
  3049. resolvers.delete(id);
  3050. if ("result" in args) resolve(args.result);
  3051. else reject(args.error);
  3052. }
  3053. });
  3054. return { call };
  3055. };
  3056. const fnString = fn.toString().replaceAll(stackBlitzImport, "import").replaceAll(viteSsrDynamicImport, "import");
  3057. return `
  3058. ${isModule ? "import { parentPort, receiveMessageOnPort, workerData } from 'worker_threads'" : "const { parentPort, receiveMessageOnPort, workerData } = require('worker_threads')"}
  3059. ${isModule ? "import { performance } from 'node:perf_hooks'" : "const { performance } = require('node:perf_hooks')"}
  3060. const [parentFunctionSyncMessagePort, parentFunctionAsyncMessagePort, lockState] = workerData
  3061. const waitTimeout = ${waitTimeout}
  3062. const createLock = ${createLock.toString()}
  3063. const parentFunctionRequester = (${createParentFunctionRequester.toString()})(
  3064. parentFunctionSyncMessagePort,
  3065. parentFunctionAsyncMessagePort,
  3066. receiveMessageOnPort,
  3067. createLock(performance, lockState)
  3068. )
  3069. const doWorkPromise = (async () => {
  3070. ${Object.keys(parentFunctions).map((key) => `const ${key} = parentFunctionRequester.call(${JSON.stringify(key)});`).join("\n")}
  3071. return await (${fnString})()
  3072. })()
  3073. let doWork
  3074. parentPort.on('message', async (args) => {
  3075. doWork ||= await doWorkPromise
  3076. try {
  3077. const res = await doWork(...args.args)
  3078. parentPort.postMessage({ result: res })
  3079. } catch (e) {
  3080. parentPort.postMessage({ error: e })
  3081. }
  3082. })
  3083. `;
  3084. }
  3085. const importRe = /\bimport\s*\(/g;
  3086. const internalImportName = "__artichokie_local_import__";
  3087. var FakeWorker = class {
  3088. /** @internal */
  3089. _fn;
  3090. constructor(fn, options = {}) {
  3091. const declareRequire = options.type !== "module";
  3092. const argsAndCode = genFakeWorkerArgsAndCode(fn, declareRequire, options.parentFunctions ?? {});
  3093. const localImport = (specifier) => import(specifier);
  3094. const args = [
  3095. ...declareRequire ? [createRequire(import.meta.url)] : [],
  3096. localImport,
  3097. options.parentFunctions
  3098. ];
  3099. this._fn = new AsyncFunction(...argsAndCode)(...args);
  3100. }
  3101. async run(...args) {
  3102. try {
  3103. return await (await this._fn)(...args);
  3104. } catch (err) {
  3105. if (err instanceof ReferenceError) err.message += ". Maybe you forgot to pass the function to parentFunction?";
  3106. throw err;
  3107. }
  3108. }
  3109. stop() {}
  3110. };
  3111. function genFakeWorkerArgsAndCode(fn, declareRequire, parentFunctions) {
  3112. const fnString = fn.toString().replace(importRe, `${internalImportName}(`).replaceAll(stackBlitzImport, internalImportName).replaceAll(viteSsrDynamicImport, internalImportName);
  3113. return [
  3114. ...declareRequire ? ["require"] : [],
  3115. internalImportName,
  3116. "parentFunctions",
  3117. `
  3118. ${Object.keys(parentFunctions).map((key) => `const ${key} = parentFunctions[${JSON.stringify(key)}];`).join("\n")}
  3119. return await (${fnString})()
  3120. `
  3121. ];
  3122. }
  3123. var WorkerWithFallback = class {
  3124. /** @internal */
  3125. _disableReal;
  3126. /** @internal */
  3127. _realWorker;
  3128. /** @internal */
  3129. _fakeWorker;
  3130. /** @internal */
  3131. _shouldUseFake;
  3132. constructor(fn, options) {
  3133. this._disableReal = options.max !== void 0 && options.max <= 0;
  3134. this._realWorker = new Worker$1(fn, options);
  3135. this._fakeWorker = new FakeWorker(fn, options);
  3136. this._shouldUseFake = options.shouldUseFake;
  3137. }
  3138. async run(...args) {
  3139. const useFake = this._disableReal || this._shouldUseFake(...args);
  3140. return this[useFake ? "_fakeWorker" : "_realWorker"].run(...args);
  3141. }
  3142. stop() {
  3143. this._realWorker.stop();
  3144. this._fakeWorker.stop();
  3145. }
  3146. };
  3147. //#endregion
  3148. //#region ../../node_modules/.pnpm/resolve.exports@2.0.3/node_modules/resolve.exports/dist/index.mjs
  3149. function e(e, n, r) {
  3150. throw new Error(r ? `No known conditions for "${n}" specifier in "${e}" package` : `Missing "${n}" specifier in "${e}" package`);
  3151. }
  3152. function n$1(n, i, o, f) {
  3153. let s, u, l = r(n, o), c = function(e) {
  3154. let n = new Set(["default", ...e.conditions || []]);
  3155. return e.unsafe || n.add(e.require ? "require" : "import"), e.unsafe || n.add(e.browser ? "browser" : "node"), n;
  3156. }(f || {}), a = i[l];
  3157. if (void 0 === a) {
  3158. let e, n, r, t;
  3159. for (t in i) n && t.length < n.length || ("/" === t[t.length - 1] && l.startsWith(t) ? (u = l.substring(t.length), n = t) : t.length > 1 && (r = t.indexOf("*", 1), ~r && (e = RegExp("^" + t.substring(0, r) + "(.*)" + t.substring(1 + r) + "$").exec(l), e && e[1] && (u = e[1], n = t))));
  3160. a = i[n];
  3161. }
  3162. return a || e(n, l), s = t(a, c), s || e(n, l, 1), u && function(e, n) {
  3163. let r, t = 0, i = e.length, o = /[*]/g, f = /[/]$/;
  3164. for (; t < i; t++) e[t] = o.test(r = e[t]) ? r.replace(o, n) : f.test(r) ? r + n : r;
  3165. }(s, u), s;
  3166. }
  3167. function r(e, n, r) {
  3168. if (e === n || "." === n) return ".";
  3169. let t = e + "/", i = t.length, o = n.slice(0, i) === t, f = o ? n.slice(i) : n;
  3170. return "#" === f[0] ? f : o || !r ? "./" === f.slice(0, 2) ? f : "./" + f : f;
  3171. }
  3172. function t(e, n, r) {
  3173. if (e) {
  3174. if ("string" == typeof e) return r && r.add(e), [e];
  3175. let i, o;
  3176. if (Array.isArray(e)) {
  3177. for (o = r || /* @__PURE__ */ new Set(), i = 0; i < e.length; i++) t(e[i], n, o);
  3178. if (!r && o.size) return [...o];
  3179. } else for (i in e) if (n.has(i)) return t(e[i], n, r);
  3180. }
  3181. }
  3182. function o(e, r, t) {
  3183. let i, o = e.exports;
  3184. if (o) {
  3185. if ("string" == typeof o) o = { ".": o };
  3186. else for (i in o) {
  3187. "." !== i[0] && (o = { ".": o });
  3188. break;
  3189. }
  3190. return n$1(e.name, o, r || ".", t);
  3191. }
  3192. }
  3193. function f(e, r, t) {
  3194. if (e.imports) return n$1(e.name, e.imports, r, t);
  3195. }
  3196. //#endregion
  3197. //#region ../../node_modules/.pnpm/ufo@1.6.3/node_modules/ufo/dist/index.mjs
  3198. const HASH_RE = /#/g;
  3199. const AMPERSAND_RE = /&/g;
  3200. const SLASH_RE = /\//g;
  3201. const EQUAL_RE = /=/g;
  3202. const PLUS_RE = /\+/g;
  3203. const ENC_CARET_RE = /%5e/gi;
  3204. const ENC_BACKTICK_RE = /%60/gi;
  3205. const ENC_PIPE_RE = /%7c/gi;
  3206. const ENC_SPACE_RE = /%20/gi;
  3207. function encode(text) {
  3208. return encodeURI("" + text).replace(ENC_PIPE_RE, "|");
  3209. }
  3210. function encodeQueryValue(input) {
  3211. return encode(typeof input === "string" ? input : JSON.stringify(input)).replace(PLUS_RE, "%2B").replace(ENC_SPACE_RE, "+").replace(HASH_RE, "%23").replace(AMPERSAND_RE, "%26").replace(ENC_BACKTICK_RE, "`").replace(ENC_CARET_RE, "^").replace(SLASH_RE, "%2F");
  3212. }
  3213. function encodeQueryKey(text) {
  3214. return encodeQueryValue(text).replace(EQUAL_RE, "%3D");
  3215. }
  3216. function encodeQueryItem(key, value) {
  3217. if (typeof value === "number" || typeof value === "boolean") value = String(value);
  3218. if (!value) return encodeQueryKey(key);
  3219. if (Array.isArray(value)) return value.map((_value) => `${encodeQueryKey(key)}=${encodeQueryValue(_value)}`).join("&");
  3220. return `${encodeQueryKey(key)}=${encodeQueryValue(value)}`;
  3221. }
  3222. function stringifyQuery(query) {
  3223. return Object.keys(query).filter((k) => query[k] !== void 0).map((k) => encodeQueryItem(k, query[k])).filter(Boolean).join("&");
  3224. }
  3225. new Set(builtinModules);
  3226. function clearImports(imports) {
  3227. return (imports || "").replace(/\/\/[^\n]*\n|\/\*.*\*\//g, "").replace(/\s+/g, " ");
  3228. }
  3229. function getImportNames(cleanedImports) {
  3230. const topLevelImports = cleanedImports.replace(/{[^}]*}/, "");
  3231. return {
  3232. namespacedImport: topLevelImports.match(/\* as \s*(\S*)/)?.[1],
  3233. defaultImport: topLevelImports.split(",").find((index) => !/[*{}]/.test(index))?.trim() || void 0
  3234. };
  3235. }
  3236. /**
  3237. * @typedef ErrnoExceptionFields
  3238. * @property {number | undefined} [errnode]
  3239. * @property {string | undefined} [code]
  3240. * @property {string | undefined} [path]
  3241. * @property {string | undefined} [syscall]
  3242. * @property {string | undefined} [url]
  3243. *
  3244. * @typedef {Error & ErrnoExceptionFields} ErrnoException
  3245. */
  3246. const own$1 = {}.hasOwnProperty;
  3247. const classRegExp = /^([A-Z][a-z\d]*)+$/;
  3248. const kTypes = new Set([
  3249. "string",
  3250. "function",
  3251. "number",
  3252. "object",
  3253. "Function",
  3254. "Object",
  3255. "boolean",
  3256. "bigint",
  3257. "symbol"
  3258. ]);
  3259. const codes = {};
  3260. /**
  3261. * Create a list string in the form like 'A and B' or 'A, B, ..., and Z'.
  3262. * We cannot use Intl.ListFormat because it's not available in
  3263. * --without-intl builds.
  3264. *
  3265. * @param {Array<string>} array
  3266. * An array of strings.
  3267. * @param {string} [type]
  3268. * The list type to be inserted before the last element.
  3269. * @returns {string}
  3270. */
  3271. function formatList(array, type = "and") {
  3272. return array.length < 3 ? array.join(` ${type} `) : `${array.slice(0, -1).join(", ")}, ${type} ${array[array.length - 1]}`;
  3273. }
  3274. /** @type {Map<string, MessageFunction | string>} */
  3275. const messages = /* @__PURE__ */ new Map();
  3276. const nodeInternalPrefix = "__node_internal_";
  3277. /** @type {number} */
  3278. let userStackTraceLimit;
  3279. codes.ERR_INVALID_ARG_TYPE = createError(
  3280. "ERR_INVALID_ARG_TYPE",
  3281. /**
  3282. * @param {string} name
  3283. * @param {Array<string> | string} expected
  3284. * @param {unknown} actual
  3285. */
  3286. (name, expected, actual) => {
  3287. assert.ok(typeof name === "string", "'name' must be a string");
  3288. if (!Array.isArray(expected)) expected = [expected];
  3289. let message = "The ";
  3290. if (name.endsWith(" argument")) message += `${name} `;
  3291. else {
  3292. const type = name.includes(".") ? "property" : "argument";
  3293. message += `"${name}" ${type} `;
  3294. }
  3295. message += "must be ";
  3296. /** @type {Array<string>} */
  3297. const types = [];
  3298. /** @type {Array<string>} */
  3299. const instances = [];
  3300. /** @type {Array<string>} */
  3301. const other = [];
  3302. for (const value of expected) {
  3303. assert.ok(typeof value === "string", "All expected entries have to be of type string");
  3304. if (kTypes.has(value)) types.push(value.toLowerCase());
  3305. else if (classRegExp.exec(value) === null) {
  3306. assert.ok(value !== "object", "The value \"object\" should be written as \"Object\"");
  3307. other.push(value);
  3308. } else instances.push(value);
  3309. }
  3310. if (instances.length > 0) {
  3311. const pos = types.indexOf("object");
  3312. if (pos !== -1) {
  3313. types.slice(pos, 1);
  3314. instances.push("Object");
  3315. }
  3316. }
  3317. if (types.length > 0) {
  3318. message += `${types.length > 1 ? "one of type" : "of type"} ${formatList(types, "or")}`;
  3319. if (instances.length > 0 || other.length > 0) message += " or ";
  3320. }
  3321. if (instances.length > 0) {
  3322. message += `an instance of ${formatList(instances, "or")}`;
  3323. if (other.length > 0) message += " or ";
  3324. }
  3325. if (other.length > 0) if (other.length > 1) message += `one of ${formatList(other, "or")}`;
  3326. else {
  3327. if (other[0].toLowerCase() !== other[0]) message += "an ";
  3328. message += `${other[0]}`;
  3329. }
  3330. message += `. Received ${determineSpecificType(actual)}`;
  3331. return message;
  3332. },
  3333. TypeError
  3334. );
  3335. codes.ERR_INVALID_MODULE_SPECIFIER = createError(
  3336. "ERR_INVALID_MODULE_SPECIFIER",
  3337. /**
  3338. * @param {string} request
  3339. * @param {string} reason
  3340. * @param {string} [base]
  3341. */
  3342. (request, reason, base = void 0) => {
  3343. return `Invalid module "${request}" ${reason}${base ? ` imported from ${base}` : ""}`;
  3344. },
  3345. TypeError
  3346. );
  3347. codes.ERR_INVALID_PACKAGE_CONFIG = createError(
  3348. "ERR_INVALID_PACKAGE_CONFIG",
  3349. /**
  3350. * @param {string} path
  3351. * @param {string} [base]
  3352. * @param {string} [message]
  3353. */
  3354. (path, base, message) => {
  3355. return `Invalid package config ${path}${base ? ` while importing ${base}` : ""}${message ? `. ${message}` : ""}`;
  3356. },
  3357. Error
  3358. );
  3359. codes.ERR_INVALID_PACKAGE_TARGET = createError(
  3360. "ERR_INVALID_PACKAGE_TARGET",
  3361. /**
  3362. * @param {string} packagePath
  3363. * @param {string} key
  3364. * @param {unknown} target
  3365. * @param {boolean} [isImport=false]
  3366. * @param {string} [base]
  3367. */
  3368. (packagePath, key, target, isImport = false, base = void 0) => {
  3369. const relatedError = typeof target === "string" && !isImport && target.length > 0 && !target.startsWith("./");
  3370. if (key === ".") {
  3371. assert.ok(isImport === false);
  3372. return `Invalid "exports" main target ${JSON.stringify(target)} defined in the package config ${packagePath}package.json${base ? ` imported from ${base}` : ""}${relatedError ? "; targets must start with \"./\"" : ""}`;
  3373. }
  3374. return `Invalid "${isImport ? "imports" : "exports"}" target ${JSON.stringify(target)} defined for '${key}' in the package config ${packagePath}package.json${base ? ` imported from ${base}` : ""}${relatedError ? "; targets must start with \"./\"" : ""}`;
  3375. },
  3376. Error
  3377. );
  3378. codes.ERR_MODULE_NOT_FOUND = createError(
  3379. "ERR_MODULE_NOT_FOUND",
  3380. /**
  3381. * @param {string} path
  3382. * @param {string} base
  3383. * @param {boolean} [exactUrl]
  3384. */
  3385. (path, base, exactUrl = false) => {
  3386. return `Cannot find ${exactUrl ? "module" : "package"} '${path}' imported from ${base}`;
  3387. },
  3388. Error
  3389. );
  3390. codes.ERR_NETWORK_IMPORT_DISALLOWED = createError("ERR_NETWORK_IMPORT_DISALLOWED", "import of '%s' by %s is not supported: %s", Error);
  3391. codes.ERR_PACKAGE_IMPORT_NOT_DEFINED = createError(
  3392. "ERR_PACKAGE_IMPORT_NOT_DEFINED",
  3393. /**
  3394. * @param {string} specifier
  3395. * @param {string} packagePath
  3396. * @param {string} base
  3397. */
  3398. (specifier, packagePath, base) => {
  3399. return `Package import specifier "${specifier}" is not defined${packagePath ? ` in package ${packagePath}package.json` : ""} imported from ${base}`;
  3400. },
  3401. TypeError
  3402. );
  3403. codes.ERR_PACKAGE_PATH_NOT_EXPORTED = createError(
  3404. "ERR_PACKAGE_PATH_NOT_EXPORTED",
  3405. /**
  3406. * @param {string} packagePath
  3407. * @param {string} subpath
  3408. * @param {string} [base]
  3409. */
  3410. (packagePath, subpath, base = void 0) => {
  3411. if (subpath === ".") return `No "exports" main defined in ${packagePath}package.json${base ? ` imported from ${base}` : ""}`;
  3412. return `Package subpath '${subpath}' is not defined by "exports" in ${packagePath}package.json${base ? ` imported from ${base}` : ""}`;
  3413. },
  3414. Error
  3415. );
  3416. codes.ERR_UNSUPPORTED_DIR_IMPORT = createError("ERR_UNSUPPORTED_DIR_IMPORT", "Directory import '%s' is not supported resolving ES modules imported from %s", Error);
  3417. codes.ERR_UNSUPPORTED_RESOLVE_REQUEST = createError("ERR_UNSUPPORTED_RESOLVE_REQUEST", "Failed to resolve module specifier \"%s\" from \"%s\": Invalid relative URL or base scheme is not hierarchical.", TypeError);
  3418. codes.ERR_UNKNOWN_FILE_EXTENSION = createError(
  3419. "ERR_UNKNOWN_FILE_EXTENSION",
  3420. /**
  3421. * @param {string} extension
  3422. * @param {string} path
  3423. */
  3424. (extension, path) => {
  3425. return `Unknown file extension "${extension}" for ${path}`;
  3426. },
  3427. TypeError
  3428. );
  3429. codes.ERR_INVALID_ARG_VALUE = createError(
  3430. "ERR_INVALID_ARG_VALUE",
  3431. /**
  3432. * @param {string} name
  3433. * @param {unknown} value
  3434. * @param {string} [reason='is invalid']
  3435. */
  3436. (name, value, reason = "is invalid") => {
  3437. let inspected = inspect(value);
  3438. if (inspected.length > 128) inspected = `${inspected.slice(0, 128)}...`;
  3439. return `The ${name.includes(".") ? "property" : "argument"} '${name}' ${reason}. Received ${inspected}`;
  3440. },
  3441. TypeError
  3442. );
  3443. /**
  3444. * Utility function for registering the error codes. Only used here. Exported
  3445. * *only* to allow for testing.
  3446. * @param {string} sym
  3447. * @param {MessageFunction | string} value
  3448. * @param {ErrorConstructor} constructor
  3449. * @returns {new (...parameters: Array<any>) => Error}
  3450. */
  3451. function createError(sym, value, constructor) {
  3452. messages.set(sym, value);
  3453. return makeNodeErrorWithCode(constructor, sym);
  3454. }
  3455. /**
  3456. * @param {ErrorConstructor} Base
  3457. * @param {string} key
  3458. * @returns {ErrorConstructor}
  3459. */
  3460. function makeNodeErrorWithCode(Base, key) {
  3461. return NodeError;
  3462. /**
  3463. * @param {Array<unknown>} parameters
  3464. */
  3465. function NodeError(...parameters) {
  3466. const limit = Error.stackTraceLimit;
  3467. if (isErrorStackTraceLimitWritable()) Error.stackTraceLimit = 0;
  3468. const error = new Base();
  3469. if (isErrorStackTraceLimitWritable()) Error.stackTraceLimit = limit;
  3470. const message = getMessage(key, parameters, error);
  3471. Object.defineProperties(error, {
  3472. message: {
  3473. value: message,
  3474. enumerable: false,
  3475. writable: true,
  3476. configurable: true
  3477. },
  3478. toString: {
  3479. value() {
  3480. return `${this.name} [${key}]: ${this.message}`;
  3481. },
  3482. enumerable: false,
  3483. writable: true,
  3484. configurable: true
  3485. }
  3486. });
  3487. captureLargerStackTrace(error);
  3488. error.code = key;
  3489. return error;
  3490. }
  3491. }
  3492. /**
  3493. * @returns {boolean}
  3494. */
  3495. function isErrorStackTraceLimitWritable() {
  3496. try {
  3497. if (v8.startupSnapshot.isBuildingSnapshot()) return false;
  3498. } catch {}
  3499. const desc = Object.getOwnPropertyDescriptor(Error, "stackTraceLimit");
  3500. if (desc === void 0) return Object.isExtensible(Error);
  3501. return own$1.call(desc, "writable") && desc.writable !== void 0 ? desc.writable : desc.set !== void 0;
  3502. }
  3503. /**
  3504. * This function removes unnecessary frames from Node.js core errors.
  3505. * @template {(...parameters: unknown[]) => unknown} T
  3506. * @param {T} wrappedFunction
  3507. * @returns {T}
  3508. */
  3509. function hideStackFrames(wrappedFunction) {
  3510. const hidden = nodeInternalPrefix + wrappedFunction.name;
  3511. Object.defineProperty(wrappedFunction, "name", { value: hidden });
  3512. return wrappedFunction;
  3513. }
  3514. const captureLargerStackTrace = hideStackFrames(
  3515. /**
  3516. * @param {Error} error
  3517. * @returns {Error}
  3518. */
  3519. function(error) {
  3520. const stackTraceLimitIsWritable = isErrorStackTraceLimitWritable();
  3521. if (stackTraceLimitIsWritable) {
  3522. userStackTraceLimit = Error.stackTraceLimit;
  3523. Error.stackTraceLimit = Number.POSITIVE_INFINITY;
  3524. }
  3525. Error.captureStackTrace(error);
  3526. if (stackTraceLimitIsWritable) Error.stackTraceLimit = userStackTraceLimit;
  3527. return error;
  3528. }
  3529. );
  3530. /**
  3531. * @param {string} key
  3532. * @param {Array<unknown>} parameters
  3533. * @param {Error} self
  3534. * @returns {string}
  3535. */
  3536. function getMessage(key, parameters, self) {
  3537. const message = messages.get(key);
  3538. assert.ok(message !== void 0, "expected `message` to be found");
  3539. if (typeof message === "function") {
  3540. assert.ok(message.length <= parameters.length, `Code: ${key}; The provided arguments length (${parameters.length}) does not match the required ones (${message.length}).`);
  3541. return Reflect.apply(message, self, parameters);
  3542. }
  3543. const regex = /%[dfijoOs]/g;
  3544. let expectedLength = 0;
  3545. while (regex.exec(message) !== null) expectedLength++;
  3546. assert.ok(expectedLength === parameters.length, `Code: ${key}; The provided arguments length (${parameters.length}) does not match the required ones (${expectedLength}).`);
  3547. if (parameters.length === 0) return message;
  3548. parameters.unshift(message);
  3549. return Reflect.apply(format, null, parameters);
  3550. }
  3551. /**
  3552. * Determine the specific type of a value for type-mismatch errors.
  3553. * @param {unknown} value
  3554. * @returns {string}
  3555. */
  3556. function determineSpecificType(value) {
  3557. if (value === null || value === void 0) return String(value);
  3558. if (typeof value === "function" && value.name) return `function ${value.name}`;
  3559. if (typeof value === "object") {
  3560. if (value.constructor && value.constructor.name) return `an instance of ${value.constructor.name}`;
  3561. return `${inspect(value, { depth: -1 })}`;
  3562. }
  3563. let inspected = inspect(value, { colors: false });
  3564. if (inspected.length > 28) inspected = `${inspected.slice(0, 25)}...`;
  3565. return `type ${typeof value} (${inspected})`;
  3566. }
  3567. const DEFAULT_CONDITIONS = Object.freeze(["node", "import"]);
  3568. new Set(DEFAULT_CONDITIONS);
  3569. const ESM_STATIC_IMPORT_RE = /(?<=\s|^|;|\})import\s*(?:[\s"']*(?<imports>[\p{L}\p{M}\w\t\n\r $*,/{}@.]+)from\s*)?["']\s*(?<specifier>(?<="\s*)[^"]*[^\s"](?=\s*")|(?<='\s*)[^']*[^\s'](?=\s*'))\s*["'][\s;]*/gmu;
  3570. const TYPE_RE = /^\s*?type\s/;
  3571. function parseStaticImport(matched) {
  3572. const cleanedImports = clearImports(matched.imports);
  3573. const namedImports = {};
  3574. const _matches = cleanedImports.match(/{([^}]*)}/)?.[1]?.split(",") || [];
  3575. for (const namedImport of _matches) {
  3576. const _match = namedImport.match(/^\s*(\S*) as (\S*)\s*$/);
  3577. const source = _match?.[1] || namedImport.trim();
  3578. const importName = _match?.[2] || source;
  3579. if (source && !TYPE_RE.test(source)) namedImports[source] = importName;
  3580. }
  3581. const { namespacedImport, defaultImport } = getImportNames(cleanedImports);
  3582. return {
  3583. ...matched,
  3584. defaultImport,
  3585. namespacedImport,
  3586. namedImports
  3587. };
  3588. }
  3589. const ESM_RE = /(?:[\s;]|^)(?:import[\s\w*,{}]*from|import\s*["'*{]|export\b\s*(?:[*{]|default|class|type|function|const|var|let|async function)|import\.meta\b)/m;
  3590. const COMMENT_RE = /\/\*.+?\*\/|\/\/.*(?=[nr])/g;
  3591. function hasESMSyntax(code, opts = {}) {
  3592. if (opts.stripComments) code = code.replace(COMMENT_RE, "");
  3593. return ESM_RE.test(code);
  3594. }
  3595. //#endregion
  3596. //#region ../../node_modules/.pnpm/es-module-lexer@1.7.0/node_modules/es-module-lexer/dist/lexer.js
  3597. var ImportType;
  3598. (function(A) {
  3599. A[A.Static = 1] = "Static", A[A.Dynamic = 2] = "Dynamic", A[A.ImportMeta = 3] = "ImportMeta", A[A.StaticSourcePhase = 4] = "StaticSourcePhase", A[A.DynamicSourcePhase = 5] = "DynamicSourcePhase", A[A.StaticDeferPhase = 6] = "StaticDeferPhase", A[A.DynamicDeferPhase = 7] = "DynamicDeferPhase";
  3600. })(ImportType || (ImportType = {}));
  3601. const A = 1 === new Uint8Array(new Uint16Array([1]).buffer)[0];
  3602. function parse$2(E, g = "@") {
  3603. if (!C) return init.then((() => parse$2(E)));
  3604. const I = E.length + 1, w = (C.__heap_base.value || C.__heap_base) + 4 * I - C.memory.buffer.byteLength;
  3605. w > 0 && C.memory.grow(Math.ceil(w / 65536));
  3606. const K = C.sa(I - 1);
  3607. if ((A ? B : Q)(E, new Uint16Array(C.memory.buffer, K, I)), !C.parse()) throw Object.assign(/* @__PURE__ */ new Error(`Parse error ${g}:${E.slice(0, C.e()).split("\n").length}:${C.e() - E.lastIndexOf("\n", C.e() - 1)}`), { idx: C.e() });
  3608. const o = [], D = [];
  3609. for (; C.ri();) {
  3610. const A = C.is(), Q = C.ie(), B = C.it(), g = C.ai(), I = C.id(), w = C.ss(), K = C.se();
  3611. let D;
  3612. C.ip() && (D = k(E.slice(-1 === I ? A - 1 : A, -1 === I ? Q + 1 : Q))), o.push({
  3613. n: D,
  3614. t: B,
  3615. s: A,
  3616. e: Q,
  3617. ss: w,
  3618. se: K,
  3619. d: I,
  3620. a: g
  3621. });
  3622. }
  3623. for (; C.re();) {
  3624. const A = C.es(), Q = C.ee(), B = C.els(), g = C.ele(), I = E.slice(A, Q), w = I[0], K = B < 0 ? void 0 : E.slice(B, g), o = K ? K[0] : "";
  3625. D.push({
  3626. s: A,
  3627. e: Q,
  3628. ls: B,
  3629. le: g,
  3630. n: "\"" === w || "'" === w ? k(I) : I,
  3631. ln: "\"" === o || "'" === o ? k(K) : K
  3632. });
  3633. }
  3634. function k(A) {
  3635. try {
  3636. return (0, eval)(A);
  3637. } catch (A) {}
  3638. }
  3639. return [
  3640. o,
  3641. D,
  3642. !!C.f(),
  3643. !!C.ms()
  3644. ];
  3645. }
  3646. function Q(A, Q) {
  3647. const B = A.length;
  3648. let C = 0;
  3649. for (; C < B;) {
  3650. const B = A.charCodeAt(C);
  3651. Q[C++] = (255 & B) << 8 | B >>> 8;
  3652. }
  3653. }
  3654. function B(A, Q) {
  3655. const B = A.length;
  3656. let C = 0;
  3657. for (; C < B;) Q[C] = A.charCodeAt(C++);
  3658. }
  3659. let C;
  3660. const E = () => {
  3661. return A = "AGFzbQEAAAABKwhgAX8Bf2AEf39/fwBgAAF/YAAAYAF/AGADf39/AX9gAn9/AX9gA39/fwADMTAAAQECAgICAgICAgICAgICAgICAgIAAwMDBAQAAAUAAAAAAAMDAwAGAAAABwAGAgUEBQFwAQEBBQMBAAEGDwJ/AUHA8gALfwBBwPIACwd6FQZtZW1vcnkCAAJzYQAAAWUAAwJpcwAEAmllAAUCc3MABgJzZQAHAml0AAgCYWkACQJpZAAKAmlwAAsCZXMADAJlZQANA2VscwAOA2VsZQAPAnJpABACcmUAEQFmABICbXMAEwVwYXJzZQAUC19faGVhcF9iYXNlAwEKzkQwaAEBf0EAIAA2AoAKQQAoAtwJIgEgAEEBdGoiAEEAOwEAQQAgAEECaiIANgKECkEAIAA2AogKQQBBADYC4AlBAEEANgLwCUEAQQA2AugJQQBBADYC5AlBAEEANgL4CUEAQQA2AuwJIAEL0wEBA39BACgC8AkhBEEAQQAoAogKIgU2AvAJQQAgBDYC9AlBACAFQSRqNgKICiAEQSBqQeAJIAQbIAU2AgBBACgC1AkhBEEAKALQCSEGIAUgATYCACAFIAA2AgggBSACIAJBAmpBACAGIANGIgAbIAQgA0YiBBs2AgwgBSADNgIUIAVBADYCECAFIAI2AgQgBUEANgIgIAVBA0EBQQIgABsgBBs2AhwgBUEAKALQCSADRiICOgAYAkACQCACDQBBACgC1AkgA0cNAQtBAEEBOgCMCgsLXgEBf0EAKAL4CSIEQRBqQeQJIAQbQQAoAogKIgQ2AgBBACAENgL4CUEAIARBFGo2AogKQQBBAToAjAogBEEANgIQIAQgAzYCDCAEIAI2AgggBCABNgIEIAQgADYCAAsIAEEAKAKQCgsVAEEAKALoCSgCAEEAKALcCWtBAXULHgEBf0EAKALoCSgCBCIAQQAoAtwJa0EBdUF/IAAbCxUAQQAoAugJKAIIQQAoAtwJa0EBdQseAQF/QQAoAugJKAIMIgBBACgC3AlrQQF1QX8gABsLCwBBACgC6AkoAhwLHgEBf0EAKALoCSgCECIAQQAoAtwJa0EBdUF/IAAbCzsBAX8CQEEAKALoCSgCFCIAQQAoAtAJRw0AQX8PCwJAIABBACgC1AlHDQBBfg8LIABBACgC3AlrQQF1CwsAQQAoAugJLQAYCxUAQQAoAuwJKAIAQQAoAtwJa0EBdQsVAEEAKALsCSgCBEEAKALcCWtBAXULHgEBf0EAKALsCSgCCCIAQQAoAtwJa0EBdUF/IAAbCx4BAX9BACgC7AkoAgwiAEEAKALcCWtBAXVBfyAAGwslAQF/QQBBACgC6AkiAEEgakHgCSAAGygCACIANgLoCSAAQQBHCyUBAX9BAEEAKALsCSIAQRBqQeQJIAAbKAIAIgA2AuwJIABBAEcLCABBAC0AlAoLCABBAC0AjAoL3Q0BBX8jAEGA0ABrIgAkAEEAQQE6AJQKQQBBACgC2Ak2ApwKQQBBACgC3AlBfmoiATYCsApBACABQQAoAoAKQQF0aiICNgK0CkEAQQA6AIwKQQBBADsBlgpBAEEAOwGYCkEAQQA6AKAKQQBBADYCkApBAEEAOgD8CUEAIABBgBBqNgKkCkEAIAA2AqgKQQBBADoArAoCQAJAAkACQANAQQAgAUECaiIDNgKwCiABIAJPDQECQCADLwEAIgJBd2pBBUkNAAJAAkACQAJAAkAgAkGbf2oOBQEICAgCAAsgAkEgRg0EIAJBL0YNAyACQTtGDQIMBwtBAC8BmAoNASADEBVFDQEgAUEEakGCCEEKEC8NARAWQQAtAJQKDQFBAEEAKAKwCiIBNgKcCgwHCyADEBVFDQAgAUEEakGMCEEKEC8NABAXC0EAQQAoArAKNgKcCgwBCwJAIAEvAQQiA0EqRg0AIANBL0cNBBAYDAELQQEQGQtBACgCtAohAkEAKAKwCiEBDAALC0EAIQIgAyEBQQAtAPwJDQIMAQtBACABNgKwCkEAQQA6AJQKCwNAQQAgAUECaiIDNgKwCgJAAkACQAJAAkACQAJAIAFBACgCtApPDQAgAy8BACICQXdqQQVJDQYCQAJAAkACQAJAAkACQAJAAkACQCACQWBqDgoQDwYPDw8PBQECAAsCQAJAAkACQCACQaB/ag4KCxISAxIBEhISAgALIAJBhX9qDgMFEQYJC0EALwGYCg0QIAMQFUUNECABQQRqQYIIQQoQLw0QEBYMEAsgAxAVRQ0PIAFBBGpBjAhBChAvDQ8QFwwPCyADEBVFDQ4gASkABELsgISDsI7AOVINDiABLwEMIgNBd2oiAUEXSw0MQQEgAXRBn4CABHFFDQwMDQtBAEEALwGYCiIBQQFqOwGYCkEAKAKkCiABQQN0aiIBQQE2AgAgAUEAKAKcCjYCBAwNC0EALwGYCiIDRQ0JQQAgA0F/aiIDOwGYCkEALwGWCiICRQ0MQQAoAqQKIANB//8DcUEDdGooAgBBBUcNDAJAIAJBAnRBACgCqApqQXxqKAIAIgMoAgQNACADQQAoApwKQQJqNgIEC0EAIAJBf2o7AZYKIAMgAUEEajYCDAwMCwJAQQAoApwKIgEvAQBBKUcNAEEAKALwCSIDRQ0AIAMoAgQgAUcNAEEAQQAoAvQJIgM2AvAJAkAgA0UNACADQQA2AiAMAQtBAEEANgLgCQtBAEEALwGYCiIDQQFqOwGYCkEAKAKkCiADQQN0aiIDQQZBAkEALQCsChs2AgAgAyABNgIEQQBBADoArAoMCwtBAC8BmAoiAUUNB0EAIAFBf2oiATsBmApBACgCpAogAUH//wNxQQN0aigCAEEERg0EDAoLQScQGgwJC0EiEBoMCAsgAkEvRw0HAkACQCABLwEEIgFBKkYNACABQS9HDQEQGAwKC0EBEBkMCQsCQAJAAkACQEEAKAKcCiIBLwEAIgMQG0UNAAJAAkAgA0FVag4EAAkBAwkLIAFBfmovAQBBK0YNAwwICyABQX5qLwEAQS1GDQIMBwsgA0EpRw0BQQAoAqQKQQAvAZgKIgJBA3RqKAIEEBxFDQIMBgsgAUF+ai8BAEFQakH//wNxQQpPDQULQQAvAZgKIQILAkACQCACQf//A3EiAkUNACADQeYARw0AQQAoAqQKIAJBf2pBA3RqIgQoAgBBAUcNACABQX5qLwEAQe8ARw0BIAQoAgRBlghBAxAdRQ0BDAULIANB/QBHDQBBACgCpAogAkEDdGoiAigCBBAeDQQgAigCAEEGRg0ECyABEB8NAyADRQ0DIANBL0ZBAC0AoApBAEdxDQMCQEEAKAL4CSICRQ0AIAEgAigCAEkNACABIAIoAgRNDQQLIAFBfmohAUEAKALcCSECAkADQCABQQJqIgQgAk0NAUEAIAE2ApwKIAEvAQAhAyABQX5qIgQhASADECBFDQALIARBAmohBAsCQCADQf//A3EQIUUNACAEQX5qIQECQANAIAFBAmoiAyACTQ0BQQAgATYCnAogAS8BACEDIAFBfmoiBCEBIAMQIQ0ACyAEQQJqIQMLIAMQIg0EC0EAQQE6AKAKDAcLQQAoAqQKQQAvAZgKIgFBA3QiA2pBACgCnAo2AgRBACABQQFqOwGYCkEAKAKkCiADakEDNgIACxAjDAULQQAtAPwJQQAvAZYKQQAvAZgKcnJFIQIMBwsQJEEAQQA6AKAKDAMLECVBACECDAULIANBoAFHDQELQQBBAToArAoLQQBBACgCsAo2ApwKC0EAKAKwCiEBDAALCyAAQYDQAGokACACCxoAAkBBACgC3AkgAEcNAEEBDwsgAEF+ahAmC/4KAQZ/QQBBACgCsAoiAEEMaiIBNgKwCkEAKAL4CSECQQEQKSEDAkACQAJAAkACQAJAAkACQAJAQQAoArAKIgQgAUcNACADEChFDQELAkACQAJAAkACQAJAAkAgA0EqRg0AIANB+wBHDQFBACAEQQJqNgKwCkEBECkhA0EAKAKwCiEEA0ACQAJAIANB//8DcSIDQSJGDQAgA0EnRg0AIAMQLBpBACgCsAohAwwBCyADEBpBAEEAKAKwCkECaiIDNgKwCgtBARApGgJAIAQgAxAtIgNBLEcNAEEAQQAoArAKQQJqNgKwCkEBECkhAwsgA0H9AEYNA0EAKAKwCiIFIARGDQ8gBSEEIAVBACgCtApNDQAMDwsLQQAgBEECajYCsApBARApGkEAKAKwCiIDIAMQLRoMAgtBAEEAOgCUCgJAAkACQAJAAkACQCADQZ9/ag4MAgsEAQsDCwsLCwsFAAsgA0H2AEYNBAwKC0EAIARBDmoiAzYCsAoCQAJAAkBBARApQZ9/ag4GABICEhIBEgtBACgCsAoiBSkAAkLzgOSD4I3AMVINESAFLwEKECFFDRFBACAFQQpqNgKwCkEAECkaC0EAKAKwCiIFQQJqQbIIQQ4QLw0QIAUvARAiAkF3aiIBQRdLDQ1BASABdEGfgIAEcUUNDQwOC0EAKAKwCiIFKQACQuyAhIOwjsA5Ug0PIAUvAQoiAkF3aiIBQRdNDQYMCgtBACAEQQpqNgKwCkEAECkaQQAoArAKIQQLQQAgBEEQajYCsAoCQEEBECkiBEEqRw0AQQBBACgCsApBAmo2ArAKQQEQKSEEC0EAKAKwCiEDIAQQLBogA0EAKAKwCiIEIAMgBBACQQBBACgCsApBfmo2ArAKDwsCQCAEKQACQuyAhIOwjsA5Ug0AIAQvAQoQIEUNAEEAIARBCmo2ArAKQQEQKSEEQQAoArAKIQMgBBAsGiADQQAoArAKIgQgAyAEEAJBAEEAKAKwCkF+ajYCsAoPC0EAIARBBGoiBDYCsAoLQQAgBEEGajYCsApBAEEAOgCUCkEBECkhBEEAKAKwCiEDIAQQLCEEQQAoArAKIQIgBEHf/wNxIgFB2wBHDQNBACACQQJqNgKwCkEBECkhBUEAKAKwCiEDQQAhBAwEC0EAQQE6AIwKQQBBACgCsApBAmo2ArAKC0EBECkhBEEAKAKwCiEDAkAgBEHmAEcNACADQQJqQawIQQYQLw0AQQAgA0EIajYCsAogAEEBEClBABArIAJBEGpB5AkgAhshAwNAIAMoAgAiA0UNBSADQgA3AgggA0EQaiEDDAALC0EAIANBfmo2ArAKDAMLQQEgAXRBn4CABHFFDQMMBAtBASEECwNAAkACQCAEDgIAAQELIAVB//8DcRAsGkEBIQQMAQsCQAJAQQAoArAKIgQgA0YNACADIAQgAyAEEAJBARApIQQCQCABQdsARw0AIARBIHJB/QBGDQQLQQAoArAKIQMCQCAEQSxHDQBBACADQQJqNgKwCkEBECkhBUEAKAKwCiEDIAVBIHJB+wBHDQILQQAgA0F+ajYCsAoLIAFB2wBHDQJBACACQX5qNgKwCg8LQQAhBAwACwsPCyACQaABRg0AIAJB+wBHDQQLQQAgBUEKajYCsApBARApIgVB+wBGDQMMAgsCQCACQVhqDgMBAwEACyACQaABRw0CC0EAIAVBEGo2ArAKAkBBARApIgVBKkcNAEEAQQAoArAKQQJqNgKwCkEBECkhBQsgBUEoRg0BC0EAKAKwCiEBIAUQLBpBACgCsAoiBSABTQ0AIAQgAyABIAUQAkEAQQAoArAKQX5qNgKwCg8LIAQgA0EAQQAQAkEAIARBDGo2ArAKDwsQJQuFDAEKf0EAQQAoArAKIgBBDGoiATYCsApBARApIQJBACgCsAohAwJAAkACQAJAAkACQAJAAkAgAkEuRw0AQQAgA0ECajYCsAoCQEEBECkiAkHkAEYNAAJAIAJB8wBGDQAgAkHtAEcNB0EAKAKwCiICQQJqQZwIQQYQLw0HAkBBACgCnAoiAxAqDQAgAy8BAEEuRg0ICyAAIAAgAkEIakEAKALUCRABDwtBACgCsAoiAkECakGiCEEKEC8NBgJAQQAoApwKIgMQKg0AIAMvAQBBLkYNBwtBACEEQQAgAkEMajYCsApBASEFQQUhBkEBECkhAkEAIQdBASEIDAILQQAoArAKIgIpAAJC5YCYg9CMgDlSDQUCQEEAKAKcCiIDECoNACADLwEAQS5GDQYLQQAhBEEAIAJBCmo2ArAKQQIhCEEHIQZBASEHQQEQKSECQQEhBQwBCwJAAkACQAJAIAJB8wBHDQAgAyABTQ0AIANBAmpBoghBChAvDQACQCADLwEMIgRBd2oiB0EXSw0AQQEgB3RBn4CABHENAgsgBEGgAUYNAQtBACEHQQchBkEBIQQgAkHkAEYNAQwCC0EAIQRBACADQQxqIgI2ArAKQQEhBUEBECkhCQJAQQAoArAKIgYgAkYNAEHmACECAkAgCUHmAEYNAEEFIQZBACEHQQEhCCAJIQIMBAtBACEHQQEhCCAGQQJqQawIQQYQLw0EIAYvAQgQIEUNBAtBACEHQQAgAzYCsApBByEGQQEhBEEAIQVBACEIIAkhAgwCCyADIABBCmpNDQBBACEIQeQAIQICQCADKQACQuWAmIPQjIA5Ug0AAkACQCADLwEKIgRBd2oiB0EXSw0AQQEgB3RBn4CABHENAQtBACEIIARBoAFHDQELQQAhBUEAIANBCmo2ArAKQSohAkEBIQdBAiEIQQEQKSIJQSpGDQRBACADNgKwCkEBIQRBACEHQQAhCCAJIQIMAgsgAyEGQQAhBwwCC0EAIQVBACEICwJAIAJBKEcNAEEAKAKkCkEALwGYCiICQQN0aiIDQQAoArAKNgIEQQAgAkEBajsBmAogA0EFNgIAQQAoApwKLwEAQS5GDQRBAEEAKAKwCiIDQQJqNgKwCkEBECkhAiAAQQAoArAKQQAgAxABAkACQCAFDQBBACgC8AkhAQwBC0EAKALwCSIBIAY2AhwLQQBBAC8BlgoiA0EBajsBlgpBACgCqAogA0ECdGogATYCAAJAIAJBIkYNACACQSdGDQBBAEEAKAKwCkF+ajYCsAoPCyACEBpBAEEAKAKwCkECaiICNgKwCgJAAkACQEEBEClBV2oOBAECAgACC0EAQQAoArAKQQJqNgKwCkEBECkaQQAoAvAJIgMgAjYCBCADQQE6ABggA0EAKAKwCiICNgIQQQAgAkF+ajYCsAoPC0EAKALwCSIDIAI2AgQgA0EBOgAYQQBBAC8BmApBf2o7AZgKIANBACgCsApBAmo2AgxBAEEALwGWCkF/ajsBlgoPC0EAQQAoArAKQX5qNgKwCg8LAkAgBEEBcyACQfsAR3INAEEAKAKwCiECQQAvAZgKDQUDQAJAAkACQCACQQAoArQKTw0AQQEQKSICQSJGDQEgAkEnRg0BIAJB/QBHDQJBAEEAKAKwCkECajYCsAoLQQEQKSEDQQAoArAKIQICQCADQeYARw0AIAJBAmpBrAhBBhAvDQcLQQAgAkEIajYCsAoCQEEBECkiAkEiRg0AIAJBJ0cNBwsgACACQQAQKw8LIAIQGgtBAEEAKAKwCkECaiICNgKwCgwACwsCQAJAIAJBWWoOBAMBAQMACyACQSJGDQILQQAoArAKIQYLIAYgAUcNAEEAIABBCmo2ArAKDwsgAkEqRyAHcQ0DQQAvAZgKQf//A3ENA0EAKAKwCiECQQAoArQKIQEDQCACIAFPDQECQAJAIAIvAQAiA0EnRg0AIANBIkcNAQsgACADIAgQKw8LQQAgAkECaiICNgKwCgwACwsQJQsPC0EAIAJBfmo2ArAKDwtBAEEAKAKwCkF+ajYCsAoLRwEDf0EAKAKwCkECaiEAQQAoArQKIQECQANAIAAiAkF+aiABTw0BIAJBAmohACACLwEAQXZqDgQBAAABAAsLQQAgAjYCsAoLmAEBA39BAEEAKAKwCiIBQQJqNgKwCiABQQZqIQFBACgCtAohAgNAAkACQAJAIAFBfGogAk8NACABQX5qLwEAIQMCQAJAIAANACADQSpGDQEgA0F2ag4EAgQEAgQLIANBKkcNAwsgAS8BAEEvRw0CQQAgAUF+ajYCsAoMAQsgAUF+aiEBC0EAIAE2ArAKDwsgAUECaiEBDAALC4gBAQR/QQAoArAKIQFBACgCtAohAgJAAkADQCABIgNBAmohASADIAJPDQEgAS8BACIEIABGDQICQCAEQdwARg0AIARBdmoOBAIBAQIBCyADQQRqIQEgAy8BBEENRw0AIANBBmogASADLwEGQQpGGyEBDAALC0EAIAE2ArAKECUPC0EAIAE2ArAKC2wBAX8CQAJAIABBX2oiAUEFSw0AQQEgAXRBMXENAQsgAEFGakH//wNxQQZJDQAgAEEpRyAAQVhqQf//A3FBB0lxDQACQCAAQaV/ag4EAQAAAQALIABB/QBHIABBhX9qQf//A3FBBElxDwtBAQsuAQF/QQEhAQJAIABBpglBBRAdDQAgAEGWCEEDEB0NACAAQbAJQQIQHSEBCyABC0YBA39BACEDAkAgACACQQF0IgJrIgRBAmoiAEEAKALcCSIFSQ0AIAAgASACEC8NAAJAIAAgBUcNAEEBDwsgBBAmIQMLIAMLgwEBAn9BASEBAkACQAJAAkACQAJAIAAvAQAiAkFFag4EBQQEAQALAkAgAkGbf2oOBAMEBAIACyACQSlGDQQgAkH5AEcNAyAAQX5qQbwJQQYQHQ8LIABBfmovAQBBPUYPCyAAQX5qQbQJQQQQHQ8LIABBfmpByAlBAxAdDwtBACEBCyABC7QDAQJ/QQAhAQJAAkACQAJAAkACQAJAAkACQAJAIAAvAQBBnH9qDhQAAQIJCQkJAwkJBAUJCQYJBwkJCAkLAkACQCAAQX5qLwEAQZd/ag4EAAoKAQoLIABBfGpByghBAhAdDwsgAEF8akHOCEEDEB0PCwJAAkACQCAAQX5qLwEAQY1/ag4DAAECCgsCQCAAQXxqLwEAIgJB4QBGDQAgAkHsAEcNCiAAQXpqQeUAECcPCyAAQXpqQeMAECcPCyAAQXxqQdQIQQQQHQ8LIABBfGpB3AhBBhAdDwsgAEF+ai8BAEHvAEcNBiAAQXxqLwEAQeUARw0GAkAgAEF6ai8BACICQfAARg0AIAJB4wBHDQcgAEF4akHoCEEGEB0PCyAAQXhqQfQIQQIQHQ8LIABBfmpB+AhBBBAdDwtBASEBIABBfmoiAEHpABAnDQQgAEGACUEFEB0PCyAAQX5qQeQAECcPCyAAQX5qQYoJQQcQHQ8LIABBfmpBmAlBBBAdDwsCQCAAQX5qLwEAIgJB7wBGDQAgAkHlAEcNASAAQXxqQe4AECcPCyAAQXxqQaAJQQMQHSEBCyABCzQBAX9BASEBAkAgAEF3akH//wNxQQVJDQAgAEGAAXJBoAFGDQAgAEEuRyAAEChxIQELIAELMAEBfwJAAkAgAEF3aiIBQRdLDQBBASABdEGNgIAEcQ0BCyAAQaABRg0AQQAPC0EBC04BAn9BACEBAkACQCAALwEAIgJB5QBGDQAgAkHrAEcNASAAQX5qQfgIQQQQHQ8LIABBfmovAQBB9QBHDQAgAEF8akHcCEEGEB0hAQsgAQveAQEEf0EAKAKwCiEAQQAoArQKIQECQAJAAkADQCAAIgJBAmohACACIAFPDQECQAJAAkAgAC8BACIDQaR/ag4FAgMDAwEACyADQSRHDQIgAi8BBEH7AEcNAkEAIAJBBGoiADYCsApBAEEALwGYCiICQQFqOwGYCkEAKAKkCiACQQN0aiICQQQ2AgAgAiAANgIEDwtBACAANgKwCkEAQQAvAZgKQX9qIgA7AZgKQQAoAqQKIABB//8DcUEDdGooAgBBA0cNAwwECyACQQRqIQAMAAsLQQAgADYCsAoLECULC3ABAn8CQAJAA0BBAEEAKAKwCiIAQQJqIgE2ArAKIABBACgCtApPDQECQAJAAkAgAS8BACIBQaV/ag4CAQIACwJAIAFBdmoOBAQDAwQACyABQS9HDQIMBAsQLhoMAQtBACAAQQRqNgKwCgwACwsQJQsLNQEBf0EAQQE6APwJQQAoArAKIQBBAEEAKAK0CkECajYCsApBACAAQQAoAtwJa0EBdTYCkAoLQwECf0EBIQECQCAALwEAIgJBd2pB//8DcUEFSQ0AIAJBgAFyQaABRg0AQQAhASACEChFDQAgAkEuRyAAECpyDwsgAQs9AQJ/QQAhAgJAQQAoAtwJIgMgAEsNACAALwEAIAFHDQACQCADIABHDQBBAQ8LIABBfmovAQAQICECCyACC2gBAn9BASEBAkACQCAAQV9qIgJBBUsNAEEBIAJ0QTFxDQELIABB+P8DcUEoRg0AIABBRmpB//8DcUEGSQ0AAkAgAEGlf2oiAkEDSw0AIAJBAUcNAQsgAEGFf2pB//8DcUEESSEBCyABC5wBAQN/QQAoArAKIQECQANAAkACQCABLwEAIgJBL0cNAAJAIAEvAQIiAUEqRg0AIAFBL0cNBBAYDAILIAAQGQwBCwJAAkAgAEUNACACQXdqIgFBF0sNAUEBIAF0QZ+AgARxRQ0BDAILIAIQIUUNAwwBCyACQaABRw0CC0EAQQAoArAKIgNBAmoiATYCsAogA0EAKAK0CkkNAAsLIAILMQEBf0EAIQECQCAALwEAQS5HDQAgAEF+ai8BAEEuRw0AIABBfGovAQBBLkYhAQsgAQumBAEBfwJAIAFBIkYNACABQSdGDQAQJQ8LQQAoArAKIQMgARAaIAAgA0ECakEAKAKwCkEAKALQCRABAkAgAkEBSA0AQQAoAvAJQQRBBiACQQFGGzYCHAtBAEEAKAKwCkECajYCsAoCQAJAAkACQEEAECkiAUHhAEYNACABQfcARg0BQQAoArAKIQEMAgtBACgCsAoiAUECakHACEEKEC8NAUEGIQIMAgtBACgCsAoiAS8BAkHpAEcNACABLwEEQfQARw0AQQQhAiABLwEGQegARg0BC0EAIAFBfmo2ArAKDwtBACABIAJBAXRqNgKwCgJAQQEQKUH7AEYNAEEAIAE2ArAKDwtBACgCsAoiACECA0BBACACQQJqNgKwCgJAAkACQEEBECkiAkEiRg0AIAJBJ0cNAUEnEBpBAEEAKAKwCkECajYCsApBARApIQIMAgtBIhAaQQBBACgCsApBAmo2ArAKQQEQKSECDAELIAIQLCECCwJAIAJBOkYNAEEAIAE2ArAKDwtBAEEAKAKwCkECajYCsAoCQEEBECkiAkEiRg0AIAJBJ0YNAEEAIAE2ArAKDwsgAhAaQQBBACgCsApBAmo2ArAKAkACQEEBECkiAkEsRg0AIAJB/QBGDQFBACABNgKwCg8LQQBBACgCsApBAmo2ArAKQQEQKUH9AEYNAEEAKAKwCiECDAELC0EAKALwCSIBIAA2AhAgAUEAKAKwCkECajYCDAttAQJ/AkACQANAAkAgAEH//wNxIgFBd2oiAkEXSw0AQQEgAnRBn4CABHENAgsgAUGgAUYNASAAIQIgARAoDQJBACECQQBBACgCsAoiAEECajYCsAogAC8BAiIADQAMAgsLIAAhAgsgAkH//wNxC6sBAQR/AkACQEEAKAKwCiICLwEAIgNB4QBGDQAgASEEIAAhBQwBC0EAIAJBBGo2ArAKQQEQKSECQQAoArAKIQUCQAJAIAJBIkYNACACQSdGDQAgAhAsGkEAKAKwCiEEDAELIAIQGkEAQQAoArAKQQJqIgQ2ArAKC0EBECkhA0EAKAKwCiECCwJAIAIgBUYNACAFIARBACAAIAAgAUYiAhtBACABIAIbEAILIAMLcgEEf0EAKAKwCiEAQQAoArQKIQECQAJAA0AgAEECaiECIAAgAU8NAQJAAkAgAi8BACIDQaR/ag4CAQQACyACIQAgA0F2ag4EAgEBAgELIABBBGohAAwACwtBACACNgKwChAlQQAPC0EAIAI2ArAKQd0AC0kBA39BACEDAkAgAkUNAAJAA0AgAC0AACIEIAEtAAAiBUcNASABQQFqIQEgAEEBaiEAIAJBf2oiAg0ADAILCyAEIAVrIQMLIAMLC+wBAgBBgAgLzgEAAHgAcABvAHIAdABtAHAAbwByAHQAZgBvAHIAZQB0AGEAbwB1AHIAYwBlAHIAbwBtAHUAbgBjAHQAaQBvAG4AcwBzAGUAcgB0AHYAbwB5AGkAZQBkAGUAbABlAGMAbwBuAHQAaQBuAGkAbgBzAHQAYQBuAHQAeQBiAHIAZQBhAHIAZQB0AHUAcgBkAGUAYgB1AGcAZwBlAGEAdwBhAGkAdABoAHIAdwBoAGkAbABlAGkAZgBjAGEAdABjAGYAaQBuAGEAbABsAGUAbABzAABB0AkLEAEAAAACAAAAAAQAAEA5AAA=", "undefined" != typeof Buffer ? Buffer.from(A, "base64") : Uint8Array.from(atob(A), ((A) => A.charCodeAt(0)));
  3662. var A;
  3663. };
  3664. const init = WebAssembly.compile(E()).then(WebAssembly.instantiate).then((({ exports: A }) => {
  3665. C = A;
  3666. }));
  3667. //#endregion
  3668. //#region src/node/plugins/oxc.ts
  3669. const IIFE_BEGIN_RE = /(?:(?:(?:const|var)\s+[^.\s]+|[^.\s]+\.[^.\s]+\.[^.\s]+)\s*=\s*|^|\n)\(?function\([^()]*\)\s*\{(?:\s*"use strict";)?/;
  3670. const UMD_BEGIN_RE = /\}\)\((?:this,\s*)?function\([^()]*\)\s*\{(?:\s*"use strict";)?/;
  3671. const jsxExtensionsRE = /\.(?:j|t)sx\b/;
  3672. const validExtensionRE = /\.\w+$/;
  3673. function getRollupJsxPresets(preset) {
  3674. switch (preset) {
  3675. case "react": return {
  3676. runtime: "classic",
  3677. pragma: "React.createElement",
  3678. pragmaFrag: "React.Fragment",
  3679. importSource: "react"
  3680. };
  3681. case "react-jsx": return {
  3682. runtime: "automatic",
  3683. pragma: "React.createElement",
  3684. importSource: "react"
  3685. };
  3686. }
  3687. }
  3688. function joinNewLine(s1, s2) {
  3689. return s1.replace(/\n+$/, "") + "\n" + s2.replace(/^\n+/, "");
  3690. }
  3691. function getErrorMessage(e) {
  3692. if (Object.hasOwn(e, "kind")) return e.message;
  3693. let s = "";
  3694. if (e.plugin) s += `[plugin ${e.plugin}]`;
  3695. const id = e.id ?? e.loc?.file;
  3696. if (id) {
  3697. s += " " + id;
  3698. if (e.loc) s += `:${e.loc.line}:${e.loc.column}`;
  3699. }
  3700. if (s) s += "\n";
  3701. const message = `${e.name ?? "Error"}: ${e.message}`;
  3702. s += message;
  3703. if (e.frame) s = joinNewLine(s, e.frame);
  3704. if (e.stack) s = joinNewLine(s, e.stack.replace(message, ""));
  3705. if (e.cause) {
  3706. s = joinNewLine(s, "Caused by:");
  3707. s = joinNewLine(s, getErrorMessage(e.cause).split("\n").map((line) => " " + line).join("\n"));
  3708. }
  3709. return s;
  3710. }
  3711. async function transformWithOxc(code, filename, options, inMap, config, watcher) {
  3712. let lang = options?.lang;
  3713. if (!lang) {
  3714. const ext = path.extname(validExtensionRE.test(filename) ? filename : cleanUrl(filename)).slice(1);
  3715. if (ext === "cjs" || ext === "mjs") lang = "js";
  3716. else if (ext === "cts" || ext === "mts") lang = "ts";
  3717. else lang = ext;
  3718. }
  3719. const result = transformSync(filename, code, {
  3720. sourcemap: true,
  3721. ...options,
  3722. inputMap: inMap,
  3723. lang
  3724. }, getTSConfigResolutionCache(config));
  3725. if (watcher && config && result.tsconfigFilePaths && result.tsconfigFilePaths.length > 0) for (const tsconfigFile of result.tsconfigFilePaths) ensureWatchedFile(watcher, normalizePath(tsconfigFile), config.root);
  3726. if (result.errors.length > 0) {
  3727. let summary = `Transform failed with ${result.errors.length} error${result.errors.length < 2 ? "" : "s"}:\n`;
  3728. for (let i = 0; i < result.errors.length; i++) {
  3729. summary += "\n";
  3730. if (i >= 5) {
  3731. summary += "...";
  3732. break;
  3733. }
  3734. summary += getErrorMessage(result.errors[i]);
  3735. }
  3736. const wrapper = new Error(summary);
  3737. Object.defineProperty(wrapper, "errors", {
  3738. configurable: true,
  3739. enumerable: true,
  3740. get: () => result.errors,
  3741. set: (value) => Object.defineProperty(wrapper, "errors", {
  3742. configurable: true,
  3743. enumerable: true,
  3744. value
  3745. })
  3746. });
  3747. throw wrapper;
  3748. }
  3749. return result;
  3750. }
  3751. const warnedMessages = /* @__PURE__ */ new Set();
  3752. function shouldSkipWarning(warning) {
  3753. if (warning.code === "UNSUPPORTED_TSCONFIG_OPTION") {
  3754. if (warnedMessages.has(warning.message)) return true;
  3755. warnedMessages.add(warning.message);
  3756. }
  3757. return false;
  3758. }
  3759. function oxcPlugin(config) {
  3760. if (config.isBundled) return perEnvironmentPlugin("native:transform", (environment) => {
  3761. const { jsxInject, include = /\.(m?ts|[jt]sx)$/, exclude = /\.js$/, jsxRefreshInclude, jsxRefreshExclude, ..._transformOptions } = config.oxc;
  3762. const transformOptions = _transformOptions;
  3763. transformOptions.sourcemap = environment.config.mode !== "build" || !!environment.config.build.sourcemap;
  3764. return viteTransformPlugin({
  3765. root: environment.config.root,
  3766. include,
  3767. exclude,
  3768. jsxRefreshInclude,
  3769. jsxRefreshExclude,
  3770. isServerConsumer: environment.config.consumer === "server",
  3771. jsxInject,
  3772. transformOptions
  3773. });
  3774. });
  3775. const { jsxInject, include, exclude, jsxRefreshInclude, jsxRefreshExclude, ...oxcTransformOptions } = config.oxc;
  3776. const filter = createFilter$1(include || /\.(m?ts|[jt]sx)$/, exclude || /\.js$/);
  3777. const jsxRefreshFilter = jsxRefreshInclude || jsxRefreshExclude ? createFilter$1(jsxRefreshInclude, jsxRefreshExclude) : void 0;
  3778. const jsxImportSource = typeof oxcTransformOptions.jsx === "object" && oxcTransformOptions.jsx.importSource || "react";
  3779. const jsxImportRuntime = `${jsxImportSource}/jsx-runtime`;
  3780. const jsxImportDevRuntime = `${jsxImportSource}/jsx-dev-runtime`;
  3781. const getModifiedOxcTransformOptions = (oxcTransformOptions, id, code, environment) => {
  3782. const result = {
  3783. ...oxcTransformOptions,
  3784. sourcemap: environment.mode !== "build" || !!environment.config.build.sourcemap
  3785. };
  3786. const jsxOptions = result.jsx;
  3787. const [filepath] = id.split("?");
  3788. const isJSX = filepath.endsWith("x");
  3789. if (typeof jsxOptions === "object" && jsxOptions.refresh && (environment.config.consumer === "server" || jsxRefreshFilter && !jsxRefreshFilter(id) || !(isJSX || code.includes(jsxImportRuntime) || code.includes(jsxImportDevRuntime)))) result.jsx = {
  3790. ...jsxOptions,
  3791. refresh: false
  3792. };
  3793. if (jsxRefreshFilter?.(id) && !JS_TYPES_RE.test(cleanUrl(id))) result.lang = "js";
  3794. return result;
  3795. };
  3796. let server;
  3797. return {
  3798. name: "vite:oxc",
  3799. configureServer(_server) {
  3800. server = _server;
  3801. },
  3802. async transform(code, id) {
  3803. if (filter(id) || filter(cleanUrl(id)) || jsxRefreshFilter?.(id)) {
  3804. const result = await transformWithOxc(code, id, getModifiedOxcTransformOptions(oxcTransformOptions, id, code, this.environment), void 0, config, server?.watcher);
  3805. if (jsxInject && jsxExtensionsRE.test(id)) result.code = jsxInject + ";" + result.code;
  3806. for (const warning of result.warnings) if (!shouldSkipWarning(warning)) this.warn(warning);
  3807. return {
  3808. code: result.code,
  3809. map: result.map,
  3810. moduleType: "js"
  3811. };
  3812. }
  3813. }
  3814. };
  3815. }
  3816. function convertEsbuildConfigToOxcConfig(esbuildConfig, logger) {
  3817. const { jsxInject, include, exclude, ...esbuildTransformOptions } = esbuildConfig;
  3818. const oxcOptions = {
  3819. jsxInject,
  3820. include,
  3821. exclude
  3822. };
  3823. if (esbuildTransformOptions.jsx === "preserve") oxcOptions.jsx = "preserve";
  3824. else {
  3825. const jsxOptions = {};
  3826. switch (esbuildTransformOptions.jsx) {
  3827. case "automatic":
  3828. jsxOptions.runtime = "automatic";
  3829. if (esbuildTransformOptions.jsxImportSource) jsxOptions.importSource = esbuildTransformOptions.jsxImportSource;
  3830. break;
  3831. case "transform":
  3832. jsxOptions.runtime = "classic";
  3833. if (esbuildTransformOptions.jsxFactory) jsxOptions.pragma = esbuildTransformOptions.jsxFactory;
  3834. if (esbuildTransformOptions.jsxFragment) jsxOptions.pragmaFrag = esbuildTransformOptions.jsxFragment;
  3835. break;
  3836. default: break;
  3837. }
  3838. if (esbuildTransformOptions.jsxDev !== void 0) jsxOptions.development = esbuildTransformOptions.jsxDev;
  3839. if (esbuildTransformOptions.jsxSideEffects !== void 0) jsxOptions.pure = esbuildTransformOptions.jsxSideEffects;
  3840. oxcOptions.jsx = jsxOptions;
  3841. }
  3842. if (esbuildTransformOptions.define) oxcOptions.define = esbuildTransformOptions.define;
  3843. if (esbuildTransformOptions.banner) warnDeprecatedShouldBeConvertedToPluginOptions(logger, "banner");
  3844. if (esbuildTransformOptions.footer) warnDeprecatedShouldBeConvertedToPluginOptions(logger, "footer");
  3845. return oxcOptions;
  3846. }
  3847. function warnDeprecatedShouldBeConvertedToPluginOptions(logger, name) {
  3848. logger.warn(import_picocolors.default.yellow(`\`esbuild.${name}\` option was specified. But this option is deprecated and will be removed in future versions. This option can be achieved by using a plugin with transform hook, please use that instead.`));
  3849. }
  3850. //#endregion
  3851. //#region ../../node_modules/.pnpm/magic-string@0.30.21/node_modules/magic-string/dist/magic-string.es.mjs
  3852. var BitSet = class BitSet {
  3853. constructor(arg) {
  3854. this.bits = arg instanceof BitSet ? arg.bits.slice() : [];
  3855. }
  3856. add(n) {
  3857. this.bits[n >> 5] |= 1 << (n & 31);
  3858. }
  3859. has(n) {
  3860. return !!(this.bits[n >> 5] & 1 << (n & 31));
  3861. }
  3862. };
  3863. var Chunk = class Chunk {
  3864. constructor(start, end, content) {
  3865. this.start = start;
  3866. this.end = end;
  3867. this.original = content;
  3868. this.intro = "";
  3869. this.outro = "";
  3870. this.content = content;
  3871. this.storeName = false;
  3872. this.edited = false;
  3873. this.previous = null;
  3874. this.next = null;
  3875. }
  3876. appendLeft(content) {
  3877. this.outro += content;
  3878. }
  3879. appendRight(content) {
  3880. this.intro = this.intro + content;
  3881. }
  3882. clone() {
  3883. const chunk = new Chunk(this.start, this.end, this.original);
  3884. chunk.intro = this.intro;
  3885. chunk.outro = this.outro;
  3886. chunk.content = this.content;
  3887. chunk.storeName = this.storeName;
  3888. chunk.edited = this.edited;
  3889. return chunk;
  3890. }
  3891. contains(index) {
  3892. return this.start < index && index < this.end;
  3893. }
  3894. eachNext(fn) {
  3895. let chunk = this;
  3896. while (chunk) {
  3897. fn(chunk);
  3898. chunk = chunk.next;
  3899. }
  3900. }
  3901. eachPrevious(fn) {
  3902. let chunk = this;
  3903. while (chunk) {
  3904. fn(chunk);
  3905. chunk = chunk.previous;
  3906. }
  3907. }
  3908. edit(content, storeName, contentOnly) {
  3909. this.content = content;
  3910. if (!contentOnly) {
  3911. this.intro = "";
  3912. this.outro = "";
  3913. }
  3914. this.storeName = storeName;
  3915. this.edited = true;
  3916. return this;
  3917. }
  3918. prependLeft(content) {
  3919. this.outro = content + this.outro;
  3920. }
  3921. prependRight(content) {
  3922. this.intro = content + this.intro;
  3923. }
  3924. reset() {
  3925. this.intro = "";
  3926. this.outro = "";
  3927. if (this.edited) {
  3928. this.content = this.original;
  3929. this.storeName = false;
  3930. this.edited = false;
  3931. }
  3932. }
  3933. split(index) {
  3934. const sliceIndex = index - this.start;
  3935. const originalBefore = this.original.slice(0, sliceIndex);
  3936. const originalAfter = this.original.slice(sliceIndex);
  3937. this.original = originalBefore;
  3938. const newChunk = new Chunk(index, this.end, originalAfter);
  3939. newChunk.outro = this.outro;
  3940. this.outro = "";
  3941. this.end = index;
  3942. if (this.edited) {
  3943. newChunk.edit("", false);
  3944. this.content = "";
  3945. } else this.content = originalBefore;
  3946. newChunk.next = this.next;
  3947. if (newChunk.next) newChunk.next.previous = newChunk;
  3948. newChunk.previous = this;
  3949. this.next = newChunk;
  3950. return newChunk;
  3951. }
  3952. toString() {
  3953. return this.intro + this.content + this.outro;
  3954. }
  3955. trimEnd(rx) {
  3956. this.outro = this.outro.replace(rx, "");
  3957. if (this.outro.length) return true;
  3958. const trimmed = this.content.replace(rx, "");
  3959. if (trimmed.length) {
  3960. if (trimmed !== this.content) {
  3961. this.split(this.start + trimmed.length).edit("", void 0, true);
  3962. if (this.edited) this.edit(trimmed, this.storeName, true);
  3963. }
  3964. return true;
  3965. } else {
  3966. this.edit("", void 0, true);
  3967. this.intro = this.intro.replace(rx, "");
  3968. if (this.intro.length) return true;
  3969. }
  3970. }
  3971. trimStart(rx) {
  3972. this.intro = this.intro.replace(rx, "");
  3973. if (this.intro.length) return true;
  3974. const trimmed = this.content.replace(rx, "");
  3975. if (trimmed.length) {
  3976. if (trimmed !== this.content) {
  3977. const newChunk = this.split(this.end - trimmed.length);
  3978. if (this.edited) newChunk.edit(trimmed, this.storeName, true);
  3979. this.edit("", void 0, true);
  3980. }
  3981. return true;
  3982. } else {
  3983. this.edit("", void 0, true);
  3984. this.outro = this.outro.replace(rx, "");
  3985. if (this.outro.length) return true;
  3986. }
  3987. }
  3988. };
  3989. function getBtoa() {
  3990. if (typeof globalThis !== "undefined" && typeof globalThis.btoa === "function") return (str) => globalThis.btoa(unescape(encodeURIComponent(str)));
  3991. else if (typeof Buffer === "function") return (str) => Buffer.from(str, "utf-8").toString("base64");
  3992. else return () => {
  3993. throw new Error("Unsupported environment: `window.btoa` or `Buffer` should be supported.");
  3994. };
  3995. }
  3996. const btoa$1 = /* @__PURE__ */ getBtoa();
  3997. var SourceMap = class {
  3998. constructor(properties) {
  3999. this.version = 3;
  4000. this.file = properties.file;
  4001. this.sources = properties.sources;
  4002. this.sourcesContent = properties.sourcesContent;
  4003. this.names = properties.names;
  4004. this.mappings = encode$1(properties.mappings);
  4005. if (typeof properties.x_google_ignoreList !== "undefined") this.x_google_ignoreList = properties.x_google_ignoreList;
  4006. if (typeof properties.debugId !== "undefined") this.debugId = properties.debugId;
  4007. }
  4008. toString() {
  4009. return JSON.stringify(this);
  4010. }
  4011. toUrl() {
  4012. return "data:application/json;charset=utf-8;base64," + btoa$1(this.toString());
  4013. }
  4014. };
  4015. function guessIndent(code) {
  4016. const lines = code.split("\n");
  4017. const tabbed = lines.filter((line) => /^\t+/.test(line));
  4018. const spaced = lines.filter((line) => /^ {2,}/.test(line));
  4019. if (tabbed.length === 0 && spaced.length === 0) return null;
  4020. if (tabbed.length >= spaced.length) return " ";
  4021. const min = spaced.reduce((previous, current) => {
  4022. const numSpaces = /^ +/.exec(current)[0].length;
  4023. return Math.min(numSpaces, previous);
  4024. }, Infinity);
  4025. return new Array(min + 1).join(" ");
  4026. }
  4027. function getRelativePath(from, to) {
  4028. const fromParts = from.split(/[/\\]/);
  4029. const toParts = to.split(/[/\\]/);
  4030. fromParts.pop();
  4031. while (fromParts[0] === toParts[0]) {
  4032. fromParts.shift();
  4033. toParts.shift();
  4034. }
  4035. if (fromParts.length) {
  4036. let i = fromParts.length;
  4037. while (i--) fromParts[i] = "..";
  4038. }
  4039. return fromParts.concat(toParts).join("/");
  4040. }
  4041. const toString = Object.prototype.toString;
  4042. function isObject(thing) {
  4043. return toString.call(thing) === "[object Object]";
  4044. }
  4045. function getLocator(source) {
  4046. const originalLines = source.split("\n");
  4047. const lineOffsets = [];
  4048. for (let i = 0, pos = 0; i < originalLines.length; i++) {
  4049. lineOffsets.push(pos);
  4050. pos += originalLines[i].length + 1;
  4051. }
  4052. return function locate(index) {
  4053. let i = 0;
  4054. let j = lineOffsets.length;
  4055. while (i < j) {
  4056. const m = i + j >> 1;
  4057. if (index < lineOffsets[m]) j = m;
  4058. else i = m + 1;
  4059. }
  4060. const line = i - 1;
  4061. return {
  4062. line,
  4063. column: index - lineOffsets[line]
  4064. };
  4065. };
  4066. }
  4067. const wordRegex = /\w/;
  4068. var Mappings = class {
  4069. constructor(hires) {
  4070. this.hires = hires;
  4071. this.generatedCodeLine = 0;
  4072. this.generatedCodeColumn = 0;
  4073. this.raw = [];
  4074. this.rawSegments = this.raw[this.generatedCodeLine] = [];
  4075. this.pending = null;
  4076. }
  4077. addEdit(sourceIndex, content, loc, nameIndex) {
  4078. if (content.length) {
  4079. const contentLengthMinusOne = content.length - 1;
  4080. let contentLineEnd = content.indexOf("\n", 0);
  4081. let previousContentLineEnd = -1;
  4082. while (contentLineEnd >= 0 && contentLengthMinusOne > contentLineEnd) {
  4083. const segment = [
  4084. this.generatedCodeColumn,
  4085. sourceIndex,
  4086. loc.line,
  4087. loc.column
  4088. ];
  4089. if (nameIndex >= 0) segment.push(nameIndex);
  4090. this.rawSegments.push(segment);
  4091. this.generatedCodeLine += 1;
  4092. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  4093. this.generatedCodeColumn = 0;
  4094. previousContentLineEnd = contentLineEnd;
  4095. contentLineEnd = content.indexOf("\n", contentLineEnd + 1);
  4096. }
  4097. const segment = [
  4098. this.generatedCodeColumn,
  4099. sourceIndex,
  4100. loc.line,
  4101. loc.column
  4102. ];
  4103. if (nameIndex >= 0) segment.push(nameIndex);
  4104. this.rawSegments.push(segment);
  4105. this.advance(content.slice(previousContentLineEnd + 1));
  4106. } else if (this.pending) {
  4107. this.rawSegments.push(this.pending);
  4108. this.advance(content);
  4109. }
  4110. this.pending = null;
  4111. }
  4112. addUneditedChunk(sourceIndex, chunk, original, loc, sourcemapLocations) {
  4113. let originalCharIndex = chunk.start;
  4114. let first = true;
  4115. let charInHiresBoundary = false;
  4116. while (originalCharIndex < chunk.end) {
  4117. if (original[originalCharIndex] === "\n") {
  4118. loc.line += 1;
  4119. loc.column = 0;
  4120. this.generatedCodeLine += 1;
  4121. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  4122. this.generatedCodeColumn = 0;
  4123. first = true;
  4124. charInHiresBoundary = false;
  4125. } else {
  4126. if (this.hires || first || sourcemapLocations.has(originalCharIndex)) {
  4127. const segment = [
  4128. this.generatedCodeColumn,
  4129. sourceIndex,
  4130. loc.line,
  4131. loc.column
  4132. ];
  4133. if (this.hires === "boundary") if (wordRegex.test(original[originalCharIndex])) {
  4134. if (!charInHiresBoundary) {
  4135. this.rawSegments.push(segment);
  4136. charInHiresBoundary = true;
  4137. }
  4138. } else {
  4139. this.rawSegments.push(segment);
  4140. charInHiresBoundary = false;
  4141. }
  4142. else this.rawSegments.push(segment);
  4143. }
  4144. loc.column += 1;
  4145. this.generatedCodeColumn += 1;
  4146. first = false;
  4147. }
  4148. originalCharIndex += 1;
  4149. }
  4150. this.pending = null;
  4151. }
  4152. advance(str) {
  4153. if (!str) return;
  4154. const lines = str.split("\n");
  4155. if (lines.length > 1) {
  4156. for (let i = 0; i < lines.length - 1; i++) {
  4157. this.generatedCodeLine++;
  4158. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  4159. }
  4160. this.generatedCodeColumn = 0;
  4161. }
  4162. this.generatedCodeColumn += lines[lines.length - 1].length;
  4163. }
  4164. };
  4165. const n = "\n";
  4166. const warned = {
  4167. insertLeft: false,
  4168. insertRight: false,
  4169. storeName: false
  4170. };
  4171. var MagicString = class MagicString {
  4172. constructor(string, options = {}) {
  4173. const chunk = new Chunk(0, string.length, string);
  4174. Object.defineProperties(this, {
  4175. original: {
  4176. writable: true,
  4177. value: string
  4178. },
  4179. outro: {
  4180. writable: true,
  4181. value: ""
  4182. },
  4183. intro: {
  4184. writable: true,
  4185. value: ""
  4186. },
  4187. firstChunk: {
  4188. writable: true,
  4189. value: chunk
  4190. },
  4191. lastChunk: {
  4192. writable: true,
  4193. value: chunk
  4194. },
  4195. lastSearchedChunk: {
  4196. writable: true,
  4197. value: chunk
  4198. },
  4199. byStart: {
  4200. writable: true,
  4201. value: {}
  4202. },
  4203. byEnd: {
  4204. writable: true,
  4205. value: {}
  4206. },
  4207. filename: {
  4208. writable: true,
  4209. value: options.filename
  4210. },
  4211. indentExclusionRanges: {
  4212. writable: true,
  4213. value: options.indentExclusionRanges
  4214. },
  4215. sourcemapLocations: {
  4216. writable: true,
  4217. value: new BitSet()
  4218. },
  4219. storedNames: {
  4220. writable: true,
  4221. value: {}
  4222. },
  4223. indentStr: {
  4224. writable: true,
  4225. value: void 0
  4226. },
  4227. ignoreList: {
  4228. writable: true,
  4229. value: options.ignoreList
  4230. },
  4231. offset: {
  4232. writable: true,
  4233. value: options.offset || 0
  4234. }
  4235. });
  4236. this.byStart[0] = chunk;
  4237. this.byEnd[string.length] = chunk;
  4238. }
  4239. addSourcemapLocation(char) {
  4240. this.sourcemapLocations.add(char);
  4241. }
  4242. append(content) {
  4243. if (typeof content !== "string") throw new TypeError("outro content must be a string");
  4244. this.outro += content;
  4245. return this;
  4246. }
  4247. appendLeft(index, content) {
  4248. index = index + this.offset;
  4249. if (typeof content !== "string") throw new TypeError("inserted content must be a string");
  4250. this._split(index);
  4251. const chunk = this.byEnd[index];
  4252. if (chunk) chunk.appendLeft(content);
  4253. else this.intro += content;
  4254. return this;
  4255. }
  4256. appendRight(index, content) {
  4257. index = index + this.offset;
  4258. if (typeof content !== "string") throw new TypeError("inserted content must be a string");
  4259. this._split(index);
  4260. const chunk = this.byStart[index];
  4261. if (chunk) chunk.appendRight(content);
  4262. else this.outro += content;
  4263. return this;
  4264. }
  4265. clone() {
  4266. const cloned = new MagicString(this.original, {
  4267. filename: this.filename,
  4268. offset: this.offset
  4269. });
  4270. let originalChunk = this.firstChunk;
  4271. let clonedChunk = cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone();
  4272. while (originalChunk) {
  4273. cloned.byStart[clonedChunk.start] = clonedChunk;
  4274. cloned.byEnd[clonedChunk.end] = clonedChunk;
  4275. const nextOriginalChunk = originalChunk.next;
  4276. const nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone();
  4277. if (nextClonedChunk) {
  4278. clonedChunk.next = nextClonedChunk;
  4279. nextClonedChunk.previous = clonedChunk;
  4280. clonedChunk = nextClonedChunk;
  4281. }
  4282. originalChunk = nextOriginalChunk;
  4283. }
  4284. cloned.lastChunk = clonedChunk;
  4285. if (this.indentExclusionRanges) cloned.indentExclusionRanges = this.indentExclusionRanges.slice();
  4286. cloned.sourcemapLocations = new BitSet(this.sourcemapLocations);
  4287. cloned.intro = this.intro;
  4288. cloned.outro = this.outro;
  4289. return cloned;
  4290. }
  4291. generateDecodedMap(options) {
  4292. options = options || {};
  4293. const sourceIndex = 0;
  4294. const names = Object.keys(this.storedNames);
  4295. const mappings = new Mappings(options.hires);
  4296. const locate = getLocator(this.original);
  4297. if (this.intro) mappings.advance(this.intro);
  4298. this.firstChunk.eachNext((chunk) => {
  4299. const loc = locate(chunk.start);
  4300. if (chunk.intro.length) mappings.advance(chunk.intro);
  4301. if (chunk.edited) mappings.addEdit(sourceIndex, chunk.content, loc, chunk.storeName ? names.indexOf(chunk.original) : -1);
  4302. else mappings.addUneditedChunk(sourceIndex, chunk, this.original, loc, this.sourcemapLocations);
  4303. if (chunk.outro.length) mappings.advance(chunk.outro);
  4304. });
  4305. if (this.outro) mappings.advance(this.outro);
  4306. return {
  4307. file: options.file ? options.file.split(/[/\\]/).pop() : void 0,
  4308. sources: [options.source ? getRelativePath(options.file || "", options.source) : options.file || ""],
  4309. sourcesContent: options.includeContent ? [this.original] : void 0,
  4310. names,
  4311. mappings: mappings.raw,
  4312. x_google_ignoreList: this.ignoreList ? [sourceIndex] : void 0
  4313. };
  4314. }
  4315. generateMap(options) {
  4316. return new SourceMap(this.generateDecodedMap(options));
  4317. }
  4318. _ensureindentStr() {
  4319. if (this.indentStr === void 0) this.indentStr = guessIndent(this.original);
  4320. }
  4321. _getRawIndentString() {
  4322. this._ensureindentStr();
  4323. return this.indentStr;
  4324. }
  4325. getIndentString() {
  4326. this._ensureindentStr();
  4327. return this.indentStr === null ? " " : this.indentStr;
  4328. }
  4329. indent(indentStr, options) {
  4330. const pattern = /^[^\r\n]/gm;
  4331. if (isObject(indentStr)) {
  4332. options = indentStr;
  4333. indentStr = void 0;
  4334. }
  4335. if (indentStr === void 0) {
  4336. this._ensureindentStr();
  4337. indentStr = this.indentStr || " ";
  4338. }
  4339. if (indentStr === "") return this;
  4340. options = options || {};
  4341. const isExcluded = {};
  4342. if (options.exclude) (typeof options.exclude[0] === "number" ? [options.exclude] : options.exclude).forEach((exclusion) => {
  4343. for (let i = exclusion[0]; i < exclusion[1]; i += 1) isExcluded[i] = true;
  4344. });
  4345. let shouldIndentNextCharacter = options.indentStart !== false;
  4346. const replacer = (match) => {
  4347. if (shouldIndentNextCharacter) return `${indentStr}${match}`;
  4348. shouldIndentNextCharacter = true;
  4349. return match;
  4350. };
  4351. this.intro = this.intro.replace(pattern, replacer);
  4352. let charIndex = 0;
  4353. let chunk = this.firstChunk;
  4354. while (chunk) {
  4355. const end = chunk.end;
  4356. if (chunk.edited) {
  4357. if (!isExcluded[charIndex]) {
  4358. chunk.content = chunk.content.replace(pattern, replacer);
  4359. if (chunk.content.length) shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === "\n";
  4360. }
  4361. } else {
  4362. charIndex = chunk.start;
  4363. while (charIndex < end) {
  4364. if (!isExcluded[charIndex]) {
  4365. const char = this.original[charIndex];
  4366. if (char === "\n") shouldIndentNextCharacter = true;
  4367. else if (char !== "\r" && shouldIndentNextCharacter) {
  4368. shouldIndentNextCharacter = false;
  4369. if (charIndex === chunk.start) chunk.prependRight(indentStr);
  4370. else {
  4371. this._splitChunk(chunk, charIndex);
  4372. chunk = chunk.next;
  4373. chunk.prependRight(indentStr);
  4374. }
  4375. }
  4376. }
  4377. charIndex += 1;
  4378. }
  4379. }
  4380. charIndex = chunk.end;
  4381. chunk = chunk.next;
  4382. }
  4383. this.outro = this.outro.replace(pattern, replacer);
  4384. return this;
  4385. }
  4386. insert() {
  4387. throw new Error("magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)");
  4388. }
  4389. insertLeft(index, content) {
  4390. if (!warned.insertLeft) {
  4391. console.warn("magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead");
  4392. warned.insertLeft = true;
  4393. }
  4394. return this.appendLeft(index, content);
  4395. }
  4396. insertRight(index, content) {
  4397. if (!warned.insertRight) {
  4398. console.warn("magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead");
  4399. warned.insertRight = true;
  4400. }
  4401. return this.prependRight(index, content);
  4402. }
  4403. move(start, end, index) {
  4404. start = start + this.offset;
  4405. end = end + this.offset;
  4406. index = index + this.offset;
  4407. if (index >= start && index <= end) throw new Error("Cannot move a selection inside itself");
  4408. this._split(start);
  4409. this._split(end);
  4410. this._split(index);
  4411. const first = this.byStart[start];
  4412. const last = this.byEnd[end];
  4413. const oldLeft = first.previous;
  4414. const oldRight = last.next;
  4415. const newRight = this.byStart[index];
  4416. if (!newRight && last === this.lastChunk) return this;
  4417. const newLeft = newRight ? newRight.previous : this.lastChunk;
  4418. if (oldLeft) oldLeft.next = oldRight;
  4419. if (oldRight) oldRight.previous = oldLeft;
  4420. if (newLeft) newLeft.next = first;
  4421. if (newRight) newRight.previous = last;
  4422. if (!first.previous) this.firstChunk = last.next;
  4423. if (!last.next) {
  4424. this.lastChunk = first.previous;
  4425. this.lastChunk.next = null;
  4426. }
  4427. first.previous = newLeft;
  4428. last.next = newRight || null;
  4429. if (!newLeft) this.firstChunk = first;
  4430. if (!newRight) this.lastChunk = last;
  4431. return this;
  4432. }
  4433. overwrite(start, end, content, options) {
  4434. options = options || {};
  4435. return this.update(start, end, content, {
  4436. ...options,
  4437. overwrite: !options.contentOnly
  4438. });
  4439. }
  4440. update(start, end, content, options) {
  4441. start = start + this.offset;
  4442. end = end + this.offset;
  4443. if (typeof content !== "string") throw new TypeError("replacement content must be a string");
  4444. if (this.original.length !== 0) {
  4445. while (start < 0) start += this.original.length;
  4446. while (end < 0) end += this.original.length;
  4447. }
  4448. if (end > this.original.length) throw new Error("end is out of bounds");
  4449. if (start === end) throw new Error("Cannot overwrite a zero-length range – use appendLeft or prependRight instead");
  4450. this._split(start);
  4451. this._split(end);
  4452. if (options === true) {
  4453. if (!warned.storeName) {
  4454. console.warn("The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string");
  4455. warned.storeName = true;
  4456. }
  4457. options = { storeName: true };
  4458. }
  4459. const storeName = options !== void 0 ? options.storeName : false;
  4460. const overwrite = options !== void 0 ? options.overwrite : false;
  4461. if (storeName) {
  4462. const original = this.original.slice(start, end);
  4463. Object.defineProperty(this.storedNames, original, {
  4464. writable: true,
  4465. value: true,
  4466. enumerable: true
  4467. });
  4468. }
  4469. const first = this.byStart[start];
  4470. const last = this.byEnd[end];
  4471. if (first) {
  4472. let chunk = first;
  4473. while (chunk !== last) {
  4474. if (chunk.next !== this.byStart[chunk.end]) throw new Error("Cannot overwrite across a split point");
  4475. chunk = chunk.next;
  4476. chunk.edit("", false);
  4477. }
  4478. first.edit(content, storeName, !overwrite);
  4479. } else {
  4480. const newChunk = new Chunk(start, end, "").edit(content, storeName);
  4481. last.next = newChunk;
  4482. newChunk.previous = last;
  4483. }
  4484. return this;
  4485. }
  4486. prepend(content) {
  4487. if (typeof content !== "string") throw new TypeError("outro content must be a string");
  4488. this.intro = content + this.intro;
  4489. return this;
  4490. }
  4491. prependLeft(index, content) {
  4492. index = index + this.offset;
  4493. if (typeof content !== "string") throw new TypeError("inserted content must be a string");
  4494. this._split(index);
  4495. const chunk = this.byEnd[index];
  4496. if (chunk) chunk.prependLeft(content);
  4497. else this.intro = content + this.intro;
  4498. return this;
  4499. }
  4500. prependRight(index, content) {
  4501. index = index + this.offset;
  4502. if (typeof content !== "string") throw new TypeError("inserted content must be a string");
  4503. this._split(index);
  4504. const chunk = this.byStart[index];
  4505. if (chunk) chunk.prependRight(content);
  4506. else this.outro = content + this.outro;
  4507. return this;
  4508. }
  4509. remove(start, end) {
  4510. start = start + this.offset;
  4511. end = end + this.offset;
  4512. if (this.original.length !== 0) {
  4513. while (start < 0) start += this.original.length;
  4514. while (end < 0) end += this.original.length;
  4515. }
  4516. if (start === end) return this;
  4517. if (start < 0 || end > this.original.length) throw new Error("Character is out of bounds");
  4518. if (start > end) throw new Error("end must be greater than start");
  4519. this._split(start);
  4520. this._split(end);
  4521. let chunk = this.byStart[start];
  4522. while (chunk) {
  4523. chunk.intro = "";
  4524. chunk.outro = "";
  4525. chunk.edit("");
  4526. chunk = end > chunk.end ? this.byStart[chunk.end] : null;
  4527. }
  4528. return this;
  4529. }
  4530. reset(start, end) {
  4531. start = start + this.offset;
  4532. end = end + this.offset;
  4533. if (this.original.length !== 0) {
  4534. while (start < 0) start += this.original.length;
  4535. while (end < 0) end += this.original.length;
  4536. }
  4537. if (start === end) return this;
  4538. if (start < 0 || end > this.original.length) throw new Error("Character is out of bounds");
  4539. if (start > end) throw new Error("end must be greater than start");
  4540. this._split(start);
  4541. this._split(end);
  4542. let chunk = this.byStart[start];
  4543. while (chunk) {
  4544. chunk.reset();
  4545. chunk = end > chunk.end ? this.byStart[chunk.end] : null;
  4546. }
  4547. return this;
  4548. }
  4549. lastChar() {
  4550. if (this.outro.length) return this.outro[this.outro.length - 1];
  4551. let chunk = this.lastChunk;
  4552. do {
  4553. if (chunk.outro.length) return chunk.outro[chunk.outro.length - 1];
  4554. if (chunk.content.length) return chunk.content[chunk.content.length - 1];
  4555. if (chunk.intro.length) return chunk.intro[chunk.intro.length - 1];
  4556. } while (chunk = chunk.previous);
  4557. if (this.intro.length) return this.intro[this.intro.length - 1];
  4558. return "";
  4559. }
  4560. lastLine() {
  4561. let lineIndex = this.outro.lastIndexOf(n);
  4562. if (lineIndex !== -1) return this.outro.substr(lineIndex + 1);
  4563. let lineStr = this.outro;
  4564. let chunk = this.lastChunk;
  4565. do {
  4566. if (chunk.outro.length > 0) {
  4567. lineIndex = chunk.outro.lastIndexOf(n);
  4568. if (lineIndex !== -1) return chunk.outro.substr(lineIndex + 1) + lineStr;
  4569. lineStr = chunk.outro + lineStr;
  4570. }
  4571. if (chunk.content.length > 0) {
  4572. lineIndex = chunk.content.lastIndexOf(n);
  4573. if (lineIndex !== -1) return chunk.content.substr(lineIndex + 1) + lineStr;
  4574. lineStr = chunk.content + lineStr;
  4575. }
  4576. if (chunk.intro.length > 0) {
  4577. lineIndex = chunk.intro.lastIndexOf(n);
  4578. if (lineIndex !== -1) return chunk.intro.substr(lineIndex + 1) + lineStr;
  4579. lineStr = chunk.intro + lineStr;
  4580. }
  4581. } while (chunk = chunk.previous);
  4582. lineIndex = this.intro.lastIndexOf(n);
  4583. if (lineIndex !== -1) return this.intro.substr(lineIndex + 1) + lineStr;
  4584. return this.intro + lineStr;
  4585. }
  4586. slice(start = 0, end = this.original.length - this.offset) {
  4587. start = start + this.offset;
  4588. end = end + this.offset;
  4589. if (this.original.length !== 0) {
  4590. while (start < 0) start += this.original.length;
  4591. while (end < 0) end += this.original.length;
  4592. }
  4593. let result = "";
  4594. let chunk = this.firstChunk;
  4595. while (chunk && (chunk.start > start || chunk.end <= start)) {
  4596. if (chunk.start < end && chunk.end >= end) return result;
  4597. chunk = chunk.next;
  4598. }
  4599. if (chunk && chunk.edited && chunk.start !== start) throw new Error(`Cannot use replaced character ${start} as slice start anchor.`);
  4600. const startChunk = chunk;
  4601. while (chunk) {
  4602. if (chunk.intro && (startChunk !== chunk || chunk.start === start)) result += chunk.intro;
  4603. const containsEnd = chunk.start < end && chunk.end >= end;
  4604. if (containsEnd && chunk.edited && chunk.end !== end) throw new Error(`Cannot use replaced character ${end} as slice end anchor.`);
  4605. const sliceStart = startChunk === chunk ? start - chunk.start : 0;
  4606. const sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length;
  4607. result += chunk.content.slice(sliceStart, sliceEnd);
  4608. if (chunk.outro && (!containsEnd || chunk.end === end)) result += chunk.outro;
  4609. if (containsEnd) break;
  4610. chunk = chunk.next;
  4611. }
  4612. return result;
  4613. }
  4614. snip(start, end) {
  4615. const clone = this.clone();
  4616. clone.remove(0, start);
  4617. clone.remove(end, clone.original.length);
  4618. return clone;
  4619. }
  4620. _split(index) {
  4621. if (this.byStart[index] || this.byEnd[index]) return;
  4622. let chunk = this.lastSearchedChunk;
  4623. let previousChunk = chunk;
  4624. const searchForward = index > chunk.end;
  4625. while (chunk) {
  4626. if (chunk.contains(index)) return this._splitChunk(chunk, index);
  4627. chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start];
  4628. if (chunk === previousChunk) return;
  4629. previousChunk = chunk;
  4630. }
  4631. }
  4632. _splitChunk(chunk, index) {
  4633. if (chunk.edited && chunk.content.length) {
  4634. const loc = getLocator(this.original)(index);
  4635. throw new Error(`Cannot split a chunk that has already been edited (${loc.line}:${loc.column} – "${chunk.original}")`);
  4636. }
  4637. const newChunk = chunk.split(index);
  4638. this.byEnd[index] = chunk;
  4639. this.byStart[index] = newChunk;
  4640. this.byEnd[newChunk.end] = newChunk;
  4641. if (chunk === this.lastChunk) this.lastChunk = newChunk;
  4642. this.lastSearchedChunk = chunk;
  4643. return true;
  4644. }
  4645. toString() {
  4646. let str = this.intro;
  4647. let chunk = this.firstChunk;
  4648. while (chunk) {
  4649. str += chunk.toString();
  4650. chunk = chunk.next;
  4651. }
  4652. return str + this.outro;
  4653. }
  4654. isEmpty() {
  4655. let chunk = this.firstChunk;
  4656. do
  4657. if (chunk.intro.length && chunk.intro.trim() || chunk.content.length && chunk.content.trim() || chunk.outro.length && chunk.outro.trim()) return false;
  4658. while (chunk = chunk.next);
  4659. return true;
  4660. }
  4661. length() {
  4662. let chunk = this.firstChunk;
  4663. let length = 0;
  4664. do
  4665. length += chunk.intro.length + chunk.content.length + chunk.outro.length;
  4666. while (chunk = chunk.next);
  4667. return length;
  4668. }
  4669. trimLines() {
  4670. return this.trim("[\\r\\n]");
  4671. }
  4672. trim(charType) {
  4673. return this.trimStart(charType).trimEnd(charType);
  4674. }
  4675. trimEndAborted(charType) {
  4676. const rx = new RegExp((charType || "\\s") + "+$");
  4677. this.outro = this.outro.replace(rx, "");
  4678. if (this.outro.length) return true;
  4679. let chunk = this.lastChunk;
  4680. do {
  4681. const end = chunk.end;
  4682. const aborted = chunk.trimEnd(rx);
  4683. if (chunk.end !== end) {
  4684. if (this.lastChunk === chunk) this.lastChunk = chunk.next;
  4685. this.byEnd[chunk.end] = chunk;
  4686. this.byStart[chunk.next.start] = chunk.next;
  4687. this.byEnd[chunk.next.end] = chunk.next;
  4688. }
  4689. if (aborted) return true;
  4690. chunk = chunk.previous;
  4691. } while (chunk);
  4692. return false;
  4693. }
  4694. trimEnd(charType) {
  4695. this.trimEndAborted(charType);
  4696. return this;
  4697. }
  4698. trimStartAborted(charType) {
  4699. const rx = new RegExp("^" + (charType || "\\s") + "+");
  4700. this.intro = this.intro.replace(rx, "");
  4701. if (this.intro.length) return true;
  4702. let chunk = this.firstChunk;
  4703. do {
  4704. const end = chunk.end;
  4705. const aborted = chunk.trimStart(rx);
  4706. if (chunk.end !== end) {
  4707. if (chunk === this.lastChunk) this.lastChunk = chunk.next;
  4708. this.byEnd[chunk.end] = chunk;
  4709. this.byStart[chunk.next.start] = chunk.next;
  4710. this.byEnd[chunk.next.end] = chunk.next;
  4711. }
  4712. if (aborted) return true;
  4713. chunk = chunk.next;
  4714. } while (chunk);
  4715. return false;
  4716. }
  4717. trimStart(charType) {
  4718. this.trimStartAborted(charType);
  4719. return this;
  4720. }
  4721. hasChanged() {
  4722. return this.original !== this.toString();
  4723. }
  4724. _replaceRegexp(searchValue, replacement) {
  4725. function getReplacement(match, str) {
  4726. if (typeof replacement === "string") return replacement.replace(/\$(\$|&|\d+)/g, (_, i) => {
  4727. if (i === "$") return "$";
  4728. if (i === "&") return match[0];
  4729. if (+i < match.length) return match[+i];
  4730. return `$${i}`;
  4731. });
  4732. else return replacement(...match, match.index, str, match.groups);
  4733. }
  4734. function matchAll(re, str) {
  4735. let match;
  4736. const matches = [];
  4737. while (match = re.exec(str)) matches.push(match);
  4738. return matches;
  4739. }
  4740. if (searchValue.global) matchAll(searchValue, this.original).forEach((match) => {
  4741. if (match.index != null) {
  4742. const replacement = getReplacement(match, this.original);
  4743. if (replacement !== match[0]) this.overwrite(match.index, match.index + match[0].length, replacement);
  4744. }
  4745. });
  4746. else {
  4747. const match = this.original.match(searchValue);
  4748. if (match && match.index != null) {
  4749. const replacement = getReplacement(match, this.original);
  4750. if (replacement !== match[0]) this.overwrite(match.index, match.index + match[0].length, replacement);
  4751. }
  4752. }
  4753. return this;
  4754. }
  4755. _replaceString(string, replacement) {
  4756. const { original } = this;
  4757. const index = original.indexOf(string);
  4758. if (index !== -1) {
  4759. if (typeof replacement === "function") replacement = replacement(string, index, original);
  4760. if (string !== replacement) this.overwrite(index, index + string.length, replacement);
  4761. }
  4762. return this;
  4763. }
  4764. replace(searchValue, replacement) {
  4765. if (typeof searchValue === "string") return this._replaceString(searchValue, replacement);
  4766. return this._replaceRegexp(searchValue, replacement);
  4767. }
  4768. _replaceAllString(string, replacement) {
  4769. const { original } = this;
  4770. const stringLength = string.length;
  4771. for (let index = original.indexOf(string); index !== -1; index = original.indexOf(string, index + stringLength)) {
  4772. const previous = original.slice(index, index + stringLength);
  4773. let _replacement = replacement;
  4774. if (typeof replacement === "function") _replacement = replacement(previous, index, original);
  4775. if (previous !== _replacement) this.overwrite(index, index + stringLength, _replacement);
  4776. }
  4777. return this;
  4778. }
  4779. replaceAll(searchValue, replacement) {
  4780. if (typeof searchValue === "string") return this._replaceAllString(searchValue, replacement);
  4781. if (!searchValue.global) throw new TypeError("MagicString.prototype.replaceAll called with a non-global RegExp argument");
  4782. return this._replaceRegexp(searchValue, replacement);
  4783. }
  4784. };
  4785. //#endregion
  4786. //#region ../../node_modules/.pnpm/@rollup+plugin-alias@6.0.0_rollup@4.59.0/node_modules/@rollup/plugin-alias/dist/index.js
  4787. function matches$1(pattern, importee) {
  4788. if (pattern instanceof RegExp) return pattern.test(importee);
  4789. if (importee.length < pattern.length) return false;
  4790. if (importee === pattern) return true;
  4791. return importee.startsWith(pattern + "/");
  4792. }
  4793. function getEntries({ entries, customResolver }) {
  4794. if (!entries) return [];
  4795. const resolverFunctionFromOptions = resolveCustomResolver(customResolver);
  4796. if (Array.isArray(entries)) return entries.map((entry) => {
  4797. return {
  4798. find: entry.find,
  4799. replacement: entry.replacement,
  4800. resolverFunction: resolveCustomResolver(entry.customResolver) || resolverFunctionFromOptions
  4801. };
  4802. });
  4803. return Object.entries(entries).map(([key, value]) => {
  4804. return {
  4805. find: key,
  4806. replacement: value,
  4807. resolverFunction: resolverFunctionFromOptions
  4808. };
  4809. });
  4810. }
  4811. function getHookFunction(hook) {
  4812. if (typeof hook === "function") return hook;
  4813. if (hook && "handler" in hook && typeof hook.handler === "function") return hook.handler;
  4814. return null;
  4815. }
  4816. function resolveCustomResolver(customResolver) {
  4817. if (typeof customResolver === "function") return customResolver;
  4818. if (customResolver) return getHookFunction(customResolver.resolveId);
  4819. return null;
  4820. }
  4821. function alias$1(options = {}) {
  4822. const entries = getEntries(options);
  4823. if (entries.length === 0) return {
  4824. name: "alias",
  4825. resolveId: () => null
  4826. };
  4827. return {
  4828. name: "alias",
  4829. async buildStart(inputOptions) {
  4830. await Promise.all([...Array.isArray(options.entries) ? options.entries : [], options].map(({ customResolver }) => customResolver && getHookFunction(customResolver.buildStart)?.call(this, inputOptions)));
  4831. },
  4832. resolveId(importee, importer, resolveOptions) {
  4833. const matchedEntry = entries.find((entry) => matches$1(entry.find, importee));
  4834. if (!matchedEntry) return null;
  4835. const updatedId = importee.replace(matchedEntry.find, matchedEntry.replacement);
  4836. if (matchedEntry.resolverFunction) return matchedEntry.resolverFunction.call(this, updatedId, importer, resolveOptions);
  4837. return this.resolve(updatedId, importer, Object.assign({ skipSelf: true }, resolveOptions)).then((resolved) => {
  4838. if (resolved) return resolved;
  4839. if (!path.isAbsolute(updatedId)) this.warn(`rewrote ${importee} to ${updatedId} but was not an absolute path and was not handled by other plugins. This will lead to duplicated modules for the same path. To avoid duplicating modules, you should resolve to an absolute path.`);
  4840. return { id: updatedId };
  4841. });
  4842. }
  4843. };
  4844. }
  4845. //#endregion
  4846. //#region src/node/plugins/optimizedDeps.ts
  4847. const debug$13 = createDebugger("vite:optimize-deps");
  4848. function optimizedDepsPlugin() {
  4849. return {
  4850. name: "vite:optimized-deps",
  4851. applyToEnvironment(environment) {
  4852. return !isDepOptimizationDisabled(environment.config.optimizeDeps);
  4853. },
  4854. resolveId(id) {
  4855. if (this.environment.depsOptimizer?.isOptimizedDepFile(id)) return id;
  4856. },
  4857. async load(id) {
  4858. const environment = this.environment;
  4859. const depsOptimizer = environment.depsOptimizer;
  4860. if (depsOptimizer?.isOptimizedDepFile(id)) {
  4861. const metadata = depsOptimizer.metadata;
  4862. const file = cleanUrl(id);
  4863. const versionMatch = DEP_VERSION_RE.exec(id);
  4864. const browserHash = versionMatch ? versionMatch[1].split("=")[1] : void 0;
  4865. const info = optimizedDepInfoFromFile(metadata, file);
  4866. if (info) {
  4867. if (browserHash && info.browserHash !== browserHash && !environment.config.optimizeDeps.ignoreOutdatedRequests) throwOutdatedRequest(id);
  4868. try {
  4869. await info.processing;
  4870. } catch {
  4871. throwProcessingError(id);
  4872. }
  4873. const newMetadata = depsOptimizer.metadata;
  4874. if (metadata !== newMetadata) {
  4875. const currentInfo = optimizedDepInfoFromFile(newMetadata, file);
  4876. if (info.browserHash !== currentInfo?.browserHash && !environment.config.optimizeDeps.ignoreOutdatedRequests) throwOutdatedRequest(id);
  4877. }
  4878. }
  4879. debug$13?.(`load ${import_picocolors.default.cyan(file)}`);
  4880. try {
  4881. return await fsp.readFile(file, "utf-8");
  4882. } catch {
  4883. if (browserHash && !environment.config.optimizeDeps.ignoreOutdatedRequests) throwOutdatedRequest(id);
  4884. throwFileNotFoundInOptimizedDep(id);
  4885. }
  4886. }
  4887. }
  4888. };
  4889. }
  4890. function throwProcessingError(id) {
  4891. const err = /* @__PURE__ */ new Error(`Something unexpected happened while optimizing "${id}". The current page should have reloaded by now`);
  4892. err.code = ERR_OPTIMIZE_DEPS_PROCESSING_ERROR;
  4893. throw err;
  4894. }
  4895. function throwOutdatedRequest(id) {
  4896. const err = /* @__PURE__ */ new Error(`There is a new version of the pre-bundle for "${id}", a page reload is going to ask for it.`);
  4897. err.code = ERR_OUTDATED_OPTIMIZED_DEP;
  4898. throw err;
  4899. }
  4900. function throwFileNotFoundInOptimizedDep(id) {
  4901. const err = /* @__PURE__ */ new Error(`The file does not exist at "${id}" which is in the optimize deps directory. The dependency might be incompatible with the dep optimizer. Try adding it to \`optimizeDeps.exclude\`.`);
  4902. err.code = ERR_FILE_NOT_FOUND_IN_OPTIMIZED_DEP_DIR;
  4903. throw err;
  4904. }
  4905. //#endregion
  4906. //#region src/node/env.ts
  4907. var import_main = (/* @__PURE__ */ __commonJSMin(((exports, module) => {
  4908. function _resolveEscapeSequences(value) {
  4909. return value.replace(/\\\$/g, "$");
  4910. }
  4911. function expandValue(value, processEnv, runningParsed) {
  4912. const env = {
  4913. ...runningParsed,
  4914. ...processEnv
  4915. };
  4916. const regex = /(?<!\\)\${([^{}]+)}|(?<!\\)\$([A-Za-z_][A-Za-z0-9_]*)/g;
  4917. let result = value;
  4918. let match;
  4919. const seen = /* @__PURE__ */ new Set();
  4920. while ((match = regex.exec(result)) !== null) {
  4921. seen.add(result);
  4922. const [template, bracedExpression, unbracedExpression] = match;
  4923. const expression = bracedExpression || unbracedExpression;
  4924. const opMatch = expression.match(/(:\+|\+|:-|-)/);
  4925. const splitter = opMatch ? opMatch[0] : null;
  4926. const r = expression.split(splitter);
  4927. let defaultValue;
  4928. let value;
  4929. const key = r.shift();
  4930. if ([":+", "+"].includes(splitter)) {
  4931. defaultValue = env[key] ? r.join(splitter) : "";
  4932. value = null;
  4933. } else {
  4934. defaultValue = r.join(splitter);
  4935. value = env[key];
  4936. }
  4937. if (value) if (seen.has(value)) result = result.replace(template, defaultValue);
  4938. else result = result.replace(template, value);
  4939. else result = result.replace(template, defaultValue);
  4940. if (result === runningParsed[key]) break;
  4941. regex.lastIndex = 0;
  4942. }
  4943. return result;
  4944. }
  4945. function expand(options) {
  4946. let processEnv = process.env;
  4947. if (options && options.processEnv != null) processEnv = options.processEnv;
  4948. for (const key in options.parsed) {
  4949. let value = options.parsed[key];
  4950. if (processEnv[key] && processEnv[key] !== value) value = processEnv[key];
  4951. else value = expandValue(value, processEnv, options.parsed);
  4952. options.parsed[key] = _resolveEscapeSequences(value);
  4953. }
  4954. for (const processKey in options.parsed) processEnv[processKey] = options.parsed[processKey];
  4955. return options;
  4956. }
  4957. module.exports.expand = expand;
  4958. })))();
  4959. const debug$12 = createDebugger("vite:env");
  4960. function getEnvFilesForMode(mode, envDir) {
  4961. if (envDir !== false) return [
  4962. `.env`,
  4963. `.env.local`,
  4964. `.env.${mode}`,
  4965. `.env.${mode}.local`
  4966. ].map((file) => normalizePath(path.join(envDir, file)));
  4967. return [];
  4968. }
  4969. function loadEnv(mode, envDir, prefixes = "VITE_") {
  4970. const start = performance.now();
  4971. const getTime = () => `${(performance.now() - start).toFixed(2)}ms`;
  4972. if (mode === "local") throw new Error("\"local\" cannot be used as a mode name because it conflicts with the .local postfix for .env files.");
  4973. prefixes = arraify(prefixes);
  4974. const env = {};
  4975. const envFiles = getEnvFilesForMode(mode, envDir);
  4976. debug$12?.(`loading env files: %O`, envFiles);
  4977. const parsed = Object.fromEntries(envFiles.flatMap((filePath) => {
  4978. const stat = tryStatSync(filePath);
  4979. if (!stat || !stat.isFile() && !stat.isFIFO()) return [];
  4980. const parsedEnv = parseEnv(fs.readFileSync(filePath, "utf-8"));
  4981. return Object.entries(parsedEnv);
  4982. }));
  4983. debug$12?.(`env files loaded in ${getTime()}`);
  4984. if (parsed.NODE_ENV && process.env.VITE_USER_NODE_ENV === void 0) process.env.VITE_USER_NODE_ENV = parsed.NODE_ENV;
  4985. if (parsed.BROWSER && process.env.BROWSER === void 0) process.env.BROWSER = parsed.BROWSER;
  4986. if (parsed.BROWSER_ARGS && process.env.BROWSER_ARGS === void 0) process.env.BROWSER_ARGS = parsed.BROWSER_ARGS;
  4987. (0, import_main.expand)({
  4988. parsed,
  4989. processEnv: { ...process.env }
  4990. });
  4991. for (const [key, value] of Object.entries(parsed)) if (prefixes.some((prefix) => key.startsWith(prefix))) env[key] = value;
  4992. for (const key in process.env) if (prefixes.some((prefix) => key.startsWith(prefix))) env[key] = process.env[key];
  4993. debug$12?.(`using resolved env: %O`, env);
  4994. return env;
  4995. }
  4996. function resolveEnvPrefix({ envPrefix = "VITE_" }) {
  4997. envPrefix = arraify(envPrefix);
  4998. if (envPrefix.includes("")) throw new Error(`envPrefix option contains value '', which could lead unexpected exposure of sensitive information.`);
  4999. if (envPrefix.some((prefix) => /\s/.test(prefix))) console.warn(import_picocolors.default.yellow(`[vite] Warning: envPrefix option contains values with whitespace, which does not work in practice.`));
  5000. return envPrefix;
  5001. }
  5002. //#endregion
  5003. //#region src/node/deprecations.ts
  5004. const docsURL = "https://vite.dev";
  5005. const deprecationCode = {
  5006. removePluginHookSsrArgument: "this-environment-in-hooks",
  5007. removePluginHookHandleHotUpdate: "hotupdate-hook",
  5008. removeServerModuleGraph: "per-environment-apis",
  5009. removeServerReloadModule: "per-environment-apis",
  5010. removeServerPluginContainer: "per-environment-apis",
  5011. removeServerHot: "per-environment-apis",
  5012. removeServerTransformRequest: "per-environment-apis",
  5013. removeServerWarmupRequest: "per-environment-apis",
  5014. removeSsrLoadModule: "ssr-using-modulerunner"
  5015. };
  5016. const deprecationMessages = {
  5017. removePluginHookSsrArgument: "Plugin hook `options.ssr` is replaced with `this.environment.config.consumer === 'server'`.",
  5018. removePluginHookHandleHotUpdate: "Plugin hook `handleHotUpdate()` is replaced with `hotUpdate()`.",
  5019. removeServerModuleGraph: "The `server.moduleGraph` is replaced with `this.environment.moduleGraph`.",
  5020. removeServerReloadModule: "The `server.reloadModule` is replaced with `environment.reloadModule`.",
  5021. removeServerPluginContainer: "The `server.pluginContainer` is replaced with `this.environment.pluginContainer`.",
  5022. removeServerHot: "The `server.hot` is replaced with `this.environment.hot`.",
  5023. removeServerTransformRequest: "The `server.transformRequest` is replaced with `this.environment.transformRequest`.",
  5024. removeServerWarmupRequest: "The `server.warmupRequest` is replaced with `this.environment.warmupRequest`.",
  5025. removeSsrLoadModule: "The `server.ssrLoadModule` is replaced with Environment Runner."
  5026. };
  5027. let _ignoreDeprecationWarnings = false;
  5028. function isFutureDeprecationEnabled(config, type) {
  5029. return !!config.future?.[type];
  5030. }
  5031. /**
  5032. * Warn about future deprecations.
  5033. */
  5034. function warnFutureDeprecation(config, type, extraMessage, stacktrace = true) {
  5035. if (_ignoreDeprecationWarnings || !config.future || config.future[type] !== "warn") return;
  5036. let msg = `[vite future] ${deprecationMessages[type]}`;
  5037. if (extraMessage) msg += ` ${extraMessage}`;
  5038. msg = import_picocolors.default.yellow(msg);
  5039. const docs = `${docsURL}/changes/${deprecationCode[type].toLowerCase()}`;
  5040. msg += import_picocolors.default.gray(`\n ${stacktrace ? "├" : "└"}─── `) + import_picocolors.default.underline(docs) + "\n";
  5041. if (stacktrace) {
  5042. const stack = (/* @__PURE__ */ new Error()).stack;
  5043. if (stack) {
  5044. let stacks = stack.split("\n").slice(3).filter((i) => !i.includes("/node_modules/vite/dist/"));
  5045. if (stacks.length === 0) stacks.push("No stack trace found.");
  5046. stacks = stacks.map((i, idx) => ` ${idx === stacks.length - 1 ? "└" : "│"} ${i.trim()}`);
  5047. msg += import_picocolors.default.dim(stacks.join("\n")) + "\n";
  5048. }
  5049. }
  5050. config.logger.warnOnce(msg);
  5051. }
  5052. function ignoreDeprecationWarnings(fn) {
  5053. const before = _ignoreDeprecationWarnings;
  5054. _ignoreDeprecationWarnings = true;
  5055. const ret = fn();
  5056. _ignoreDeprecationWarnings = before;
  5057. return ret;
  5058. }
  5059. //#endregion
  5060. //#region src/node/server/middlewares/error.ts
  5061. function prepareError(err) {
  5062. return {
  5063. message: stripVTControlCharacters(err.message),
  5064. stack: stripVTControlCharacters(cleanStack(err.stack || "")),
  5065. id: err.id,
  5066. frame: stripVTControlCharacters(err.frame || ""),
  5067. plugin: err.plugin,
  5068. pluginCode: err.pluginCode?.toString(),
  5069. loc: err.loc
  5070. };
  5071. }
  5072. function buildErrorMessage(err, args = [], includeStack = true) {
  5073. if (err.plugin) args.push(` Plugin: ${import_picocolors.default.magenta(err.plugin)}`);
  5074. const loc = err.loc ? `:${err.loc.line}:${err.loc.column}` : "";
  5075. if (err.id) args.push(` File: ${import_picocolors.default.cyan(err.id)}${loc}`);
  5076. if (err.frame) args.push(import_picocolors.default.yellow(pad(err.frame)));
  5077. if (includeStack && err.stack) args.push(pad(cleanStack(err.stack)));
  5078. return args.join("\n");
  5079. }
  5080. function cleanStack(stack) {
  5081. return stack.split(/\n/).filter((l) => /^\s*at/.test(l)).join("\n");
  5082. }
  5083. function logError(server, err) {
  5084. const msg = buildErrorMessage(err, [import_picocolors.default.red(`Internal server error: ${err.message}`)]);
  5085. server.config.logger.error(msg, {
  5086. clear: true,
  5087. timestamp: true,
  5088. error: err
  5089. });
  5090. server.environments.client.hot.send({
  5091. type: "error",
  5092. err: prepareError(err)
  5093. });
  5094. }
  5095. function errorMiddleware(server, allowNext = false) {
  5096. return function viteErrorMiddleware(err, _req, res, next) {
  5097. logError(server, err);
  5098. if (allowNext) next();
  5099. else {
  5100. res.statusCode = 500;
  5101. res.end(`
  5102. <!DOCTYPE html>
  5103. <html lang="en">
  5104. <head>
  5105. <meta charset="UTF-8" />
  5106. <title>Error</title>
  5107. <script type="module">
  5108. const error = ${JSON.stringify(prepareError(err)).replace(/</g, "\\u003c")}
  5109. try {
  5110. const { ErrorOverlay } = await import(${JSON.stringify(path.posix.join(server.config.base, CLIENT_PUBLIC_PATH))})
  5111. document.body.appendChild(new ErrorOverlay(error))
  5112. } catch {
  5113. const h = (tag, text) => {
  5114. const el = document.createElement(tag)
  5115. el.textContent = text
  5116. return el
  5117. }
  5118. document.body.appendChild(h('h1', 'Internal Server Error'))
  5119. document.body.appendChild(h('h2', error.message))
  5120. document.body.appendChild(h('pre', error.stack))
  5121. document.body.appendChild(h('p', '(Error overlay failed to load)'))
  5122. }
  5123. <\/script>
  5124. </head>
  5125. <body>
  5126. </body>
  5127. </html>
  5128. `);
  5129. }
  5130. };
  5131. }
  5132. //#endregion
  5133. //#region ../../node_modules/.pnpm/encodeurl@1.0.2/node_modules/encodeurl/index.js
  5134. /*!
  5135. * encodeurl
  5136. * Copyright(c) 2016 Douglas Christopher Wilson
  5137. * MIT Licensed
  5138. */
  5139. var require_encodeurl = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  5140. /**
  5141. * Module exports.
  5142. * @public
  5143. */
  5144. module.exports = encodeUrl;
  5145. /**
  5146. * RegExp to match non-URL code points, *after* encoding (i.e. not including "%")
  5147. * and including invalid escape sequences.
  5148. * @private
  5149. */
  5150. var ENCODE_CHARS_REGEXP = /(?:[^\x21\x25\x26-\x3B\x3D\x3F-\x5B\x5D\x5F\x61-\x7A\x7E]|%(?:[^0-9A-Fa-f]|[0-9A-Fa-f][^0-9A-Fa-f]|$))+/g;
  5151. /**
  5152. * RegExp to match unmatched surrogate pair.
  5153. * @private
  5154. */
  5155. var UNMATCHED_SURROGATE_PAIR_REGEXP = /(^|[^\uD800-\uDBFF])[\uDC00-\uDFFF]|[\uD800-\uDBFF]([^\uDC00-\uDFFF]|$)/g;
  5156. /**
  5157. * String to replace unmatched surrogate pair with.
  5158. * @private
  5159. */
  5160. var UNMATCHED_SURROGATE_PAIR_REPLACE = "$1�$2";
  5161. /**
  5162. * Encode a URL to a percent-encoded form, excluding already-encoded sequences.
  5163. *
  5164. * This function will take an already-encoded URL and encode all the non-URL
  5165. * code points. This function will not encode the "%" character unless it is
  5166. * not part of a valid sequence (`%20` will be left as-is, but `%foo` will
  5167. * be encoded as `%25foo`).
  5168. *
  5169. * This encode is meant to be "safe" and does not throw errors. It will try as
  5170. * hard as it can to properly encode the given URL, including replacing any raw,
  5171. * unpaired surrogate pairs with the Unicode replacement character prior to
  5172. * encoding.
  5173. *
  5174. * @param {string} url
  5175. * @return {string}
  5176. * @public
  5177. */
  5178. function encodeUrl(url) {
  5179. return String(url).replace(UNMATCHED_SURROGATE_PAIR_REGEXP, UNMATCHED_SURROGATE_PAIR_REPLACE).replace(ENCODE_CHARS_REGEXP, encodeURI);
  5180. }
  5181. }));
  5182. //#endregion
  5183. //#region ../../node_modules/.pnpm/escape-html@1.0.3/node_modules/escape-html/index.js
  5184. /*!
  5185. * escape-html
  5186. * Copyright(c) 2012-2013 TJ Holowaychuk
  5187. * Copyright(c) 2015 Andreas Lubbe
  5188. * Copyright(c) 2015 Tiancheng "Timothy" Gu
  5189. * MIT Licensed
  5190. */
  5191. var require_escape_html = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  5192. /**
  5193. * Module variables.
  5194. * @private
  5195. */
  5196. var matchHtmlRegExp = /["'&<>]/;
  5197. /**
  5198. * Module exports.
  5199. * @public
  5200. */
  5201. module.exports = escapeHtml;
  5202. /**
  5203. * Escape special characters in the given string of html.
  5204. *
  5205. * @param {string} string The string to escape for inserting into HTML
  5206. * @return {string}
  5207. * @public
  5208. */
  5209. function escapeHtml(string) {
  5210. var str = "" + string;
  5211. var match = matchHtmlRegExp.exec(str);
  5212. if (!match) return str;
  5213. var escape;
  5214. var html = "";
  5215. var index = 0;
  5216. var lastIndex = 0;
  5217. for (index = match.index; index < str.length; index++) {
  5218. switch (str.charCodeAt(index)) {
  5219. case 34:
  5220. escape = "&quot;";
  5221. break;
  5222. case 38:
  5223. escape = "&amp;";
  5224. break;
  5225. case 39:
  5226. escape = "&#39;";
  5227. break;
  5228. case 60:
  5229. escape = "&lt;";
  5230. break;
  5231. case 62:
  5232. escape = "&gt;";
  5233. break;
  5234. default: continue;
  5235. }
  5236. if (lastIndex !== index) html += str.substring(lastIndex, index);
  5237. lastIndex = index + 1;
  5238. html += escape;
  5239. }
  5240. return lastIndex !== index ? html + str.substring(lastIndex, index) : html;
  5241. }
  5242. }));
  5243. //#endregion
  5244. //#region ../../node_modules/.pnpm/ee-first@1.1.1/node_modules/ee-first/index.js
  5245. /*!
  5246. * ee-first
  5247. * Copyright(c) 2014 Jonathan Ong
  5248. * MIT Licensed
  5249. */
  5250. var require_ee_first = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  5251. /**
  5252. * Module exports.
  5253. * @public
  5254. */
  5255. module.exports = first;
  5256. /**
  5257. * Get the first event in a set of event emitters and event pairs.
  5258. *
  5259. * @param {array} stuff
  5260. * @param {function} done
  5261. * @public
  5262. */
  5263. function first(stuff, done) {
  5264. if (!Array.isArray(stuff)) throw new TypeError("arg must be an array of [ee, events...] arrays");
  5265. var cleanups = [];
  5266. for (var i = 0; i < stuff.length; i++) {
  5267. var arr = stuff[i];
  5268. if (!Array.isArray(arr) || arr.length < 2) throw new TypeError("each array member must be [ee, events...]");
  5269. var ee = arr[0];
  5270. for (var j = 1; j < arr.length; j++) {
  5271. var event = arr[j];
  5272. var fn = listener(event, callback);
  5273. ee.on(event, fn);
  5274. cleanups.push({
  5275. ee,
  5276. event,
  5277. fn
  5278. });
  5279. }
  5280. }
  5281. function callback() {
  5282. cleanup();
  5283. done.apply(null, arguments);
  5284. }
  5285. function cleanup() {
  5286. var x;
  5287. for (var i = 0; i < cleanups.length; i++) {
  5288. x = cleanups[i];
  5289. x.ee.removeListener(x.event, x.fn);
  5290. }
  5291. }
  5292. function thunk(fn) {
  5293. done = fn;
  5294. }
  5295. thunk.cancel = cleanup;
  5296. return thunk;
  5297. }
  5298. /**
  5299. * Create the event listener.
  5300. * @private
  5301. */
  5302. function listener(event, done) {
  5303. return function onevent(arg1) {
  5304. var args = new Array(arguments.length);
  5305. var ee = this;
  5306. var err = event === "error" ? arg1 : null;
  5307. for (var i = 0; i < args.length; i++) args[i] = arguments[i];
  5308. done(err, ee, event, args);
  5309. };
  5310. }
  5311. }));
  5312. //#endregion
  5313. //#region ../../node_modules/.pnpm/on-finished@2.3.0/node_modules/on-finished/index.js
  5314. /*!
  5315. * on-finished
  5316. * Copyright(c) 2013 Jonathan Ong
  5317. * Copyright(c) 2014 Douglas Christopher Wilson
  5318. * MIT Licensed
  5319. */
  5320. var require_on_finished = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  5321. /**
  5322. * Module exports.
  5323. * @public
  5324. */
  5325. module.exports = onFinished;
  5326. module.exports.isFinished = isFinished;
  5327. /**
  5328. * Module dependencies.
  5329. * @private
  5330. */
  5331. var first = require_ee_first();
  5332. /**
  5333. * Variables.
  5334. * @private
  5335. */
  5336. /* istanbul ignore next */
  5337. var defer = typeof setImmediate === "function" ? setImmediate : function(fn) {
  5338. process.nextTick(fn.bind.apply(fn, arguments));
  5339. };
  5340. /**
  5341. * Invoke callback when the response has finished, useful for
  5342. * cleaning up resources afterwards.
  5343. *
  5344. * @param {object} msg
  5345. * @param {function} listener
  5346. * @return {object}
  5347. * @public
  5348. */
  5349. function onFinished(msg, listener) {
  5350. if (isFinished(msg) !== false) {
  5351. defer(listener, null, msg);
  5352. return msg;
  5353. }
  5354. attachListener(msg, listener);
  5355. return msg;
  5356. }
  5357. /**
  5358. * Determine if message is already finished.
  5359. *
  5360. * @param {object} msg
  5361. * @return {boolean}
  5362. * @public
  5363. */
  5364. function isFinished(msg) {
  5365. var socket = msg.socket;
  5366. if (typeof msg.finished === "boolean") return Boolean(msg.finished || socket && !socket.writable);
  5367. if (typeof msg.complete === "boolean") return Boolean(msg.upgrade || !socket || !socket.readable || msg.complete && !msg.readable);
  5368. }
  5369. /**
  5370. * Attach a finished listener to the message.
  5371. *
  5372. * @param {object} msg
  5373. * @param {function} callback
  5374. * @private
  5375. */
  5376. function attachFinishedListener(msg, callback) {
  5377. var eeMsg;
  5378. var eeSocket;
  5379. var finished = false;
  5380. function onFinish(error) {
  5381. eeMsg.cancel();
  5382. eeSocket.cancel();
  5383. finished = true;
  5384. callback(error);
  5385. }
  5386. eeMsg = eeSocket = first([[
  5387. msg,
  5388. "end",
  5389. "finish"
  5390. ]], onFinish);
  5391. function onSocket(socket) {
  5392. msg.removeListener("socket", onSocket);
  5393. if (finished) return;
  5394. if (eeMsg !== eeSocket) return;
  5395. eeSocket = first([[
  5396. socket,
  5397. "error",
  5398. "close"
  5399. ]], onFinish);
  5400. }
  5401. if (msg.socket) {
  5402. onSocket(msg.socket);
  5403. return;
  5404. }
  5405. msg.on("socket", onSocket);
  5406. if (msg.socket === void 0) patchAssignSocket(msg, onSocket);
  5407. }
  5408. /**
  5409. * Attach the listener to the message.
  5410. *
  5411. * @param {object} msg
  5412. * @return {function}
  5413. * @private
  5414. */
  5415. function attachListener(msg, listener) {
  5416. var attached = msg.__onFinished;
  5417. if (!attached || !attached.queue) {
  5418. attached = msg.__onFinished = createListener(msg);
  5419. attachFinishedListener(msg, attached);
  5420. }
  5421. attached.queue.push(listener);
  5422. }
  5423. /**
  5424. * Create listener on message.
  5425. *
  5426. * @param {object} msg
  5427. * @return {function}
  5428. * @private
  5429. */
  5430. function createListener(msg) {
  5431. function listener(err) {
  5432. if (msg.__onFinished === listener) msg.__onFinished = null;
  5433. if (!listener.queue) return;
  5434. var queue = listener.queue;
  5435. listener.queue = null;
  5436. for (var i = 0; i < queue.length; i++) queue[i](err, msg);
  5437. }
  5438. listener.queue = [];
  5439. return listener;
  5440. }
  5441. /**
  5442. * Patch ServerResponse.prototype.assignSocket for node.js 0.8.
  5443. *
  5444. * @param {ServerResponse} res
  5445. * @param {function} callback
  5446. * @private
  5447. */
  5448. function patchAssignSocket(res, callback) {
  5449. var assignSocket = res.assignSocket;
  5450. if (typeof assignSocket !== "function") return;
  5451. res.assignSocket = function _assignSocket(socket) {
  5452. assignSocket.call(this, socket);
  5453. callback(socket);
  5454. };
  5455. }
  5456. }));
  5457. //#endregion
  5458. //#region ../../node_modules/.pnpm/parseurl@1.3.3/node_modules/parseurl/index.js
  5459. /*!
  5460. * parseurl
  5461. * Copyright(c) 2014 Jonathan Ong
  5462. * Copyright(c) 2014-2017 Douglas Christopher Wilson
  5463. * MIT Licensed
  5464. */
  5465. var require_parseurl = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  5466. /**
  5467. * Module dependencies.
  5468. * @private
  5469. */
  5470. var url$2 = __require("url");
  5471. var parse = url$2.parse;
  5472. var Url = url$2.Url;
  5473. /**
  5474. * Module exports.
  5475. * @public
  5476. */
  5477. module.exports = parseurl;
  5478. module.exports.original = originalurl;
  5479. /**
  5480. * Parse the `req` url with memoization.
  5481. *
  5482. * @param {ServerRequest} req
  5483. * @return {Object}
  5484. * @public
  5485. */
  5486. function parseurl(req) {
  5487. var url = req.url;
  5488. if (url === void 0) return;
  5489. var parsed = req._parsedUrl;
  5490. if (fresh(url, parsed)) return parsed;
  5491. parsed = fastparse(url);
  5492. parsed._raw = url;
  5493. return req._parsedUrl = parsed;
  5494. }
  5495. /**
  5496. * Parse the `req` original url with fallback and memoization.
  5497. *
  5498. * @param {ServerRequest} req
  5499. * @return {Object}
  5500. * @public
  5501. */
  5502. function originalurl(req) {
  5503. var url = req.originalUrl;
  5504. if (typeof url !== "string") return parseurl(req);
  5505. var parsed = req._parsedOriginalUrl;
  5506. if (fresh(url, parsed)) return parsed;
  5507. parsed = fastparse(url);
  5508. parsed._raw = url;
  5509. return req._parsedOriginalUrl = parsed;
  5510. }
  5511. /**
  5512. * Parse the `str` url with fast-path short-cut.
  5513. *
  5514. * @param {string} str
  5515. * @return {Object}
  5516. * @private
  5517. */
  5518. function fastparse(str) {
  5519. if (typeof str !== "string" || str.charCodeAt(0) !== 47) return parse(str);
  5520. var pathname = str;
  5521. var query = null;
  5522. var search = null;
  5523. for (var i = 1; i < str.length; i++) switch (str.charCodeAt(i)) {
  5524. case 63:
  5525. if (search === null) {
  5526. pathname = str.substring(0, i);
  5527. query = str.substring(i + 1);
  5528. search = str.substring(i);
  5529. }
  5530. break;
  5531. case 9:
  5532. case 10:
  5533. case 12:
  5534. case 13:
  5535. case 32:
  5536. case 35:
  5537. case 160:
  5538. case 65279: return parse(str);
  5539. }
  5540. var url = Url !== void 0 ? new Url() : {};
  5541. url.path = str;
  5542. url.href = str;
  5543. url.pathname = pathname;
  5544. if (search !== null) {
  5545. url.query = query;
  5546. url.search = search;
  5547. }
  5548. return url;
  5549. }
  5550. /**
  5551. * Determine if parsed is still fresh for url.
  5552. *
  5553. * @param {string} url
  5554. * @param {object} parsedUrl
  5555. * @return {boolean}
  5556. * @private
  5557. */
  5558. function fresh(url, parsedUrl) {
  5559. return typeof parsedUrl === "object" && parsedUrl !== null && (Url === void 0 || parsedUrl instanceof Url) && parsedUrl._raw === url;
  5560. }
  5561. }));
  5562. //#endregion
  5563. //#region ../../node_modules/.pnpm/statuses@1.5.0/node_modules/statuses/codes.json
  5564. var require_codes = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  5565. module.exports = {
  5566. "100": "Continue",
  5567. "101": "Switching Protocols",
  5568. "102": "Processing",
  5569. "103": "Early Hints",
  5570. "200": "OK",
  5571. "201": "Created",
  5572. "202": "Accepted",
  5573. "203": "Non-Authoritative Information",
  5574. "204": "No Content",
  5575. "205": "Reset Content",
  5576. "206": "Partial Content",
  5577. "207": "Multi-Status",
  5578. "208": "Already Reported",
  5579. "226": "IM Used",
  5580. "300": "Multiple Choices",
  5581. "301": "Moved Permanently",
  5582. "302": "Found",
  5583. "303": "See Other",
  5584. "304": "Not Modified",
  5585. "305": "Use Proxy",
  5586. "306": "(Unused)",
  5587. "307": "Temporary Redirect",
  5588. "308": "Permanent Redirect",
  5589. "400": "Bad Request",
  5590. "401": "Unauthorized",
  5591. "402": "Payment Required",
  5592. "403": "Forbidden",
  5593. "404": "Not Found",
  5594. "405": "Method Not Allowed",
  5595. "406": "Not Acceptable",
  5596. "407": "Proxy Authentication Required",
  5597. "408": "Request Timeout",
  5598. "409": "Conflict",
  5599. "410": "Gone",
  5600. "411": "Length Required",
  5601. "412": "Precondition Failed",
  5602. "413": "Payload Too Large",
  5603. "414": "URI Too Long",
  5604. "415": "Unsupported Media Type",
  5605. "416": "Range Not Satisfiable",
  5606. "417": "Expectation Failed",
  5607. "418": "I'm a teapot",
  5608. "421": "Misdirected Request",
  5609. "422": "Unprocessable Entity",
  5610. "423": "Locked",
  5611. "424": "Failed Dependency",
  5612. "425": "Unordered Collection",
  5613. "426": "Upgrade Required",
  5614. "428": "Precondition Required",
  5615. "429": "Too Many Requests",
  5616. "431": "Request Header Fields Too Large",
  5617. "451": "Unavailable For Legal Reasons",
  5618. "500": "Internal Server Error",
  5619. "501": "Not Implemented",
  5620. "502": "Bad Gateway",
  5621. "503": "Service Unavailable",
  5622. "504": "Gateway Timeout",
  5623. "505": "HTTP Version Not Supported",
  5624. "506": "Variant Also Negotiates",
  5625. "507": "Insufficient Storage",
  5626. "508": "Loop Detected",
  5627. "509": "Bandwidth Limit Exceeded",
  5628. "510": "Not Extended",
  5629. "511": "Network Authentication Required"
  5630. };
  5631. }));
  5632. //#endregion
  5633. //#region ../../node_modules/.pnpm/statuses@1.5.0/node_modules/statuses/index.js
  5634. /*!
  5635. * statuses
  5636. * Copyright(c) 2014 Jonathan Ong
  5637. * Copyright(c) 2016 Douglas Christopher Wilson
  5638. * MIT Licensed
  5639. */
  5640. var require_statuses = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  5641. /**
  5642. * Module dependencies.
  5643. * @private
  5644. */
  5645. var codes = require_codes();
  5646. /**
  5647. * Module exports.
  5648. * @public
  5649. */
  5650. module.exports = status;
  5651. status.STATUS_CODES = codes;
  5652. status.codes = populateStatusesMap(status, codes);
  5653. status.redirect = {
  5654. 300: true,
  5655. 301: true,
  5656. 302: true,
  5657. 303: true,
  5658. 305: true,
  5659. 307: true,
  5660. 308: true
  5661. };
  5662. status.empty = {
  5663. 204: true,
  5664. 205: true,
  5665. 304: true
  5666. };
  5667. status.retry = {
  5668. 502: true,
  5669. 503: true,
  5670. 504: true
  5671. };
  5672. /**
  5673. * Populate the statuses map for given codes.
  5674. * @private
  5675. */
  5676. function populateStatusesMap(statuses, codes) {
  5677. var arr = [];
  5678. Object.keys(codes).forEach(function forEachCode(code) {
  5679. var message = codes[code];
  5680. var status = Number(code);
  5681. statuses[status] = message;
  5682. statuses[message] = status;
  5683. statuses[message.toLowerCase()] = status;
  5684. arr.push(status);
  5685. });
  5686. return arr;
  5687. }
  5688. /**
  5689. * Get the status code.
  5690. *
  5691. * Given a number, this will throw if it is not a known status
  5692. * code, otherwise the code will be returned. Given a string,
  5693. * the string will be parsed for a number and return the code
  5694. * if valid, otherwise will lookup the code assuming this is
  5695. * the status message.
  5696. *
  5697. * @param {string|number} code
  5698. * @returns {number}
  5699. * @public
  5700. */
  5701. function status(code) {
  5702. if (typeof code === "number") {
  5703. if (!status[code]) throw new Error("invalid status code: " + code);
  5704. return code;
  5705. }
  5706. if (typeof code !== "string") throw new TypeError("code must be a number or string");
  5707. var n = parseInt(code, 10);
  5708. if (!isNaN(n)) {
  5709. if (!status[n]) throw new Error("invalid status code: " + n);
  5710. return n;
  5711. }
  5712. n = status[code.toLowerCase()];
  5713. if (!n) throw new Error("invalid status message: \"" + code + "\"");
  5714. return n;
  5715. }
  5716. }));
  5717. //#endregion
  5718. //#region ../../node_modules/.pnpm/unpipe@1.0.0/node_modules/unpipe/index.js
  5719. /*!
  5720. * unpipe
  5721. * Copyright(c) 2015 Douglas Christopher Wilson
  5722. * MIT Licensed
  5723. */
  5724. var require_unpipe = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  5725. /**
  5726. * Module exports.
  5727. * @public
  5728. */
  5729. module.exports = unpipe;
  5730. /**
  5731. * Determine if there are Node.js pipe-like data listeners.
  5732. * @private
  5733. */
  5734. function hasPipeDataListeners(stream) {
  5735. var listeners = stream.listeners("data");
  5736. for (var i = 0; i < listeners.length; i++) if (listeners[i].name === "ondata") return true;
  5737. return false;
  5738. }
  5739. /**
  5740. * Unpipe a stream from all destinations.
  5741. *
  5742. * @param {object} stream
  5743. * @public
  5744. */
  5745. function unpipe(stream) {
  5746. if (!stream) throw new TypeError("argument stream is required");
  5747. if (typeof stream.unpipe === "function") {
  5748. stream.unpipe();
  5749. return;
  5750. }
  5751. if (!hasPipeDataListeners(stream)) return;
  5752. var listener;
  5753. var listeners = stream.listeners("close");
  5754. for (var i = 0; i < listeners.length; i++) {
  5755. listener = listeners[i];
  5756. if (listener.name !== "cleanup" && listener.name !== "onclose") continue;
  5757. listener.call(stream);
  5758. }
  5759. }
  5760. }));
  5761. //#endregion
  5762. //#region ../../node_modules/.pnpm/finalhandler@1.1.2_ms@2.1.3/node_modules/finalhandler/index.js
  5763. /*!
  5764. * finalhandler
  5765. * Copyright(c) 2014-2017 Douglas Christopher Wilson
  5766. * MIT Licensed
  5767. */
  5768. var require_finalhandler = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  5769. /**
  5770. * Module dependencies.
  5771. * @private
  5772. */
  5773. var debug = (init_node(), __toCommonJS(node_exports))("finalhandler");
  5774. var encodeUrl = require_encodeurl();
  5775. var escapeHtml = require_escape_html();
  5776. var onFinished = require_on_finished();
  5777. var parseUrl = require_parseurl();
  5778. var statuses = require_statuses();
  5779. var unpipe = require_unpipe();
  5780. /**
  5781. * Module variables.
  5782. * @private
  5783. */
  5784. var DOUBLE_SPACE_REGEXP = /\x20{2}/g;
  5785. var NEWLINE_REGEXP = /\n/g;
  5786. /* istanbul ignore next */
  5787. var defer = typeof setImmediate === "function" ? setImmediate : function(fn) {
  5788. process.nextTick(fn.bind.apply(fn, arguments));
  5789. };
  5790. var isFinished = onFinished.isFinished;
  5791. /**
  5792. * Create a minimal HTML document.
  5793. *
  5794. * @param {string} message
  5795. * @private
  5796. */
  5797. function createHtmlDocument(message) {
  5798. return "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n<title>Error</title>\n</head>\n<body>\n<pre>" + escapeHtml(message).replace(NEWLINE_REGEXP, "<br>").replace(DOUBLE_SPACE_REGEXP, " &nbsp;") + "</pre>\n</body>\n</html>\n";
  5799. }
  5800. /**
  5801. * Module exports.
  5802. * @public
  5803. */
  5804. module.exports = finalhandler;
  5805. /**
  5806. * Create a function to handle the final response.
  5807. *
  5808. * @param {Request} req
  5809. * @param {Response} res
  5810. * @param {Object} [options]
  5811. * @return {Function}
  5812. * @public
  5813. */
  5814. function finalhandler(req, res, options) {
  5815. var opts = options || {};
  5816. var env = opts.env || process.env.NODE_ENV || "development";
  5817. var onerror = opts.onerror;
  5818. return function(err) {
  5819. var headers;
  5820. var msg;
  5821. var status;
  5822. if (!err && headersSent(res)) {
  5823. debug("cannot 404 after headers sent");
  5824. return;
  5825. }
  5826. if (err) {
  5827. status = getErrorStatusCode(err);
  5828. if (status === void 0) status = getResponseStatusCode(res);
  5829. else headers = getErrorHeaders(err);
  5830. msg = getErrorMessage(err, status, env);
  5831. } else {
  5832. status = 404;
  5833. msg = "Cannot " + req.method + " " + encodeUrl(getResourceName(req));
  5834. }
  5835. debug("default %s", status);
  5836. if (err && onerror) defer(onerror, err, req, res);
  5837. if (headersSent(res)) {
  5838. debug("cannot %d after headers sent", status);
  5839. req.socket.destroy();
  5840. return;
  5841. }
  5842. send(req, res, status, headers, msg);
  5843. };
  5844. }
  5845. /**
  5846. * Get headers from Error object.
  5847. *
  5848. * @param {Error} err
  5849. * @return {object}
  5850. * @private
  5851. */
  5852. function getErrorHeaders(err) {
  5853. if (!err.headers || typeof err.headers !== "object") return;
  5854. var headers = Object.create(null);
  5855. var keys = Object.keys(err.headers);
  5856. for (var i = 0; i < keys.length; i++) {
  5857. var key = keys[i];
  5858. headers[key] = err.headers[key];
  5859. }
  5860. return headers;
  5861. }
  5862. /**
  5863. * Get message from Error object, fallback to status message.
  5864. *
  5865. * @param {Error} err
  5866. * @param {number} status
  5867. * @param {string} env
  5868. * @return {string}
  5869. * @private
  5870. */
  5871. function getErrorMessage(err, status, env) {
  5872. var msg;
  5873. if (env !== "production") {
  5874. msg = err.stack;
  5875. if (!msg && typeof err.toString === "function") msg = err.toString();
  5876. }
  5877. return msg || statuses[status];
  5878. }
  5879. /**
  5880. * Get status code from Error object.
  5881. *
  5882. * @param {Error} err
  5883. * @return {number}
  5884. * @private
  5885. */
  5886. function getErrorStatusCode(err) {
  5887. if (typeof err.status === "number" && err.status >= 400 && err.status < 600) return err.status;
  5888. if (typeof err.statusCode === "number" && err.statusCode >= 400 && err.statusCode < 600) return err.statusCode;
  5889. }
  5890. /**
  5891. * Get resource name for the request.
  5892. *
  5893. * This is typically just the original pathname of the request
  5894. * but will fallback to "resource" is that cannot be determined.
  5895. *
  5896. * @param {IncomingMessage} req
  5897. * @return {string}
  5898. * @private
  5899. */
  5900. function getResourceName(req) {
  5901. try {
  5902. return parseUrl.original(req).pathname;
  5903. } catch (e) {
  5904. return "resource";
  5905. }
  5906. }
  5907. /**
  5908. * Get status code from response.
  5909. *
  5910. * @param {OutgoingMessage} res
  5911. * @return {number}
  5912. * @private
  5913. */
  5914. function getResponseStatusCode(res) {
  5915. var status = res.statusCode;
  5916. if (typeof status !== "number" || status < 400 || status > 599) status = 500;
  5917. return status;
  5918. }
  5919. /**
  5920. * Determine if the response headers have been sent.
  5921. *
  5922. * @param {object} res
  5923. * @returns {boolean}
  5924. * @private
  5925. */
  5926. function headersSent(res) {
  5927. return typeof res.headersSent !== "boolean" ? Boolean(res._header) : res.headersSent;
  5928. }
  5929. /**
  5930. * Send response.
  5931. *
  5932. * @param {IncomingMessage} req
  5933. * @param {OutgoingMessage} res
  5934. * @param {number} status
  5935. * @param {object} headers
  5936. * @param {string} message
  5937. * @private
  5938. */
  5939. function send(req, res, status, headers, message) {
  5940. function write() {
  5941. var body = createHtmlDocument(message);
  5942. res.statusCode = status;
  5943. res.statusMessage = statuses[status];
  5944. setHeaders(res, headers);
  5945. res.setHeader("Content-Security-Policy", "default-src 'none'");
  5946. res.setHeader("X-Content-Type-Options", "nosniff");
  5947. res.setHeader("Content-Type", "text/html; charset=utf-8");
  5948. res.setHeader("Content-Length", Buffer.byteLength(body, "utf8"));
  5949. if (req.method === "HEAD") {
  5950. res.end();
  5951. return;
  5952. }
  5953. res.end(body, "utf8");
  5954. }
  5955. if (isFinished(req)) {
  5956. write();
  5957. return;
  5958. }
  5959. unpipe(req);
  5960. onFinished(req, write);
  5961. req.resume();
  5962. }
  5963. /**
  5964. * Set response headers from an object.
  5965. *
  5966. * @param {OutgoingMessage} res
  5967. * @param {object} headers
  5968. * @private
  5969. */
  5970. function setHeaders(res, headers) {
  5971. if (!headers) return;
  5972. var keys = Object.keys(headers);
  5973. for (var i = 0; i < keys.length; i++) {
  5974. var key = keys[i];
  5975. res.setHeader(key, headers[key]);
  5976. }
  5977. }
  5978. }));
  5979. //#endregion
  5980. //#region ../../node_modules/.pnpm/utils-merge@1.0.1/node_modules/utils-merge/index.js
  5981. var require_utils_merge = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  5982. /**
  5983. * Merge object b with object a.
  5984. *
  5985. * var a = { foo: 'bar' }
  5986. * , b = { bar: 'baz' };
  5987. *
  5988. * merge(a, b);
  5989. * // => { foo: 'bar', bar: 'baz' }
  5990. *
  5991. * @param {Object} a
  5992. * @param {Object} b
  5993. * @return {Object}
  5994. * @api public
  5995. */
  5996. exports = module.exports = function(a, b) {
  5997. if (a && b) for (var key in b) a[key] = b[key];
  5998. return a;
  5999. };
  6000. }));
  6001. //#endregion
  6002. //#region ../../node_modules/.pnpm/connect@3.7.0_ms@2.1.3/node_modules/connect/index.js
  6003. /*!
  6004. * connect
  6005. * Copyright(c) 2010 Sencha Inc.
  6006. * Copyright(c) 2011 TJ Holowaychuk
  6007. * Copyright(c) 2015 Douglas Christopher Wilson
  6008. * MIT Licensed
  6009. */
  6010. var require_connect = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  6011. /**
  6012. * Module dependencies.
  6013. * @private
  6014. */
  6015. var debug = (init_node(), __toCommonJS(node_exports))("connect:dispatcher");
  6016. var EventEmitter$4 = __require("events").EventEmitter;
  6017. var finalhandler = require_finalhandler();
  6018. var http$6 = __require("http");
  6019. var merge = require_utils_merge();
  6020. var parseUrl = require_parseurl();
  6021. /**
  6022. * Module exports.
  6023. * @public
  6024. */
  6025. module.exports = createServer;
  6026. /**
  6027. * Module variables.
  6028. * @private
  6029. */
  6030. var env = process.env.NODE_ENV || "development";
  6031. var proto = {};
  6032. /* istanbul ignore next */
  6033. var defer = typeof setImmediate === "function" ? setImmediate : function(fn) {
  6034. process.nextTick(fn.bind.apply(fn, arguments));
  6035. };
  6036. /**
  6037. * Create a new connect server.
  6038. *
  6039. * @return {function}
  6040. * @public
  6041. */
  6042. function createServer() {
  6043. function app(req, res, next) {
  6044. app.handle(req, res, next);
  6045. }
  6046. merge(app, proto);
  6047. merge(app, EventEmitter$4.prototype);
  6048. app.route = "/";
  6049. app.stack = [];
  6050. return app;
  6051. }
  6052. /**
  6053. * Utilize the given middleware `handle` to the given `route`,
  6054. * defaulting to _/_. This "route" is the mount-point for the
  6055. * middleware, when given a value other than _/_ the middleware
  6056. * is only effective when that segment is present in the request's
  6057. * pathname.
  6058. *
  6059. * For example if we were to mount a function at _/admin_, it would
  6060. * be invoked on _/admin_, and _/admin/settings_, however it would
  6061. * not be invoked for _/_, or _/posts_.
  6062. *
  6063. * @param {String|Function|Server} route, callback or server
  6064. * @param {Function|Server} callback or server
  6065. * @return {Server} for chaining
  6066. * @public
  6067. */
  6068. proto.use = function use(route, fn) {
  6069. var handle = fn;
  6070. var path = route;
  6071. if (typeof route !== "string") {
  6072. handle = route;
  6073. path = "/";
  6074. }
  6075. if (typeof handle.handle === "function") {
  6076. var server = handle;
  6077. server.route = path;
  6078. handle = function(req, res, next) {
  6079. server.handle(req, res, next);
  6080. };
  6081. }
  6082. if (handle instanceof http$6.Server) handle = handle.listeners("request")[0];
  6083. if (path[path.length - 1] === "/") path = path.slice(0, -1);
  6084. debug("use %s %s", path || "/", handle.name || "anonymous");
  6085. this.stack.push({
  6086. route: path,
  6087. handle
  6088. });
  6089. return this;
  6090. };
  6091. /**
  6092. * Handle server requests, punting them down
  6093. * the middleware stack.
  6094. *
  6095. * @private
  6096. */
  6097. proto.handle = function handle(req, res, out) {
  6098. var index = 0;
  6099. var protohost = getProtohost(req.url) || "";
  6100. var removed = "";
  6101. var slashAdded = false;
  6102. var stack = this.stack;
  6103. var done = out || finalhandler(req, res, {
  6104. env,
  6105. onerror: logerror
  6106. });
  6107. req.originalUrl = req.originalUrl || req.url;
  6108. function next(err) {
  6109. if (slashAdded) {
  6110. req.url = req.url.substr(1);
  6111. slashAdded = false;
  6112. }
  6113. if (removed.length !== 0) {
  6114. req.url = protohost + removed + req.url.substr(protohost.length);
  6115. removed = "";
  6116. }
  6117. var layer = stack[index++];
  6118. if (!layer) {
  6119. defer(done, err);
  6120. return;
  6121. }
  6122. var path = parseUrl(req).pathname || "/";
  6123. var route = layer.route;
  6124. if (path.toLowerCase().substr(0, route.length) !== route.toLowerCase()) return next(err);
  6125. var c = path.length > route.length && path[route.length];
  6126. if (c && c !== "/" && c !== ".") return next(err);
  6127. if (route.length !== 0 && route !== "/") {
  6128. removed = route;
  6129. req.url = protohost + req.url.substr(protohost.length + removed.length);
  6130. if (!protohost && req.url[0] !== "/") {
  6131. req.url = "/" + req.url;
  6132. slashAdded = true;
  6133. }
  6134. }
  6135. call(layer.handle, route, err, req, res, next);
  6136. }
  6137. next();
  6138. };
  6139. /**
  6140. * Listen for connections.
  6141. *
  6142. * This method takes the same arguments
  6143. * as node's `http.Server#listen()`.
  6144. *
  6145. * HTTP and HTTPS:
  6146. *
  6147. * If you run your application both as HTTP
  6148. * and HTTPS you may wrap them individually,
  6149. * since your Connect "server" is really just
  6150. * a JavaScript `Function`.
  6151. *
  6152. * var connect = require('connect')
  6153. * , http = require('http')
  6154. * , https = require('https');
  6155. *
  6156. * var app = connect();
  6157. *
  6158. * http.createServer(app).listen(80);
  6159. * https.createServer(options, app).listen(443);
  6160. *
  6161. * @return {http.Server}
  6162. * @api public
  6163. */
  6164. proto.listen = function listen() {
  6165. var server = http$6.createServer(this);
  6166. return server.listen.apply(server, arguments);
  6167. };
  6168. /**
  6169. * Invoke a route handle.
  6170. * @private
  6171. */
  6172. function call(handle, route, err, req, res, next) {
  6173. var arity = handle.length;
  6174. var error = err;
  6175. var hasError = Boolean(err);
  6176. debug("%s %s : %s", handle.name || "<anonymous>", route, req.originalUrl);
  6177. try {
  6178. if (hasError && arity === 4) {
  6179. handle(err, req, res, next);
  6180. return;
  6181. } else if (!hasError && arity < 4) {
  6182. handle(req, res, next);
  6183. return;
  6184. }
  6185. } catch (e) {
  6186. error = e;
  6187. }
  6188. next(error);
  6189. }
  6190. /**
  6191. * Log error using console.error.
  6192. *
  6193. * @param {Error} err
  6194. * @private
  6195. */
  6196. function logerror(err) {
  6197. if (env !== "test") console.error(err.stack || err.toString());
  6198. }
  6199. /**
  6200. * Get get protocol + host for a URL.
  6201. *
  6202. * @param {string} url
  6203. * @private
  6204. */
  6205. function getProtohost(url) {
  6206. if (url.length === 0 || url[0] === "/") return;
  6207. var fqdnIndex = url.indexOf("://");
  6208. return fqdnIndex !== -1 && url.lastIndexOf("?", fqdnIndex) === -1 ? url.substr(0, url.indexOf("/", 3 + fqdnIndex)) : void 0;
  6209. }
  6210. }));
  6211. //#endregion
  6212. //#region ../../node_modules/.pnpm/object-assign@4.1.1/node_modules/object-assign/index.js
  6213. /*
  6214. object-assign
  6215. (c) Sindre Sorhus
  6216. @license MIT
  6217. */
  6218. var require_object_assign = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  6219. var getOwnPropertySymbols = Object.getOwnPropertySymbols;
  6220. var hasOwnProperty = Object.prototype.hasOwnProperty;
  6221. var propIsEnumerable = Object.prototype.propertyIsEnumerable;
  6222. function toObject(val) {
  6223. if (val === null || val === void 0) throw new TypeError("Object.assign cannot be called with null or undefined");
  6224. return Object(val);
  6225. }
  6226. function shouldUseNative() {
  6227. try {
  6228. if (!Object.assign) return false;
  6229. var test1 = /* @__PURE__ */ new String("abc");
  6230. test1[5] = "de";
  6231. if (Object.getOwnPropertyNames(test1)[0] === "5") return false;
  6232. var test2 = {};
  6233. for (var i = 0; i < 10; i++) test2["_" + String.fromCharCode(i)] = i;
  6234. if (Object.getOwnPropertyNames(test2).map(function(n) {
  6235. return test2[n];
  6236. }).join("") !== "0123456789") return false;
  6237. var test3 = {};
  6238. "abcdefghijklmnopqrst".split("").forEach(function(letter) {
  6239. test3[letter] = letter;
  6240. });
  6241. if (Object.keys(Object.assign({}, test3)).join("") !== "abcdefghijklmnopqrst") return false;
  6242. return true;
  6243. } catch (err) {
  6244. return false;
  6245. }
  6246. }
  6247. module.exports = shouldUseNative() ? Object.assign : function(target, source) {
  6248. var from;
  6249. var to = toObject(target);
  6250. var symbols;
  6251. for (var s = 1; s < arguments.length; s++) {
  6252. from = Object(arguments[s]);
  6253. for (var key in from) if (hasOwnProperty.call(from, key)) to[key] = from[key];
  6254. if (getOwnPropertySymbols) {
  6255. symbols = getOwnPropertySymbols(from);
  6256. for (var i = 0; i < symbols.length; i++) if (propIsEnumerable.call(from, symbols[i])) to[symbols[i]] = from[symbols[i]];
  6257. }
  6258. }
  6259. return to;
  6260. };
  6261. }));
  6262. //#endregion
  6263. //#region ../../node_modules/.pnpm/vary@1.1.2/node_modules/vary/index.js
  6264. /*!
  6265. * vary
  6266. * Copyright(c) 2014-2017 Douglas Christopher Wilson
  6267. * MIT Licensed
  6268. */
  6269. var require_vary = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  6270. /**
  6271. * Module exports.
  6272. */
  6273. module.exports = vary;
  6274. module.exports.append = append;
  6275. /**
  6276. * RegExp to match field-name in RFC 7230 sec 3.2
  6277. *
  6278. * field-name = token
  6279. * token = 1*tchar
  6280. * tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*"
  6281. * / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~"
  6282. * / DIGIT / ALPHA
  6283. * ; any VCHAR, except delimiters
  6284. */
  6285. var FIELD_NAME_REGEXP = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
  6286. /**
  6287. * Append a field to a vary header.
  6288. *
  6289. * @param {String} header
  6290. * @param {String|Array} field
  6291. * @return {String}
  6292. * @public
  6293. */
  6294. function append(header, field) {
  6295. if (typeof header !== "string") throw new TypeError("header argument is required");
  6296. if (!field) throw new TypeError("field argument is required");
  6297. var fields = !Array.isArray(field) ? parse(String(field)) : field;
  6298. for (var j = 0; j < fields.length; j++) if (!FIELD_NAME_REGEXP.test(fields[j])) throw new TypeError("field argument contains an invalid header name");
  6299. if (header === "*") return header;
  6300. var val = header;
  6301. var vals = parse(header.toLowerCase());
  6302. if (fields.indexOf("*") !== -1 || vals.indexOf("*") !== -1) return "*";
  6303. for (var i = 0; i < fields.length; i++) {
  6304. var fld = fields[i].toLowerCase();
  6305. if (vals.indexOf(fld) === -1) {
  6306. vals.push(fld);
  6307. val = val ? val + ", " + fields[i] : fields[i];
  6308. }
  6309. }
  6310. return val;
  6311. }
  6312. /**
  6313. * Parse a vary header into an array.
  6314. *
  6315. * @param {String} header
  6316. * @return {Array}
  6317. * @private
  6318. */
  6319. function parse(header) {
  6320. var end = 0;
  6321. var list = [];
  6322. var start = 0;
  6323. for (var i = 0, len = header.length; i < len; i++) switch (header.charCodeAt(i)) {
  6324. case 32:
  6325. if (start === end) start = end = i + 1;
  6326. break;
  6327. case 44:
  6328. list.push(header.substring(start, end));
  6329. start = end = i + 1;
  6330. break;
  6331. default:
  6332. end = i + 1;
  6333. break;
  6334. }
  6335. list.push(header.substring(start, end));
  6336. return list;
  6337. }
  6338. /**
  6339. * Mark that a request is varied on a header field.
  6340. *
  6341. * @param {Object} res
  6342. * @param {String|Array} field
  6343. * @public
  6344. */
  6345. function vary(res, field) {
  6346. if (!res || !res.getHeader || !res.setHeader) throw new TypeError("res argument is required");
  6347. var val = res.getHeader("Vary") || "";
  6348. if (val = append(Array.isArray(val) ? val.join(", ") : String(val), field)) res.setHeader("Vary", val);
  6349. }
  6350. }));
  6351. //#endregion
  6352. //#region ../../node_modules/.pnpm/cors@2.8.6/node_modules/cors/lib/index.js
  6353. var require_lib$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  6354. (function() {
  6355. "use strict";
  6356. var assign = require_object_assign();
  6357. var vary = require_vary();
  6358. var defaults = {
  6359. origin: "*",
  6360. methods: "GET,HEAD,PUT,PATCH,POST,DELETE",
  6361. preflightContinue: false,
  6362. optionsSuccessStatus: 204
  6363. };
  6364. function isString(s) {
  6365. return typeof s === "string" || s instanceof String;
  6366. }
  6367. function isOriginAllowed(origin, allowedOrigin) {
  6368. if (Array.isArray(allowedOrigin)) {
  6369. for (var i = 0; i < allowedOrigin.length; ++i) if (isOriginAllowed(origin, allowedOrigin[i])) return true;
  6370. return false;
  6371. } else if (isString(allowedOrigin)) return origin === allowedOrigin;
  6372. else if (allowedOrigin instanceof RegExp) return allowedOrigin.test(origin);
  6373. else return !!allowedOrigin;
  6374. }
  6375. function configureOrigin(options, req) {
  6376. var requestOrigin = req.headers.origin, headers = [], isAllowed;
  6377. if (!options.origin || options.origin === "*") headers.push([{
  6378. key: "Access-Control-Allow-Origin",
  6379. value: "*"
  6380. }]);
  6381. else if (isString(options.origin)) {
  6382. headers.push([{
  6383. key: "Access-Control-Allow-Origin",
  6384. value: options.origin
  6385. }]);
  6386. headers.push([{
  6387. key: "Vary",
  6388. value: "Origin"
  6389. }]);
  6390. } else {
  6391. isAllowed = isOriginAllowed(requestOrigin, options.origin);
  6392. headers.push([{
  6393. key: "Access-Control-Allow-Origin",
  6394. value: isAllowed ? requestOrigin : false
  6395. }]);
  6396. headers.push([{
  6397. key: "Vary",
  6398. value: "Origin"
  6399. }]);
  6400. }
  6401. return headers;
  6402. }
  6403. function configureMethods(options) {
  6404. var methods = options.methods;
  6405. if (methods.join) methods = options.methods.join(",");
  6406. return {
  6407. key: "Access-Control-Allow-Methods",
  6408. value: methods
  6409. };
  6410. }
  6411. function configureCredentials(options) {
  6412. if (options.credentials === true) return {
  6413. key: "Access-Control-Allow-Credentials",
  6414. value: "true"
  6415. };
  6416. return null;
  6417. }
  6418. function configureAllowedHeaders(options, req) {
  6419. var allowedHeaders = options.allowedHeaders || options.headers;
  6420. var headers = [];
  6421. if (!allowedHeaders) {
  6422. allowedHeaders = req.headers["access-control-request-headers"];
  6423. headers.push([{
  6424. key: "Vary",
  6425. value: "Access-Control-Request-Headers"
  6426. }]);
  6427. } else if (allowedHeaders.join) allowedHeaders = allowedHeaders.join(",");
  6428. if (allowedHeaders && allowedHeaders.length) headers.push([{
  6429. key: "Access-Control-Allow-Headers",
  6430. value: allowedHeaders
  6431. }]);
  6432. return headers;
  6433. }
  6434. function configureExposedHeaders(options) {
  6435. var headers = options.exposedHeaders;
  6436. if (!headers) return null;
  6437. else if (headers.join) headers = headers.join(",");
  6438. if (headers && headers.length) return {
  6439. key: "Access-Control-Expose-Headers",
  6440. value: headers
  6441. };
  6442. return null;
  6443. }
  6444. function configureMaxAge(options) {
  6445. var maxAge = (typeof options.maxAge === "number" || options.maxAge) && options.maxAge.toString();
  6446. if (maxAge && maxAge.length) return {
  6447. key: "Access-Control-Max-Age",
  6448. value: maxAge
  6449. };
  6450. return null;
  6451. }
  6452. function applyHeaders(headers, res) {
  6453. for (var i = 0, n = headers.length; i < n; i++) {
  6454. var header = headers[i];
  6455. if (header) {
  6456. if (Array.isArray(header)) applyHeaders(header, res);
  6457. else if (header.key === "Vary" && header.value) vary(res, header.value);
  6458. else if (header.value) res.setHeader(header.key, header.value);
  6459. }
  6460. }
  6461. }
  6462. function cors(options, req, res, next) {
  6463. var headers = [];
  6464. if ((req.method && req.method.toUpperCase && req.method.toUpperCase()) === "OPTIONS") {
  6465. headers.push(configureOrigin(options, req));
  6466. headers.push(configureCredentials(options));
  6467. headers.push(configureMethods(options));
  6468. headers.push(configureAllowedHeaders(options, req));
  6469. headers.push(configureMaxAge(options));
  6470. headers.push(configureExposedHeaders(options));
  6471. applyHeaders(headers, res);
  6472. if (options.preflightContinue) next();
  6473. else {
  6474. res.statusCode = options.optionsSuccessStatus;
  6475. res.setHeader("Content-Length", "0");
  6476. res.end();
  6477. }
  6478. } else {
  6479. headers.push(configureOrigin(options, req));
  6480. headers.push(configureCredentials(options));
  6481. headers.push(configureExposedHeaders(options));
  6482. applyHeaders(headers, res);
  6483. next();
  6484. }
  6485. }
  6486. function middlewareWrapper(o) {
  6487. var optionsCallback = null;
  6488. if (typeof o === "function") optionsCallback = o;
  6489. else optionsCallback = function(req, cb) {
  6490. cb(null, o);
  6491. };
  6492. return function corsMiddleware(req, res, next) {
  6493. optionsCallback(req, function(err, options) {
  6494. if (err) next(err);
  6495. else {
  6496. var corsOptions = assign({}, defaults, options);
  6497. var originCallback = null;
  6498. if (corsOptions.origin && typeof corsOptions.origin === "function") originCallback = corsOptions.origin;
  6499. else if (corsOptions.origin) originCallback = function(origin, cb) {
  6500. cb(null, corsOptions.origin);
  6501. };
  6502. if (originCallback) originCallback(req.headers.origin, function(err2, origin) {
  6503. if (err2 || !origin) next(err2);
  6504. else {
  6505. corsOptions.origin = origin;
  6506. cors(corsOptions, req, res, next);
  6507. }
  6508. });
  6509. else next();
  6510. }
  6511. });
  6512. };
  6513. }
  6514. module.exports = middlewareWrapper;
  6515. })();
  6516. }));
  6517. //#endregion
  6518. //#region ../../node_modules/.pnpm/readdirp@3.6.0/node_modules/readdirp/index.js
  6519. var require_readdirp = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  6520. const fs$10 = __require("fs");
  6521. const { Readable: Readable$1 } = __require("stream");
  6522. const sysPath$3 = __require("path");
  6523. const { promisify: promisify$4 } = __require("util");
  6524. const picomatch$2 = __require("picomatch");
  6525. const readdir = promisify$4(fs$10.readdir);
  6526. const stat = promisify$4(fs$10.stat);
  6527. const lstat = promisify$4(fs$10.lstat);
  6528. const realpath = promisify$4(fs$10.realpath);
  6529. /**
  6530. * @typedef {Object} EntryInfo
  6531. * @property {String} path
  6532. * @property {String} fullPath
  6533. * @property {fs.Stats=} stats
  6534. * @property {fs.Dirent=} dirent
  6535. * @property {String} basename
  6536. */
  6537. const BANG = "!";
  6538. const RECURSIVE_ERROR_CODE = "READDIRP_RECURSIVE_ERROR";
  6539. const NORMAL_FLOW_ERRORS = new Set([
  6540. "ENOENT",
  6541. "EPERM",
  6542. "EACCES",
  6543. "ELOOP",
  6544. RECURSIVE_ERROR_CODE
  6545. ]);
  6546. const FILE_TYPE = "files";
  6547. const DIR_TYPE = "directories";
  6548. const FILE_DIR_TYPE = "files_directories";
  6549. const EVERYTHING_TYPE = "all";
  6550. const ALL_TYPES = [
  6551. FILE_TYPE,
  6552. DIR_TYPE,
  6553. FILE_DIR_TYPE,
  6554. EVERYTHING_TYPE
  6555. ];
  6556. const isNormalFlowError = (error) => NORMAL_FLOW_ERRORS.has(error.code);
  6557. const [maj, min] = process.versions.node.split(".").slice(0, 2).map((n) => Number.parseInt(n, 10));
  6558. const wantBigintFsStats = process.platform === "win32" && (maj > 10 || maj === 10 && min >= 5);
  6559. const normalizeFilter = (filter) => {
  6560. if (filter === void 0) return;
  6561. if (typeof filter === "function") return filter;
  6562. if (typeof filter === "string") {
  6563. const glob = picomatch$2(filter.trim());
  6564. return (entry) => glob(entry.basename);
  6565. }
  6566. if (Array.isArray(filter)) {
  6567. const positive = [];
  6568. const negative = [];
  6569. for (const item of filter) {
  6570. const trimmed = item.trim();
  6571. if (trimmed.charAt(0) === BANG) negative.push(picomatch$2(trimmed.slice(1)));
  6572. else positive.push(picomatch$2(trimmed));
  6573. }
  6574. if (negative.length > 0) {
  6575. if (positive.length > 0) return (entry) => positive.some((f) => f(entry.basename)) && !negative.some((f) => f(entry.basename));
  6576. return (entry) => !negative.some((f) => f(entry.basename));
  6577. }
  6578. return (entry) => positive.some((f) => f(entry.basename));
  6579. }
  6580. };
  6581. var ReaddirpStream = class ReaddirpStream extends Readable$1 {
  6582. static get defaultOptions() {
  6583. return {
  6584. root: ".",
  6585. fileFilter: (path) => true,
  6586. directoryFilter: (path) => true,
  6587. type: FILE_TYPE,
  6588. lstat: false,
  6589. depth: 2147483648,
  6590. alwaysStat: false
  6591. };
  6592. }
  6593. constructor(options = {}) {
  6594. super({
  6595. objectMode: true,
  6596. autoDestroy: true,
  6597. highWaterMark: options.highWaterMark || 4096
  6598. });
  6599. const opts = {
  6600. ...ReaddirpStream.defaultOptions,
  6601. ...options
  6602. };
  6603. const { root, type } = opts;
  6604. this._fileFilter = normalizeFilter(opts.fileFilter);
  6605. this._directoryFilter = normalizeFilter(opts.directoryFilter);
  6606. const statMethod = opts.lstat ? lstat : stat;
  6607. if (wantBigintFsStats) this._stat = (path) => statMethod(path, { bigint: true });
  6608. else this._stat = statMethod;
  6609. this._maxDepth = opts.depth;
  6610. this._wantsDir = [
  6611. DIR_TYPE,
  6612. FILE_DIR_TYPE,
  6613. EVERYTHING_TYPE
  6614. ].includes(type);
  6615. this._wantsFile = [
  6616. FILE_TYPE,
  6617. FILE_DIR_TYPE,
  6618. EVERYTHING_TYPE
  6619. ].includes(type);
  6620. this._wantsEverything = type === EVERYTHING_TYPE;
  6621. this._root = sysPath$3.resolve(root);
  6622. this._isDirent = "Dirent" in fs$10 && !opts.alwaysStat;
  6623. this._statsProp = this._isDirent ? "dirent" : "stats";
  6624. this._rdOptions = {
  6625. encoding: "utf8",
  6626. withFileTypes: this._isDirent
  6627. };
  6628. this.parents = [this._exploreDir(root, 1)];
  6629. this.reading = false;
  6630. this.parent = void 0;
  6631. }
  6632. async _read(batch) {
  6633. if (this.reading) return;
  6634. this.reading = true;
  6635. try {
  6636. while (!this.destroyed && batch > 0) {
  6637. const { path, depth, files = [] } = this.parent || {};
  6638. if (files.length > 0) {
  6639. const slice = files.splice(0, batch).map((dirent) => this._formatEntry(dirent, path));
  6640. for (const entry of await Promise.all(slice)) {
  6641. if (this.destroyed) return;
  6642. const entryType = await this._getEntryType(entry);
  6643. if (entryType === "directory" && this._directoryFilter(entry)) {
  6644. if (depth <= this._maxDepth) this.parents.push(this._exploreDir(entry.fullPath, depth + 1));
  6645. if (this._wantsDir) {
  6646. this.push(entry);
  6647. batch--;
  6648. }
  6649. } else if ((entryType === "file" || this._includeAsFile(entry)) && this._fileFilter(entry)) {
  6650. if (this._wantsFile) {
  6651. this.push(entry);
  6652. batch--;
  6653. }
  6654. }
  6655. }
  6656. } else {
  6657. const parent = this.parents.pop();
  6658. if (!parent) {
  6659. this.push(null);
  6660. break;
  6661. }
  6662. this.parent = await parent;
  6663. if (this.destroyed) return;
  6664. }
  6665. }
  6666. } catch (error) {
  6667. this.destroy(error);
  6668. } finally {
  6669. this.reading = false;
  6670. }
  6671. }
  6672. async _exploreDir(path, depth) {
  6673. let files;
  6674. try {
  6675. files = await readdir(path, this._rdOptions);
  6676. } catch (error) {
  6677. this._onError(error);
  6678. }
  6679. return {
  6680. files,
  6681. depth,
  6682. path
  6683. };
  6684. }
  6685. async _formatEntry(dirent, path) {
  6686. let entry;
  6687. try {
  6688. const basename = this._isDirent ? dirent.name : dirent;
  6689. const fullPath = sysPath$3.resolve(sysPath$3.join(path, basename));
  6690. entry = {
  6691. path: sysPath$3.relative(this._root, fullPath),
  6692. fullPath,
  6693. basename
  6694. };
  6695. entry[this._statsProp] = this._isDirent ? dirent : await this._stat(fullPath);
  6696. } catch (err) {
  6697. this._onError(err);
  6698. }
  6699. return entry;
  6700. }
  6701. _onError(err) {
  6702. if (isNormalFlowError(err) && !this.destroyed) this.emit("warn", err);
  6703. else this.destroy(err);
  6704. }
  6705. async _getEntryType(entry) {
  6706. const stats = entry && entry[this._statsProp];
  6707. if (!stats) return;
  6708. if (stats.isFile()) return "file";
  6709. if (stats.isDirectory()) return "directory";
  6710. if (stats && stats.isSymbolicLink()) {
  6711. const full = entry.fullPath;
  6712. try {
  6713. const entryRealPath = await realpath(full);
  6714. const entryRealPathStats = await lstat(entryRealPath);
  6715. if (entryRealPathStats.isFile()) return "file";
  6716. if (entryRealPathStats.isDirectory()) {
  6717. const len = entryRealPath.length;
  6718. if (full.startsWith(entryRealPath) && full.substr(len, 1) === sysPath$3.sep) {
  6719. const recursiveError = /* @__PURE__ */ new Error(`Circular symlink detected: "${full}" points to "${entryRealPath}"`);
  6720. recursiveError.code = RECURSIVE_ERROR_CODE;
  6721. return this._onError(recursiveError);
  6722. }
  6723. return "directory";
  6724. }
  6725. } catch (error) {
  6726. this._onError(error);
  6727. }
  6728. }
  6729. }
  6730. _includeAsFile(entry) {
  6731. const stats = entry && entry[this._statsProp];
  6732. return stats && this._wantsEverything && !stats.isDirectory();
  6733. }
  6734. };
  6735. /**
  6736. * @typedef {Object} ReaddirpArguments
  6737. * @property {Function=} fileFilter
  6738. * @property {Function=} directoryFilter
  6739. * @property {String=} type
  6740. * @property {Number=} depth
  6741. * @property {String=} root
  6742. * @property {Boolean=} lstat
  6743. * @property {Boolean=} bigint
  6744. */
  6745. /**
  6746. * Main function which ends up calling readdirRec and reads all files and directories in given root recursively.
  6747. * @param {String} root Root directory
  6748. * @param {ReaddirpArguments=} options Options to specify root (start directory), filters and recursion depth
  6749. */
  6750. const readdirp = (root, options = {}) => {
  6751. let type = options.entryType || options.type;
  6752. if (type === "both") type = FILE_DIR_TYPE;
  6753. if (type) options.type = type;
  6754. if (!root) throw new Error("readdirp: root argument is required. Usage: readdirp(root, options)");
  6755. else if (typeof root !== "string") throw new TypeError("readdirp: root argument must be a string. Usage: readdirp(root, options)");
  6756. else if (type && !ALL_TYPES.includes(type)) throw new Error(`readdirp: Invalid type passed. Use one of ${ALL_TYPES.join(", ")}`);
  6757. options.root = root;
  6758. return new ReaddirpStream(options);
  6759. };
  6760. const readdirpPromise = (root, options = {}) => {
  6761. return new Promise((resolve, reject) => {
  6762. const files = [];
  6763. readdirp(root, options).on("data", (entry) => files.push(entry)).on("end", () => resolve(files)).on("error", (error) => reject(error));
  6764. });
  6765. };
  6766. readdirp.promise = readdirpPromise;
  6767. readdirp.ReaddirpStream = ReaddirpStream;
  6768. readdirp.default = readdirp;
  6769. module.exports = readdirp;
  6770. }));
  6771. //#endregion
  6772. //#region ../../node_modules/.pnpm/normalize-path@3.0.0/node_modules/normalize-path/index.js
  6773. var require_normalize_path = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  6774. /*!
  6775. * normalize-path <https://github.com/jonschlinkert/normalize-path>
  6776. *
  6777. * Copyright (c) 2014-2018, Jon Schlinkert.
  6778. * Released under the MIT License.
  6779. */
  6780. module.exports = function(path, stripTrailing) {
  6781. if (typeof path !== "string") throw new TypeError("expected path to be a string");
  6782. if (path === "\\" || path === "/") return "/";
  6783. var len = path.length;
  6784. if (len <= 1) return path;
  6785. var prefix = "";
  6786. if (len > 4 && path[3] === "\\") {
  6787. var ch = path[2];
  6788. if ((ch === "?" || ch === ".") && path.slice(0, 2) === "\\\\") {
  6789. path = path.slice(2);
  6790. prefix = "//";
  6791. }
  6792. }
  6793. var segs = path.split(/[/\\]+/);
  6794. if (stripTrailing !== false && segs[segs.length - 1] === "") segs.pop();
  6795. return prefix + segs.join("/");
  6796. };
  6797. }));
  6798. //#endregion
  6799. //#region ../../node_modules/.pnpm/anymatch@3.1.3/node_modules/anymatch/index.js
  6800. var require_anymatch = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  6801. Object.defineProperty(exports, "__esModule", { value: true });
  6802. const picomatch$1 = __require("picomatch");
  6803. const normalizePath = require_normalize_path();
  6804. /**
  6805. * @typedef {(testString: string) => boolean} AnymatchFn
  6806. * @typedef {string|RegExp|AnymatchFn} AnymatchPattern
  6807. * @typedef {AnymatchPattern|AnymatchPattern[]} AnymatchMatcher
  6808. */
  6809. const BANG = "!";
  6810. const DEFAULT_OPTIONS = { returnIndex: false };
  6811. const arrify = (item) => Array.isArray(item) ? item : [item];
  6812. /**
  6813. * @param {AnymatchPattern} matcher
  6814. * @param {object} options
  6815. * @returns {AnymatchFn}
  6816. */
  6817. const createPattern = (matcher, options) => {
  6818. if (typeof matcher === "function") return matcher;
  6819. if (typeof matcher === "string") {
  6820. const glob = picomatch$1(matcher, options);
  6821. return (string) => matcher === string || glob(string);
  6822. }
  6823. if (matcher instanceof RegExp) return (string) => matcher.test(string);
  6824. return (string) => false;
  6825. };
  6826. /**
  6827. * @param {Array<Function>} patterns
  6828. * @param {Array<Function>} negPatterns
  6829. * @param {String|Array} args
  6830. * @param {Boolean} returnIndex
  6831. * @returns {boolean|number}
  6832. */
  6833. const matchPatterns = (patterns, negPatterns, args, returnIndex) => {
  6834. const isList = Array.isArray(args);
  6835. const _path = isList ? args[0] : args;
  6836. if (!isList && typeof _path !== "string") throw new TypeError("anymatch: second argument must be a string: got " + Object.prototype.toString.call(_path));
  6837. const path = normalizePath(_path, false);
  6838. for (let index = 0; index < negPatterns.length; index++) {
  6839. const nglob = negPatterns[index];
  6840. if (nglob(path)) return returnIndex ? -1 : false;
  6841. }
  6842. const applied = isList && [path].concat(args.slice(1));
  6843. for (let index = 0; index < patterns.length; index++) {
  6844. const pattern = patterns[index];
  6845. if (isList ? pattern(...applied) : pattern(path)) return returnIndex ? index : true;
  6846. }
  6847. return returnIndex ? -1 : false;
  6848. };
  6849. /**
  6850. * @param {AnymatchMatcher} matchers
  6851. * @param {Array|string} testString
  6852. * @param {object} options
  6853. * @returns {boolean|number|Function}
  6854. */
  6855. const anymatch = (matchers, testString, options = DEFAULT_OPTIONS) => {
  6856. if (matchers == null) throw new TypeError("anymatch: specify first argument");
  6857. const opts = typeof options === "boolean" ? { returnIndex: options } : options;
  6858. const returnIndex = opts.returnIndex || false;
  6859. const mtchers = arrify(matchers);
  6860. const negatedGlobs = mtchers.filter((item) => typeof item === "string" && item.charAt(0) === BANG).map((item) => item.slice(1)).map((item) => picomatch$1(item, opts));
  6861. const patterns = mtchers.filter((item) => typeof item !== "string" || typeof item === "string" && item.charAt(0) !== BANG).map((matcher) => createPattern(matcher, opts));
  6862. if (testString == null) return (testString, ri = false) => {
  6863. return matchPatterns(patterns, negatedGlobs, testString, typeof ri === "boolean" ? ri : false);
  6864. };
  6865. return matchPatterns(patterns, negatedGlobs, testString, returnIndex);
  6866. };
  6867. anymatch.default = anymatch;
  6868. module.exports = anymatch;
  6869. }));
  6870. //#endregion
  6871. //#region ../../node_modules/.pnpm/is-extglob@2.1.1/node_modules/is-extglob/index.js
  6872. var require_is_extglob = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  6873. /*!
  6874. * is-extglob <https://github.com/jonschlinkert/is-extglob>
  6875. *
  6876. * Copyright (c) 2014-2016, Jon Schlinkert.
  6877. * Licensed under the MIT License.
  6878. */
  6879. module.exports = function isExtglob(str) {
  6880. if (typeof str !== "string" || str === "") return false;
  6881. var match;
  6882. while (match = /(\\).|([@?!+*]\(.*\))/g.exec(str)) {
  6883. if (match[2]) return true;
  6884. str = str.slice(match.index + match[0].length);
  6885. }
  6886. return false;
  6887. };
  6888. }));
  6889. //#endregion
  6890. //#region ../../node_modules/.pnpm/is-glob@4.0.3/node_modules/is-glob/index.js
  6891. var require_is_glob = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  6892. /*!
  6893. * is-glob <https://github.com/jonschlinkert/is-glob>
  6894. *
  6895. * Copyright (c) 2014-2017, Jon Schlinkert.
  6896. * Released under the MIT License.
  6897. */
  6898. var isExtglob = require_is_extglob();
  6899. var chars = {
  6900. "{": "}",
  6901. "(": ")",
  6902. "[": "]"
  6903. };
  6904. var strictCheck = function(str) {
  6905. if (str[0] === "!") return true;
  6906. var index = 0;
  6907. var pipeIndex = -2;
  6908. var closeSquareIndex = -2;
  6909. var closeCurlyIndex = -2;
  6910. var closeParenIndex = -2;
  6911. var backSlashIndex = -2;
  6912. while (index < str.length) {
  6913. if (str[index] === "*") return true;
  6914. if (str[index + 1] === "?" && /[\].+)]/.test(str[index])) return true;
  6915. if (closeSquareIndex !== -1 && str[index] === "[" && str[index + 1] !== "]") {
  6916. if (closeSquareIndex < index) closeSquareIndex = str.indexOf("]", index);
  6917. if (closeSquareIndex > index) {
  6918. if (backSlashIndex === -1 || backSlashIndex > closeSquareIndex) return true;
  6919. backSlashIndex = str.indexOf("\\", index);
  6920. if (backSlashIndex === -1 || backSlashIndex > closeSquareIndex) return true;
  6921. }
  6922. }
  6923. if (closeCurlyIndex !== -1 && str[index] === "{" && str[index + 1] !== "}") {
  6924. closeCurlyIndex = str.indexOf("}", index);
  6925. if (closeCurlyIndex > index) {
  6926. backSlashIndex = str.indexOf("\\", index);
  6927. if (backSlashIndex === -1 || backSlashIndex > closeCurlyIndex) return true;
  6928. }
  6929. }
  6930. if (closeParenIndex !== -1 && str[index] === "(" && str[index + 1] === "?" && /[:!=]/.test(str[index + 2]) && str[index + 3] !== ")") {
  6931. closeParenIndex = str.indexOf(")", index);
  6932. if (closeParenIndex > index) {
  6933. backSlashIndex = str.indexOf("\\", index);
  6934. if (backSlashIndex === -1 || backSlashIndex > closeParenIndex) return true;
  6935. }
  6936. }
  6937. if (pipeIndex !== -1 && str[index] === "(" && str[index + 1] !== "|") {
  6938. if (pipeIndex < index) pipeIndex = str.indexOf("|", index);
  6939. if (pipeIndex !== -1 && str[pipeIndex + 1] !== ")") {
  6940. closeParenIndex = str.indexOf(")", pipeIndex);
  6941. if (closeParenIndex > pipeIndex) {
  6942. backSlashIndex = str.indexOf("\\", pipeIndex);
  6943. if (backSlashIndex === -1 || backSlashIndex > closeParenIndex) return true;
  6944. }
  6945. }
  6946. }
  6947. if (str[index] === "\\") {
  6948. var open = str[index + 1];
  6949. index += 2;
  6950. var close = chars[open];
  6951. if (close) {
  6952. var n = str.indexOf(close, index);
  6953. if (n !== -1) index = n + 1;
  6954. }
  6955. if (str[index] === "!") return true;
  6956. } else index++;
  6957. }
  6958. return false;
  6959. };
  6960. var relaxedCheck = function(str) {
  6961. if (str[0] === "!") return true;
  6962. var index = 0;
  6963. while (index < str.length) {
  6964. if (/[*?{}()[\]]/.test(str[index])) return true;
  6965. if (str[index] === "\\") {
  6966. var open = str[index + 1];
  6967. index += 2;
  6968. var close = chars[open];
  6969. if (close) {
  6970. var n = str.indexOf(close, index);
  6971. if (n !== -1) index = n + 1;
  6972. }
  6973. if (str[index] === "!") return true;
  6974. } else index++;
  6975. }
  6976. return false;
  6977. };
  6978. module.exports = function isGlob(str, options) {
  6979. if (typeof str !== "string" || str === "") return false;
  6980. if (isExtglob(str)) return true;
  6981. var check = strictCheck;
  6982. if (options && options.strict === false) check = relaxedCheck;
  6983. return check(str);
  6984. };
  6985. }));
  6986. //#endregion
  6987. //#region ../../node_modules/.pnpm/glob-parent@5.1.2/node_modules/glob-parent/index.js
  6988. var require_glob_parent = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  6989. var isGlob = require_is_glob();
  6990. var pathPosixDirname = __require("path").posix.dirname;
  6991. var isWin32 = __require("os").platform() === "win32";
  6992. var slash = "/";
  6993. var backslash = /\\/g;
  6994. var enclosure = /[\{\[].*[\}\]]$/;
  6995. var globby = /(^|[^\\])([\{\[]|\([^\)]+$)/;
  6996. var escaped = /\\([\!\*\?\|\[\]\(\)\{\}])/g;
  6997. /**
  6998. * @param {string} str
  6999. * @param {Object} opts
  7000. * @param {boolean} [opts.flipBackslashes=true]
  7001. * @returns {string}
  7002. */
  7003. module.exports = function globParent(str, opts) {
  7004. if (Object.assign({ flipBackslashes: true }, opts).flipBackslashes && isWin32 && str.indexOf(slash) < 0) str = str.replace(backslash, slash);
  7005. if (enclosure.test(str)) str += slash;
  7006. str += "a";
  7007. do
  7008. str = pathPosixDirname(str);
  7009. while (isGlob(str) || globby.test(str));
  7010. return str.replace(escaped, "$1");
  7011. };
  7012. }));
  7013. //#endregion
  7014. //#region ../../node_modules/.pnpm/braces@3.0.3/node_modules/braces/lib/utils.js
  7015. var require_utils = /* @__PURE__ */ __commonJSMin(((exports) => {
  7016. exports.isInteger = (num) => {
  7017. if (typeof num === "number") return Number.isInteger(num);
  7018. if (typeof num === "string" && num.trim() !== "") return Number.isInteger(Number(num));
  7019. return false;
  7020. };
  7021. /**
  7022. * Find a node of the given type
  7023. */
  7024. exports.find = (node, type) => node.nodes.find((node) => node.type === type);
  7025. /**
  7026. * Find a node of the given type
  7027. */
  7028. exports.exceedsLimit = (min, max, step = 1, limit) => {
  7029. if (limit === false) return false;
  7030. if (!exports.isInteger(min) || !exports.isInteger(max)) return false;
  7031. return (Number(max) - Number(min)) / Number(step) >= limit;
  7032. };
  7033. /**
  7034. * Escape the given node with '\\' before node.value
  7035. */
  7036. exports.escapeNode = (block, n = 0, type) => {
  7037. const node = block.nodes[n];
  7038. if (!node) return;
  7039. if (type && node.type === type || node.type === "open" || node.type === "close") {
  7040. if (node.escaped !== true) {
  7041. node.value = "\\" + node.value;
  7042. node.escaped = true;
  7043. }
  7044. }
  7045. };
  7046. /**
  7047. * Returns true if the given brace node should be enclosed in literal braces
  7048. */
  7049. exports.encloseBrace = (node) => {
  7050. if (node.type !== "brace") return false;
  7051. if (node.commas >> 0 + node.ranges >> 0 === 0) {
  7052. node.invalid = true;
  7053. return true;
  7054. }
  7055. return false;
  7056. };
  7057. /**
  7058. * Returns true if a brace node is invalid.
  7059. */
  7060. exports.isInvalidBrace = (block) => {
  7061. if (block.type !== "brace") return false;
  7062. if (block.invalid === true || block.dollar) return true;
  7063. if (block.commas >> 0 + block.ranges >> 0 === 0) {
  7064. block.invalid = true;
  7065. return true;
  7066. }
  7067. if (block.open !== true || block.close !== true) {
  7068. block.invalid = true;
  7069. return true;
  7070. }
  7071. return false;
  7072. };
  7073. /**
  7074. * Returns true if a node is an open or close node
  7075. */
  7076. exports.isOpenOrClose = (node) => {
  7077. if (node.type === "open" || node.type === "close") return true;
  7078. return node.open === true || node.close === true;
  7079. };
  7080. /**
  7081. * Reduce an array of text nodes.
  7082. */
  7083. exports.reduce = (nodes) => nodes.reduce((acc, node) => {
  7084. if (node.type === "text") acc.push(node.value);
  7085. if (node.type === "range") node.type = "text";
  7086. return acc;
  7087. }, []);
  7088. /**
  7089. * Flatten an array
  7090. */
  7091. exports.flatten = (...args) => {
  7092. const result = [];
  7093. const flat = (arr) => {
  7094. for (let i = 0; i < arr.length; i++) {
  7095. const ele = arr[i];
  7096. if (Array.isArray(ele)) {
  7097. flat(ele);
  7098. continue;
  7099. }
  7100. if (ele !== void 0) result.push(ele);
  7101. }
  7102. return result;
  7103. };
  7104. flat(args);
  7105. return result;
  7106. };
  7107. }));
  7108. //#endregion
  7109. //#region ../../node_modules/.pnpm/braces@3.0.3/node_modules/braces/lib/stringify.js
  7110. var require_stringify = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  7111. const utils = require_utils();
  7112. module.exports = (ast, options = {}) => {
  7113. const stringify = (node, parent = {}) => {
  7114. const invalidBlock = options.escapeInvalid && utils.isInvalidBrace(parent);
  7115. const invalidNode = node.invalid === true && options.escapeInvalid === true;
  7116. let output = "";
  7117. if (node.value) {
  7118. if ((invalidBlock || invalidNode) && utils.isOpenOrClose(node)) return "\\" + node.value;
  7119. return node.value;
  7120. }
  7121. if (node.value) return node.value;
  7122. if (node.nodes) for (const child of node.nodes) output += stringify(child);
  7123. return output;
  7124. };
  7125. return stringify(ast);
  7126. };
  7127. }));
  7128. //#endregion
  7129. //#region ../../node_modules/.pnpm/is-number@7.0.0/node_modules/is-number/index.js
  7130. /*!
  7131. * is-number <https://github.com/jonschlinkert/is-number>
  7132. *
  7133. * Copyright (c) 2014-present, Jon Schlinkert.
  7134. * Released under the MIT License.
  7135. */
  7136. var require_is_number = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  7137. module.exports = function(num) {
  7138. if (typeof num === "number") return num - num === 0;
  7139. if (typeof num === "string" && num.trim() !== "") return Number.isFinite ? Number.isFinite(+num) : isFinite(+num);
  7140. return false;
  7141. };
  7142. }));
  7143. //#endregion
  7144. //#region ../../node_modules/.pnpm/to-regex-range@5.0.1/node_modules/to-regex-range/index.js
  7145. /*!
  7146. * to-regex-range <https://github.com/micromatch/to-regex-range>
  7147. *
  7148. * Copyright (c) 2015-present, Jon Schlinkert.
  7149. * Released under the MIT License.
  7150. */
  7151. var require_to_regex_range = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  7152. const isNumber = require_is_number();
  7153. const toRegexRange = (min, max, options) => {
  7154. if (isNumber(min) === false) throw new TypeError("toRegexRange: expected the first argument to be a number");
  7155. if (max === void 0 || min === max) return String(min);
  7156. if (isNumber(max) === false) throw new TypeError("toRegexRange: expected the second argument to be a number.");
  7157. let opts = {
  7158. relaxZeros: true,
  7159. ...options
  7160. };
  7161. if (typeof opts.strictZeros === "boolean") opts.relaxZeros = opts.strictZeros === false;
  7162. let relax = String(opts.relaxZeros);
  7163. let shorthand = String(opts.shorthand);
  7164. let capture = String(opts.capture);
  7165. let wrap = String(opts.wrap);
  7166. let cacheKey = min + ":" + max + "=" + relax + shorthand + capture + wrap;
  7167. if (toRegexRange.cache.hasOwnProperty(cacheKey)) return toRegexRange.cache[cacheKey].result;
  7168. let a = Math.min(min, max);
  7169. let b = Math.max(min, max);
  7170. if (Math.abs(a - b) === 1) {
  7171. let result = min + "|" + max;
  7172. if (opts.capture) return `(${result})`;
  7173. if (opts.wrap === false) return result;
  7174. return `(?:${result})`;
  7175. }
  7176. let isPadded = hasPadding(min) || hasPadding(max);
  7177. let state = {
  7178. min,
  7179. max,
  7180. a,
  7181. b
  7182. };
  7183. let positives = [];
  7184. let negatives = [];
  7185. if (isPadded) {
  7186. state.isPadded = isPadded;
  7187. state.maxLen = String(state.max).length;
  7188. }
  7189. if (a < 0) {
  7190. negatives = splitToPatterns(b < 0 ? Math.abs(b) : 1, Math.abs(a), state, opts);
  7191. a = state.a = 0;
  7192. }
  7193. if (b >= 0) positives = splitToPatterns(a, b, state, opts);
  7194. state.negatives = negatives;
  7195. state.positives = positives;
  7196. state.result = collatePatterns(negatives, positives, opts);
  7197. if (opts.capture === true) state.result = `(${state.result})`;
  7198. else if (opts.wrap !== false && positives.length + negatives.length > 1) state.result = `(?:${state.result})`;
  7199. toRegexRange.cache[cacheKey] = state;
  7200. return state.result;
  7201. };
  7202. function collatePatterns(neg, pos, options) {
  7203. let onlyNegative = filterPatterns(neg, pos, "-", false, options) || [];
  7204. let onlyPositive = filterPatterns(pos, neg, "", false, options) || [];
  7205. let intersected = filterPatterns(neg, pos, "-?", true, options) || [];
  7206. return onlyNegative.concat(intersected).concat(onlyPositive).join("|");
  7207. }
  7208. function splitToRanges(min, max) {
  7209. let nines = 1;
  7210. let zeros = 1;
  7211. let stop = countNines(min, nines);
  7212. let stops = new Set([max]);
  7213. while (min <= stop && stop <= max) {
  7214. stops.add(stop);
  7215. nines += 1;
  7216. stop = countNines(min, nines);
  7217. }
  7218. stop = countZeros(max + 1, zeros) - 1;
  7219. while (min < stop && stop <= max) {
  7220. stops.add(stop);
  7221. zeros += 1;
  7222. stop = countZeros(max + 1, zeros) - 1;
  7223. }
  7224. stops = [...stops];
  7225. stops.sort(compare);
  7226. return stops;
  7227. }
  7228. /**
  7229. * Convert a range to a regex pattern
  7230. * @param {Number} `start`
  7231. * @param {Number} `stop`
  7232. * @return {String}
  7233. */
  7234. function rangeToPattern(start, stop, options) {
  7235. if (start === stop) return {
  7236. pattern: start,
  7237. count: [],
  7238. digits: 0
  7239. };
  7240. let zipped = zip(start, stop);
  7241. let digits = zipped.length;
  7242. let pattern = "";
  7243. let count = 0;
  7244. for (let i = 0; i < digits; i++) {
  7245. let [startDigit, stopDigit] = zipped[i];
  7246. if (startDigit === stopDigit) pattern += startDigit;
  7247. else if (startDigit !== "0" || stopDigit !== "9") pattern += toCharacterClass(startDigit, stopDigit, options);
  7248. else count++;
  7249. }
  7250. if (count) pattern += options.shorthand === true ? "\\d" : "[0-9]";
  7251. return {
  7252. pattern,
  7253. count: [count],
  7254. digits
  7255. };
  7256. }
  7257. function splitToPatterns(min, max, tok, options) {
  7258. let ranges = splitToRanges(min, max);
  7259. let tokens = [];
  7260. let start = min;
  7261. let prev;
  7262. for (let i = 0; i < ranges.length; i++) {
  7263. let max = ranges[i];
  7264. let obj = rangeToPattern(String(start), String(max), options);
  7265. let zeros = "";
  7266. if (!tok.isPadded && prev && prev.pattern === obj.pattern) {
  7267. if (prev.count.length > 1) prev.count.pop();
  7268. prev.count.push(obj.count[0]);
  7269. prev.string = prev.pattern + toQuantifier(prev.count);
  7270. start = max + 1;
  7271. continue;
  7272. }
  7273. if (tok.isPadded) zeros = padZeros(max, tok, options);
  7274. obj.string = zeros + obj.pattern + toQuantifier(obj.count);
  7275. tokens.push(obj);
  7276. start = max + 1;
  7277. prev = obj;
  7278. }
  7279. return tokens;
  7280. }
  7281. function filterPatterns(arr, comparison, prefix, intersection, options) {
  7282. let result = [];
  7283. for (let ele of arr) {
  7284. let { string } = ele;
  7285. if (!intersection && !contains(comparison, "string", string)) result.push(prefix + string);
  7286. if (intersection && contains(comparison, "string", string)) result.push(prefix + string);
  7287. }
  7288. return result;
  7289. }
  7290. /**
  7291. * Zip strings
  7292. */
  7293. function zip(a, b) {
  7294. let arr = [];
  7295. for (let i = 0; i < a.length; i++) arr.push([a[i], b[i]]);
  7296. return arr;
  7297. }
  7298. function compare(a, b) {
  7299. return a > b ? 1 : b > a ? -1 : 0;
  7300. }
  7301. function contains(arr, key, val) {
  7302. return arr.some((ele) => ele[key] === val);
  7303. }
  7304. function countNines(min, len) {
  7305. return Number(String(min).slice(0, -len) + "9".repeat(len));
  7306. }
  7307. function countZeros(integer, zeros) {
  7308. return integer - integer % Math.pow(10, zeros);
  7309. }
  7310. function toQuantifier(digits) {
  7311. let [start = 0, stop = ""] = digits;
  7312. if (stop || start > 1) return `{${start + (stop ? "," + stop : "")}}`;
  7313. return "";
  7314. }
  7315. function toCharacterClass(a, b, options) {
  7316. return `[${a}${b - a === 1 ? "" : "-"}${b}]`;
  7317. }
  7318. function hasPadding(str) {
  7319. return /^-?(0+)\d/.test(str);
  7320. }
  7321. function padZeros(value, tok, options) {
  7322. if (!tok.isPadded) return value;
  7323. let diff = Math.abs(tok.maxLen - String(value).length);
  7324. let relax = options.relaxZeros !== false;
  7325. switch (diff) {
  7326. case 0: return "";
  7327. case 1: return relax ? "0?" : "0";
  7328. case 2: return relax ? "0{0,2}" : "00";
  7329. default: return relax ? `0{0,${diff}}` : `0{${diff}}`;
  7330. }
  7331. }
  7332. /**
  7333. * Cache
  7334. */
  7335. toRegexRange.cache = {};
  7336. toRegexRange.clearCache = () => toRegexRange.cache = {};
  7337. /**
  7338. * Expose `toRegexRange`
  7339. */
  7340. module.exports = toRegexRange;
  7341. }));
  7342. //#endregion
  7343. //#region ../../node_modules/.pnpm/fill-range@7.1.1/node_modules/fill-range/index.js
  7344. /*!
  7345. * fill-range <https://github.com/jonschlinkert/fill-range>
  7346. *
  7347. * Copyright (c) 2014-present, Jon Schlinkert.
  7348. * Licensed under the MIT License.
  7349. */
  7350. var require_fill_range = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  7351. const util = __require("util");
  7352. const toRegexRange = require_to_regex_range();
  7353. const isObject = (val) => val !== null && typeof val === "object" && !Array.isArray(val);
  7354. const transform = (toNumber) => {
  7355. return (value) => toNumber === true ? Number(value) : String(value);
  7356. };
  7357. const isValidValue = (value) => {
  7358. return typeof value === "number" || typeof value === "string" && value !== "";
  7359. };
  7360. const isNumber = (num) => Number.isInteger(+num);
  7361. const zeros = (input) => {
  7362. let value = `${input}`;
  7363. let index = -1;
  7364. if (value[0] === "-") value = value.slice(1);
  7365. if (value === "0") return false;
  7366. while (value[++index] === "0");
  7367. return index > 0;
  7368. };
  7369. const stringify = (start, end, options) => {
  7370. if (typeof start === "string" || typeof end === "string") return true;
  7371. return options.stringify === true;
  7372. };
  7373. const pad = (input, maxLength, toNumber) => {
  7374. if (maxLength > 0) {
  7375. let dash = input[0] === "-" ? "-" : "";
  7376. if (dash) input = input.slice(1);
  7377. input = dash + input.padStart(dash ? maxLength - 1 : maxLength, "0");
  7378. }
  7379. if (toNumber === false) return String(input);
  7380. return input;
  7381. };
  7382. const toMaxLen = (input, maxLength) => {
  7383. let negative = input[0] === "-" ? "-" : "";
  7384. if (negative) {
  7385. input = input.slice(1);
  7386. maxLength--;
  7387. }
  7388. while (input.length < maxLength) input = "0" + input;
  7389. return negative ? "-" + input : input;
  7390. };
  7391. const toSequence = (parts, options, maxLen) => {
  7392. parts.negatives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
  7393. parts.positives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
  7394. let prefix = options.capture ? "" : "?:";
  7395. let positives = "";
  7396. let negatives = "";
  7397. let result;
  7398. if (parts.positives.length) positives = parts.positives.map((v) => toMaxLen(String(v), maxLen)).join("|");
  7399. if (parts.negatives.length) negatives = `-(${prefix}${parts.negatives.map((v) => toMaxLen(String(v), maxLen)).join("|")})`;
  7400. if (positives && negatives) result = `${positives}|${negatives}`;
  7401. else result = positives || negatives;
  7402. if (options.wrap) return `(${prefix}${result})`;
  7403. return result;
  7404. };
  7405. const toRange = (a, b, isNumbers, options) => {
  7406. if (isNumbers) return toRegexRange(a, b, {
  7407. wrap: false,
  7408. ...options
  7409. });
  7410. let start = String.fromCharCode(a);
  7411. if (a === b) return start;
  7412. return `[${start}-${String.fromCharCode(b)}]`;
  7413. };
  7414. const toRegex = (start, end, options) => {
  7415. if (Array.isArray(start)) return options.wrap === true ? `(${options.capture ? "" : "?:"}${start.join("|")})` : start.join("|");
  7416. return toRegexRange(start, end, options);
  7417. };
  7418. const rangeError = (...args) => {
  7419. return /* @__PURE__ */ new RangeError("Invalid range arguments: " + util.inspect(...args));
  7420. };
  7421. const invalidRange = (start, end, options) => {
  7422. if (options.strictRanges === true) throw rangeError([start, end]);
  7423. return [];
  7424. };
  7425. const invalidStep = (step, options) => {
  7426. if (options.strictRanges === true) throw new TypeError(`Expected step "${step}" to be a number`);
  7427. return [];
  7428. };
  7429. const fillNumbers = (start, end, step = 1, options = {}) => {
  7430. let a = Number(start);
  7431. let b = Number(end);
  7432. if (!Number.isInteger(a) || !Number.isInteger(b)) {
  7433. if (options.strictRanges === true) throw rangeError([start, end]);
  7434. return [];
  7435. }
  7436. if (a === 0) a = 0;
  7437. if (b === 0) b = 0;
  7438. let descending = a > b;
  7439. let startString = String(start);
  7440. let endString = String(end);
  7441. let stepString = String(step);
  7442. step = Math.max(Math.abs(step), 1);
  7443. let padded = zeros(startString) || zeros(endString) || zeros(stepString);
  7444. let maxLen = padded ? Math.max(startString.length, endString.length, stepString.length) : 0;
  7445. let toNumber = padded === false && stringify(start, end, options) === false;
  7446. let format = options.transform || transform(toNumber);
  7447. if (options.toRegex && step === 1) return toRange(toMaxLen(start, maxLen), toMaxLen(end, maxLen), true, options);
  7448. let parts = {
  7449. negatives: [],
  7450. positives: []
  7451. };
  7452. let push = (num) => parts[num < 0 ? "negatives" : "positives"].push(Math.abs(num));
  7453. let range = [];
  7454. let index = 0;
  7455. while (descending ? a >= b : a <= b) {
  7456. if (options.toRegex === true && step > 1) push(a);
  7457. else range.push(pad(format(a, index), maxLen, toNumber));
  7458. a = descending ? a - step : a + step;
  7459. index++;
  7460. }
  7461. if (options.toRegex === true) return step > 1 ? toSequence(parts, options, maxLen) : toRegex(range, null, {
  7462. wrap: false,
  7463. ...options
  7464. });
  7465. return range;
  7466. };
  7467. const fillLetters = (start, end, step = 1, options = {}) => {
  7468. if (!isNumber(start) && start.length > 1 || !isNumber(end) && end.length > 1) return invalidRange(start, end, options);
  7469. let format = options.transform || ((val) => String.fromCharCode(val));
  7470. let a = `${start}`.charCodeAt(0);
  7471. let b = `${end}`.charCodeAt(0);
  7472. let descending = a > b;
  7473. let min = Math.min(a, b);
  7474. let max = Math.max(a, b);
  7475. if (options.toRegex && step === 1) return toRange(min, max, false, options);
  7476. let range = [];
  7477. let index = 0;
  7478. while (descending ? a >= b : a <= b) {
  7479. range.push(format(a, index));
  7480. a = descending ? a - step : a + step;
  7481. index++;
  7482. }
  7483. if (options.toRegex === true) return toRegex(range, null, {
  7484. wrap: false,
  7485. options
  7486. });
  7487. return range;
  7488. };
  7489. const fill = (start, end, step, options = {}) => {
  7490. if (end == null && isValidValue(start)) return [start];
  7491. if (!isValidValue(start) || !isValidValue(end)) return invalidRange(start, end, options);
  7492. if (typeof step === "function") return fill(start, end, 1, { transform: step });
  7493. if (isObject(step)) return fill(start, end, 0, step);
  7494. let opts = { ...options };
  7495. if (opts.capture === true) opts.wrap = true;
  7496. step = step || opts.step || 1;
  7497. if (!isNumber(step)) {
  7498. if (step != null && !isObject(step)) return invalidStep(step, opts);
  7499. return fill(start, end, 1, step);
  7500. }
  7501. if (isNumber(start) && isNumber(end)) return fillNumbers(start, end, step, opts);
  7502. return fillLetters(start, end, Math.max(Math.abs(step), 1), opts);
  7503. };
  7504. module.exports = fill;
  7505. }));
  7506. //#endregion
  7507. //#region ../../node_modules/.pnpm/braces@3.0.3/node_modules/braces/lib/compile.js
  7508. var require_compile = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  7509. const fill = require_fill_range();
  7510. const utils = require_utils();
  7511. const compile = (ast, options = {}) => {
  7512. const walk = (node, parent = {}) => {
  7513. const invalid = utils.isInvalidBrace(parent) === true || (node.invalid === true && options.escapeInvalid === true) === true;
  7514. const prefix = options.escapeInvalid === true ? "\\" : "";
  7515. let output = "";
  7516. if (node.isOpen === true) return prefix + node.value;
  7517. if (node.isClose === true) {
  7518. console.log("node.isClose", prefix, node.value);
  7519. return prefix + node.value;
  7520. }
  7521. if (node.type === "open") return invalid ? prefix + node.value : "(";
  7522. if (node.type === "close") return invalid ? prefix + node.value : ")";
  7523. if (node.type === "comma") return node.prev.type === "comma" ? "" : invalid ? node.value : "|";
  7524. if (node.value) return node.value;
  7525. if (node.nodes && node.ranges > 0) {
  7526. const args = utils.reduce(node.nodes);
  7527. const range = fill(...args, {
  7528. ...options,
  7529. wrap: false,
  7530. toRegex: true,
  7531. strictZeros: true
  7532. });
  7533. if (range.length !== 0) return args.length > 1 && range.length > 1 ? `(${range})` : range;
  7534. }
  7535. if (node.nodes) for (const child of node.nodes) output += walk(child, node);
  7536. return output;
  7537. };
  7538. return walk(ast);
  7539. };
  7540. module.exports = compile;
  7541. }));
  7542. //#endregion
  7543. //#region ../../node_modules/.pnpm/braces@3.0.3/node_modules/braces/lib/expand.js
  7544. var require_expand = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  7545. const fill = require_fill_range();
  7546. const stringify = require_stringify();
  7547. const utils = require_utils();
  7548. const append = (queue = "", stash = "", enclose = false) => {
  7549. const result = [];
  7550. queue = [].concat(queue);
  7551. stash = [].concat(stash);
  7552. if (!stash.length) return queue;
  7553. if (!queue.length) return enclose ? utils.flatten(stash).map((ele) => `{${ele}}`) : stash;
  7554. for (const item of queue) if (Array.isArray(item)) for (const value of item) result.push(append(value, stash, enclose));
  7555. else for (let ele of stash) {
  7556. if (enclose === true && typeof ele === "string") ele = `{${ele}}`;
  7557. result.push(Array.isArray(ele) ? append(item, ele, enclose) : item + ele);
  7558. }
  7559. return utils.flatten(result);
  7560. };
  7561. const expand = (ast, options = {}) => {
  7562. const rangeLimit = options.rangeLimit === void 0 ? 1e3 : options.rangeLimit;
  7563. const walk = (node, parent = {}) => {
  7564. node.queue = [];
  7565. let p = parent;
  7566. let q = parent.queue;
  7567. while (p.type !== "brace" && p.type !== "root" && p.parent) {
  7568. p = p.parent;
  7569. q = p.queue;
  7570. }
  7571. if (node.invalid || node.dollar) {
  7572. q.push(append(q.pop(), stringify(node, options)));
  7573. return;
  7574. }
  7575. if (node.type === "brace" && node.invalid !== true && node.nodes.length === 2) {
  7576. q.push(append(q.pop(), ["{}"]));
  7577. return;
  7578. }
  7579. if (node.nodes && node.ranges > 0) {
  7580. const args = utils.reduce(node.nodes);
  7581. if (utils.exceedsLimit(...args, options.step, rangeLimit)) throw new RangeError("expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.");
  7582. let range = fill(...args, options);
  7583. if (range.length === 0) range = stringify(node, options);
  7584. q.push(append(q.pop(), range));
  7585. node.nodes = [];
  7586. return;
  7587. }
  7588. const enclose = utils.encloseBrace(node);
  7589. let queue = node.queue;
  7590. let block = node;
  7591. while (block.type !== "brace" && block.type !== "root" && block.parent) {
  7592. block = block.parent;
  7593. queue = block.queue;
  7594. }
  7595. for (let i = 0; i < node.nodes.length; i++) {
  7596. const child = node.nodes[i];
  7597. if (child.type === "comma" && node.type === "brace") {
  7598. if (i === 1) queue.push("");
  7599. queue.push("");
  7600. continue;
  7601. }
  7602. if (child.type === "close") {
  7603. q.push(append(q.pop(), queue, enclose));
  7604. continue;
  7605. }
  7606. if (child.value && child.type !== "open") {
  7607. queue.push(append(queue.pop(), child.value));
  7608. continue;
  7609. }
  7610. if (child.nodes) walk(child, node);
  7611. }
  7612. return queue;
  7613. };
  7614. return utils.flatten(walk(ast));
  7615. };
  7616. module.exports = expand;
  7617. }));
  7618. //#endregion
  7619. //#region ../../node_modules/.pnpm/braces@3.0.3/node_modules/braces/lib/constants.js
  7620. var require_constants$2 = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  7621. module.exports = {
  7622. MAX_LENGTH: 1e4,
  7623. CHAR_0: "0",
  7624. CHAR_9: "9",
  7625. CHAR_UPPERCASE_A: "A",
  7626. CHAR_LOWERCASE_A: "a",
  7627. CHAR_UPPERCASE_Z: "Z",
  7628. CHAR_LOWERCASE_Z: "z",
  7629. CHAR_LEFT_PARENTHESES: "(",
  7630. CHAR_RIGHT_PARENTHESES: ")",
  7631. CHAR_ASTERISK: "*",
  7632. CHAR_AMPERSAND: "&",
  7633. CHAR_AT: "@",
  7634. CHAR_BACKSLASH: "\\",
  7635. CHAR_BACKTICK: "`",
  7636. CHAR_CARRIAGE_RETURN: "\r",
  7637. CHAR_CIRCUMFLEX_ACCENT: "^",
  7638. CHAR_COLON: ":",
  7639. CHAR_COMMA: ",",
  7640. CHAR_DOLLAR: "$",
  7641. CHAR_DOT: ".",
  7642. CHAR_DOUBLE_QUOTE: "\"",
  7643. CHAR_EQUAL: "=",
  7644. CHAR_EXCLAMATION_MARK: "!",
  7645. CHAR_FORM_FEED: "\f",
  7646. CHAR_FORWARD_SLASH: "/",
  7647. CHAR_HASH: "#",
  7648. CHAR_HYPHEN_MINUS: "-",
  7649. CHAR_LEFT_ANGLE_BRACKET: "<",
  7650. CHAR_LEFT_CURLY_BRACE: "{",
  7651. CHAR_LEFT_SQUARE_BRACKET: "[",
  7652. CHAR_LINE_FEED: "\n",
  7653. CHAR_NO_BREAK_SPACE: "\xA0",
  7654. CHAR_PERCENT: "%",
  7655. CHAR_PLUS: "+",
  7656. CHAR_QUESTION_MARK: "?",
  7657. CHAR_RIGHT_ANGLE_BRACKET: ">",
  7658. CHAR_RIGHT_CURLY_BRACE: "}",
  7659. CHAR_RIGHT_SQUARE_BRACKET: "]",
  7660. CHAR_SEMICOLON: ";",
  7661. CHAR_SINGLE_QUOTE: "'",
  7662. CHAR_SPACE: " ",
  7663. CHAR_TAB: " ",
  7664. CHAR_UNDERSCORE: "_",
  7665. CHAR_VERTICAL_LINE: "|",
  7666. CHAR_ZERO_WIDTH_NOBREAK_SPACE: ""
  7667. };
  7668. }));
  7669. //#endregion
  7670. //#region ../../node_modules/.pnpm/braces@3.0.3/node_modules/braces/lib/parse.js
  7671. var require_parse$2 = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  7672. const stringify = require_stringify();
  7673. /**
  7674. * Constants
  7675. */
  7676. const { MAX_LENGTH, CHAR_BACKSLASH, CHAR_BACKTICK, CHAR_COMMA, CHAR_DOT, CHAR_LEFT_PARENTHESES, CHAR_RIGHT_PARENTHESES, CHAR_LEFT_CURLY_BRACE, CHAR_RIGHT_CURLY_BRACE, CHAR_LEFT_SQUARE_BRACKET, CHAR_RIGHT_SQUARE_BRACKET, CHAR_DOUBLE_QUOTE, CHAR_SINGLE_QUOTE, CHAR_NO_BREAK_SPACE, CHAR_ZERO_WIDTH_NOBREAK_SPACE } = require_constants$2();
  7677. /**
  7678. * parse
  7679. */
  7680. const parse = (input, options = {}) => {
  7681. if (typeof input !== "string") throw new TypeError("Expected a string");
  7682. const opts = options || {};
  7683. const max = typeof opts.maxLength === "number" ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
  7684. if (input.length > max) throw new SyntaxError(`Input length (${input.length}), exceeds max characters (${max})`);
  7685. const ast = {
  7686. type: "root",
  7687. input,
  7688. nodes: []
  7689. };
  7690. const stack = [ast];
  7691. let block = ast;
  7692. let prev = ast;
  7693. let brackets = 0;
  7694. const length = input.length;
  7695. let index = 0;
  7696. let depth = 0;
  7697. let value;
  7698. /**
  7699. * Helpers
  7700. */
  7701. const advance = () => input[index++];
  7702. const push = (node) => {
  7703. if (node.type === "text" && prev.type === "dot") prev.type = "text";
  7704. if (prev && prev.type === "text" && node.type === "text") {
  7705. prev.value += node.value;
  7706. return;
  7707. }
  7708. block.nodes.push(node);
  7709. node.parent = block;
  7710. node.prev = prev;
  7711. prev = node;
  7712. return node;
  7713. };
  7714. push({ type: "bos" });
  7715. while (index < length) {
  7716. block = stack[stack.length - 1];
  7717. value = advance();
  7718. /**
  7719. * Invalid chars
  7720. */
  7721. if (value === CHAR_ZERO_WIDTH_NOBREAK_SPACE || value === CHAR_NO_BREAK_SPACE) continue;
  7722. /**
  7723. * Escaped chars
  7724. */
  7725. if (value === CHAR_BACKSLASH) {
  7726. push({
  7727. type: "text",
  7728. value: (options.keepEscaping ? value : "") + advance()
  7729. });
  7730. continue;
  7731. }
  7732. /**
  7733. * Right square bracket (literal): ']'
  7734. */
  7735. if (value === CHAR_RIGHT_SQUARE_BRACKET) {
  7736. push({
  7737. type: "text",
  7738. value: "\\" + value
  7739. });
  7740. continue;
  7741. }
  7742. /**
  7743. * Left square bracket: '['
  7744. */
  7745. if (value === CHAR_LEFT_SQUARE_BRACKET) {
  7746. brackets++;
  7747. let next;
  7748. while (index < length && (next = advance())) {
  7749. value += next;
  7750. if (next === CHAR_LEFT_SQUARE_BRACKET) {
  7751. brackets++;
  7752. continue;
  7753. }
  7754. if (next === CHAR_BACKSLASH) {
  7755. value += advance();
  7756. continue;
  7757. }
  7758. if (next === CHAR_RIGHT_SQUARE_BRACKET) {
  7759. brackets--;
  7760. if (brackets === 0) break;
  7761. }
  7762. }
  7763. push({
  7764. type: "text",
  7765. value
  7766. });
  7767. continue;
  7768. }
  7769. /**
  7770. * Parentheses
  7771. */
  7772. if (value === CHAR_LEFT_PARENTHESES) {
  7773. block = push({
  7774. type: "paren",
  7775. nodes: []
  7776. });
  7777. stack.push(block);
  7778. push({
  7779. type: "text",
  7780. value
  7781. });
  7782. continue;
  7783. }
  7784. if (value === CHAR_RIGHT_PARENTHESES) {
  7785. if (block.type !== "paren") {
  7786. push({
  7787. type: "text",
  7788. value
  7789. });
  7790. continue;
  7791. }
  7792. block = stack.pop();
  7793. push({
  7794. type: "text",
  7795. value
  7796. });
  7797. block = stack[stack.length - 1];
  7798. continue;
  7799. }
  7800. /**
  7801. * Quotes: '|"|`
  7802. */
  7803. if (value === CHAR_DOUBLE_QUOTE || value === CHAR_SINGLE_QUOTE || value === CHAR_BACKTICK) {
  7804. const open = value;
  7805. let next;
  7806. if (options.keepQuotes !== true) value = "";
  7807. while (index < length && (next = advance())) {
  7808. if (next === CHAR_BACKSLASH) {
  7809. value += next + advance();
  7810. continue;
  7811. }
  7812. if (next === open) {
  7813. if (options.keepQuotes === true) value += next;
  7814. break;
  7815. }
  7816. value += next;
  7817. }
  7818. push({
  7819. type: "text",
  7820. value
  7821. });
  7822. continue;
  7823. }
  7824. /**
  7825. * Left curly brace: '{'
  7826. */
  7827. if (value === CHAR_LEFT_CURLY_BRACE) {
  7828. depth++;
  7829. block = push({
  7830. type: "brace",
  7831. open: true,
  7832. close: false,
  7833. dollar: prev.value && prev.value.slice(-1) === "$" || block.dollar === true,
  7834. depth,
  7835. commas: 0,
  7836. ranges: 0,
  7837. nodes: []
  7838. });
  7839. stack.push(block);
  7840. push({
  7841. type: "open",
  7842. value
  7843. });
  7844. continue;
  7845. }
  7846. /**
  7847. * Right curly brace: '}'
  7848. */
  7849. if (value === CHAR_RIGHT_CURLY_BRACE) {
  7850. if (block.type !== "brace") {
  7851. push({
  7852. type: "text",
  7853. value
  7854. });
  7855. continue;
  7856. }
  7857. const type = "close";
  7858. block = stack.pop();
  7859. block.close = true;
  7860. push({
  7861. type,
  7862. value
  7863. });
  7864. depth--;
  7865. block = stack[stack.length - 1];
  7866. continue;
  7867. }
  7868. /**
  7869. * Comma: ','
  7870. */
  7871. if (value === CHAR_COMMA && depth > 0) {
  7872. if (block.ranges > 0) {
  7873. block.ranges = 0;
  7874. const open = block.nodes.shift();
  7875. block.nodes = [open, {
  7876. type: "text",
  7877. value: stringify(block)
  7878. }];
  7879. }
  7880. push({
  7881. type: "comma",
  7882. value
  7883. });
  7884. block.commas++;
  7885. continue;
  7886. }
  7887. /**
  7888. * Dot: '.'
  7889. */
  7890. if (value === CHAR_DOT && depth > 0 && block.commas === 0) {
  7891. const siblings = block.nodes;
  7892. if (depth === 0 || siblings.length === 0) {
  7893. push({
  7894. type: "text",
  7895. value
  7896. });
  7897. continue;
  7898. }
  7899. if (prev.type === "dot") {
  7900. block.range = [];
  7901. prev.value += value;
  7902. prev.type = "range";
  7903. if (block.nodes.length !== 3 && block.nodes.length !== 5) {
  7904. block.invalid = true;
  7905. block.ranges = 0;
  7906. prev.type = "text";
  7907. continue;
  7908. }
  7909. block.ranges++;
  7910. block.args = [];
  7911. continue;
  7912. }
  7913. if (prev.type === "range") {
  7914. siblings.pop();
  7915. const before = siblings[siblings.length - 1];
  7916. before.value += prev.value + value;
  7917. prev = before;
  7918. block.ranges--;
  7919. continue;
  7920. }
  7921. push({
  7922. type: "dot",
  7923. value
  7924. });
  7925. continue;
  7926. }
  7927. /**
  7928. * Text
  7929. */
  7930. push({
  7931. type: "text",
  7932. value
  7933. });
  7934. }
  7935. do {
  7936. block = stack.pop();
  7937. if (block.type !== "root") {
  7938. block.nodes.forEach((node) => {
  7939. if (!node.nodes) {
  7940. if (node.type === "open") node.isOpen = true;
  7941. if (node.type === "close") node.isClose = true;
  7942. if (!node.nodes) node.type = "text";
  7943. node.invalid = true;
  7944. }
  7945. });
  7946. const parent = stack[stack.length - 1];
  7947. const index = parent.nodes.indexOf(block);
  7948. parent.nodes.splice(index, 1, ...block.nodes);
  7949. }
  7950. } while (stack.length > 0);
  7951. push({ type: "eos" });
  7952. return ast;
  7953. };
  7954. module.exports = parse;
  7955. }));
  7956. //#endregion
  7957. //#region ../../node_modules/.pnpm/braces@3.0.3/node_modules/braces/index.js
  7958. var require_braces = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  7959. const stringify = require_stringify();
  7960. const compile = require_compile();
  7961. const expand = require_expand();
  7962. const parse = require_parse$2();
  7963. /**
  7964. * Expand the given pattern or create a regex-compatible string.
  7965. *
  7966. * ```js
  7967. * const braces = require('braces');
  7968. * console.log(braces('{a,b,c}', { compile: true })); //=> ['(a|b|c)']
  7969. * console.log(braces('{a,b,c}')); //=> ['a', 'b', 'c']
  7970. * ```
  7971. * @param {String} `str`
  7972. * @param {Object} `options`
  7973. * @return {String}
  7974. * @api public
  7975. */
  7976. const braces = (input, options = {}) => {
  7977. let output = [];
  7978. if (Array.isArray(input)) for (const pattern of input) {
  7979. const result = braces.create(pattern, options);
  7980. if (Array.isArray(result)) output.push(...result);
  7981. else output.push(result);
  7982. }
  7983. else output = [].concat(braces.create(input, options));
  7984. if (options && options.expand === true && options.nodupes === true) output = [...new Set(output)];
  7985. return output;
  7986. };
  7987. /**
  7988. * Parse the given `str` with the given `options`.
  7989. *
  7990. * ```js
  7991. * // braces.parse(pattern, [, options]);
  7992. * const ast = braces.parse('a/{b,c}/d');
  7993. * console.log(ast);
  7994. * ```
  7995. * @param {String} pattern Brace pattern to parse
  7996. * @param {Object} options
  7997. * @return {Object} Returns an AST
  7998. * @api public
  7999. */
  8000. braces.parse = (input, options = {}) => parse(input, options);
  8001. /**
  8002. * Creates a braces string from an AST, or an AST node.
  8003. *
  8004. * ```js
  8005. * const braces = require('braces');
  8006. * let ast = braces.parse('foo/{a,b}/bar');
  8007. * console.log(stringify(ast.nodes[2])); //=> '{a,b}'
  8008. * ```
  8009. * @param {String} `input` Brace pattern or AST.
  8010. * @param {Object} `options`
  8011. * @return {Array} Returns an array of expanded values.
  8012. * @api public
  8013. */
  8014. braces.stringify = (input, options = {}) => {
  8015. if (typeof input === "string") return stringify(braces.parse(input, options), options);
  8016. return stringify(input, options);
  8017. };
  8018. /**
  8019. * Compiles a brace pattern into a regex-compatible, optimized string.
  8020. * This method is called by the main [braces](#braces) function by default.
  8021. *
  8022. * ```js
  8023. * const braces = require('braces');
  8024. * console.log(braces.compile('a/{b,c}/d'));
  8025. * //=> ['a/(b|c)/d']
  8026. * ```
  8027. * @param {String} `input` Brace pattern or AST.
  8028. * @param {Object} `options`
  8029. * @return {Array} Returns an array of expanded values.
  8030. * @api public
  8031. */
  8032. braces.compile = (input, options = {}) => {
  8033. if (typeof input === "string") input = braces.parse(input, options);
  8034. return compile(input, options);
  8035. };
  8036. /**
  8037. * Expands a brace pattern into an array. This method is called by the
  8038. * main [braces](#braces) function when `options.expand` is true. Before
  8039. * using this method it's recommended that you read the [performance notes](#performance))
  8040. * and advantages of using [.compile](#compile) instead.
  8041. *
  8042. * ```js
  8043. * const braces = require('braces');
  8044. * console.log(braces.expand('a/{b,c}/d'));
  8045. * //=> ['a/b/d', 'a/c/d'];
  8046. * ```
  8047. * @param {String} `pattern` Brace pattern
  8048. * @param {Object} `options`
  8049. * @return {Array} Returns an array of expanded values.
  8050. * @api public
  8051. */
  8052. braces.expand = (input, options = {}) => {
  8053. if (typeof input === "string") input = braces.parse(input, options);
  8054. let result = expand(input, options);
  8055. if (options.noempty === true) result = result.filter(Boolean);
  8056. if (options.nodupes === true) result = [...new Set(result)];
  8057. return result;
  8058. };
  8059. /**
  8060. * Processes a brace pattern and returns either an expanded array
  8061. * (if `options.expand` is true), a highly optimized regex-compatible string.
  8062. * This method is called by the main [braces](#braces) function.
  8063. *
  8064. * ```js
  8065. * const braces = require('braces');
  8066. * console.log(braces.create('user-{200..300}/project-{a,b,c}-{1..10}'))
  8067. * //=> 'user-(20[0-9]|2[1-9][0-9]|300)/project-(a|b|c)-([1-9]|10)'
  8068. * ```
  8069. * @param {String} `pattern` Brace pattern
  8070. * @param {Object} `options`
  8071. * @return {Array} Returns an array of expanded values.
  8072. * @api public
  8073. */
  8074. braces.create = (input, options = {}) => {
  8075. if (input === "" || input.length < 3) return [input];
  8076. return options.expand !== true ? braces.compile(input, options) : braces.expand(input, options);
  8077. };
  8078. /**
  8079. * Expose "braces"
  8080. */
  8081. module.exports = braces;
  8082. }));
  8083. //#endregion
  8084. //#region ../../node_modules/.pnpm/binary-extensions@2.3.0/node_modules/binary-extensions/binary-extensions.json
  8085. var require_binary_extensions$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  8086. module.exports = [
  8087. "3dm",
  8088. "3ds",
  8089. "3g2",
  8090. "3gp",
  8091. "7z",
  8092. "a",
  8093. "aac",
  8094. "adp",
  8095. "afdesign",
  8096. "afphoto",
  8097. "afpub",
  8098. "ai",
  8099. "aif",
  8100. "aiff",
  8101. "alz",
  8102. "ape",
  8103. "apk",
  8104. "appimage",
  8105. "ar",
  8106. "arj",
  8107. "asf",
  8108. "au",
  8109. "avi",
  8110. "bak",
  8111. "baml",
  8112. "bh",
  8113. "bin",
  8114. "bk",
  8115. "bmp",
  8116. "btif",
  8117. "bz2",
  8118. "bzip2",
  8119. "cab",
  8120. "caf",
  8121. "cgm",
  8122. "class",
  8123. "cmx",
  8124. "cpio",
  8125. "cr2",
  8126. "cur",
  8127. "dat",
  8128. "dcm",
  8129. "deb",
  8130. "dex",
  8131. "djvu",
  8132. "dll",
  8133. "dmg",
  8134. "dng",
  8135. "doc",
  8136. "docm",
  8137. "docx",
  8138. "dot",
  8139. "dotm",
  8140. "dra",
  8141. "DS_Store",
  8142. "dsk",
  8143. "dts",
  8144. "dtshd",
  8145. "dvb",
  8146. "dwg",
  8147. "dxf",
  8148. "ecelp4800",
  8149. "ecelp7470",
  8150. "ecelp9600",
  8151. "egg",
  8152. "eol",
  8153. "eot",
  8154. "epub",
  8155. "exe",
  8156. "f4v",
  8157. "fbs",
  8158. "fh",
  8159. "fla",
  8160. "flac",
  8161. "flatpak",
  8162. "fli",
  8163. "flv",
  8164. "fpx",
  8165. "fst",
  8166. "fvt",
  8167. "g3",
  8168. "gh",
  8169. "gif",
  8170. "graffle",
  8171. "gz",
  8172. "gzip",
  8173. "h261",
  8174. "h263",
  8175. "h264",
  8176. "icns",
  8177. "ico",
  8178. "ief",
  8179. "img",
  8180. "ipa",
  8181. "iso",
  8182. "jar",
  8183. "jpeg",
  8184. "jpg",
  8185. "jpgv",
  8186. "jpm",
  8187. "jxr",
  8188. "key",
  8189. "ktx",
  8190. "lha",
  8191. "lib",
  8192. "lvp",
  8193. "lz",
  8194. "lzh",
  8195. "lzma",
  8196. "lzo",
  8197. "m3u",
  8198. "m4a",
  8199. "m4v",
  8200. "mar",
  8201. "mdi",
  8202. "mht",
  8203. "mid",
  8204. "midi",
  8205. "mj2",
  8206. "mka",
  8207. "mkv",
  8208. "mmr",
  8209. "mng",
  8210. "mobi",
  8211. "mov",
  8212. "movie",
  8213. "mp3",
  8214. "mp4",
  8215. "mp4a",
  8216. "mpeg",
  8217. "mpg",
  8218. "mpga",
  8219. "mxu",
  8220. "nef",
  8221. "npx",
  8222. "numbers",
  8223. "nupkg",
  8224. "o",
  8225. "odp",
  8226. "ods",
  8227. "odt",
  8228. "oga",
  8229. "ogg",
  8230. "ogv",
  8231. "otf",
  8232. "ott",
  8233. "pages",
  8234. "pbm",
  8235. "pcx",
  8236. "pdb",
  8237. "pdf",
  8238. "pea",
  8239. "pgm",
  8240. "pic",
  8241. "png",
  8242. "pnm",
  8243. "pot",
  8244. "potm",
  8245. "potx",
  8246. "ppa",
  8247. "ppam",
  8248. "ppm",
  8249. "pps",
  8250. "ppsm",
  8251. "ppsx",
  8252. "ppt",
  8253. "pptm",
  8254. "pptx",
  8255. "psd",
  8256. "pya",
  8257. "pyc",
  8258. "pyo",
  8259. "pyv",
  8260. "qt",
  8261. "rar",
  8262. "ras",
  8263. "raw",
  8264. "resources",
  8265. "rgb",
  8266. "rip",
  8267. "rlc",
  8268. "rmf",
  8269. "rmvb",
  8270. "rpm",
  8271. "rtf",
  8272. "rz",
  8273. "s3m",
  8274. "s7z",
  8275. "scpt",
  8276. "sgi",
  8277. "shar",
  8278. "snap",
  8279. "sil",
  8280. "sketch",
  8281. "slk",
  8282. "smv",
  8283. "snk",
  8284. "so",
  8285. "stl",
  8286. "suo",
  8287. "sub",
  8288. "swf",
  8289. "tar",
  8290. "tbz",
  8291. "tbz2",
  8292. "tga",
  8293. "tgz",
  8294. "thmx",
  8295. "tif",
  8296. "tiff",
  8297. "tlz",
  8298. "ttc",
  8299. "ttf",
  8300. "txz",
  8301. "udf",
  8302. "uvh",
  8303. "uvi",
  8304. "uvm",
  8305. "uvp",
  8306. "uvs",
  8307. "uvu",
  8308. "viv",
  8309. "vob",
  8310. "war",
  8311. "wav",
  8312. "wax",
  8313. "wbmp",
  8314. "wdp",
  8315. "weba",
  8316. "webm",
  8317. "webp",
  8318. "whl",
  8319. "wim",
  8320. "wm",
  8321. "wma",
  8322. "wmv",
  8323. "wmx",
  8324. "woff",
  8325. "woff2",
  8326. "wrm",
  8327. "wvx",
  8328. "xbm",
  8329. "xif",
  8330. "xla",
  8331. "xlam",
  8332. "xls",
  8333. "xlsb",
  8334. "xlsm",
  8335. "xlsx",
  8336. "xlt",
  8337. "xltm",
  8338. "xltx",
  8339. "xm",
  8340. "xmind",
  8341. "xpi",
  8342. "xpm",
  8343. "xwd",
  8344. "xz",
  8345. "z",
  8346. "zip",
  8347. "zipx"
  8348. ];
  8349. }));
  8350. //#endregion
  8351. //#region ../../node_modules/.pnpm/binary-extensions@2.3.0/node_modules/binary-extensions/index.js
  8352. var require_binary_extensions = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  8353. module.exports = require_binary_extensions$1();
  8354. }));
  8355. //#endregion
  8356. //#region ../../node_modules/.pnpm/is-binary-path@2.1.0/node_modules/is-binary-path/index.js
  8357. var require_is_binary_path = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  8358. const path$10 = __require("path");
  8359. const binaryExtensions = require_binary_extensions();
  8360. const extensions = new Set(binaryExtensions);
  8361. module.exports = (filePath) => extensions.has(path$10.extname(filePath).slice(1).toLowerCase());
  8362. }));
  8363. //#endregion
  8364. //#region ../../node_modules/.pnpm/chokidar@3.6.0_patch_hash=8a4f9e2b397e6034b91a0508faae3cecb97f222313faa129d7cb0eb71e9d0e84/node_modules/chokidar/lib/constants.js
  8365. var require_constants$1 = /* @__PURE__ */ __commonJSMin(((exports) => {
  8366. const { sep: sep$1 } = __require("path");
  8367. const { platform } = process;
  8368. const os$3 = __require("os");
  8369. exports.EV_ALL = "all";
  8370. exports.EV_READY = "ready";
  8371. exports.EV_ADD = "add";
  8372. exports.EV_CHANGE = "change";
  8373. exports.EV_ADD_DIR = "addDir";
  8374. exports.EV_UNLINK = "unlink";
  8375. exports.EV_UNLINK_DIR = "unlinkDir";
  8376. exports.EV_RAW = "raw";
  8377. exports.EV_ERROR = "error";
  8378. exports.STR_DATA = "data";
  8379. exports.STR_END = "end";
  8380. exports.STR_CLOSE = "close";
  8381. exports.FSEVENT_CREATED = "created";
  8382. exports.FSEVENT_MODIFIED = "modified";
  8383. exports.FSEVENT_DELETED = "deleted";
  8384. exports.FSEVENT_MOVED = "moved";
  8385. exports.FSEVENT_CLONED = "cloned";
  8386. exports.FSEVENT_UNKNOWN = "unknown";
  8387. exports.FSEVENT_FLAG_MUST_SCAN_SUBDIRS = 1;
  8388. exports.FSEVENT_TYPE_FILE = "file";
  8389. exports.FSEVENT_TYPE_DIRECTORY = "directory";
  8390. exports.FSEVENT_TYPE_SYMLINK = "symlink";
  8391. exports.KEY_LISTENERS = "listeners";
  8392. exports.KEY_ERR = "errHandlers";
  8393. exports.KEY_RAW = "rawEmitters";
  8394. exports.HANDLER_KEYS = [
  8395. exports.KEY_LISTENERS,
  8396. exports.KEY_ERR,
  8397. exports.KEY_RAW
  8398. ];
  8399. exports.DOT_SLASH = `.${sep$1}`;
  8400. exports.BACK_SLASH_RE = /\\/g;
  8401. exports.DOUBLE_SLASH_RE = /\/\//;
  8402. exports.SLASH_OR_BACK_SLASH_RE = /[/\\]/;
  8403. exports.DOT_RE = /\..*\.(sw[px])$|~$|\.subl.*\.tmp/;
  8404. exports.REPLACER_RE = /^\.[/\\]/;
  8405. exports.SLASH = "/";
  8406. exports.SLASH_SLASH = "//";
  8407. exports.BRACE_START = "{";
  8408. exports.BANG = "!";
  8409. exports.ONE_DOT = ".";
  8410. exports.TWO_DOTS = "..";
  8411. exports.STAR = "*";
  8412. exports.GLOBSTAR = "**";
  8413. exports.ROOT_GLOBSTAR = "/**/*";
  8414. exports.SLASH_GLOBSTAR = "/**";
  8415. exports.DIR_SUFFIX = "Dir";
  8416. exports.ANYMATCH_OPTS = { dot: true };
  8417. exports.STRING_TYPE = "string";
  8418. exports.FUNCTION_TYPE = "function";
  8419. exports.EMPTY_STR = "";
  8420. exports.EMPTY_FN = () => {};
  8421. exports.IDENTITY_FN = (val) => val;
  8422. exports.isWindows = platform === "win32";
  8423. exports.isMacos = platform === "darwin";
  8424. exports.isLinux = platform === "linux";
  8425. exports.isIBMi = os$3.type() === "OS400";
  8426. }));
  8427. //#endregion
  8428. //#region ../../node_modules/.pnpm/chokidar@3.6.0_patch_hash=8a4f9e2b397e6034b91a0508faae3cecb97f222313faa129d7cb0eb71e9d0e84/node_modules/chokidar/lib/nodefs-handler.js
  8429. var require_nodefs_handler = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  8430. const fs$9 = __require("fs");
  8431. const sysPath$2 = __require("path");
  8432. const { promisify: promisify$3 } = __require("util");
  8433. const isBinaryPath = require_is_binary_path();
  8434. const { isWindows, isLinux, EMPTY_FN, EMPTY_STR, KEY_LISTENERS, KEY_ERR, KEY_RAW, HANDLER_KEYS, EV_CHANGE, EV_ADD, EV_ADD_DIR, EV_ERROR, STR_DATA, STR_END, BRACE_START, STAR } = require_constants$1();
  8435. const THROTTLE_MODE_WATCH = "watch";
  8436. const open = promisify$3(fs$9.open);
  8437. const stat = promisify$3(fs$9.stat);
  8438. const lstat = promisify$3(fs$9.lstat);
  8439. const close = promisify$3(fs$9.close);
  8440. const fsrealpath = promisify$3(fs$9.realpath);
  8441. const statMethods = {
  8442. lstat,
  8443. stat
  8444. };
  8445. const foreach = (val, fn) => {
  8446. if (val instanceof Set) val.forEach(fn);
  8447. else fn(val);
  8448. };
  8449. const addAndConvert = (main, prop, item) => {
  8450. let container = main[prop];
  8451. if (!(container instanceof Set)) main[prop] = container = new Set([container]);
  8452. container.add(item);
  8453. };
  8454. const clearItem = (cont) => (key) => {
  8455. const set = cont[key];
  8456. if (set instanceof Set) set.clear();
  8457. else delete cont[key];
  8458. };
  8459. const delFromSet = (main, prop, item) => {
  8460. const container = main[prop];
  8461. if (container instanceof Set) container.delete(item);
  8462. else if (container === item) delete main[prop];
  8463. };
  8464. const isEmptySet = (val) => val instanceof Set ? val.size === 0 : !val;
  8465. /**
  8466. * @typedef {String} Path
  8467. */
  8468. /**
  8469. * @typedef {Object} FsWatchContainer
  8470. * @property {Set} listeners
  8471. * @property {Set} errHandlers
  8472. * @property {Set} rawEmitters
  8473. * @property {fs.FSWatcher=} watcher
  8474. * @property {Boolean=} watcherUnusable
  8475. */
  8476. /**
  8477. * @type {Map<String,FsWatchContainer>}
  8478. */
  8479. const FsWatchInstances = /* @__PURE__ */ new Map();
  8480. /**
  8481. * Instantiates the fs_watch interface
  8482. * @param {String} path to be watched
  8483. * @param {Object} options to be passed to fs_watch
  8484. * @param {Function} listener main event handler
  8485. * @param {Function} errHandler emits info about errors
  8486. * @param {Function} emitRaw emits raw event data
  8487. * @returns {fs.FSWatcher} new fsevents instance
  8488. */
  8489. function createFsWatchInstance(path, options, listener, errHandler, emitRaw) {
  8490. const handleEvent = (rawEvent, evPath) => {
  8491. listener(path);
  8492. emitRaw(rawEvent, evPath, { watchedPath: path });
  8493. if (evPath && path !== evPath) fsWatchBroadcast(sysPath$2.resolve(path, evPath), KEY_LISTENERS, sysPath$2.join(path, evPath));
  8494. };
  8495. try {
  8496. return fs$9.watch(path, options, handleEvent);
  8497. } catch (error) {
  8498. errHandler(error);
  8499. }
  8500. }
  8501. /**
  8502. * Helper for passing fs_watch event data to a collection of listeners
  8503. * @param {Path} fullPath absolute path bound to fs_watch instance
  8504. * @param {String} type listener type
  8505. * @param {*=} val1 arguments to be passed to listeners
  8506. * @param {*=} val2
  8507. * @param {*=} val3
  8508. */
  8509. const fsWatchBroadcast = (fullPath, type, val1, val2, val3) => {
  8510. const cont = FsWatchInstances.get(fullPath);
  8511. if (!cont) return;
  8512. foreach(cont[type], (listener) => {
  8513. listener(val1, val2, val3);
  8514. });
  8515. };
  8516. /**
  8517. * Instantiates the fs_watch interface or binds listeners
  8518. * to an existing one covering the same file system entry
  8519. * @param {String} path
  8520. * @param {String} fullPath absolute path
  8521. * @param {Object} options to be passed to fs_watch
  8522. * @param {Object} handlers container for event listener functions
  8523. */
  8524. const setFsWatchListener = (path, fullPath, options, handlers) => {
  8525. const { listener, errHandler, rawEmitter } = handlers;
  8526. let cont = FsWatchInstances.get(fullPath);
  8527. /** @type {fs.FSWatcher=} */
  8528. let watcher;
  8529. if (!options.persistent) {
  8530. watcher = createFsWatchInstance(path, options, listener, errHandler, rawEmitter);
  8531. return watcher.close.bind(watcher);
  8532. }
  8533. if (cont) {
  8534. addAndConvert(cont, KEY_LISTENERS, listener);
  8535. addAndConvert(cont, KEY_ERR, errHandler);
  8536. addAndConvert(cont, KEY_RAW, rawEmitter);
  8537. } else {
  8538. watcher = createFsWatchInstance(path, options, fsWatchBroadcast.bind(null, fullPath, KEY_LISTENERS), errHandler, fsWatchBroadcast.bind(null, fullPath, KEY_RAW));
  8539. if (!watcher) return;
  8540. watcher.on(EV_ERROR, async (error) => {
  8541. const broadcastErr = fsWatchBroadcast.bind(null, fullPath, KEY_ERR);
  8542. cont.watcherUnusable = true;
  8543. if (isWindows && error.code === "EPERM") try {
  8544. await close(await open(path, "r"));
  8545. broadcastErr(error);
  8546. } catch (err) {}
  8547. else broadcastErr(error);
  8548. });
  8549. cont = {
  8550. listeners: listener,
  8551. errHandlers: errHandler,
  8552. rawEmitters: rawEmitter,
  8553. watcher
  8554. };
  8555. FsWatchInstances.set(fullPath, cont);
  8556. }
  8557. return () => {
  8558. delFromSet(cont, KEY_LISTENERS, listener);
  8559. delFromSet(cont, KEY_ERR, errHandler);
  8560. delFromSet(cont, KEY_RAW, rawEmitter);
  8561. if (isEmptySet(cont.listeners)) {
  8562. cont.watcher.close();
  8563. FsWatchInstances.delete(fullPath);
  8564. HANDLER_KEYS.forEach(clearItem(cont));
  8565. cont.watcher = void 0;
  8566. Object.freeze(cont);
  8567. }
  8568. };
  8569. };
  8570. const FsWatchFileInstances = /* @__PURE__ */ new Map();
  8571. /**
  8572. * Instantiates the fs_watchFile interface or binds listeners
  8573. * to an existing one covering the same file system entry
  8574. * @param {String} path to be watched
  8575. * @param {String} fullPath absolute path
  8576. * @param {Object} options options to be passed to fs_watchFile
  8577. * @param {Object} handlers container for event listener functions
  8578. * @returns {Function} closer
  8579. */
  8580. const setFsWatchFileListener = (path, fullPath, options, handlers) => {
  8581. const { listener, rawEmitter } = handlers;
  8582. let cont = FsWatchFileInstances.get(fullPath);
  8583. const copts = cont && cont.options;
  8584. if (copts && (copts.persistent < options.persistent || copts.interval > options.interval)) {
  8585. fs$9.unwatchFile(fullPath);
  8586. cont = void 0;
  8587. }
  8588. if (cont) {
  8589. addAndConvert(cont, KEY_LISTENERS, listener);
  8590. addAndConvert(cont, KEY_RAW, rawEmitter);
  8591. } else {
  8592. cont = {
  8593. listeners: listener,
  8594. rawEmitters: rawEmitter,
  8595. options,
  8596. watcher: fs$9.watchFile(fullPath, options, (curr, prev) => {
  8597. foreach(cont.rawEmitters, (rawEmitter) => {
  8598. rawEmitter(EV_CHANGE, fullPath, {
  8599. curr,
  8600. prev
  8601. });
  8602. });
  8603. const currmtime = curr.mtimeMs;
  8604. if (curr.size !== prev.size || currmtime > prev.mtimeMs || currmtime === 0) foreach(cont.listeners, (listener) => listener(path, curr));
  8605. })
  8606. };
  8607. FsWatchFileInstances.set(fullPath, cont);
  8608. }
  8609. return () => {
  8610. delFromSet(cont, KEY_LISTENERS, listener);
  8611. delFromSet(cont, KEY_RAW, rawEmitter);
  8612. if (isEmptySet(cont.listeners)) {
  8613. FsWatchFileInstances.delete(fullPath);
  8614. fs$9.unwatchFile(fullPath);
  8615. cont.options = cont.watcher = void 0;
  8616. Object.freeze(cont);
  8617. }
  8618. };
  8619. };
  8620. /**
  8621. * @mixin
  8622. */
  8623. var NodeFsHandler = class {
  8624. /**
  8625. * @param {import("../index").FSWatcher} fsW
  8626. */
  8627. constructor(fsW) {
  8628. this.fsw = fsW;
  8629. this._boundHandleError = (error) => fsW._handleError(error);
  8630. }
  8631. /**
  8632. * Watch file for changes with fs_watchFile or fs_watch.
  8633. * @param {String} path to file or dir
  8634. * @param {Function} listener on fs change
  8635. * @returns {Function} closer for the watcher instance
  8636. */
  8637. _watchWithNodeFs(path, listener) {
  8638. const opts = this.fsw.options;
  8639. const directory = sysPath$2.dirname(path);
  8640. const basename = sysPath$2.basename(path);
  8641. this.fsw._getWatchedDir(directory).add(basename);
  8642. const absolutePath = sysPath$2.resolve(path);
  8643. const options = { persistent: opts.persistent };
  8644. if (!listener) listener = EMPTY_FN;
  8645. let closer;
  8646. if (opts.usePolling) {
  8647. options.interval = opts.enableBinaryInterval && isBinaryPath(basename) ? opts.binaryInterval : opts.interval;
  8648. closer = setFsWatchFileListener(path, absolutePath, options, {
  8649. listener,
  8650. rawEmitter: this.fsw._emitRaw
  8651. });
  8652. } else closer = setFsWatchListener(path, absolutePath, options, {
  8653. listener,
  8654. errHandler: this._boundHandleError,
  8655. rawEmitter: this.fsw._emitRaw
  8656. });
  8657. return closer;
  8658. }
  8659. /**
  8660. * Watch a file and emit add event if warranted.
  8661. * @param {Path} file Path
  8662. * @param {fs.Stats} stats result of fs_stat
  8663. * @param {Boolean} initialAdd was the file added at watch instantiation?
  8664. * @returns {Function} closer for the watcher instance
  8665. */
  8666. _handleFile(file, stats, initialAdd) {
  8667. if (this.fsw.closed) return;
  8668. const dirname = sysPath$2.dirname(file);
  8669. const basename = sysPath$2.basename(file);
  8670. const parent = this.fsw._getWatchedDir(dirname);
  8671. let prevStats = stats;
  8672. if (parent.has(basename)) return;
  8673. const listener = async (path, newStats) => {
  8674. if (!this.fsw._throttle(THROTTLE_MODE_WATCH, file, 5)) return;
  8675. if (!newStats || newStats.mtimeMs === 0) try {
  8676. const newStats = await stat(file);
  8677. if (this.fsw.closed) return;
  8678. const at = newStats.atimeMs;
  8679. const mt = newStats.mtimeMs;
  8680. if (!at || at <= mt || mt !== prevStats.mtimeMs) this.fsw._emit(EV_CHANGE, file, newStats);
  8681. if (isLinux && prevStats.ino !== newStats.ino) {
  8682. this.fsw._closeFile(path);
  8683. prevStats = newStats;
  8684. this.fsw._addPathCloser(path, this._watchWithNodeFs(file, listener));
  8685. } else prevStats = newStats;
  8686. } catch (error) {
  8687. this.fsw._remove(dirname, basename);
  8688. }
  8689. else if (parent.has(basename)) {
  8690. const at = newStats.atimeMs;
  8691. const mt = newStats.mtimeMs;
  8692. if (!at || at <= mt || mt !== prevStats.mtimeMs) this.fsw._emit(EV_CHANGE, file, newStats);
  8693. prevStats = newStats;
  8694. }
  8695. };
  8696. const closer = this._watchWithNodeFs(file, listener);
  8697. if (!(initialAdd && this.fsw.options.ignoreInitial) && this.fsw._isntIgnored(file)) {
  8698. if (!this.fsw._throttle(EV_ADD, file, 0)) return;
  8699. this.fsw._emit(EV_ADD, file, stats);
  8700. }
  8701. return closer;
  8702. }
  8703. /**
  8704. * Handle symlinks encountered while reading a dir.
  8705. * @param {Object} entry returned by readdirp
  8706. * @param {String} directory path of dir being read
  8707. * @param {String} path of this item
  8708. * @param {String} item basename of this item
  8709. * @returns {Promise<Boolean>} true if no more processing is needed for this entry.
  8710. */
  8711. async _handleSymlink(entry, directory, path, item) {
  8712. if (this.fsw.closed) return;
  8713. const full = entry.fullPath;
  8714. const dir = this.fsw._getWatchedDir(directory);
  8715. if (!this.fsw.options.followSymlinks) {
  8716. this.fsw._incrReadyCount();
  8717. let linkPath;
  8718. try {
  8719. linkPath = await fsrealpath(path);
  8720. } catch (e) {
  8721. this.fsw._emitReady();
  8722. return true;
  8723. }
  8724. if (this.fsw.closed) return;
  8725. if (dir.has(item)) {
  8726. if (this.fsw._symlinkPaths.get(full) !== linkPath) {
  8727. this.fsw._symlinkPaths.set(full, linkPath);
  8728. this.fsw._emit(EV_CHANGE, path, entry.stats);
  8729. }
  8730. } else {
  8731. dir.add(item);
  8732. this.fsw._symlinkPaths.set(full, linkPath);
  8733. this.fsw._emit(EV_ADD, path, entry.stats);
  8734. }
  8735. this.fsw._emitReady();
  8736. return true;
  8737. }
  8738. if (this.fsw._symlinkPaths.has(full)) return true;
  8739. this.fsw._symlinkPaths.set(full, true);
  8740. }
  8741. _handleRead(directory, initialAdd, wh, target, dir, depth, throttler) {
  8742. directory = sysPath$2.join(directory, EMPTY_STR);
  8743. if (!wh.hasGlob) {
  8744. throttler = this.fsw._throttle("readdir", directory, 1e3);
  8745. if (!throttler) return;
  8746. }
  8747. const previous = this.fsw._getWatchedDir(wh.path);
  8748. const current = /* @__PURE__ */ new Set();
  8749. let stream = this.fsw._readdirp(directory, {
  8750. fileFilter: (entry) => wh.filterPath(entry),
  8751. directoryFilter: (entry) => wh.filterDir(entry),
  8752. depth: 0
  8753. }).on(STR_DATA, async (entry) => {
  8754. if (this.fsw.closed) {
  8755. stream = void 0;
  8756. return;
  8757. }
  8758. const item = entry.path;
  8759. let path = sysPath$2.join(directory, item);
  8760. current.add(item);
  8761. if (entry.stats.isSymbolicLink() && await this._handleSymlink(entry, directory, path, item)) return;
  8762. if (this.fsw.closed) {
  8763. stream = void 0;
  8764. return;
  8765. }
  8766. if (item === target || !target && !previous.has(item)) {
  8767. this.fsw._incrReadyCount();
  8768. path = sysPath$2.join(dir, sysPath$2.relative(dir, path));
  8769. this._addToNodeFs(path, initialAdd, wh, depth + 1);
  8770. }
  8771. }).on(EV_ERROR, this._boundHandleError);
  8772. return new Promise((resolve) => stream.once(STR_END, () => {
  8773. if (this.fsw.closed) {
  8774. stream = void 0;
  8775. return;
  8776. }
  8777. const wasThrottled = throttler ? throttler.clear() : false;
  8778. resolve();
  8779. previous.getChildren().filter((item) => {
  8780. return item !== directory && !current.has(item) && (!wh.hasGlob || wh.filterPath({ fullPath: sysPath$2.resolve(directory, item) }));
  8781. }).forEach((item) => {
  8782. this.fsw._remove(directory, item);
  8783. });
  8784. stream = void 0;
  8785. if (wasThrottled) this._handleRead(directory, false, wh, target, dir, depth, throttler);
  8786. }));
  8787. }
  8788. /**
  8789. * Read directory to add / remove files from `@watched` list and re-read it on change.
  8790. * @param {String} dir fs path
  8791. * @param {fs.Stats} stats
  8792. * @param {Boolean} initialAdd
  8793. * @param {Number} depth relative to user-supplied path
  8794. * @param {String} target child path targeted for watch
  8795. * @param {Object} wh Common watch helpers for this path
  8796. * @param {String} realpath
  8797. * @returns {Promise<Function>} closer for the watcher instance.
  8798. */
  8799. async _handleDir(dir, stats, initialAdd, depth, target, wh, realpath) {
  8800. const parentDir = this.fsw._getWatchedDir(sysPath$2.dirname(dir));
  8801. const tracked = parentDir.has(sysPath$2.basename(dir));
  8802. if (!(initialAdd && this.fsw.options.ignoreInitial) && !target && !tracked) {
  8803. if (!wh.hasGlob || wh.globFilter(dir)) this.fsw._emit(EV_ADD_DIR, dir, stats);
  8804. }
  8805. parentDir.add(sysPath$2.basename(dir));
  8806. this.fsw._getWatchedDir(dir);
  8807. let throttler;
  8808. let closer;
  8809. const oDepth = this.fsw.options.depth;
  8810. if ((oDepth == null || depth <= oDepth) && !this.fsw._symlinkPaths.has(realpath)) {
  8811. if (!target) {
  8812. await this._handleRead(dir, initialAdd, wh, target, dir, depth, throttler);
  8813. if (this.fsw.closed) return;
  8814. }
  8815. closer = this._watchWithNodeFs(dir, (dirPath, stats) => {
  8816. if (stats && stats.mtimeMs === 0) return;
  8817. this._handleRead(dirPath, false, wh, target, dir, depth, throttler);
  8818. });
  8819. }
  8820. return closer;
  8821. }
  8822. /**
  8823. * Handle added file, directory, or glob pattern.
  8824. * Delegates call to _handleFile / _handleDir after checks.
  8825. * @param {String} path to file or ir
  8826. * @param {Boolean} initialAdd was the file added at watch instantiation?
  8827. * @param {Object} priorWh depth relative to user-supplied path
  8828. * @param {Number} depth Child path actually targeted for watch
  8829. * @param {String=} target Child path actually targeted for watch
  8830. * @returns {Promise}
  8831. */
  8832. async _addToNodeFs(path, initialAdd, priorWh, depth, target) {
  8833. const ready = this.fsw._emitReady;
  8834. if (this.fsw._isIgnored(path) || this.fsw.closed) {
  8835. ready();
  8836. return false;
  8837. }
  8838. const wh = this.fsw._getWatchHelpers(path, depth);
  8839. if (!wh.hasGlob && priorWh) {
  8840. wh.hasGlob = priorWh.hasGlob;
  8841. wh.globFilter = priorWh.globFilter;
  8842. wh.filterPath = (entry) => priorWh.filterPath(entry);
  8843. wh.filterDir = (entry) => priorWh.filterDir(entry);
  8844. }
  8845. try {
  8846. const stats = await statMethods[wh.statMethod](wh.watchPath);
  8847. if (this.fsw.closed) return;
  8848. if (this.fsw._isIgnored(wh.watchPath, stats)) {
  8849. ready();
  8850. return false;
  8851. }
  8852. const follow = this.fsw.options.followSymlinks && !path.includes(STAR) && !path.includes(BRACE_START);
  8853. let closer;
  8854. if (stats.isDirectory()) {
  8855. const absPath = sysPath$2.resolve(path);
  8856. const targetPath = follow ? await fsrealpath(path) : path;
  8857. if (this.fsw.closed) return;
  8858. closer = await this._handleDir(wh.watchPath, stats, initialAdd, depth, target, wh, targetPath);
  8859. if (this.fsw.closed) return;
  8860. if (absPath !== targetPath && targetPath !== void 0) this.fsw._symlinkPaths.set(absPath, targetPath);
  8861. } else if (stats.isSymbolicLink()) {
  8862. const targetPath = follow ? await fsrealpath(path) : path;
  8863. if (this.fsw.closed) return;
  8864. const parent = sysPath$2.dirname(wh.watchPath);
  8865. this.fsw._getWatchedDir(parent).add(wh.watchPath);
  8866. this.fsw._emit(EV_ADD, wh.watchPath, stats);
  8867. closer = await this._handleDir(parent, stats, initialAdd, depth, path, wh, targetPath);
  8868. if (this.fsw.closed) return;
  8869. if (targetPath !== void 0) this.fsw._symlinkPaths.set(sysPath$2.resolve(path), targetPath);
  8870. } else closer = this._handleFile(wh.watchPath, stats, initialAdd);
  8871. ready();
  8872. this.fsw._addPathCloser(path, closer);
  8873. return false;
  8874. } catch (error) {
  8875. if (this.fsw._handleError(error)) {
  8876. ready();
  8877. return path;
  8878. }
  8879. }
  8880. }
  8881. };
  8882. module.exports = NodeFsHandler;
  8883. }));
  8884. //#endregion
  8885. //#region ../../node_modules/.pnpm/chokidar@3.6.0_patch_hash=8a4f9e2b397e6034b91a0508faae3cecb97f222313faa129d7cb0eb71e9d0e84/node_modules/chokidar/lib/fsevents-handler.js
  8886. var require_fsevents_handler = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  8887. const fs$8 = __require("fs");
  8888. const sysPath$1 = __require("path");
  8889. const { promisify: promisify$2 } = __require("util");
  8890. let fsevents;
  8891. try {
  8892. fsevents = __require("fsevents");
  8893. } catch (error) {
  8894. if (process.env.CHOKIDAR_PRINT_FSEVENTS_REQUIRE_ERROR) console.error(error);
  8895. }
  8896. if (fsevents) {
  8897. const mtch = process.version.match(/v(\d+)\.(\d+)/);
  8898. if (mtch && mtch[1] && mtch[2]) {
  8899. if (Number.parseInt(mtch[1], 10) === 8 && Number.parseInt(mtch[2], 10) < 16) fsevents = void 0;
  8900. }
  8901. }
  8902. const { EV_ADD, EV_CHANGE, EV_ADD_DIR, EV_UNLINK, EV_ERROR, STR_DATA, STR_END, FSEVENT_CREATED, FSEVENT_MODIFIED, FSEVENT_DELETED, FSEVENT_MOVED, FSEVENT_UNKNOWN, FSEVENT_FLAG_MUST_SCAN_SUBDIRS, FSEVENT_TYPE_FILE, FSEVENT_TYPE_DIRECTORY, FSEVENT_TYPE_SYMLINK, ROOT_GLOBSTAR, DIR_SUFFIX, DOT_SLASH, FUNCTION_TYPE, EMPTY_FN, IDENTITY_FN } = require_constants$1();
  8903. const Depth = (value) => isNaN(value) ? {} : { depth: value };
  8904. const stat = promisify$2(fs$8.stat);
  8905. const lstat = promisify$2(fs$8.lstat);
  8906. const realpath = promisify$2(fs$8.realpath);
  8907. const statMethods = {
  8908. stat,
  8909. lstat
  8910. };
  8911. /**
  8912. * @typedef {String} Path
  8913. */
  8914. /**
  8915. * @typedef {Object} FsEventsWatchContainer
  8916. * @property {Set<Function>} listeners
  8917. * @property {Function} rawEmitter
  8918. * @property {{stop: Function}} watcher
  8919. */
  8920. /**
  8921. * Object to hold per-process fsevents instances (may be shared across chokidar FSWatcher instances)
  8922. * @type {Map<Path,FsEventsWatchContainer>}
  8923. */
  8924. const FSEventsWatchers = /* @__PURE__ */ new Map();
  8925. const consolidateThreshhold = 10;
  8926. const wrongEventFlags = new Set([
  8927. 69888,
  8928. 70400,
  8929. 71424,
  8930. 72704,
  8931. 73472,
  8932. 131328,
  8933. 131840,
  8934. 262912
  8935. ]);
  8936. /**
  8937. * Instantiates the fsevents interface
  8938. * @param {Path} path path to be watched
  8939. * @param {Function} callback called when fsevents is bound and ready
  8940. * @returns {{stop: Function}} new fsevents instance
  8941. */
  8942. const createFSEventsInstance = (path, callback) => {
  8943. return { stop: fsevents.watch(path, callback) };
  8944. };
  8945. /**
  8946. * Instantiates the fsevents interface or binds listeners to an existing one covering
  8947. * the same file tree.
  8948. * @param {Path} path - to be watched
  8949. * @param {Path} realPath - real path for symlinks
  8950. * @param {Function} listener - called when fsevents emits events
  8951. * @param {Function} rawEmitter - passes data to listeners of the 'raw' event
  8952. * @returns {Function} closer
  8953. */
  8954. function setFSEventsListener(path, realPath, listener, rawEmitter) {
  8955. let watchPath = sysPath$1.extname(realPath) ? sysPath$1.dirname(realPath) : realPath;
  8956. const parentPath = sysPath$1.dirname(watchPath);
  8957. let cont = FSEventsWatchers.get(watchPath);
  8958. if (couldConsolidate(parentPath)) watchPath = parentPath;
  8959. const resolvedPath = sysPath$1.resolve(path);
  8960. const hasSymlink = resolvedPath !== realPath;
  8961. const filteredListener = (fullPath, flags, info) => {
  8962. if (hasSymlink) fullPath = fullPath.replace(realPath, resolvedPath);
  8963. if (fullPath === resolvedPath || !fullPath.indexOf(resolvedPath + sysPath$1.sep)) listener(fullPath, flags, info);
  8964. };
  8965. let watchedParent = false;
  8966. for (const watchedPath of FSEventsWatchers.keys()) if (realPath.indexOf(sysPath$1.resolve(watchedPath) + sysPath$1.sep) === 0) {
  8967. watchPath = watchedPath;
  8968. cont = FSEventsWatchers.get(watchPath);
  8969. watchedParent = true;
  8970. break;
  8971. }
  8972. if (cont || watchedParent) cont.listeners.add(filteredListener);
  8973. else {
  8974. cont = {
  8975. listeners: new Set([filteredListener]),
  8976. rawEmitter,
  8977. watcher: createFSEventsInstance(watchPath, (fullPath, flags) => {
  8978. if (!cont.listeners.size) return;
  8979. if (flags & FSEVENT_FLAG_MUST_SCAN_SUBDIRS) return;
  8980. const info = fsevents.getInfo(fullPath, flags);
  8981. cont.listeners.forEach((list) => {
  8982. list(fullPath, flags, info);
  8983. });
  8984. cont.rawEmitter(info.event, fullPath, info);
  8985. })
  8986. };
  8987. FSEventsWatchers.set(watchPath, cont);
  8988. }
  8989. return () => {
  8990. const lst = cont.listeners;
  8991. lst.delete(filteredListener);
  8992. if (!lst.size) {
  8993. FSEventsWatchers.delete(watchPath);
  8994. if (cont.watcher) return cont.watcher.stop().then(() => {
  8995. cont.rawEmitter = cont.watcher = void 0;
  8996. Object.freeze(cont);
  8997. });
  8998. }
  8999. };
  9000. }
  9001. const couldConsolidate = (path) => {
  9002. let count = 0;
  9003. for (const watchPath of FSEventsWatchers.keys()) if (watchPath.indexOf(path) === 0) {
  9004. count++;
  9005. if (count >= consolidateThreshhold) return true;
  9006. }
  9007. return false;
  9008. };
  9009. const canUse = () => fsevents && FSEventsWatchers.size < 128;
  9010. const calcDepth = (path, root) => {
  9011. let i = 0;
  9012. while (!path.indexOf(root) && (path = sysPath$1.dirname(path)) !== root) i++;
  9013. return i;
  9014. };
  9015. const sameTypes = (info, stats) => info.type === FSEVENT_TYPE_DIRECTORY && stats.isDirectory() || info.type === FSEVENT_TYPE_SYMLINK && stats.isSymbolicLink() || info.type === FSEVENT_TYPE_FILE && stats.isFile();
  9016. /**
  9017. * @mixin
  9018. */
  9019. var FsEventsHandler = class {
  9020. /**
  9021. * @param {import('../index').FSWatcher} fsw
  9022. */
  9023. constructor(fsw) {
  9024. this.fsw = fsw;
  9025. }
  9026. checkIgnored(path, stats) {
  9027. const ipaths = this.fsw._ignoredPaths;
  9028. if (this.fsw._isIgnored(path, stats)) {
  9029. ipaths.add(path);
  9030. if (stats && stats.isDirectory()) ipaths.add(path + ROOT_GLOBSTAR);
  9031. return true;
  9032. }
  9033. ipaths.delete(path);
  9034. ipaths.delete(path + ROOT_GLOBSTAR);
  9035. }
  9036. addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts) {
  9037. const event = watchedDir.has(item) ? EV_CHANGE : EV_ADD;
  9038. this.handleEvent(event, path, fullPath, realPath, parent, watchedDir, item, info, opts);
  9039. }
  9040. async checkExists(path, fullPath, realPath, parent, watchedDir, item, info, opts) {
  9041. try {
  9042. const stats = await stat(path);
  9043. if (this.fsw.closed) return;
  9044. if (sameTypes(info, stats)) this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts);
  9045. else this.handleEvent(EV_UNLINK, path, fullPath, realPath, parent, watchedDir, item, info, opts);
  9046. } catch (error) {
  9047. if (error.code === "EACCES") this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts);
  9048. else this.handleEvent(EV_UNLINK, path, fullPath, realPath, parent, watchedDir, item, info, opts);
  9049. }
  9050. }
  9051. handleEvent(event, path, fullPath, realPath, parent, watchedDir, item, info, opts) {
  9052. if (this.fsw.closed || this.checkIgnored(path)) return;
  9053. if (event === EV_UNLINK) {
  9054. const isDirectory = info.type === FSEVENT_TYPE_DIRECTORY;
  9055. if (isDirectory || watchedDir.has(item)) this.fsw._remove(parent, item, isDirectory);
  9056. } else {
  9057. if (event === EV_ADD) {
  9058. if (info.type === FSEVENT_TYPE_DIRECTORY) this.fsw._getWatchedDir(path);
  9059. if (info.type === FSEVENT_TYPE_SYMLINK && opts.followSymlinks) {
  9060. const curDepth = opts.depth === void 0 ? void 0 : calcDepth(fullPath, realPath) + 1;
  9061. return this._addToFsEvents(path, false, true, curDepth);
  9062. }
  9063. this.fsw._getWatchedDir(parent).add(item);
  9064. }
  9065. /**
  9066. * @type {'add'|'addDir'|'unlink'|'unlinkDir'}
  9067. */
  9068. const eventName = info.type === FSEVENT_TYPE_DIRECTORY ? event + DIR_SUFFIX : event;
  9069. this.fsw._emit(eventName, path);
  9070. if (eventName === EV_ADD_DIR) this._addToFsEvents(path, false, true);
  9071. }
  9072. }
  9073. /**
  9074. * Handle symlinks encountered during directory scan
  9075. * @param {String} watchPath - file/dir path to be watched with fsevents
  9076. * @param {String} realPath - real path (in case of symlinks)
  9077. * @param {Function} transform - path transformer
  9078. * @param {Function} globFilter - path filter in case a glob pattern was provided
  9079. * @returns {Function} closer for the watcher instance
  9080. */
  9081. _watchWithFsEvents(watchPath, realPath, transform, globFilter) {
  9082. if (this.fsw.closed || this.fsw._isIgnored(watchPath)) return;
  9083. const opts = this.fsw.options;
  9084. const watchCallback = async (fullPath, flags, info) => {
  9085. if (this.fsw.closed || this.fsw._isIgnored(fullPath)) return;
  9086. if (opts.depth !== void 0 && calcDepth(fullPath, realPath) > opts.depth) return;
  9087. const path = transform(sysPath$1.join(watchPath, sysPath$1.relative(watchPath, fullPath)));
  9088. if (globFilter && !globFilter(path)) return;
  9089. const parent = sysPath$1.dirname(path);
  9090. const item = sysPath$1.basename(path);
  9091. const watchedDir = this.fsw._getWatchedDir(info.type === FSEVENT_TYPE_DIRECTORY ? path : parent);
  9092. if (wrongEventFlags.has(flags) || info.event === FSEVENT_UNKNOWN) if (typeof opts.ignored === FUNCTION_TYPE) {
  9093. let stats;
  9094. try {
  9095. stats = await stat(path);
  9096. } catch (error) {}
  9097. if (this.fsw.closed) return;
  9098. if (this.checkIgnored(path, stats)) return;
  9099. if (sameTypes(info, stats)) this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts);
  9100. else this.handleEvent(EV_UNLINK, path, fullPath, realPath, parent, watchedDir, item, info, opts);
  9101. } else this.checkExists(path, fullPath, realPath, parent, watchedDir, item, info, opts);
  9102. else switch (info.event) {
  9103. case FSEVENT_CREATED:
  9104. case FSEVENT_MODIFIED: return this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts);
  9105. case FSEVENT_DELETED:
  9106. case FSEVENT_MOVED: return this.checkExists(path, fullPath, realPath, parent, watchedDir, item, info, opts);
  9107. }
  9108. };
  9109. const closer = setFSEventsListener(watchPath, realPath, watchCallback, this.fsw._emitRaw);
  9110. this.fsw._emitReady();
  9111. return closer;
  9112. }
  9113. /**
  9114. * Handle symlinks encountered during directory scan
  9115. * @param {String} linkPath path to symlink
  9116. * @param {String} fullPath absolute path to the symlink
  9117. * @param {Function} transform pre-existing path transformer
  9118. * @param {Number} curDepth level of subdirectories traversed to where symlink is
  9119. * @returns {Promise<void>}
  9120. */
  9121. async _handleFsEventsSymlink(linkPath, fullPath, transform, curDepth) {
  9122. if (this.fsw.closed || this.fsw._symlinkPaths.has(fullPath)) return;
  9123. this.fsw._symlinkPaths.set(fullPath, true);
  9124. this.fsw._incrReadyCount();
  9125. try {
  9126. const linkTarget = await realpath(linkPath);
  9127. if (this.fsw.closed) return;
  9128. if (this.fsw._isIgnored(linkTarget)) return this.fsw._emitReady();
  9129. this.fsw._incrReadyCount();
  9130. this._addToFsEvents(linkTarget || linkPath, (path) => {
  9131. let aliasedPath = linkPath;
  9132. if (linkTarget && linkTarget !== DOT_SLASH) aliasedPath = path.replace(linkTarget, linkPath);
  9133. else if (path !== DOT_SLASH) aliasedPath = sysPath$1.join(linkPath, path);
  9134. return transform(aliasedPath);
  9135. }, false, curDepth);
  9136. } catch (error) {
  9137. if (this.fsw._handleError(error)) return this.fsw._emitReady();
  9138. }
  9139. }
  9140. /**
  9141. *
  9142. * @param {Path} newPath
  9143. * @param {fs.Stats} stats
  9144. */
  9145. emitAdd(newPath, stats, processPath, opts, forceAdd) {
  9146. const pp = processPath(newPath);
  9147. const isDir = stats.isDirectory();
  9148. const dirObj = this.fsw._getWatchedDir(sysPath$1.dirname(pp));
  9149. const base = sysPath$1.basename(pp);
  9150. if (isDir) this.fsw._getWatchedDir(pp);
  9151. if (dirObj.has(base)) return;
  9152. dirObj.add(base);
  9153. if (!opts.ignoreInitial || forceAdd === true) this.fsw._emit(isDir ? EV_ADD_DIR : EV_ADD, pp, stats);
  9154. }
  9155. initWatch(realPath, path, wh, processPath) {
  9156. if (this.fsw.closed) return;
  9157. const closer = this._watchWithFsEvents(wh.watchPath, sysPath$1.resolve(realPath || wh.watchPath), processPath, wh.globFilter);
  9158. this.fsw._addPathCloser(path, closer);
  9159. }
  9160. /**
  9161. * Handle added path with fsevents
  9162. * @param {String} path file/dir path or glob pattern
  9163. * @param {Function|Boolean=} transform converts working path to what the user expects
  9164. * @param {Boolean=} forceAdd ensure add is emitted
  9165. * @param {Number=} priorDepth Level of subdirectories already traversed.
  9166. * @returns {Promise<void>}
  9167. */
  9168. async _addToFsEvents(path, transform, forceAdd, priorDepth) {
  9169. if (this.fsw.closed) return;
  9170. const opts = this.fsw.options;
  9171. const processPath = typeof transform === FUNCTION_TYPE ? transform : IDENTITY_FN;
  9172. const wh = this.fsw._getWatchHelpers(path);
  9173. try {
  9174. const stats = await statMethods[wh.statMethod](wh.watchPath);
  9175. if (this.fsw.closed) return;
  9176. if (this.fsw._isIgnored(wh.watchPath, stats)) throw null;
  9177. if (stats.isDirectory()) {
  9178. if (!wh.globFilter) this.emitAdd(processPath(path), stats, processPath, opts, forceAdd);
  9179. if (priorDepth && priorDepth > opts.depth) return;
  9180. this.fsw._readdirp(wh.watchPath, {
  9181. fileFilter: (entry) => wh.filterPath(entry),
  9182. directoryFilter: (entry) => wh.filterDir(entry),
  9183. ...Depth(opts.depth - (priorDepth || 0))
  9184. }).on(STR_DATA, (entry) => {
  9185. if (this.fsw.closed) return;
  9186. if (entry.stats.isDirectory() && !wh.filterPath(entry)) return;
  9187. const joinedPath = sysPath$1.join(wh.watchPath, entry.path);
  9188. const { fullPath } = entry;
  9189. if (wh.followSymlinks && entry.stats.isSymbolicLink()) {
  9190. const curDepth = opts.depth === void 0 ? void 0 : calcDepth(joinedPath, sysPath$1.resolve(wh.watchPath)) + 1;
  9191. this._handleFsEventsSymlink(joinedPath, fullPath, processPath, curDepth);
  9192. } else this.emitAdd(joinedPath, entry.stats, processPath, opts, forceAdd);
  9193. }).on(EV_ERROR, EMPTY_FN).on(STR_END, () => {
  9194. this.fsw._emitReady();
  9195. });
  9196. } else {
  9197. this.emitAdd(wh.watchPath, stats, processPath, opts, forceAdd);
  9198. this.fsw._emitReady();
  9199. }
  9200. } catch (error) {
  9201. if (!error || this.fsw._handleError(error)) {
  9202. this.fsw._emitReady();
  9203. this.fsw._emitReady();
  9204. }
  9205. }
  9206. if (opts.persistent && forceAdd !== true) if (typeof transform === FUNCTION_TYPE) this.initWatch(void 0, path, wh, processPath);
  9207. else {
  9208. let realPath;
  9209. try {
  9210. realPath = await realpath(wh.watchPath);
  9211. } catch (e) {}
  9212. this.initWatch(realPath, path, wh, processPath);
  9213. }
  9214. }
  9215. };
  9216. module.exports = FsEventsHandler;
  9217. module.exports.canUse = canUse;
  9218. }));
  9219. //#endregion
  9220. //#region ../../node_modules/.pnpm/chokidar@3.6.0_patch_hash=8a4f9e2b397e6034b91a0508faae3cecb97f222313faa129d7cb0eb71e9d0e84/node_modules/chokidar/index.js
  9221. var require_chokidar = /* @__PURE__ */ __commonJSMin(((exports) => {
  9222. const { EventEmitter: EventEmitter$3 } = __require("events");
  9223. const fs$7 = __require("fs");
  9224. const sysPath = __require("path");
  9225. const { promisify: promisify$1 } = __require("util");
  9226. const readdirp = require_readdirp();
  9227. const anymatch = require_anymatch().default;
  9228. const globParent = require_glob_parent();
  9229. const isGlob = require_is_glob();
  9230. const braces = require_braces();
  9231. const normalizePath = require_normalize_path();
  9232. const NodeFsHandler = require_nodefs_handler();
  9233. const FsEventsHandler = require_fsevents_handler();
  9234. const { EV_ALL, EV_READY, EV_ADD, EV_CHANGE, EV_UNLINK, EV_ADD_DIR, EV_UNLINK_DIR, EV_RAW, EV_ERROR, STR_CLOSE, STR_END, BACK_SLASH_RE, DOUBLE_SLASH_RE, SLASH_OR_BACK_SLASH_RE, DOT_RE, REPLACER_RE, SLASH, SLASH_SLASH, BRACE_START, BANG, ONE_DOT, TWO_DOTS, GLOBSTAR, SLASH_GLOBSTAR, ANYMATCH_OPTS, STRING_TYPE, FUNCTION_TYPE, EMPTY_STR, EMPTY_FN, isWindows, isMacos, isIBMi } = require_constants$1();
  9235. const stat = promisify$1(fs$7.stat);
  9236. const readdir = promisify$1(fs$7.readdir);
  9237. /**
  9238. * @typedef {String} Path
  9239. * @typedef {'all'|'add'|'addDir'|'change'|'unlink'|'unlinkDir'|'raw'|'error'|'ready'} EventName
  9240. * @typedef {'readdir'|'watch'|'add'|'remove'|'change'} ThrottleType
  9241. */
  9242. /**
  9243. *
  9244. * @typedef {Object} WatchHelpers
  9245. * @property {Boolean} followSymlinks
  9246. * @property {'stat'|'lstat'} statMethod
  9247. * @property {Path} path
  9248. * @property {Path} watchPath
  9249. * @property {Function} entryPath
  9250. * @property {Boolean} hasGlob
  9251. * @property {Object} globFilter
  9252. * @property {Function} filterPath
  9253. * @property {Function} filterDir
  9254. */
  9255. const arrify = (value = []) => Array.isArray(value) ? value : [value];
  9256. const flatten = (list, result = []) => {
  9257. list.forEach((item) => {
  9258. if (Array.isArray(item)) flatten(item, result);
  9259. else result.push(item);
  9260. });
  9261. return result;
  9262. };
  9263. const unifyPaths = (paths_) => {
  9264. /**
  9265. * @type {Array<String>}
  9266. */
  9267. const paths = flatten(arrify(paths_));
  9268. if (!paths.every((p) => typeof p === STRING_TYPE)) throw new TypeError(`Non-string provided as watch path: ${paths}`);
  9269. return paths.map(normalizePathToUnix);
  9270. };
  9271. const toUnix = (string) => {
  9272. let str = string.replace(BACK_SLASH_RE, SLASH);
  9273. let prepend = false;
  9274. if (str.startsWith(SLASH_SLASH)) prepend = true;
  9275. while (str.match(DOUBLE_SLASH_RE)) str = str.replace(DOUBLE_SLASH_RE, SLASH);
  9276. if (prepend) str = SLASH + str;
  9277. return str;
  9278. };
  9279. const normalizePathToUnix = (path) => toUnix(sysPath.normalize(toUnix(path)));
  9280. const normalizeIgnored = (cwd = EMPTY_STR) => (path) => {
  9281. if (typeof path !== STRING_TYPE) return path;
  9282. return normalizePathToUnix(sysPath.isAbsolute(path) ? path : sysPath.join(cwd, path));
  9283. };
  9284. const getAbsolutePath = (path, cwd) => {
  9285. if (sysPath.isAbsolute(path)) return path;
  9286. if (path.startsWith(BANG)) return BANG + sysPath.join(cwd, path.slice(1));
  9287. return sysPath.join(cwd, path);
  9288. };
  9289. const undef = (opts, key) => opts[key] === void 0;
  9290. /**
  9291. * Directory entry.
  9292. * @property {Path} path
  9293. * @property {Set<Path>} items
  9294. */
  9295. var DirEntry = class {
  9296. /**
  9297. * @param {Path} dir
  9298. * @param {Function} removeWatcher
  9299. */
  9300. constructor(dir, removeWatcher) {
  9301. this.path = dir;
  9302. this._removeWatcher = removeWatcher;
  9303. /** @type {Set<Path>} */
  9304. this.items = /* @__PURE__ */ new Set();
  9305. }
  9306. add(item) {
  9307. const { items } = this;
  9308. if (!items) return;
  9309. if (item !== ONE_DOT && item !== TWO_DOTS) items.add(item);
  9310. }
  9311. async remove(item) {
  9312. const { items } = this;
  9313. if (!items) return;
  9314. items.delete(item);
  9315. if (items.size > 0) return;
  9316. const dir = this.path;
  9317. try {
  9318. await readdir(dir);
  9319. } catch (err) {
  9320. if (this._removeWatcher) this._removeWatcher(sysPath.dirname(dir), sysPath.basename(dir));
  9321. }
  9322. }
  9323. has(item) {
  9324. const { items } = this;
  9325. if (!items) return;
  9326. return items.has(item);
  9327. }
  9328. /**
  9329. * @returns {Array<String>}
  9330. */
  9331. getChildren() {
  9332. const { items } = this;
  9333. if (!items) return;
  9334. return [...items.values()];
  9335. }
  9336. dispose() {
  9337. this.items.clear();
  9338. delete this.path;
  9339. delete this._removeWatcher;
  9340. delete this.items;
  9341. Object.freeze(this);
  9342. }
  9343. };
  9344. const STAT_METHOD_F = "stat";
  9345. const STAT_METHOD_L = "lstat";
  9346. var WatchHelper = class {
  9347. constructor(path, watchPath, follow, fsw) {
  9348. this.fsw = fsw;
  9349. this.path = path = path.replace(REPLACER_RE, EMPTY_STR);
  9350. this.watchPath = watchPath;
  9351. this.fullWatchPath = sysPath.resolve(watchPath);
  9352. this.hasGlob = watchPath !== path;
  9353. /** @type {object|boolean} */
  9354. if (path === EMPTY_STR) this.hasGlob = false;
  9355. this.globSymlink = this.hasGlob && follow ? void 0 : false;
  9356. this.globFilter = this.hasGlob ? anymatch(path, void 0, ANYMATCH_OPTS) : false;
  9357. this.dirParts = this.getDirParts(path);
  9358. this.dirParts.forEach((parts) => {
  9359. if (parts.length > 1) parts.pop();
  9360. });
  9361. this.followSymlinks = follow;
  9362. this.statMethod = follow ? STAT_METHOD_F : STAT_METHOD_L;
  9363. }
  9364. checkGlobSymlink(entry) {
  9365. if (this.globSymlink === void 0) this.globSymlink = entry.fullParentDir === this.fullWatchPath ? false : {
  9366. realPath: entry.fullParentDir,
  9367. linkPath: this.fullWatchPath
  9368. };
  9369. if (this.globSymlink) return entry.fullPath.replace(this.globSymlink.realPath, this.globSymlink.linkPath);
  9370. return entry.fullPath;
  9371. }
  9372. entryPath(entry) {
  9373. return sysPath.join(this.watchPath, sysPath.relative(this.watchPath, this.checkGlobSymlink(entry)));
  9374. }
  9375. filterPath(entry) {
  9376. const { stats } = entry;
  9377. if (stats && stats.isSymbolicLink()) return this.filterDir(entry);
  9378. const resolvedPath = this.entryPath(entry);
  9379. return (this.hasGlob && typeof this.globFilter === FUNCTION_TYPE ? this.globFilter(resolvedPath) : true) && this.fsw._isntIgnored(resolvedPath, stats) && this.fsw._hasReadPermissions(stats);
  9380. }
  9381. getDirParts(path) {
  9382. if (!this.hasGlob) return [];
  9383. const parts = [];
  9384. (path.includes(BRACE_START) ? braces.expand(path) : [path]).forEach((path) => {
  9385. parts.push(sysPath.relative(this.watchPath, path).split(SLASH_OR_BACK_SLASH_RE));
  9386. });
  9387. return parts;
  9388. }
  9389. filterDir(entry) {
  9390. if (this.hasGlob) {
  9391. const entryParts = this.getDirParts(this.checkGlobSymlink(entry));
  9392. let globstar = false;
  9393. this.unmatchedGlob = !this.dirParts.some((parts) => {
  9394. return parts.every((part, i) => {
  9395. if (part === GLOBSTAR) globstar = true;
  9396. return globstar || !entryParts[0][i] || anymatch(part, entryParts[0][i], ANYMATCH_OPTS);
  9397. });
  9398. });
  9399. }
  9400. return !this.unmatchedGlob && this.fsw._isntIgnored(this.entryPath(entry), entry.stats);
  9401. }
  9402. };
  9403. /**
  9404. * Watches files & directories for changes. Emitted events:
  9405. * `add`, `addDir`, `change`, `unlink`, `unlinkDir`, `all`, `error`
  9406. *
  9407. * new FSWatcher()
  9408. * .add(directories)
  9409. * .on('add', path => log('File', path, 'was added'))
  9410. */
  9411. var FSWatcher = class extends EventEmitter$3 {
  9412. constructor(_opts) {
  9413. super();
  9414. const opts = {};
  9415. if (_opts) Object.assign(opts, _opts);
  9416. /** @type {Map<String, DirEntry>} */
  9417. this._watched = /* @__PURE__ */ new Map();
  9418. /** @type {Map<String, Array>} */
  9419. this._closers = /* @__PURE__ */ new Map();
  9420. /** @type {Set<String>} */
  9421. this._ignoredPaths = /* @__PURE__ */ new Set();
  9422. /** @type {Map<ThrottleType, Map>} */
  9423. this._throttled = /* @__PURE__ */ new Map();
  9424. /** @type {Map<Path, String|Boolean>} */
  9425. this._symlinkPaths = /* @__PURE__ */ new Map();
  9426. this._streams = /* @__PURE__ */ new Set();
  9427. this.closed = false;
  9428. if (undef(opts, "persistent")) opts.persistent = true;
  9429. if (undef(opts, "ignoreInitial")) opts.ignoreInitial = false;
  9430. if (undef(opts, "ignorePermissionErrors")) opts.ignorePermissionErrors = false;
  9431. if (undef(opts, "interval")) opts.interval = 100;
  9432. if (undef(opts, "binaryInterval")) opts.binaryInterval = 300;
  9433. if (undef(opts, "disableGlobbing")) opts.disableGlobbing = false;
  9434. opts.enableBinaryInterval = opts.binaryInterval !== opts.interval;
  9435. if (undef(opts, "useFsEvents")) opts.useFsEvents = !opts.usePolling;
  9436. if (!FsEventsHandler.canUse()) opts.useFsEvents = false;
  9437. if (undef(opts, "usePolling") && !opts.useFsEvents) opts.usePolling = isMacos;
  9438. if (isIBMi) opts.usePolling = true;
  9439. const envPoll = process.env.CHOKIDAR_USEPOLLING;
  9440. if (envPoll !== void 0) {
  9441. const envLower = envPoll.toLowerCase();
  9442. if (envLower === "false" || envLower === "0") opts.usePolling = false;
  9443. else if (envLower === "true" || envLower === "1") opts.usePolling = true;
  9444. else opts.usePolling = !!envLower;
  9445. }
  9446. const envInterval = process.env.CHOKIDAR_INTERVAL;
  9447. if (envInterval) opts.interval = Number.parseInt(envInterval, 10);
  9448. if (undef(opts, "atomic")) opts.atomic = !opts.usePolling && !opts.useFsEvents;
  9449. if (opts.atomic) this._pendingUnlinks = /* @__PURE__ */ new Map();
  9450. if (undef(opts, "followSymlinks")) opts.followSymlinks = true;
  9451. if (undef(opts, "awaitWriteFinish")) opts.awaitWriteFinish = false;
  9452. if (opts.awaitWriteFinish === true) opts.awaitWriteFinish = {};
  9453. const awf = opts.awaitWriteFinish;
  9454. if (awf) {
  9455. if (!awf.stabilityThreshold) awf.stabilityThreshold = 2e3;
  9456. if (!awf.pollInterval) awf.pollInterval = 100;
  9457. this._pendingWrites = /* @__PURE__ */ new Map();
  9458. }
  9459. if (opts.ignored) opts.ignored = arrify(opts.ignored);
  9460. let readyCalls = 0;
  9461. this._emitReady = () => {
  9462. readyCalls++;
  9463. if (readyCalls >= this._readyCount) {
  9464. this._emitReady = EMPTY_FN;
  9465. this._readyEmitted = true;
  9466. process.nextTick(() => this.emit(EV_READY));
  9467. }
  9468. };
  9469. this._emitRaw = (...args) => this.emit(EV_RAW, ...args);
  9470. this._readyEmitted = false;
  9471. this.options = opts;
  9472. if (opts.useFsEvents) this._fsEventsHandler = new FsEventsHandler(this);
  9473. else this._nodeFsHandler = new NodeFsHandler(this);
  9474. Object.freeze(opts);
  9475. }
  9476. /**
  9477. * Adds paths to be watched on an existing FSWatcher instance
  9478. * @param {Path|Array<Path>} paths_
  9479. * @param {String=} _origAdd private; for handling non-existent paths to be watched
  9480. * @param {Boolean=} _internal private; indicates a non-user add
  9481. * @returns {FSWatcher} for chaining
  9482. */
  9483. add(paths_, _origAdd, _internal) {
  9484. const { cwd, disableGlobbing } = this.options;
  9485. this.closed = false;
  9486. let paths = unifyPaths(paths_);
  9487. if (cwd) paths = paths.map((path) => {
  9488. const absPath = getAbsolutePath(path, cwd);
  9489. if (disableGlobbing || !isGlob(path)) return absPath;
  9490. return normalizePath(absPath);
  9491. });
  9492. paths = paths.filter((path) => {
  9493. if (path.startsWith(BANG)) {
  9494. this._ignoredPaths.add(path.slice(1));
  9495. return false;
  9496. }
  9497. this._ignoredPaths.delete(path);
  9498. this._ignoredPaths.delete(path + SLASH_GLOBSTAR);
  9499. this._userIgnored = void 0;
  9500. return true;
  9501. });
  9502. if (this.options.useFsEvents && this._fsEventsHandler) {
  9503. if (!this._readyCount) this._readyCount = paths.length;
  9504. if (this.options.persistent) this._readyCount += paths.length;
  9505. paths.forEach((path) => this._fsEventsHandler._addToFsEvents(path));
  9506. } else {
  9507. if (!this._readyCount) this._readyCount = 0;
  9508. this._readyCount += paths.length;
  9509. Promise.all(paths.map(async (path) => {
  9510. const res = await this._nodeFsHandler._addToNodeFs(path, !_internal, 0, 0, _origAdd);
  9511. if (res) this._emitReady();
  9512. return res;
  9513. })).then((results) => {
  9514. if (this.closed) return;
  9515. results.filter((item) => item).forEach((item) => {
  9516. this.add(sysPath.dirname(item), sysPath.basename(_origAdd || item));
  9517. });
  9518. });
  9519. }
  9520. return this;
  9521. }
  9522. /**
  9523. * Close watchers or start ignoring events from specified paths.
  9524. * @param {Path|Array<Path>} paths_ - string or array of strings, file/directory paths and/or globs
  9525. * @returns {FSWatcher} for chaining
  9526. */
  9527. unwatch(paths_) {
  9528. if (this.closed) return this;
  9529. const paths = unifyPaths(paths_);
  9530. const { cwd } = this.options;
  9531. paths.forEach((path) => {
  9532. if (!sysPath.isAbsolute(path) && !this._closers.has(path)) {
  9533. if (cwd) path = sysPath.join(cwd, path);
  9534. path = sysPath.resolve(path);
  9535. }
  9536. this._closePath(path);
  9537. this._ignoredPaths.add(path);
  9538. if (this._watched.has(path)) this._ignoredPaths.add(path + SLASH_GLOBSTAR);
  9539. this._userIgnored = void 0;
  9540. });
  9541. return this;
  9542. }
  9543. /**
  9544. * Close watchers and remove all listeners from watched paths.
  9545. * @returns {Promise<void>}.
  9546. */
  9547. close() {
  9548. if (this.closed) return this._closePromise;
  9549. this.closed = true;
  9550. this.removeAllListeners();
  9551. const closers = [];
  9552. this._closers.forEach((closerList) => closerList.forEach((closer) => {
  9553. const promise = closer();
  9554. if (promise instanceof Promise) closers.push(promise);
  9555. }));
  9556. this._streams.forEach((stream) => stream.destroy());
  9557. this._userIgnored = void 0;
  9558. this._readyCount = 0;
  9559. this._readyEmitted = false;
  9560. this._watched.forEach((dirent) => dirent.dispose());
  9561. [
  9562. "closers",
  9563. "watched",
  9564. "streams",
  9565. "symlinkPaths",
  9566. "throttled"
  9567. ].forEach((key) => {
  9568. this[`_${key}`].clear();
  9569. });
  9570. this._closePromise = closers.length ? Promise.all(closers).then(() => void 0) : Promise.resolve();
  9571. return this._closePromise;
  9572. }
  9573. /**
  9574. * Expose list of watched paths
  9575. * @returns {Object} for chaining
  9576. */
  9577. getWatched() {
  9578. const watchList = {};
  9579. this._watched.forEach((entry, dir) => {
  9580. const key = this.options.cwd ? sysPath.relative(this.options.cwd, dir) : dir;
  9581. watchList[key || ONE_DOT] = entry.getChildren().sort();
  9582. });
  9583. return watchList;
  9584. }
  9585. emitWithAll(event, args) {
  9586. this.emit(...args);
  9587. if (event !== EV_ERROR) this.emit(EV_ALL, ...args);
  9588. }
  9589. /**
  9590. * Normalize and emit events.
  9591. * Calling _emit DOES NOT MEAN emit() would be called!
  9592. * @param {EventName} event Type of event
  9593. * @param {Path} path File or directory path
  9594. * @param {*=} val1 arguments to be passed with event
  9595. * @param {*=} val2
  9596. * @param {*=} val3
  9597. * @returns the error if defined, otherwise the value of the FSWatcher instance's `closed` flag
  9598. */
  9599. async _emit(event, path, val1, val2, val3) {
  9600. if (this.closed) return;
  9601. const opts = this.options;
  9602. if (isWindows) path = sysPath.normalize(path);
  9603. if (opts.cwd) path = sysPath.relative(opts.cwd, path);
  9604. /** @type Array<any> */
  9605. const args = [event, path];
  9606. if (val3 !== void 0) args.push(val1, val2, val3);
  9607. else if (val2 !== void 0) args.push(val1, val2);
  9608. else if (val1 !== void 0) args.push(val1);
  9609. const awf = opts.awaitWriteFinish;
  9610. let pw;
  9611. if (awf && (pw = this._pendingWrites.get(path))) {
  9612. pw.lastChange = /* @__PURE__ */ new Date();
  9613. return this;
  9614. }
  9615. if (opts.atomic) {
  9616. if (event === EV_UNLINK) {
  9617. this._pendingUnlinks.set(path, args);
  9618. setTimeout(() => {
  9619. this._pendingUnlinks.forEach((entry, path) => {
  9620. this.emit(...entry);
  9621. this.emit(EV_ALL, ...entry);
  9622. this._pendingUnlinks.delete(path);
  9623. });
  9624. }, typeof opts.atomic === "number" ? opts.atomic : 100);
  9625. return this;
  9626. }
  9627. if (event === EV_ADD && this._pendingUnlinks.has(path)) {
  9628. event = args[0] = EV_CHANGE;
  9629. this._pendingUnlinks.delete(path);
  9630. }
  9631. }
  9632. if (awf && (event === EV_ADD || event === EV_CHANGE) && this._readyEmitted) {
  9633. const awfEmit = (err, stats) => {
  9634. if (err) {
  9635. event = args[0] = EV_ERROR;
  9636. args[1] = err;
  9637. this.emitWithAll(event, args);
  9638. } else if (stats) {
  9639. if (args.length > 2) args[2] = stats;
  9640. else args.push(stats);
  9641. this.emitWithAll(event, args);
  9642. }
  9643. };
  9644. this._awaitWriteFinish(path, awf.stabilityThreshold, event, awfEmit);
  9645. return this;
  9646. }
  9647. if (event === EV_CHANGE) {
  9648. if (!this._throttle(EV_CHANGE, path, 50)) return this;
  9649. }
  9650. if (opts.alwaysStat && val1 === void 0 && (event === EV_ADD || event === EV_ADD_DIR || event === EV_CHANGE)) {
  9651. const fullPath = opts.cwd ? sysPath.join(opts.cwd, path) : path;
  9652. let stats;
  9653. try {
  9654. stats = await stat(fullPath);
  9655. } catch (err) {}
  9656. if (!stats || this.closed) return;
  9657. args.push(stats);
  9658. }
  9659. this.emitWithAll(event, args);
  9660. return this;
  9661. }
  9662. /**
  9663. * Common handler for errors
  9664. * @param {Error} error
  9665. * @returns {Error|Boolean} The error if defined, otherwise the value of the FSWatcher instance's `closed` flag
  9666. */
  9667. _handleError(error) {
  9668. const code = error && error.code;
  9669. if (error && code !== "ENOENT" && code !== "ENOTDIR" && (!this.options.ignorePermissionErrors || code !== "EPERM" && code !== "EACCES")) this.emit(EV_ERROR, error);
  9670. return error || this.closed;
  9671. }
  9672. /**
  9673. * Helper utility for throttling
  9674. * @param {ThrottleType} actionType type being throttled
  9675. * @param {Path} path being acted upon
  9676. * @param {Number} timeout duration of time to suppress duplicate actions
  9677. * @returns {Object|false} tracking object or false if action should be suppressed
  9678. */
  9679. _throttle(actionType, path, timeout) {
  9680. if (!this._throttled.has(actionType)) this._throttled.set(actionType, /* @__PURE__ */ new Map());
  9681. /** @type {Map<Path, Object>} */
  9682. const action = this._throttled.get(actionType);
  9683. /** @type {Object} */
  9684. const actionPath = action.get(path);
  9685. if (actionPath) {
  9686. actionPath.count++;
  9687. return false;
  9688. }
  9689. let timeoutObject;
  9690. const clear = () => {
  9691. const item = action.get(path);
  9692. const count = item ? item.count : 0;
  9693. action.delete(path);
  9694. clearTimeout(timeoutObject);
  9695. if (item) clearTimeout(item.timeoutObject);
  9696. return count;
  9697. };
  9698. timeoutObject = setTimeout(clear, timeout);
  9699. const thr = {
  9700. timeoutObject,
  9701. clear,
  9702. count: 0
  9703. };
  9704. action.set(path, thr);
  9705. return thr;
  9706. }
  9707. _incrReadyCount() {
  9708. return this._readyCount++;
  9709. }
  9710. /**
  9711. * Awaits write operation to finish.
  9712. * Polls a newly created file for size variations. When files size does not change for 'threshold' milliseconds calls callback.
  9713. * @param {Path} path being acted upon
  9714. * @param {Number} threshold Time in milliseconds a file size must be fixed before acknowledging write OP is finished
  9715. * @param {EventName} event
  9716. * @param {Function} awfEmit Callback to be called when ready for event to be emitted.
  9717. */
  9718. _awaitWriteFinish(path, threshold, event, awfEmit) {
  9719. let timeoutHandler;
  9720. let fullPath = path;
  9721. if (this.options.cwd && !sysPath.isAbsolute(path)) fullPath = sysPath.join(this.options.cwd, path);
  9722. const now = /* @__PURE__ */ new Date();
  9723. const awaitWriteFinish = (prevStat) => {
  9724. fs$7.stat(fullPath, (err, curStat) => {
  9725. if (err || !this._pendingWrites.has(path)) {
  9726. if (err && err.code !== "ENOENT") awfEmit(err);
  9727. return;
  9728. }
  9729. const now = Number(/* @__PURE__ */ new Date());
  9730. if (prevStat && curStat.size !== prevStat.size) this._pendingWrites.get(path).lastChange = now;
  9731. if (now - this._pendingWrites.get(path).lastChange >= threshold) {
  9732. this._pendingWrites.delete(path);
  9733. awfEmit(void 0, curStat);
  9734. } else timeoutHandler = setTimeout(awaitWriteFinish, this.options.awaitWriteFinish.pollInterval, curStat);
  9735. });
  9736. };
  9737. if (!this._pendingWrites.has(path)) {
  9738. this._pendingWrites.set(path, {
  9739. lastChange: now,
  9740. cancelWait: () => {
  9741. this._pendingWrites.delete(path);
  9742. clearTimeout(timeoutHandler);
  9743. return event;
  9744. }
  9745. });
  9746. timeoutHandler = setTimeout(awaitWriteFinish, this.options.awaitWriteFinish.pollInterval);
  9747. }
  9748. }
  9749. _getGlobIgnored() {
  9750. return [...this._ignoredPaths.values()];
  9751. }
  9752. /**
  9753. * Determines whether user has asked to ignore this path.
  9754. * @param {Path} path filepath or dir
  9755. * @param {fs.Stats=} stats result of fs.stat
  9756. * @returns {Boolean}
  9757. */
  9758. _isIgnored(path, stats) {
  9759. if (this.options.atomic && DOT_RE.test(path)) return true;
  9760. if (!this._userIgnored) {
  9761. const { cwd } = this.options;
  9762. const ign = this.options.ignored;
  9763. const ignored = ign && ign.map(normalizeIgnored(cwd));
  9764. const paths = arrify(ignored).filter((path) => typeof path === STRING_TYPE && !isGlob(path)).map((path) => path + SLASH_GLOBSTAR);
  9765. this._userIgnored = anymatch(this._getGlobIgnored().map(normalizeIgnored(cwd)).concat(ignored, paths), void 0, ANYMATCH_OPTS);
  9766. }
  9767. return this._userIgnored([path, stats]);
  9768. }
  9769. _isntIgnored(path, stat) {
  9770. return !this._isIgnored(path, stat);
  9771. }
  9772. /**
  9773. * Provides a set of common helpers and properties relating to symlink and glob handling.
  9774. * @param {Path} path file, directory, or glob pattern being watched
  9775. * @param {Number=} depth at any depth > 0, this isn't a glob
  9776. * @returns {WatchHelper} object containing helpers for this path
  9777. */
  9778. _getWatchHelpers(path, depth) {
  9779. const watchPath = depth || this.options.disableGlobbing || !isGlob(path) ? path : globParent(path);
  9780. const follow = this.options.followSymlinks;
  9781. return new WatchHelper(path, watchPath, follow, this);
  9782. }
  9783. /**
  9784. * Provides directory tracking objects
  9785. * @param {String} directory path of the directory
  9786. * @returns {DirEntry} the directory's tracking object
  9787. */
  9788. _getWatchedDir(directory) {
  9789. if (!this._boundRemove) this._boundRemove = this._remove.bind(this);
  9790. const dir = sysPath.resolve(directory);
  9791. if (!this._watched.has(dir)) this._watched.set(dir, new DirEntry(dir, this._boundRemove));
  9792. return this._watched.get(dir);
  9793. }
  9794. /**
  9795. * Check for read permissions.
  9796. * Based on this answer on SO: https://stackoverflow.com/a/11781404/1358405
  9797. * @param {fs.Stats} stats - object, result of fs_stat
  9798. * @returns {Boolean} indicates whether the file can be read
  9799. */
  9800. _hasReadPermissions(stats) {
  9801. if (this.options.ignorePermissionErrors) return true;
  9802. const st = (stats && Number.parseInt(stats.mode, 10)) & 511;
  9803. const it = Number.parseInt(st.toString(8)[0], 10);
  9804. return Boolean(4 & it);
  9805. }
  9806. /**
  9807. * Handles emitting unlink events for
  9808. * files and directories, and via recursion, for
  9809. * files and directories within directories that are unlinked
  9810. * @param {String} directory within which the following item is located
  9811. * @param {String} item base path of item/directory
  9812. * @returns {void}
  9813. */
  9814. _remove(directory, item, isDirectory) {
  9815. const path = sysPath.join(directory, item);
  9816. const fullPath = sysPath.resolve(path);
  9817. isDirectory = isDirectory != null ? isDirectory : this._watched.has(path) || this._watched.has(fullPath);
  9818. if (!this._throttle("remove", path, 100)) return;
  9819. if (!isDirectory && !this.options.useFsEvents && this._watched.size === 1) this.add(directory, item, true);
  9820. this._getWatchedDir(path).getChildren().forEach((nested) => this._remove(path, nested));
  9821. const parent = this._getWatchedDir(directory);
  9822. const wasTracked = parent.has(item);
  9823. parent.remove(item);
  9824. if (this._symlinkPaths.has(fullPath)) this._symlinkPaths.delete(fullPath);
  9825. let relPath = path;
  9826. if (this.options.cwd) relPath = sysPath.relative(this.options.cwd, path);
  9827. if (this.options.awaitWriteFinish && this._pendingWrites.has(relPath)) {
  9828. if (this._pendingWrites.get(relPath).cancelWait() === EV_ADD) return;
  9829. }
  9830. this._watched.delete(path);
  9831. this._watched.delete(fullPath);
  9832. const eventName = isDirectory ? EV_UNLINK_DIR : EV_UNLINK;
  9833. if (wasTracked && !this._isIgnored(path)) this._emit(eventName, path);
  9834. if (!this.options.useFsEvents) this._closePath(path);
  9835. }
  9836. /**
  9837. * Closes all watchers for a path
  9838. * @param {Path} path
  9839. */
  9840. _closePath(path) {
  9841. this._closeFile(path);
  9842. const dir = sysPath.dirname(path);
  9843. this._getWatchedDir(dir).remove(sysPath.basename(path));
  9844. }
  9845. /**
  9846. * Closes only file-specific watchers
  9847. * @param {Path} path
  9848. */
  9849. _closeFile(path) {
  9850. const closers = this._closers.get(path);
  9851. if (!closers) return;
  9852. closers.forEach((closer) => closer());
  9853. this._closers.delete(path);
  9854. }
  9855. /**
  9856. *
  9857. * @param {Path} path
  9858. * @param {Function} closer
  9859. */
  9860. _addPathCloser(path, closer) {
  9861. if (!closer) return;
  9862. let list = this._closers.get(path);
  9863. if (!list) {
  9864. list = [];
  9865. this._closers.set(path, list);
  9866. }
  9867. list.push(closer);
  9868. }
  9869. _readdirp(root, opts) {
  9870. if (this.closed) return;
  9871. let stream = readdirp(root, {
  9872. type: EV_ALL,
  9873. alwaysStat: true,
  9874. lstat: true,
  9875. ...opts
  9876. });
  9877. this._streams.add(stream);
  9878. stream.once(STR_CLOSE, () => {
  9879. stream = void 0;
  9880. });
  9881. stream.once(STR_END, () => {
  9882. if (stream) {
  9883. this._streams.delete(stream);
  9884. stream = void 0;
  9885. }
  9886. });
  9887. return stream;
  9888. }
  9889. };
  9890. /**
  9891. * Instantiates watcher with paths to be tracked.
  9892. * @param {String|Array<String>} paths file/directory paths and/or globs
  9893. * @param {Object=} options chokidar opts
  9894. * @returns an instance of FSWatcher for chaining.
  9895. */
  9896. const watch = (paths, options) => {
  9897. const watcher = new FSWatcher(options);
  9898. watcher.add(paths);
  9899. return watcher;
  9900. };
  9901. exports.watch = watch;
  9902. }));
  9903. //#endregion
  9904. //#region ../../node_modules/.pnpm/shell-quote@1.8.3/node_modules/shell-quote/quote.js
  9905. var require_quote = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  9906. module.exports = function quote(xs) {
  9907. return xs.map(function(s) {
  9908. if (s === "") return "''";
  9909. if (s && typeof s === "object") return s.op.replace(/(.)/g, "\\$1");
  9910. if (/["\s\\]/.test(s) && !/'/.test(s)) return "'" + s.replace(/(['])/g, "\\$1") + "'";
  9911. if (/["'\s]/.test(s)) return "\"" + s.replace(/(["\\$`!])/g, "\\$1") + "\"";
  9912. return String(s).replace(/([A-Za-z]:)?([#!"$&'()*,:;<=>?@[\\\]^`{|}])/g, "$1\\$2");
  9913. }).join(" ");
  9914. };
  9915. }));
  9916. //#endregion
  9917. //#region ../../node_modules/.pnpm/shell-quote@1.8.3/node_modules/shell-quote/parse.js
  9918. var require_parse$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  9919. var CONTROL = "(?:" + [
  9920. "\\|\\|",
  9921. "\\&\\&",
  9922. ";;",
  9923. "\\|\\&",
  9924. "\\<\\(",
  9925. "\\<\\<\\<",
  9926. ">>",
  9927. ">\\&",
  9928. "<\\&",
  9929. "[&;()|<>]"
  9930. ].join("|") + ")";
  9931. var controlRE = new RegExp("^" + CONTROL + "$");
  9932. var META = "|&;()<> \\t";
  9933. var SINGLE_QUOTE = "\"((\\\\\"|[^\"])*?)\"";
  9934. var DOUBLE_QUOTE = "'((\\\\'|[^'])*?)'";
  9935. var hash = /^#$/;
  9936. var SQ = "'";
  9937. var DQ = "\"";
  9938. var DS = "$";
  9939. var TOKEN = "";
  9940. var mult = 4294967296;
  9941. for (var i = 0; i < 4; i++) TOKEN += (mult * Math.random()).toString(16);
  9942. var startsWithToken = new RegExp("^" + TOKEN);
  9943. function matchAll(s, r) {
  9944. var origIndex = r.lastIndex;
  9945. var matches = [];
  9946. var matchObj;
  9947. while (matchObj = r.exec(s)) {
  9948. matches.push(matchObj);
  9949. if (r.lastIndex === matchObj.index) r.lastIndex += 1;
  9950. }
  9951. r.lastIndex = origIndex;
  9952. return matches;
  9953. }
  9954. function getVar(env, pre, key) {
  9955. var r = typeof env === "function" ? env(key) : env[key];
  9956. if (typeof r === "undefined" && key != "") r = "";
  9957. else if (typeof r === "undefined") r = "$";
  9958. if (typeof r === "object") return pre + TOKEN + JSON.stringify(r) + TOKEN;
  9959. return pre + r;
  9960. }
  9961. function parseInternal(string, env, opts) {
  9962. if (!opts) opts = {};
  9963. var BS = opts.escape || "\\";
  9964. var BAREWORD = "(\\" + BS + "['\"" + META + "]|[^\\s'\"" + META + "])+";
  9965. var matches = matchAll(string, new RegExp(["(" + CONTROL + ")", "(" + BAREWORD + "|" + SINGLE_QUOTE + "|" + DOUBLE_QUOTE + ")+"].join("|"), "g"));
  9966. if (matches.length === 0) return [];
  9967. if (!env) env = {};
  9968. var commented = false;
  9969. return matches.map(function(match) {
  9970. var s = match[0];
  9971. if (!s || commented) return;
  9972. if (controlRE.test(s)) return { op: s };
  9973. var quote = false;
  9974. var esc = false;
  9975. var out = "";
  9976. var isGlob = false;
  9977. var i;
  9978. function parseEnvVar() {
  9979. i += 1;
  9980. var varend;
  9981. var varname;
  9982. var char = s.charAt(i);
  9983. if (char === "{") {
  9984. i += 1;
  9985. if (s.charAt(i) === "}") throw new Error("Bad substitution: " + s.slice(i - 2, i + 1));
  9986. varend = s.indexOf("}", i);
  9987. if (varend < 0) throw new Error("Bad substitution: " + s.slice(i));
  9988. varname = s.slice(i, varend);
  9989. i = varend;
  9990. } else if (/[*@#?$!_-]/.test(char)) {
  9991. varname = char;
  9992. i += 1;
  9993. } else {
  9994. var slicedFromI = s.slice(i);
  9995. varend = slicedFromI.match(/[^\w\d_]/);
  9996. if (!varend) {
  9997. varname = slicedFromI;
  9998. i = s.length;
  9999. } else {
  10000. varname = slicedFromI.slice(0, varend.index);
  10001. i += varend.index - 1;
  10002. }
  10003. }
  10004. return getVar(env, "", varname);
  10005. }
  10006. for (i = 0; i < s.length; i++) {
  10007. var c = s.charAt(i);
  10008. isGlob = isGlob || !quote && (c === "*" || c === "?");
  10009. if (esc) {
  10010. out += c;
  10011. esc = false;
  10012. } else if (quote) if (c === quote) quote = false;
  10013. else if (quote == SQ) out += c;
  10014. else if (c === BS) {
  10015. i += 1;
  10016. c = s.charAt(i);
  10017. if (c === DQ || c === BS || c === DS) out += c;
  10018. else out += BS + c;
  10019. } else if (c === DS) out += parseEnvVar();
  10020. else out += c;
  10021. else if (c === DQ || c === SQ) quote = c;
  10022. else if (controlRE.test(c)) return { op: s };
  10023. else if (hash.test(c)) {
  10024. commented = true;
  10025. var commentObj = { comment: string.slice(match.index + i + 1) };
  10026. if (out.length) return [out, commentObj];
  10027. return [commentObj];
  10028. } else if (c === BS) esc = true;
  10029. else if (c === DS) out += parseEnvVar();
  10030. else out += c;
  10031. }
  10032. if (isGlob) return {
  10033. op: "glob",
  10034. pattern: out
  10035. };
  10036. return out;
  10037. }).reduce(function(prev, arg) {
  10038. return typeof arg === "undefined" ? prev : prev.concat(arg);
  10039. }, []);
  10040. }
  10041. module.exports = function parse(s, env, opts) {
  10042. var mapped = parseInternal(s, env, opts);
  10043. if (typeof env !== "function") return mapped;
  10044. return mapped.reduce(function(acc, s) {
  10045. if (typeof s === "object") return acc.concat(s);
  10046. var xs = s.split(RegExp("(" + TOKEN + ".*?" + TOKEN + ")", "g"));
  10047. if (xs.length === 1) return acc.concat(xs[0]);
  10048. return acc.concat(xs.filter(Boolean).map(function(x) {
  10049. if (startsWithToken.test(x)) return JSON.parse(x.split(TOKEN)[1]);
  10050. return x;
  10051. }));
  10052. }, []);
  10053. };
  10054. }));
  10055. //#endregion
  10056. //#region ../../node_modules/.pnpm/shell-quote@1.8.3/node_modules/shell-quote/index.js
  10057. var require_shell_quote = /* @__PURE__ */ __commonJSMin(((exports) => {
  10058. exports.quote = require_quote();
  10059. exports.parse = require_parse$1();
  10060. }));
  10061. //#endregion
  10062. //#region ../../node_modules/.pnpm/launch-editor@2.13.2/node_modules/launch-editor/editor-info/macos.js
  10063. var require_macos = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  10064. module.exports = {
  10065. "/Applications/Atom.app/Contents/MacOS/Atom": "atom",
  10066. "/Applications/Atom Beta.app/Contents/MacOS/Atom Beta": "/Applications/Atom Beta.app/Contents/MacOS/Atom Beta",
  10067. "/Applications/Brackets.app/Contents/MacOS/Brackets": "brackets",
  10068. "/Applications/Sublime Text.app/Contents/MacOS/Sublime Text": "/Applications/Sublime Text.app/Contents/SharedSupport/bin/subl",
  10069. "/Applications/Sublime Text.app/Contents/MacOS/sublime_text": "/Applications/Sublime Text.app/Contents/SharedSupport/bin/subl",
  10070. "/Applications/Sublime Text 2.app/Contents/MacOS/Sublime Text 2": "/Applications/Sublime Text 2.app/Contents/SharedSupport/bin/subl",
  10071. "/Applications/Sublime Text Dev.app/Contents/MacOS/Sublime Text": "/Applications/Sublime Text Dev.app/Contents/SharedSupport/bin/subl",
  10072. "/Applications/Visual Studio Code.app/Contents/MacOS/Code": "code",
  10073. "/Applications/Visual Studio Code.app/Contents/MacOS/Electron": "code",
  10074. "/Applications/Visual Studio Code - Insiders.app/Contents/MacOS/Code - Insiders": "code-insiders",
  10075. "/Applications/Visual Studio Code - Insiders.app/Contents/MacOS/Electron": "code-insiders",
  10076. "/Applications/VSCodium.app/Contents/MacOS/Electron": "codium",
  10077. "/Applications/Cursor.app/Contents/MacOS/Cursor": "cursor",
  10078. "/Applications/Trae.app/Contents/MacOS/Electron": "trae",
  10079. "/Applications/Antigravity.app/Contents/MacOS/Electron": "antigravity",
  10080. "/Applications/AppCode.app/Contents/MacOS/appcode": "/Applications/AppCode.app/Contents/MacOS/appcode",
  10081. "/Applications/CLion.app/Contents/MacOS/clion": "/Applications/CLion.app/Contents/MacOS/clion",
  10082. "/Applications/IntelliJ IDEA.app/Contents/MacOS/idea": "/Applications/IntelliJ IDEA.app/Contents/MacOS/idea",
  10083. "/Applications/IntelliJ IDEA Ultimate.app/Contents/MacOS/idea": "/Applications/IntelliJ IDEA Ultimate.app/Contents/MacOS/idea",
  10084. "/Applications/IntelliJ IDEA Community Edition.app/Contents/MacOS/idea": "/Applications/IntelliJ IDEA Community Edition.app/Contents/MacOS/idea",
  10085. "/Applications/PhpStorm.app/Contents/MacOS/phpstorm": "/Applications/PhpStorm.app/Contents/MacOS/phpstorm",
  10086. "/Applications/PyCharm.app/Contents/MacOS/pycharm": "/Applications/PyCharm.app/Contents/MacOS/pycharm",
  10087. "/Applications/PyCharm CE.app/Contents/MacOS/pycharm": "/Applications/PyCharm CE.app/Contents/MacOS/pycharm",
  10088. "/Applications/RubyMine.app/Contents/MacOS/rubymine": "/Applications/RubyMine.app/Contents/MacOS/rubymine",
  10089. "/Applications/WebStorm.app/Contents/MacOS/webstorm": "/Applications/WebStorm.app/Contents/MacOS/webstorm",
  10090. "/Applications/MacVim.app/Contents/MacOS/MacVim": "mvim",
  10091. "/Applications/GoLand.app/Contents/MacOS/goland": "/Applications/GoLand.app/Contents/MacOS/goland",
  10092. "/Applications/Rider.app/Contents/MacOS/rider": "/Applications/Rider.app/Contents/MacOS/rider",
  10093. "/Applications/Zed.app/Contents/MacOS/zed": "zed"
  10094. };
  10095. }));
  10096. //#endregion
  10097. //#region ../../node_modules/.pnpm/launch-editor@2.13.2/node_modules/launch-editor/editor-info/linux.js
  10098. var require_linux = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  10099. module.exports = {
  10100. atom: "atom",
  10101. Brackets: "brackets",
  10102. "code-insiders": "code-insiders",
  10103. code: "code",
  10104. vscodium: "vscodium",
  10105. codium: "codium",
  10106. cursor: "cursor",
  10107. trae: "trae",
  10108. antigravity: "antigravity",
  10109. emacs: "emacs",
  10110. gvim: "gvim",
  10111. idea: "idea",
  10112. "idea.sh": "idea",
  10113. phpstorm: "phpstorm",
  10114. "phpstorm.sh": "phpstorm",
  10115. pycharm: "pycharm",
  10116. "pycharm.sh": "pycharm",
  10117. rubymine: "rubymine",
  10118. "rubymine.sh": "rubymine",
  10119. sublime_text: "subl",
  10120. vim: "vim",
  10121. webstorm: "webstorm",
  10122. "webstorm.sh": "webstorm",
  10123. goland: "goland",
  10124. "goland.sh": "goland",
  10125. rider: "rider",
  10126. "rider.sh": "rider",
  10127. zed: "zed"
  10128. };
  10129. }));
  10130. //#endregion
  10131. //#region ../../node_modules/.pnpm/launch-editor@2.13.2/node_modules/launch-editor/editor-info/windows.js
  10132. var require_windows$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  10133. module.exports = [
  10134. "Brackets.exe",
  10135. "Code.exe",
  10136. "Code - Insiders.exe",
  10137. "VSCodium.exe",
  10138. "Cursor.exe",
  10139. "atom.exe",
  10140. "sublime_text.exe",
  10141. "notepad++.exe",
  10142. "clion.exe",
  10143. "clion64.exe",
  10144. "idea.exe",
  10145. "idea64.exe",
  10146. "phpstorm.exe",
  10147. "phpstorm64.exe",
  10148. "pycharm.exe",
  10149. "pycharm64.exe",
  10150. "rubymine.exe",
  10151. "rubymine64.exe",
  10152. "webstorm.exe",
  10153. "webstorm64.exe",
  10154. "goland.exe",
  10155. "goland64.exe",
  10156. "rider.exe",
  10157. "rider64.exe",
  10158. "Trae.exe",
  10159. "zed.exe",
  10160. "Antigravity.exe"
  10161. ];
  10162. }));
  10163. //#endregion
  10164. //#region ../../node_modules/.pnpm/launch-editor@2.13.2/node_modules/launch-editor/guess.js
  10165. var require_guess = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  10166. const path$9 = __require("path");
  10167. const shellQuote = require_shell_quote();
  10168. const childProcess$2 = __require("child_process");
  10169. const COMMON_EDITORS_MACOS = require_macos();
  10170. const COMMON_EDITORS_LINUX = require_linux();
  10171. const COMMON_EDITORS_WIN = require_windows$1();
  10172. module.exports = function guessEditor(specifiedEditor) {
  10173. if (specifiedEditor) return shellQuote.parse(specifiedEditor);
  10174. if (process.env.LAUNCH_EDITOR) return [process.env.LAUNCH_EDITOR];
  10175. if (process.versions.webcontainer) return [process.env.EDITOR || "code"];
  10176. try {
  10177. if (process.platform === "darwin") {
  10178. const output = childProcess$2.execSync("ps x -o comm=", { stdio: [
  10179. "pipe",
  10180. "pipe",
  10181. "ignore"
  10182. ] }).toString();
  10183. const processNames = Object.keys(COMMON_EDITORS_MACOS);
  10184. const processList = output.split("\n");
  10185. for (let i = 0; i < processNames.length; i++) {
  10186. const processName = processNames[i];
  10187. if (processList.includes(processName)) return [COMMON_EDITORS_MACOS[processName]];
  10188. const processNameWithoutApplications = processName.replace("/Applications", "");
  10189. if (output.indexOf(processNameWithoutApplications) !== -1) {
  10190. if (processName !== COMMON_EDITORS_MACOS[processName]) return [COMMON_EDITORS_MACOS[processName]];
  10191. const runningProcess = processList.find((procName) => procName.endsWith(processNameWithoutApplications));
  10192. if (runningProcess !== void 0) return [runningProcess];
  10193. }
  10194. }
  10195. } else if (process.platform === "win32") {
  10196. const runningProcesses = childProcess$2.execSync("powershell -NoProfile -Command \"[Console]::OutputEncoding=[Text.Encoding]::UTF8;Get-CimInstance -Query \\\"select executablepath from win32_process where executablepath is not null\\\" | % { $_.ExecutablePath }\"", { stdio: [
  10197. "pipe",
  10198. "pipe",
  10199. "ignore"
  10200. ] }).toString().split("\r\n");
  10201. for (let i = 0; i < runningProcesses.length; i++) {
  10202. const fullProcessPath = runningProcesses[i].trim();
  10203. const shortProcessName = path$9.basename(fullProcessPath);
  10204. if (COMMON_EDITORS_WIN.indexOf(shortProcessName) !== -1) return [fullProcessPath];
  10205. }
  10206. } else if (process.platform === "linux") {
  10207. const output = childProcess$2.execSync("ps x --no-heading -o comm --sort=comm", { stdio: [
  10208. "pipe",
  10209. "pipe",
  10210. "ignore"
  10211. ] }).toString();
  10212. const processNames = Object.keys(COMMON_EDITORS_LINUX);
  10213. for (let i = 0; i < processNames.length; i++) {
  10214. const processName = processNames[i];
  10215. if (output.indexOf(processName) !== -1) return [COMMON_EDITORS_LINUX[processName]];
  10216. }
  10217. }
  10218. } catch (ignoreError) {}
  10219. if (process.env.VISUAL) return [process.env.VISUAL];
  10220. else if (process.env.EDITOR) return [process.env.EDITOR];
  10221. return [null];
  10222. };
  10223. }));
  10224. //#endregion
  10225. //#region ../../node_modules/.pnpm/launch-editor@2.13.2/node_modules/launch-editor/get-args.js
  10226. var require_get_args = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  10227. const path$8 = __require("path");
  10228. module.exports = function getArgumentsForPosition(editor, fileName, lineNumber, columnNumber = 1) {
  10229. switch (path$8.basename(editor).replace(/\.(exe|cmd|bat)$/i, "")) {
  10230. case "atom":
  10231. case "Atom":
  10232. case "Atom Beta":
  10233. case "subl":
  10234. case "sublime":
  10235. case "sublime_text":
  10236. case "wstorm":
  10237. case "charm":
  10238. case "zed": return [`${fileName}:${lineNumber}:${columnNumber}`];
  10239. case "notepad++": return [
  10240. "-n" + lineNumber,
  10241. "-c" + columnNumber,
  10242. fileName
  10243. ];
  10244. case "vim":
  10245. case "mvim": return [`+call cursor(${lineNumber}, ${columnNumber})`, fileName];
  10246. case "joe":
  10247. case "gvim": return [`+${lineNumber}`, fileName];
  10248. case "emacs":
  10249. case "emacsclient": return [`+${lineNumber}:${columnNumber}`, fileName];
  10250. case "rmate":
  10251. case "mate":
  10252. case "mine": return [
  10253. "--line",
  10254. lineNumber,
  10255. fileName
  10256. ];
  10257. case "code":
  10258. case "Code":
  10259. case "code-insiders":
  10260. case "Code - Insiders":
  10261. case "codium":
  10262. case "trae":
  10263. case "antigravity":
  10264. case "cursor":
  10265. case "vscodium":
  10266. case "VSCodium": return [
  10267. "-r",
  10268. "-g",
  10269. `${fileName}:${lineNumber}:${columnNumber}`
  10270. ];
  10271. case "appcode":
  10272. case "clion":
  10273. case "clion64":
  10274. case "idea":
  10275. case "idea64":
  10276. case "phpstorm":
  10277. case "phpstorm64":
  10278. case "pycharm":
  10279. case "pycharm64":
  10280. case "rubymine":
  10281. case "rubymine64":
  10282. case "webstorm":
  10283. case "webstorm64":
  10284. case "goland":
  10285. case "goland64":
  10286. case "rider":
  10287. case "rider64": return [
  10288. "--line",
  10289. lineNumber,
  10290. "--column",
  10291. columnNumber,
  10292. fileName
  10293. ];
  10294. }
  10295. if (process.env.LAUNCH_EDITOR) return [
  10296. fileName,
  10297. lineNumber,
  10298. columnNumber
  10299. ];
  10300. return [fileName];
  10301. };
  10302. }));
  10303. //#endregion
  10304. //#region ../../node_modules/.pnpm/launch-editor@2.13.2/node_modules/launch-editor/index.js
  10305. var require_launch_editor = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  10306. /**
  10307. * Copyright (c) 2015-present, Facebook, Inc.
  10308. *
  10309. * This source code is licensed under the MIT license found in the
  10310. * LICENSE file at
  10311. * https://github.com/facebookincubator/create-react-app/blob/master/LICENSE
  10312. *
  10313. * Modified by Yuxi Evan You
  10314. */
  10315. const fs$6 = __require("fs");
  10316. const os$2 = __require("os");
  10317. const path$7 = __require("path");
  10318. const colors = require_picocolors();
  10319. const childProcess$1 = __require("child_process");
  10320. const guessEditor = require_guess();
  10321. const getArgumentsForPosition = require_get_args();
  10322. function wrapErrorCallback(cb) {
  10323. return (fileName, errorMessage) => {
  10324. console.log();
  10325. console.log(colors.red("Could not open " + path$7.basename(fileName) + " in the editor."));
  10326. if (errorMessage) {
  10327. if (errorMessage[errorMessage.length - 1] !== ".") errorMessage += ".";
  10328. console.log(colors.red("The editor process exited with an error: " + errorMessage));
  10329. }
  10330. console.log();
  10331. if (cb) cb(fileName, errorMessage);
  10332. };
  10333. }
  10334. function isTerminalEditor(editor) {
  10335. switch (editor) {
  10336. case "vim":
  10337. case "emacs":
  10338. case "nano": return true;
  10339. }
  10340. return false;
  10341. }
  10342. const positionRE = /:(\d+)(:(\d+))?$/;
  10343. function parseFile(file) {
  10344. if (file.startsWith("file://")) file = __require("url").fileURLToPath(file);
  10345. const fileName = file.replace(positionRE, "");
  10346. const match = file.match(positionRE);
  10347. return {
  10348. fileName,
  10349. lineNumber: match && match[1],
  10350. columnNumber: match && match[3]
  10351. };
  10352. }
  10353. let _childProcess = null;
  10354. function launchEditor(file, specifiedEditor, onErrorCallback) {
  10355. const parsed = parseFile(file);
  10356. let { fileName } = parsed;
  10357. const { lineNumber, columnNumber } = parsed;
  10358. if (!fs$6.existsSync(fileName)) return;
  10359. if (typeof specifiedEditor === "function") {
  10360. onErrorCallback = specifiedEditor;
  10361. specifiedEditor = void 0;
  10362. }
  10363. onErrorCallback = wrapErrorCallback(onErrorCallback);
  10364. const [editor, ...args] = guessEditor(specifiedEditor);
  10365. if (!editor) {
  10366. onErrorCallback(fileName, null);
  10367. return;
  10368. }
  10369. if (process.platform === "linux" && fileName.startsWith("/mnt/") && /Microsoft/i.test(os$2.release())) fileName = path$7.relative("", fileName);
  10370. if (lineNumber) {
  10371. const extraArgs = getArgumentsForPosition(editor, fileName, lineNumber, columnNumber);
  10372. args.push.apply(args, extraArgs);
  10373. } else args.push(fileName);
  10374. if (_childProcess && isTerminalEditor(editor)) _childProcess.kill("SIGKILL");
  10375. if (process.platform === "win32") {
  10376. function escapeCmdArgs(cmdArgs) {
  10377. return cmdArgs.replace(/([&|<>,;=^])/g, "^$1");
  10378. }
  10379. function doubleQuoteIfNeeded(str) {
  10380. if (str.includes("^")) return `^"${str}^"`;
  10381. else if (str.includes(" ")) return `"${str}"`;
  10382. return str;
  10383. }
  10384. const launchCommand = [editor, ...args.map(escapeCmdArgs)].map(doubleQuoteIfNeeded).join(" ");
  10385. _childProcess = childProcess$1.exec(launchCommand, {
  10386. stdio: "inherit",
  10387. shell: true
  10388. });
  10389. } else _childProcess = childProcess$1.spawn(editor, args, { stdio: "inherit" });
  10390. _childProcess.on("exit", function(errorCode) {
  10391. _childProcess = null;
  10392. if (errorCode) onErrorCallback(fileName, "(code " + errorCode + ")");
  10393. });
  10394. _childProcess.on("error", function(error) {
  10395. let { code, message } = error;
  10396. if ("ENOENT" === code) message = `${message} ('${editor}' command does not exist in 'PATH')`;
  10397. onErrorCallback(fileName, message);
  10398. });
  10399. }
  10400. module.exports = launchEditor;
  10401. }));
  10402. //#endregion
  10403. //#region ../../node_modules/.pnpm/launch-editor-middleware@2.13.2/node_modules/launch-editor-middleware/index.js
  10404. var require_launch_editor_middleware = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  10405. const path$6 = __require("path");
  10406. const launch = require_launch_editor();
  10407. module.exports = (specifiedEditor, srcRoot, onErrorCallback) => {
  10408. if (typeof specifiedEditor === "function") {
  10409. onErrorCallback = specifiedEditor;
  10410. specifiedEditor = void 0;
  10411. }
  10412. if (typeof srcRoot === "function") {
  10413. onErrorCallback = srcRoot;
  10414. srcRoot = void 0;
  10415. }
  10416. srcRoot = srcRoot || process.cwd();
  10417. return function launchEditorMiddleware(req, res) {
  10418. let url;
  10419. try {
  10420. const fullUrl = req.url.startsWith("http") ? req.url : `http://localhost${req.url}`;
  10421. url = new URL(fullUrl);
  10422. } catch (_err) {
  10423. res.statusCode = 500;
  10424. res.end(`launch-editor-middleware: invalid URL.`);
  10425. return;
  10426. }
  10427. const file = url.searchParams.get("file");
  10428. if (!file) {
  10429. res.statusCode = 500;
  10430. res.end(`launch-editor-middleware: required query param "file" is missing.`);
  10431. } else {
  10432. launch(file.startsWith("file://") ? file : path$6.resolve(srcRoot, file), specifiedEditor, onErrorCallback);
  10433. res.end();
  10434. }
  10435. };
  10436. };
  10437. }));
  10438. //#endregion
  10439. //#region ../../node_modules/.pnpm/@vercel+detect-agent@1.2.1/node_modules/@vercel/detect-agent/dist/index.js
  10440. var require_dist = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  10441. var __defProp = Object.defineProperty;
  10442. var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
  10443. var __getOwnPropNames = Object.getOwnPropertyNames;
  10444. var __hasOwnProp = Object.prototype.hasOwnProperty;
  10445. var __export = (target, all) => {
  10446. for (var name in all) __defProp(target, name, {
  10447. get: all[name],
  10448. enumerable: true
  10449. });
  10450. };
  10451. var __copyProps = (to, from, except, desc) => {
  10452. if (from && typeof from === "object" || typeof from === "function") {
  10453. for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
  10454. get: () => from[key],
  10455. enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
  10456. });
  10457. }
  10458. return to;
  10459. };
  10460. var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
  10461. var src_exports = {};
  10462. __export(src_exports, {
  10463. KNOWN_AGENTS: () => KNOWN_AGENTS,
  10464. determineAgent: () => determineAgent
  10465. });
  10466. module.exports = __toCommonJS(src_exports);
  10467. var import_promises = __require("node:fs/promises");
  10468. var import_node_fs = __require("node:fs");
  10469. const DEVIN_LOCAL_PATH = "/opt/.devin";
  10470. const CURSOR = "cursor";
  10471. const CURSOR_CLI = "cursor-cli";
  10472. const CLAUDE = "claude";
  10473. const COWORK = "cowork";
  10474. const DEVIN = "devin";
  10475. const REPLIT = "replit";
  10476. const GEMINI = "gemini";
  10477. const CODEX = "codex";
  10478. const ANTIGRAVITY = "antigravity";
  10479. const AUGMENT_CLI = "augment-cli";
  10480. const OPENCODE = "opencode";
  10481. const GITHUB_COPILOT = "github-copilot";
  10482. const GITHUB_COPILOT_CLI = "github-copilot-cli";
  10483. const KNOWN_AGENTS = {
  10484. CURSOR,
  10485. CURSOR_CLI,
  10486. CLAUDE,
  10487. COWORK,
  10488. DEVIN,
  10489. REPLIT,
  10490. GEMINI,
  10491. CODEX,
  10492. ANTIGRAVITY,
  10493. AUGMENT_CLI,
  10494. OPENCODE,
  10495. GITHUB_COPILOT
  10496. };
  10497. async function determineAgent() {
  10498. if (process.env.AI_AGENT) {
  10499. const name = process.env.AI_AGENT.trim();
  10500. if (name) {
  10501. if (name === GITHUB_COPILOT || name === GITHUB_COPILOT_CLI) return {
  10502. isAgent: true,
  10503. agent: { name: GITHUB_COPILOT }
  10504. };
  10505. return {
  10506. isAgent: true,
  10507. agent: { name }
  10508. };
  10509. }
  10510. }
  10511. if (process.env.CURSOR_TRACE_ID) return {
  10512. isAgent: true,
  10513. agent: { name: CURSOR }
  10514. };
  10515. if (process.env.CURSOR_AGENT) return {
  10516. isAgent: true,
  10517. agent: { name: CURSOR_CLI }
  10518. };
  10519. if (process.env.GEMINI_CLI) return {
  10520. isAgent: true,
  10521. agent: { name: GEMINI }
  10522. };
  10523. if (process.env.CODEX_SANDBOX || process.env.CODEX_CI || process.env.CODEX_THREAD_ID) return {
  10524. isAgent: true,
  10525. agent: { name: CODEX }
  10526. };
  10527. if (process.env.ANTIGRAVITY_AGENT) return {
  10528. isAgent: true,
  10529. agent: { name: ANTIGRAVITY }
  10530. };
  10531. if (process.env.AUGMENT_AGENT) return {
  10532. isAgent: true,
  10533. agent: { name: AUGMENT_CLI }
  10534. };
  10535. if (process.env.OPENCODE_CLIENT) return {
  10536. isAgent: true,
  10537. agent: { name: OPENCODE }
  10538. };
  10539. if (process.env.CLAUDECODE || process.env.CLAUDE_CODE) {
  10540. if (process.env.CLAUDE_CODE_IS_COWORK) return {
  10541. isAgent: true,
  10542. agent: { name: COWORK }
  10543. };
  10544. return {
  10545. isAgent: true,
  10546. agent: { name: CLAUDE }
  10547. };
  10548. }
  10549. if (process.env.REPL_ID) return {
  10550. isAgent: true,
  10551. agent: { name: REPLIT }
  10552. };
  10553. if (process.env.COPILOT_MODEL || process.env.COPILOT_ALLOW_ALL || process.env.COPILOT_GITHUB_TOKEN) return {
  10554. isAgent: true,
  10555. agent: { name: GITHUB_COPILOT }
  10556. };
  10557. try {
  10558. await (0, import_promises.access)(DEVIN_LOCAL_PATH, import_node_fs.constants.F_OK);
  10559. return {
  10560. isAgent: true,
  10561. agent: { name: DEVIN }
  10562. };
  10563. } catch (_error) {}
  10564. return {
  10565. isAgent: false,
  10566. agent: void 0
  10567. };
  10568. }
  10569. }));
  10570. //#endregion
  10571. //#region src/node/http.ts
  10572. async function resolveHttpServer(app, httpsOptions) {
  10573. if (!httpsOptions) {
  10574. const { createServer } = await import("node:http");
  10575. return createServer(app);
  10576. }
  10577. const { createSecureServer } = await import("node:http2");
  10578. return createSecureServer({
  10579. maxSessionMemory: 1e3,
  10580. streamResetBurst: 1e5,
  10581. streamResetRate: 33,
  10582. ...httpsOptions,
  10583. allowHTTP1: true
  10584. }, app);
  10585. }
  10586. async function resolveHttpsConfig(https) {
  10587. if (!https) return void 0;
  10588. const [ca, cert, key, pfx] = await Promise.all([
  10589. readFileIfExists(https.ca),
  10590. readFileIfExists(https.cert),
  10591. readFileIfExists(https.key),
  10592. readFileIfExists(https.pfx)
  10593. ]);
  10594. return {
  10595. ...https,
  10596. ca,
  10597. cert,
  10598. key,
  10599. pfx
  10600. };
  10601. }
  10602. async function readFileIfExists(value) {
  10603. if (typeof value === "string") return fsp.readFile(path.resolve(value)).catch(() => value);
  10604. return value;
  10605. }
  10606. async function isPortAvailable(port) {
  10607. for (const host of wildcardHosts) if (!await tryListen(port, host).catch(() => true)) return false;
  10608. return true;
  10609. }
  10610. function tryListen(port, host) {
  10611. return new Promise((resolve) => {
  10612. const server = net.createServer();
  10613. server.once("error", (e) => {
  10614. server.close(() => resolve(e.code !== "EADDRINUSE"));
  10615. });
  10616. server.once("listening", () => {
  10617. server.close(() => resolve(true));
  10618. });
  10619. server.listen(port, host);
  10620. });
  10621. }
  10622. async function tryBindServer(httpServer, port, host) {
  10623. return new Promise((resolve) => {
  10624. const onError = (e) => {
  10625. httpServer.off("error", onError);
  10626. httpServer.off("listening", onListening);
  10627. resolve({
  10628. success: false,
  10629. error: e
  10630. });
  10631. };
  10632. const onListening = () => {
  10633. httpServer.off("error", onError);
  10634. httpServer.off("listening", onListening);
  10635. resolve({ success: true });
  10636. };
  10637. httpServer.on("error", onError);
  10638. httpServer.on("listening", onListening);
  10639. httpServer.listen(port, host);
  10640. });
  10641. }
  10642. const MAX_PORT = 65535;
  10643. async function httpServerStart(httpServer, serverOptions) {
  10644. const { port: startPort, strictPort, host, logger } = serverOptions;
  10645. for (let port = startPort; port <= MAX_PORT; port++) {
  10646. if (await isPortAvailable(port)) {
  10647. const result = await tryBindServer(httpServer, port, host);
  10648. if (result.success) return port;
  10649. if (result.error.code !== "EADDRINUSE") throw result.error;
  10650. }
  10651. if (strictPort) throw new Error(`Port ${port} is already in use`);
  10652. logger.info(`Port ${port} is in use, trying another one...`);
  10653. }
  10654. throw new Error(`No available ports found between ${startPort} and ${MAX_PORT}`);
  10655. }
  10656. function setClientErrorHandler(server, logger) {
  10657. server.on("clientError", (err, socket) => {
  10658. let msg = "400 Bad Request";
  10659. if (err.code === "HPE_HEADER_OVERFLOW") {
  10660. msg = "431 Request Header Fields Too Large";
  10661. logger.warn(import_picocolors.default.yellow("Server responded with status code 431. See https://vite.dev/guide/troubleshooting.html#_431-request-header-fields-too-large."));
  10662. }
  10663. if (err.code === "ECONNRESET" || !socket.writable) return;
  10664. socket.end(`HTTP/1.1 ${msg}\r\n\r\n`);
  10665. });
  10666. }
  10667. //#endregion
  10668. //#region src/node/ssr/ssrStacktrace.ts
  10669. let offset;
  10670. function calculateOffsetOnce() {
  10671. if (offset !== void 0) return;
  10672. try {
  10673. new Function("throw new Error(1)")();
  10674. } catch (e) {
  10675. const match = /:(\d+):\d+\)$/.exec(e.stack.split("\n")[1]);
  10676. offset = match ? +match[1] - 1 : 0;
  10677. }
  10678. }
  10679. function ssrRewriteStacktrace(stack, moduleGraph) {
  10680. calculateOffsetOnce();
  10681. let alreadyRewritten = false;
  10682. return {
  10683. result: stack.split("\n").map((line) => {
  10684. return line.replace(/^ {4}at (?:(\S.*?)\s\()?(.+?):(\d+)(?::(\d+))?\)?/, (input, varName, id, originalLine, originalColumn) => {
  10685. if (!id) return input;
  10686. const rawSourceMap = moduleGraph.getModuleById(id)?.transformResult?.map;
  10687. if (!rawSourceMap) return input;
  10688. const traced = new TraceMap(rawSourceMap);
  10689. const line = Number(originalLine) - offset;
  10690. const column = Number(originalColumn) - 1;
  10691. if (line <= 0 || column < 0) {
  10692. alreadyRewritten = true;
  10693. return input;
  10694. }
  10695. const pos = originalPositionFor$2(traced, {
  10696. line,
  10697. column
  10698. });
  10699. if (!pos.source) return input;
  10700. const trimmedVarName = varName?.trim();
  10701. const source = `${path.resolve(path.dirname(id), pos.source)}:${pos.line}:${pos.column + 1}`;
  10702. if (!trimmedVarName || trimmedVarName === "eval") return ` at ${source}`;
  10703. else return ` at ${trimmedVarName} (${source})`;
  10704. });
  10705. }).join("\n"),
  10706. alreadyRewritten
  10707. };
  10708. }
  10709. function rebindErrorStacktrace(e, stacktrace) {
  10710. const { configurable, writable } = Object.getOwnPropertyDescriptor(e, "stack");
  10711. if (configurable) Object.defineProperty(e, "stack", {
  10712. value: stacktrace,
  10713. enumerable: true,
  10714. configurable: true,
  10715. writable: true
  10716. });
  10717. else if (writable) e.stack = stacktrace;
  10718. }
  10719. const rewroteStacktraces = /* @__PURE__ */ new WeakSet();
  10720. function ssrFixStacktrace(e, moduleGraph) {
  10721. if (!e.stack) return;
  10722. if (rewroteStacktraces.has(e)) return;
  10723. const { result: stacktrace, alreadyRewritten } = ssrRewriteStacktrace(e.stack, moduleGraph);
  10724. rebindErrorStacktrace(e, stacktrace);
  10725. if (alreadyRewritten) e.message += " (The stacktrace appears to be already rewritten by something else, but was passed to vite.ssrFixStacktrace. This may cause incorrect stacktraces.)";
  10726. rewroteStacktraces.add(e);
  10727. }
  10728. //#endregion
  10729. //#region src/node/ssr/runtime/serverModuleRunner.ts
  10730. function createHMROptions(environment, options) {
  10731. if (environment.config.server.hmr === false || options.hmr === false) return false;
  10732. if (!("api" in environment.hot)) return false;
  10733. return { logger: options.hmr?.logger };
  10734. }
  10735. const prepareStackTrace = { retrieveFile(id) {
  10736. if (existsSync(id)) return readFileSync(id, "utf-8");
  10737. } };
  10738. function resolveSourceMapOptions(options) {
  10739. if (options.sourcemapInterceptor != null) {
  10740. if (options.sourcemapInterceptor === "prepareStackTrace") return prepareStackTrace;
  10741. if (typeof options.sourcemapInterceptor === "object") return {
  10742. ...prepareStackTrace,
  10743. ...options.sourcemapInterceptor
  10744. };
  10745. return options.sourcemapInterceptor;
  10746. }
  10747. if (typeof process !== "undefined" && "setSourceMapsEnabled" in process) return "node";
  10748. return prepareStackTrace;
  10749. }
  10750. const createServerModuleRunnerTransport = (options) => {
  10751. const hmrClient = { send: (payload) => {
  10752. if (payload.type !== "custom") throw new Error("Cannot send non-custom events from the client to the server.");
  10753. options.channel.send(payload);
  10754. } };
  10755. let handler;
  10756. return {
  10757. connect({ onMessage }) {
  10758. options.channel.api.outsideEmitter.on("send", onMessage);
  10759. options.channel.api.innerEmitter.emit("vite:client:connect", void 0, hmrClient);
  10760. onMessage({ type: "connected" });
  10761. handler = onMessage;
  10762. },
  10763. disconnect() {
  10764. if (handler) options.channel.api.outsideEmitter.off("send", handler);
  10765. options.channel.api.innerEmitter.emit("vite:client:disconnect", void 0, hmrClient);
  10766. },
  10767. send(payload) {
  10768. if (payload.type !== "custom") throw new Error("Cannot send non-custom events from the server to the client.");
  10769. options.channel.api.innerEmitter.emit(payload.event, payload.data, hmrClient);
  10770. }
  10771. };
  10772. };
  10773. /**
  10774. * Create an instance of the Vite SSR runtime that support HMR.
  10775. * @experimental
  10776. */
  10777. function createServerModuleRunner(environment, options = {}) {
  10778. const hmr = createHMROptions(environment, options);
  10779. return new ModuleRunner({
  10780. ...options,
  10781. transport: createServerModuleRunnerTransport({ channel: environment.hot }),
  10782. hmr,
  10783. createImportMeta: createNodeImportMeta,
  10784. sourcemapInterceptor: resolveSourceMapOptions(options)
  10785. }, options.evaluator);
  10786. }
  10787. //#endregion
  10788. //#region src/node/ssr/ssrModuleLoader.ts
  10789. async function ssrLoadModule(url, server, fixStacktrace) {
  10790. const environment = server.environments.ssr;
  10791. if (!isRunnableDevEnvironment(environment)) throw new Error(`ssrLoadModule requires the 'ssr' environment to be a runnable environment.`);
  10792. server._ssrCompatModuleRunner ||= new SSRCompatModuleRunner(environment);
  10793. url = unwrapId(url);
  10794. return instantiateModule(url, server._ssrCompatModuleRunner, environment, fixStacktrace);
  10795. }
  10796. async function instantiateModule(url, runner, environment, fixStacktrace) {
  10797. const mod = await environment.moduleGraph.ensureEntryFromUrl(url);
  10798. if (mod.ssrError) throw mod.ssrError;
  10799. try {
  10800. return await runner.import(url);
  10801. } catch (e) {
  10802. if (e.stack && fixStacktrace) ssrFixStacktrace(e, environment.moduleGraph);
  10803. environment.logger.error(buildErrorMessage(e, [import_picocolors.default.red(`Error when evaluating SSR module ${url}: ${e.message}`)]), {
  10804. timestamp: true,
  10805. clear: environment.config.clearScreen,
  10806. error: e
  10807. });
  10808. throw e;
  10809. }
  10810. }
  10811. var SSRCompatModuleRunner = class extends ModuleRunner {
  10812. constructor(environment) {
  10813. super({
  10814. transport: createServerModuleRunnerTransport({ channel: environment.hot }),
  10815. createImportMeta: createNodeImportMeta,
  10816. sourcemapInterceptor: false,
  10817. hmr: false
  10818. }, new ESModulesEvaluator());
  10819. this.environment = environment;
  10820. }
  10821. async directRequest(url, mod, callstack) {
  10822. const id = mod.meta && "id" in mod.meta && mod.meta.id;
  10823. if (!id) return super.directRequest(url, mod, callstack);
  10824. const viteMod = this.environment.moduleGraph.getModuleById(id);
  10825. if (!viteMod) return super.directRequest(id, mod, callstack);
  10826. try {
  10827. const exports = await super.directRequest(id, mod, callstack);
  10828. viteMod.ssrModule = exports;
  10829. return exports;
  10830. } catch (err) {
  10831. viteMod.ssrError = err;
  10832. throw err;
  10833. }
  10834. }
  10835. };
  10836. //#endregion
  10837. //#region ../../node_modules/.pnpm/periscopic@4.0.2/node_modules/periscopic/src/index.js
  10838. /**
  10839. * @param {import('estree').Node} param
  10840. * @returns {string[]}
  10841. */
  10842. function extract_names(param) {
  10843. return extract_identifiers(param).map((node) => node.name);
  10844. }
  10845. /**
  10846. * @param {import('estree').Node} param
  10847. * @param {import('estree').Identifier[]} nodes
  10848. * @returns {import('estree').Identifier[]}
  10849. */
  10850. function extract_identifiers(param, nodes = []) {
  10851. switch (param.type) {
  10852. case "Identifier":
  10853. nodes.push(param);
  10854. break;
  10855. case "MemberExpression":
  10856. let object = param;
  10857. while (object.type === "MemberExpression") object = object.object;
  10858. nodes.push(object);
  10859. break;
  10860. case "ObjectPattern":
  10861. for (const prop of param.properties) if (prop.type === "RestElement") extract_identifiers(prop.argument, nodes);
  10862. else extract_identifiers(prop.value, nodes);
  10863. break;
  10864. case "ArrayPattern":
  10865. for (const element of param.elements) if (element) extract_identifiers(element, nodes);
  10866. break;
  10867. case "RestElement":
  10868. extract_identifiers(param.argument, nodes);
  10869. break;
  10870. case "AssignmentPattern":
  10871. extract_identifiers(param.left, nodes);
  10872. break;
  10873. }
  10874. return nodes;
  10875. }
  10876. //#endregion
  10877. //#region ../../node_modules/.pnpm/estree-walker@3.0.3/node_modules/estree-walker/src/walker.js
  10878. /**
  10879. * @typedef { import('estree').Node} Node
  10880. * @typedef {{
  10881. * skip: () => void;
  10882. * remove: () => void;
  10883. * replace: (node: Node) => void;
  10884. * }} WalkerContext
  10885. */
  10886. var WalkerBase = class {
  10887. constructor() {
  10888. /** @type {boolean} */
  10889. this.should_skip = false;
  10890. /** @type {boolean} */
  10891. this.should_remove = false;
  10892. /** @type {Node | null} */
  10893. this.replacement = null;
  10894. /** @type {WalkerContext} */
  10895. this.context = {
  10896. skip: () => this.should_skip = true,
  10897. remove: () => this.should_remove = true,
  10898. replace: (node) => this.replacement = node
  10899. };
  10900. }
  10901. /**
  10902. * @template {Node} Parent
  10903. * @param {Parent | null | undefined} parent
  10904. * @param {keyof Parent | null | undefined} prop
  10905. * @param {number | null | undefined} index
  10906. * @param {Node} node
  10907. */
  10908. replace(parent, prop, index, node) {
  10909. if (parent && prop) if (index != null)
  10910. /** @type {Array<Node>} */ parent[prop][index] = node;
  10911. else
  10912. /** @type {Node} */ parent[prop] = node;
  10913. }
  10914. /**
  10915. * @template {Node} Parent
  10916. * @param {Parent | null | undefined} parent
  10917. * @param {keyof Parent | null | undefined} prop
  10918. * @param {number | null | undefined} index
  10919. */
  10920. remove(parent, prop, index) {
  10921. if (parent && prop) if (index !== null && index !== void 0)
  10922. /** @type {Array<Node>} */ parent[prop].splice(index, 1);
  10923. else delete parent[prop];
  10924. }
  10925. };
  10926. //#endregion
  10927. //#region ../../node_modules/.pnpm/estree-walker@3.0.3/node_modules/estree-walker/src/sync.js
  10928. /**
  10929. * @typedef { import('estree').Node} Node
  10930. * @typedef { import('./walker.js').WalkerContext} WalkerContext
  10931. * @typedef {(
  10932. * this: WalkerContext,
  10933. * node: Node,
  10934. * parent: Node | null,
  10935. * key: string | number | symbol | null | undefined,
  10936. * index: number | null | undefined
  10937. * ) => void} SyncHandler
  10938. */
  10939. var SyncWalker = class extends WalkerBase {
  10940. /**
  10941. *
  10942. * @param {SyncHandler} [enter]
  10943. * @param {SyncHandler} [leave]
  10944. */
  10945. constructor(enter, leave) {
  10946. super();
  10947. /** @type {boolean} */
  10948. this.should_skip = false;
  10949. /** @type {boolean} */
  10950. this.should_remove = false;
  10951. /** @type {Node | null} */
  10952. this.replacement = null;
  10953. /** @type {WalkerContext} */
  10954. this.context = {
  10955. skip: () => this.should_skip = true,
  10956. remove: () => this.should_remove = true,
  10957. replace: (node) => this.replacement = node
  10958. };
  10959. /** @type {SyncHandler | undefined} */
  10960. this.enter = enter;
  10961. /** @type {SyncHandler | undefined} */
  10962. this.leave = leave;
  10963. }
  10964. /**
  10965. * @template {Node} Parent
  10966. * @param {Node} node
  10967. * @param {Parent | null} parent
  10968. * @param {keyof Parent} [prop]
  10969. * @param {number | null} [index]
  10970. * @returns {Node | null}
  10971. */
  10972. visit(node, parent, prop, index) {
  10973. if (node) {
  10974. if (this.enter) {
  10975. const _should_skip = this.should_skip;
  10976. const _should_remove = this.should_remove;
  10977. const _replacement = this.replacement;
  10978. this.should_skip = false;
  10979. this.should_remove = false;
  10980. this.replacement = null;
  10981. this.enter.call(this.context, node, parent, prop, index);
  10982. if (this.replacement) {
  10983. node = this.replacement;
  10984. this.replace(parent, prop, index, node);
  10985. }
  10986. if (this.should_remove) this.remove(parent, prop, index);
  10987. const skipped = this.should_skip;
  10988. const removed = this.should_remove;
  10989. this.should_skip = _should_skip;
  10990. this.should_remove = _should_remove;
  10991. this.replacement = _replacement;
  10992. if (skipped) return node;
  10993. if (removed) return null;
  10994. }
  10995. /** @type {keyof Node} */
  10996. let key;
  10997. for (key in node) {
  10998. /** @type {unknown} */
  10999. const value = node[key];
  11000. if (value && typeof value === "object") {
  11001. if (Array.isArray(value)) {
  11002. const nodes = value;
  11003. for (let i = 0; i < nodes.length; i += 1) {
  11004. const item = nodes[i];
  11005. if (isNode(item)) {
  11006. if (!this.visit(item, node, key, i)) i--;
  11007. }
  11008. }
  11009. } else if (isNode(value)) this.visit(value, node, key, null);
  11010. }
  11011. }
  11012. if (this.leave) {
  11013. const _replacement = this.replacement;
  11014. const _should_remove = this.should_remove;
  11015. this.replacement = null;
  11016. this.should_remove = false;
  11017. this.leave.call(this.context, node, parent, prop, index);
  11018. if (this.replacement) {
  11019. node = this.replacement;
  11020. this.replace(parent, prop, index, node);
  11021. }
  11022. if (this.should_remove) this.remove(parent, prop, index);
  11023. const removed = this.should_remove;
  11024. this.replacement = _replacement;
  11025. this.should_remove = _should_remove;
  11026. if (removed) return null;
  11027. }
  11028. }
  11029. return node;
  11030. }
  11031. };
  11032. /**
  11033. * Ducktype a node.
  11034. *
  11035. * @param {unknown} value
  11036. * @returns {value is Node}
  11037. */
  11038. function isNode(value) {
  11039. return value !== null && typeof value === "object" && "type" in value && typeof value.type === "string";
  11040. }
  11041. //#endregion
  11042. //#region ../../node_modules/.pnpm/estree-walker@3.0.3/node_modules/estree-walker/src/index.js
  11043. /**
  11044. * @typedef {import('estree').Node} Node
  11045. * @typedef {import('./sync.js').SyncHandler} SyncHandler
  11046. * @typedef {import('./async.js').AsyncHandler} AsyncHandler
  11047. */
  11048. /**
  11049. * @param {Node} ast
  11050. * @param {{
  11051. * enter?: SyncHandler
  11052. * leave?: SyncHandler
  11053. * }} walker
  11054. * @returns {Node | null}
  11055. */
  11056. function walk$1(ast, { enter, leave }) {
  11057. return new SyncWalker(enter, leave).visit(ast, null);
  11058. }
  11059. //#endregion
  11060. //#region src/node/plugins/json.ts
  11061. const jsonLangRE = new RegExp(`\\.(?:json|json5)(?:$|\\?)`);
  11062. const isJSONRequest = (request) => jsonLangRE.test(request);
  11063. //#endregion
  11064. //#region src/node/ssr/ssrTransform.ts
  11065. const ssrModuleExportsKey = `__vite_ssr_exports__`;
  11066. const ssrImportKey = `__vite_ssr_import__`;
  11067. const ssrDynamicImportKey = `__vite_ssr_dynamic_import__`;
  11068. const ssrExportAllKey = `__vite_ssr_exportAll__`;
  11069. const ssrExportNameKey = `__vite_ssr_exportName__`;
  11070. const ssrImportMetaKey = `__vite_ssr_import_meta__`;
  11071. async function ssrTransform(code, inMap, url, originalCode, options) {
  11072. if (options?.json?.stringify && isJSONRequest(url)) return ssrTransformJSON(code, inMap);
  11073. return ssrTransformScript(code, inMap, url, originalCode);
  11074. }
  11075. async function ssrTransformJSON(code, inMap) {
  11076. return {
  11077. code: code.replace("export default", `${ssrModuleExportsKey}.default =`),
  11078. map: inMap,
  11079. deps: [],
  11080. dynamicDeps: [],
  11081. ssr: true
  11082. };
  11083. }
  11084. async function ssrTransformScript(code, inMap, url, originalCode) {
  11085. const s = new MagicString(code);
  11086. let ast;
  11087. try {
  11088. ast = await parseAstAsync(code);
  11089. } catch (err) {
  11090. if (err.code === "PARSE_ERROR") {
  11091. err.message = `Parse failure: ${err.message}\n`;
  11092. err.id = url;
  11093. if (typeof err.pos === "number") {
  11094. err.loc = numberToPos(code, err.pos);
  11095. err.loc.file = url;
  11096. err.frame = generateCodeFrame(code, err.pos);
  11097. err.message += `At file: ${url}:${err.loc.line}:${err.loc.column}`;
  11098. } else err.message += `At file: ${url}`;
  11099. }
  11100. throw err;
  11101. }
  11102. let uid = 0;
  11103. const deps = /* @__PURE__ */ new Set();
  11104. const dynamicDeps = /* @__PURE__ */ new Set();
  11105. const idToImportMap = /* @__PURE__ */ new Map();
  11106. const declaredConst = /* @__PURE__ */ new Set();
  11107. const fileStartIndex = getFileStartIndex(code);
  11108. let hoistIndex = fileStartIndex;
  11109. function defineImport(index, importNode, metadata) {
  11110. const source = importNode.source.value;
  11111. deps.add(source);
  11112. const metadataArg = (metadata?.importedNames?.length ?? 0) > 0 ? `, ${JSON.stringify(metadata)}` : "";
  11113. const importId = `__vite_ssr_import_${uid++}__`;
  11114. const transformedImport = `const ${importId} = await ${ssrImportKey}(${JSON.stringify(source)}${metadataArg});\n`;
  11115. s.update(importNode.start, importNode.end, transformedImport);
  11116. if (importNode.start === index) hoistIndex = importNode.end;
  11117. else s.move(importNode.start, importNode.end, index);
  11118. return importId;
  11119. }
  11120. function defineExport(name, local = name) {
  11121. s.appendLeft(fileStartIndex, `${ssrExportNameKey}(${JSON.stringify(name)}, () => { try { return ${local} } catch {} });\n`);
  11122. }
  11123. const imports = [];
  11124. const exports = [];
  11125. const reExportImportIdMap = /* @__PURE__ */ new Map();
  11126. for (const node of ast.body) if (node.type === "ImportDeclaration") imports.push(node);
  11127. else if (node.type === "ExportDefaultDeclaration") exports.push(node);
  11128. else if (node.type === "ExportNamedDeclaration" || node.type === "ExportAllDeclaration") {
  11129. imports.push(node);
  11130. exports.push(node);
  11131. }
  11132. for (const node of imports) {
  11133. if (node.type === "ExportNamedDeclaration") {
  11134. if (node.source) {
  11135. const importId = defineImport(hoistIndex, node, { importedNames: node.specifiers.map((s) => getIdentifierNameOrLiteralValue$1(s.local)) });
  11136. reExportImportIdMap.set(node, importId);
  11137. }
  11138. continue;
  11139. }
  11140. if (node.type === "ExportAllDeclaration") {
  11141. if (node.source) {
  11142. const importId = defineImport(hoistIndex, node);
  11143. reExportImportIdMap.set(node, importId);
  11144. }
  11145. continue;
  11146. }
  11147. const importId = defineImport(hoistIndex, node, { importedNames: node.specifiers.map((s) => {
  11148. if (s.type === "ImportSpecifier") return getIdentifierNameOrLiteralValue$1(s.imported);
  11149. else if (s.type === "ImportDefaultSpecifier") return "default";
  11150. }).filter(isDefined) });
  11151. for (const spec of node.specifiers) if (spec.type === "ImportSpecifier") if (spec.imported.type === "Identifier") idToImportMap.set(spec.local.name, `${importId}.${spec.imported.name}`);
  11152. else idToImportMap.set(spec.local.name, `${importId}[${JSON.stringify(spec.imported.value)}]`);
  11153. else if (spec.type === "ImportDefaultSpecifier") idToImportMap.set(spec.local.name, `${importId}.default`);
  11154. else idToImportMap.set(spec.local.name, importId);
  11155. }
  11156. for (const node of exports) {
  11157. if (node.type === "ExportNamedDeclaration") if (node.declaration) {
  11158. if (node.declaration.type === "FunctionDeclaration" || node.declaration.type === "ClassDeclaration") defineExport(node.declaration.id.name);
  11159. else {
  11160. const declaration = node.declaration;
  11161. for (const decl of declaration.declarations) {
  11162. const names = extract_names(decl.id);
  11163. for (const name of names) defineExport(name);
  11164. }
  11165. }
  11166. s.remove(node.start, node.declaration.start);
  11167. } else if (node.source) {
  11168. const importId = reExportImportIdMap.get(node);
  11169. for (const spec of node.specifiers) {
  11170. const exportedAs = getIdentifierNameOrLiteralValue$1(spec.exported);
  11171. if (spec.local.type === "Identifier") defineExport(exportedAs, `${importId}.${spec.local.name}`);
  11172. else defineExport(exportedAs, `${importId}[${JSON.stringify(spec.local.value)}]`);
  11173. }
  11174. } else {
  11175. s.remove(node.start, node.end);
  11176. for (const spec of node.specifiers) {
  11177. const local = spec.local.name;
  11178. const binding = idToImportMap.get(local);
  11179. defineExport(getIdentifierNameOrLiteralValue$1(spec.exported), binding || local);
  11180. }
  11181. }
  11182. if (node.type === "ExportDefaultDeclaration") if ("id" in node.declaration && node.declaration.id && !["FunctionExpression", "ClassExpression"].includes(node.declaration.type)) {
  11183. const { name } = node.declaration.id;
  11184. s.remove(node.start, node.start + 15);
  11185. defineExport("default", name);
  11186. } else {
  11187. const name = `__vite_ssr_export_default__`;
  11188. s.update(node.start, node.start + 14, `const ${name} =`);
  11189. defineExport("default", name);
  11190. }
  11191. if (node.type === "ExportAllDeclaration") {
  11192. const importId = reExportImportIdMap.get(node);
  11193. if (node.exported) defineExport(getIdentifierNameOrLiteralValue$1(node.exported), `${importId}`);
  11194. else s.appendLeft(node.end, `${ssrExportAllKey}(${importId});\n`);
  11195. }
  11196. }
  11197. walk(ast, {
  11198. onStatements(statements) {
  11199. for (let i = 0; i < statements.length - 1; i++) {
  11200. const stmt = statements[i];
  11201. if (code[stmt.end - 1] !== ";" && stmt.type !== "FunctionDeclaration" && stmt.type !== "ClassDeclaration" && stmt.type !== "BlockStatement" && stmt.type !== "ImportDeclaration") s.appendLeft(stmt.end, ";");
  11202. }
  11203. },
  11204. onIdentifier(id, parent, parentStack) {
  11205. const binding = idToImportMap.get(id.name);
  11206. if (!binding) return;
  11207. if (isStaticProperty(parent) && parent.shorthand) {
  11208. if (!isNodeInPattern(parent) || isInDestructuringAssignment(parent, parentStack)) s.appendLeft(id.end, `: ${binding}`);
  11209. } else if (parent.type === "ClassDeclaration" && id === parent.superClass) {
  11210. if (!declaredConst.has(id.name)) {
  11211. declaredConst.add(id.name);
  11212. const topNode = parentStack[parentStack.length - 2];
  11213. s.prependRight(topNode.start, `const ${id.name} = ${binding};\n`);
  11214. }
  11215. } else if (parent.type === "CallExpression") {
  11216. s.update(id.start, id.end, binding);
  11217. s.prependRight(id.start, `(0,`);
  11218. s.appendLeft(id.end, `)`);
  11219. } else if (!(parent.type === "ClassExpression" && id === parent.id)) s.update(id.start, id.end, binding);
  11220. },
  11221. onImportMeta(node) {
  11222. s.update(node.start, node.end, ssrImportMetaKey);
  11223. },
  11224. onDynamicImport(node) {
  11225. s.update(node.start, node.start + 6, ssrDynamicImportKey);
  11226. if (node.type === "ImportExpression" && node.source.type === "Literal") dynamicDeps.add(node.source.value);
  11227. }
  11228. });
  11229. let map;
  11230. if (inMap?.mappings === "") map = inMap;
  11231. else {
  11232. map = s.generateMap({ hires: "boundary" });
  11233. map.sources = [path.basename(url)];
  11234. map.sourcesContent = [originalCode];
  11235. if (inMap && inMap.mappings && "sources" in inMap && inMap.sources.length > 0) map = combineSourcemaps(url, [map, inMap]);
  11236. }
  11237. return {
  11238. code: s.toString(),
  11239. map,
  11240. ssr: true,
  11241. deps: [...deps],
  11242. dynamicDeps: [...dynamicDeps]
  11243. };
  11244. }
  11245. function getIdentifierNameOrLiteralValue$1(node) {
  11246. return node.type === "Identifier" ? node.name : node.value;
  11247. }
  11248. const isNodeInPatternWeakSet = /* @__PURE__ */ new WeakSet();
  11249. const setIsNodeInPattern = (node) => isNodeInPatternWeakSet.add(node);
  11250. const isNodeInPattern = (node) => isNodeInPatternWeakSet.has(node);
  11251. /**
  11252. * Same logic from \@vue/compiler-core & \@vue/compiler-sfc
  11253. * Except this is using acorn AST
  11254. */
  11255. function walk(root, { onIdentifier, onImportMeta, onDynamicImport, onStatements }) {
  11256. const parentStack = [];
  11257. const varKindStack = [];
  11258. const scopeMap = /* @__PURE__ */ new WeakMap();
  11259. const identifiers = [];
  11260. const setScope = (node, name) => {
  11261. let scopeIds = scopeMap.get(node);
  11262. if (scopeIds && scopeIds.has(name)) return;
  11263. if (!scopeIds) {
  11264. scopeIds = /* @__PURE__ */ new Set();
  11265. scopeMap.set(node, scopeIds);
  11266. }
  11267. scopeIds.add(name);
  11268. };
  11269. function isInScope(name, parents) {
  11270. return parents.some((node) => scopeMap.get(node)?.has(name));
  11271. }
  11272. function handlePattern(p, parentScope) {
  11273. if (p.type === "Identifier") setScope(parentScope, p.name);
  11274. else if (p.type === "RestElement") handlePattern(p.argument, parentScope);
  11275. else if (p.type === "ObjectPattern") p.properties.forEach((property) => {
  11276. if (property.type === "RestElement") setScope(parentScope, property.argument.name);
  11277. else handlePattern(property.value, parentScope);
  11278. });
  11279. else if (p.type === "ArrayPattern") p.elements.forEach((element) => {
  11280. if (element) handlePattern(element, parentScope);
  11281. });
  11282. else if (p.type === "AssignmentPattern") handlePattern(p.left, parentScope);
  11283. else setScope(parentScope, p.name);
  11284. }
  11285. walk$1(root, {
  11286. enter(node, parent) {
  11287. if (node.type === "ImportDeclaration") return this.skip();
  11288. if (node.type === "Program" || node.type === "BlockStatement" || node.type === "StaticBlock") onStatements(node.body);
  11289. else if (node.type === "SwitchCase") onStatements(node.consequent);
  11290. if (parent && !(parent.type === "IfStatement" && node === parent.alternate)) parentStack.unshift(parent);
  11291. if (node.type === "VariableDeclaration") varKindStack.unshift(node.kind);
  11292. if (node.type === "MetaProperty" && node.meta.name === "import") onImportMeta(node);
  11293. else if (node.type === "ImportExpression") onDynamicImport(node);
  11294. if (node.type === "Identifier") {
  11295. if (!isInScope(node.name, parentStack) && isRefIdentifier(node, parent, parentStack)) identifiers.push([node, parentStack.slice(0)]);
  11296. } else if (isFunction(node)) {
  11297. if (node.type === "FunctionDeclaration") {
  11298. const parentScope = findParentScope(parentStack);
  11299. if (parentScope) setScope(parentScope, node.id.name);
  11300. }
  11301. if (node.type === "FunctionExpression" && node.id) setScope(node, node.id.name);
  11302. node.params.forEach((p) => {
  11303. if (p.type === "ObjectPattern" || p.type === "ArrayPattern") {
  11304. handlePattern(p, node);
  11305. return;
  11306. }
  11307. walk$1(p.type === "AssignmentPattern" ? p.left : p, { enter(child, parent) {
  11308. if (parent?.type === "AssignmentPattern" && parent.right === child) return this.skip();
  11309. if (child.type !== "Identifier") return;
  11310. if (isStaticPropertyKey(child, parent)) return;
  11311. if (parent?.type === "TemplateLiteral" && parent.expressions.includes(child) || parent?.type === "CallExpression" && parent.callee === child) return;
  11312. setScope(node, child.name);
  11313. } });
  11314. });
  11315. } else if (node.type === "ClassDeclaration") {
  11316. const parentScope = findParentScope(parentStack);
  11317. if (parentScope) setScope(parentScope, node.id.name);
  11318. } else if (node.type === "ClassExpression" && node.id) setScope(node, node.id.name);
  11319. else if (node.type === "Property" && parent.type === "ObjectPattern") setIsNodeInPattern(node);
  11320. else if (node.type === "VariableDeclarator") {
  11321. const parentFunction = findParentScope(parentStack, varKindStack[0] === "var");
  11322. if (parentFunction) handlePattern(node.id, parentFunction);
  11323. } else if (node.type === "CatchClause" && node.param) handlePattern(node.param, node);
  11324. },
  11325. leave(node, parent) {
  11326. if (parent && !(parent.type === "IfStatement" && node === parent.alternate)) parentStack.shift();
  11327. if (node.type === "VariableDeclaration") varKindStack.shift();
  11328. }
  11329. });
  11330. identifiers.forEach(([node, stack]) => {
  11331. if (!isInScope(node.name, stack)) onIdentifier(node, stack[0], stack);
  11332. });
  11333. }
  11334. function isRefIdentifier(id, parent, parentStack) {
  11335. if (parent.type === "CatchClause" || (parent.type === "VariableDeclarator" || parent.type === "ClassDeclaration") && parent.id === id) return false;
  11336. if (isFunction(parent)) {
  11337. if (parent.id === id) return false;
  11338. if (parent.params.includes(id)) return false;
  11339. }
  11340. if (parent.type === "MethodDefinition" && !parent.computed) return false;
  11341. if (parent.type === "PropertyDefinition" && !parent.computed) return parent.value === id;
  11342. if (isStaticPropertyKey(id, parent)) return false;
  11343. if (isNodeInPattern(parent) && parent.value === id) return false;
  11344. if (parent.type === "ArrayPattern" && !isInDestructuringAssignment(parent, parentStack)) return false;
  11345. if (parent.type === "MemberExpression" && parent.property === id && !parent.computed) return false;
  11346. if (parent.type === "MetaProperty") return false;
  11347. if (parent.type === "ExportSpecifier" || parent.type === "ExportAllDeclaration") return false;
  11348. if (id.name === "arguments") return false;
  11349. return true;
  11350. }
  11351. const isStaticProperty = (node) => node.type === "Property" && !node.computed;
  11352. const isStaticPropertyKey = (node, parent) => parent && isStaticProperty(parent) && parent.key === node;
  11353. const functionNodeTypeRE = /Function(?:Expression|Declaration)$|Method$/;
  11354. function isFunction(node) {
  11355. return functionNodeTypeRE.test(node.type);
  11356. }
  11357. const blockNodeTypeRE = /^BlockStatement$|^For(?:In|Of)?Statement$/;
  11358. function isBlock(node) {
  11359. return blockNodeTypeRE.test(node.type);
  11360. }
  11361. function findParentScope(parentStack, isVar = false) {
  11362. return parentStack.find(isVar ? isFunction : isBlock);
  11363. }
  11364. function isInDestructuringAssignment(parent, parentStack) {
  11365. if (parent.type === "Property" || parent.type === "ArrayPattern") return parentStack.some((i) => i.type === "AssignmentExpression");
  11366. return false;
  11367. }
  11368. //#endregion
  11369. //#region ../../node_modules/.pnpm/is-docker@3.0.0/node_modules/is-docker/index.js
  11370. let isDockerCached;
  11371. function hasDockerEnv() {
  11372. try {
  11373. fs.statSync("/.dockerenv");
  11374. return true;
  11375. } catch {
  11376. return false;
  11377. }
  11378. }
  11379. function hasDockerCGroup() {
  11380. try {
  11381. return fs.readFileSync("/proc/self/cgroup", "utf8").includes("docker");
  11382. } catch {
  11383. return false;
  11384. }
  11385. }
  11386. function isDocker() {
  11387. if (isDockerCached === void 0) isDockerCached = hasDockerEnv() || hasDockerCGroup();
  11388. return isDockerCached;
  11389. }
  11390. //#endregion
  11391. //#region ../../node_modules/.pnpm/is-inside-container@1.0.0/node_modules/is-inside-container/index.js
  11392. let cachedResult;
  11393. const hasContainerEnv = () => {
  11394. try {
  11395. fs.statSync("/run/.containerenv");
  11396. return true;
  11397. } catch {
  11398. return false;
  11399. }
  11400. };
  11401. function isInsideContainer() {
  11402. if (cachedResult === void 0) cachedResult = hasContainerEnv() || isDocker();
  11403. return cachedResult;
  11404. }
  11405. //#endregion
  11406. //#region ../../node_modules/.pnpm/is-wsl@3.1.0/node_modules/is-wsl/index.js
  11407. const isWsl = () => {
  11408. if (process$1.platform !== "linux") return false;
  11409. if (os.release().toLowerCase().includes("microsoft")) {
  11410. if (isInsideContainer()) return false;
  11411. return true;
  11412. }
  11413. try {
  11414. return fs.readFileSync("/proc/version", "utf8").toLowerCase().includes("microsoft") ? !isInsideContainer() : false;
  11415. } catch {
  11416. return false;
  11417. }
  11418. };
  11419. var is_wsl_default = process$1.env.__IS_WSL_TEST__ ? isWsl : isWsl();
  11420. //#endregion
  11421. //#region ../../node_modules/.pnpm/wsl-utils@0.1.0/node_modules/wsl-utils/index.js
  11422. const wslDrivesMountPoint = (() => {
  11423. const defaultMountPoint = "/mnt/";
  11424. let mountPoint;
  11425. return async function() {
  11426. if (mountPoint) return mountPoint;
  11427. const configFilePath = "/etc/wsl.conf";
  11428. let isConfigFileExists = false;
  11429. try {
  11430. await fsp.access(configFilePath, constants.F_OK);
  11431. isConfigFileExists = true;
  11432. } catch {}
  11433. if (!isConfigFileExists) return defaultMountPoint;
  11434. const configContent = await fsp.readFile(configFilePath, { encoding: "utf8" });
  11435. const configMountPoint = /(?<!#.*)root\s*=\s*(?<mountPoint>.*)/g.exec(configContent);
  11436. if (!configMountPoint) return defaultMountPoint;
  11437. mountPoint = configMountPoint.groups.mountPoint.trim();
  11438. mountPoint = mountPoint.endsWith("/") ? mountPoint : `${mountPoint}/`;
  11439. return mountPoint;
  11440. };
  11441. })();
  11442. const powerShellPathFromWsl = async () => {
  11443. return `${await wslDrivesMountPoint()}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`;
  11444. };
  11445. const powerShellPath = async () => {
  11446. if (is_wsl_default) return powerShellPathFromWsl();
  11447. return `${process$1.env.SYSTEMROOT || process$1.env.windir || String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;
  11448. };
  11449. //#endregion
  11450. //#region ../../node_modules/.pnpm/define-lazy-prop@3.0.0/node_modules/define-lazy-prop/index.js
  11451. function defineLazyProperty(object, propertyName, valueGetter) {
  11452. const define = (value) => Object.defineProperty(object, propertyName, {
  11453. value,
  11454. enumerable: true,
  11455. writable: true
  11456. });
  11457. Object.defineProperty(object, propertyName, {
  11458. configurable: true,
  11459. enumerable: true,
  11460. get() {
  11461. const result = valueGetter();
  11462. define(result);
  11463. return result;
  11464. },
  11465. set(value) {
  11466. define(value);
  11467. }
  11468. });
  11469. return object;
  11470. }
  11471. //#endregion
  11472. //#region ../../node_modules/.pnpm/default-browser-id@5.0.1/node_modules/default-browser-id/index.js
  11473. const execFileAsync$3 = promisify(execFile);
  11474. async function defaultBrowserId() {
  11475. if (process$1.platform !== "darwin") throw new Error("macOS only");
  11476. const { stdout } = await execFileAsync$3("defaults", [
  11477. "read",
  11478. "com.apple.LaunchServices/com.apple.launchservices.secure",
  11479. "LSHandlers"
  11480. ]);
  11481. const browserId = /LSHandlerRoleAll = "(?!-)(?<id>[^"]+?)";\s+?LSHandlerURLScheme = (?:http|https);/.exec(stdout)?.groups.id ?? "com.apple.Safari";
  11482. if (browserId === "com.apple.safari") return "com.apple.Safari";
  11483. return browserId;
  11484. }
  11485. //#endregion
  11486. //#region ../../node_modules/.pnpm/run-applescript@7.1.0/node_modules/run-applescript/index.js
  11487. const execFileAsync$2 = promisify(execFile);
  11488. async function runAppleScript(script, { humanReadableOutput = true, signal } = {}) {
  11489. if (process$1.platform !== "darwin") throw new Error("macOS only");
  11490. const outputArguments = humanReadableOutput ? [] : ["-ss"];
  11491. const execOptions = {};
  11492. if (signal) execOptions.signal = signal;
  11493. const { stdout } = await execFileAsync$2("osascript", [
  11494. "-e",
  11495. script,
  11496. outputArguments
  11497. ], execOptions);
  11498. return stdout.trim();
  11499. }
  11500. //#endregion
  11501. //#region ../../node_modules/.pnpm/bundle-name@4.1.0/node_modules/bundle-name/index.js
  11502. async function bundleName(bundleId) {
  11503. return runAppleScript(`tell application "Finder" to set app_path to application file id "${bundleId}" as string\ntell application "System Events" to get value of property list item "CFBundleName" of property list file (app_path & ":Contents:Info.plist")`);
  11504. }
  11505. //#endregion
  11506. //#region ../../node_modules/.pnpm/default-browser@5.5.0/node_modules/default-browser/windows.js
  11507. const execFileAsync$1 = promisify(execFile);
  11508. const windowsBrowserProgIds = {
  11509. MSEdgeHTM: {
  11510. name: "Edge",
  11511. id: "com.microsoft.edge"
  11512. },
  11513. MSEdgeBHTML: {
  11514. name: "Edge Beta",
  11515. id: "com.microsoft.edge.beta"
  11516. },
  11517. MSEdgeDHTML: {
  11518. name: "Edge Dev",
  11519. id: "com.microsoft.edge.dev"
  11520. },
  11521. AppXq0fevzme2pys62n3e0fbqa7peapykr8v: {
  11522. name: "Edge",
  11523. id: "com.microsoft.edge.old"
  11524. },
  11525. ChromeHTML: {
  11526. name: "Chrome",
  11527. id: "com.google.chrome"
  11528. },
  11529. ChromeBHTML: {
  11530. name: "Chrome Beta",
  11531. id: "com.google.chrome.beta"
  11532. },
  11533. ChromeDHTML: {
  11534. name: "Chrome Dev",
  11535. id: "com.google.chrome.dev"
  11536. },
  11537. ChromiumHTM: {
  11538. name: "Chromium",
  11539. id: "org.chromium.Chromium"
  11540. },
  11541. BraveHTML: {
  11542. name: "Brave",
  11543. id: "com.brave.Browser"
  11544. },
  11545. BraveBHTML: {
  11546. name: "Brave Beta",
  11547. id: "com.brave.Browser.beta"
  11548. },
  11549. BraveDHTML: {
  11550. name: "Brave Dev",
  11551. id: "com.brave.Browser.dev"
  11552. },
  11553. BraveSSHTM: {
  11554. name: "Brave Nightly",
  11555. id: "com.brave.Browser.nightly"
  11556. },
  11557. FirefoxURL: {
  11558. name: "Firefox",
  11559. id: "org.mozilla.firefox"
  11560. },
  11561. OperaStable: {
  11562. name: "Opera",
  11563. id: "com.operasoftware.Opera"
  11564. },
  11565. VivaldiHTM: {
  11566. name: "Vivaldi",
  11567. id: "com.vivaldi.Vivaldi"
  11568. },
  11569. "IE.HTTP": {
  11570. name: "Internet Explorer",
  11571. id: "com.microsoft.ie"
  11572. }
  11573. };
  11574. new Map(Object.entries(windowsBrowserProgIds));
  11575. var UnknownBrowserError = class extends Error {};
  11576. async function defaultBrowser$1(_execFileAsync = execFileAsync$1) {
  11577. const { stdout } = await _execFileAsync("reg", [
  11578. "QUERY",
  11579. " HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http\\UserChoice",
  11580. "/v",
  11581. "ProgId"
  11582. ]);
  11583. const match = /ProgId\s*REG_SZ\s*(?<id>\S+)/.exec(stdout);
  11584. if (!match) throw new UnknownBrowserError(`Cannot find Windows browser in stdout: ${JSON.stringify(stdout)}`);
  11585. const { id } = match.groups;
  11586. const dotIndex = id.lastIndexOf(".");
  11587. const hyphenIndex = id.lastIndexOf("-");
  11588. const baseIdByDot = dotIndex === -1 ? void 0 : id.slice(0, dotIndex);
  11589. const baseIdByHyphen = hyphenIndex === -1 ? void 0 : id.slice(0, hyphenIndex);
  11590. return windowsBrowserProgIds[id] ?? windowsBrowserProgIds[baseIdByDot] ?? windowsBrowserProgIds[baseIdByHyphen] ?? {
  11591. name: id,
  11592. id
  11593. };
  11594. }
  11595. //#endregion
  11596. //#region ../../node_modules/.pnpm/default-browser@5.5.0/node_modules/default-browser/index.js
  11597. const execFileAsync = promisify(execFile);
  11598. const titleize = (string) => string.toLowerCase().replaceAll(/(?:^|\s|-)\S/g, (x) => x.toUpperCase());
  11599. async function defaultBrowser() {
  11600. if (process$1.platform === "darwin") {
  11601. const id = await defaultBrowserId();
  11602. return {
  11603. name: await bundleName(id),
  11604. id
  11605. };
  11606. }
  11607. if (process$1.platform === "linux") {
  11608. const { stdout } = await execFileAsync("xdg-mime", [
  11609. "query",
  11610. "default",
  11611. "x-scheme-handler/http"
  11612. ]);
  11613. const id = stdout.trim();
  11614. return {
  11615. name: titleize(id.replace(/.desktop$/, "").replace("-", " ")),
  11616. id
  11617. };
  11618. }
  11619. if (process$1.platform === "win32") return defaultBrowser$1();
  11620. throw new Error("Only macOS, Linux, and Windows are supported");
  11621. }
  11622. //#endregion
  11623. //#region ../../node_modules/.pnpm/open@10.2.0/node_modules/open/index.js
  11624. const execFile$1 = promisify(childProcess.execFile);
  11625. const __dirname = path.dirname(fileURLToPath(import.meta.url));
  11626. const localXdgOpenPath = path.join(__dirname, "xdg-open");
  11627. const { platform, arch } = process$1;
  11628. /**
  11629. Get the default browser name in Windows from WSL.
  11630. @returns {Promise<string>} Browser name.
  11631. */
  11632. async function getWindowsDefaultBrowserFromWsl() {
  11633. const powershellPath = await powerShellPath();
  11634. const rawCommand = String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`;
  11635. const { stdout } = await execFile$1(powershellPath, [
  11636. "-NoProfile",
  11637. "-NonInteractive",
  11638. "-ExecutionPolicy",
  11639. "Bypass",
  11640. "-EncodedCommand",
  11641. Buffer$1.from(rawCommand, "utf16le").toString("base64")
  11642. ], { encoding: "utf8" });
  11643. const progId = stdout.trim();
  11644. const browserMap = {
  11645. ChromeHTML: "com.google.chrome",
  11646. BraveHTML: "com.brave.Browser",
  11647. MSEdgeHTM: "com.microsoft.edge",
  11648. FirefoxURL: "org.mozilla.firefox"
  11649. };
  11650. return browserMap[progId] ? { id: browserMap[progId] } : {};
  11651. }
  11652. const pTryEach = async (array, mapper) => {
  11653. let latestError;
  11654. for (const item of array) try {
  11655. return await mapper(item);
  11656. } catch (error) {
  11657. latestError = error;
  11658. }
  11659. throw latestError;
  11660. };
  11661. const baseOpen = async (options) => {
  11662. options = {
  11663. wait: false,
  11664. background: false,
  11665. newInstance: false,
  11666. allowNonzeroExitCode: false,
  11667. ...options
  11668. };
  11669. if (Array.isArray(options.app)) return pTryEach(options.app, (singleApp) => baseOpen({
  11670. ...options,
  11671. app: singleApp
  11672. }));
  11673. let { name: app, arguments: appArguments = [] } = options.app ?? {};
  11674. appArguments = [...appArguments];
  11675. if (Array.isArray(app)) return pTryEach(app, (appName) => baseOpen({
  11676. ...options,
  11677. app: {
  11678. name: appName,
  11679. arguments: appArguments
  11680. }
  11681. }));
  11682. if (app === "browser" || app === "browserPrivate") {
  11683. const ids = {
  11684. "com.google.chrome": "chrome",
  11685. "google-chrome.desktop": "chrome",
  11686. "com.brave.Browser": "brave",
  11687. "org.mozilla.firefox": "firefox",
  11688. "firefox.desktop": "firefox",
  11689. "com.microsoft.msedge": "edge",
  11690. "com.microsoft.edge": "edge",
  11691. "com.microsoft.edgemac": "edge",
  11692. "microsoft-edge.desktop": "edge"
  11693. };
  11694. const flags = {
  11695. chrome: "--incognito",
  11696. brave: "--incognito",
  11697. firefox: "--private-window",
  11698. edge: "--inPrivate"
  11699. };
  11700. const browser = is_wsl_default ? await getWindowsDefaultBrowserFromWsl() : await defaultBrowser();
  11701. if (browser.id in ids) {
  11702. const browserName = ids[browser.id];
  11703. if (app === "browserPrivate") appArguments.push(flags[browserName]);
  11704. return baseOpen({
  11705. ...options,
  11706. app: {
  11707. name: apps[browserName],
  11708. arguments: appArguments
  11709. }
  11710. });
  11711. }
  11712. throw new Error(`${browser.name} is not supported as a default browser`);
  11713. }
  11714. let command;
  11715. const cliArguments = [];
  11716. const childProcessOptions = {};
  11717. if (platform === "darwin") {
  11718. command = "open";
  11719. if (options.wait) cliArguments.push("--wait-apps");
  11720. if (options.background) cliArguments.push("--background");
  11721. if (options.newInstance) cliArguments.push("--new");
  11722. if (app) cliArguments.push("-a", app);
  11723. } else if (platform === "win32" || is_wsl_default && !isInsideContainer() && !app) {
  11724. command = await powerShellPath();
  11725. cliArguments.push("-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-EncodedCommand");
  11726. if (!is_wsl_default) childProcessOptions.windowsVerbatimArguments = true;
  11727. const encodedArguments = ["Start"];
  11728. if (options.wait) encodedArguments.push("-Wait");
  11729. if (app) {
  11730. encodedArguments.push(`"\`"${app}\`""`);
  11731. if (options.target) appArguments.push(options.target);
  11732. } else if (options.target) encodedArguments.push(`"${options.target}"`);
  11733. if (appArguments.length > 0) {
  11734. appArguments = appArguments.map((argument) => `"\`"${argument}\`""`);
  11735. encodedArguments.push("-ArgumentList", appArguments.join(","));
  11736. }
  11737. options.target = Buffer$1.from(encodedArguments.join(" "), "utf16le").toString("base64");
  11738. } else {
  11739. if (app) command = app;
  11740. else {
  11741. const isBundled = !__dirname || __dirname === "/";
  11742. let exeLocalXdgOpen = false;
  11743. try {
  11744. await fsp.access(localXdgOpenPath, constants.X_OK);
  11745. exeLocalXdgOpen = true;
  11746. } catch {}
  11747. command = process$1.versions.electron ?? (platform === "android" || isBundled || !exeLocalXdgOpen) ? "xdg-open" : localXdgOpenPath;
  11748. }
  11749. if (appArguments.length > 0) cliArguments.push(...appArguments);
  11750. if (!options.wait) {
  11751. childProcessOptions.stdio = "ignore";
  11752. childProcessOptions.detached = true;
  11753. }
  11754. }
  11755. if (platform === "darwin" && appArguments.length > 0) cliArguments.push("--args", ...appArguments);
  11756. if (options.target) cliArguments.push(options.target);
  11757. const subprocess = childProcess.spawn(command, cliArguments, childProcessOptions);
  11758. if (options.wait) return new Promise((resolve, reject) => {
  11759. subprocess.once("error", reject);
  11760. subprocess.once("close", (exitCode) => {
  11761. if (!options.allowNonzeroExitCode && exitCode > 0) {
  11762. reject(/* @__PURE__ */ new Error(`Exited with code ${exitCode}`));
  11763. return;
  11764. }
  11765. resolve(subprocess);
  11766. });
  11767. });
  11768. subprocess.unref();
  11769. return subprocess;
  11770. };
  11771. const open = (target, options) => {
  11772. if (typeof target !== "string") throw new TypeError("Expected a `target`");
  11773. return baseOpen({
  11774. ...options,
  11775. target
  11776. });
  11777. };
  11778. function detectArchBinary(binary) {
  11779. if (typeof binary === "string" || Array.isArray(binary)) return binary;
  11780. const { [arch]: archBinary } = binary;
  11781. if (!archBinary) throw new Error(`${arch} is not supported`);
  11782. return archBinary;
  11783. }
  11784. function detectPlatformBinary({ [platform]: platformBinary }, { wsl }) {
  11785. if (wsl && is_wsl_default) return detectArchBinary(wsl);
  11786. if (!platformBinary) throw new Error(`${platform} is not supported`);
  11787. return detectArchBinary(platformBinary);
  11788. }
  11789. const apps = {};
  11790. defineLazyProperty(apps, "chrome", () => detectPlatformBinary({
  11791. darwin: "google chrome",
  11792. win32: "chrome",
  11793. linux: [
  11794. "google-chrome",
  11795. "google-chrome-stable",
  11796. "chromium"
  11797. ]
  11798. }, { wsl: {
  11799. ia32: "/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe",
  11800. x64: ["/mnt/c/Program Files/Google/Chrome/Application/chrome.exe", "/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe"]
  11801. } }));
  11802. defineLazyProperty(apps, "brave", () => detectPlatformBinary({
  11803. darwin: "brave browser",
  11804. win32: "brave",
  11805. linux: ["brave-browser", "brave"]
  11806. }, { wsl: {
  11807. ia32: "/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe",
  11808. x64: ["/mnt/c/Program Files/BraveSoftware/Brave-Browser/Application/brave.exe", "/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe"]
  11809. } }));
  11810. defineLazyProperty(apps, "firefox", () => detectPlatformBinary({
  11811. darwin: "firefox",
  11812. win32: String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,
  11813. linux: "firefox"
  11814. }, { wsl: "/mnt/c/Program Files/Mozilla Firefox/firefox.exe" }));
  11815. defineLazyProperty(apps, "edge", () => detectPlatformBinary({
  11816. darwin: "microsoft edge",
  11817. win32: "msedge",
  11818. linux: ["microsoft-edge", "microsoft-edge-dev"]
  11819. }, { wsl: "/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe" }));
  11820. defineLazyProperty(apps, "browser", () => "browser");
  11821. defineLazyProperty(apps, "browserPrivate", () => "browserPrivate");
  11822. //#endregion
  11823. //#region ../../node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/windows.js
  11824. var require_windows = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  11825. module.exports = isexe;
  11826. isexe.sync = sync;
  11827. var fs$5 = __require("fs");
  11828. function checkPathExt(path, options) {
  11829. var pathext = options.pathExt !== void 0 ? options.pathExt : process.env.PATHEXT;
  11830. if (!pathext) return true;
  11831. pathext = pathext.split(";");
  11832. if (pathext.indexOf("") !== -1) return true;
  11833. for (var i = 0; i < pathext.length; i++) {
  11834. var p = pathext[i].toLowerCase();
  11835. if (p && path.substr(-p.length).toLowerCase() === p) return true;
  11836. }
  11837. return false;
  11838. }
  11839. function checkStat(stat, path, options) {
  11840. if (!stat.isSymbolicLink() && !stat.isFile()) return false;
  11841. return checkPathExt(path, options);
  11842. }
  11843. function isexe(path, options, cb) {
  11844. fs$5.stat(path, function(er, stat) {
  11845. cb(er, er ? false : checkStat(stat, path, options));
  11846. });
  11847. }
  11848. function sync(path, options) {
  11849. return checkStat(fs$5.statSync(path), path, options);
  11850. }
  11851. }));
  11852. //#endregion
  11853. //#region ../../node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/mode.js
  11854. var require_mode = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  11855. module.exports = isexe;
  11856. isexe.sync = sync;
  11857. var fs$4 = __require("fs");
  11858. function isexe(path, options, cb) {
  11859. fs$4.stat(path, function(er, stat) {
  11860. cb(er, er ? false : checkStat(stat, options));
  11861. });
  11862. }
  11863. function sync(path, options) {
  11864. return checkStat(fs$4.statSync(path), options);
  11865. }
  11866. function checkStat(stat, options) {
  11867. return stat.isFile() && checkMode(stat, options);
  11868. }
  11869. function checkMode(stat, options) {
  11870. var mod = stat.mode;
  11871. var uid = stat.uid;
  11872. var gid = stat.gid;
  11873. var myUid = options.uid !== void 0 ? options.uid : process.getuid && process.getuid();
  11874. var myGid = options.gid !== void 0 ? options.gid : process.getgid && process.getgid();
  11875. var u = parseInt("100", 8);
  11876. var g = parseInt("010", 8);
  11877. var o = parseInt("001", 8);
  11878. var ug = u | g;
  11879. return mod & o || mod & g && gid === myGid || mod & u && uid === myUid || mod & ug && myUid === 0;
  11880. }
  11881. }));
  11882. //#endregion
  11883. //#region ../../node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/index.js
  11884. var require_isexe = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  11885. __require("fs");
  11886. var core;
  11887. if (process.platform === "win32" || global.TESTING_WINDOWS) core = require_windows();
  11888. else core = require_mode();
  11889. module.exports = isexe;
  11890. isexe.sync = sync;
  11891. function isexe(path, options, cb) {
  11892. if (typeof options === "function") {
  11893. cb = options;
  11894. options = {};
  11895. }
  11896. if (!cb) {
  11897. if (typeof Promise !== "function") throw new TypeError("callback not provided");
  11898. return new Promise(function(resolve, reject) {
  11899. isexe(path, options || {}, function(er, is) {
  11900. if (er) reject(er);
  11901. else resolve(is);
  11902. });
  11903. });
  11904. }
  11905. core(path, options || {}, function(er, is) {
  11906. if (er) {
  11907. if (er.code === "EACCES" || options && options.ignoreErrors) {
  11908. er = null;
  11909. is = false;
  11910. }
  11911. }
  11912. cb(er, is);
  11913. });
  11914. }
  11915. function sync(path, options) {
  11916. try {
  11917. return core.sync(path, options || {});
  11918. } catch (er) {
  11919. if (options && options.ignoreErrors || er.code === "EACCES") return false;
  11920. else throw er;
  11921. }
  11922. }
  11923. }));
  11924. //#endregion
  11925. //#region ../../node_modules/.pnpm/which@2.0.2/node_modules/which/which.js
  11926. var require_which = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  11927. const isWindows = process.platform === "win32" || process.env.OSTYPE === "cygwin" || process.env.OSTYPE === "msys";
  11928. const path$5 = __require("path");
  11929. const COLON = isWindows ? ";" : ":";
  11930. const isexe = require_isexe();
  11931. const getNotFoundError = (cmd) => Object.assign(/* @__PURE__ */ new Error(`not found: ${cmd}`), { code: "ENOENT" });
  11932. const getPathInfo = (cmd, opt) => {
  11933. const colon = opt.colon || COLON;
  11934. const pathEnv = cmd.match(/\//) || isWindows && cmd.match(/\\/) ? [""] : [...isWindows ? [process.cwd()] : [], ...(opt.path || process.env.PATH || "").split(colon)];
  11935. const pathExtExe = isWindows ? opt.pathExt || process.env.PATHEXT || ".EXE;.CMD;.BAT;.COM" : "";
  11936. const pathExt = isWindows ? pathExtExe.split(colon) : [""];
  11937. if (isWindows) {
  11938. if (cmd.indexOf(".") !== -1 && pathExt[0] !== "") pathExt.unshift("");
  11939. }
  11940. return {
  11941. pathEnv,
  11942. pathExt,
  11943. pathExtExe
  11944. };
  11945. };
  11946. const which = (cmd, opt, cb) => {
  11947. if (typeof opt === "function") {
  11948. cb = opt;
  11949. opt = {};
  11950. }
  11951. if (!opt) opt = {};
  11952. const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt);
  11953. const found = [];
  11954. const step = (i) => new Promise((resolve, reject) => {
  11955. if (i === pathEnv.length) return opt.all && found.length ? resolve(found) : reject(getNotFoundError(cmd));
  11956. const ppRaw = pathEnv[i];
  11957. const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw;
  11958. const pCmd = path$5.join(pathPart, cmd);
  11959. resolve(subStep(!pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd, i, 0));
  11960. });
  11961. const subStep = (p, i, ii) => new Promise((resolve, reject) => {
  11962. if (ii === pathExt.length) return resolve(step(i + 1));
  11963. const ext = pathExt[ii];
  11964. isexe(p + ext, { pathExt: pathExtExe }, (er, is) => {
  11965. if (!er && is) if (opt.all) found.push(p + ext);
  11966. else return resolve(p + ext);
  11967. return resolve(subStep(p, i, ii + 1));
  11968. });
  11969. });
  11970. return cb ? step(0).then((res) => cb(null, res), cb) : step(0);
  11971. };
  11972. const whichSync = (cmd, opt) => {
  11973. opt = opt || {};
  11974. const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt);
  11975. const found = [];
  11976. for (let i = 0; i < pathEnv.length; i++) {
  11977. const ppRaw = pathEnv[i];
  11978. const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw;
  11979. const pCmd = path$5.join(pathPart, cmd);
  11980. const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd;
  11981. for (let j = 0; j < pathExt.length; j++) {
  11982. const cur = p + pathExt[j];
  11983. try {
  11984. if (isexe.sync(cur, { pathExt: pathExtExe })) if (opt.all) found.push(cur);
  11985. else return cur;
  11986. } catch (ex) {}
  11987. }
  11988. }
  11989. if (opt.all && found.length) return found;
  11990. if (opt.nothrow) return null;
  11991. throw getNotFoundError(cmd);
  11992. };
  11993. module.exports = which;
  11994. which.sync = whichSync;
  11995. }));
  11996. //#endregion
  11997. //#region ../../node_modules/.pnpm/path-key@3.1.1/node_modules/path-key/index.js
  11998. var require_path_key = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  11999. const pathKey = (options = {}) => {
  12000. const environment = options.env || process.env;
  12001. if ((options.platform || process.platform) !== "win32") return "PATH";
  12002. return Object.keys(environment).reverse().find((key) => key.toUpperCase() === "PATH") || "Path";
  12003. };
  12004. module.exports = pathKey;
  12005. module.exports.default = pathKey;
  12006. }));
  12007. //#endregion
  12008. //#region ../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/resolveCommand.js
  12009. var require_resolveCommand = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  12010. const path$4 = __require("path");
  12011. const which = require_which();
  12012. const getPathKey = require_path_key();
  12013. function resolveCommandAttempt(parsed, withoutPathExt) {
  12014. const env = parsed.options.env || process.env;
  12015. const cwd = process.cwd();
  12016. const hasCustomCwd = parsed.options.cwd != null;
  12017. const shouldSwitchCwd = hasCustomCwd && process.chdir !== void 0 && !process.chdir.disabled;
  12018. if (shouldSwitchCwd) try {
  12019. process.chdir(parsed.options.cwd);
  12020. } catch (err) {}
  12021. let resolved;
  12022. try {
  12023. resolved = which.sync(parsed.command, {
  12024. path: env[getPathKey({ env })],
  12025. pathExt: withoutPathExt ? path$4.delimiter : void 0
  12026. });
  12027. } catch (e) {} finally {
  12028. if (shouldSwitchCwd) process.chdir(cwd);
  12029. }
  12030. if (resolved) resolved = path$4.resolve(hasCustomCwd ? parsed.options.cwd : "", resolved);
  12031. return resolved;
  12032. }
  12033. function resolveCommand(parsed) {
  12034. return resolveCommandAttempt(parsed) || resolveCommandAttempt(parsed, true);
  12035. }
  12036. module.exports = resolveCommand;
  12037. }));
  12038. //#endregion
  12039. //#region ../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/escape.js
  12040. var require_escape = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  12041. const metaCharsRegExp = /([()\][%!^"`<>&|;, *?])/g;
  12042. function escapeCommand(arg) {
  12043. arg = arg.replace(metaCharsRegExp, "^$1");
  12044. return arg;
  12045. }
  12046. function escapeArgument(arg, doubleEscapeMetaChars) {
  12047. arg = `${arg}`;
  12048. arg = arg.replace(/(?=(\\+?)?)\1"/g, "$1$1\\\"");
  12049. arg = arg.replace(/(?=(\\+?)?)\1$/, "$1$1");
  12050. arg = `"${arg}"`;
  12051. arg = arg.replace(metaCharsRegExp, "^$1");
  12052. if (doubleEscapeMetaChars) arg = arg.replace(metaCharsRegExp, "^$1");
  12053. return arg;
  12054. }
  12055. module.exports.command = escapeCommand;
  12056. module.exports.argument = escapeArgument;
  12057. }));
  12058. //#endregion
  12059. //#region ../../node_modules/.pnpm/shebang-regex@3.0.0/node_modules/shebang-regex/index.js
  12060. var require_shebang_regex = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  12061. module.exports = /^#!(.*)/;
  12062. }));
  12063. //#endregion
  12064. //#region ../../node_modules/.pnpm/shebang-command@2.0.0/node_modules/shebang-command/index.js
  12065. var require_shebang_command = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  12066. const shebangRegex = require_shebang_regex();
  12067. module.exports = (string = "") => {
  12068. const match = string.match(shebangRegex);
  12069. if (!match) return null;
  12070. const [path, argument] = match[0].replace(/#! ?/, "").split(" ");
  12071. const binary = path.split("/").pop();
  12072. if (binary === "env") return argument;
  12073. return argument ? `${binary} ${argument}` : binary;
  12074. };
  12075. }));
  12076. //#endregion
  12077. //#region ../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/readShebang.js
  12078. var require_readShebang = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  12079. const fs$3 = __require("fs");
  12080. const shebangCommand = require_shebang_command();
  12081. function readShebang(command) {
  12082. const size = 150;
  12083. const buffer = Buffer.alloc(size);
  12084. let fd;
  12085. try {
  12086. fd = fs$3.openSync(command, "r");
  12087. fs$3.readSync(fd, buffer, 0, size, 0);
  12088. fs$3.closeSync(fd);
  12089. } catch (e) {}
  12090. return shebangCommand(buffer.toString());
  12091. }
  12092. module.exports = readShebang;
  12093. }));
  12094. //#endregion
  12095. //#region ../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/parse.js
  12096. var require_parse = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  12097. const path$3 = __require("path");
  12098. const resolveCommand = require_resolveCommand();
  12099. const escape = require_escape();
  12100. const readShebang = require_readShebang();
  12101. const isWin = process.platform === "win32";
  12102. const isExecutableRegExp = /\.(?:com|exe)$/i;
  12103. const isCmdShimRegExp = /node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;
  12104. function detectShebang(parsed) {
  12105. parsed.file = resolveCommand(parsed);
  12106. const shebang = parsed.file && readShebang(parsed.file);
  12107. if (shebang) {
  12108. parsed.args.unshift(parsed.file);
  12109. parsed.command = shebang;
  12110. return resolveCommand(parsed);
  12111. }
  12112. return parsed.file;
  12113. }
  12114. function parseNonShell(parsed) {
  12115. if (!isWin) return parsed;
  12116. const commandFile = detectShebang(parsed);
  12117. const needsShell = !isExecutableRegExp.test(commandFile);
  12118. if (parsed.options.forceShell || needsShell) {
  12119. const needsDoubleEscapeMetaChars = isCmdShimRegExp.test(commandFile);
  12120. parsed.command = path$3.normalize(parsed.command);
  12121. parsed.command = escape.command(parsed.command);
  12122. parsed.args = parsed.args.map((arg) => escape.argument(arg, needsDoubleEscapeMetaChars));
  12123. parsed.args = [
  12124. "/d",
  12125. "/s",
  12126. "/c",
  12127. `"${[parsed.command].concat(parsed.args).join(" ")}"`
  12128. ];
  12129. parsed.command = process.env.comspec || "cmd.exe";
  12130. parsed.options.windowsVerbatimArguments = true;
  12131. }
  12132. return parsed;
  12133. }
  12134. function parse(command, args, options) {
  12135. if (args && !Array.isArray(args)) {
  12136. options = args;
  12137. args = null;
  12138. }
  12139. args = args ? args.slice(0) : [];
  12140. options = Object.assign({}, options);
  12141. const parsed = {
  12142. command,
  12143. args,
  12144. options,
  12145. file: void 0,
  12146. original: {
  12147. command,
  12148. args
  12149. }
  12150. };
  12151. return options.shell ? parsed : parseNonShell(parsed);
  12152. }
  12153. module.exports = parse;
  12154. }));
  12155. //#endregion
  12156. //#region ../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/enoent.js
  12157. var require_enoent = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  12158. const isWin = process.platform === "win32";
  12159. function notFoundError(original, syscall) {
  12160. return Object.assign(/* @__PURE__ */ new Error(`${syscall} ${original.command} ENOENT`), {
  12161. code: "ENOENT",
  12162. errno: "ENOENT",
  12163. syscall: `${syscall} ${original.command}`,
  12164. path: original.command,
  12165. spawnargs: original.args
  12166. });
  12167. }
  12168. function hookChildProcess(cp, parsed) {
  12169. if (!isWin) return;
  12170. const originalEmit = cp.emit;
  12171. cp.emit = function(name, arg1) {
  12172. if (name === "exit") {
  12173. const err = verifyENOENT(arg1, parsed);
  12174. if (err) return originalEmit.call(cp, "error", err);
  12175. }
  12176. return originalEmit.apply(cp, arguments);
  12177. };
  12178. }
  12179. function verifyENOENT(status, parsed) {
  12180. if (isWin && status === 1 && !parsed.file) return notFoundError(parsed.original, "spawn");
  12181. return null;
  12182. }
  12183. function verifyENOENTSync(status, parsed) {
  12184. if (isWin && status === 1 && !parsed.file) return notFoundError(parsed.original, "spawnSync");
  12185. return null;
  12186. }
  12187. module.exports = {
  12188. hookChildProcess,
  12189. verifyENOENT,
  12190. verifyENOENTSync,
  12191. notFoundError
  12192. };
  12193. }));
  12194. //#endregion
  12195. //#region src/node/server/openBrowser.ts
  12196. /**
  12197. * The following is modified based on source found in
  12198. * https://github.com/facebook/create-react-app
  12199. *
  12200. * MIT Licensed
  12201. * Copyright (c) 2015-present, Facebook, Inc.
  12202. * https://github.com/facebook/create-react-app/blob/main/LICENSE
  12203. *
  12204. */
  12205. var import_cross_spawn = /* @__PURE__ */ __toESM((/* @__PURE__ */ __commonJSMin(((exports, module) => {
  12206. const cp = __require("child_process");
  12207. const parse = require_parse();
  12208. const enoent = require_enoent();
  12209. function spawn(command, args, options) {
  12210. const parsed = parse(command, args, options);
  12211. const spawned = cp.spawn(parsed.command, parsed.args, parsed.options);
  12212. enoent.hookChildProcess(spawned, parsed);
  12213. return spawned;
  12214. }
  12215. function spawnSync(command, args, options) {
  12216. const parsed = parse(command, args, options);
  12217. const result = cp.spawnSync(parsed.command, parsed.args, parsed.options);
  12218. result.error = result.error || enoent.verifyENOENTSync(result.status, parsed);
  12219. return result;
  12220. }
  12221. module.exports = spawn;
  12222. module.exports.spawn = spawn;
  12223. module.exports.sync = spawnSync;
  12224. module.exports._parse = parse;
  12225. module.exports._enoent = enoent;
  12226. })))(), 1);
  12227. /**
  12228. * Reads the BROWSER environment variable and decides what to do with it.
  12229. */
  12230. function openBrowser(url, opt, logger) {
  12231. const browser = typeof opt === "string" ? opt : process.env.BROWSER || "";
  12232. if (browser.toLowerCase().endsWith(".js")) executeNodeScript(browser, url, logger);
  12233. else if (browser.toLowerCase() !== "none") startBrowserProcess(browser, process.env.BROWSER_ARGS ? process.env.BROWSER_ARGS.split(" ") : [], url, logger);
  12234. }
  12235. function executeNodeScript(scriptPath, url, logger) {
  12236. const extraArgs = process.argv.slice(2);
  12237. (0, import_cross_spawn.default)(process.execPath, [
  12238. scriptPath,
  12239. ...extraArgs,
  12240. url
  12241. ], { stdio: "inherit" }).on("close", (code) => {
  12242. if (code !== 0) logger.error(import_picocolors.default.red(`\nThe script specified as BROWSER environment variable failed.\n\n${import_picocolors.default.cyan(scriptPath)} exited with code ${code}.`), { error: null });
  12243. });
  12244. }
  12245. const supportedChromiumBrowsers = [
  12246. "Google Chrome Canary",
  12247. "Google Chrome Dev",
  12248. "Google Chrome Beta",
  12249. "Google Chrome",
  12250. "Microsoft Edge",
  12251. "Brave Browser",
  12252. "Vivaldi",
  12253. "Chromium"
  12254. ];
  12255. async function startBrowserProcess(browser, browserArgs, url, logger) {
  12256. const preferredOSXBrowser = browser === "google chrome" ? "Google Chrome" : browser;
  12257. if (process.platform === "darwin" && (!preferredOSXBrowser || supportedChromiumBrowsers.includes(preferredOSXBrowser))) try {
  12258. const ps = await execAsync("ps cax");
  12259. const openedBrowser = preferredOSXBrowser && ps.includes(preferredOSXBrowser) ? preferredOSXBrowser : supportedChromiumBrowsers.find((b) => ps.includes(b));
  12260. if (openedBrowser) {
  12261. await execAsync(`osascript openChrome.js "${url}" "${openedBrowser}"`, { cwd: join(VITE_PACKAGE_DIR, "bin") });
  12262. return true;
  12263. }
  12264. } catch {}
  12265. if (process.platform === "darwin" && browser === "open") browser = void 0;
  12266. try {
  12267. const options = browser ? { app: {
  12268. name: browser,
  12269. arguments: browserArgs
  12270. } } : {};
  12271. new Promise((_, reject) => {
  12272. open(url, options).then((subprocess) => {
  12273. subprocess.on("error", reject);
  12274. }).catch(reject);
  12275. }).catch((err) => {
  12276. logger.error(err.stack || err.message);
  12277. });
  12278. return true;
  12279. } catch {
  12280. return false;
  12281. }
  12282. }
  12283. function execAsync(command, options) {
  12284. return new Promise((resolve, reject) => {
  12285. exec(command, options, (error, stdout) => {
  12286. if (error) reject(error);
  12287. else resolve(stdout.toString());
  12288. });
  12289. });
  12290. }
  12291. //#endregion
  12292. //#region src/node/shortcuts.ts
  12293. function bindCLIShortcuts(server, opts, enabled = process.stdin.isTTY && !process.env.CI) {
  12294. if (!server.httpServer || !enabled) return;
  12295. const isDev = isDevServer(server);
  12296. const previousShortcuts = server._shortcutsState?.options.customShortcuts ?? [];
  12297. const newShortcuts = opts?.customShortcuts ?? [];
  12298. const previousKeys = new Set(previousShortcuts.map((s) => s.key));
  12299. const customShortcuts = [...newShortcuts.filter((s) => !previousKeys.has(s.key)), ...previousShortcuts.map((s) => newShortcuts.find((n) => n.key === s.key) ?? s)];
  12300. const newOptions = {
  12301. ...opts,
  12302. customShortcuts
  12303. };
  12304. if (opts?.print) server.config.logger.info(import_picocolors.default.dim(import_picocolors.default.green(" ➜")) + import_picocolors.default.dim(" press ") + import_picocolors.default.bold("h + enter") + import_picocolors.default.dim(" to show help"));
  12305. const shortcuts = customShortcuts.concat(isDev ? BASE_DEV_SHORTCUTS : BASE_PREVIEW_SHORTCUTS);
  12306. let actionRunning = false;
  12307. const onInput = async (input) => {
  12308. if (actionRunning) return;
  12309. input = input.trim().toLocaleLowerCase();
  12310. if (input === "h") {
  12311. const loggedKeys = /* @__PURE__ */ new Set();
  12312. server.config.logger.info("\n Shortcuts");
  12313. for (const shortcut of shortcuts) {
  12314. if (loggedKeys.has(shortcut.key)) continue;
  12315. loggedKeys.add(shortcut.key);
  12316. if (shortcut.action == null) continue;
  12317. server.config.logger.info(import_picocolors.default.dim(" press ") + import_picocolors.default.bold(`${shortcut.key} + enter`) + import_picocolors.default.dim(` to ${shortcut.description}`));
  12318. }
  12319. return;
  12320. }
  12321. const shortcut = shortcuts.find((shortcut) => shortcut.key === input);
  12322. if (!shortcut || shortcut.action == null) return;
  12323. actionRunning = true;
  12324. await shortcut.action(server);
  12325. actionRunning = false;
  12326. };
  12327. if (!server._shortcutsState) {
  12328. server._shortcutsState = {
  12329. rl: readline.createInterface({ input: process.stdin }),
  12330. options: newOptions
  12331. };
  12332. server.httpServer.on("close", () => {
  12333. if (server._shortcutsState) server._shortcutsState.rl.close();
  12334. });
  12335. } else {
  12336. server._shortcutsState.rl.removeAllListeners("line");
  12337. server._shortcutsState.options = newOptions;
  12338. }
  12339. server._shortcutsState.rl.on("line", onInput);
  12340. }
  12341. const BASE_DEV_SHORTCUTS = [
  12342. {
  12343. key: "r",
  12344. description: "restart the server",
  12345. async action(server) {
  12346. await restartServerWithUrls(server);
  12347. }
  12348. },
  12349. {
  12350. key: "u",
  12351. description: "show server url",
  12352. action(server) {
  12353. server.config.logger.info("");
  12354. server.printUrls();
  12355. }
  12356. },
  12357. {
  12358. key: "o",
  12359. description: "open in browser",
  12360. action(server) {
  12361. server.openBrowser();
  12362. }
  12363. },
  12364. {
  12365. key: "c",
  12366. description: "clear console",
  12367. action(server) {
  12368. server.config.logger.clearScreen("error");
  12369. }
  12370. },
  12371. {
  12372. key: "q",
  12373. description: "quit",
  12374. async action(server) {
  12375. try {
  12376. await server.close();
  12377. } finally {
  12378. process.exit();
  12379. }
  12380. }
  12381. }
  12382. ];
  12383. const BASE_PREVIEW_SHORTCUTS = [{
  12384. key: "o",
  12385. description: "open in browser",
  12386. action(server) {
  12387. const url = server.resolvedUrls?.local[0] ?? server.resolvedUrls?.network[0];
  12388. if (url) openBrowser(url, true, server.config.logger);
  12389. else server.config.logger.warn("No URL available to open in browser");
  12390. }
  12391. }, {
  12392. key: "q",
  12393. description: "quit",
  12394. async action(server) {
  12395. try {
  12396. await server.close();
  12397. } finally {
  12398. process.exit();
  12399. }
  12400. }
  12401. }];
  12402. //#endregion
  12403. //#region src/node/watch.ts
  12404. function getResolvedOutDirs(root, outDir, outputOptions) {
  12405. const resolvedOutDir = path.resolve(root, outDir);
  12406. if (!outputOptions) return new Set([resolvedOutDir]);
  12407. return new Set(arraify(outputOptions).map(({ dir }) => dir ? path.resolve(root, dir) : resolvedOutDir));
  12408. }
  12409. function resolveEmptyOutDir(emptyOutDir, root, outDirs, logger) {
  12410. if (emptyOutDir != null) return emptyOutDir;
  12411. for (const outDir of outDirs) if (!normalizePath(outDir).startsWith(withTrailingSlash(root))) {
  12412. logger?.warn(import_picocolors.default.yellow(`\n${import_picocolors.default.bold(`(!)`)} outDir ${import_picocolors.default.white(import_picocolors.default.dim(outDir))} is not inside project root and will not be emptied.\nUse --emptyOutDir to override.\n`));
  12413. return false;
  12414. }
  12415. return true;
  12416. }
  12417. function resolveChokidarOptions(options, resolvedOutDirs, emptyOutDir, cacheDir) {
  12418. const { ignored: ignoredList, ...otherOptions } = options ?? {};
  12419. const ignored = [
  12420. "**/.git/**",
  12421. "**/node_modules/**",
  12422. "**/test-results/**",
  12423. escapePath(cacheDir) + "/**",
  12424. ...arraify(ignoredList || [])
  12425. ];
  12426. if (emptyOutDir) ignored.push(...[...resolvedOutDirs].map((outDir) => escapePath(outDir) + "/**"));
  12427. return {
  12428. ignored,
  12429. ignoreInitial: true,
  12430. ignorePermissionErrors: true,
  12431. ...otherOptions
  12432. };
  12433. }
  12434. function convertToWatcherOptions(options) {
  12435. if (!options) return;
  12436. return {
  12437. usePolling: options.usePolling,
  12438. pollInterval: options.interval
  12439. };
  12440. }
  12441. var NoopWatcher = class extends EventEmitter {
  12442. constructor(options) {
  12443. super();
  12444. this.options = options;
  12445. }
  12446. add() {
  12447. return this;
  12448. }
  12449. unwatch() {
  12450. return this;
  12451. }
  12452. getWatched() {
  12453. return {};
  12454. }
  12455. ref() {
  12456. return this;
  12457. }
  12458. unref() {
  12459. return this;
  12460. }
  12461. async close() {}
  12462. };
  12463. function createNoopWatcher(options) {
  12464. return new NoopWatcher(options);
  12465. }
  12466. //#endregion
  12467. //#region src/node/publicDir.ts
  12468. const publicFilesMap = /* @__PURE__ */ new WeakMap();
  12469. async function initPublicFiles(config) {
  12470. let fileNames;
  12471. try {
  12472. fileNames = await recursiveReaddir(config.publicDir);
  12473. } catch (e) {
  12474. if (e.code === "ERR_SYMLINK_IN_RECURSIVE_READDIR") return;
  12475. throw e;
  12476. }
  12477. const publicFiles = new Set(fileNames.map((fileName) => fileName.slice(config.publicDir.length)));
  12478. publicFilesMap.set(config, publicFiles);
  12479. return publicFiles;
  12480. }
  12481. function getPublicFiles(config) {
  12482. return publicFilesMap.get(config);
  12483. }
  12484. function checkPublicFile(url, config) {
  12485. const { publicDir } = config;
  12486. if (!publicDir || url[0] !== "/") return;
  12487. const fileName = cleanUrl(url);
  12488. const publicFiles = getPublicFiles(config);
  12489. if (publicFiles) return publicFiles.has(fileName) ? normalizePath(path.join(publicDir, fileName)) : void 0;
  12490. const publicFile = normalizePath(path.join(publicDir, fileName));
  12491. if (!publicFile.startsWith(withTrailingSlash(publicDir))) return;
  12492. return tryStatSync(publicFile)?.isFile() ? publicFile : void 0;
  12493. }
  12494. //#endregion
  12495. //#region ../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/constants.js
  12496. var require_constants = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  12497. const BINARY_TYPES = [
  12498. "nodebuffer",
  12499. "arraybuffer",
  12500. "fragments"
  12501. ];
  12502. const hasBlob = typeof Blob !== "undefined";
  12503. if (hasBlob) BINARY_TYPES.push("blob");
  12504. module.exports = {
  12505. BINARY_TYPES,
  12506. CLOSE_TIMEOUT: 3e4,
  12507. EMPTY_BUFFER: Buffer.alloc(0),
  12508. GUID: "258EAFA5-E914-47DA-95CA-C5AB0DC85B11",
  12509. hasBlob,
  12510. kForOnEventAttribute: Symbol("kIsForOnEventAttribute"),
  12511. kListener: Symbol("kListener"),
  12512. kStatusCode: Symbol("status-code"),
  12513. kWebSocket: Symbol("websocket"),
  12514. NOOP: () => {}
  12515. };
  12516. }));
  12517. //#endregion
  12518. //#region ../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/buffer-util.js
  12519. var require_buffer_util = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  12520. const { EMPTY_BUFFER } = require_constants();
  12521. const FastBuffer = Buffer[Symbol.species];
  12522. /**
  12523. * Merges an array of buffers into a new buffer.
  12524. *
  12525. * @param {Buffer[]} list The array of buffers to concat
  12526. * @param {Number} totalLength The total length of buffers in the list
  12527. * @return {Buffer} The resulting buffer
  12528. * @public
  12529. */
  12530. function concat(list, totalLength) {
  12531. if (list.length === 0) return EMPTY_BUFFER;
  12532. if (list.length === 1) return list[0];
  12533. const target = Buffer.allocUnsafe(totalLength);
  12534. let offset = 0;
  12535. for (let i = 0; i < list.length; i++) {
  12536. const buf = list[i];
  12537. target.set(buf, offset);
  12538. offset += buf.length;
  12539. }
  12540. if (offset < totalLength) return new FastBuffer(target.buffer, target.byteOffset, offset);
  12541. return target;
  12542. }
  12543. /**
  12544. * Masks a buffer using the given mask.
  12545. *
  12546. * @param {Buffer} source The buffer to mask
  12547. * @param {Buffer} mask The mask to use
  12548. * @param {Buffer} output The buffer where to store the result
  12549. * @param {Number} offset The offset at which to start writing
  12550. * @param {Number} length The number of bytes to mask.
  12551. * @public
  12552. */
  12553. function _mask(source, mask, output, offset, length) {
  12554. for (let i = 0; i < length; i++) output[offset + i] = source[i] ^ mask[i & 3];
  12555. }
  12556. /**
  12557. * Unmasks a buffer using the given mask.
  12558. *
  12559. * @param {Buffer} buffer The buffer to unmask
  12560. * @param {Buffer} mask The mask to use
  12561. * @public
  12562. */
  12563. function _unmask(buffer, mask) {
  12564. for (let i = 0; i < buffer.length; i++) buffer[i] ^= mask[i & 3];
  12565. }
  12566. /**
  12567. * Converts a buffer to an `ArrayBuffer`.
  12568. *
  12569. * @param {Buffer} buf The buffer to convert
  12570. * @return {ArrayBuffer} Converted buffer
  12571. * @public
  12572. */
  12573. function toArrayBuffer(buf) {
  12574. if (buf.length === buf.buffer.byteLength) return buf.buffer;
  12575. return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.length);
  12576. }
  12577. /**
  12578. * Converts `data` to a `Buffer`.
  12579. *
  12580. * @param {*} data The data to convert
  12581. * @return {Buffer} The buffer
  12582. * @throws {TypeError}
  12583. * @public
  12584. */
  12585. function toBuffer(data) {
  12586. toBuffer.readOnly = true;
  12587. if (Buffer.isBuffer(data)) return data;
  12588. let buf;
  12589. if (data instanceof ArrayBuffer) buf = new FastBuffer(data);
  12590. else if (ArrayBuffer.isView(data)) buf = new FastBuffer(data.buffer, data.byteOffset, data.byteLength);
  12591. else {
  12592. buf = Buffer.from(data);
  12593. toBuffer.readOnly = false;
  12594. }
  12595. return buf;
  12596. }
  12597. module.exports = {
  12598. concat,
  12599. mask: _mask,
  12600. toArrayBuffer,
  12601. toBuffer,
  12602. unmask: _unmask
  12603. };
  12604. /* istanbul ignore else */
  12605. if (!process.env.WS_NO_BUFFER_UTIL) try {
  12606. const bufferUtil = __require("bufferutil");
  12607. module.exports.mask = function(source, mask, output, offset, length) {
  12608. if (length < 48) _mask(source, mask, output, offset, length);
  12609. else bufferUtil.mask(source, mask, output, offset, length);
  12610. };
  12611. module.exports.unmask = function(buffer, mask) {
  12612. if (buffer.length < 32) _unmask(buffer, mask);
  12613. else bufferUtil.unmask(buffer, mask);
  12614. };
  12615. } catch (e) {}
  12616. }));
  12617. //#endregion
  12618. //#region ../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/limiter.js
  12619. var require_limiter = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  12620. const kDone = Symbol("kDone");
  12621. const kRun = Symbol("kRun");
  12622. /**
  12623. * A very simple job queue with adjustable concurrency. Adapted from
  12624. * https://github.com/STRML/async-limiter
  12625. */
  12626. var Limiter = class {
  12627. /**
  12628. * Creates a new `Limiter`.
  12629. *
  12630. * @param {Number} [concurrency=Infinity] The maximum number of jobs allowed
  12631. * to run concurrently
  12632. */
  12633. constructor(concurrency) {
  12634. this[kDone] = () => {
  12635. this.pending--;
  12636. this[kRun]();
  12637. };
  12638. this.concurrency = concurrency || Infinity;
  12639. this.jobs = [];
  12640. this.pending = 0;
  12641. }
  12642. /**
  12643. * Adds a job to the queue.
  12644. *
  12645. * @param {Function} job The job to run
  12646. * @public
  12647. */
  12648. add(job) {
  12649. this.jobs.push(job);
  12650. this[kRun]();
  12651. }
  12652. /**
  12653. * Removes a job from the queue and runs it if possible.
  12654. *
  12655. * @private
  12656. */
  12657. [kRun]() {
  12658. if (this.pending === this.concurrency) return;
  12659. if (this.jobs.length) {
  12660. const job = this.jobs.shift();
  12661. this.pending++;
  12662. job(this[kDone]);
  12663. }
  12664. }
  12665. };
  12666. module.exports = Limiter;
  12667. }));
  12668. //#endregion
  12669. //#region ../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/permessage-deflate.js
  12670. var require_permessage_deflate = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  12671. const zlib$1 = __require("zlib");
  12672. const bufferUtil = require_buffer_util();
  12673. const Limiter = require_limiter();
  12674. const { kStatusCode } = require_constants();
  12675. const FastBuffer = Buffer[Symbol.species];
  12676. const TRAILER = Buffer.from([
  12677. 0,
  12678. 0,
  12679. 255,
  12680. 255
  12681. ]);
  12682. const kPerMessageDeflate = Symbol("permessage-deflate");
  12683. const kTotalLength = Symbol("total-length");
  12684. const kCallback = Symbol("callback");
  12685. const kBuffers = Symbol("buffers");
  12686. const kError = Symbol("error");
  12687. let zlibLimiter;
  12688. /**
  12689. * permessage-deflate implementation.
  12690. */
  12691. var PerMessageDeflate = class {
  12692. /**
  12693. * Creates a PerMessageDeflate instance.
  12694. *
  12695. * @param {Object} [options] Configuration options
  12696. * @param {(Boolean|Number)} [options.clientMaxWindowBits] Advertise support
  12697. * for, or request, a custom client window size
  12698. * @param {Boolean} [options.clientNoContextTakeover=false] Advertise/
  12699. * acknowledge disabling of client context takeover
  12700. * @param {Number} [options.concurrencyLimit=10] The number of concurrent
  12701. * calls to zlib
  12702. * @param {Boolean} [options.isServer=false] Create the instance in either
  12703. * server or client mode
  12704. * @param {Number} [options.maxPayload=0] The maximum allowed message length
  12705. * @param {(Boolean|Number)} [options.serverMaxWindowBits] Request/confirm the
  12706. * use of a custom server window size
  12707. * @param {Boolean} [options.serverNoContextTakeover=false] Request/accept
  12708. * disabling of server context takeover
  12709. * @param {Number} [options.threshold=1024] Size (in bytes) below which
  12710. * messages should not be compressed if context takeover is disabled
  12711. * @param {Object} [options.zlibDeflateOptions] Options to pass to zlib on
  12712. * deflate
  12713. * @param {Object} [options.zlibInflateOptions] Options to pass to zlib on
  12714. * inflate
  12715. */
  12716. constructor(options) {
  12717. this._options = options || {};
  12718. this._threshold = this._options.threshold !== void 0 ? this._options.threshold : 1024;
  12719. this._maxPayload = this._options.maxPayload | 0;
  12720. this._isServer = !!this._options.isServer;
  12721. this._deflate = null;
  12722. this._inflate = null;
  12723. this.params = null;
  12724. if (!zlibLimiter) zlibLimiter = new Limiter(this._options.concurrencyLimit !== void 0 ? this._options.concurrencyLimit : 10);
  12725. }
  12726. /**
  12727. * @type {String}
  12728. */
  12729. static get extensionName() {
  12730. return "permessage-deflate";
  12731. }
  12732. /**
  12733. * Create an extension negotiation offer.
  12734. *
  12735. * @return {Object} Extension parameters
  12736. * @public
  12737. */
  12738. offer() {
  12739. const params = {};
  12740. if (this._options.serverNoContextTakeover) params.server_no_context_takeover = true;
  12741. if (this._options.clientNoContextTakeover) params.client_no_context_takeover = true;
  12742. if (this._options.serverMaxWindowBits) params.server_max_window_bits = this._options.serverMaxWindowBits;
  12743. if (this._options.clientMaxWindowBits) params.client_max_window_bits = this._options.clientMaxWindowBits;
  12744. else if (this._options.clientMaxWindowBits == null) params.client_max_window_bits = true;
  12745. return params;
  12746. }
  12747. /**
  12748. * Accept an extension negotiation offer/response.
  12749. *
  12750. * @param {Array} configurations The extension negotiation offers/reponse
  12751. * @return {Object} Accepted configuration
  12752. * @public
  12753. */
  12754. accept(configurations) {
  12755. configurations = this.normalizeParams(configurations);
  12756. this.params = this._isServer ? this.acceptAsServer(configurations) : this.acceptAsClient(configurations);
  12757. return this.params;
  12758. }
  12759. /**
  12760. * Releases all resources used by the extension.
  12761. *
  12762. * @public
  12763. */
  12764. cleanup() {
  12765. if (this._inflate) {
  12766. this._inflate.close();
  12767. this._inflate = null;
  12768. }
  12769. if (this._deflate) {
  12770. const callback = this._deflate[kCallback];
  12771. this._deflate.close();
  12772. this._deflate = null;
  12773. if (callback) callback(/* @__PURE__ */ new Error("The deflate stream was closed while data was being processed"));
  12774. }
  12775. }
  12776. /**
  12777. * Accept an extension negotiation offer.
  12778. *
  12779. * @param {Array} offers The extension negotiation offers
  12780. * @return {Object} Accepted configuration
  12781. * @private
  12782. */
  12783. acceptAsServer(offers) {
  12784. const opts = this._options;
  12785. const accepted = offers.find((params) => {
  12786. if (opts.serverNoContextTakeover === false && params.server_no_context_takeover || params.server_max_window_bits && (opts.serverMaxWindowBits === false || typeof opts.serverMaxWindowBits === "number" && opts.serverMaxWindowBits > params.server_max_window_bits) || typeof opts.clientMaxWindowBits === "number" && !params.client_max_window_bits) return false;
  12787. return true;
  12788. });
  12789. if (!accepted) throw new Error("None of the extension offers can be accepted");
  12790. if (opts.serverNoContextTakeover) accepted.server_no_context_takeover = true;
  12791. if (opts.clientNoContextTakeover) accepted.client_no_context_takeover = true;
  12792. if (typeof opts.serverMaxWindowBits === "number") accepted.server_max_window_bits = opts.serverMaxWindowBits;
  12793. if (typeof opts.clientMaxWindowBits === "number") accepted.client_max_window_bits = opts.clientMaxWindowBits;
  12794. else if (accepted.client_max_window_bits === true || opts.clientMaxWindowBits === false) delete accepted.client_max_window_bits;
  12795. return accepted;
  12796. }
  12797. /**
  12798. * Accept the extension negotiation response.
  12799. *
  12800. * @param {Array} response The extension negotiation response
  12801. * @return {Object} Accepted configuration
  12802. * @private
  12803. */
  12804. acceptAsClient(response) {
  12805. const params = response[0];
  12806. if (this._options.clientNoContextTakeover === false && params.client_no_context_takeover) throw new Error("Unexpected parameter \"client_no_context_takeover\"");
  12807. if (!params.client_max_window_bits) {
  12808. if (typeof this._options.clientMaxWindowBits === "number") params.client_max_window_bits = this._options.clientMaxWindowBits;
  12809. } else if (this._options.clientMaxWindowBits === false || typeof this._options.clientMaxWindowBits === "number" && params.client_max_window_bits > this._options.clientMaxWindowBits) throw new Error("Unexpected or invalid parameter \"client_max_window_bits\"");
  12810. return params;
  12811. }
  12812. /**
  12813. * Normalize parameters.
  12814. *
  12815. * @param {Array} configurations The extension negotiation offers/reponse
  12816. * @return {Array} The offers/response with normalized parameters
  12817. * @private
  12818. */
  12819. normalizeParams(configurations) {
  12820. configurations.forEach((params) => {
  12821. Object.keys(params).forEach((key) => {
  12822. let value = params[key];
  12823. if (value.length > 1) throw new Error(`Parameter "${key}" must have only a single value`);
  12824. value = value[0];
  12825. if (key === "client_max_window_bits") {
  12826. if (value !== true) {
  12827. const num = +value;
  12828. if (!Number.isInteger(num) || num < 8 || num > 15) throw new TypeError(`Invalid value for parameter "${key}": ${value}`);
  12829. value = num;
  12830. } else if (!this._isServer) throw new TypeError(`Invalid value for parameter "${key}": ${value}`);
  12831. } else if (key === "server_max_window_bits") {
  12832. const num = +value;
  12833. if (!Number.isInteger(num) || num < 8 || num > 15) throw new TypeError(`Invalid value for parameter "${key}": ${value}`);
  12834. value = num;
  12835. } else if (key === "client_no_context_takeover" || key === "server_no_context_takeover") {
  12836. if (value !== true) throw new TypeError(`Invalid value for parameter "${key}": ${value}`);
  12837. } else throw new Error(`Unknown parameter "${key}"`);
  12838. params[key] = value;
  12839. });
  12840. });
  12841. return configurations;
  12842. }
  12843. /**
  12844. * Decompress data. Concurrency limited.
  12845. *
  12846. * @param {Buffer} data Compressed data
  12847. * @param {Boolean} fin Specifies whether or not this is the last fragment
  12848. * @param {Function} callback Callback
  12849. * @public
  12850. */
  12851. decompress(data, fin, callback) {
  12852. zlibLimiter.add((done) => {
  12853. this._decompress(data, fin, (err, result) => {
  12854. done();
  12855. callback(err, result);
  12856. });
  12857. });
  12858. }
  12859. /**
  12860. * Compress data. Concurrency limited.
  12861. *
  12862. * @param {(Buffer|String)} data Data to compress
  12863. * @param {Boolean} fin Specifies whether or not this is the last fragment
  12864. * @param {Function} callback Callback
  12865. * @public
  12866. */
  12867. compress(data, fin, callback) {
  12868. zlibLimiter.add((done) => {
  12869. this._compress(data, fin, (err, result) => {
  12870. done();
  12871. callback(err, result);
  12872. });
  12873. });
  12874. }
  12875. /**
  12876. * Decompress data.
  12877. *
  12878. * @param {Buffer} data Compressed data
  12879. * @param {Boolean} fin Specifies whether or not this is the last fragment
  12880. * @param {Function} callback Callback
  12881. * @private
  12882. */
  12883. _decompress(data, fin, callback) {
  12884. const endpoint = this._isServer ? "client" : "server";
  12885. if (!this._inflate) {
  12886. const key = `${endpoint}_max_window_bits`;
  12887. const windowBits = typeof this.params[key] !== "number" ? zlib$1.Z_DEFAULT_WINDOWBITS : this.params[key];
  12888. this._inflate = zlib$1.createInflateRaw({
  12889. ...this._options.zlibInflateOptions,
  12890. windowBits
  12891. });
  12892. this._inflate[kPerMessageDeflate] = this;
  12893. this._inflate[kTotalLength] = 0;
  12894. this._inflate[kBuffers] = [];
  12895. this._inflate.on("error", inflateOnError);
  12896. this._inflate.on("data", inflateOnData);
  12897. }
  12898. this._inflate[kCallback] = callback;
  12899. this._inflate.write(data);
  12900. if (fin) this._inflate.write(TRAILER);
  12901. this._inflate.flush(() => {
  12902. const err = this._inflate[kError];
  12903. if (err) {
  12904. this._inflate.close();
  12905. this._inflate = null;
  12906. callback(err);
  12907. return;
  12908. }
  12909. const data = bufferUtil.concat(this._inflate[kBuffers], this._inflate[kTotalLength]);
  12910. if (this._inflate._readableState.endEmitted) {
  12911. this._inflate.close();
  12912. this._inflate = null;
  12913. } else {
  12914. this._inflate[kTotalLength] = 0;
  12915. this._inflate[kBuffers] = [];
  12916. if (fin && this.params[`${endpoint}_no_context_takeover`]) this._inflate.reset();
  12917. }
  12918. callback(null, data);
  12919. });
  12920. }
  12921. /**
  12922. * Compress data.
  12923. *
  12924. * @param {(Buffer|String)} data Data to compress
  12925. * @param {Boolean} fin Specifies whether or not this is the last fragment
  12926. * @param {Function} callback Callback
  12927. * @private
  12928. */
  12929. _compress(data, fin, callback) {
  12930. const endpoint = this._isServer ? "server" : "client";
  12931. if (!this._deflate) {
  12932. const key = `${endpoint}_max_window_bits`;
  12933. const windowBits = typeof this.params[key] !== "number" ? zlib$1.Z_DEFAULT_WINDOWBITS : this.params[key];
  12934. this._deflate = zlib$1.createDeflateRaw({
  12935. ...this._options.zlibDeflateOptions,
  12936. windowBits
  12937. });
  12938. this._deflate[kTotalLength] = 0;
  12939. this._deflate[kBuffers] = [];
  12940. this._deflate.on("data", deflateOnData);
  12941. }
  12942. this._deflate[kCallback] = callback;
  12943. this._deflate.write(data);
  12944. this._deflate.flush(zlib$1.Z_SYNC_FLUSH, () => {
  12945. if (!this._deflate) return;
  12946. let data = bufferUtil.concat(this._deflate[kBuffers], this._deflate[kTotalLength]);
  12947. if (fin) data = new FastBuffer(data.buffer, data.byteOffset, data.length - 4);
  12948. this._deflate[kCallback] = null;
  12949. this._deflate[kTotalLength] = 0;
  12950. this._deflate[kBuffers] = [];
  12951. if (fin && this.params[`${endpoint}_no_context_takeover`]) this._deflate.reset();
  12952. callback(null, data);
  12953. });
  12954. }
  12955. };
  12956. module.exports = PerMessageDeflate;
  12957. /**
  12958. * The listener of the `zlib.DeflateRaw` stream `'data'` event.
  12959. *
  12960. * @param {Buffer} chunk A chunk of data
  12961. * @private
  12962. */
  12963. function deflateOnData(chunk) {
  12964. this[kBuffers].push(chunk);
  12965. this[kTotalLength] += chunk.length;
  12966. }
  12967. /**
  12968. * The listener of the `zlib.InflateRaw` stream `'data'` event.
  12969. *
  12970. * @param {Buffer} chunk A chunk of data
  12971. * @private
  12972. */
  12973. function inflateOnData(chunk) {
  12974. this[kTotalLength] += chunk.length;
  12975. if (this[kPerMessageDeflate]._maxPayload < 1 || this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload) {
  12976. this[kBuffers].push(chunk);
  12977. return;
  12978. }
  12979. this[kError] = /* @__PURE__ */ new RangeError("Max payload size exceeded");
  12980. this[kError].code = "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH";
  12981. this[kError][kStatusCode] = 1009;
  12982. this.removeListener("data", inflateOnData);
  12983. this.reset();
  12984. }
  12985. /**
  12986. * The listener of the `zlib.InflateRaw` stream `'error'` event.
  12987. *
  12988. * @param {Error} err The emitted error
  12989. * @private
  12990. */
  12991. function inflateOnError(err) {
  12992. this[kPerMessageDeflate]._inflate = null;
  12993. if (this[kError]) {
  12994. this[kCallback](this[kError]);
  12995. return;
  12996. }
  12997. err[kStatusCode] = 1007;
  12998. this[kCallback](err);
  12999. }
  13000. }));
  13001. //#endregion
  13002. //#region ../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/validation.js
  13003. var require_validation = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  13004. const { isUtf8 } = __require("buffer");
  13005. const { hasBlob } = require_constants();
  13006. const tokenChars = [
  13007. 0,
  13008. 0,
  13009. 0,
  13010. 0,
  13011. 0,
  13012. 0,
  13013. 0,
  13014. 0,
  13015. 0,
  13016. 0,
  13017. 0,
  13018. 0,
  13019. 0,
  13020. 0,
  13021. 0,
  13022. 0,
  13023. 0,
  13024. 0,
  13025. 0,
  13026. 0,
  13027. 0,
  13028. 0,
  13029. 0,
  13030. 0,
  13031. 0,
  13032. 0,
  13033. 0,
  13034. 0,
  13035. 0,
  13036. 0,
  13037. 0,
  13038. 0,
  13039. 0,
  13040. 1,
  13041. 0,
  13042. 1,
  13043. 1,
  13044. 1,
  13045. 1,
  13046. 1,
  13047. 0,
  13048. 0,
  13049. 1,
  13050. 1,
  13051. 0,
  13052. 1,
  13053. 1,
  13054. 0,
  13055. 1,
  13056. 1,
  13057. 1,
  13058. 1,
  13059. 1,
  13060. 1,
  13061. 1,
  13062. 1,
  13063. 1,
  13064. 1,
  13065. 0,
  13066. 0,
  13067. 0,
  13068. 0,
  13069. 0,
  13070. 0,
  13071. 0,
  13072. 1,
  13073. 1,
  13074. 1,
  13075. 1,
  13076. 1,
  13077. 1,
  13078. 1,
  13079. 1,
  13080. 1,
  13081. 1,
  13082. 1,
  13083. 1,
  13084. 1,
  13085. 1,
  13086. 1,
  13087. 1,
  13088. 1,
  13089. 1,
  13090. 1,
  13091. 1,
  13092. 1,
  13093. 1,
  13094. 1,
  13095. 1,
  13096. 1,
  13097. 1,
  13098. 0,
  13099. 0,
  13100. 0,
  13101. 1,
  13102. 1,
  13103. 1,
  13104. 1,
  13105. 1,
  13106. 1,
  13107. 1,
  13108. 1,
  13109. 1,
  13110. 1,
  13111. 1,
  13112. 1,
  13113. 1,
  13114. 1,
  13115. 1,
  13116. 1,
  13117. 1,
  13118. 1,
  13119. 1,
  13120. 1,
  13121. 1,
  13122. 1,
  13123. 1,
  13124. 1,
  13125. 1,
  13126. 1,
  13127. 1,
  13128. 1,
  13129. 1,
  13130. 0,
  13131. 1,
  13132. 0,
  13133. 1,
  13134. 0
  13135. ];
  13136. /**
  13137. * Checks if a status code is allowed in a close frame.
  13138. *
  13139. * @param {Number} code The status code
  13140. * @return {Boolean} `true` if the status code is valid, else `false`
  13141. * @public
  13142. */
  13143. function isValidStatusCode(code) {
  13144. return code >= 1e3 && code <= 1014 && code !== 1004 && code !== 1005 && code !== 1006 || code >= 3e3 && code <= 4999;
  13145. }
  13146. /**
  13147. * Checks if a given buffer contains only correct UTF-8.
  13148. * Ported from https://www.cl.cam.ac.uk/%7Emgk25/ucs/utf8_check.c by
  13149. * Markus Kuhn.
  13150. *
  13151. * @param {Buffer} buf The buffer to check
  13152. * @return {Boolean} `true` if `buf` contains only correct UTF-8, else `false`
  13153. * @public
  13154. */
  13155. function _isValidUTF8(buf) {
  13156. const len = buf.length;
  13157. let i = 0;
  13158. while (i < len) if ((buf[i] & 128) === 0) i++;
  13159. else if ((buf[i] & 224) === 192) {
  13160. if (i + 1 === len || (buf[i + 1] & 192) !== 128 || (buf[i] & 254) === 192) return false;
  13161. i += 2;
  13162. } else if ((buf[i] & 240) === 224) {
  13163. if (i + 2 >= len || (buf[i + 1] & 192) !== 128 || (buf[i + 2] & 192) !== 128 || buf[i] === 224 && (buf[i + 1] & 224) === 128 || buf[i] === 237 && (buf[i + 1] & 224) === 160) return false;
  13164. i += 3;
  13165. } else if ((buf[i] & 248) === 240) {
  13166. if (i + 3 >= len || (buf[i + 1] & 192) !== 128 || (buf[i + 2] & 192) !== 128 || (buf[i + 3] & 192) !== 128 || buf[i] === 240 && (buf[i + 1] & 240) === 128 || buf[i] === 244 && buf[i + 1] > 143 || buf[i] > 244) return false;
  13167. i += 4;
  13168. } else return false;
  13169. return true;
  13170. }
  13171. /**
  13172. * Determines whether a value is a `Blob`.
  13173. *
  13174. * @param {*} value The value to be tested
  13175. * @return {Boolean} `true` if `value` is a `Blob`, else `false`
  13176. * @private
  13177. */
  13178. function isBlob(value) {
  13179. return hasBlob && typeof value === "object" && typeof value.arrayBuffer === "function" && typeof value.type === "string" && typeof value.stream === "function" && (value[Symbol.toStringTag] === "Blob" || value[Symbol.toStringTag] === "File");
  13180. }
  13181. module.exports = {
  13182. isBlob,
  13183. isValidStatusCode,
  13184. isValidUTF8: _isValidUTF8,
  13185. tokenChars
  13186. };
  13187. if (isUtf8) module.exports.isValidUTF8 = function(buf) {
  13188. return buf.length < 24 ? _isValidUTF8(buf) : isUtf8(buf);
  13189. };
  13190. else if (!process.env.WS_NO_UTF_8_VALIDATE) try {
  13191. const isValidUTF8 = __require("utf-8-validate");
  13192. module.exports.isValidUTF8 = function(buf) {
  13193. return buf.length < 32 ? _isValidUTF8(buf) : isValidUTF8(buf);
  13194. };
  13195. } catch (e) {}
  13196. }));
  13197. //#endregion
  13198. //#region ../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/receiver.js
  13199. var require_receiver = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  13200. const { Writable: Writable$1 } = __require("stream");
  13201. const PerMessageDeflate = require_permessage_deflate();
  13202. const { BINARY_TYPES, EMPTY_BUFFER, kStatusCode, kWebSocket } = require_constants();
  13203. const { concat, toArrayBuffer, unmask } = require_buffer_util();
  13204. const { isValidStatusCode, isValidUTF8 } = require_validation();
  13205. const FastBuffer = Buffer[Symbol.species];
  13206. const GET_INFO = 0;
  13207. const GET_PAYLOAD_LENGTH_16 = 1;
  13208. const GET_PAYLOAD_LENGTH_64 = 2;
  13209. const GET_MASK = 3;
  13210. const GET_DATA = 4;
  13211. const INFLATING = 5;
  13212. const DEFER_EVENT = 6;
  13213. /**
  13214. * HyBi Receiver implementation.
  13215. *
  13216. * @extends Writable
  13217. */
  13218. var Receiver = class extends Writable$1 {
  13219. /**
  13220. * Creates a Receiver instance.
  13221. *
  13222. * @param {Object} [options] Options object
  13223. * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether
  13224. * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
  13225. * multiple times in the same tick
  13226. * @param {String} [options.binaryType=nodebuffer] The type for binary data
  13227. * @param {Object} [options.extensions] An object containing the negotiated
  13228. * extensions
  13229. * @param {Boolean} [options.isServer=false] Specifies whether to operate in
  13230. * client or server mode
  13231. * @param {Number} [options.maxPayload=0] The maximum allowed message length
  13232. * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
  13233. * not to skip UTF-8 validation for text and close messages
  13234. */
  13235. constructor(options = {}) {
  13236. super();
  13237. this._allowSynchronousEvents = options.allowSynchronousEvents !== void 0 ? options.allowSynchronousEvents : true;
  13238. this._binaryType = options.binaryType || BINARY_TYPES[0];
  13239. this._extensions = options.extensions || {};
  13240. this._isServer = !!options.isServer;
  13241. this._maxPayload = options.maxPayload | 0;
  13242. this._skipUTF8Validation = !!options.skipUTF8Validation;
  13243. this[kWebSocket] = void 0;
  13244. this._bufferedBytes = 0;
  13245. this._buffers = [];
  13246. this._compressed = false;
  13247. this._payloadLength = 0;
  13248. this._mask = void 0;
  13249. this._fragmented = 0;
  13250. this._masked = false;
  13251. this._fin = false;
  13252. this._opcode = 0;
  13253. this._totalPayloadLength = 0;
  13254. this._messageLength = 0;
  13255. this._fragments = [];
  13256. this._errored = false;
  13257. this._loop = false;
  13258. this._state = GET_INFO;
  13259. }
  13260. /**
  13261. * Implements `Writable.prototype._write()`.
  13262. *
  13263. * @param {Buffer} chunk The chunk of data to write
  13264. * @param {String} encoding The character encoding of `chunk`
  13265. * @param {Function} cb Callback
  13266. * @private
  13267. */
  13268. _write(chunk, encoding, cb) {
  13269. if (this._opcode === 8 && this._state == GET_INFO) return cb();
  13270. this._bufferedBytes += chunk.length;
  13271. this._buffers.push(chunk);
  13272. this.startLoop(cb);
  13273. }
  13274. /**
  13275. * Consumes `n` bytes from the buffered data.
  13276. *
  13277. * @param {Number} n The number of bytes to consume
  13278. * @return {Buffer} The consumed bytes
  13279. * @private
  13280. */
  13281. consume(n) {
  13282. this._bufferedBytes -= n;
  13283. if (n === this._buffers[0].length) return this._buffers.shift();
  13284. if (n < this._buffers[0].length) {
  13285. const buf = this._buffers[0];
  13286. this._buffers[0] = new FastBuffer(buf.buffer, buf.byteOffset + n, buf.length - n);
  13287. return new FastBuffer(buf.buffer, buf.byteOffset, n);
  13288. }
  13289. const dst = Buffer.allocUnsafe(n);
  13290. do {
  13291. const buf = this._buffers[0];
  13292. const offset = dst.length - n;
  13293. if (n >= buf.length) dst.set(this._buffers.shift(), offset);
  13294. else {
  13295. dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n), offset);
  13296. this._buffers[0] = new FastBuffer(buf.buffer, buf.byteOffset + n, buf.length - n);
  13297. }
  13298. n -= buf.length;
  13299. } while (n > 0);
  13300. return dst;
  13301. }
  13302. /**
  13303. * Starts the parsing loop.
  13304. *
  13305. * @param {Function} cb Callback
  13306. * @private
  13307. */
  13308. startLoop(cb) {
  13309. this._loop = true;
  13310. do
  13311. switch (this._state) {
  13312. case GET_INFO:
  13313. this.getInfo(cb);
  13314. break;
  13315. case GET_PAYLOAD_LENGTH_16:
  13316. this.getPayloadLength16(cb);
  13317. break;
  13318. case GET_PAYLOAD_LENGTH_64:
  13319. this.getPayloadLength64(cb);
  13320. break;
  13321. case GET_MASK:
  13322. this.getMask();
  13323. break;
  13324. case GET_DATA:
  13325. this.getData(cb);
  13326. break;
  13327. case INFLATING:
  13328. case DEFER_EVENT:
  13329. this._loop = false;
  13330. return;
  13331. }
  13332. while (this._loop);
  13333. if (!this._errored) cb();
  13334. }
  13335. /**
  13336. * Reads the first two bytes of a frame.
  13337. *
  13338. * @param {Function} cb Callback
  13339. * @private
  13340. */
  13341. getInfo(cb) {
  13342. if (this._bufferedBytes < 2) {
  13343. this._loop = false;
  13344. return;
  13345. }
  13346. const buf = this.consume(2);
  13347. if ((buf[0] & 48) !== 0) {
  13348. cb(this.createError(RangeError, "RSV2 and RSV3 must be clear", true, 1002, "WS_ERR_UNEXPECTED_RSV_2_3"));
  13349. return;
  13350. }
  13351. const compressed = (buf[0] & 64) === 64;
  13352. if (compressed && !this._extensions[PerMessageDeflate.extensionName]) {
  13353. cb(this.createError(RangeError, "RSV1 must be clear", true, 1002, "WS_ERR_UNEXPECTED_RSV_1"));
  13354. return;
  13355. }
  13356. this._fin = (buf[0] & 128) === 128;
  13357. this._opcode = buf[0] & 15;
  13358. this._payloadLength = buf[1] & 127;
  13359. if (this._opcode === 0) {
  13360. if (compressed) {
  13361. cb(this.createError(RangeError, "RSV1 must be clear", true, 1002, "WS_ERR_UNEXPECTED_RSV_1"));
  13362. return;
  13363. }
  13364. if (!this._fragmented) {
  13365. cb(this.createError(RangeError, "invalid opcode 0", true, 1002, "WS_ERR_INVALID_OPCODE"));
  13366. return;
  13367. }
  13368. this._opcode = this._fragmented;
  13369. } else if (this._opcode === 1 || this._opcode === 2) {
  13370. if (this._fragmented) {
  13371. cb(this.createError(RangeError, `invalid opcode ${this._opcode}`, true, 1002, "WS_ERR_INVALID_OPCODE"));
  13372. return;
  13373. }
  13374. this._compressed = compressed;
  13375. } else if (this._opcode > 7 && this._opcode < 11) {
  13376. if (!this._fin) {
  13377. cb(this.createError(RangeError, "FIN must be set", true, 1002, "WS_ERR_EXPECTED_FIN"));
  13378. return;
  13379. }
  13380. if (compressed) {
  13381. cb(this.createError(RangeError, "RSV1 must be clear", true, 1002, "WS_ERR_UNEXPECTED_RSV_1"));
  13382. return;
  13383. }
  13384. if (this._payloadLength > 125 || this._opcode === 8 && this._payloadLength === 1) {
  13385. cb(this.createError(RangeError, `invalid payload length ${this._payloadLength}`, true, 1002, "WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH"));
  13386. return;
  13387. }
  13388. } else {
  13389. cb(this.createError(RangeError, `invalid opcode ${this._opcode}`, true, 1002, "WS_ERR_INVALID_OPCODE"));
  13390. return;
  13391. }
  13392. if (!this._fin && !this._fragmented) this._fragmented = this._opcode;
  13393. this._masked = (buf[1] & 128) === 128;
  13394. if (this._isServer) {
  13395. if (!this._masked) {
  13396. cb(this.createError(RangeError, "MASK must be set", true, 1002, "WS_ERR_EXPECTED_MASK"));
  13397. return;
  13398. }
  13399. } else if (this._masked) {
  13400. cb(this.createError(RangeError, "MASK must be clear", true, 1002, "WS_ERR_UNEXPECTED_MASK"));
  13401. return;
  13402. }
  13403. if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16;
  13404. else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64;
  13405. else this.haveLength(cb);
  13406. }
  13407. /**
  13408. * Gets extended payload length (7+16).
  13409. *
  13410. * @param {Function} cb Callback
  13411. * @private
  13412. */
  13413. getPayloadLength16(cb) {
  13414. if (this._bufferedBytes < 2) {
  13415. this._loop = false;
  13416. return;
  13417. }
  13418. this._payloadLength = this.consume(2).readUInt16BE(0);
  13419. this.haveLength(cb);
  13420. }
  13421. /**
  13422. * Gets extended payload length (7+64).
  13423. *
  13424. * @param {Function} cb Callback
  13425. * @private
  13426. */
  13427. getPayloadLength64(cb) {
  13428. if (this._bufferedBytes < 8) {
  13429. this._loop = false;
  13430. return;
  13431. }
  13432. const buf = this.consume(8);
  13433. const num = buf.readUInt32BE(0);
  13434. if (num > Math.pow(2, 21) - 1) {
  13435. cb(this.createError(RangeError, "Unsupported WebSocket frame: payload length > 2^53 - 1", false, 1009, "WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH"));
  13436. return;
  13437. }
  13438. this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4);
  13439. this.haveLength(cb);
  13440. }
  13441. /**
  13442. * Payload length has been read.
  13443. *
  13444. * @param {Function} cb Callback
  13445. * @private
  13446. */
  13447. haveLength(cb) {
  13448. if (this._payloadLength && this._opcode < 8) {
  13449. this._totalPayloadLength += this._payloadLength;
  13450. if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) {
  13451. cb(this.createError(RangeError, "Max payload size exceeded", false, 1009, "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"));
  13452. return;
  13453. }
  13454. }
  13455. if (this._masked) this._state = GET_MASK;
  13456. else this._state = GET_DATA;
  13457. }
  13458. /**
  13459. * Reads mask bytes.
  13460. *
  13461. * @private
  13462. */
  13463. getMask() {
  13464. if (this._bufferedBytes < 4) {
  13465. this._loop = false;
  13466. return;
  13467. }
  13468. this._mask = this.consume(4);
  13469. this._state = GET_DATA;
  13470. }
  13471. /**
  13472. * Reads data bytes.
  13473. *
  13474. * @param {Function} cb Callback
  13475. * @private
  13476. */
  13477. getData(cb) {
  13478. let data = EMPTY_BUFFER;
  13479. if (this._payloadLength) {
  13480. if (this._bufferedBytes < this._payloadLength) {
  13481. this._loop = false;
  13482. return;
  13483. }
  13484. data = this.consume(this._payloadLength);
  13485. if (this._masked && (this._mask[0] | this._mask[1] | this._mask[2] | this._mask[3]) !== 0) unmask(data, this._mask);
  13486. }
  13487. if (this._opcode > 7) {
  13488. this.controlMessage(data, cb);
  13489. return;
  13490. }
  13491. if (this._compressed) {
  13492. this._state = INFLATING;
  13493. this.decompress(data, cb);
  13494. return;
  13495. }
  13496. if (data.length) {
  13497. this._messageLength = this._totalPayloadLength;
  13498. this._fragments.push(data);
  13499. }
  13500. this.dataMessage(cb);
  13501. }
  13502. /**
  13503. * Decompresses data.
  13504. *
  13505. * @param {Buffer} data Compressed data
  13506. * @param {Function} cb Callback
  13507. * @private
  13508. */
  13509. decompress(data, cb) {
  13510. this._extensions[PerMessageDeflate.extensionName].decompress(data, this._fin, (err, buf) => {
  13511. if (err) return cb(err);
  13512. if (buf.length) {
  13513. this._messageLength += buf.length;
  13514. if (this._messageLength > this._maxPayload && this._maxPayload > 0) {
  13515. cb(this.createError(RangeError, "Max payload size exceeded", false, 1009, "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"));
  13516. return;
  13517. }
  13518. this._fragments.push(buf);
  13519. }
  13520. this.dataMessage(cb);
  13521. if (this._state === GET_INFO) this.startLoop(cb);
  13522. });
  13523. }
  13524. /**
  13525. * Handles a data message.
  13526. *
  13527. * @param {Function} cb Callback
  13528. * @private
  13529. */
  13530. dataMessage(cb) {
  13531. if (!this._fin) {
  13532. this._state = GET_INFO;
  13533. return;
  13534. }
  13535. const messageLength = this._messageLength;
  13536. const fragments = this._fragments;
  13537. this._totalPayloadLength = 0;
  13538. this._messageLength = 0;
  13539. this._fragmented = 0;
  13540. this._fragments = [];
  13541. if (this._opcode === 2) {
  13542. let data;
  13543. if (this._binaryType === "nodebuffer") data = concat(fragments, messageLength);
  13544. else if (this._binaryType === "arraybuffer") data = toArrayBuffer(concat(fragments, messageLength));
  13545. else if (this._binaryType === "blob") data = new Blob(fragments);
  13546. else data = fragments;
  13547. if (this._allowSynchronousEvents) {
  13548. this.emit("message", data, true);
  13549. this._state = GET_INFO;
  13550. } else {
  13551. this._state = DEFER_EVENT;
  13552. setImmediate(() => {
  13553. this.emit("message", data, true);
  13554. this._state = GET_INFO;
  13555. this.startLoop(cb);
  13556. });
  13557. }
  13558. } else {
  13559. const buf = concat(fragments, messageLength);
  13560. if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
  13561. cb(this.createError(Error, "invalid UTF-8 sequence", true, 1007, "WS_ERR_INVALID_UTF8"));
  13562. return;
  13563. }
  13564. if (this._state === INFLATING || this._allowSynchronousEvents) {
  13565. this.emit("message", buf, false);
  13566. this._state = GET_INFO;
  13567. } else {
  13568. this._state = DEFER_EVENT;
  13569. setImmediate(() => {
  13570. this.emit("message", buf, false);
  13571. this._state = GET_INFO;
  13572. this.startLoop(cb);
  13573. });
  13574. }
  13575. }
  13576. }
  13577. /**
  13578. * Handles a control message.
  13579. *
  13580. * @param {Buffer} data Data to handle
  13581. * @return {(Error|RangeError|undefined)} A possible error
  13582. * @private
  13583. */
  13584. controlMessage(data, cb) {
  13585. if (this._opcode === 8) {
  13586. if (data.length === 0) {
  13587. this._loop = false;
  13588. this.emit("conclude", 1005, EMPTY_BUFFER);
  13589. this.end();
  13590. } else {
  13591. const code = data.readUInt16BE(0);
  13592. if (!isValidStatusCode(code)) {
  13593. cb(this.createError(RangeError, `invalid status code ${code}`, true, 1002, "WS_ERR_INVALID_CLOSE_CODE"));
  13594. return;
  13595. }
  13596. const buf = new FastBuffer(data.buffer, data.byteOffset + 2, data.length - 2);
  13597. if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
  13598. cb(this.createError(Error, "invalid UTF-8 sequence", true, 1007, "WS_ERR_INVALID_UTF8"));
  13599. return;
  13600. }
  13601. this._loop = false;
  13602. this.emit("conclude", code, buf);
  13603. this.end();
  13604. }
  13605. this._state = GET_INFO;
  13606. return;
  13607. }
  13608. if (this._allowSynchronousEvents) {
  13609. this.emit(this._opcode === 9 ? "ping" : "pong", data);
  13610. this._state = GET_INFO;
  13611. } else {
  13612. this._state = DEFER_EVENT;
  13613. setImmediate(() => {
  13614. this.emit(this._opcode === 9 ? "ping" : "pong", data);
  13615. this._state = GET_INFO;
  13616. this.startLoop(cb);
  13617. });
  13618. }
  13619. }
  13620. /**
  13621. * Builds an error object.
  13622. *
  13623. * @param {function(new:Error|RangeError)} ErrorCtor The error constructor
  13624. * @param {String} message The error message
  13625. * @param {Boolean} prefix Specifies whether or not to add a default prefix to
  13626. * `message`
  13627. * @param {Number} statusCode The status code
  13628. * @param {String} errorCode The exposed error code
  13629. * @return {(Error|RangeError)} The error
  13630. * @private
  13631. */
  13632. createError(ErrorCtor, message, prefix, statusCode, errorCode) {
  13633. this._loop = false;
  13634. this._errored = true;
  13635. const err = new ErrorCtor(prefix ? `Invalid WebSocket frame: ${message}` : message);
  13636. Error.captureStackTrace(err, this.createError);
  13637. err.code = errorCode;
  13638. err[kStatusCode] = statusCode;
  13639. return err;
  13640. }
  13641. };
  13642. module.exports = Receiver;
  13643. }));
  13644. //#endregion
  13645. //#region ../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/sender.js
  13646. var require_sender = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  13647. const { Duplex: Duplex$3 } = __require("stream");
  13648. const { randomFillSync } = __require("crypto");
  13649. const PerMessageDeflate = require_permessage_deflate();
  13650. const { EMPTY_BUFFER, kWebSocket, NOOP } = require_constants();
  13651. const { isBlob, isValidStatusCode } = require_validation();
  13652. const { mask: applyMask, toBuffer } = require_buffer_util();
  13653. const kByteLength = Symbol("kByteLength");
  13654. const maskBuffer = Buffer.alloc(4);
  13655. const RANDOM_POOL_SIZE = 8 * 1024;
  13656. let randomPool;
  13657. let randomPoolPointer = RANDOM_POOL_SIZE;
  13658. const DEFAULT = 0;
  13659. const DEFLATING = 1;
  13660. const GET_BLOB_DATA = 2;
  13661. module.exports = class Sender {
  13662. /**
  13663. * Creates a Sender instance.
  13664. *
  13665. * @param {Duplex} socket The connection socket
  13666. * @param {Object} [extensions] An object containing the negotiated extensions
  13667. * @param {Function} [generateMask] The function used to generate the masking
  13668. * key
  13669. */
  13670. constructor(socket, extensions, generateMask) {
  13671. this._extensions = extensions || {};
  13672. if (generateMask) {
  13673. this._generateMask = generateMask;
  13674. this._maskBuffer = Buffer.alloc(4);
  13675. }
  13676. this._socket = socket;
  13677. this._firstFragment = true;
  13678. this._compress = false;
  13679. this._bufferedBytes = 0;
  13680. this._queue = [];
  13681. this._state = DEFAULT;
  13682. this.onerror = NOOP;
  13683. this[kWebSocket] = void 0;
  13684. }
  13685. /**
  13686. * Frames a piece of data according to the HyBi WebSocket protocol.
  13687. *
  13688. * @param {(Buffer|String)} data The data to frame
  13689. * @param {Object} options Options object
  13690. * @param {Boolean} [options.fin=false] Specifies whether or not to set the
  13691. * FIN bit
  13692. * @param {Function} [options.generateMask] The function used to generate the
  13693. * masking key
  13694. * @param {Boolean} [options.mask=false] Specifies whether or not to mask
  13695. * `data`
  13696. * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
  13697. * key
  13698. * @param {Number} options.opcode The opcode
  13699. * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
  13700. * modified
  13701. * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
  13702. * RSV1 bit
  13703. * @return {(Buffer|String)[]} The framed data
  13704. * @public
  13705. */
  13706. static frame(data, options) {
  13707. let mask;
  13708. let merge = false;
  13709. let offset = 2;
  13710. let skipMasking = false;
  13711. if (options.mask) {
  13712. mask = options.maskBuffer || maskBuffer;
  13713. if (options.generateMask) options.generateMask(mask);
  13714. else {
  13715. if (randomPoolPointer === RANDOM_POOL_SIZE) {
  13716. /* istanbul ignore else */
  13717. if (randomPool === void 0) randomPool = Buffer.alloc(RANDOM_POOL_SIZE);
  13718. randomFillSync(randomPool, 0, RANDOM_POOL_SIZE);
  13719. randomPoolPointer = 0;
  13720. }
  13721. mask[0] = randomPool[randomPoolPointer++];
  13722. mask[1] = randomPool[randomPoolPointer++];
  13723. mask[2] = randomPool[randomPoolPointer++];
  13724. mask[3] = randomPool[randomPoolPointer++];
  13725. }
  13726. skipMasking = (mask[0] | mask[1] | mask[2] | mask[3]) === 0;
  13727. offset = 6;
  13728. }
  13729. let dataLength;
  13730. if (typeof data === "string") if ((!options.mask || skipMasking) && options[kByteLength] !== void 0) dataLength = options[kByteLength];
  13731. else {
  13732. data = Buffer.from(data);
  13733. dataLength = data.length;
  13734. }
  13735. else {
  13736. dataLength = data.length;
  13737. merge = options.mask && options.readOnly && !skipMasking;
  13738. }
  13739. let payloadLength = dataLength;
  13740. if (dataLength >= 65536) {
  13741. offset += 8;
  13742. payloadLength = 127;
  13743. } else if (dataLength > 125) {
  13744. offset += 2;
  13745. payloadLength = 126;
  13746. }
  13747. const target = Buffer.allocUnsafe(merge ? dataLength + offset : offset);
  13748. target[0] = options.fin ? options.opcode | 128 : options.opcode;
  13749. if (options.rsv1) target[0] |= 64;
  13750. target[1] = payloadLength;
  13751. if (payloadLength === 126) target.writeUInt16BE(dataLength, 2);
  13752. else if (payloadLength === 127) {
  13753. target[2] = target[3] = 0;
  13754. target.writeUIntBE(dataLength, 4, 6);
  13755. }
  13756. if (!options.mask) return [target, data];
  13757. target[1] |= 128;
  13758. target[offset - 4] = mask[0];
  13759. target[offset - 3] = mask[1];
  13760. target[offset - 2] = mask[2];
  13761. target[offset - 1] = mask[3];
  13762. if (skipMasking) return [target, data];
  13763. if (merge) {
  13764. applyMask(data, mask, target, offset, dataLength);
  13765. return [target];
  13766. }
  13767. applyMask(data, mask, data, 0, dataLength);
  13768. return [target, data];
  13769. }
  13770. /**
  13771. * Sends a close message to the other peer.
  13772. *
  13773. * @param {Number} [code] The status code component of the body
  13774. * @param {(String|Buffer)} [data] The message component of the body
  13775. * @param {Boolean} [mask=false] Specifies whether or not to mask the message
  13776. * @param {Function} [cb] Callback
  13777. * @public
  13778. */
  13779. close(code, data, mask, cb) {
  13780. let buf;
  13781. if (code === void 0) buf = EMPTY_BUFFER;
  13782. else if (typeof code !== "number" || !isValidStatusCode(code)) throw new TypeError("First argument must be a valid error code number");
  13783. else if (data === void 0 || !data.length) {
  13784. buf = Buffer.allocUnsafe(2);
  13785. buf.writeUInt16BE(code, 0);
  13786. } else {
  13787. const length = Buffer.byteLength(data);
  13788. if (length > 123) throw new RangeError("The message must not be greater than 123 bytes");
  13789. buf = Buffer.allocUnsafe(2 + length);
  13790. buf.writeUInt16BE(code, 0);
  13791. if (typeof data === "string") buf.write(data, 2);
  13792. else buf.set(data, 2);
  13793. }
  13794. const options = {
  13795. [kByteLength]: buf.length,
  13796. fin: true,
  13797. generateMask: this._generateMask,
  13798. mask,
  13799. maskBuffer: this._maskBuffer,
  13800. opcode: 8,
  13801. readOnly: false,
  13802. rsv1: false
  13803. };
  13804. if (this._state !== DEFAULT) this.enqueue([
  13805. this.dispatch,
  13806. buf,
  13807. false,
  13808. options,
  13809. cb
  13810. ]);
  13811. else this.sendFrame(Sender.frame(buf, options), cb);
  13812. }
  13813. /**
  13814. * Sends a ping message to the other peer.
  13815. *
  13816. * @param {*} data The message to send
  13817. * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
  13818. * @param {Function} [cb] Callback
  13819. * @public
  13820. */
  13821. ping(data, mask, cb) {
  13822. let byteLength;
  13823. let readOnly;
  13824. if (typeof data === "string") {
  13825. byteLength = Buffer.byteLength(data);
  13826. readOnly = false;
  13827. } else if (isBlob(data)) {
  13828. byteLength = data.size;
  13829. readOnly = false;
  13830. } else {
  13831. data = toBuffer(data);
  13832. byteLength = data.length;
  13833. readOnly = toBuffer.readOnly;
  13834. }
  13835. if (byteLength > 125) throw new RangeError("The data size must not be greater than 125 bytes");
  13836. const options = {
  13837. [kByteLength]: byteLength,
  13838. fin: true,
  13839. generateMask: this._generateMask,
  13840. mask,
  13841. maskBuffer: this._maskBuffer,
  13842. opcode: 9,
  13843. readOnly,
  13844. rsv1: false
  13845. };
  13846. if (isBlob(data)) if (this._state !== DEFAULT) this.enqueue([
  13847. this.getBlobData,
  13848. data,
  13849. false,
  13850. options,
  13851. cb
  13852. ]);
  13853. else this.getBlobData(data, false, options, cb);
  13854. else if (this._state !== DEFAULT) this.enqueue([
  13855. this.dispatch,
  13856. data,
  13857. false,
  13858. options,
  13859. cb
  13860. ]);
  13861. else this.sendFrame(Sender.frame(data, options), cb);
  13862. }
  13863. /**
  13864. * Sends a pong message to the other peer.
  13865. *
  13866. * @param {*} data The message to send
  13867. * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
  13868. * @param {Function} [cb] Callback
  13869. * @public
  13870. */
  13871. pong(data, mask, cb) {
  13872. let byteLength;
  13873. let readOnly;
  13874. if (typeof data === "string") {
  13875. byteLength = Buffer.byteLength(data);
  13876. readOnly = false;
  13877. } else if (isBlob(data)) {
  13878. byteLength = data.size;
  13879. readOnly = false;
  13880. } else {
  13881. data = toBuffer(data);
  13882. byteLength = data.length;
  13883. readOnly = toBuffer.readOnly;
  13884. }
  13885. if (byteLength > 125) throw new RangeError("The data size must not be greater than 125 bytes");
  13886. const options = {
  13887. [kByteLength]: byteLength,
  13888. fin: true,
  13889. generateMask: this._generateMask,
  13890. mask,
  13891. maskBuffer: this._maskBuffer,
  13892. opcode: 10,
  13893. readOnly,
  13894. rsv1: false
  13895. };
  13896. if (isBlob(data)) if (this._state !== DEFAULT) this.enqueue([
  13897. this.getBlobData,
  13898. data,
  13899. false,
  13900. options,
  13901. cb
  13902. ]);
  13903. else this.getBlobData(data, false, options, cb);
  13904. else if (this._state !== DEFAULT) this.enqueue([
  13905. this.dispatch,
  13906. data,
  13907. false,
  13908. options,
  13909. cb
  13910. ]);
  13911. else this.sendFrame(Sender.frame(data, options), cb);
  13912. }
  13913. /**
  13914. * Sends a data message to the other peer.
  13915. *
  13916. * @param {*} data The message to send
  13917. * @param {Object} options Options object
  13918. * @param {Boolean} [options.binary=false] Specifies whether `data` is binary
  13919. * or text
  13920. * @param {Boolean} [options.compress=false] Specifies whether or not to
  13921. * compress `data`
  13922. * @param {Boolean} [options.fin=false] Specifies whether the fragment is the
  13923. * last one
  13924. * @param {Boolean} [options.mask=false] Specifies whether or not to mask
  13925. * `data`
  13926. * @param {Function} [cb] Callback
  13927. * @public
  13928. */
  13929. send(data, options, cb) {
  13930. const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
  13931. let opcode = options.binary ? 2 : 1;
  13932. let rsv1 = options.compress;
  13933. let byteLength;
  13934. let readOnly;
  13935. if (typeof data === "string") {
  13936. byteLength = Buffer.byteLength(data);
  13937. readOnly = false;
  13938. } else if (isBlob(data)) {
  13939. byteLength = data.size;
  13940. readOnly = false;
  13941. } else {
  13942. data = toBuffer(data);
  13943. byteLength = data.length;
  13944. readOnly = toBuffer.readOnly;
  13945. }
  13946. if (this._firstFragment) {
  13947. this._firstFragment = false;
  13948. if (rsv1 && perMessageDeflate && perMessageDeflate.params[perMessageDeflate._isServer ? "server_no_context_takeover" : "client_no_context_takeover"]) rsv1 = byteLength >= perMessageDeflate._threshold;
  13949. this._compress = rsv1;
  13950. } else {
  13951. rsv1 = false;
  13952. opcode = 0;
  13953. }
  13954. if (options.fin) this._firstFragment = true;
  13955. const opts = {
  13956. [kByteLength]: byteLength,
  13957. fin: options.fin,
  13958. generateMask: this._generateMask,
  13959. mask: options.mask,
  13960. maskBuffer: this._maskBuffer,
  13961. opcode,
  13962. readOnly,
  13963. rsv1
  13964. };
  13965. if (isBlob(data)) if (this._state !== DEFAULT) this.enqueue([
  13966. this.getBlobData,
  13967. data,
  13968. this._compress,
  13969. opts,
  13970. cb
  13971. ]);
  13972. else this.getBlobData(data, this._compress, opts, cb);
  13973. else if (this._state !== DEFAULT) this.enqueue([
  13974. this.dispatch,
  13975. data,
  13976. this._compress,
  13977. opts,
  13978. cb
  13979. ]);
  13980. else this.dispatch(data, this._compress, opts, cb);
  13981. }
  13982. /**
  13983. * Gets the contents of a blob as binary data.
  13984. *
  13985. * @param {Blob} blob The blob
  13986. * @param {Boolean} [compress=false] Specifies whether or not to compress
  13987. * the data
  13988. * @param {Object} options Options object
  13989. * @param {Boolean} [options.fin=false] Specifies whether or not to set the
  13990. * FIN bit
  13991. * @param {Function} [options.generateMask] The function used to generate the
  13992. * masking key
  13993. * @param {Boolean} [options.mask=false] Specifies whether or not to mask
  13994. * `data`
  13995. * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
  13996. * key
  13997. * @param {Number} options.opcode The opcode
  13998. * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
  13999. * modified
  14000. * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
  14001. * RSV1 bit
  14002. * @param {Function} [cb] Callback
  14003. * @private
  14004. */
  14005. getBlobData(blob, compress, options, cb) {
  14006. this._bufferedBytes += options[kByteLength];
  14007. this._state = GET_BLOB_DATA;
  14008. blob.arrayBuffer().then((arrayBuffer) => {
  14009. if (this._socket.destroyed) {
  14010. const err = /* @__PURE__ */ new Error("The socket was closed while the blob was being read");
  14011. process.nextTick(callCallbacks, this, err, cb);
  14012. return;
  14013. }
  14014. this._bufferedBytes -= options[kByteLength];
  14015. const data = toBuffer(arrayBuffer);
  14016. if (!compress) {
  14017. this._state = DEFAULT;
  14018. this.sendFrame(Sender.frame(data, options), cb);
  14019. this.dequeue();
  14020. } else this.dispatch(data, compress, options, cb);
  14021. }).catch((err) => {
  14022. process.nextTick(onError, this, err, cb);
  14023. });
  14024. }
  14025. /**
  14026. * Dispatches a message.
  14027. *
  14028. * @param {(Buffer|String)} data The message to send
  14029. * @param {Boolean} [compress=false] Specifies whether or not to compress
  14030. * `data`
  14031. * @param {Object} options Options object
  14032. * @param {Boolean} [options.fin=false] Specifies whether or not to set the
  14033. * FIN bit
  14034. * @param {Function} [options.generateMask] The function used to generate the
  14035. * masking key
  14036. * @param {Boolean} [options.mask=false] Specifies whether or not to mask
  14037. * `data`
  14038. * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
  14039. * key
  14040. * @param {Number} options.opcode The opcode
  14041. * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
  14042. * modified
  14043. * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
  14044. * RSV1 bit
  14045. * @param {Function} [cb] Callback
  14046. * @private
  14047. */
  14048. dispatch(data, compress, options, cb) {
  14049. if (!compress) {
  14050. this.sendFrame(Sender.frame(data, options), cb);
  14051. return;
  14052. }
  14053. const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
  14054. this._bufferedBytes += options[kByteLength];
  14055. this._state = DEFLATING;
  14056. perMessageDeflate.compress(data, options.fin, (_, buf) => {
  14057. if (this._socket.destroyed) {
  14058. callCallbacks(this, /* @__PURE__ */ new Error("The socket was closed while data was being compressed"), cb);
  14059. return;
  14060. }
  14061. this._bufferedBytes -= options[kByteLength];
  14062. this._state = DEFAULT;
  14063. options.readOnly = false;
  14064. this.sendFrame(Sender.frame(buf, options), cb);
  14065. this.dequeue();
  14066. });
  14067. }
  14068. /**
  14069. * Executes queued send operations.
  14070. *
  14071. * @private
  14072. */
  14073. dequeue() {
  14074. while (this._state === DEFAULT && this._queue.length) {
  14075. const params = this._queue.shift();
  14076. this._bufferedBytes -= params[3][kByteLength];
  14077. Reflect.apply(params[0], this, params.slice(1));
  14078. }
  14079. }
  14080. /**
  14081. * Enqueues a send operation.
  14082. *
  14083. * @param {Array} params Send operation parameters.
  14084. * @private
  14085. */
  14086. enqueue(params) {
  14087. this._bufferedBytes += params[3][kByteLength];
  14088. this._queue.push(params);
  14089. }
  14090. /**
  14091. * Sends a frame.
  14092. *
  14093. * @param {(Buffer | String)[]} list The frame to send
  14094. * @param {Function} [cb] Callback
  14095. * @private
  14096. */
  14097. sendFrame(list, cb) {
  14098. if (list.length === 2) {
  14099. this._socket.cork();
  14100. this._socket.write(list[0]);
  14101. this._socket.write(list[1], cb);
  14102. this._socket.uncork();
  14103. } else this._socket.write(list[0], cb);
  14104. }
  14105. };
  14106. /**
  14107. * Calls queued callbacks with an error.
  14108. *
  14109. * @param {Sender} sender The `Sender` instance
  14110. * @param {Error} err The error to call the callbacks with
  14111. * @param {Function} [cb] The first callback
  14112. * @private
  14113. */
  14114. function callCallbacks(sender, err, cb) {
  14115. if (typeof cb === "function") cb(err);
  14116. for (let i = 0; i < sender._queue.length; i++) {
  14117. const params = sender._queue[i];
  14118. const callback = params[params.length - 1];
  14119. if (typeof callback === "function") callback(err);
  14120. }
  14121. }
  14122. /**
  14123. * Handles a `Sender` error.
  14124. *
  14125. * @param {Sender} sender The `Sender` instance
  14126. * @param {Error} err The error
  14127. * @param {Function} [cb] The first pending callback
  14128. * @private
  14129. */
  14130. function onError(sender, err, cb) {
  14131. callCallbacks(sender, err, cb);
  14132. sender.onerror(err);
  14133. }
  14134. }));
  14135. //#endregion
  14136. //#region ../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/event-target.js
  14137. var require_event_target = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  14138. const { kForOnEventAttribute, kListener } = require_constants();
  14139. const kCode = Symbol("kCode");
  14140. const kData = Symbol("kData");
  14141. const kError = Symbol("kError");
  14142. const kMessage = Symbol("kMessage");
  14143. const kReason = Symbol("kReason");
  14144. const kTarget = Symbol("kTarget");
  14145. const kType = Symbol("kType");
  14146. const kWasClean = Symbol("kWasClean");
  14147. /**
  14148. * Class representing an event.
  14149. */
  14150. var Event = class {
  14151. /**
  14152. * Create a new `Event`.
  14153. *
  14154. * @param {String} type The name of the event
  14155. * @throws {TypeError} If the `type` argument is not specified
  14156. */
  14157. constructor(type) {
  14158. this[kTarget] = null;
  14159. this[kType] = type;
  14160. }
  14161. /**
  14162. * @type {*}
  14163. */
  14164. get target() {
  14165. return this[kTarget];
  14166. }
  14167. /**
  14168. * @type {String}
  14169. */
  14170. get type() {
  14171. return this[kType];
  14172. }
  14173. };
  14174. Object.defineProperty(Event.prototype, "target", { enumerable: true });
  14175. Object.defineProperty(Event.prototype, "type", { enumerable: true });
  14176. /**
  14177. * Class representing a close event.
  14178. *
  14179. * @extends Event
  14180. */
  14181. var CloseEvent = class extends Event {
  14182. /**
  14183. * Create a new `CloseEvent`.
  14184. *
  14185. * @param {String} type The name of the event
  14186. * @param {Object} [options] A dictionary object that allows for setting
  14187. * attributes via object members of the same name
  14188. * @param {Number} [options.code=0] The status code explaining why the
  14189. * connection was closed
  14190. * @param {String} [options.reason=''] A human-readable string explaining why
  14191. * the connection was closed
  14192. * @param {Boolean} [options.wasClean=false] Indicates whether or not the
  14193. * connection was cleanly closed
  14194. */
  14195. constructor(type, options = {}) {
  14196. super(type);
  14197. this[kCode] = options.code === void 0 ? 0 : options.code;
  14198. this[kReason] = options.reason === void 0 ? "" : options.reason;
  14199. this[kWasClean] = options.wasClean === void 0 ? false : options.wasClean;
  14200. }
  14201. /**
  14202. * @type {Number}
  14203. */
  14204. get code() {
  14205. return this[kCode];
  14206. }
  14207. /**
  14208. * @type {String}
  14209. */
  14210. get reason() {
  14211. return this[kReason];
  14212. }
  14213. /**
  14214. * @type {Boolean}
  14215. */
  14216. get wasClean() {
  14217. return this[kWasClean];
  14218. }
  14219. };
  14220. Object.defineProperty(CloseEvent.prototype, "code", { enumerable: true });
  14221. Object.defineProperty(CloseEvent.prototype, "reason", { enumerable: true });
  14222. Object.defineProperty(CloseEvent.prototype, "wasClean", { enumerable: true });
  14223. /**
  14224. * Class representing an error event.
  14225. *
  14226. * @extends Event
  14227. */
  14228. var ErrorEvent = class extends Event {
  14229. /**
  14230. * Create a new `ErrorEvent`.
  14231. *
  14232. * @param {String} type The name of the event
  14233. * @param {Object} [options] A dictionary object that allows for setting
  14234. * attributes via object members of the same name
  14235. * @param {*} [options.error=null] The error that generated this event
  14236. * @param {String} [options.message=''] The error message
  14237. */
  14238. constructor(type, options = {}) {
  14239. super(type);
  14240. this[kError] = options.error === void 0 ? null : options.error;
  14241. this[kMessage] = options.message === void 0 ? "" : options.message;
  14242. }
  14243. /**
  14244. * @type {*}
  14245. */
  14246. get error() {
  14247. return this[kError];
  14248. }
  14249. /**
  14250. * @type {String}
  14251. */
  14252. get message() {
  14253. return this[kMessage];
  14254. }
  14255. };
  14256. Object.defineProperty(ErrorEvent.prototype, "error", { enumerable: true });
  14257. Object.defineProperty(ErrorEvent.prototype, "message", { enumerable: true });
  14258. /**
  14259. * Class representing a message event.
  14260. *
  14261. * @extends Event
  14262. */
  14263. var MessageEvent = class extends Event {
  14264. /**
  14265. * Create a new `MessageEvent`.
  14266. *
  14267. * @param {String} type The name of the event
  14268. * @param {Object} [options] A dictionary object that allows for setting
  14269. * attributes via object members of the same name
  14270. * @param {*} [options.data=null] The message content
  14271. */
  14272. constructor(type, options = {}) {
  14273. super(type);
  14274. this[kData] = options.data === void 0 ? null : options.data;
  14275. }
  14276. /**
  14277. * @type {*}
  14278. */
  14279. get data() {
  14280. return this[kData];
  14281. }
  14282. };
  14283. Object.defineProperty(MessageEvent.prototype, "data", { enumerable: true });
  14284. module.exports = {
  14285. CloseEvent,
  14286. ErrorEvent,
  14287. Event,
  14288. EventTarget: {
  14289. addEventListener(type, handler, options = {}) {
  14290. for (const listener of this.listeners(type)) if (!options[kForOnEventAttribute] && listener[kListener] === handler && !listener[kForOnEventAttribute]) return;
  14291. let wrapper;
  14292. if (type === "message") wrapper = function onMessage(data, isBinary) {
  14293. const event = new MessageEvent("message", { data: isBinary ? data : data.toString() });
  14294. event[kTarget] = this;
  14295. callListener(handler, this, event);
  14296. };
  14297. else if (type === "close") wrapper = function onClose(code, message) {
  14298. const event = new CloseEvent("close", {
  14299. code,
  14300. reason: message.toString(),
  14301. wasClean: this._closeFrameReceived && this._closeFrameSent
  14302. });
  14303. event[kTarget] = this;
  14304. callListener(handler, this, event);
  14305. };
  14306. else if (type === "error") wrapper = function onError(error) {
  14307. const event = new ErrorEvent("error", {
  14308. error,
  14309. message: error.message
  14310. });
  14311. event[kTarget] = this;
  14312. callListener(handler, this, event);
  14313. };
  14314. else if (type === "open") wrapper = function onOpen() {
  14315. const event = new Event("open");
  14316. event[kTarget] = this;
  14317. callListener(handler, this, event);
  14318. };
  14319. else return;
  14320. wrapper[kForOnEventAttribute] = !!options[kForOnEventAttribute];
  14321. wrapper[kListener] = handler;
  14322. if (options.once) this.once(type, wrapper);
  14323. else this.on(type, wrapper);
  14324. },
  14325. removeEventListener(type, handler) {
  14326. for (const listener of this.listeners(type)) if (listener[kListener] === handler && !listener[kForOnEventAttribute]) {
  14327. this.removeListener(type, listener);
  14328. break;
  14329. }
  14330. }
  14331. },
  14332. MessageEvent
  14333. };
  14334. /**
  14335. * Call an event listener
  14336. *
  14337. * @param {(Function|Object)} listener The listener to call
  14338. * @param {*} thisArg The value to use as `this`` when calling the listener
  14339. * @param {Event} event The event to pass to the listener
  14340. * @private
  14341. */
  14342. function callListener(listener, thisArg, event) {
  14343. if (typeof listener === "object" && listener.handleEvent) listener.handleEvent.call(listener, event);
  14344. else listener.call(thisArg, event);
  14345. }
  14346. }));
  14347. //#endregion
  14348. //#region ../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/extension.js
  14349. var require_extension = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  14350. const { tokenChars } = require_validation();
  14351. /**
  14352. * Adds an offer to the map of extension offers or a parameter to the map of
  14353. * parameters.
  14354. *
  14355. * @param {Object} dest The map of extension offers or parameters
  14356. * @param {String} name The extension or parameter name
  14357. * @param {(Object|Boolean|String)} elem The extension parameters or the
  14358. * parameter value
  14359. * @private
  14360. */
  14361. function push(dest, name, elem) {
  14362. if (dest[name] === void 0) dest[name] = [elem];
  14363. else dest[name].push(elem);
  14364. }
  14365. /**
  14366. * Parses the `Sec-WebSocket-Extensions` header into an object.
  14367. *
  14368. * @param {String} header The field value of the header
  14369. * @return {Object} The parsed object
  14370. * @public
  14371. */
  14372. function parse(header) {
  14373. const offers = Object.create(null);
  14374. let params = Object.create(null);
  14375. let mustUnescape = false;
  14376. let isEscaping = false;
  14377. let inQuotes = false;
  14378. let extensionName;
  14379. let paramName;
  14380. let start = -1;
  14381. let code = -1;
  14382. let end = -1;
  14383. let i = 0;
  14384. for (; i < header.length; i++) {
  14385. code = header.charCodeAt(i);
  14386. if (extensionName === void 0) if (end === -1 && tokenChars[code] === 1) {
  14387. if (start === -1) start = i;
  14388. } else if (i !== 0 && (code === 32 || code === 9)) {
  14389. if (end === -1 && start !== -1) end = i;
  14390. } else if (code === 59 || code === 44) {
  14391. if (start === -1) throw new SyntaxError(`Unexpected character at index ${i}`);
  14392. if (end === -1) end = i;
  14393. const name = header.slice(start, end);
  14394. if (code === 44) {
  14395. push(offers, name, params);
  14396. params = Object.create(null);
  14397. } else extensionName = name;
  14398. start = end = -1;
  14399. } else throw new SyntaxError(`Unexpected character at index ${i}`);
  14400. else if (paramName === void 0) if (end === -1 && tokenChars[code] === 1) {
  14401. if (start === -1) start = i;
  14402. } else if (code === 32 || code === 9) {
  14403. if (end === -1 && start !== -1) end = i;
  14404. } else if (code === 59 || code === 44) {
  14405. if (start === -1) throw new SyntaxError(`Unexpected character at index ${i}`);
  14406. if (end === -1) end = i;
  14407. push(params, header.slice(start, end), true);
  14408. if (code === 44) {
  14409. push(offers, extensionName, params);
  14410. params = Object.create(null);
  14411. extensionName = void 0;
  14412. }
  14413. start = end = -1;
  14414. } else if (code === 61 && start !== -1 && end === -1) {
  14415. paramName = header.slice(start, i);
  14416. start = end = -1;
  14417. } else throw new SyntaxError(`Unexpected character at index ${i}`);
  14418. else if (isEscaping) {
  14419. if (tokenChars[code] !== 1) throw new SyntaxError(`Unexpected character at index ${i}`);
  14420. if (start === -1) start = i;
  14421. else if (!mustUnescape) mustUnescape = true;
  14422. isEscaping = false;
  14423. } else if (inQuotes) if (tokenChars[code] === 1) {
  14424. if (start === -1) start = i;
  14425. } else if (code === 34 && start !== -1) {
  14426. inQuotes = false;
  14427. end = i;
  14428. } else if (code === 92) isEscaping = true;
  14429. else throw new SyntaxError(`Unexpected character at index ${i}`);
  14430. else if (code === 34 && header.charCodeAt(i - 1) === 61) inQuotes = true;
  14431. else if (end === -1 && tokenChars[code] === 1) {
  14432. if (start === -1) start = i;
  14433. } else if (start !== -1 && (code === 32 || code === 9)) {
  14434. if (end === -1) end = i;
  14435. } else if (code === 59 || code === 44) {
  14436. if (start === -1) throw new SyntaxError(`Unexpected character at index ${i}`);
  14437. if (end === -1) end = i;
  14438. let value = header.slice(start, end);
  14439. if (mustUnescape) {
  14440. value = value.replace(/\\/g, "");
  14441. mustUnescape = false;
  14442. }
  14443. push(params, paramName, value);
  14444. if (code === 44) {
  14445. push(offers, extensionName, params);
  14446. params = Object.create(null);
  14447. extensionName = void 0;
  14448. }
  14449. paramName = void 0;
  14450. start = end = -1;
  14451. } else throw new SyntaxError(`Unexpected character at index ${i}`);
  14452. }
  14453. if (start === -1 || inQuotes || code === 32 || code === 9) throw new SyntaxError("Unexpected end of input");
  14454. if (end === -1) end = i;
  14455. const token = header.slice(start, end);
  14456. if (extensionName === void 0) push(offers, token, params);
  14457. else {
  14458. if (paramName === void 0) push(params, token, true);
  14459. else if (mustUnescape) push(params, paramName, token.replace(/\\/g, ""));
  14460. else push(params, paramName, token);
  14461. push(offers, extensionName, params);
  14462. }
  14463. return offers;
  14464. }
  14465. /**
  14466. * Builds the `Sec-WebSocket-Extensions` header field value.
  14467. *
  14468. * @param {Object} extensions The map of extensions and parameters to format
  14469. * @return {String} A string representing the given object
  14470. * @public
  14471. */
  14472. function format(extensions) {
  14473. return Object.keys(extensions).map((extension) => {
  14474. let configurations = extensions[extension];
  14475. if (!Array.isArray(configurations)) configurations = [configurations];
  14476. return configurations.map((params) => {
  14477. return [extension].concat(Object.keys(params).map((k) => {
  14478. let values = params[k];
  14479. if (!Array.isArray(values)) values = [values];
  14480. return values.map((v) => v === true ? k : `${k}=${v}`).join("; ");
  14481. })).join("; ");
  14482. }).join(", ");
  14483. }).join(", ");
  14484. }
  14485. module.exports = {
  14486. format,
  14487. parse
  14488. };
  14489. }));
  14490. //#endregion
  14491. //#region ../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/websocket.js
  14492. var require_websocket = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  14493. const EventEmitter$2 = __require("events");
  14494. const https$3 = __require("https");
  14495. const http$5 = __require("http");
  14496. const net$1 = __require("net");
  14497. const tls = __require("tls");
  14498. const { randomBytes, createHash: createHash$1 } = __require("crypto");
  14499. const { Duplex: Duplex$2, Readable } = __require("stream");
  14500. const { URL: URL$2 } = __require("url");
  14501. const PerMessageDeflate = require_permessage_deflate();
  14502. const Receiver = require_receiver();
  14503. const Sender = require_sender();
  14504. const { isBlob } = require_validation();
  14505. const { BINARY_TYPES, CLOSE_TIMEOUT, EMPTY_BUFFER, GUID, kForOnEventAttribute, kListener, kStatusCode, kWebSocket, NOOP } = require_constants();
  14506. const { EventTarget: { addEventListener, removeEventListener } } = require_event_target();
  14507. const { format, parse } = require_extension();
  14508. const { toBuffer } = require_buffer_util();
  14509. const kAborted = Symbol("kAborted");
  14510. const protocolVersions = [8, 13];
  14511. const readyStates = [
  14512. "CONNECTING",
  14513. "OPEN",
  14514. "CLOSING",
  14515. "CLOSED"
  14516. ];
  14517. const subprotocolRegex = /^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;
  14518. /**
  14519. * Class representing a WebSocket.
  14520. *
  14521. * @extends EventEmitter
  14522. */
  14523. var WebSocket = class WebSocket extends EventEmitter$2 {
  14524. /**
  14525. * Create a new `WebSocket`.
  14526. *
  14527. * @param {(String|URL)} address The URL to which to connect
  14528. * @param {(String|String[])} [protocols] The subprotocols
  14529. * @param {Object} [options] Connection options
  14530. */
  14531. constructor(address, protocols, options) {
  14532. super();
  14533. this._binaryType = BINARY_TYPES[0];
  14534. this._closeCode = 1006;
  14535. this._closeFrameReceived = false;
  14536. this._closeFrameSent = false;
  14537. this._closeMessage = EMPTY_BUFFER;
  14538. this._closeTimer = null;
  14539. this._errorEmitted = false;
  14540. this._extensions = {};
  14541. this._paused = false;
  14542. this._protocol = "";
  14543. this._readyState = WebSocket.CONNECTING;
  14544. this._receiver = null;
  14545. this._sender = null;
  14546. this._socket = null;
  14547. if (address !== null) {
  14548. this._bufferedAmount = 0;
  14549. this._isServer = false;
  14550. this._redirects = 0;
  14551. if (protocols === void 0) protocols = [];
  14552. else if (!Array.isArray(protocols)) if (typeof protocols === "object" && protocols !== null) {
  14553. options = protocols;
  14554. protocols = [];
  14555. } else protocols = [protocols];
  14556. initAsClient(this, address, protocols, options);
  14557. } else {
  14558. this._autoPong = options.autoPong;
  14559. this._closeTimeout = options.closeTimeout;
  14560. this._isServer = true;
  14561. }
  14562. }
  14563. /**
  14564. * For historical reasons, the custom "nodebuffer" type is used by the default
  14565. * instead of "blob".
  14566. *
  14567. * @type {String}
  14568. */
  14569. get binaryType() {
  14570. return this._binaryType;
  14571. }
  14572. set binaryType(type) {
  14573. if (!BINARY_TYPES.includes(type)) return;
  14574. this._binaryType = type;
  14575. if (this._receiver) this._receiver._binaryType = type;
  14576. }
  14577. /**
  14578. * @type {Number}
  14579. */
  14580. get bufferedAmount() {
  14581. if (!this._socket) return this._bufferedAmount;
  14582. return this._socket._writableState.length + this._sender._bufferedBytes;
  14583. }
  14584. /**
  14585. * @type {String}
  14586. */
  14587. get extensions() {
  14588. return Object.keys(this._extensions).join();
  14589. }
  14590. /**
  14591. * @type {Boolean}
  14592. */
  14593. get isPaused() {
  14594. return this._paused;
  14595. }
  14596. /**
  14597. * @type {Function}
  14598. */
  14599. /* istanbul ignore next */
  14600. get onclose() {
  14601. return null;
  14602. }
  14603. /**
  14604. * @type {Function}
  14605. */
  14606. /* istanbul ignore next */
  14607. get onerror() {
  14608. return null;
  14609. }
  14610. /**
  14611. * @type {Function}
  14612. */
  14613. /* istanbul ignore next */
  14614. get onopen() {
  14615. return null;
  14616. }
  14617. /**
  14618. * @type {Function}
  14619. */
  14620. /* istanbul ignore next */
  14621. get onmessage() {
  14622. return null;
  14623. }
  14624. /**
  14625. * @type {String}
  14626. */
  14627. get protocol() {
  14628. return this._protocol;
  14629. }
  14630. /**
  14631. * @type {Number}
  14632. */
  14633. get readyState() {
  14634. return this._readyState;
  14635. }
  14636. /**
  14637. * @type {String}
  14638. */
  14639. get url() {
  14640. return this._url;
  14641. }
  14642. /**
  14643. * Set up the socket and the internal resources.
  14644. *
  14645. * @param {Duplex} socket The network socket between the server and client
  14646. * @param {Buffer} head The first packet of the upgraded stream
  14647. * @param {Object} options Options object
  14648. * @param {Boolean} [options.allowSynchronousEvents=false] Specifies whether
  14649. * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
  14650. * multiple times in the same tick
  14651. * @param {Function} [options.generateMask] The function used to generate the
  14652. * masking key
  14653. * @param {Number} [options.maxPayload=0] The maximum allowed message size
  14654. * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
  14655. * not to skip UTF-8 validation for text and close messages
  14656. * @private
  14657. */
  14658. setSocket(socket, head, options) {
  14659. const receiver = new Receiver({
  14660. allowSynchronousEvents: options.allowSynchronousEvents,
  14661. binaryType: this.binaryType,
  14662. extensions: this._extensions,
  14663. isServer: this._isServer,
  14664. maxPayload: options.maxPayload,
  14665. skipUTF8Validation: options.skipUTF8Validation
  14666. });
  14667. const sender = new Sender(socket, this._extensions, options.generateMask);
  14668. this._receiver = receiver;
  14669. this._sender = sender;
  14670. this._socket = socket;
  14671. receiver[kWebSocket] = this;
  14672. sender[kWebSocket] = this;
  14673. socket[kWebSocket] = this;
  14674. receiver.on("conclude", receiverOnConclude);
  14675. receiver.on("drain", receiverOnDrain);
  14676. receiver.on("error", receiverOnError);
  14677. receiver.on("message", receiverOnMessage);
  14678. receiver.on("ping", receiverOnPing);
  14679. receiver.on("pong", receiverOnPong);
  14680. sender.onerror = senderOnError;
  14681. if (socket.setTimeout) socket.setTimeout(0);
  14682. if (socket.setNoDelay) socket.setNoDelay();
  14683. if (head.length > 0) socket.unshift(head);
  14684. socket.on("close", socketOnClose);
  14685. socket.on("data", socketOnData);
  14686. socket.on("end", socketOnEnd);
  14687. socket.on("error", socketOnError);
  14688. this._readyState = WebSocket.OPEN;
  14689. this.emit("open");
  14690. }
  14691. /**
  14692. * Emit the `'close'` event.
  14693. *
  14694. * @private
  14695. */
  14696. emitClose() {
  14697. if (!this._socket) {
  14698. this._readyState = WebSocket.CLOSED;
  14699. this.emit("close", this._closeCode, this._closeMessage);
  14700. return;
  14701. }
  14702. if (this._extensions[PerMessageDeflate.extensionName]) this._extensions[PerMessageDeflate.extensionName].cleanup();
  14703. this._receiver.removeAllListeners();
  14704. this._readyState = WebSocket.CLOSED;
  14705. this.emit("close", this._closeCode, this._closeMessage);
  14706. }
  14707. /**
  14708. * Start a closing handshake.
  14709. *
  14710. * +----------+ +-----------+ +----------+
  14711. * - - -|ws.close()|-->|close frame|-->|ws.close()|- - -
  14712. * | +----------+ +-----------+ +----------+ |
  14713. * +----------+ +-----------+ |
  14714. * CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING
  14715. * +----------+ +-----------+ |
  14716. * | | | +---+ |
  14717. * +------------------------+-->|fin| - - - -
  14718. * | +---+ | +---+
  14719. * - - - - -|fin|<---------------------+
  14720. * +---+
  14721. *
  14722. * @param {Number} [code] Status code explaining why the connection is closing
  14723. * @param {(String|Buffer)} [data] The reason why the connection is
  14724. * closing
  14725. * @public
  14726. */
  14727. close(code, data) {
  14728. if (this.readyState === WebSocket.CLOSED) return;
  14729. if (this.readyState === WebSocket.CONNECTING) {
  14730. abortHandshake(this, this._req, "WebSocket was closed before the connection was established");
  14731. return;
  14732. }
  14733. if (this.readyState === WebSocket.CLOSING) {
  14734. if (this._closeFrameSent && (this._closeFrameReceived || this._receiver._writableState.errorEmitted)) this._socket.end();
  14735. return;
  14736. }
  14737. this._readyState = WebSocket.CLOSING;
  14738. this._sender.close(code, data, !this._isServer, (err) => {
  14739. if (err) return;
  14740. this._closeFrameSent = true;
  14741. if (this._closeFrameReceived || this._receiver._writableState.errorEmitted) this._socket.end();
  14742. });
  14743. setCloseTimer(this);
  14744. }
  14745. /**
  14746. * Pause the socket.
  14747. *
  14748. * @public
  14749. */
  14750. pause() {
  14751. if (this.readyState === WebSocket.CONNECTING || this.readyState === WebSocket.CLOSED) return;
  14752. this._paused = true;
  14753. this._socket.pause();
  14754. }
  14755. /**
  14756. * Send a ping.
  14757. *
  14758. * @param {*} [data] The data to send
  14759. * @param {Boolean} [mask] Indicates whether or not to mask `data`
  14760. * @param {Function} [cb] Callback which is executed when the ping is sent
  14761. * @public
  14762. */
  14763. ping(data, mask, cb) {
  14764. if (this.readyState === WebSocket.CONNECTING) throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
  14765. if (typeof data === "function") {
  14766. cb = data;
  14767. data = mask = void 0;
  14768. } else if (typeof mask === "function") {
  14769. cb = mask;
  14770. mask = void 0;
  14771. }
  14772. if (typeof data === "number") data = data.toString();
  14773. if (this.readyState !== WebSocket.OPEN) {
  14774. sendAfterClose(this, data, cb);
  14775. return;
  14776. }
  14777. if (mask === void 0) mask = !this._isServer;
  14778. this._sender.ping(data || EMPTY_BUFFER, mask, cb);
  14779. }
  14780. /**
  14781. * Send a pong.
  14782. *
  14783. * @param {*} [data] The data to send
  14784. * @param {Boolean} [mask] Indicates whether or not to mask `data`
  14785. * @param {Function} [cb] Callback which is executed when the pong is sent
  14786. * @public
  14787. */
  14788. pong(data, mask, cb) {
  14789. if (this.readyState === WebSocket.CONNECTING) throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
  14790. if (typeof data === "function") {
  14791. cb = data;
  14792. data = mask = void 0;
  14793. } else if (typeof mask === "function") {
  14794. cb = mask;
  14795. mask = void 0;
  14796. }
  14797. if (typeof data === "number") data = data.toString();
  14798. if (this.readyState !== WebSocket.OPEN) {
  14799. sendAfterClose(this, data, cb);
  14800. return;
  14801. }
  14802. if (mask === void 0) mask = !this._isServer;
  14803. this._sender.pong(data || EMPTY_BUFFER, mask, cb);
  14804. }
  14805. /**
  14806. * Resume the socket.
  14807. *
  14808. * @public
  14809. */
  14810. resume() {
  14811. if (this.readyState === WebSocket.CONNECTING || this.readyState === WebSocket.CLOSED) return;
  14812. this._paused = false;
  14813. if (!this._receiver._writableState.needDrain) this._socket.resume();
  14814. }
  14815. /**
  14816. * Send a data message.
  14817. *
  14818. * @param {*} data The message to send
  14819. * @param {Object} [options] Options object
  14820. * @param {Boolean} [options.binary] Specifies whether `data` is binary or
  14821. * text
  14822. * @param {Boolean} [options.compress] Specifies whether or not to compress
  14823. * `data`
  14824. * @param {Boolean} [options.fin=true] Specifies whether the fragment is the
  14825. * last one
  14826. * @param {Boolean} [options.mask] Specifies whether or not to mask `data`
  14827. * @param {Function} [cb] Callback which is executed when data is written out
  14828. * @public
  14829. */
  14830. send(data, options, cb) {
  14831. if (this.readyState === WebSocket.CONNECTING) throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
  14832. if (typeof options === "function") {
  14833. cb = options;
  14834. options = {};
  14835. }
  14836. if (typeof data === "number") data = data.toString();
  14837. if (this.readyState !== WebSocket.OPEN) {
  14838. sendAfterClose(this, data, cb);
  14839. return;
  14840. }
  14841. const opts = {
  14842. binary: typeof data !== "string",
  14843. mask: !this._isServer,
  14844. compress: true,
  14845. fin: true,
  14846. ...options
  14847. };
  14848. if (!this._extensions[PerMessageDeflate.extensionName]) opts.compress = false;
  14849. this._sender.send(data || EMPTY_BUFFER, opts, cb);
  14850. }
  14851. /**
  14852. * Forcibly close the connection.
  14853. *
  14854. * @public
  14855. */
  14856. terminate() {
  14857. if (this.readyState === WebSocket.CLOSED) return;
  14858. if (this.readyState === WebSocket.CONNECTING) {
  14859. abortHandshake(this, this._req, "WebSocket was closed before the connection was established");
  14860. return;
  14861. }
  14862. if (this._socket) {
  14863. this._readyState = WebSocket.CLOSING;
  14864. this._socket.destroy();
  14865. }
  14866. }
  14867. };
  14868. /**
  14869. * @constant {Number} CONNECTING
  14870. * @memberof WebSocket
  14871. */
  14872. Object.defineProperty(WebSocket, "CONNECTING", {
  14873. enumerable: true,
  14874. value: readyStates.indexOf("CONNECTING")
  14875. });
  14876. /**
  14877. * @constant {Number} CONNECTING
  14878. * @memberof WebSocket.prototype
  14879. */
  14880. Object.defineProperty(WebSocket.prototype, "CONNECTING", {
  14881. enumerable: true,
  14882. value: readyStates.indexOf("CONNECTING")
  14883. });
  14884. /**
  14885. * @constant {Number} OPEN
  14886. * @memberof WebSocket
  14887. */
  14888. Object.defineProperty(WebSocket, "OPEN", {
  14889. enumerable: true,
  14890. value: readyStates.indexOf("OPEN")
  14891. });
  14892. /**
  14893. * @constant {Number} OPEN
  14894. * @memberof WebSocket.prototype
  14895. */
  14896. Object.defineProperty(WebSocket.prototype, "OPEN", {
  14897. enumerable: true,
  14898. value: readyStates.indexOf("OPEN")
  14899. });
  14900. /**
  14901. * @constant {Number} CLOSING
  14902. * @memberof WebSocket
  14903. */
  14904. Object.defineProperty(WebSocket, "CLOSING", {
  14905. enumerable: true,
  14906. value: readyStates.indexOf("CLOSING")
  14907. });
  14908. /**
  14909. * @constant {Number} CLOSING
  14910. * @memberof WebSocket.prototype
  14911. */
  14912. Object.defineProperty(WebSocket.prototype, "CLOSING", {
  14913. enumerable: true,
  14914. value: readyStates.indexOf("CLOSING")
  14915. });
  14916. /**
  14917. * @constant {Number} CLOSED
  14918. * @memberof WebSocket
  14919. */
  14920. Object.defineProperty(WebSocket, "CLOSED", {
  14921. enumerable: true,
  14922. value: readyStates.indexOf("CLOSED")
  14923. });
  14924. /**
  14925. * @constant {Number} CLOSED
  14926. * @memberof WebSocket.prototype
  14927. */
  14928. Object.defineProperty(WebSocket.prototype, "CLOSED", {
  14929. enumerable: true,
  14930. value: readyStates.indexOf("CLOSED")
  14931. });
  14932. [
  14933. "binaryType",
  14934. "bufferedAmount",
  14935. "extensions",
  14936. "isPaused",
  14937. "protocol",
  14938. "readyState",
  14939. "url"
  14940. ].forEach((property) => {
  14941. Object.defineProperty(WebSocket.prototype, property, { enumerable: true });
  14942. });
  14943. [
  14944. "open",
  14945. "error",
  14946. "close",
  14947. "message"
  14948. ].forEach((method) => {
  14949. Object.defineProperty(WebSocket.prototype, `on${method}`, {
  14950. enumerable: true,
  14951. get() {
  14952. for (const listener of this.listeners(method)) if (listener[kForOnEventAttribute]) return listener[kListener];
  14953. return null;
  14954. },
  14955. set(handler) {
  14956. for (const listener of this.listeners(method)) if (listener[kForOnEventAttribute]) {
  14957. this.removeListener(method, listener);
  14958. break;
  14959. }
  14960. if (typeof handler !== "function") return;
  14961. this.addEventListener(method, handler, { [kForOnEventAttribute]: true });
  14962. }
  14963. });
  14964. });
  14965. WebSocket.prototype.addEventListener = addEventListener;
  14966. WebSocket.prototype.removeEventListener = removeEventListener;
  14967. module.exports = WebSocket;
  14968. /**
  14969. * Initialize a WebSocket client.
  14970. *
  14971. * @param {WebSocket} websocket The client to initialize
  14972. * @param {(String|URL)} address The URL to which to connect
  14973. * @param {Array} protocols The subprotocols
  14974. * @param {Object} [options] Connection options
  14975. * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether any
  14976. * of the `'message'`, `'ping'`, and `'pong'` events can be emitted multiple
  14977. * times in the same tick
  14978. * @param {Boolean} [options.autoPong=true] Specifies whether or not to
  14979. * automatically send a pong in response to a ping
  14980. * @param {Number} [options.closeTimeout=30000] Duration in milliseconds to wait
  14981. * for the closing handshake to finish after `websocket.close()` is called
  14982. * @param {Function} [options.finishRequest] A function which can be used to
  14983. * customize the headers of each http request before it is sent
  14984. * @param {Boolean} [options.followRedirects=false] Whether or not to follow
  14985. * redirects
  14986. * @param {Function} [options.generateMask] The function used to generate the
  14987. * masking key
  14988. * @param {Number} [options.handshakeTimeout] Timeout in milliseconds for the
  14989. * handshake request
  14990. * @param {Number} [options.maxPayload=104857600] The maximum allowed message
  14991. * size
  14992. * @param {Number} [options.maxRedirects=10] The maximum number of redirects
  14993. * allowed
  14994. * @param {String} [options.origin] Value of the `Origin` or
  14995. * `Sec-WebSocket-Origin` header
  14996. * @param {(Boolean|Object)} [options.perMessageDeflate=true] Enable/disable
  14997. * permessage-deflate
  14998. * @param {Number} [options.protocolVersion=13] Value of the
  14999. * `Sec-WebSocket-Version` header
  15000. * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
  15001. * not to skip UTF-8 validation for text and close messages
  15002. * @private
  15003. */
  15004. function initAsClient(websocket, address, protocols, options) {
  15005. const opts = {
  15006. allowSynchronousEvents: true,
  15007. autoPong: true,
  15008. closeTimeout: CLOSE_TIMEOUT,
  15009. protocolVersion: protocolVersions[1],
  15010. maxPayload: 100 * 1024 * 1024,
  15011. skipUTF8Validation: false,
  15012. perMessageDeflate: true,
  15013. followRedirects: false,
  15014. maxRedirects: 10,
  15015. ...options,
  15016. socketPath: void 0,
  15017. hostname: void 0,
  15018. protocol: void 0,
  15019. timeout: void 0,
  15020. method: "GET",
  15021. host: void 0,
  15022. path: void 0,
  15023. port: void 0
  15024. };
  15025. websocket._autoPong = opts.autoPong;
  15026. websocket._closeTimeout = opts.closeTimeout;
  15027. if (!protocolVersions.includes(opts.protocolVersion)) throw new RangeError(`Unsupported protocol version: ${opts.protocolVersion} (supported versions: ${protocolVersions.join(", ")})`);
  15028. let parsedUrl;
  15029. if (address instanceof URL$2) parsedUrl = address;
  15030. else try {
  15031. parsedUrl = new URL$2(address);
  15032. } catch {
  15033. throw new SyntaxError(`Invalid URL: ${address}`);
  15034. }
  15035. if (parsedUrl.protocol === "http:") parsedUrl.protocol = "ws:";
  15036. else if (parsedUrl.protocol === "https:") parsedUrl.protocol = "wss:";
  15037. websocket._url = parsedUrl.href;
  15038. const isSecure = parsedUrl.protocol === "wss:";
  15039. const isIpcUrl = parsedUrl.protocol === "ws+unix:";
  15040. let invalidUrlMessage;
  15041. if (parsedUrl.protocol !== "ws:" && !isSecure && !isIpcUrl) invalidUrlMessage = "The URL's protocol must be one of \"ws:\", \"wss:\", \"http:\", \"https:\", or \"ws+unix:\"";
  15042. else if (isIpcUrl && !parsedUrl.pathname) invalidUrlMessage = "The URL's pathname is empty";
  15043. else if (parsedUrl.hash) invalidUrlMessage = "The URL contains a fragment identifier";
  15044. if (invalidUrlMessage) {
  15045. const err = new SyntaxError(invalidUrlMessage);
  15046. if (websocket._redirects === 0) throw err;
  15047. else {
  15048. emitErrorAndClose(websocket, err);
  15049. return;
  15050. }
  15051. }
  15052. const defaultPort = isSecure ? 443 : 80;
  15053. const key = randomBytes(16).toString("base64");
  15054. const request = isSecure ? https$3.request : http$5.request;
  15055. const protocolSet = /* @__PURE__ */ new Set();
  15056. let perMessageDeflate;
  15057. opts.createConnection = opts.createConnection || (isSecure ? tlsConnect : netConnect);
  15058. opts.defaultPort = opts.defaultPort || defaultPort;
  15059. opts.port = parsedUrl.port || defaultPort;
  15060. opts.host = parsedUrl.hostname.startsWith("[") ? parsedUrl.hostname.slice(1, -1) : parsedUrl.hostname;
  15061. opts.headers = {
  15062. ...opts.headers,
  15063. "Sec-WebSocket-Version": opts.protocolVersion,
  15064. "Sec-WebSocket-Key": key,
  15065. Connection: "Upgrade",
  15066. Upgrade: "websocket"
  15067. };
  15068. opts.path = parsedUrl.pathname + parsedUrl.search;
  15069. opts.timeout = opts.handshakeTimeout;
  15070. if (opts.perMessageDeflate) {
  15071. perMessageDeflate = new PerMessageDeflate({
  15072. ...opts.perMessageDeflate,
  15073. isServer: false,
  15074. maxPayload: opts.maxPayload
  15075. });
  15076. opts.headers["Sec-WebSocket-Extensions"] = format({ [PerMessageDeflate.extensionName]: perMessageDeflate.offer() });
  15077. }
  15078. if (protocols.length) {
  15079. for (const protocol of protocols) {
  15080. if (typeof protocol !== "string" || !subprotocolRegex.test(protocol) || protocolSet.has(protocol)) throw new SyntaxError("An invalid or duplicated subprotocol was specified");
  15081. protocolSet.add(protocol);
  15082. }
  15083. opts.headers["Sec-WebSocket-Protocol"] = protocols.join(",");
  15084. }
  15085. if (opts.origin) if (opts.protocolVersion < 13) opts.headers["Sec-WebSocket-Origin"] = opts.origin;
  15086. else opts.headers.Origin = opts.origin;
  15087. if (parsedUrl.username || parsedUrl.password) opts.auth = `${parsedUrl.username}:${parsedUrl.password}`;
  15088. if (isIpcUrl) {
  15089. const parts = opts.path.split(":");
  15090. opts.socketPath = parts[0];
  15091. opts.path = parts[1];
  15092. }
  15093. let req;
  15094. if (opts.followRedirects) {
  15095. if (websocket._redirects === 0) {
  15096. websocket._originalIpc = isIpcUrl;
  15097. websocket._originalSecure = isSecure;
  15098. websocket._originalHostOrSocketPath = isIpcUrl ? opts.socketPath : parsedUrl.host;
  15099. const headers = options && options.headers;
  15100. options = {
  15101. ...options,
  15102. headers: {}
  15103. };
  15104. if (headers) for (const [key, value] of Object.entries(headers)) options.headers[key.toLowerCase()] = value;
  15105. } else if (websocket.listenerCount("redirect") === 0) {
  15106. const isSameHost = isIpcUrl ? websocket._originalIpc ? opts.socketPath === websocket._originalHostOrSocketPath : false : websocket._originalIpc ? false : parsedUrl.host === websocket._originalHostOrSocketPath;
  15107. if (!isSameHost || websocket._originalSecure && !isSecure) {
  15108. delete opts.headers.authorization;
  15109. delete opts.headers.cookie;
  15110. if (!isSameHost) delete opts.headers.host;
  15111. opts.auth = void 0;
  15112. }
  15113. }
  15114. if (opts.auth && !options.headers.authorization) options.headers.authorization = "Basic " + Buffer.from(opts.auth).toString("base64");
  15115. req = websocket._req = request(opts);
  15116. if (websocket._redirects) websocket.emit("redirect", websocket.url, req);
  15117. } else req = websocket._req = request(opts);
  15118. if (opts.timeout) req.on("timeout", () => {
  15119. abortHandshake(websocket, req, "Opening handshake has timed out");
  15120. });
  15121. req.on("error", (err) => {
  15122. if (req === null || req[kAborted]) return;
  15123. req = websocket._req = null;
  15124. emitErrorAndClose(websocket, err);
  15125. });
  15126. req.on("response", (res) => {
  15127. const location = res.headers.location;
  15128. const statusCode = res.statusCode;
  15129. if (location && opts.followRedirects && statusCode >= 300 && statusCode < 400) {
  15130. if (++websocket._redirects > opts.maxRedirects) {
  15131. abortHandshake(websocket, req, "Maximum redirects exceeded");
  15132. return;
  15133. }
  15134. req.abort();
  15135. let addr;
  15136. try {
  15137. addr = new URL$2(location, address);
  15138. } catch (e) {
  15139. emitErrorAndClose(websocket, /* @__PURE__ */ new SyntaxError(`Invalid URL: ${location}`));
  15140. return;
  15141. }
  15142. initAsClient(websocket, addr, protocols, options);
  15143. } else if (!websocket.emit("unexpected-response", req, res)) abortHandshake(websocket, req, `Unexpected server response: ${res.statusCode}`);
  15144. });
  15145. req.on("upgrade", (res, socket, head) => {
  15146. websocket.emit("upgrade", res);
  15147. if (websocket.readyState !== WebSocket.CONNECTING) return;
  15148. req = websocket._req = null;
  15149. const upgrade = res.headers.upgrade;
  15150. if (upgrade === void 0 || upgrade.toLowerCase() !== "websocket") {
  15151. abortHandshake(websocket, socket, "Invalid Upgrade header");
  15152. return;
  15153. }
  15154. const digest = createHash$1("sha1").update(key + GUID).digest("base64");
  15155. if (res.headers["sec-websocket-accept"] !== digest) {
  15156. abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header");
  15157. return;
  15158. }
  15159. const serverProt = res.headers["sec-websocket-protocol"];
  15160. let protError;
  15161. if (serverProt !== void 0) {
  15162. if (!protocolSet.size) protError = "Server sent a subprotocol but none was requested";
  15163. else if (!protocolSet.has(serverProt)) protError = "Server sent an invalid subprotocol";
  15164. } else if (protocolSet.size) protError = "Server sent no subprotocol";
  15165. if (protError) {
  15166. abortHandshake(websocket, socket, protError);
  15167. return;
  15168. }
  15169. if (serverProt) websocket._protocol = serverProt;
  15170. const secWebSocketExtensions = res.headers["sec-websocket-extensions"];
  15171. if (secWebSocketExtensions !== void 0) {
  15172. if (!perMessageDeflate) {
  15173. abortHandshake(websocket, socket, "Server sent a Sec-WebSocket-Extensions header but no extension was requested");
  15174. return;
  15175. }
  15176. let extensions;
  15177. try {
  15178. extensions = parse(secWebSocketExtensions);
  15179. } catch (err) {
  15180. abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Extensions header");
  15181. return;
  15182. }
  15183. const extensionNames = Object.keys(extensions);
  15184. if (extensionNames.length !== 1 || extensionNames[0] !== PerMessageDeflate.extensionName) {
  15185. abortHandshake(websocket, socket, "Server indicated an extension that was not requested");
  15186. return;
  15187. }
  15188. try {
  15189. perMessageDeflate.accept(extensions[PerMessageDeflate.extensionName]);
  15190. } catch (err) {
  15191. abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Extensions header");
  15192. return;
  15193. }
  15194. websocket._extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
  15195. }
  15196. websocket.setSocket(socket, head, {
  15197. allowSynchronousEvents: opts.allowSynchronousEvents,
  15198. generateMask: opts.generateMask,
  15199. maxPayload: opts.maxPayload,
  15200. skipUTF8Validation: opts.skipUTF8Validation
  15201. });
  15202. });
  15203. if (opts.finishRequest) opts.finishRequest(req, websocket);
  15204. else req.end();
  15205. }
  15206. /**
  15207. * Emit the `'error'` and `'close'` events.
  15208. *
  15209. * @param {WebSocket} websocket The WebSocket instance
  15210. * @param {Error} The error to emit
  15211. * @private
  15212. */
  15213. function emitErrorAndClose(websocket, err) {
  15214. websocket._readyState = WebSocket.CLOSING;
  15215. websocket._errorEmitted = true;
  15216. websocket.emit("error", err);
  15217. websocket.emitClose();
  15218. }
  15219. /**
  15220. * Create a `net.Socket` and initiate a connection.
  15221. *
  15222. * @param {Object} options Connection options
  15223. * @return {net.Socket} The newly created socket used to start the connection
  15224. * @private
  15225. */
  15226. function netConnect(options) {
  15227. options.path = options.socketPath;
  15228. return net$1.connect(options);
  15229. }
  15230. /**
  15231. * Create a `tls.TLSSocket` and initiate a connection.
  15232. *
  15233. * @param {Object} options Connection options
  15234. * @return {tls.TLSSocket} The newly created socket used to start the connection
  15235. * @private
  15236. */
  15237. function tlsConnect(options) {
  15238. options.path = void 0;
  15239. if (!options.servername && options.servername !== "") options.servername = net$1.isIP(options.host) ? "" : options.host;
  15240. return tls.connect(options);
  15241. }
  15242. /**
  15243. * Abort the handshake and emit an error.
  15244. *
  15245. * @param {WebSocket} websocket The WebSocket instance
  15246. * @param {(http.ClientRequest|net.Socket|tls.Socket)} stream The request to
  15247. * abort or the socket to destroy
  15248. * @param {String} message The error message
  15249. * @private
  15250. */
  15251. function abortHandshake(websocket, stream, message) {
  15252. websocket._readyState = WebSocket.CLOSING;
  15253. const err = new Error(message);
  15254. Error.captureStackTrace(err, abortHandshake);
  15255. if (stream.setHeader) {
  15256. stream[kAborted] = true;
  15257. stream.abort();
  15258. if (stream.socket && !stream.socket.destroyed) stream.socket.destroy();
  15259. process.nextTick(emitErrorAndClose, websocket, err);
  15260. } else {
  15261. stream.destroy(err);
  15262. stream.once("error", websocket.emit.bind(websocket, "error"));
  15263. stream.once("close", websocket.emitClose.bind(websocket));
  15264. }
  15265. }
  15266. /**
  15267. * Handle cases where the `ping()`, `pong()`, or `send()` methods are called
  15268. * when the `readyState` attribute is `CLOSING` or `CLOSED`.
  15269. *
  15270. * @param {WebSocket} websocket The WebSocket instance
  15271. * @param {*} [data] The data to send
  15272. * @param {Function} [cb] Callback
  15273. * @private
  15274. */
  15275. function sendAfterClose(websocket, data, cb) {
  15276. if (data) {
  15277. const length = isBlob(data) ? data.size : toBuffer(data).length;
  15278. if (websocket._socket) websocket._sender._bufferedBytes += length;
  15279. else websocket._bufferedAmount += length;
  15280. }
  15281. if (cb) {
  15282. const err = /* @__PURE__ */ new Error(`WebSocket is not open: readyState ${websocket.readyState} (${readyStates[websocket.readyState]})`);
  15283. process.nextTick(cb, err);
  15284. }
  15285. }
  15286. /**
  15287. * The listener of the `Receiver` `'conclude'` event.
  15288. *
  15289. * @param {Number} code The status code
  15290. * @param {Buffer} reason The reason for closing
  15291. * @private
  15292. */
  15293. function receiverOnConclude(code, reason) {
  15294. const websocket = this[kWebSocket];
  15295. websocket._closeFrameReceived = true;
  15296. websocket._closeMessage = reason;
  15297. websocket._closeCode = code;
  15298. if (websocket._socket[kWebSocket] === void 0) return;
  15299. websocket._socket.removeListener("data", socketOnData);
  15300. process.nextTick(resume, websocket._socket);
  15301. if (code === 1005) websocket.close();
  15302. else websocket.close(code, reason);
  15303. }
  15304. /**
  15305. * The listener of the `Receiver` `'drain'` event.
  15306. *
  15307. * @private
  15308. */
  15309. function receiverOnDrain() {
  15310. const websocket = this[kWebSocket];
  15311. if (!websocket.isPaused) websocket._socket.resume();
  15312. }
  15313. /**
  15314. * The listener of the `Receiver` `'error'` event.
  15315. *
  15316. * @param {(RangeError|Error)} err The emitted error
  15317. * @private
  15318. */
  15319. function receiverOnError(err) {
  15320. const websocket = this[kWebSocket];
  15321. if (websocket._socket[kWebSocket] !== void 0) {
  15322. websocket._socket.removeListener("data", socketOnData);
  15323. process.nextTick(resume, websocket._socket);
  15324. websocket.close(err[kStatusCode]);
  15325. }
  15326. if (!websocket._errorEmitted) {
  15327. websocket._errorEmitted = true;
  15328. websocket.emit("error", err);
  15329. }
  15330. }
  15331. /**
  15332. * The listener of the `Receiver` `'finish'` event.
  15333. *
  15334. * @private
  15335. */
  15336. function receiverOnFinish() {
  15337. this[kWebSocket].emitClose();
  15338. }
  15339. /**
  15340. * The listener of the `Receiver` `'message'` event.
  15341. *
  15342. * @param {Buffer|ArrayBuffer|Buffer[])} data The message
  15343. * @param {Boolean} isBinary Specifies whether the message is binary or not
  15344. * @private
  15345. */
  15346. function receiverOnMessage(data, isBinary) {
  15347. this[kWebSocket].emit("message", data, isBinary);
  15348. }
  15349. /**
  15350. * The listener of the `Receiver` `'ping'` event.
  15351. *
  15352. * @param {Buffer} data The data included in the ping frame
  15353. * @private
  15354. */
  15355. function receiverOnPing(data) {
  15356. const websocket = this[kWebSocket];
  15357. if (websocket._autoPong) websocket.pong(data, !this._isServer, NOOP);
  15358. websocket.emit("ping", data);
  15359. }
  15360. /**
  15361. * The listener of the `Receiver` `'pong'` event.
  15362. *
  15363. * @param {Buffer} data The data included in the pong frame
  15364. * @private
  15365. */
  15366. function receiverOnPong(data) {
  15367. this[kWebSocket].emit("pong", data);
  15368. }
  15369. /**
  15370. * Resume a readable stream
  15371. *
  15372. * @param {Readable} stream The readable stream
  15373. * @private
  15374. */
  15375. function resume(stream) {
  15376. stream.resume();
  15377. }
  15378. /**
  15379. * The `Sender` error event handler.
  15380. *
  15381. * @param {Error} The error
  15382. * @private
  15383. */
  15384. function senderOnError(err) {
  15385. const websocket = this[kWebSocket];
  15386. if (websocket.readyState === WebSocket.CLOSED) return;
  15387. if (websocket.readyState === WebSocket.OPEN) {
  15388. websocket._readyState = WebSocket.CLOSING;
  15389. setCloseTimer(websocket);
  15390. }
  15391. this._socket.end();
  15392. if (!websocket._errorEmitted) {
  15393. websocket._errorEmitted = true;
  15394. websocket.emit("error", err);
  15395. }
  15396. }
  15397. /**
  15398. * Set a timer to destroy the underlying raw socket of a WebSocket.
  15399. *
  15400. * @param {WebSocket} websocket The WebSocket instance
  15401. * @private
  15402. */
  15403. function setCloseTimer(websocket) {
  15404. websocket._closeTimer = setTimeout(websocket._socket.destroy.bind(websocket._socket), websocket._closeTimeout);
  15405. }
  15406. /**
  15407. * The listener of the socket `'close'` event.
  15408. *
  15409. * @private
  15410. */
  15411. function socketOnClose() {
  15412. const websocket = this[kWebSocket];
  15413. this.removeListener("close", socketOnClose);
  15414. this.removeListener("data", socketOnData);
  15415. this.removeListener("end", socketOnEnd);
  15416. websocket._readyState = WebSocket.CLOSING;
  15417. if (!this._readableState.endEmitted && !websocket._closeFrameReceived && !websocket._receiver._writableState.errorEmitted && this._readableState.length !== 0) {
  15418. const chunk = this.read(this._readableState.length);
  15419. websocket._receiver.write(chunk);
  15420. }
  15421. websocket._receiver.end();
  15422. this[kWebSocket] = void 0;
  15423. clearTimeout(websocket._closeTimer);
  15424. if (websocket._receiver._writableState.finished || websocket._receiver._writableState.errorEmitted) websocket.emitClose();
  15425. else {
  15426. websocket._receiver.on("error", receiverOnFinish);
  15427. websocket._receiver.on("finish", receiverOnFinish);
  15428. }
  15429. }
  15430. /**
  15431. * The listener of the socket `'data'` event.
  15432. *
  15433. * @param {Buffer} chunk A chunk of data
  15434. * @private
  15435. */
  15436. function socketOnData(chunk) {
  15437. if (!this[kWebSocket]._receiver.write(chunk)) this.pause();
  15438. }
  15439. /**
  15440. * The listener of the socket `'end'` event.
  15441. *
  15442. * @private
  15443. */
  15444. function socketOnEnd() {
  15445. const websocket = this[kWebSocket];
  15446. websocket._readyState = WebSocket.CLOSING;
  15447. websocket._receiver.end();
  15448. this.end();
  15449. }
  15450. /**
  15451. * The listener of the socket `'error'` event.
  15452. *
  15453. * @private
  15454. */
  15455. function socketOnError() {
  15456. const websocket = this[kWebSocket];
  15457. this.removeListener("error", socketOnError);
  15458. this.on("error", NOOP);
  15459. if (websocket) {
  15460. websocket._readyState = WebSocket.CLOSING;
  15461. this.destroy();
  15462. }
  15463. }
  15464. }));
  15465. //#endregion
  15466. //#region ../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/stream.js
  15467. var require_stream = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  15468. require_websocket();
  15469. const { Duplex: Duplex$1 } = __require("stream");
  15470. /**
  15471. * Emits the `'close'` event on a stream.
  15472. *
  15473. * @param {Duplex} stream The stream.
  15474. * @private
  15475. */
  15476. function emitClose(stream) {
  15477. stream.emit("close");
  15478. }
  15479. /**
  15480. * The listener of the `'end'` event.
  15481. *
  15482. * @private
  15483. */
  15484. function duplexOnEnd() {
  15485. if (!this.destroyed && this._writableState.finished) this.destroy();
  15486. }
  15487. /**
  15488. * The listener of the `'error'` event.
  15489. *
  15490. * @param {Error} err The error
  15491. * @private
  15492. */
  15493. function duplexOnError(err) {
  15494. this.removeListener("error", duplexOnError);
  15495. this.destroy();
  15496. if (this.listenerCount("error") === 0) this.emit("error", err);
  15497. }
  15498. /**
  15499. * Wraps a `WebSocket` in a duplex stream.
  15500. *
  15501. * @param {WebSocket} ws The `WebSocket` to wrap
  15502. * @param {Object} [options] The options for the `Duplex` constructor
  15503. * @return {Duplex} The duplex stream
  15504. * @public
  15505. */
  15506. function createWebSocketStream(ws, options) {
  15507. let terminateOnDestroy = true;
  15508. const duplex = new Duplex$1({
  15509. ...options,
  15510. autoDestroy: false,
  15511. emitClose: false,
  15512. objectMode: false,
  15513. writableObjectMode: false
  15514. });
  15515. ws.on("message", function message(msg, isBinary) {
  15516. const data = !isBinary && duplex._readableState.objectMode ? msg.toString() : msg;
  15517. if (!duplex.push(data)) ws.pause();
  15518. });
  15519. ws.once("error", function error(err) {
  15520. if (duplex.destroyed) return;
  15521. terminateOnDestroy = false;
  15522. duplex.destroy(err);
  15523. });
  15524. ws.once("close", function close() {
  15525. if (duplex.destroyed) return;
  15526. duplex.push(null);
  15527. });
  15528. duplex._destroy = function(err, callback) {
  15529. if (ws.readyState === ws.CLOSED) {
  15530. callback(err);
  15531. process.nextTick(emitClose, duplex);
  15532. return;
  15533. }
  15534. let called = false;
  15535. ws.once("error", function error(err) {
  15536. called = true;
  15537. callback(err);
  15538. });
  15539. ws.once("close", function close() {
  15540. if (!called) callback(err);
  15541. process.nextTick(emitClose, duplex);
  15542. });
  15543. if (terminateOnDestroy) ws.terminate();
  15544. };
  15545. duplex._final = function(callback) {
  15546. if (ws.readyState === ws.CONNECTING) {
  15547. ws.once("open", function open() {
  15548. duplex._final(callback);
  15549. });
  15550. return;
  15551. }
  15552. if (ws._socket === null) return;
  15553. if (ws._socket._writableState.finished) {
  15554. callback();
  15555. if (duplex._readableState.endEmitted) duplex.destroy();
  15556. } else {
  15557. ws._socket.once("finish", function finish() {
  15558. callback();
  15559. });
  15560. ws.close();
  15561. }
  15562. };
  15563. duplex._read = function() {
  15564. if (ws.isPaused) ws.resume();
  15565. };
  15566. duplex._write = function(chunk, encoding, callback) {
  15567. if (ws.readyState === ws.CONNECTING) {
  15568. ws.once("open", function open() {
  15569. duplex._write(chunk, encoding, callback);
  15570. });
  15571. return;
  15572. }
  15573. ws.send(chunk, callback);
  15574. };
  15575. duplex.on("end", duplexOnEnd);
  15576. duplex.on("error", duplexOnError);
  15577. return duplex;
  15578. }
  15579. module.exports = createWebSocketStream;
  15580. }));
  15581. //#endregion
  15582. //#region ../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/subprotocol.js
  15583. var require_subprotocol = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  15584. const { tokenChars } = require_validation();
  15585. /**
  15586. * Parses the `Sec-WebSocket-Protocol` header into a set of subprotocol names.
  15587. *
  15588. * @param {String} header The field value of the header
  15589. * @return {Set} The subprotocol names
  15590. * @public
  15591. */
  15592. function parse(header) {
  15593. const protocols = /* @__PURE__ */ new Set();
  15594. let start = -1;
  15595. let end = -1;
  15596. let i = 0;
  15597. for (; i < header.length; i++) {
  15598. const code = header.charCodeAt(i);
  15599. if (end === -1 && tokenChars[code] === 1) {
  15600. if (start === -1) start = i;
  15601. } else if (i !== 0 && (code === 32 || code === 9)) {
  15602. if (end === -1 && start !== -1) end = i;
  15603. } else if (code === 44) {
  15604. if (start === -1) throw new SyntaxError(`Unexpected character at index ${i}`);
  15605. if (end === -1) end = i;
  15606. const protocol = header.slice(start, end);
  15607. if (protocols.has(protocol)) throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`);
  15608. protocols.add(protocol);
  15609. start = end = -1;
  15610. } else throw new SyntaxError(`Unexpected character at index ${i}`);
  15611. }
  15612. if (start === -1 || end !== -1) throw new SyntaxError("Unexpected end of input");
  15613. const protocol = header.slice(start, i);
  15614. if (protocols.has(protocol)) throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`);
  15615. protocols.add(protocol);
  15616. return protocols;
  15617. }
  15618. module.exports = { parse };
  15619. }));
  15620. //#endregion
  15621. //#region ../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/websocket-server.js
  15622. var require_websocket_server = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  15623. const EventEmitter$1 = __require("events");
  15624. const http$4 = __require("http");
  15625. const { Duplex } = __require("stream");
  15626. const { createHash } = __require("crypto");
  15627. const extension = require_extension();
  15628. const PerMessageDeflate = require_permessage_deflate();
  15629. const subprotocol = require_subprotocol();
  15630. const WebSocket = require_websocket();
  15631. const { CLOSE_TIMEOUT, GUID, kWebSocket } = require_constants();
  15632. const keyRegex = /^[+/0-9A-Za-z]{22}==$/;
  15633. const RUNNING = 0;
  15634. const CLOSING = 1;
  15635. const CLOSED = 2;
  15636. /**
  15637. * Class representing a WebSocket server.
  15638. *
  15639. * @extends EventEmitter
  15640. */
  15641. var WebSocketServer = class extends EventEmitter$1 {
  15642. /**
  15643. * Create a `WebSocketServer` instance.
  15644. *
  15645. * @param {Object} options Configuration options
  15646. * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether
  15647. * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
  15648. * multiple times in the same tick
  15649. * @param {Boolean} [options.autoPong=true] Specifies whether or not to
  15650. * automatically send a pong in response to a ping
  15651. * @param {Number} [options.backlog=511] The maximum length of the queue of
  15652. * pending connections
  15653. * @param {Boolean} [options.clientTracking=true] Specifies whether or not to
  15654. * track clients
  15655. * @param {Number} [options.closeTimeout=30000] Duration in milliseconds to
  15656. * wait for the closing handshake to finish after `websocket.close()` is
  15657. * called
  15658. * @param {Function} [options.handleProtocols] A hook to handle protocols
  15659. * @param {String} [options.host] The hostname where to bind the server
  15660. * @param {Number} [options.maxPayload=104857600] The maximum allowed message
  15661. * size
  15662. * @param {Boolean} [options.noServer=false] Enable no server mode
  15663. * @param {String} [options.path] Accept only connections matching this path
  15664. * @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable
  15665. * permessage-deflate
  15666. * @param {Number} [options.port] The port where to bind the server
  15667. * @param {(http.Server|https.Server)} [options.server] A pre-created HTTP/S
  15668. * server to use
  15669. * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
  15670. * not to skip UTF-8 validation for text and close messages
  15671. * @param {Function} [options.verifyClient] A hook to reject connections
  15672. * @param {Function} [options.WebSocket=WebSocket] Specifies the `WebSocket`
  15673. * class to use. It must be the `WebSocket` class or class that extends it
  15674. * @param {Function} [callback] A listener for the `listening` event
  15675. */
  15676. constructor(options, callback) {
  15677. super();
  15678. options = {
  15679. allowSynchronousEvents: true,
  15680. autoPong: true,
  15681. maxPayload: 100 * 1024 * 1024,
  15682. skipUTF8Validation: false,
  15683. perMessageDeflate: false,
  15684. handleProtocols: null,
  15685. clientTracking: true,
  15686. closeTimeout: CLOSE_TIMEOUT,
  15687. verifyClient: null,
  15688. noServer: false,
  15689. backlog: null,
  15690. server: null,
  15691. host: null,
  15692. path: null,
  15693. port: null,
  15694. WebSocket,
  15695. ...options
  15696. };
  15697. if (options.port == null && !options.server && !options.noServer || options.port != null && (options.server || options.noServer) || options.server && options.noServer) throw new TypeError("One and only one of the \"port\", \"server\", or \"noServer\" options must be specified");
  15698. if (options.port != null) {
  15699. this._server = http$4.createServer((req, res) => {
  15700. const body = http$4.STATUS_CODES[426];
  15701. res.writeHead(426, {
  15702. "Content-Length": body.length,
  15703. "Content-Type": "text/plain"
  15704. });
  15705. res.end(body);
  15706. });
  15707. this._server.listen(options.port, options.host, options.backlog, callback);
  15708. } else if (options.server) this._server = options.server;
  15709. if (this._server) {
  15710. const emitConnection = this.emit.bind(this, "connection");
  15711. this._removeListeners = addListeners(this._server, {
  15712. listening: this.emit.bind(this, "listening"),
  15713. error: this.emit.bind(this, "error"),
  15714. upgrade: (req, socket, head) => {
  15715. this.handleUpgrade(req, socket, head, emitConnection);
  15716. }
  15717. });
  15718. }
  15719. if (options.perMessageDeflate === true) options.perMessageDeflate = {};
  15720. if (options.clientTracking) {
  15721. this.clients = /* @__PURE__ */ new Set();
  15722. this._shouldEmitClose = false;
  15723. }
  15724. this.options = options;
  15725. this._state = RUNNING;
  15726. }
  15727. /**
  15728. * Returns the bound address, the address family name, and port of the server
  15729. * as reported by the operating system if listening on an IP socket.
  15730. * If the server is listening on a pipe or UNIX domain socket, the name is
  15731. * returned as a string.
  15732. *
  15733. * @return {(Object|String|null)} The address of the server
  15734. * @public
  15735. */
  15736. address() {
  15737. if (this.options.noServer) throw new Error("The server is operating in \"noServer\" mode");
  15738. if (!this._server) return null;
  15739. return this._server.address();
  15740. }
  15741. /**
  15742. * Stop the server from accepting new connections and emit the `'close'` event
  15743. * when all existing connections are closed.
  15744. *
  15745. * @param {Function} [cb] A one-time listener for the `'close'` event
  15746. * @public
  15747. */
  15748. close(cb) {
  15749. if (this._state === CLOSED) {
  15750. if (cb) this.once("close", () => {
  15751. cb(/* @__PURE__ */ new Error("The server is not running"));
  15752. });
  15753. process.nextTick(emitClose, this);
  15754. return;
  15755. }
  15756. if (cb) this.once("close", cb);
  15757. if (this._state === CLOSING) return;
  15758. this._state = CLOSING;
  15759. if (this.options.noServer || this.options.server) {
  15760. if (this._server) {
  15761. this._removeListeners();
  15762. this._removeListeners = this._server = null;
  15763. }
  15764. if (this.clients) if (!this.clients.size) process.nextTick(emitClose, this);
  15765. else this._shouldEmitClose = true;
  15766. else process.nextTick(emitClose, this);
  15767. } else {
  15768. const server = this._server;
  15769. this._removeListeners();
  15770. this._removeListeners = this._server = null;
  15771. server.close(() => {
  15772. emitClose(this);
  15773. });
  15774. }
  15775. }
  15776. /**
  15777. * See if a given request should be handled by this server instance.
  15778. *
  15779. * @param {http.IncomingMessage} req Request object to inspect
  15780. * @return {Boolean} `true` if the request is valid, else `false`
  15781. * @public
  15782. */
  15783. shouldHandle(req) {
  15784. if (this.options.path) {
  15785. const index = req.url.indexOf("?");
  15786. if ((index !== -1 ? req.url.slice(0, index) : req.url) !== this.options.path) return false;
  15787. }
  15788. return true;
  15789. }
  15790. /**
  15791. * Handle a HTTP Upgrade request.
  15792. *
  15793. * @param {http.IncomingMessage} req The request object
  15794. * @param {Duplex} socket The network socket between the server and client
  15795. * @param {Buffer} head The first packet of the upgraded stream
  15796. * @param {Function} cb Callback
  15797. * @public
  15798. */
  15799. handleUpgrade(req, socket, head, cb) {
  15800. socket.on("error", socketOnError);
  15801. const key = req.headers["sec-websocket-key"];
  15802. const upgrade = req.headers.upgrade;
  15803. const version = +req.headers["sec-websocket-version"];
  15804. if (req.method !== "GET") {
  15805. abortHandshakeOrEmitwsClientError(this, req, socket, 405, "Invalid HTTP method");
  15806. return;
  15807. }
  15808. if (upgrade === void 0 || upgrade.toLowerCase() !== "websocket") {
  15809. abortHandshakeOrEmitwsClientError(this, req, socket, 400, "Invalid Upgrade header");
  15810. return;
  15811. }
  15812. if (key === void 0 || !keyRegex.test(key)) {
  15813. abortHandshakeOrEmitwsClientError(this, req, socket, 400, "Missing or invalid Sec-WebSocket-Key header");
  15814. return;
  15815. }
  15816. if (version !== 13 && version !== 8) {
  15817. abortHandshakeOrEmitwsClientError(this, req, socket, 400, "Missing or invalid Sec-WebSocket-Version header", { "Sec-WebSocket-Version": "13, 8" });
  15818. return;
  15819. }
  15820. if (!this.shouldHandle(req)) {
  15821. abortHandshake(socket, 400);
  15822. return;
  15823. }
  15824. const secWebSocketProtocol = req.headers["sec-websocket-protocol"];
  15825. let protocols = /* @__PURE__ */ new Set();
  15826. if (secWebSocketProtocol !== void 0) try {
  15827. protocols = subprotocol.parse(secWebSocketProtocol);
  15828. } catch (err) {
  15829. abortHandshakeOrEmitwsClientError(this, req, socket, 400, "Invalid Sec-WebSocket-Protocol header");
  15830. return;
  15831. }
  15832. const secWebSocketExtensions = req.headers["sec-websocket-extensions"];
  15833. const extensions = {};
  15834. if (this.options.perMessageDeflate && secWebSocketExtensions !== void 0) {
  15835. const perMessageDeflate = new PerMessageDeflate({
  15836. ...this.options.perMessageDeflate,
  15837. isServer: true,
  15838. maxPayload: this.options.maxPayload
  15839. });
  15840. try {
  15841. const offers = extension.parse(secWebSocketExtensions);
  15842. if (offers[PerMessageDeflate.extensionName]) {
  15843. perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]);
  15844. extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
  15845. }
  15846. } catch (err) {
  15847. abortHandshakeOrEmitwsClientError(this, req, socket, 400, "Invalid or unacceptable Sec-WebSocket-Extensions header");
  15848. return;
  15849. }
  15850. }
  15851. if (this.options.verifyClient) {
  15852. const info = {
  15853. origin: req.headers[`${version === 8 ? "sec-websocket-origin" : "origin"}`],
  15854. secure: !!(req.socket.authorized || req.socket.encrypted),
  15855. req
  15856. };
  15857. if (this.options.verifyClient.length === 2) {
  15858. this.options.verifyClient(info, (verified, code, message, headers) => {
  15859. if (!verified) return abortHandshake(socket, code || 401, message, headers);
  15860. this.completeUpgrade(extensions, key, protocols, req, socket, head, cb);
  15861. });
  15862. return;
  15863. }
  15864. if (!this.options.verifyClient(info)) return abortHandshake(socket, 401);
  15865. }
  15866. this.completeUpgrade(extensions, key, protocols, req, socket, head, cb);
  15867. }
  15868. /**
  15869. * Upgrade the connection to WebSocket.
  15870. *
  15871. * @param {Object} extensions The accepted extensions
  15872. * @param {String} key The value of the `Sec-WebSocket-Key` header
  15873. * @param {Set} protocols The subprotocols
  15874. * @param {http.IncomingMessage} req The request object
  15875. * @param {Duplex} socket The network socket between the server and client
  15876. * @param {Buffer} head The first packet of the upgraded stream
  15877. * @param {Function} cb Callback
  15878. * @throws {Error} If called more than once with the same socket
  15879. * @private
  15880. */
  15881. completeUpgrade(extensions, key, protocols, req, socket, head, cb) {
  15882. if (!socket.readable || !socket.writable) return socket.destroy();
  15883. if (socket[kWebSocket]) throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");
  15884. if (this._state > RUNNING) return abortHandshake(socket, 503);
  15885. const headers = [
  15886. "HTTP/1.1 101 Switching Protocols",
  15887. "Upgrade: websocket",
  15888. "Connection: Upgrade",
  15889. `Sec-WebSocket-Accept: ${createHash("sha1").update(key + GUID).digest("base64")}`
  15890. ];
  15891. const ws = new this.options.WebSocket(null, void 0, this.options);
  15892. if (protocols.size) {
  15893. const protocol = this.options.handleProtocols ? this.options.handleProtocols(protocols, req) : protocols.values().next().value;
  15894. if (protocol) {
  15895. headers.push(`Sec-WebSocket-Protocol: ${protocol}`);
  15896. ws._protocol = protocol;
  15897. }
  15898. }
  15899. if (extensions[PerMessageDeflate.extensionName]) {
  15900. const params = extensions[PerMessageDeflate.extensionName].params;
  15901. const value = extension.format({ [PerMessageDeflate.extensionName]: [params] });
  15902. headers.push(`Sec-WebSocket-Extensions: ${value}`);
  15903. ws._extensions = extensions;
  15904. }
  15905. this.emit("headers", headers, req);
  15906. socket.write(headers.concat("\r\n").join("\r\n"));
  15907. socket.removeListener("error", socketOnError);
  15908. ws.setSocket(socket, head, {
  15909. allowSynchronousEvents: this.options.allowSynchronousEvents,
  15910. maxPayload: this.options.maxPayload,
  15911. skipUTF8Validation: this.options.skipUTF8Validation
  15912. });
  15913. if (this.clients) {
  15914. this.clients.add(ws);
  15915. ws.on("close", () => {
  15916. this.clients.delete(ws);
  15917. if (this._shouldEmitClose && !this.clients.size) process.nextTick(emitClose, this);
  15918. });
  15919. }
  15920. cb(ws, req);
  15921. }
  15922. };
  15923. module.exports = WebSocketServer;
  15924. /**
  15925. * Add event listeners on an `EventEmitter` using a map of <event, listener>
  15926. * pairs.
  15927. *
  15928. * @param {EventEmitter} server The event emitter
  15929. * @param {Object.<String, Function>} map The listeners to add
  15930. * @return {Function} A function that will remove the added listeners when
  15931. * called
  15932. * @private
  15933. */
  15934. function addListeners(server, map) {
  15935. for (const event of Object.keys(map)) server.on(event, map[event]);
  15936. return function removeListeners() {
  15937. for (const event of Object.keys(map)) server.removeListener(event, map[event]);
  15938. };
  15939. }
  15940. /**
  15941. * Emit a `'close'` event on an `EventEmitter`.
  15942. *
  15943. * @param {EventEmitter} server The event emitter
  15944. * @private
  15945. */
  15946. function emitClose(server) {
  15947. server._state = CLOSED;
  15948. server.emit("close");
  15949. }
  15950. /**
  15951. * Handle socket errors.
  15952. *
  15953. * @private
  15954. */
  15955. function socketOnError() {
  15956. this.destroy();
  15957. }
  15958. /**
  15959. * Close the connection when preconditions are not fulfilled.
  15960. *
  15961. * @param {Duplex} socket The socket of the upgrade request
  15962. * @param {Number} code The HTTP response status code
  15963. * @param {String} [message] The HTTP response body
  15964. * @param {Object} [headers] Additional HTTP response headers
  15965. * @private
  15966. */
  15967. function abortHandshake(socket, code, message, headers) {
  15968. message = message || http$4.STATUS_CODES[code];
  15969. headers = {
  15970. Connection: "close",
  15971. "Content-Type": "text/html",
  15972. "Content-Length": Buffer.byteLength(message),
  15973. ...headers
  15974. };
  15975. socket.once("finish", socket.destroy);
  15976. socket.end(`HTTP/1.1 ${code} ${http$4.STATUS_CODES[code]}\r\n` + Object.keys(headers).map((h) => `${h}: ${headers[h]}`).join("\r\n") + "\r\n\r\n" + message);
  15977. }
  15978. /**
  15979. * Emit a `'wsClientError'` event on a `WebSocketServer` if there is at least
  15980. * one listener for it, otherwise call `abortHandshake()`.
  15981. *
  15982. * @param {WebSocketServer} server The WebSocket server
  15983. * @param {http.IncomingMessage} req The request object
  15984. * @param {Duplex} socket The socket of the upgrade request
  15985. * @param {Number} code The HTTP response status code
  15986. * @param {String} message The HTTP response body
  15987. * @param {Object} [headers] The HTTP response headers
  15988. * @private
  15989. */
  15990. function abortHandshakeOrEmitwsClientError(server, req, socket, code, message, headers) {
  15991. if (server.listenerCount("wsClientError")) {
  15992. const err = new Error(message);
  15993. Error.captureStackTrace(err, abortHandshakeOrEmitwsClientError);
  15994. server.emit("wsClientError", err, socket, req);
  15995. } else abortHandshake(socket, code, message, headers);
  15996. }
  15997. }));
  15998. require_stream();
  15999. require_extension();
  16000. require_permessage_deflate();
  16001. require_receiver();
  16002. require_sender();
  16003. require_subprotocol();
  16004. require_websocket();
  16005. var import_websocket_server = /* @__PURE__ */ __toESM(require_websocket_server(), 1);
  16006. //#endregion
  16007. //#region ../../node_modules/.pnpm/host-validation-middleware@0.1.4/node_modules/host-validation-middleware/dist/index.js
  16008. /**
  16009. * This function assumes that the input is not malformed.
  16010. * This is because we only care about browser requests.
  16011. * Non-browser clients can send any value they want anyway.
  16012. */
  16013. function extractHostNameFromHostHeader(hostHeader) {
  16014. const trimmedHost = hostHeader.trim();
  16015. if (trimmedHost[0] === "[") {
  16016. const endIpv6 = trimmedHost.indexOf("]");
  16017. if (endIpv6 < 0) return { type: "invalid" };
  16018. return net.isIP(trimmedHost.slice(1, endIpv6)) === 6 ? { type: "ipv6" } : { type: "invalid" };
  16019. }
  16020. const colonPos = trimmedHost.indexOf(":");
  16021. const hostname = colonPos === -1 ? trimmedHost : trimmedHost.slice(0, colonPos);
  16022. if (net.isIP(hostname) === 4) return { type: "ipv4" };
  16023. return {
  16024. type: "hostname",
  16025. value: hostname
  16026. };
  16027. }
  16028. const isFileOrExtensionProtocolRE = /^(?:file|.+-extension):/i;
  16029. function isHostAllowedInternal(hostHeader, allowedHosts) {
  16030. if (isFileOrExtensionProtocolRE.test(hostHeader)) return true;
  16031. const extracted = extractHostNameFromHostHeader(hostHeader);
  16032. if (extracted.type === "invalid") return false;
  16033. if (extracted.type === "ipv4" || extracted.type === "ipv6") return true;
  16034. const hostname = extracted.value;
  16035. if (hostname === "localhost" || hostname.endsWith(".localhost")) return true;
  16036. for (const allowedHost of allowedHosts) {
  16037. if (allowedHost === hostname) return true;
  16038. if (allowedHost[0] === "." && (allowedHost.slice(1) === hostname || hostname.endsWith(allowedHost))) return true;
  16039. }
  16040. return false;
  16041. }
  16042. const cache = /* @__PURE__ */ new WeakMap();
  16043. /**
  16044. * Check if the host contained in the host header is allowed.
  16045. *
  16046. * This function will cache the result if the `allowedHosts` array is frozen.
  16047. *
  16048. * @param hostHeader - The value of host header. See [RFC 9110 7.2](https://datatracker.ietf.org/doc/html/rfc9110#name-host-and-authority).
  16049. * @param allowedHosts - The allowed host patterns. See the README for more details.
  16050. */
  16051. function isHostAllowed(hostHeader, allowedHosts) {
  16052. if (hostHeader === void 0) return true;
  16053. let cachedAllowedHosts;
  16054. if (Object.isFrozen(allowedHosts)) {
  16055. if (!cache.has(allowedHosts)) cache.set(allowedHosts, /* @__PURE__ */ new Set());
  16056. cachedAllowedHosts = cache.get(allowedHosts);
  16057. if (cachedAllowedHosts.has(hostHeader)) return true;
  16058. }
  16059. const result = isHostAllowedInternal(hostHeader, allowedHosts);
  16060. if (cachedAllowedHosts && result) cachedAllowedHosts.add(hostHeader);
  16061. return result;
  16062. }
  16063. /**
  16064. * Middleware to validate the host header of incoming requests.
  16065. *
  16066. * If the host header is not in the allowed hosts list, a 403 Forbidden response
  16067. * is sent.
  16068. */
  16069. function hostValidationMiddleware$1(options) {
  16070. return async function hostValidationMiddleware(req, res, next) {
  16071. const hostHeader = req.headers.host;
  16072. if (!isHostAllowed(hostHeader, options.allowedHosts)) {
  16073. const hostname = hostHeader?.replace(/:\d+$/, "") ?? "";
  16074. const errorMessage = options.generateErrorMessage?.(hostname) ?? generateDefaultErrorMessage(hostname);
  16075. res.writeHead(403, { "Content-Type": options.errorResponseContentType ?? "text/plain" });
  16076. res.end(errorMessage);
  16077. return;
  16078. }
  16079. next();
  16080. };
  16081. }
  16082. function generateDefaultErrorMessage(hostname) {
  16083. return `Blocked request. This host (${JSON.stringify(hostname)}) is not allowed.`;
  16084. }
  16085. //#endregion
  16086. //#region src/node/server/ws.ts
  16087. const WebSocketServerRaw = process.versions.bun ? import.meta.require("ws").WebSocketServer : import_websocket_server.default;
  16088. const isWebSocketServer = Symbol("isWebSocketServer");
  16089. const wsServerEvents = [
  16090. "connection",
  16091. "error",
  16092. "headers",
  16093. "listening",
  16094. "message"
  16095. ];
  16096. function noop$1() {}
  16097. function hasValidToken(config, url) {
  16098. const token = url.searchParams.get("token");
  16099. if (!token) return false;
  16100. try {
  16101. return crypto.timingSafeEqual(Buffer.from(token), Buffer.from(config.webSocketToken));
  16102. } catch {}
  16103. return false;
  16104. }
  16105. function createWebSocketServer(server, config, httpsOptions) {
  16106. if (config.server.ws === false) return {
  16107. [isWebSocketServer]: true,
  16108. get clients() {
  16109. return /* @__PURE__ */ new Set();
  16110. },
  16111. async close() {},
  16112. on: noop$1,
  16113. off: noop$1,
  16114. setInvokeHandler: noop$1,
  16115. handleInvoke: async () => ({ error: {
  16116. name: "TransportError",
  16117. message: "handleInvoke not implemented",
  16118. stack: (/* @__PURE__ */ new Error()).stack
  16119. } }),
  16120. listen: noop$1,
  16121. send: noop$1
  16122. };
  16123. let wsHttpServer = void 0;
  16124. const hmr = isObject$1(config.server.hmr) && config.server.hmr;
  16125. const hmrServer = hmr && hmr.server;
  16126. const hmrPort = hmr && hmr.port;
  16127. const wsServer = hmrServer || (!hmrPort || hmrPort === config.server.port) && server;
  16128. let hmrServerWsListener;
  16129. const customListeners = /* @__PURE__ */ new Map();
  16130. const clientsMap = /* @__PURE__ */ new WeakMap();
  16131. const port = hmrPort || 24678;
  16132. const host = hmr && hmr.host || void 0;
  16133. const allowedHosts = config.server.allowedHosts === true ? config.server.allowedHosts : Object.freeze([...config.server.allowedHosts]);
  16134. const shouldHandle = (req) => {
  16135. if (req.headers["sec-websocket-protocol"] === "vite-ping") return true;
  16136. if (allowedHosts !== true && !isHostAllowed(req.headers.host, allowedHosts)) return false;
  16137. if (config.legacy?.skipWebSocketTokenCheck) return true;
  16138. if (req.headers.origin) return hasValidToken(config, new URL(`http://example.com${req.url}`));
  16139. return true;
  16140. };
  16141. const handleUpgrade = (req, socket, head, isPing) => {
  16142. wss.handleUpgrade(req, socket, head, (ws) => {
  16143. if (isPing) {
  16144. ws.close(1e3);
  16145. return;
  16146. }
  16147. wss.emit("connection", ws, req);
  16148. });
  16149. };
  16150. const wss = new WebSocketServerRaw({ noServer: true });
  16151. wss.shouldHandle = shouldHandle;
  16152. if (wsServer) {
  16153. let hmrBase = config.base;
  16154. const hmrPath = hmr ? hmr.path : void 0;
  16155. if (hmrPath) hmrBase = path.posix.join(hmrBase, hmrPath);
  16156. hmrServerWsListener = (req, socket, head) => {
  16157. const protocol = req.headers["sec-websocket-protocol"];
  16158. const parsedUrl = new URL(`http://example.com${req.url}`);
  16159. if (["vite-hmr", "vite-ping"].includes(protocol) && parsedUrl.pathname === hmrBase) handleUpgrade(req, socket, head, protocol === "vite-ping");
  16160. };
  16161. wsServer.on("upgrade", hmrServerWsListener);
  16162. } else {
  16163. const route = ((_, res) => {
  16164. const statusCode = 426;
  16165. const body = STATUS_CODES[statusCode];
  16166. if (!body) throw new Error(`No body text found for the ${statusCode} status code`);
  16167. res.writeHead(statusCode, {
  16168. "Content-Length": body.length,
  16169. "Content-Type": "text/plain"
  16170. });
  16171. res.end(body);
  16172. });
  16173. if (httpsOptions) wsHttpServer = createServer$1(httpsOptions, route);
  16174. else wsHttpServer = createServer(route);
  16175. wsHttpServer.on("upgrade", (req, socket, head) => {
  16176. const protocol = req.headers["sec-websocket-protocol"];
  16177. if (protocol === "vite-ping" && server && !server.listening) {
  16178. req.destroy();
  16179. return;
  16180. }
  16181. handleUpgrade(req, socket, head, protocol === "vite-ping");
  16182. });
  16183. wsHttpServer.on("error", (e) => {
  16184. if (e.code === "EADDRINUSE") config.logger.error(import_picocolors.default.red(`WebSocket server error: Port ${e.port} is already in use`), { error: e });
  16185. else config.logger.error(import_picocolors.default.red(`WebSocket server error:\n${e.stack || e.message}`), { error: e });
  16186. });
  16187. }
  16188. const emitCustomEvent = (event, data, socket) => {
  16189. const listeners = customListeners.get(event);
  16190. if (!listeners?.size) return;
  16191. const client = getSocketClient(socket);
  16192. for (const listener of listeners) listener(data, client);
  16193. };
  16194. wss.on("connection", (socket) => {
  16195. socket.on("message", (raw) => {
  16196. if (!customListeners.size) return;
  16197. let parsed;
  16198. try {
  16199. parsed = JSON.parse(String(raw));
  16200. } catch {}
  16201. if (!parsed || parsed.type !== "custom" || !parsed.event) return;
  16202. emitCustomEvent(parsed.event, parsed.data, socket);
  16203. });
  16204. socket.on("error", (err) => {
  16205. config.logger.error(`${import_picocolors.default.red(`ws error:`)}\n${err.stack}`, {
  16206. timestamp: true,
  16207. error: err
  16208. });
  16209. });
  16210. socket.on("close", () => {
  16211. emitCustomEvent("vite:client:disconnect", void 0, socket);
  16212. });
  16213. emitCustomEvent("vite:client:connect", void 0, socket);
  16214. socket.send(JSON.stringify({ type: "connected" }));
  16215. if (bufferedMessage) {
  16216. socket.send(JSON.stringify(bufferedMessage));
  16217. bufferedMessage = null;
  16218. }
  16219. });
  16220. wss.on("error", (e) => {
  16221. if (e.code === "EADDRINUSE") config.logger.error(import_picocolors.default.red(`WebSocket server error: Port ${e.port} is already in use`), { error: e });
  16222. else config.logger.error(import_picocolors.default.red(`WebSocket server error:\n${e.stack || e.message}`), { error: e });
  16223. });
  16224. function getSocketClient(socket) {
  16225. if (!clientsMap.has(socket)) clientsMap.set(socket, {
  16226. send: (...args) => {
  16227. let payload;
  16228. if (typeof args[0] === "string") payload = {
  16229. type: "custom",
  16230. event: args[0],
  16231. data: args[1]
  16232. };
  16233. else payload = args[0];
  16234. socket.send(JSON.stringify(payload));
  16235. },
  16236. socket
  16237. });
  16238. return clientsMap.get(socket);
  16239. }
  16240. let bufferedMessage = null;
  16241. const normalizedHotChannel = normalizeHotChannel({
  16242. send(payload) {
  16243. if ((payload.type === "error" || payload.type === "full-reload") && !wss.clients.size) {
  16244. bufferedMessage = payload;
  16245. return;
  16246. }
  16247. const stringified = JSON.stringify(payload);
  16248. wss.clients.forEach((client) => {
  16249. if (client.readyState === 1) client.send(stringified);
  16250. });
  16251. },
  16252. on(event, fn) {
  16253. if (!customListeners.has(event)) customListeners.set(event, /* @__PURE__ */ new Set());
  16254. customListeners.get(event).add(fn);
  16255. },
  16256. off(event, fn) {
  16257. customListeners.get(event)?.delete(fn);
  16258. },
  16259. listen() {
  16260. wsHttpServer?.listen(port, host);
  16261. },
  16262. close() {
  16263. if (hmrServerWsListener && wsServer) wsServer.off("upgrade", hmrServerWsListener);
  16264. return new Promise((resolve, reject) => {
  16265. wss.clients.forEach((client) => {
  16266. client.terminate();
  16267. });
  16268. wss.close((err) => {
  16269. if (err) reject(err);
  16270. else if (wsHttpServer) wsHttpServer.close((err) => {
  16271. if (err) reject(err);
  16272. else resolve();
  16273. });
  16274. else resolve();
  16275. });
  16276. });
  16277. }
  16278. }, config.server.hmr !== false, false);
  16279. return {
  16280. ...normalizedHotChannel,
  16281. on: ((event, fn) => {
  16282. if (wsServerEvents.includes(event)) {
  16283. wss.on(event, fn);
  16284. return;
  16285. }
  16286. normalizedHotChannel.on(event, fn);
  16287. }),
  16288. off: ((event, fn) => {
  16289. if (wsServerEvents.includes(event)) {
  16290. wss.off(event, fn);
  16291. return;
  16292. }
  16293. normalizedHotChannel.off(event, fn);
  16294. }),
  16295. async close() {
  16296. await normalizedHotChannel.close();
  16297. },
  16298. [isWebSocketServer]: true,
  16299. get clients() {
  16300. return new Set(Array.from(wss.clients).map(getSocketClient));
  16301. }
  16302. };
  16303. }
  16304. //#endregion
  16305. //#region src/node/server/middlewares/base.ts
  16306. function baseMiddleware(rawBase, middlewareMode) {
  16307. return function viteBaseMiddleware(req, res, next) {
  16308. const url = req.url;
  16309. const pathname = cleanUrl(url);
  16310. const base = rawBase;
  16311. if (pathname.startsWith(base)) {
  16312. req.url = stripBase(url, base);
  16313. return next();
  16314. }
  16315. if (middlewareMode) return next();
  16316. if (pathname === "/" || pathname === "/index.html") {
  16317. res.writeHead(302, { Location: base + url.slice(pathname.length) });
  16318. res.end();
  16319. return;
  16320. }
  16321. const redirectPath = withTrailingSlash(url) !== base ? joinUrlSegments(base, url) : base;
  16322. if (req.headers.accept?.includes("text/html")) {
  16323. res.writeHead(404, { "Content-Type": "text/html" });
  16324. res.end(`The server is configured with a public base URL of ${base} - did you mean to visit <a href="${redirectPath}">${redirectPath}</a> instead?`);
  16325. return;
  16326. } else {
  16327. res.writeHead(404, { "Content-Type": "text/plain" });
  16328. res.end(`The server is configured with a public base URL of ${base} - did you mean to visit ${redirectPath} instead?`);
  16329. return;
  16330. }
  16331. };
  16332. }
  16333. //#endregion
  16334. //#region ../../node_modules/.pnpm/follow-redirects@1.15.11_obug@1.0.2/node_modules/follow-redirects/debug.js
  16335. var require_debug = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  16336. var debug;
  16337. module.exports = function() {
  16338. if (!debug) {
  16339. try {
  16340. debug = (init_node(), __toCommonJS(node_exports))("follow-redirects");
  16341. } catch (error) {}
  16342. if (typeof debug !== "function") debug = function() {};
  16343. }
  16344. debug.apply(null, arguments);
  16345. };
  16346. }));
  16347. //#endregion
  16348. //#region ../../node_modules/.pnpm/follow-redirects@1.15.11_obug@1.0.2/node_modules/follow-redirects/index.js
  16349. var require_follow_redirects = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  16350. var url$1 = __require("url");
  16351. var URL = url$1.URL;
  16352. var http$3 = __require("http");
  16353. var https$2 = __require("https");
  16354. var Writable = __require("stream").Writable;
  16355. var assert$1 = __require("assert");
  16356. var debug = require_debug();
  16357. // istanbul ignore next
  16358. (function detectUnsupportedEnvironment() {
  16359. var looksLikeNode = typeof process !== "undefined";
  16360. var looksLikeBrowser = typeof window !== "undefined" && typeof document !== "undefined";
  16361. var looksLikeV8 = isFunction(Error.captureStackTrace);
  16362. if (!looksLikeNode && (looksLikeBrowser || !looksLikeV8)) console.warn("The follow-redirects package should be excluded from browser builds.");
  16363. })();
  16364. var useNativeURL = false;
  16365. try {
  16366. assert$1(new URL(""));
  16367. } catch (error) {
  16368. useNativeURL = error.code === "ERR_INVALID_URL";
  16369. }
  16370. var preservedUrlFields = [
  16371. "auth",
  16372. "host",
  16373. "hostname",
  16374. "href",
  16375. "path",
  16376. "pathname",
  16377. "port",
  16378. "protocol",
  16379. "query",
  16380. "search",
  16381. "hash"
  16382. ];
  16383. var events = [
  16384. "abort",
  16385. "aborted",
  16386. "connect",
  16387. "error",
  16388. "socket",
  16389. "timeout"
  16390. ];
  16391. var eventHandlers = Object.create(null);
  16392. events.forEach(function(event) {
  16393. eventHandlers[event] = function(arg1, arg2, arg3) {
  16394. this._redirectable.emit(event, arg1, arg2, arg3);
  16395. };
  16396. });
  16397. var InvalidUrlError = createErrorType("ERR_INVALID_URL", "Invalid URL", TypeError);
  16398. var RedirectionError = createErrorType("ERR_FR_REDIRECTION_FAILURE", "Redirected request failed");
  16399. var TooManyRedirectsError = createErrorType("ERR_FR_TOO_MANY_REDIRECTS", "Maximum number of redirects exceeded", RedirectionError);
  16400. var MaxBodyLengthExceededError = createErrorType("ERR_FR_MAX_BODY_LENGTH_EXCEEDED", "Request body larger than maxBodyLength limit");
  16401. var WriteAfterEndError = createErrorType("ERR_STREAM_WRITE_AFTER_END", "write after end");
  16402. // istanbul ignore next
  16403. var destroy = Writable.prototype.destroy || noop;
  16404. function RedirectableRequest(options, responseCallback) {
  16405. Writable.call(this);
  16406. this._sanitizeOptions(options);
  16407. this._options = options;
  16408. this._ended = false;
  16409. this._ending = false;
  16410. this._redirectCount = 0;
  16411. this._redirects = [];
  16412. this._requestBodyLength = 0;
  16413. this._requestBodyBuffers = [];
  16414. if (responseCallback) this.on("response", responseCallback);
  16415. var self = this;
  16416. this._onNativeResponse = function(response) {
  16417. try {
  16418. self._processResponse(response);
  16419. } catch (cause) {
  16420. self.emit("error", cause instanceof RedirectionError ? cause : new RedirectionError({ cause }));
  16421. }
  16422. };
  16423. this._performRequest();
  16424. }
  16425. RedirectableRequest.prototype = Object.create(Writable.prototype);
  16426. RedirectableRequest.prototype.abort = function() {
  16427. destroyRequest(this._currentRequest);
  16428. this._currentRequest.abort();
  16429. this.emit("abort");
  16430. };
  16431. RedirectableRequest.prototype.destroy = function(error) {
  16432. destroyRequest(this._currentRequest, error);
  16433. destroy.call(this, error);
  16434. return this;
  16435. };
  16436. RedirectableRequest.prototype.write = function(data, encoding, callback) {
  16437. if (this._ending) throw new WriteAfterEndError();
  16438. if (!isString(data) && !isBuffer(data)) throw new TypeError("data should be a string, Buffer or Uint8Array");
  16439. if (isFunction(encoding)) {
  16440. callback = encoding;
  16441. encoding = null;
  16442. }
  16443. if (data.length === 0) {
  16444. if (callback) callback();
  16445. return;
  16446. }
  16447. if (this._requestBodyLength + data.length <= this._options.maxBodyLength) {
  16448. this._requestBodyLength += data.length;
  16449. this._requestBodyBuffers.push({
  16450. data,
  16451. encoding
  16452. });
  16453. this._currentRequest.write(data, encoding, callback);
  16454. } else {
  16455. this.emit("error", new MaxBodyLengthExceededError());
  16456. this.abort();
  16457. }
  16458. };
  16459. RedirectableRequest.prototype.end = function(data, encoding, callback) {
  16460. if (isFunction(data)) {
  16461. callback = data;
  16462. data = encoding = null;
  16463. } else if (isFunction(encoding)) {
  16464. callback = encoding;
  16465. encoding = null;
  16466. }
  16467. if (!data) {
  16468. this._ended = this._ending = true;
  16469. this._currentRequest.end(null, null, callback);
  16470. } else {
  16471. var self = this;
  16472. var currentRequest = this._currentRequest;
  16473. this.write(data, encoding, function() {
  16474. self._ended = true;
  16475. currentRequest.end(null, null, callback);
  16476. });
  16477. this._ending = true;
  16478. }
  16479. };
  16480. RedirectableRequest.prototype.setHeader = function(name, value) {
  16481. this._options.headers[name] = value;
  16482. this._currentRequest.setHeader(name, value);
  16483. };
  16484. RedirectableRequest.prototype.removeHeader = function(name) {
  16485. delete this._options.headers[name];
  16486. this._currentRequest.removeHeader(name);
  16487. };
  16488. RedirectableRequest.prototype.setTimeout = function(msecs, callback) {
  16489. var self = this;
  16490. function destroyOnTimeout(socket) {
  16491. socket.setTimeout(msecs);
  16492. socket.removeListener("timeout", socket.destroy);
  16493. socket.addListener("timeout", socket.destroy);
  16494. }
  16495. function startTimer(socket) {
  16496. if (self._timeout) clearTimeout(self._timeout);
  16497. self._timeout = setTimeout(function() {
  16498. self.emit("timeout");
  16499. clearTimer();
  16500. }, msecs);
  16501. destroyOnTimeout(socket);
  16502. }
  16503. function clearTimer() {
  16504. if (self._timeout) {
  16505. clearTimeout(self._timeout);
  16506. self._timeout = null;
  16507. }
  16508. self.removeListener("abort", clearTimer);
  16509. self.removeListener("error", clearTimer);
  16510. self.removeListener("response", clearTimer);
  16511. self.removeListener("close", clearTimer);
  16512. if (callback) self.removeListener("timeout", callback);
  16513. if (!self.socket) self._currentRequest.removeListener("socket", startTimer);
  16514. }
  16515. if (callback) this.on("timeout", callback);
  16516. if (this.socket) startTimer(this.socket);
  16517. else this._currentRequest.once("socket", startTimer);
  16518. this.on("socket", destroyOnTimeout);
  16519. this.on("abort", clearTimer);
  16520. this.on("error", clearTimer);
  16521. this.on("response", clearTimer);
  16522. this.on("close", clearTimer);
  16523. return this;
  16524. };
  16525. [
  16526. "flushHeaders",
  16527. "getHeader",
  16528. "setNoDelay",
  16529. "setSocketKeepAlive"
  16530. ].forEach(function(method) {
  16531. RedirectableRequest.prototype[method] = function(a, b) {
  16532. return this._currentRequest[method](a, b);
  16533. };
  16534. });
  16535. [
  16536. "aborted",
  16537. "connection",
  16538. "socket"
  16539. ].forEach(function(property) {
  16540. Object.defineProperty(RedirectableRequest.prototype, property, { get: function() {
  16541. return this._currentRequest[property];
  16542. } });
  16543. });
  16544. RedirectableRequest.prototype._sanitizeOptions = function(options) {
  16545. if (!options.headers) options.headers = {};
  16546. if (options.host) {
  16547. if (!options.hostname) options.hostname = options.host;
  16548. delete options.host;
  16549. }
  16550. if (!options.pathname && options.path) {
  16551. var searchPos = options.path.indexOf("?");
  16552. if (searchPos < 0) options.pathname = options.path;
  16553. else {
  16554. options.pathname = options.path.substring(0, searchPos);
  16555. options.search = options.path.substring(searchPos);
  16556. }
  16557. }
  16558. };
  16559. RedirectableRequest.prototype._performRequest = function() {
  16560. var protocol = this._options.protocol;
  16561. var nativeProtocol = this._options.nativeProtocols[protocol];
  16562. if (!nativeProtocol) throw new TypeError("Unsupported protocol " + protocol);
  16563. if (this._options.agents) {
  16564. var scheme = protocol.slice(0, -1);
  16565. this._options.agent = this._options.agents[scheme];
  16566. }
  16567. var request = this._currentRequest = nativeProtocol.request(this._options, this._onNativeResponse);
  16568. request._redirectable = this;
  16569. for (var event of events) request.on(event, eventHandlers[event]);
  16570. this._currentUrl = /^\//.test(this._options.path) ? url$1.format(this._options) : this._options.path;
  16571. if (this._isRedirect) {
  16572. var i = 0;
  16573. var self = this;
  16574. var buffers = this._requestBodyBuffers;
  16575. (function writeNext(error) {
  16576. // istanbul ignore else
  16577. if (request === self._currentRequest) {
  16578. // istanbul ignore if
  16579. if (error) self.emit("error", error);
  16580. else if (i < buffers.length) {
  16581. var buffer = buffers[i++];
  16582. // istanbul ignore else
  16583. if (!request.finished) request.write(buffer.data, buffer.encoding, writeNext);
  16584. } else if (self._ended) request.end();
  16585. }
  16586. })();
  16587. }
  16588. };
  16589. RedirectableRequest.prototype._processResponse = function(response) {
  16590. var statusCode = response.statusCode;
  16591. if (this._options.trackRedirects) this._redirects.push({
  16592. url: this._currentUrl,
  16593. headers: response.headers,
  16594. statusCode
  16595. });
  16596. var location = response.headers.location;
  16597. if (!location || this._options.followRedirects === false || statusCode < 300 || statusCode >= 400) {
  16598. response.responseUrl = this._currentUrl;
  16599. response.redirects = this._redirects;
  16600. this.emit("response", response);
  16601. this._requestBodyBuffers = [];
  16602. return;
  16603. }
  16604. destroyRequest(this._currentRequest);
  16605. response.destroy();
  16606. if (++this._redirectCount > this._options.maxRedirects) throw new TooManyRedirectsError();
  16607. var requestHeaders;
  16608. var beforeRedirect = this._options.beforeRedirect;
  16609. if (beforeRedirect) requestHeaders = Object.assign({ Host: response.req.getHeader("host") }, this._options.headers);
  16610. var method = this._options.method;
  16611. if ((statusCode === 301 || statusCode === 302) && this._options.method === "POST" || statusCode === 303 && !/^(?:GET|HEAD)$/.test(this._options.method)) {
  16612. this._options.method = "GET";
  16613. this._requestBodyBuffers = [];
  16614. removeMatchingHeaders(/^content-/i, this._options.headers);
  16615. }
  16616. var currentHostHeader = removeMatchingHeaders(/^host$/i, this._options.headers);
  16617. var currentUrlParts = parseUrl(this._currentUrl);
  16618. var currentHost = currentHostHeader || currentUrlParts.host;
  16619. var currentUrl = /^\w+:/.test(location) ? this._currentUrl : url$1.format(Object.assign(currentUrlParts, { host: currentHost }));
  16620. var redirectUrl = resolveUrl(location, currentUrl);
  16621. debug("redirecting to", redirectUrl.href);
  16622. this._isRedirect = true;
  16623. spreadUrlObject(redirectUrl, this._options);
  16624. if (redirectUrl.protocol !== currentUrlParts.protocol && redirectUrl.protocol !== "https:" || redirectUrl.host !== currentHost && !isSubdomain(redirectUrl.host, currentHost)) removeMatchingHeaders(/^(?:(?:proxy-)?authorization|cookie)$/i, this._options.headers);
  16625. if (isFunction(beforeRedirect)) {
  16626. beforeRedirect(this._options, {
  16627. headers: response.headers,
  16628. statusCode
  16629. }, {
  16630. url: currentUrl,
  16631. method,
  16632. headers: requestHeaders
  16633. });
  16634. this._sanitizeOptions(this._options);
  16635. }
  16636. this._performRequest();
  16637. };
  16638. function wrap(protocols) {
  16639. var exports$1 = {
  16640. maxRedirects: 21,
  16641. maxBodyLength: 10 * 1024 * 1024
  16642. };
  16643. var nativeProtocols = {};
  16644. Object.keys(protocols).forEach(function(scheme) {
  16645. var protocol = scheme + ":";
  16646. var nativeProtocol = nativeProtocols[protocol] = protocols[scheme];
  16647. var wrappedProtocol = exports$1[scheme] = Object.create(nativeProtocol);
  16648. function request(input, options, callback) {
  16649. if (isURL(input)) input = spreadUrlObject(input);
  16650. else if (isString(input)) input = spreadUrlObject(parseUrl(input));
  16651. else {
  16652. callback = options;
  16653. options = validateUrl(input);
  16654. input = { protocol };
  16655. }
  16656. if (isFunction(options)) {
  16657. callback = options;
  16658. options = null;
  16659. }
  16660. options = Object.assign({
  16661. maxRedirects: exports$1.maxRedirects,
  16662. maxBodyLength: exports$1.maxBodyLength
  16663. }, input, options);
  16664. options.nativeProtocols = nativeProtocols;
  16665. if (!isString(options.host) && !isString(options.hostname)) options.hostname = "::1";
  16666. assert$1.equal(options.protocol, protocol, "protocol mismatch");
  16667. debug("options", options);
  16668. return new RedirectableRequest(options, callback);
  16669. }
  16670. function get(input, options, callback) {
  16671. var wrappedRequest = wrappedProtocol.request(input, options, callback);
  16672. wrappedRequest.end();
  16673. return wrappedRequest;
  16674. }
  16675. Object.defineProperties(wrappedProtocol, {
  16676. request: {
  16677. value: request,
  16678. configurable: true,
  16679. enumerable: true,
  16680. writable: true
  16681. },
  16682. get: {
  16683. value: get,
  16684. configurable: true,
  16685. enumerable: true,
  16686. writable: true
  16687. }
  16688. });
  16689. });
  16690. return exports$1;
  16691. }
  16692. function noop() {}
  16693. function parseUrl(input) {
  16694. var parsed;
  16695. // istanbul ignore else
  16696. if (useNativeURL) parsed = new URL(input);
  16697. else {
  16698. parsed = validateUrl(url$1.parse(input));
  16699. if (!isString(parsed.protocol)) throw new InvalidUrlError({ input });
  16700. }
  16701. return parsed;
  16702. }
  16703. function resolveUrl(relative, base) {
  16704. // istanbul ignore next
  16705. return useNativeURL ? new URL(relative, base) : parseUrl(url$1.resolve(base, relative));
  16706. }
  16707. function validateUrl(input) {
  16708. if (/^\[/.test(input.hostname) && !/^\[[:0-9a-f]+\]$/i.test(input.hostname)) throw new InvalidUrlError({ input: input.href || input });
  16709. if (/^\[/.test(input.host) && !/^\[[:0-9a-f]+\](:\d+)?$/i.test(input.host)) throw new InvalidUrlError({ input: input.href || input });
  16710. return input;
  16711. }
  16712. function spreadUrlObject(urlObject, target) {
  16713. var spread = target || {};
  16714. for (var key of preservedUrlFields) spread[key] = urlObject[key];
  16715. if (spread.hostname.startsWith("[")) spread.hostname = spread.hostname.slice(1, -1);
  16716. if (spread.port !== "") spread.port = Number(spread.port);
  16717. spread.path = spread.search ? spread.pathname + spread.search : spread.pathname;
  16718. return spread;
  16719. }
  16720. function removeMatchingHeaders(regex, headers) {
  16721. var lastValue;
  16722. for (var header in headers) if (regex.test(header)) {
  16723. lastValue = headers[header];
  16724. delete headers[header];
  16725. }
  16726. return lastValue === null || typeof lastValue === "undefined" ? void 0 : String(lastValue).trim();
  16727. }
  16728. function createErrorType(code, message, baseClass) {
  16729. function CustomError(properties) {
  16730. // istanbul ignore else
  16731. if (isFunction(Error.captureStackTrace)) Error.captureStackTrace(this, this.constructor);
  16732. Object.assign(this, properties || {});
  16733. this.code = code;
  16734. this.message = this.cause ? message + ": " + this.cause.message : message;
  16735. }
  16736. CustomError.prototype = new (baseClass || Error)();
  16737. Object.defineProperties(CustomError.prototype, {
  16738. constructor: {
  16739. value: CustomError,
  16740. enumerable: false
  16741. },
  16742. name: {
  16743. value: "Error [" + code + "]",
  16744. enumerable: false
  16745. }
  16746. });
  16747. return CustomError;
  16748. }
  16749. function destroyRequest(request, error) {
  16750. for (var event of events) request.removeListener(event, eventHandlers[event]);
  16751. request.on("error", noop);
  16752. request.destroy(error);
  16753. }
  16754. function isSubdomain(subdomain, domain) {
  16755. assert$1(isString(subdomain) && isString(domain));
  16756. var dot = subdomain.length - domain.length - 1;
  16757. return dot > 0 && subdomain[dot] === "." && subdomain.endsWith(domain);
  16758. }
  16759. function isString(value) {
  16760. return typeof value === "string" || value instanceof String;
  16761. }
  16762. function isFunction(value) {
  16763. return typeof value === "function";
  16764. }
  16765. function isBuffer(value) {
  16766. return typeof value === "object" && "length" in value;
  16767. }
  16768. function isURL(value) {
  16769. return URL && value instanceof URL;
  16770. }
  16771. module.exports = wrap({
  16772. http: http$3,
  16773. https: https$2
  16774. });
  16775. module.exports.wrap = wrap;
  16776. }));
  16777. //#endregion
  16778. //#region ../../node_modules/.pnpm/http-proxy-3@1.23.2_ms@2.1.3/node_modules/http-proxy-3/dist/lib/http-proxy/common.js
  16779. var require_common = /* @__PURE__ */ __commonJSMin(((exports) => {
  16780. Object.defineProperty(exports, "__esModule", { value: true });
  16781. exports.isSSL = void 0;
  16782. exports.setupOutgoing = setupOutgoing;
  16783. exports.setupSocket = setupSocket;
  16784. exports.getPort = getPort;
  16785. exports.hasEncryptedConnection = hasEncryptedConnection;
  16786. exports.urlJoin = urlJoin;
  16787. exports.rewriteCookieProperty = rewriteCookieProperty;
  16788. exports.toURL = toURL;
  16789. const node_tls_1 = __require("node:tls");
  16790. const upgradeHeader = /(^|,)\s*upgrade\s*($|,)/i;
  16791. exports.isSSL = /^https|wss/;
  16792. const HEADER_BLACKLIST = "trailer";
  16793. const HTTP2_HEADER_BLACKLIST = [
  16794. ":method",
  16795. ":path",
  16796. ":scheme",
  16797. ":authority",
  16798. "connection",
  16799. "keep-alive"
  16800. ];
  16801. function setupOutgoing(outgoing, options, req, forward) {
  16802. const target = options[forward || "target"];
  16803. outgoing.port = +(target.port ?? (target.protocol !== void 0 && exports.isSSL.test(target.protocol) ? 443 : 80));
  16804. for (const e of [
  16805. "host",
  16806. "hostname",
  16807. "socketPath",
  16808. "pfx",
  16809. "key",
  16810. "passphrase",
  16811. "cert",
  16812. "ca",
  16813. "ciphers",
  16814. "secureProtocol"
  16815. ]) outgoing[e] = target[e];
  16816. outgoing.method = options.method || req.method;
  16817. outgoing.headers = { ...req.headers };
  16818. if (req.headers?.[":authority"]) outgoing.headers.host = req.headers[":authority"];
  16819. if (options.headers) outgoing.headers = {
  16820. ...outgoing.headers,
  16821. ...options.headers
  16822. };
  16823. for (const header in outgoing.headers) if (HEADER_BLACKLIST == header.toLowerCase()) {
  16824. delete outgoing.headers[header];
  16825. break;
  16826. }
  16827. if (req.httpVersionMajor > 1) for (const header of HTTP2_HEADER_BLACKLIST) delete outgoing.headers[header];
  16828. if (options.auth) {
  16829. delete outgoing.headers.authorization;
  16830. outgoing.auth = options.auth;
  16831. }
  16832. if (options.ca) outgoing.ca = options.ca;
  16833. if (target.protocol !== void 0 && exports.isSSL.test(target.protocol)) outgoing.rejectUnauthorized = typeof options.secure === "undefined" ? true : options.secure;
  16834. outgoing.agent = options.agent || false;
  16835. outgoing.localAddress = options.localAddress;
  16836. if (!outgoing.agent) {
  16837. outgoing.headers = outgoing.headers || {};
  16838. if (typeof outgoing.headers.connection !== "string" || !upgradeHeader.test(outgoing.headers.connection)) outgoing.headers.connection = "close";
  16839. }
  16840. const targetPath = target && options.prependPath !== false && "pathname" in target ? getPath(`${target.pathname}${target.search ?? ""}`) : "/";
  16841. let outgoingPath = options.toProxy ? req.url : getPath(req.url);
  16842. outgoingPath = !options.ignorePath ? outgoingPath : "";
  16843. outgoing.path = urlJoin(targetPath, outgoingPath ?? "");
  16844. if (options.changeOrigin) outgoing.headers.host = target.protocol !== void 0 && required(outgoing.port, target.protocol) && !hasPort(outgoing.host) ? outgoing.host + ":" + outgoing.port : outgoing.host;
  16845. outgoing.url = "href" in target && target.href || (target.protocol === "https" ? "https" : "http") + "://" + outgoing.host + (outgoing.port ? ":" + outgoing.port : "");
  16846. if (req.httpVersionMajor > 1) for (const header of HTTP2_HEADER_BLACKLIST) delete outgoing.headers[header];
  16847. return outgoing;
  16848. }
  16849. function setupSocket(socket) {
  16850. socket.setTimeout(0);
  16851. socket.setNoDelay(true);
  16852. socket.setKeepAlive(true, 0);
  16853. return socket;
  16854. }
  16855. function getPort(req) {
  16856. const hostHeader = req.headers[":authority"] || req.headers.host;
  16857. const res = hostHeader ? hostHeader.match(/:(\d+)/) : "";
  16858. return res ? res[1] : hasEncryptedConnection(req) ? "443" : "80";
  16859. }
  16860. function hasEncryptedConnection(req) {
  16861. const conn = req.connection;
  16862. return conn instanceof node_tls_1.TLSSocket && conn.encrypted || Boolean(conn.pair);
  16863. }
  16864. function urlJoin(...args) {
  16865. const queryParams = [];
  16866. let queryParamRaw = "";
  16867. args.forEach((url, index) => {
  16868. const qpStart = url.indexOf("?");
  16869. if (qpStart !== -1) {
  16870. queryParams.push(url.substring(qpStart + 1));
  16871. args[index] = url.substring(0, qpStart);
  16872. }
  16873. });
  16874. queryParamRaw = queryParams.filter(Boolean).join("&");
  16875. let retSegs = "";
  16876. for (const seg of args) {
  16877. if (!seg) continue;
  16878. if (retSegs.endsWith("/")) if (seg.startsWith("/")) retSegs += seg.slice(1);
  16879. else retSegs += seg;
  16880. else if (seg.startsWith("/")) retSegs += seg;
  16881. else retSegs += "/" + seg;
  16882. }
  16883. return queryParamRaw ? retSegs + "?" + queryParamRaw : retSegs;
  16884. }
  16885. function rewriteCookieProperty(header, config, property) {
  16886. if (Array.isArray(header)) return header.map((headerElement) => {
  16887. return rewriteCookieProperty(headerElement, config, property);
  16888. });
  16889. return header.replace(new RegExp("(;\\s*" + property + "=)([^;]+)", "i"), (match, prefix, previousValue) => {
  16890. let newValue;
  16891. if (previousValue in config) newValue = config[previousValue];
  16892. else if ("*" in config) newValue = config["*"];
  16893. else return match;
  16894. if (newValue) return prefix + newValue;
  16895. else return "";
  16896. });
  16897. }
  16898. function hasPort(host) {
  16899. return !!~host.indexOf(":");
  16900. }
  16901. function getPath(url) {
  16902. if (url === "" || url?.startsWith("?")) return url;
  16903. const u = toURL(url);
  16904. return `${u.pathname ?? ""}${u.search ?? ""}`;
  16905. }
  16906. function toURL(url) {
  16907. if (url instanceof URL) return url;
  16908. else if (typeof url === "object" && "href" in url && typeof url.href === "string") url = url.href;
  16909. if (!url) url = "";
  16910. if (typeof url != "string") url = `${url}`;
  16911. if (url.startsWith("//")) url = `http://base.invalid${url}`;
  16912. return new URL(url, "http://base.invalid");
  16913. }
  16914. function required(port, protocol) {
  16915. protocol = protocol.split(":")[0];
  16916. port = +port;
  16917. if (!port) return false;
  16918. switch (protocol) {
  16919. case "http":
  16920. case "ws": return port !== 80;
  16921. case "https":
  16922. case "wss": return port !== 443;
  16923. }
  16924. return port !== 0;
  16925. }
  16926. }));
  16927. //#endregion
  16928. //#region ../../node_modules/.pnpm/http-proxy-3@1.23.2_ms@2.1.3/node_modules/http-proxy-3/dist/lib/http-proxy/passes/web-outgoing.js
  16929. var require_web_outgoing = /* @__PURE__ */ __commonJSMin(((exports) => {
  16930. var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o, m, k, k2) {
  16931. if (k2 === void 0) k2 = k;
  16932. var desc = Object.getOwnPropertyDescriptor(m, k);
  16933. if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) desc = {
  16934. enumerable: true,
  16935. get: function() {
  16936. return m[k];
  16937. }
  16938. };
  16939. Object.defineProperty(o, k2, desc);
  16940. }) : (function(o, m, k, k2) {
  16941. if (k2 === void 0) k2 = k;
  16942. o[k2] = m[k];
  16943. }));
  16944. var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o, v) {
  16945. Object.defineProperty(o, "default", {
  16946. enumerable: true,
  16947. value: v
  16948. });
  16949. }) : function(o, v) {
  16950. o["default"] = v;
  16951. });
  16952. var __importStar = exports && exports.__importStar || (function() {
  16953. var ownKeys = function(o) {
  16954. ownKeys = Object.getOwnPropertyNames || function(o) {
  16955. var ar = [];
  16956. for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
  16957. return ar;
  16958. };
  16959. return ownKeys(o);
  16960. };
  16961. return function(mod) {
  16962. if (mod && mod.__esModule) return mod;
  16963. var result = {};
  16964. if (mod != null) {
  16965. for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
  16966. }
  16967. __setModuleDefault(result, mod);
  16968. return result;
  16969. };
  16970. })();
  16971. Object.defineProperty(exports, "__esModule", { value: true });
  16972. exports.OUTGOING_PASSES = void 0;
  16973. exports.removeChunked = removeChunked;
  16974. exports.setConnection = setConnection;
  16975. exports.setRedirectHostRewrite = setRedirectHostRewrite;
  16976. exports.writeHeaders = writeHeaders;
  16977. exports.writeStatusCode = writeStatusCode;
  16978. const common = __importStar(require_common());
  16979. const redirectRegex = /^201|30(1|2|7|8)$/;
  16980. function removeChunked(_req, _res, proxyRes) {
  16981. delete proxyRes.headers["transfer-encoding"];
  16982. }
  16983. function setConnection(req, _res, proxyRes) {
  16984. if (req.httpVersion === "1.0") proxyRes.headers["connection"] = req.headers["connection"] || "close";
  16985. else if (req.httpVersion !== "2.0" && !proxyRes.headers["connection"]) proxyRes.headers["connection"] = req.headers["connection"] || "keep-alive";
  16986. }
  16987. function setRedirectHostRewrite(req, _res, proxyRes, options) {
  16988. if ((options.hostRewrite || options.autoRewrite || options.protocolRewrite) && proxyRes.headers["location"] && redirectRegex.test(`${proxyRes.statusCode}`)) {
  16989. const target = common.toURL(options.target);
  16990. const location = proxyRes.headers["location"];
  16991. if (typeof location != "string") return;
  16992. const u = common.toURL(location);
  16993. if (target.host != u.host) return;
  16994. if (options.hostRewrite) u.host = options.hostRewrite;
  16995. else if (options.autoRewrite) u.host = req.headers[":authority"] ?? req.headers["host"] ?? "";
  16996. if (options.protocolRewrite) u.protocol = options.protocolRewrite;
  16997. proxyRes.headers["location"] = u.toString();
  16998. }
  16999. }
  17000. function writeHeaders(_req, res, proxyRes, options) {
  17001. const rewriteCookieDomainConfig = typeof options.cookieDomainRewrite === "string" ? { "*": options.cookieDomainRewrite } : options.cookieDomainRewrite;
  17002. const rewriteCookiePathConfig = typeof options.cookiePathRewrite === "string" ? { "*": options.cookiePathRewrite } : options.cookiePathRewrite;
  17003. const preserveHeaderKeyCase = options.preserveHeaderKeyCase;
  17004. const setHeader = (key, header) => {
  17005. if (header == void 0) return;
  17006. if (rewriteCookieDomainConfig && key.toLowerCase() === "set-cookie") header = common.rewriteCookieProperty(header, rewriteCookieDomainConfig, "domain");
  17007. if (rewriteCookiePathConfig && key.toLowerCase() === "set-cookie") header = common.rewriteCookieProperty(header, rewriteCookiePathConfig, "path");
  17008. res.setHeader(String(key).trim(), header);
  17009. };
  17010. let rawHeaderKeyMap;
  17011. if (preserveHeaderKeyCase && proxyRes.rawHeaders != void 0) {
  17012. rawHeaderKeyMap = {};
  17013. for (let i = 0; i < proxyRes.rawHeaders.length; i += 2) {
  17014. const key = proxyRes.rawHeaders[i];
  17015. rawHeaderKeyMap[key.toLowerCase()] = key;
  17016. }
  17017. }
  17018. for (const key0 in proxyRes.headers) {
  17019. let key = key0;
  17020. if (_req.httpVersionMajor > 1 && (key === "connection" || key === "keep-alive")) continue;
  17021. const header = proxyRes.headers[key];
  17022. if (preserveHeaderKeyCase && rawHeaderKeyMap) key = rawHeaderKeyMap[key] ?? key;
  17023. setHeader(key, header);
  17024. }
  17025. }
  17026. function writeStatusCode(_req, res, proxyRes) {
  17027. res.statusCode = proxyRes.statusCode;
  17028. if (proxyRes.statusMessage && _req.httpVersionMajor === 1) res.statusMessage = proxyRes.statusMessage;
  17029. }
  17030. exports.OUTGOING_PASSES = {
  17031. removeChunked,
  17032. setConnection,
  17033. setRedirectHostRewrite,
  17034. writeHeaders,
  17035. writeStatusCode
  17036. };
  17037. }));
  17038. //#endregion
  17039. //#region ../../node_modules/.pnpm/http-proxy-3@1.23.2_ms@2.1.3/node_modules/http-proxy-3/dist/lib/http-proxy/passes/web-incoming.js
  17040. var require_web_incoming = /* @__PURE__ */ __commonJSMin(((exports) => {
  17041. var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o, m, k, k2) {
  17042. if (k2 === void 0) k2 = k;
  17043. var desc = Object.getOwnPropertyDescriptor(m, k);
  17044. if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) desc = {
  17045. enumerable: true,
  17046. get: function() {
  17047. return m[k];
  17048. }
  17049. };
  17050. Object.defineProperty(o, k2, desc);
  17051. }) : (function(o, m, k, k2) {
  17052. if (k2 === void 0) k2 = k;
  17053. o[k2] = m[k];
  17054. }));
  17055. var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o, v) {
  17056. Object.defineProperty(o, "default", {
  17057. enumerable: true,
  17058. value: v
  17059. });
  17060. }) : function(o, v) {
  17061. o["default"] = v;
  17062. });
  17063. var __importStar = exports && exports.__importStar || (function() {
  17064. var ownKeys = function(o) {
  17065. ownKeys = Object.getOwnPropertyNames || function(o) {
  17066. var ar = [];
  17067. for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
  17068. return ar;
  17069. };
  17070. return ownKeys(o);
  17071. };
  17072. return function(mod) {
  17073. if (mod && mod.__esModule) return mod;
  17074. var result = {};
  17075. if (mod != null) {
  17076. for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
  17077. }
  17078. __setModuleDefault(result, mod);
  17079. return result;
  17080. };
  17081. })();
  17082. Object.defineProperty(exports, "__esModule", { value: true });
  17083. exports.WEB_PASSES = void 0;
  17084. exports.deleteLength = deleteLength;
  17085. exports.timeout = timeout;
  17086. exports.XHeaders = XHeaders;
  17087. exports.stream = stream;
  17088. const http$2 = __importStar(__require("node:http"));
  17089. const https$1 = __importStar(__require("node:https"));
  17090. const followRedirects = __importStar(require_follow_redirects());
  17091. const common = __importStar(require_common());
  17092. const web_outgoing_1 = require_web_outgoing();
  17093. const node_stream_1 = __require("node:stream");
  17094. const web_o = Object.values(web_outgoing_1.OUTGOING_PASSES);
  17095. const nativeAgents = {
  17096. http: http$2,
  17097. https: https$1
  17098. };
  17099. function deleteLength(req) {
  17100. if ((req.method === "DELETE" || req.method === "OPTIONS") && !req.headers["content-length"]) {
  17101. req.headers["content-length"] = "0";
  17102. delete req.headers["transfer-encoding"];
  17103. }
  17104. }
  17105. function timeout(req, _res, options) {
  17106. if (options.timeout) req.socket.setTimeout(options.timeout);
  17107. }
  17108. function XHeaders(req, _res, options) {
  17109. if (!options.xfwd) return;
  17110. const encrypted = common.hasEncryptedConnection(req);
  17111. const values = {
  17112. for: req.connection.remoteAddress || req.socket.remoteAddress,
  17113. port: common.getPort(req),
  17114. proto: encrypted ? "https" : "http"
  17115. };
  17116. for (const header of [
  17117. "for",
  17118. "port",
  17119. "proto"
  17120. ]) req.headers["x-forwarded-" + header] = (req.headers["x-forwarded-" + header] || "") + (req.headers["x-forwarded-" + header] ? "," : "") + values[header];
  17121. req.headers["x-forwarded-host"] = req.headers["x-forwarded-host"] || req.headers[":authority"] || req.headers["host"] || "";
  17122. }
  17123. function stream(req, res, options, _, server, cb) {
  17124. server.emit("start", req, res, options.target || options.forward);
  17125. if (options.fetch || options.fetchOptions || process.env.FORCE_FETCH_PATH === "true") return stream2(req, res, options, _, server, cb);
  17126. const agents = options.followRedirects ? followRedirects : nativeAgents;
  17127. const http = agents.http;
  17128. const https = agents.https;
  17129. if (options.forward) {
  17130. const proto = options.forward.protocol === "https:" ? https : http;
  17131. const outgoingOptions = common.setupOutgoing(options.ssl || {}, options, req, "forward");
  17132. const forwardReq = proto.request(outgoingOptions);
  17133. const forwardError = createErrorHandler(forwardReq, options.forward);
  17134. req.on("error", forwardError);
  17135. forwardReq.on("error", forwardError);
  17136. (options.buffer || req).pipe(forwardReq);
  17137. if (!options.target) return res.end();
  17138. }
  17139. const proto = options.target.protocol === "https:" ? https : http;
  17140. const outgoingOptions = common.setupOutgoing(options.ssl || {}, options, req);
  17141. const proxyReq = proto.request(outgoingOptions);
  17142. proxyReq.on("socket", (socket) => {
  17143. if (server && !proxyReq.getHeader("expect")) server.emit("proxyReq", proxyReq, req, res, options, socket);
  17144. });
  17145. if (options.proxyTimeout) proxyReq.setTimeout(options.proxyTimeout, () => {
  17146. proxyReq.destroy();
  17147. });
  17148. res.on("close", () => {
  17149. if (!res.writableFinished) proxyReq.destroy();
  17150. });
  17151. const proxyError = createErrorHandler(proxyReq, options.target);
  17152. req.on("error", proxyError);
  17153. proxyReq.on("error", proxyError);
  17154. function createErrorHandler(proxyReq, url) {
  17155. return (err) => {
  17156. if (req.socket.destroyed && err.code === "ECONNRESET") {
  17157. server.emit("econnreset", err, req, res, url);
  17158. proxyReq.destroy();
  17159. return;
  17160. }
  17161. if (cb) cb(err, req, res, url);
  17162. else server.emit("error", err, req, res, url);
  17163. };
  17164. }
  17165. (options.buffer || req).pipe(proxyReq);
  17166. proxyReq.on("response", (proxyRes) => {
  17167. server?.emit("proxyRes", proxyRes, req, res);
  17168. if (!res.headersSent && !options.selfHandleResponse) for (const pass of web_o) pass(req, res, proxyRes, options);
  17169. if (!res.finished) {
  17170. proxyRes.on("end", () => {
  17171. server?.emit("end", req, res, proxyRes);
  17172. });
  17173. if (!options.selfHandleResponse) proxyRes.pipe(res);
  17174. } else server?.emit("end", req, res, proxyRes);
  17175. });
  17176. }
  17177. async function stream2(req, res, options, _, server, cb) {
  17178. const handleError = (err, target) => {
  17179. const e = err;
  17180. if (e.code === void 0 && e.cause?.code) e.code = e.cause.code;
  17181. if (cb) cb(err, req, res, target);
  17182. else server.emit("error", err, req, res, target);
  17183. };
  17184. req.on("error", (err) => {
  17185. if (req.socket.destroyed && err.code === "ECONNRESET") {
  17186. const target = options.target || options.forward;
  17187. if (target) server.emit("econnreset", err, req, res, target);
  17188. return;
  17189. }
  17190. handleError(err);
  17191. });
  17192. const customFetch = options.fetch || fetch;
  17193. const fetchOptions = options.fetchOptions ?? {};
  17194. const prepareRequest = (outgoing) => {
  17195. const requestOptions = {
  17196. method: outgoing.method,
  17197. ...fetchOptions.requestOptions
  17198. };
  17199. const headers = new Headers(fetchOptions.requestOptions?.headers);
  17200. if (!fetchOptions.requestOptions?.headers && outgoing.headers) {
  17201. for (const [key, value] of Object.entries(outgoing.headers)) if (typeof key === "string") {
  17202. if (Array.isArray(value)) for (const v of value) headers.append(key, v);
  17203. else if (value != null) headers.append(key, value);
  17204. }
  17205. }
  17206. if (options.auth) headers.set("authorization", `Basic ${Buffer.from(options.auth).toString("base64")}`);
  17207. if (options.proxyTimeout) requestOptions.signal = AbortSignal.timeout(options.proxyTimeout);
  17208. requestOptions.headers = headers;
  17209. if (options.buffer) requestOptions.body = options.buffer;
  17210. else if (req.method !== "GET" && req.method !== "HEAD") {
  17211. requestOptions.body = req;
  17212. requestOptions.duplex = "half";
  17213. }
  17214. return requestOptions;
  17215. };
  17216. if (options.forward) {
  17217. const outgoingOptions = common.setupOutgoing(options.ssl || {}, options, req, "forward");
  17218. const requestOptions = prepareRequest(outgoingOptions);
  17219. let targetUrl = new URL(outgoingOptions.url).origin + outgoingOptions.path;
  17220. if (targetUrl.startsWith("ws")) targetUrl = targetUrl.replace("ws", "http");
  17221. if (fetchOptions.onBeforeRequest) try {
  17222. await fetchOptions.onBeforeRequest(requestOptions, req, res, options);
  17223. } catch (err) {
  17224. handleError(err, options.forward);
  17225. return;
  17226. }
  17227. try {
  17228. const result = await customFetch(targetUrl, requestOptions);
  17229. if (fetchOptions.onAfterResponse) try {
  17230. await fetchOptions.onAfterResponse(result, req, res, options);
  17231. } catch (err) {
  17232. handleError(err, options.forward);
  17233. return;
  17234. }
  17235. } catch (err) {
  17236. handleError(err, options.forward);
  17237. }
  17238. if (!options.target) return res.end();
  17239. }
  17240. const outgoingOptions = common.setupOutgoing(options.ssl || {}, options, req);
  17241. const requestOptions = prepareRequest(outgoingOptions);
  17242. let targetUrl = new URL(outgoingOptions.url).origin + outgoingOptions.path;
  17243. if (targetUrl.startsWith("ws")) targetUrl = targetUrl.replace("ws", "http");
  17244. if (fetchOptions.onBeforeRequest) try {
  17245. await fetchOptions.onBeforeRequest(requestOptions, req, res, options);
  17246. } catch (err) {
  17247. handleError(err, options.target);
  17248. return;
  17249. }
  17250. try {
  17251. const response = await customFetch(targetUrl, requestOptions);
  17252. if (fetchOptions.onAfterResponse) try {
  17253. await fetchOptions.onAfterResponse(response, req, res, options);
  17254. } catch (err) {
  17255. handleError(err, options.target);
  17256. return;
  17257. }
  17258. const fakeProxyRes = {
  17259. statusCode: response.status,
  17260. statusMessage: response.statusText,
  17261. headers: Object.fromEntries(response.headers.entries()),
  17262. rawHeaders: Object.entries(response.headers).flatMap(([key, value]) => {
  17263. if (Array.isArray(value)) return value.flatMap((v) => v != null ? [key, v] : []);
  17264. return value != null ? [key, value] : [];
  17265. })
  17266. };
  17267. server?.emit("proxyRes", fakeProxyRes, req, res);
  17268. if (!res.headersSent && !options.selfHandleResponse) for (const pass of web_o) pass(req, res, fakeProxyRes, options);
  17269. if (!res.writableEnded) {
  17270. const nodeStream = response.body ? node_stream_1.Readable.from(response.body) : null;
  17271. if (nodeStream) {
  17272. nodeStream.on("error", (err) => {
  17273. handleError(err, options.target);
  17274. });
  17275. nodeStream.on("end", () => {
  17276. server?.emit("end", req, res, fakeProxyRes);
  17277. });
  17278. if (!options.selfHandleResponse) nodeStream.pipe(res, { end: true });
  17279. else nodeStream.resume();
  17280. } else server?.emit("end", req, res, fakeProxyRes);
  17281. } else server?.emit("end", req, res, fakeProxyRes);
  17282. } catch (err) {
  17283. handleError(err, options.target);
  17284. }
  17285. }
  17286. exports.WEB_PASSES = {
  17287. deleteLength,
  17288. timeout,
  17289. XHeaders,
  17290. stream
  17291. };
  17292. }));
  17293. //#endregion
  17294. //#region ../../node_modules/.pnpm/http-proxy-3@1.23.2_ms@2.1.3/node_modules/http-proxy-3/dist/lib/http-proxy/passes/ws-incoming.js
  17295. var require_ws_incoming = /* @__PURE__ */ __commonJSMin(((exports) => {
  17296. var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o, m, k, k2) {
  17297. if (k2 === void 0) k2 = k;
  17298. var desc = Object.getOwnPropertyDescriptor(m, k);
  17299. if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) desc = {
  17300. enumerable: true,
  17301. get: function() {
  17302. return m[k];
  17303. }
  17304. };
  17305. Object.defineProperty(o, k2, desc);
  17306. }) : (function(o, m, k, k2) {
  17307. if (k2 === void 0) k2 = k;
  17308. o[k2] = m[k];
  17309. }));
  17310. var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o, v) {
  17311. Object.defineProperty(o, "default", {
  17312. enumerable: true,
  17313. value: v
  17314. });
  17315. }) : function(o, v) {
  17316. o["default"] = v;
  17317. });
  17318. var __importStar = exports && exports.__importStar || (function() {
  17319. var ownKeys = function(o) {
  17320. ownKeys = Object.getOwnPropertyNames || function(o) {
  17321. var ar = [];
  17322. for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
  17323. return ar;
  17324. };
  17325. return ownKeys(o);
  17326. };
  17327. return function(mod) {
  17328. if (mod && mod.__esModule) return mod;
  17329. var result = {};
  17330. if (mod != null) {
  17331. for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
  17332. }
  17333. __setModuleDefault(result, mod);
  17334. return result;
  17335. };
  17336. })();
  17337. var __importDefault = exports && exports.__importDefault || function(mod) {
  17338. return mod && mod.__esModule ? mod : { "default": mod };
  17339. };
  17340. Object.defineProperty(exports, "__esModule", { value: true });
  17341. exports.WS_PASSES = void 0;
  17342. exports.numOpenSockets = numOpenSockets;
  17343. exports.checkMethodAndHeader = checkMethodAndHeader;
  17344. exports.XHeaders = XHeaders;
  17345. exports.stream = stream;
  17346. const http$1 = __importStar(__require("node:http"));
  17347. const https = __importStar(__require("node:https"));
  17348. const common = __importStar(require_common());
  17349. const web_outgoing_1 = require_web_outgoing();
  17350. const log = (0, __importDefault((init_node(), __toCommonJS(node_exports))).default)("http-proxy-3:ws-incoming");
  17351. const web_o = Object.values(web_outgoing_1.OUTGOING_PASSES);
  17352. function createSocketCounter(name) {
  17353. let sockets = /* @__PURE__ */ new Set();
  17354. return ({ add, rm } = {}) => {
  17355. if (add) {
  17356. if (!add.id) add.id = Math.random();
  17357. if (!sockets.has(add.id)) sockets.add(add.id);
  17358. }
  17359. if (rm) {
  17360. if (!rm.id) rm.id = Math.random();
  17361. if (sockets.has(rm.id)) sockets.delete(rm.id);
  17362. }
  17363. log("socket counter:", { [name]: sockets.size }, add ? "add" : rm ? "rm" : "");
  17364. return sockets.size;
  17365. };
  17366. }
  17367. const socketCounter = createSocketCounter("socket");
  17368. const proxySocketCounter = createSocketCounter("proxySocket");
  17369. var MockResponse = class {
  17370. constructor() {
  17371. this.headers = {};
  17372. this.statusCode = 200;
  17373. this.statusMessage = "";
  17374. }
  17375. setHeader(key, value) {
  17376. this.headers[key] = value;
  17377. return this;
  17378. }
  17379. };
  17380. function numOpenSockets() {
  17381. return socketCounter() + proxySocketCounter();
  17382. }
  17383. function checkMethodAndHeader(req, socket) {
  17384. log("websocket: checkMethodAndHeader");
  17385. if (req.method !== "GET" || !req.headers.upgrade) {
  17386. socket.destroy();
  17387. return true;
  17388. }
  17389. if (req.headers.upgrade.toLowerCase() !== "websocket") {
  17390. socket.destroy();
  17391. return true;
  17392. }
  17393. }
  17394. function XHeaders(req, _socket, options) {
  17395. if (!options.xfwd) return;
  17396. log("websocket: XHeaders");
  17397. const values = {
  17398. for: req.connection.remoteAddress || req.socket.remoteAddress,
  17399. port: common.getPort(req),
  17400. proto: common.hasEncryptedConnection(req) ? "wss" : "ws"
  17401. };
  17402. for (const header of [
  17403. "for",
  17404. "port",
  17405. "proto"
  17406. ]) req.headers["x-forwarded-" + header] = (req.headers["x-forwarded-" + header] || "") + (req.headers["x-forwarded-" + header] ? "," : "") + values[header];
  17407. }
  17408. function stream(req, socket, options, head, server, cb) {
  17409. log("websocket: new stream");
  17410. const proxySockets = [];
  17411. socketCounter({ add: socket });
  17412. const cleanUpProxySockets = () => {
  17413. for (const p of proxySockets) p.end();
  17414. };
  17415. socket.on("close", () => {
  17416. socketCounter({ rm: socket });
  17417. cleanUpProxySockets();
  17418. });
  17419. socket.on("error", cleanUpProxySockets);
  17420. const createHttpHeader = (line, headers) => {
  17421. return Object.keys(headers).reduce((head, key) => {
  17422. const value = headers[key];
  17423. if (!Array.isArray(value)) {
  17424. head.push(key + ": " + value);
  17425. return head;
  17426. }
  17427. for (let i = 0; i < value.length; i++) head.push(key + ": " + value[i]);
  17428. return head;
  17429. }, [line]).join("\r\n") + "\r\n\r\n";
  17430. };
  17431. common.setupSocket(socket);
  17432. if (head && head.length) socket.unshift(head);
  17433. const proto = common.isSSL.test(options.target.protocol) ? https : http$1;
  17434. const outgoingOptions = common.setupOutgoing(options.ssl || {}, options, req);
  17435. const proxyReq = proto.request(outgoingOptions);
  17436. if (server) server.emit("proxyReqWs", proxyReq, req, socket, options, head);
  17437. proxyReq.on("error", onOutgoingError);
  17438. proxyReq.on("upgrade", (proxyRes, proxySocket, proxyHead) => {
  17439. log("upgrade");
  17440. proxySocketCounter({ add: proxySocket });
  17441. proxySockets.push(proxySocket);
  17442. proxySocket.on("close", () => {
  17443. proxySocketCounter({ rm: proxySocket });
  17444. });
  17445. proxySocket.on("error", onOutgoingError);
  17446. proxySocket.on("end", () => {
  17447. server.emit("close", proxyRes, proxySocket, proxyHead);
  17448. });
  17449. proxySocket.on("close", () => {
  17450. socket.end();
  17451. });
  17452. common.setupSocket(proxySocket);
  17453. if (proxyHead && proxyHead.length) proxySocket.unshift(proxyHead);
  17454. socket.write(createHttpHeader("HTTP/1.1 101 Switching Protocols", proxyRes.headers));
  17455. proxySocket.pipe(socket).pipe(proxySocket);
  17456. server.emit("open", proxySocket);
  17457. });
  17458. function onOutgoingError(err) {
  17459. if (cb) cb(err, req, socket);
  17460. else server.emit("error", err, req, socket);
  17461. socket.destroySoon();
  17462. }
  17463. proxyReq.on("response", (proxyRes) => {
  17464. log("got non-ws HTTP response", {
  17465. statusCode: proxyRes.statusCode,
  17466. statusMessage: proxyRes.statusMessage
  17467. });
  17468. const res = new MockResponse();
  17469. for (const pass of web_o) pass(req, res, proxyRes, options);
  17470. let writeChunk = (chunk) => {
  17471. socket.write(chunk);
  17472. };
  17473. if (req.httpVersion === "1.1" && proxyRes.headers["content-length"] === void 0) {
  17474. res.headers["transfer-encoding"] = "chunked";
  17475. writeChunk = (chunk) => {
  17476. socket.write(chunk.length.toString(16));
  17477. socket.write("\r\n");
  17478. socket.write(chunk);
  17479. socket.write("\r\n");
  17480. };
  17481. }
  17482. const proxyHead = createHttpHeader(`HTTP/${req.httpVersion} ${proxyRes.statusCode} ${proxyRes.statusMessage}`, res.headers);
  17483. if (!socket.destroyed) {
  17484. socket.write(proxyHead);
  17485. proxyRes.on("data", (chunk) => {
  17486. writeChunk(chunk);
  17487. });
  17488. proxyRes.on("end", () => {
  17489. writeChunk("");
  17490. socket.destroySoon();
  17491. });
  17492. } else proxyRes.resume();
  17493. });
  17494. proxyReq.end();
  17495. }
  17496. exports.WS_PASSES = {
  17497. checkMethodAndHeader,
  17498. XHeaders,
  17499. stream
  17500. };
  17501. }));
  17502. //#endregion
  17503. //#region ../../node_modules/.pnpm/http-proxy-3@1.23.2_ms@2.1.3/node_modules/http-proxy-3/dist/lib/http-proxy/index.js
  17504. var require_http_proxy = /* @__PURE__ */ __commonJSMin(((exports) => {
  17505. var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o, m, k, k2) {
  17506. if (k2 === void 0) k2 = k;
  17507. var desc = Object.getOwnPropertyDescriptor(m, k);
  17508. if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) desc = {
  17509. enumerable: true,
  17510. get: function() {
  17511. return m[k];
  17512. }
  17513. };
  17514. Object.defineProperty(o, k2, desc);
  17515. }) : (function(o, m, k, k2) {
  17516. if (k2 === void 0) k2 = k;
  17517. o[k2] = m[k];
  17518. }));
  17519. var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o, v) {
  17520. Object.defineProperty(o, "default", {
  17521. enumerable: true,
  17522. value: v
  17523. });
  17524. }) : function(o, v) {
  17525. o["default"] = v;
  17526. });
  17527. var __importStar = exports && exports.__importStar || (function() {
  17528. var ownKeys = function(o) {
  17529. ownKeys = Object.getOwnPropertyNames || function(o) {
  17530. var ar = [];
  17531. for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
  17532. return ar;
  17533. };
  17534. return ownKeys(o);
  17535. };
  17536. return function(mod) {
  17537. if (mod && mod.__esModule) return mod;
  17538. var result = {};
  17539. if (mod != null) {
  17540. for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
  17541. }
  17542. __setModuleDefault(result, mod);
  17543. return result;
  17544. };
  17545. })();
  17546. var __importDefault = exports && exports.__importDefault || function(mod) {
  17547. return mod && mod.__esModule ? mod : { "default": mod };
  17548. };
  17549. Object.defineProperty(exports, "__esModule", { value: true });
  17550. exports.ProxyServer = void 0;
  17551. const http = __importStar(__require("node:http"));
  17552. const http2 = __importStar(__require("node:http2"));
  17553. const web_incoming_1 = require_web_incoming();
  17554. const ws_incoming_1 = require_ws_incoming();
  17555. const node_events_1 = __require("node:events");
  17556. const debug_1 = __importDefault((init_node(), __toCommonJS(node_exports)));
  17557. const common_1 = require_common();
  17558. const log = (0, debug_1.default)("http-proxy-3");
  17559. exports.ProxyServer = class ProxyServer extends node_events_1.EventEmitter {
  17560. /**
  17561. * Creates the proxy server with specified options.
  17562. * @param options - Config object passed to the proxy
  17563. */
  17564. constructor(options = {}) {
  17565. super();
  17566. this.createRightProxy = (type) => {
  17567. log("createRightProxy", { type });
  17568. return (options) => {
  17569. return (...args) => {
  17570. const req = args[0];
  17571. log("proxy: ", {
  17572. type,
  17573. path: req.url
  17574. });
  17575. const res = args[1];
  17576. const passes = type === "ws" ? this.wsPasses : this.webPasses;
  17577. if (type == "ws") res.on("error", (err) => {
  17578. this.emit("error", err, req, res);
  17579. });
  17580. let counter = args.length - 1;
  17581. let head;
  17582. let cb;
  17583. if (typeof args[counter] === "function") {
  17584. cb = args[counter];
  17585. counter--;
  17586. }
  17587. let requestOptions;
  17588. if (!(args[counter] instanceof Buffer) && args[counter] !== res) {
  17589. requestOptions = {
  17590. ...options,
  17591. ...args[counter]
  17592. };
  17593. counter--;
  17594. } else requestOptions = { ...options };
  17595. if (args[counter] instanceof Buffer) head = args[counter];
  17596. for (const e of ["target", "forward"]) if (typeof requestOptions[e] === "string") requestOptions[e] = (0, common_1.toURL)(requestOptions[e]);
  17597. if (!requestOptions.target && !requestOptions.forward) {
  17598. this.emit("error", /* @__PURE__ */ new Error("Must set target or forward"), req, res);
  17599. return;
  17600. }
  17601. for (const pass of passes)
  17602. /**
  17603. * Call of passes functions
  17604. * pass(req, res, options, head)
  17605. *
  17606. * In WebSockets case, the `res` variable
  17607. * refer to the connection socket
  17608. * pass(req, socket, options, head)
  17609. */
  17610. if (pass(req, res, requestOptions, head, this, cb)) break;
  17611. };
  17612. };
  17613. };
  17614. this.onError = (err) => {
  17615. if (this.listeners("error").length === 1) throw err;
  17616. };
  17617. /**
  17618. * A function that wraps the object in a webserver, for your convenience
  17619. * @param port - Port to listen on
  17620. * @param hostname - The hostname to listen on
  17621. */
  17622. this.listen = (port, hostname) => {
  17623. log("listen", {
  17624. port,
  17625. hostname
  17626. });
  17627. const requestListener = (req, res) => {
  17628. this.web(req, res);
  17629. };
  17630. this._server = this.options.ssl ? http2.createSecureServer({
  17631. ...this.options.ssl,
  17632. allowHTTP1: true
  17633. }, requestListener) : http.createServer(requestListener);
  17634. if (this.options.ws) this._server.on("upgrade", (req, socket, head) => {
  17635. this.ws(req, socket, head);
  17636. });
  17637. this._server.listen(port, hostname);
  17638. return this;
  17639. };
  17640. this.address = () => {
  17641. return this._server?.address();
  17642. };
  17643. /**
  17644. * A function that closes the inner webserver and stops listening on given port
  17645. */
  17646. this.close = (cb) => {
  17647. if (this._server == null) {
  17648. cb?.();
  17649. return;
  17650. }
  17651. this._server.close((err) => {
  17652. this._server = null;
  17653. cb?.(err);
  17654. });
  17655. };
  17656. this.before = (type, passName, cb) => {
  17657. if (type !== "ws" && type !== "web") throw new Error("type must be `web` or `ws`");
  17658. const passes = type === "ws" ? this.wsPasses : this.webPasses;
  17659. let i = false;
  17660. passes.forEach((v, idx) => {
  17661. if (v.name === passName) i = idx;
  17662. });
  17663. if (i === false) throw new Error("No such pass");
  17664. passes.splice(i, 0, cb);
  17665. };
  17666. this.after = (type, passName, cb) => {
  17667. if (type !== "ws" && type !== "web") throw new Error("type must be `web` or `ws`");
  17668. const passes = type === "ws" ? this.wsPasses : this.webPasses;
  17669. let i = false;
  17670. passes.forEach((v, idx) => {
  17671. if (v.name === passName) i = idx;
  17672. });
  17673. if (i === false) throw new Error("No such pass");
  17674. passes.splice(i++, 0, cb);
  17675. };
  17676. log("creating a ProxyServer", options);
  17677. options.prependPath = options.prependPath !== false;
  17678. this.options = options;
  17679. this.web = this.createRightProxy("web")(options);
  17680. this.ws = this.createRightProxy("ws")(options);
  17681. this.webPasses = Object.values(web_incoming_1.WEB_PASSES);
  17682. this.wsPasses = Object.values(ws_incoming_1.WS_PASSES);
  17683. this.on("error", this.onError);
  17684. }
  17685. /**
  17686. * Creates the proxy server with specified options.
  17687. * @param options Config object passed to the proxy
  17688. * @returns Proxy object with handlers for `ws` and `web` requests
  17689. */
  17690. static createProxyServer(options) {
  17691. return new ProxyServer(options);
  17692. }
  17693. /**
  17694. * Creates the proxy server with specified options.
  17695. * @param options Config object passed to the proxy
  17696. * @returns Proxy object with handlers for `ws` and `web` requests
  17697. */
  17698. static createServer(options) {
  17699. return new ProxyServer(options);
  17700. }
  17701. /**
  17702. * Creates the proxy server with specified options.
  17703. * @param options Config object passed to the proxy
  17704. * @returns Proxy object with handlers for `ws` and `web` requests
  17705. */
  17706. static createProxy(options) {
  17707. return new ProxyServer(options);
  17708. }
  17709. };
  17710. }));
  17711. //#endregion
  17712. //#region src/node/server/middlewares/proxy.ts
  17713. var import_lib$1 = /* @__PURE__ */ __toESM((/* @__PURE__ */ __commonJSMin(((exports) => {
  17714. Object.defineProperty(exports, "__esModule", { value: true });
  17715. exports.numOpenSockets = exports.ProxyServer = void 0;
  17716. exports.createProxyServer = createProxyServer;
  17717. const index_1 = require_http_proxy();
  17718. Object.defineProperty(exports, "ProxyServer", {
  17719. enumerable: true,
  17720. get: function() {
  17721. return index_1.ProxyServer;
  17722. }
  17723. });
  17724. var ws_incoming_1 = require_ws_incoming();
  17725. Object.defineProperty(exports, "numOpenSockets", {
  17726. enumerable: true,
  17727. get: function() {
  17728. return ws_incoming_1.numOpenSockets;
  17729. }
  17730. });
  17731. /**
  17732. * Creates the proxy server.
  17733. *
  17734. * Examples:
  17735. *
  17736. * httpProxy.createProxyServer({ .. }, 8000)
  17737. * // => '{ web: [Function], ws: [Function] ... }'
  17738. *
  17739. * @param {Object} Options Config object passed to the proxy
  17740. *
  17741. * @return {Object} Proxy Proxy object with handlers for `ws` and `web` requests
  17742. *
  17743. * @api public
  17744. */
  17745. function createProxyServer(options = {}) {
  17746. return new index_1.ProxyServer(options);
  17747. }
  17748. })))(), 1);
  17749. const debug$11 = createDebugger("vite:proxy");
  17750. const rewriteOriginHeader = (proxyReq, options, config) => {
  17751. if (options.rewriteWsOrigin) {
  17752. const { target } = options;
  17753. if (proxyReq.headersSent) {
  17754. config.logger.warn(import_picocolors.default.yellow(`Unable to rewrite Origin header as headers are already sent.`));
  17755. return;
  17756. }
  17757. if (proxyReq.getHeader("origin") && target) {
  17758. const changedOrigin = typeof target === "object" ? `${target.protocol ?? "http:"}//${target.host}` : target;
  17759. proxyReq.setHeader("origin", changedOrigin);
  17760. }
  17761. }
  17762. };
  17763. function proxyMiddleware(httpServer, options, config) {
  17764. const proxies = {};
  17765. Object.keys(options).forEach((context) => {
  17766. let opts = options[context];
  17767. if (!opts) return;
  17768. if (typeof opts === "string") opts = {
  17769. target: opts,
  17770. changeOrigin: true
  17771. };
  17772. const proxy = import_lib$1.createProxyServer(opts);
  17773. if (opts.configure) opts.configure(proxy, opts);
  17774. proxy.on("error", (err, _req, res) => {
  17775. if ("req" in res) {
  17776. config.logger.error(`${import_picocolors.default.red(`http proxy error: ${res.req.url}`)}\n${err.stack}`, {
  17777. timestamp: true,
  17778. error: err
  17779. });
  17780. if (!res.headersSent && !res.writableEnded) res.writeHead(502, { "Content-Type": "text/plain" }).end();
  17781. } else {
  17782. config.logger.error(`${import_picocolors.default.red(`ws proxy error:`)}\n${err.stack}`, {
  17783. timestamp: true,
  17784. error: err
  17785. });
  17786. res.end();
  17787. }
  17788. });
  17789. proxy.on("proxyReqWs", (proxyReq, _req, socket, options) => {
  17790. rewriteOriginHeader(proxyReq, options, config);
  17791. socket.on("error", (err) => {
  17792. config.logger.error(`${import_picocolors.default.red(`ws proxy socket error:`)}\n${err.stack}`, {
  17793. timestamp: true,
  17794. error: err
  17795. });
  17796. });
  17797. });
  17798. proxies[context] = [proxy, { ...opts }];
  17799. });
  17800. if (httpServer) httpServer.on("upgrade", async (req, socket, head) => {
  17801. const url = req.url;
  17802. for (const context in proxies) if (doesProxyContextMatchUrl(context, url)) {
  17803. const [proxy, opts] = proxies[context];
  17804. if (opts.ws || opts.target?.toString().startsWith("ws:") || opts.target?.toString().startsWith("wss:")) {
  17805. if (opts.bypass) try {
  17806. const bypassResult = await opts.bypass(req, void 0, opts);
  17807. if (typeof bypassResult === "string") {
  17808. debug$11?.(`bypass: ${req.url} -> ${bypassResult}`);
  17809. req.url = bypassResult;
  17810. return;
  17811. }
  17812. if (bypassResult === false) {
  17813. debug$11?.(`bypass: ${req.url} -> 404`);
  17814. socket.end("HTTP/1.1 404 Not Found\r\n\r\n", "");
  17815. return;
  17816. }
  17817. } catch (err) {
  17818. config.logger.error(`${import_picocolors.default.red(`ws proxy bypass error:`)}\n${err.stack}`, {
  17819. timestamp: true,
  17820. error: err
  17821. });
  17822. return;
  17823. }
  17824. if (opts.rewrite) req.url = opts.rewrite(url);
  17825. debug$11?.(`${req.url} -> ws ${opts.target}`);
  17826. proxy.ws(req, socket, head);
  17827. return;
  17828. }
  17829. }
  17830. });
  17831. return async function viteProxyMiddleware(req, res, next) {
  17832. const url = req.url;
  17833. for (const context in proxies) if (doesProxyContextMatchUrl(context, url)) {
  17834. const [proxy, opts] = proxies[context];
  17835. const options = {};
  17836. if (opts.bypass) try {
  17837. const bypassResult = await opts.bypass(req, res, opts);
  17838. if (typeof bypassResult === "string") {
  17839. debug$11?.(`bypass: ${req.url} -> ${bypassResult}`);
  17840. req.url = bypassResult;
  17841. if (res.writableEnded) return;
  17842. return next();
  17843. }
  17844. if (bypassResult === false) {
  17845. debug$11?.(`bypass: ${req.url} -> 404`);
  17846. res.statusCode = 404;
  17847. return res.end();
  17848. }
  17849. } catch (e) {
  17850. debug$11?.(`bypass: ${req.url} -> ${e}`);
  17851. return next(e);
  17852. }
  17853. debug$11?.(`${req.url} -> ${opts.target || opts.forward}`);
  17854. if (opts.rewrite) req.url = opts.rewrite(req.url);
  17855. proxy.web(req, res, options);
  17856. return;
  17857. }
  17858. next();
  17859. };
  17860. }
  17861. function doesProxyContextMatchUrl(context, url) {
  17862. return context[0] === "^" && new RegExp(context).test(url) || url.startsWith(context);
  17863. }
  17864. //#endregion
  17865. //#region ../../node_modules/.pnpm/etag@1.8.1/node_modules/etag/index.js
  17866. /*!
  17867. * etag
  17868. * Copyright(c) 2014-2016 Douglas Christopher Wilson
  17869. * MIT Licensed
  17870. */
  17871. var require_etag = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  17872. /**
  17873. * Module exports.
  17874. * @public
  17875. */
  17876. module.exports = etag;
  17877. /**
  17878. * Module dependencies.
  17879. * @private
  17880. */
  17881. var crypto$1 = __require("crypto");
  17882. var Stats = __require("fs").Stats;
  17883. /**
  17884. * Module variables.
  17885. * @private
  17886. */
  17887. var toString = Object.prototype.toString;
  17888. /**
  17889. * Generate an entity tag.
  17890. *
  17891. * @param {Buffer|string} entity
  17892. * @return {string}
  17893. * @private
  17894. */
  17895. function entitytag(entity) {
  17896. if (entity.length === 0) return "\"0-2jmj7l5rSw0yVb/vlWAYkK/YBwk\"";
  17897. var hash = crypto$1.createHash("sha1").update(entity, "utf8").digest("base64").substring(0, 27);
  17898. return "\"" + (typeof entity === "string" ? Buffer.byteLength(entity, "utf8") : entity.length).toString(16) + "-" + hash + "\"";
  17899. }
  17900. /**
  17901. * Create a simple ETag.
  17902. *
  17903. * @param {string|Buffer|Stats} entity
  17904. * @param {object} [options]
  17905. * @param {boolean} [options.weak]
  17906. * @return {String}
  17907. * @public
  17908. */
  17909. function etag(entity, options) {
  17910. if (entity == null) throw new TypeError("argument entity is required");
  17911. var isStats = isstats(entity);
  17912. var weak = options && typeof options.weak === "boolean" ? options.weak : isStats;
  17913. if (!isStats && typeof entity !== "string" && !Buffer.isBuffer(entity)) throw new TypeError("argument entity must be string, Buffer, or fs.Stats");
  17914. var tag = isStats ? stattag(entity) : entitytag(entity);
  17915. return weak ? "W/" + tag : tag;
  17916. }
  17917. /**
  17918. * Determine if object is a Stats object.
  17919. *
  17920. * @param {object} obj
  17921. * @return {boolean}
  17922. * @api private
  17923. */
  17924. function isstats(obj) {
  17925. if (typeof Stats === "function" && obj instanceof Stats) return true;
  17926. return obj && typeof obj === "object" && "ctime" in obj && toString.call(obj.ctime) === "[object Date]" && "mtime" in obj && toString.call(obj.mtime) === "[object Date]" && "ino" in obj && typeof obj.ino === "number" && "size" in obj && typeof obj.size === "number";
  17927. }
  17928. /**
  17929. * Generate a tag for a stat.
  17930. *
  17931. * @param {object} stat
  17932. * @return {string}
  17933. * @private
  17934. */
  17935. function stattag(stat) {
  17936. var mtime = stat.mtime.getTime().toString(16);
  17937. return "\"" + stat.size.toString(16) + "-" + mtime + "\"";
  17938. }
  17939. }));
  17940. //#endregion
  17941. //#region src/node/environment.ts
  17942. /**
  17943. * Creates a function that hides the complexities of a WeakMap with an initial value
  17944. * to implement object metadata. Used by plugins to implement cross hooks per
  17945. * environment metadata
  17946. *
  17947. * @experimental
  17948. */
  17949. function perEnvironmentState(initial) {
  17950. const stateMap = /* @__PURE__ */ new WeakMap();
  17951. return function(context) {
  17952. const { environment } = context;
  17953. let state = stateMap.get(environment);
  17954. if (!state) {
  17955. state = initial(environment);
  17956. stateMap.set(environment, state);
  17957. }
  17958. return state;
  17959. };
  17960. }
  17961. //#endregion
  17962. //#region ../../node_modules/.pnpm/strip-literal@3.1.0/node_modules/strip-literal/dist/index.mjs
  17963. var import_js_tokens = /* @__PURE__ */ __toESM((/* @__PURE__ */ __commonJSMin(((exports, module) => {
  17964. var HashbangComment, Identifier, JSXIdentifier, JSXPunctuator, JSXString, JSXText, KeywordsWithExpressionAfter, KeywordsWithNoLineTerminatorAfter, LineTerminatorSequence, MultiLineComment, Newline, NumericLiteral, Punctuator, RegularExpressionLiteral = /\/(?![*\/])(?:\[(?:[^\]\\\n\r\u2028\u2029]+|\\.)*\]?|[^\/[\\\n\r\u2028\u2029]+|\\.)*(\/[$_\u200C\u200D\p{ID_Continue}]*|\\)?/uy, SingleLineComment, StringLiteral, Template, TokensNotPrecedingObjectLiteral, TokensPrecedingExpression, WhiteSpace;
  17965. Punctuator = /--|\+\+|=>|\.{3}|\??\.(?!\d)|(?:&&|\|\||\?\?|[+\-%&|^]|\*{1,2}|<{1,2}|>{1,3}|!=?|={1,2}|\/(?![\/*]))=?|[?~,:;[\](){}]/y;
  17966. Identifier = /(\x23?)(?=[$_\p{ID_Start}\\])(?:[$_\u200C\u200D\p{ID_Continue}]+|\\u[\da-fA-F]{4}|\\u\{[\da-fA-F]+\})+/uy;
  17967. StringLiteral = /(['"])(?:[^'"\\\n\r]+|(?!\1)['"]|\\(?:\r\n|[^]))*(\1)?/y;
  17968. NumericLiteral = /(?:0[xX][\da-fA-F](?:_?[\da-fA-F])*|0[oO][0-7](?:_?[0-7])*|0[bB][01](?:_?[01])*)n?|0n|[1-9](?:_?\d)*n|(?:(?:0(?!\d)|0\d*[89]\d*|[1-9](?:_?\d)*)(?:\.(?:\d(?:_?\d)*)?)?|\.\d(?:_?\d)*)(?:[eE][+-]?\d(?:_?\d)*)?|0[0-7]+/y;
  17969. Template = /[`}](?:[^`\\$]+|\\[^]|\$(?!\{))*(`|\$\{)?/y;
  17970. WhiteSpace = /[\t\v\f\ufeff\p{Zs}]+/uy;
  17971. LineTerminatorSequence = /\r?\n|[\r\u2028\u2029]/y;
  17972. MultiLineComment = /\/\*(?:[^*]+|\*(?!\/))*(\*\/)?/y;
  17973. SingleLineComment = /\/\/.*/y;
  17974. HashbangComment = /^#!.*/;
  17975. JSXPunctuator = /[<>.:={}]|\/(?![\/*])/y;
  17976. JSXIdentifier = /[$_\p{ID_Start}][$_\u200C\u200D\p{ID_Continue}-]*/uy;
  17977. JSXString = /(['"])(?:[^'"]+|(?!\1)['"])*(\1)?/y;
  17978. JSXText = /[^<>{}]+/y;
  17979. TokensPrecedingExpression = /^(?:[\/+-]|\.{3}|\?(?:InterpolationIn(?:JSX|Template)|NoLineTerminatorHere|NonExpressionParenEnd|UnaryIncDec))?$|[{}([,;<>=*%&|^!~?:]$/;
  17980. TokensNotPrecedingObjectLiteral = /^(?:=>|[;\]){}]|else|\?(?:NoLineTerminatorHere|NonExpressionParenEnd))?$/;
  17981. KeywordsWithExpressionAfter = /^(?:await|case|default|delete|do|else|instanceof|new|return|throw|typeof|void|yield)$/;
  17982. KeywordsWithNoLineTerminatorAfter = /^(?:return|throw|yield)$/;
  17983. Newline = RegExp(LineTerminatorSequence.source);
  17984. module.exports = function* (input, { jsx = false } = {}) {
  17985. var braces, firstCodePoint, isExpression, lastIndex, lastSignificantToken, length, match, mode, nextLastIndex, nextLastSignificantToken, parenNesting, postfixIncDec, punctuator, stack;
  17986. ({length} = input);
  17987. lastIndex = 0;
  17988. lastSignificantToken = "";
  17989. stack = [{ tag: "JS" }];
  17990. braces = [];
  17991. parenNesting = 0;
  17992. postfixIncDec = false;
  17993. if (match = HashbangComment.exec(input)) {
  17994. yield {
  17995. type: "HashbangComment",
  17996. value: match[0]
  17997. };
  17998. lastIndex = match[0].length;
  17999. }
  18000. while (lastIndex < length) {
  18001. mode = stack[stack.length - 1];
  18002. switch (mode.tag) {
  18003. case "JS":
  18004. case "JSNonExpressionParen":
  18005. case "InterpolationInTemplate":
  18006. case "InterpolationInJSX":
  18007. if (input[lastIndex] === "/" && (TokensPrecedingExpression.test(lastSignificantToken) || KeywordsWithExpressionAfter.test(lastSignificantToken))) {
  18008. RegularExpressionLiteral.lastIndex = lastIndex;
  18009. if (match = RegularExpressionLiteral.exec(input)) {
  18010. lastIndex = RegularExpressionLiteral.lastIndex;
  18011. lastSignificantToken = match[0];
  18012. postfixIncDec = true;
  18013. yield {
  18014. type: "RegularExpressionLiteral",
  18015. value: match[0],
  18016. closed: match[1] !== void 0 && match[1] !== "\\"
  18017. };
  18018. continue;
  18019. }
  18020. }
  18021. Punctuator.lastIndex = lastIndex;
  18022. if (match = Punctuator.exec(input)) {
  18023. punctuator = match[0];
  18024. nextLastIndex = Punctuator.lastIndex;
  18025. nextLastSignificantToken = punctuator;
  18026. switch (punctuator) {
  18027. case "(":
  18028. if (lastSignificantToken === "?NonExpressionParenKeyword") stack.push({
  18029. tag: "JSNonExpressionParen",
  18030. nesting: parenNesting
  18031. });
  18032. parenNesting++;
  18033. postfixIncDec = false;
  18034. break;
  18035. case ")":
  18036. parenNesting--;
  18037. postfixIncDec = true;
  18038. if (mode.tag === "JSNonExpressionParen" && parenNesting === mode.nesting) {
  18039. stack.pop();
  18040. nextLastSignificantToken = "?NonExpressionParenEnd";
  18041. postfixIncDec = false;
  18042. }
  18043. break;
  18044. case "{":
  18045. Punctuator.lastIndex = 0;
  18046. isExpression = !TokensNotPrecedingObjectLiteral.test(lastSignificantToken) && (TokensPrecedingExpression.test(lastSignificantToken) || KeywordsWithExpressionAfter.test(lastSignificantToken));
  18047. braces.push(isExpression);
  18048. postfixIncDec = false;
  18049. break;
  18050. case "}":
  18051. switch (mode.tag) {
  18052. case "InterpolationInTemplate":
  18053. if (braces.length === mode.nesting) {
  18054. Template.lastIndex = lastIndex;
  18055. match = Template.exec(input);
  18056. lastIndex = Template.lastIndex;
  18057. lastSignificantToken = match[0];
  18058. if (match[1] === "${") {
  18059. lastSignificantToken = "?InterpolationInTemplate";
  18060. postfixIncDec = false;
  18061. yield {
  18062. type: "TemplateMiddle",
  18063. value: match[0]
  18064. };
  18065. } else {
  18066. stack.pop();
  18067. postfixIncDec = true;
  18068. yield {
  18069. type: "TemplateTail",
  18070. value: match[0],
  18071. closed: match[1] === "`"
  18072. };
  18073. }
  18074. continue;
  18075. }
  18076. break;
  18077. case "InterpolationInJSX": if (braces.length === mode.nesting) {
  18078. stack.pop();
  18079. lastIndex += 1;
  18080. lastSignificantToken = "}";
  18081. yield {
  18082. type: "JSXPunctuator",
  18083. value: "}"
  18084. };
  18085. continue;
  18086. }
  18087. }
  18088. postfixIncDec = braces.pop();
  18089. nextLastSignificantToken = postfixIncDec ? "?ExpressionBraceEnd" : "}";
  18090. break;
  18091. case "]":
  18092. postfixIncDec = true;
  18093. break;
  18094. case "++":
  18095. case "--":
  18096. nextLastSignificantToken = postfixIncDec ? "?PostfixIncDec" : "?UnaryIncDec";
  18097. break;
  18098. case "<":
  18099. if (jsx && (TokensPrecedingExpression.test(lastSignificantToken) || KeywordsWithExpressionAfter.test(lastSignificantToken))) {
  18100. stack.push({ tag: "JSXTag" });
  18101. lastIndex += 1;
  18102. lastSignificantToken = "<";
  18103. yield {
  18104. type: "JSXPunctuator",
  18105. value: punctuator
  18106. };
  18107. continue;
  18108. }
  18109. postfixIncDec = false;
  18110. break;
  18111. default: postfixIncDec = false;
  18112. }
  18113. lastIndex = nextLastIndex;
  18114. lastSignificantToken = nextLastSignificantToken;
  18115. yield {
  18116. type: "Punctuator",
  18117. value: punctuator
  18118. };
  18119. continue;
  18120. }
  18121. Identifier.lastIndex = lastIndex;
  18122. if (match = Identifier.exec(input)) {
  18123. lastIndex = Identifier.lastIndex;
  18124. nextLastSignificantToken = match[0];
  18125. switch (match[0]) {
  18126. case "for":
  18127. case "if":
  18128. case "while":
  18129. case "with": if (lastSignificantToken !== "." && lastSignificantToken !== "?.") nextLastSignificantToken = "?NonExpressionParenKeyword";
  18130. }
  18131. lastSignificantToken = nextLastSignificantToken;
  18132. postfixIncDec = !KeywordsWithExpressionAfter.test(match[0]);
  18133. yield {
  18134. type: match[1] === "#" ? "PrivateIdentifier" : "IdentifierName",
  18135. value: match[0]
  18136. };
  18137. continue;
  18138. }
  18139. StringLiteral.lastIndex = lastIndex;
  18140. if (match = StringLiteral.exec(input)) {
  18141. lastIndex = StringLiteral.lastIndex;
  18142. lastSignificantToken = match[0];
  18143. postfixIncDec = true;
  18144. yield {
  18145. type: "StringLiteral",
  18146. value: match[0],
  18147. closed: match[2] !== void 0
  18148. };
  18149. continue;
  18150. }
  18151. NumericLiteral.lastIndex = lastIndex;
  18152. if (match = NumericLiteral.exec(input)) {
  18153. lastIndex = NumericLiteral.lastIndex;
  18154. lastSignificantToken = match[0];
  18155. postfixIncDec = true;
  18156. yield {
  18157. type: "NumericLiteral",
  18158. value: match[0]
  18159. };
  18160. continue;
  18161. }
  18162. Template.lastIndex = lastIndex;
  18163. if (match = Template.exec(input)) {
  18164. lastIndex = Template.lastIndex;
  18165. lastSignificantToken = match[0];
  18166. if (match[1] === "${") {
  18167. lastSignificantToken = "?InterpolationInTemplate";
  18168. stack.push({
  18169. tag: "InterpolationInTemplate",
  18170. nesting: braces.length
  18171. });
  18172. postfixIncDec = false;
  18173. yield {
  18174. type: "TemplateHead",
  18175. value: match[0]
  18176. };
  18177. } else {
  18178. postfixIncDec = true;
  18179. yield {
  18180. type: "NoSubstitutionTemplate",
  18181. value: match[0],
  18182. closed: match[1] === "`"
  18183. };
  18184. }
  18185. continue;
  18186. }
  18187. break;
  18188. case "JSXTag":
  18189. case "JSXTagEnd":
  18190. JSXPunctuator.lastIndex = lastIndex;
  18191. if (match = JSXPunctuator.exec(input)) {
  18192. lastIndex = JSXPunctuator.lastIndex;
  18193. nextLastSignificantToken = match[0];
  18194. switch (match[0]) {
  18195. case "<":
  18196. stack.push({ tag: "JSXTag" });
  18197. break;
  18198. case ">":
  18199. stack.pop();
  18200. if (lastSignificantToken === "/" || mode.tag === "JSXTagEnd") {
  18201. nextLastSignificantToken = "?JSX";
  18202. postfixIncDec = true;
  18203. } else stack.push({ tag: "JSXChildren" });
  18204. break;
  18205. case "{":
  18206. stack.push({
  18207. tag: "InterpolationInJSX",
  18208. nesting: braces.length
  18209. });
  18210. nextLastSignificantToken = "?InterpolationInJSX";
  18211. postfixIncDec = false;
  18212. break;
  18213. case "/": if (lastSignificantToken === "<") {
  18214. stack.pop();
  18215. if (stack[stack.length - 1].tag === "JSXChildren") stack.pop();
  18216. stack.push({ tag: "JSXTagEnd" });
  18217. }
  18218. }
  18219. lastSignificantToken = nextLastSignificantToken;
  18220. yield {
  18221. type: "JSXPunctuator",
  18222. value: match[0]
  18223. };
  18224. continue;
  18225. }
  18226. JSXIdentifier.lastIndex = lastIndex;
  18227. if (match = JSXIdentifier.exec(input)) {
  18228. lastIndex = JSXIdentifier.lastIndex;
  18229. lastSignificantToken = match[0];
  18230. yield {
  18231. type: "JSXIdentifier",
  18232. value: match[0]
  18233. };
  18234. continue;
  18235. }
  18236. JSXString.lastIndex = lastIndex;
  18237. if (match = JSXString.exec(input)) {
  18238. lastIndex = JSXString.lastIndex;
  18239. lastSignificantToken = match[0];
  18240. yield {
  18241. type: "JSXString",
  18242. value: match[0],
  18243. closed: match[2] !== void 0
  18244. };
  18245. continue;
  18246. }
  18247. break;
  18248. case "JSXChildren":
  18249. JSXText.lastIndex = lastIndex;
  18250. if (match = JSXText.exec(input)) {
  18251. lastIndex = JSXText.lastIndex;
  18252. lastSignificantToken = match[0];
  18253. yield {
  18254. type: "JSXText",
  18255. value: match[0]
  18256. };
  18257. continue;
  18258. }
  18259. switch (input[lastIndex]) {
  18260. case "<":
  18261. stack.push({ tag: "JSXTag" });
  18262. lastIndex++;
  18263. lastSignificantToken = "<";
  18264. yield {
  18265. type: "JSXPunctuator",
  18266. value: "<"
  18267. };
  18268. continue;
  18269. case "{":
  18270. stack.push({
  18271. tag: "InterpolationInJSX",
  18272. nesting: braces.length
  18273. });
  18274. lastIndex++;
  18275. lastSignificantToken = "?InterpolationInJSX";
  18276. postfixIncDec = false;
  18277. yield {
  18278. type: "JSXPunctuator",
  18279. value: "{"
  18280. };
  18281. continue;
  18282. }
  18283. }
  18284. WhiteSpace.lastIndex = lastIndex;
  18285. if (match = WhiteSpace.exec(input)) {
  18286. lastIndex = WhiteSpace.lastIndex;
  18287. yield {
  18288. type: "WhiteSpace",
  18289. value: match[0]
  18290. };
  18291. continue;
  18292. }
  18293. LineTerminatorSequence.lastIndex = lastIndex;
  18294. if (match = LineTerminatorSequence.exec(input)) {
  18295. lastIndex = LineTerminatorSequence.lastIndex;
  18296. postfixIncDec = false;
  18297. if (KeywordsWithNoLineTerminatorAfter.test(lastSignificantToken)) lastSignificantToken = "?NoLineTerminatorHere";
  18298. yield {
  18299. type: "LineTerminatorSequence",
  18300. value: match[0]
  18301. };
  18302. continue;
  18303. }
  18304. MultiLineComment.lastIndex = lastIndex;
  18305. if (match = MultiLineComment.exec(input)) {
  18306. lastIndex = MultiLineComment.lastIndex;
  18307. if (Newline.test(match[0])) {
  18308. postfixIncDec = false;
  18309. if (KeywordsWithNoLineTerminatorAfter.test(lastSignificantToken)) lastSignificantToken = "?NoLineTerminatorHere";
  18310. }
  18311. yield {
  18312. type: "MultiLineComment",
  18313. value: match[0],
  18314. closed: match[1] !== void 0
  18315. };
  18316. continue;
  18317. }
  18318. SingleLineComment.lastIndex = lastIndex;
  18319. if (match = SingleLineComment.exec(input)) {
  18320. lastIndex = SingleLineComment.lastIndex;
  18321. postfixIncDec = false;
  18322. yield {
  18323. type: "SingleLineComment",
  18324. value: match[0]
  18325. };
  18326. continue;
  18327. }
  18328. firstCodePoint = String.fromCodePoint(input.codePointAt(lastIndex));
  18329. lastIndex += firstCodePoint.length;
  18330. lastSignificantToken = firstCodePoint;
  18331. postfixIncDec = false;
  18332. yield {
  18333. type: mode.tag.startsWith("JSX") ? "JSXInvalid" : "Invalid",
  18334. value: firstCodePoint
  18335. };
  18336. }
  18337. };
  18338. })))(), 1);
  18339. const FILL_COMMENT = " ";
  18340. function stripLiteralFromToken(token, fillChar, filter) {
  18341. if (token.type === "SingleLineComment") return FILL_COMMENT.repeat(token.value.length);
  18342. if (token.type === "MultiLineComment") return token.value.replace(/[^\n]/g, FILL_COMMENT);
  18343. if (token.type === "StringLiteral") {
  18344. if (!token.closed) return token.value;
  18345. const body = token.value.slice(1, -1);
  18346. if (filter(body)) return token.value[0] + fillChar.repeat(body.length) + token.value[token.value.length - 1];
  18347. }
  18348. if (token.type === "NoSubstitutionTemplate") {
  18349. const body = token.value.slice(1, -1);
  18350. if (filter(body)) return `\`${body.replace(/[^\n]/g, fillChar)}\``;
  18351. }
  18352. if (token.type === "RegularExpressionLiteral") {
  18353. const body = token.value;
  18354. if (filter(body)) return body.replace(/\/(.*)\/(\w?)$/g, (_, $1, $2) => `/${fillChar.repeat($1.length)}/${$2}`);
  18355. }
  18356. if (token.type === "TemplateHead") {
  18357. const body = token.value.slice(1, -2);
  18358. if (filter(body)) return `\`${body.replace(/[^\n]/g, fillChar)}\${`;
  18359. }
  18360. if (token.type === "TemplateTail") {
  18361. const body = token.value.slice(0, -2);
  18362. if (filter(body)) return `}${body.replace(/[^\n]/g, fillChar)}\``;
  18363. }
  18364. if (token.type === "TemplateMiddle") {
  18365. const body = token.value.slice(1, -2);
  18366. if (filter(body)) return `}${body.replace(/[^\n]/g, fillChar)}\${`;
  18367. }
  18368. return token.value;
  18369. }
  18370. function optionsWithDefaults(options) {
  18371. return {
  18372. fillChar: options?.fillChar ?? " ",
  18373. filter: options?.filter ?? (() => true)
  18374. };
  18375. }
  18376. function stripLiteral(code, options) {
  18377. let result = "";
  18378. const _options = optionsWithDefaults(options);
  18379. for (const token of (0, import_js_tokens.default)(code, { jsx: false })) result += stripLiteralFromToken(token, _options.fillChar, _options.filter);
  18380. return result;
  18381. }
  18382. //#endregion
  18383. //#region src/node/assetSource.ts
  18384. const ALLOWED_META_NAME = [
  18385. "msapplication-tileimage",
  18386. "msapplication-square70x70logo",
  18387. "msapplication-square150x150logo",
  18388. "msapplication-wide310x150logo",
  18389. "msapplication-square310x310logo",
  18390. "msapplication-config",
  18391. "twitter:image"
  18392. ];
  18393. const ALLOWED_META_PROPERTY = [
  18394. "og:image",
  18395. "og:image:url",
  18396. "og:image:secure_url",
  18397. "og:audio",
  18398. "og:audio:secure_url",
  18399. "og:video",
  18400. "og:video:secure_url"
  18401. ];
  18402. const DEFAULT_HTML_ASSET_SOURCES = {
  18403. audio: { srcAttributes: ["src"] },
  18404. embed: { srcAttributes: ["src"] },
  18405. img: {
  18406. srcAttributes: ["src"],
  18407. srcsetAttributes: ["srcset"]
  18408. },
  18409. image: { srcAttributes: ["href", "xlink:href"] },
  18410. input: { srcAttributes: ["src"] },
  18411. link: {
  18412. srcAttributes: ["href"],
  18413. srcsetAttributes: ["imagesrcset"]
  18414. },
  18415. object: { srcAttributes: ["data"] },
  18416. source: {
  18417. srcAttributes: ["src"],
  18418. srcsetAttributes: ["srcset"]
  18419. },
  18420. track: { srcAttributes: ["src"] },
  18421. use: { srcAttributes: ["href", "xlink:href"] },
  18422. video: { srcAttributes: ["src", "poster"] },
  18423. meta: {
  18424. srcAttributes: ["content"],
  18425. filter({ attributes }) {
  18426. if (attributes.name && ALLOWED_META_NAME.includes(attributes.name.trim().toLowerCase())) return true;
  18427. if (attributes.property && ALLOWED_META_PROPERTY.includes(attributes.property.trim().toLowerCase())) return true;
  18428. return false;
  18429. }
  18430. }
  18431. };
  18432. /**
  18433. * Given a HTML node, find all attributes that references an asset to be processed
  18434. */
  18435. function getNodeAssetAttributes(node) {
  18436. const matched = DEFAULT_HTML_ASSET_SOURCES[node.nodeName];
  18437. if (!matched) return [];
  18438. const attributes = {};
  18439. for (const attr of node.attrs) attributes[getAttrKey(attr)] = attr.value;
  18440. if ("vite-ignore" in attributes) return [{
  18441. type: "remove",
  18442. key: "vite-ignore",
  18443. value: "",
  18444. attributes,
  18445. location: node.sourceCodeLocation.attrs["vite-ignore"]
  18446. }];
  18447. const actions = [];
  18448. function handleAttributeKey(key, type) {
  18449. const value = attributes[key];
  18450. if (!value) return;
  18451. if (matched.filter && !matched.filter({
  18452. key,
  18453. value,
  18454. attributes
  18455. })) return;
  18456. actions.push({
  18457. type,
  18458. key,
  18459. value,
  18460. attributes,
  18461. location: node.sourceCodeLocation.attrs[key]
  18462. });
  18463. }
  18464. matched.srcAttributes?.forEach((key) => handleAttributeKey(key, "src"));
  18465. matched.srcsetAttributes?.forEach((key) => handleAttributeKey(key, "srcset"));
  18466. return actions;
  18467. }
  18468. function getAttrKey(attr) {
  18469. return attr.prefix === void 0 ? attr.name : `${attr.prefix}:${attr.name}`;
  18470. }
  18471. //#endregion
  18472. //#region ../../node_modules/.pnpm/mrmime@2.0.1/node_modules/mrmime/index.mjs
  18473. const mimes = {
  18474. "3g2": "video/3gpp2",
  18475. "3gp": "video/3gpp",
  18476. "3gpp": "video/3gpp",
  18477. "3mf": "model/3mf",
  18478. "aac": "audio/aac",
  18479. "ac": "application/pkix-attr-cert",
  18480. "adp": "audio/adpcm",
  18481. "adts": "audio/aac",
  18482. "ai": "application/postscript",
  18483. "aml": "application/automationml-aml+xml",
  18484. "amlx": "application/automationml-amlx+zip",
  18485. "amr": "audio/amr",
  18486. "apng": "image/apng",
  18487. "appcache": "text/cache-manifest",
  18488. "appinstaller": "application/appinstaller",
  18489. "appx": "application/appx",
  18490. "appxbundle": "application/appxbundle",
  18491. "asc": "application/pgp-keys",
  18492. "atom": "application/atom+xml",
  18493. "atomcat": "application/atomcat+xml",
  18494. "atomdeleted": "application/atomdeleted+xml",
  18495. "atomsvc": "application/atomsvc+xml",
  18496. "au": "audio/basic",
  18497. "avci": "image/avci",
  18498. "avcs": "image/avcs",
  18499. "avif": "image/avif",
  18500. "aw": "application/applixware",
  18501. "bdoc": "application/bdoc",
  18502. "bin": "application/octet-stream",
  18503. "bmp": "image/bmp",
  18504. "bpk": "application/octet-stream",
  18505. "btf": "image/prs.btif",
  18506. "btif": "image/prs.btif",
  18507. "buffer": "application/octet-stream",
  18508. "ccxml": "application/ccxml+xml",
  18509. "cdfx": "application/cdfx+xml",
  18510. "cdmia": "application/cdmi-capability",
  18511. "cdmic": "application/cdmi-container",
  18512. "cdmid": "application/cdmi-domain",
  18513. "cdmio": "application/cdmi-object",
  18514. "cdmiq": "application/cdmi-queue",
  18515. "cer": "application/pkix-cert",
  18516. "cgm": "image/cgm",
  18517. "cjs": "application/node",
  18518. "class": "application/java-vm",
  18519. "coffee": "text/coffeescript",
  18520. "conf": "text/plain",
  18521. "cpl": "application/cpl+xml",
  18522. "cpt": "application/mac-compactpro",
  18523. "crl": "application/pkix-crl",
  18524. "css": "text/css",
  18525. "csv": "text/csv",
  18526. "cu": "application/cu-seeme",
  18527. "cwl": "application/cwl",
  18528. "cww": "application/prs.cww",
  18529. "davmount": "application/davmount+xml",
  18530. "dbk": "application/docbook+xml",
  18531. "deb": "application/octet-stream",
  18532. "def": "text/plain",
  18533. "deploy": "application/octet-stream",
  18534. "dib": "image/bmp",
  18535. "disposition-notification": "message/disposition-notification",
  18536. "dist": "application/octet-stream",
  18537. "distz": "application/octet-stream",
  18538. "dll": "application/octet-stream",
  18539. "dmg": "application/octet-stream",
  18540. "dms": "application/octet-stream",
  18541. "doc": "application/msword",
  18542. "dot": "application/msword",
  18543. "dpx": "image/dpx",
  18544. "drle": "image/dicom-rle",
  18545. "dsc": "text/prs.lines.tag",
  18546. "dssc": "application/dssc+der",
  18547. "dtd": "application/xml-dtd",
  18548. "dump": "application/octet-stream",
  18549. "dwd": "application/atsc-dwd+xml",
  18550. "ear": "application/java-archive",
  18551. "ecma": "application/ecmascript",
  18552. "elc": "application/octet-stream",
  18553. "emf": "image/emf",
  18554. "eml": "message/rfc822",
  18555. "emma": "application/emma+xml",
  18556. "emotionml": "application/emotionml+xml",
  18557. "eps": "application/postscript",
  18558. "epub": "application/epub+zip",
  18559. "exe": "application/octet-stream",
  18560. "exi": "application/exi",
  18561. "exp": "application/express",
  18562. "exr": "image/aces",
  18563. "ez": "application/andrew-inset",
  18564. "fdf": "application/fdf",
  18565. "fdt": "application/fdt+xml",
  18566. "fits": "image/fits",
  18567. "g3": "image/g3fax",
  18568. "gbr": "application/rpki-ghostbusters",
  18569. "geojson": "application/geo+json",
  18570. "gif": "image/gif",
  18571. "glb": "model/gltf-binary",
  18572. "gltf": "model/gltf+json",
  18573. "gml": "application/gml+xml",
  18574. "gpx": "application/gpx+xml",
  18575. "gram": "application/srgs",
  18576. "grxml": "application/srgs+xml",
  18577. "gxf": "application/gxf",
  18578. "gz": "application/gzip",
  18579. "h261": "video/h261",
  18580. "h263": "video/h263",
  18581. "h264": "video/h264",
  18582. "heic": "image/heic",
  18583. "heics": "image/heic-sequence",
  18584. "heif": "image/heif",
  18585. "heifs": "image/heif-sequence",
  18586. "hej2": "image/hej2k",
  18587. "held": "application/atsc-held+xml",
  18588. "hjson": "application/hjson",
  18589. "hlp": "application/winhlp",
  18590. "hqx": "application/mac-binhex40",
  18591. "hsj2": "image/hsj2",
  18592. "htm": "text/html",
  18593. "html": "text/html",
  18594. "ics": "text/calendar",
  18595. "ief": "image/ief",
  18596. "ifb": "text/calendar",
  18597. "iges": "model/iges",
  18598. "igs": "model/iges",
  18599. "img": "application/octet-stream",
  18600. "in": "text/plain",
  18601. "ini": "text/plain",
  18602. "ink": "application/inkml+xml",
  18603. "inkml": "application/inkml+xml",
  18604. "ipfix": "application/ipfix",
  18605. "iso": "application/octet-stream",
  18606. "its": "application/its+xml",
  18607. "jade": "text/jade",
  18608. "jar": "application/java-archive",
  18609. "jhc": "image/jphc",
  18610. "jls": "image/jls",
  18611. "jp2": "image/jp2",
  18612. "jpe": "image/jpeg",
  18613. "jpeg": "image/jpeg",
  18614. "jpf": "image/jpx",
  18615. "jpg": "image/jpeg",
  18616. "jpg2": "image/jp2",
  18617. "jpgm": "image/jpm",
  18618. "jpgv": "video/jpeg",
  18619. "jph": "image/jph",
  18620. "jpm": "image/jpm",
  18621. "jpx": "image/jpx",
  18622. "js": "text/javascript",
  18623. "json": "application/json",
  18624. "json5": "application/json5",
  18625. "jsonld": "application/ld+json",
  18626. "jsonml": "application/jsonml+json",
  18627. "jsx": "text/jsx",
  18628. "jt": "model/jt",
  18629. "jxl": "image/jxl",
  18630. "jxr": "image/jxr",
  18631. "jxra": "image/jxra",
  18632. "jxrs": "image/jxrs",
  18633. "jxs": "image/jxs",
  18634. "jxsc": "image/jxsc",
  18635. "jxsi": "image/jxsi",
  18636. "jxss": "image/jxss",
  18637. "kar": "audio/midi",
  18638. "ktx": "image/ktx",
  18639. "ktx2": "image/ktx2",
  18640. "less": "text/less",
  18641. "lgr": "application/lgr+xml",
  18642. "list": "text/plain",
  18643. "litcoffee": "text/coffeescript",
  18644. "log": "text/plain",
  18645. "lostxml": "application/lost+xml",
  18646. "lrf": "application/octet-stream",
  18647. "m1v": "video/mpeg",
  18648. "m21": "application/mp21",
  18649. "m2a": "audio/mpeg",
  18650. "m2t": "video/mp2t",
  18651. "m2ts": "video/mp2t",
  18652. "m2v": "video/mpeg",
  18653. "m3a": "audio/mpeg",
  18654. "m4a": "audio/mp4",
  18655. "m4p": "application/mp4",
  18656. "m4s": "video/iso.segment",
  18657. "ma": "application/mathematica",
  18658. "mads": "application/mads+xml",
  18659. "maei": "application/mmt-aei+xml",
  18660. "man": "text/troff",
  18661. "manifest": "text/cache-manifest",
  18662. "map": "application/json",
  18663. "mar": "application/octet-stream",
  18664. "markdown": "text/markdown",
  18665. "mathml": "application/mathml+xml",
  18666. "mb": "application/mathematica",
  18667. "mbox": "application/mbox",
  18668. "md": "text/markdown",
  18669. "mdx": "text/mdx",
  18670. "me": "text/troff",
  18671. "mesh": "model/mesh",
  18672. "meta4": "application/metalink4+xml",
  18673. "metalink": "application/metalink+xml",
  18674. "mets": "application/mets+xml",
  18675. "mft": "application/rpki-manifest",
  18676. "mid": "audio/midi",
  18677. "midi": "audio/midi",
  18678. "mime": "message/rfc822",
  18679. "mj2": "video/mj2",
  18680. "mjp2": "video/mj2",
  18681. "mjs": "text/javascript",
  18682. "mml": "text/mathml",
  18683. "mods": "application/mods+xml",
  18684. "mov": "video/quicktime",
  18685. "mp2": "audio/mpeg",
  18686. "mp21": "application/mp21",
  18687. "mp2a": "audio/mpeg",
  18688. "mp3": "audio/mpeg",
  18689. "mp4": "video/mp4",
  18690. "mp4a": "audio/mp4",
  18691. "mp4s": "application/mp4",
  18692. "mp4v": "video/mp4",
  18693. "mpd": "application/dash+xml",
  18694. "mpe": "video/mpeg",
  18695. "mpeg": "video/mpeg",
  18696. "mpf": "application/media-policy-dataset+xml",
  18697. "mpg": "video/mpeg",
  18698. "mpg4": "video/mp4",
  18699. "mpga": "audio/mpeg",
  18700. "mpp": "application/dash-patch+xml",
  18701. "mrc": "application/marc",
  18702. "mrcx": "application/marcxml+xml",
  18703. "ms": "text/troff",
  18704. "mscml": "application/mediaservercontrol+xml",
  18705. "msh": "model/mesh",
  18706. "msi": "application/octet-stream",
  18707. "msix": "application/msix",
  18708. "msixbundle": "application/msixbundle",
  18709. "msm": "application/octet-stream",
  18710. "msp": "application/octet-stream",
  18711. "mtl": "model/mtl",
  18712. "mts": "video/mp2t",
  18713. "musd": "application/mmt-usd+xml",
  18714. "mxf": "application/mxf",
  18715. "mxmf": "audio/mobile-xmf",
  18716. "mxml": "application/xv+xml",
  18717. "n3": "text/n3",
  18718. "nb": "application/mathematica",
  18719. "nq": "application/n-quads",
  18720. "nt": "application/n-triples",
  18721. "obj": "model/obj",
  18722. "oda": "application/oda",
  18723. "oga": "audio/ogg",
  18724. "ogg": "audio/ogg",
  18725. "ogv": "video/ogg",
  18726. "ogx": "application/ogg",
  18727. "omdoc": "application/omdoc+xml",
  18728. "onepkg": "application/onenote",
  18729. "onetmp": "application/onenote",
  18730. "onetoc": "application/onenote",
  18731. "onetoc2": "application/onenote",
  18732. "opf": "application/oebps-package+xml",
  18733. "opus": "audio/ogg",
  18734. "otf": "font/otf",
  18735. "owl": "application/rdf+xml",
  18736. "oxps": "application/oxps",
  18737. "p10": "application/pkcs10",
  18738. "p7c": "application/pkcs7-mime",
  18739. "p7m": "application/pkcs7-mime",
  18740. "p7s": "application/pkcs7-signature",
  18741. "p8": "application/pkcs8",
  18742. "pdf": "application/pdf",
  18743. "pfr": "application/font-tdpfr",
  18744. "pgp": "application/pgp-encrypted",
  18745. "pkg": "application/octet-stream",
  18746. "pki": "application/pkixcmp",
  18747. "pkipath": "application/pkix-pkipath",
  18748. "pls": "application/pls+xml",
  18749. "png": "image/png",
  18750. "prc": "model/prc",
  18751. "prf": "application/pics-rules",
  18752. "provx": "application/provenance+xml",
  18753. "ps": "application/postscript",
  18754. "pskcxml": "application/pskc+xml",
  18755. "pti": "image/prs.pti",
  18756. "qt": "video/quicktime",
  18757. "raml": "application/raml+yaml",
  18758. "rapd": "application/route-apd+xml",
  18759. "rdf": "application/rdf+xml",
  18760. "relo": "application/p2p-overlay+xml",
  18761. "rif": "application/reginfo+xml",
  18762. "rl": "application/resource-lists+xml",
  18763. "rld": "application/resource-lists-diff+xml",
  18764. "rmi": "audio/midi",
  18765. "rnc": "application/relax-ng-compact-syntax",
  18766. "rng": "application/xml",
  18767. "roa": "application/rpki-roa",
  18768. "roff": "text/troff",
  18769. "rq": "application/sparql-query",
  18770. "rs": "application/rls-services+xml",
  18771. "rsat": "application/atsc-rsat+xml",
  18772. "rsd": "application/rsd+xml",
  18773. "rsheet": "application/urc-ressheet+xml",
  18774. "rss": "application/rss+xml",
  18775. "rtf": "text/rtf",
  18776. "rtx": "text/richtext",
  18777. "rusd": "application/route-usd+xml",
  18778. "s3m": "audio/s3m",
  18779. "sbml": "application/sbml+xml",
  18780. "scq": "application/scvp-cv-request",
  18781. "scs": "application/scvp-cv-response",
  18782. "sdp": "application/sdp",
  18783. "senmlx": "application/senml+xml",
  18784. "sensmlx": "application/sensml+xml",
  18785. "ser": "application/java-serialized-object",
  18786. "setpay": "application/set-payment-initiation",
  18787. "setreg": "application/set-registration-initiation",
  18788. "sgi": "image/sgi",
  18789. "sgm": "text/sgml",
  18790. "sgml": "text/sgml",
  18791. "shex": "text/shex",
  18792. "shf": "application/shf+xml",
  18793. "shtml": "text/html",
  18794. "sieve": "application/sieve",
  18795. "sig": "application/pgp-signature",
  18796. "sil": "audio/silk",
  18797. "silo": "model/mesh",
  18798. "siv": "application/sieve",
  18799. "slim": "text/slim",
  18800. "slm": "text/slim",
  18801. "sls": "application/route-s-tsid+xml",
  18802. "smi": "application/smil+xml",
  18803. "smil": "application/smil+xml",
  18804. "snd": "audio/basic",
  18805. "so": "application/octet-stream",
  18806. "spdx": "text/spdx",
  18807. "spp": "application/scvp-vp-response",
  18808. "spq": "application/scvp-vp-request",
  18809. "spx": "audio/ogg",
  18810. "sql": "application/sql",
  18811. "sru": "application/sru+xml",
  18812. "srx": "application/sparql-results+xml",
  18813. "ssdl": "application/ssdl+xml",
  18814. "ssml": "application/ssml+xml",
  18815. "stk": "application/hyperstudio",
  18816. "stl": "model/stl",
  18817. "stpx": "model/step+xml",
  18818. "stpxz": "model/step-xml+zip",
  18819. "stpz": "model/step+zip",
  18820. "styl": "text/stylus",
  18821. "stylus": "text/stylus",
  18822. "svg": "image/svg+xml",
  18823. "svgz": "image/svg+xml",
  18824. "swidtag": "application/swid+xml",
  18825. "t": "text/troff",
  18826. "t38": "image/t38",
  18827. "td": "application/urc-targetdesc+xml",
  18828. "tei": "application/tei+xml",
  18829. "teicorpus": "application/tei+xml",
  18830. "text": "text/plain",
  18831. "tfi": "application/thraud+xml",
  18832. "tfx": "image/tiff-fx",
  18833. "tif": "image/tiff",
  18834. "tiff": "image/tiff",
  18835. "toml": "application/toml",
  18836. "tr": "text/troff",
  18837. "trig": "application/trig",
  18838. "ts": "video/mp2t",
  18839. "tsd": "application/timestamped-data",
  18840. "tsv": "text/tab-separated-values",
  18841. "ttc": "font/collection",
  18842. "ttf": "font/ttf",
  18843. "ttl": "text/turtle",
  18844. "ttml": "application/ttml+xml",
  18845. "txt": "text/plain",
  18846. "u3d": "model/u3d",
  18847. "u8dsn": "message/global-delivery-status",
  18848. "u8hdr": "message/global-headers",
  18849. "u8mdn": "message/global-disposition-notification",
  18850. "u8msg": "message/global",
  18851. "ubj": "application/ubjson",
  18852. "uri": "text/uri-list",
  18853. "uris": "text/uri-list",
  18854. "urls": "text/uri-list",
  18855. "vcard": "text/vcard",
  18856. "vrml": "model/vrml",
  18857. "vtt": "text/vtt",
  18858. "vxml": "application/voicexml+xml",
  18859. "war": "application/java-archive",
  18860. "wasm": "application/wasm",
  18861. "wav": "audio/wav",
  18862. "weba": "audio/webm",
  18863. "webm": "video/webm",
  18864. "webmanifest": "application/manifest+json",
  18865. "webp": "image/webp",
  18866. "wgsl": "text/wgsl",
  18867. "wgt": "application/widget",
  18868. "wif": "application/watcherinfo+xml",
  18869. "wmf": "image/wmf",
  18870. "woff": "font/woff",
  18871. "woff2": "font/woff2",
  18872. "wrl": "model/vrml",
  18873. "wsdl": "application/wsdl+xml",
  18874. "wspolicy": "application/wspolicy+xml",
  18875. "x3d": "model/x3d+xml",
  18876. "x3db": "model/x3d+fastinfoset",
  18877. "x3dbz": "model/x3d+binary",
  18878. "x3dv": "model/x3d-vrml",
  18879. "x3dvz": "model/x3d+vrml",
  18880. "x3dz": "model/x3d+xml",
  18881. "xaml": "application/xaml+xml",
  18882. "xav": "application/xcap-att+xml",
  18883. "xca": "application/xcap-caps+xml",
  18884. "xcs": "application/calendar+xml",
  18885. "xdf": "application/xcap-diff+xml",
  18886. "xdssc": "application/dssc+xml",
  18887. "xel": "application/xcap-el+xml",
  18888. "xenc": "application/xenc+xml",
  18889. "xer": "application/patch-ops-error+xml",
  18890. "xfdf": "application/xfdf",
  18891. "xht": "application/xhtml+xml",
  18892. "xhtml": "application/xhtml+xml",
  18893. "xhvml": "application/xv+xml",
  18894. "xlf": "application/xliff+xml",
  18895. "xm": "audio/xm",
  18896. "xml": "text/xml",
  18897. "xns": "application/xcap-ns+xml",
  18898. "xop": "application/xop+xml",
  18899. "xpl": "application/xproc+xml",
  18900. "xsd": "application/xml",
  18901. "xsf": "application/prs.xsf+xml",
  18902. "xsl": "application/xml",
  18903. "xslt": "application/xml",
  18904. "xspf": "application/xspf+xml",
  18905. "xvm": "application/xv+xml",
  18906. "xvml": "application/xv+xml",
  18907. "yaml": "text/yaml",
  18908. "yang": "application/yang",
  18909. "yin": "application/yin+xml",
  18910. "yml": "text/yaml",
  18911. "zip": "application/zip"
  18912. };
  18913. function lookup(extn) {
  18914. let tmp = ("" + extn).trim().toLowerCase();
  18915. let idx = tmp.lastIndexOf(".");
  18916. return mimes[!~idx ? tmp : tmp.substring(++idx)];
  18917. }
  18918. //#endregion
  18919. //#region src/node/plugins/asset.ts
  18920. const assetUrlRE = /__VITE_ASSET__([\w$]+)__(?:\$_(.*?)__)?/g;
  18921. const jsSourceMapRE = /\.[cm]?js\.map$/;
  18922. const noInlineRE = /[?&]no-inline\b/;
  18923. const inlineRE$3 = /[?&]inline\b/;
  18924. const assetCache = /* @__PURE__ */ new WeakMap();
  18925. /** a set of referenceId for entry CSS assets for each environment */
  18926. const cssEntriesMap = /* @__PURE__ */ new WeakMap();
  18927. function registerCustomMime() {
  18928. mimes.ico = "image/x-icon";
  18929. mimes.cur = "image/x-icon";
  18930. mimes.flac = "audio/flac";
  18931. mimes.eot = "application/vnd.ms-fontobject";
  18932. }
  18933. function renderAssetUrlInJS(pluginContext, chunk, opts, code) {
  18934. const { environment } = pluginContext;
  18935. const toRelativeRuntime = createToImportMetaURLBasedRelativeRuntime(opts.format, environment.config.isWorker);
  18936. let match;
  18937. let s;
  18938. assetUrlRE.lastIndex = 0;
  18939. while (match = assetUrlRE.exec(code)) {
  18940. s ||= new MagicString(code);
  18941. const [full, referenceId, postfix = ""] = match;
  18942. const file = pluginContext.getFileName(referenceId);
  18943. chunk.viteMetadata.importedAssets.add(cleanUrl(file));
  18944. const replacement = toOutputFilePathInJS(environment, file + postfix, "asset", chunk.fileName, "js", toRelativeRuntime);
  18945. const replacementString = typeof replacement === "string" ? JSON.stringify(encodeURIPath(replacement)).slice(1, -1) : `"+${replacement.runtime}+"`;
  18946. s.update(match.index, match.index + full.length, replacementString);
  18947. }
  18948. const publicAssetUrlMap = publicAssetUrlCache.get(environment.getTopLevelConfig());
  18949. publicAssetUrlRE.lastIndex = 0;
  18950. while (match = publicAssetUrlRE.exec(code)) {
  18951. s ||= new MagicString(code);
  18952. const [full, hash] = match;
  18953. const replacement = toOutputFilePathInJS(environment, publicAssetUrlMap.get(hash).slice(1), "public", chunk.fileName, "js", toRelativeRuntime);
  18954. const replacementString = typeof replacement === "string" ? JSON.stringify(encodeURIPath(replacement)).slice(1, -1) : `"+${replacement.runtime}+"`;
  18955. s.update(match.index, match.index + full.length, replacementString);
  18956. }
  18957. return s;
  18958. }
  18959. /**
  18960. * Also supports loading plain strings with import text from './foo.txt?raw'
  18961. */
  18962. function assetPlugin(config) {
  18963. registerCustomMime();
  18964. return {
  18965. name: "vite:asset",
  18966. perEnvironmentStartEndDuringDev: true,
  18967. buildStart() {
  18968. assetCache.set(this.environment, /* @__PURE__ */ new Map());
  18969. cssEntriesMap.set(this.environment, /* @__PURE__ */ new Map());
  18970. },
  18971. resolveId: {
  18972. filter: { id: [
  18973. urlRE$1,
  18974. DEFAULT_ASSETS_RE,
  18975. ...makeIdFiltersToMatchWithQuery(config.rawAssetsInclude).map((v) => typeof v === "string" ? picomatch.makeRe(v, { dot: true }) : v)
  18976. ] },
  18977. handler(id) {
  18978. if (!config.assetsInclude(cleanUrl(id)) && !urlRE$1.test(id)) return;
  18979. if (checkPublicFile(id, config)) return id;
  18980. }
  18981. },
  18982. load: {
  18983. filter: { id: {
  18984. include: [
  18985. rawRE$1,
  18986. urlRE$1,
  18987. DEFAULT_ASSETS_RE,
  18988. ...makeIdFiltersToMatchWithQuery(config.rawAssetsInclude)
  18989. ],
  18990. exclude: /^\0/
  18991. } },
  18992. async handler(id) {
  18993. if (rawRE$1.test(id)) {
  18994. const file = checkPublicFile(id, config) || cleanUrl(id);
  18995. this.addWatchFile(file);
  18996. return {
  18997. code: `export default ${JSON.stringify(await fsp.readFile(file, "utf-8"))}`,
  18998. moduleType: "js"
  18999. };
  19000. }
  19001. if (!urlRE$1.test(id) && !config.assetsInclude(cleanUrl(id))) return;
  19002. id = removeUrlQuery(id);
  19003. let url = await fileToUrl$1(this, id);
  19004. if (!url.startsWith("data:") && this.environment.mode === "dev") {
  19005. const mod = this.environment.moduleGraph.getModuleById(id);
  19006. if (mod && mod.lastHMRTimestamp > 0) url = injectQuery(url, `t=${mod.lastHMRTimestamp}`);
  19007. }
  19008. return {
  19009. code: `export default ${JSON.stringify(encodeURIPath(url))}`,
  19010. moduleSideEffects: config.command === "build" && this.getModuleInfo(id)?.isEntry ? "no-treeshake" : false,
  19011. meta: config.command === "build" ? { "vite:asset": true } : void 0,
  19012. moduleType: "js"
  19013. };
  19014. }
  19015. },
  19016. ...config.command === "build" ? { renderChunk(code, chunk, opts) {
  19017. const s = renderAssetUrlInJS(this, chunk, opts, code);
  19018. if (s) return {
  19019. code: s.toString(),
  19020. map: this.environment.config.build.sourcemap ? s.generateMap({ hires: "boundary" }) : null
  19021. };
  19022. else return null;
  19023. } } : {},
  19024. generateBundle(_, bundle) {
  19025. let importedFiles;
  19026. for (const file in bundle) {
  19027. const chunk = bundle[file];
  19028. if (chunk.type === "chunk" && chunk.isEntry && chunk.moduleIds.length === 1 && config.assetsInclude(chunk.moduleIds[0]) && this.getModuleInfo(chunk.moduleIds[0])?.meta["vite:asset"]) {
  19029. if (!importedFiles) {
  19030. importedFiles = /* @__PURE__ */ new Set();
  19031. for (const file in bundle) {
  19032. const chunk = bundle[file];
  19033. if (chunk.type === "chunk") {
  19034. for (const importedFile of chunk.imports) importedFiles.add(importedFile);
  19035. for (const importedFile of chunk.dynamicImports) importedFiles.add(importedFile);
  19036. }
  19037. }
  19038. }
  19039. if (!importedFiles.has(file)) delete bundle[file];
  19040. }
  19041. }
  19042. if (config.command === "build" && !this.environment.config.build.emitAssets) {
  19043. for (const file in bundle) if (bundle[file].type === "asset" && !file.endsWith("ssr-manifest.json") && !jsSourceMapRE.test(file)) delete bundle[file];
  19044. }
  19045. },
  19046. watchChange(id) {
  19047. assetCache.get(this.environment)?.delete(normalizePath(id));
  19048. }
  19049. };
  19050. }
  19051. async function fileToUrl$1(pluginContext, id, asFileUrl = false) {
  19052. const { environment } = pluginContext;
  19053. if (!environment.config.isBundled) return fileToDevUrl(environment, id, asFileUrl);
  19054. else return fileToBuiltUrl(pluginContext, id);
  19055. }
  19056. async function fileToDevUrl(environment, id, asFileUrl = false) {
  19057. const config = environment.getTopLevelConfig();
  19058. const publicFile = checkPublicFile(id, config);
  19059. if (inlineRE$3.test(id)) {
  19060. const file = publicFile || cleanUrl(id);
  19061. return assetToDataURL(environment, file, await fsp.readFile(file));
  19062. }
  19063. const cleanedId = cleanUrl(id);
  19064. if (cleanedId.endsWith(".svg")) {
  19065. const file = publicFile || cleanedId;
  19066. const content = await fsp.readFile(file);
  19067. if (shouldInline(environment, file, id, content, void 0, void 0)) return assetToDataURL(environment, file, content);
  19068. }
  19069. if (asFileUrl) return pathToFileURL(cleanedId).href;
  19070. let rtn;
  19071. if (publicFile) rtn = id;
  19072. else if (id.startsWith(withTrailingSlash(config.root))) rtn = "/" + path.posix.relative(config.root, id);
  19073. else rtn = path.posix.join(FS_PREFIX, id);
  19074. return joinUrlSegments(joinUrlSegments(config.server.origin ?? "", config.decodedBase), removeLeadingSlash(rtn));
  19075. }
  19076. function getPublicAssetFilename(hash, config) {
  19077. return publicAssetUrlCache.get(config)?.get(hash);
  19078. }
  19079. const publicAssetUrlCache = /* @__PURE__ */ new WeakMap();
  19080. const publicAssetUrlRE = /__VITE_PUBLIC_ASSET__([a-z\d]{8})__/g;
  19081. function publicFileToBuiltUrl(url, config) {
  19082. if (config.command !== "build") return joinUrlSegments(config.decodedBase, url);
  19083. const hash = getHash(url);
  19084. let cache = publicAssetUrlCache.get(config);
  19085. if (!cache) {
  19086. cache = /* @__PURE__ */ new Map();
  19087. publicAssetUrlCache.set(config, cache);
  19088. }
  19089. if (!cache.get(hash)) cache.set(hash, url);
  19090. return `__VITE_PUBLIC_ASSET__${hash}__`;
  19091. }
  19092. const GIT_LFS_PREFIX = Buffer$1.from("version https://git-lfs.github.com");
  19093. function isGitLfsPlaceholder(content) {
  19094. if (content.length < GIT_LFS_PREFIX.length) return false;
  19095. return GIT_LFS_PREFIX.compare(content, 0, GIT_LFS_PREFIX.length) === 0;
  19096. }
  19097. /**
  19098. * Register an asset to be emitted as part of the bundle (if necessary)
  19099. * and returns the resolved public URL
  19100. */
  19101. async function fileToBuiltUrl(pluginContext, id, skipPublicCheck = false, forceInline) {
  19102. const environment = pluginContext.environment;
  19103. const topLevelConfig = environment.getTopLevelConfig();
  19104. if (!skipPublicCheck) {
  19105. const publicFile = checkPublicFile(id, topLevelConfig);
  19106. if (publicFile) if (inlineRE$3.test(id)) id = publicFile;
  19107. else return publicFileToBuiltUrl(id, topLevelConfig);
  19108. }
  19109. const cache = assetCache.get(environment);
  19110. const cached = cache.get(id);
  19111. if (cached) return cached;
  19112. let { file, postfix } = splitFileAndPostfix(id);
  19113. const content = await fsp.readFile(file);
  19114. let url;
  19115. if (shouldInline(environment, file, id, content, pluginContext, forceInline)) url = assetToDataURL(environment, file, content);
  19116. else {
  19117. const originalFileName = normalizePath(path.relative(environment.config.root, file));
  19118. const referenceId = pluginContext.emitFile({
  19119. type: "asset",
  19120. name: path.basename(file),
  19121. originalFileName,
  19122. source: content
  19123. });
  19124. if (environment.config.command === "build" && noInlineRE.test(postfix)) postfix = postfix.replace(noInlineRE, "").replace(/^&/, "?");
  19125. if (environment.config.command === "serve" && environment.config.experimental.bundledDev) url = toOutputFilePathInJSForBundledDev(environment, pluginContext.getFileName(referenceId));
  19126. else url = `__VITE_ASSET__${referenceId}__${postfix ? `$_${postfix}__` : ``}`;
  19127. }
  19128. cache.set(id, url);
  19129. return url;
  19130. }
  19131. function toOutputFilePathInJSForBundledDev(environment, filename) {
  19132. const outputUrl = toOutputFilePathInJS(environment, filename, "asset", "assets/dummy.js", "js", () => {
  19133. throw new Error("unreachable");
  19134. });
  19135. if (typeof outputUrl === "object") throw new Error("unreachable");
  19136. return outputUrl;
  19137. }
  19138. async function urlToBuiltUrl(pluginContext, url, importer, forceInline) {
  19139. const topLevelConfig = pluginContext.environment.getTopLevelConfig();
  19140. if (checkPublicFile(url, topLevelConfig)) return publicFileToBuiltUrl(url, topLevelConfig);
  19141. return fileToBuiltUrl(pluginContext, normalizePath(url[0] === "/" ? path.join(topLevelConfig.root, url) : path.join(path.dirname(importer), url)), true, forceInline);
  19142. }
  19143. function shouldInline(environment, file, id, content, buildPluginContext, forceInline) {
  19144. if (noInlineRE.test(id)) return false;
  19145. if (inlineRE$3.test(id)) return true;
  19146. if (buildPluginContext) {
  19147. if (environment.config.build.lib) return true;
  19148. if (buildPluginContext.getModuleInfo(id)?.isEntry) return false;
  19149. }
  19150. if (forceInline !== void 0) return forceInline;
  19151. if (file.endsWith(".html")) return false;
  19152. if (file.endsWith(".svg") && id.includes("#")) return false;
  19153. let limit;
  19154. const { assetsInlineLimit } = environment.config.build;
  19155. if (typeof assetsInlineLimit === "function") {
  19156. const userShouldInline = assetsInlineLimit(file, content);
  19157. if (userShouldInline != null) return userShouldInline;
  19158. limit = DEFAULT_ASSETS_INLINE_LIMIT;
  19159. } else limit = Number(assetsInlineLimit);
  19160. return content.length < limit && !isGitLfsPlaceholder(content);
  19161. }
  19162. function assetToDataURL(environment, file, content) {
  19163. if (environment.config.build.lib && isGitLfsPlaceholder(content)) environment.logger.warn(import_picocolors.default.yellow(`Inlined file ${file} was not downloaded via Git LFS`));
  19164. if (file.endsWith(".svg")) return svgToDataURL(content);
  19165. else return `data:${lookup(file) ?? "application/octet-stream"};base64,${content.toString("base64")}`;
  19166. }
  19167. const nestedQuotesRE = /"[^"']*'[^"]*"|'[^'"]*"[^']*'/;
  19168. function svgToDataURL(content) {
  19169. const stringContent = content.toString();
  19170. if (stringContent.includes("<text") || stringContent.includes("<foreignObject") || nestedQuotesRE.test(stringContent)) return `data:image/svg+xml;base64,${content.toString("base64")}`;
  19171. else return "data:image/svg+xml," + stringContent.trim().replaceAll(/>\s+</g, "><").replaceAll("\"", "'").replaceAll("%", "%25").replaceAll("#", "%23").replaceAll("<", "%3c").replaceAll(">", "%3e").replaceAll(/\s+/g, "%20");
  19172. }
  19173. //#endregion
  19174. //#region ../../node_modules/.pnpm/lilconfig@3.1.3/node_modules/lilconfig/src/index.js
  19175. var require_src$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  19176. const path$2 = __require("path");
  19177. const fs$2 = __require("fs");
  19178. const os$1 = __require("os");
  19179. const url = __require("url");
  19180. const fsReadFileAsync = fs$2.promises.readFile;
  19181. /** @type {(name: string, sync: boolean) => string[]} */
  19182. function getDefaultSearchPlaces(name, sync) {
  19183. return [
  19184. "package.json",
  19185. `.${name}rc.json`,
  19186. `.${name}rc.js`,
  19187. `.${name}rc.cjs`,
  19188. ...sync ? [] : [`.${name}rc.mjs`],
  19189. `.config/${name}rc`,
  19190. `.config/${name}rc.json`,
  19191. `.config/${name}rc.js`,
  19192. `.config/${name}rc.cjs`,
  19193. ...sync ? [] : [`.config/${name}rc.mjs`],
  19194. `${name}.config.js`,
  19195. `${name}.config.cjs`,
  19196. ...sync ? [] : [`${name}.config.mjs`]
  19197. ];
  19198. }
  19199. /**
  19200. * @type {(p: string) => string}
  19201. *
  19202. * see #17
  19203. * On *nix, if cwd is not under homedir,
  19204. * the last path will be '', ('/build' -> '')
  19205. * but it should be '/' actually.
  19206. * And on Windows, this will never happen. ('C:\build' -> 'C:')
  19207. */
  19208. function parentDir(p) {
  19209. return path$2.dirname(p) || path$2.sep;
  19210. }
  19211. /** @type {import('./index').LoaderSync} */
  19212. const jsonLoader = (_, content) => JSON.parse(content);
  19213. const requireFunc = typeof __webpack_require__ === "function" ? __non_webpack_require__ : __require;
  19214. /** @type {import('./index').LoadersSync} */
  19215. const defaultLoadersSync = Object.freeze({
  19216. ".js": requireFunc,
  19217. ".json": requireFunc,
  19218. ".cjs": requireFunc,
  19219. noExt: jsonLoader
  19220. });
  19221. module.exports.defaultLoadersSync = defaultLoadersSync;
  19222. /** @type {import('./index').Loader} */
  19223. const dynamicImport = async (id) => {
  19224. try {
  19225. return (await import(url.pathToFileURL(id).href)).default;
  19226. } catch (e) {
  19227. try {
  19228. return requireFunc(id);
  19229. } catch (requireE) {
  19230. if (requireE.code === "ERR_REQUIRE_ESM" || requireE instanceof SyntaxError && requireE.toString().includes("Cannot use import statement outside a module")) throw e;
  19231. throw requireE;
  19232. }
  19233. }
  19234. };
  19235. /** @type {import('./index').Loaders} */
  19236. const defaultLoaders = Object.freeze({
  19237. ".js": dynamicImport,
  19238. ".mjs": dynamicImport,
  19239. ".cjs": dynamicImport,
  19240. ".json": jsonLoader,
  19241. noExt: jsonLoader
  19242. });
  19243. module.exports.defaultLoaders = defaultLoaders;
  19244. /**
  19245. * @param {string} name
  19246. * @param {import('./index').Options | import('./index').OptionsSync} options
  19247. * @param {boolean} sync
  19248. * @returns {Required<import('./index').Options | import('./index').OptionsSync>}
  19249. */
  19250. function getOptions(name, options, sync) {
  19251. /** @type {Required<import('./index').Options>} */
  19252. const conf = {
  19253. stopDir: os$1.homedir(),
  19254. searchPlaces: getDefaultSearchPlaces(name, sync),
  19255. ignoreEmptySearchPlaces: true,
  19256. cache: true,
  19257. transform: (x) => x,
  19258. packageProp: [name],
  19259. ...options,
  19260. loaders: {
  19261. ...sync ? defaultLoadersSync : defaultLoaders,
  19262. ...options.loaders
  19263. }
  19264. };
  19265. conf.searchPlaces.forEach((place) => {
  19266. const key = path$2.extname(place) || "noExt";
  19267. const loader = conf.loaders[key];
  19268. if (!loader) throw new Error(`Missing loader for extension "${place}"`);
  19269. if (typeof loader !== "function") throw new Error(`Loader for extension "${place}" is not a function: Received ${typeof loader}.`);
  19270. });
  19271. return conf;
  19272. }
  19273. /** @type {(props: string | string[], obj: Record<string, any>) => unknown} */
  19274. function getPackageProp(props, obj) {
  19275. if (typeof props === "string" && props in obj) return obj[props];
  19276. return (Array.isArray(props) ? props : props.split(".")).reduce((acc, prop) => acc === void 0 ? acc : acc[prop], obj) || null;
  19277. }
  19278. /** @param {string} filepath */
  19279. function validateFilePath(filepath) {
  19280. if (!filepath) throw new Error("load must pass a non-empty string");
  19281. }
  19282. /** @type {(loader: import('./index').Loader, ext: string) => void} */
  19283. function validateLoader(loader, ext) {
  19284. if (!loader) throw new Error(`No loader specified for extension "${ext}"`);
  19285. if (typeof loader !== "function") throw new Error("loader is not a function");
  19286. }
  19287. /** @type {(enableCache: boolean) => <T>(c: Map<string, T>, filepath: string, res: T) => T} */
  19288. const makeEmplace = (enableCache) => (c, filepath, res) => {
  19289. if (enableCache) c.set(filepath, res);
  19290. return res;
  19291. };
  19292. /** @type {import('./index').lilconfig} */
  19293. module.exports.lilconfig = function lilconfig(name, options) {
  19294. const { ignoreEmptySearchPlaces, loaders, packageProp, searchPlaces, stopDir, transform, cache } = getOptions(name, options ?? {}, false);
  19295. const searchCache = /* @__PURE__ */ new Map();
  19296. const loadCache = /* @__PURE__ */ new Map();
  19297. const emplace = makeEmplace(cache);
  19298. return {
  19299. async search(searchFrom = process.cwd()) {
  19300. /** @type {import('./index').LilconfigResult} */
  19301. const result = {
  19302. config: null,
  19303. filepath: ""
  19304. };
  19305. /** @type {Set<string>} */
  19306. const visited = /* @__PURE__ */ new Set();
  19307. let dir = searchFrom;
  19308. dirLoop: while (true) {
  19309. if (cache) {
  19310. const r = searchCache.get(dir);
  19311. if (r !== void 0) {
  19312. for (const p of visited) searchCache.set(p, r);
  19313. return r;
  19314. }
  19315. visited.add(dir);
  19316. }
  19317. for (const searchPlace of searchPlaces) {
  19318. const filepath = path$2.join(dir, searchPlace);
  19319. try {
  19320. await fs$2.promises.access(filepath);
  19321. } catch {
  19322. continue;
  19323. }
  19324. const content = String(await fsReadFileAsync(filepath));
  19325. const loaderKey = path$2.extname(searchPlace) || "noExt";
  19326. const loader = loaders[loaderKey];
  19327. if (searchPlace === "package.json") {
  19328. const maybeConfig = getPackageProp(packageProp, await loader(filepath, content));
  19329. if (maybeConfig != null) {
  19330. result.config = maybeConfig;
  19331. result.filepath = filepath;
  19332. break dirLoop;
  19333. }
  19334. continue;
  19335. }
  19336. const isEmpty = content.trim() === "";
  19337. if (isEmpty && ignoreEmptySearchPlaces) continue;
  19338. if (isEmpty) {
  19339. result.isEmpty = true;
  19340. result.config = void 0;
  19341. } else {
  19342. validateLoader(loader, loaderKey);
  19343. result.config = await loader(filepath, content);
  19344. }
  19345. result.filepath = filepath;
  19346. break dirLoop;
  19347. }
  19348. if (dir === stopDir || dir === parentDir(dir)) break dirLoop;
  19349. dir = parentDir(dir);
  19350. }
  19351. const transformed = result.filepath === "" && result.config === null ? transform(null) : transform(result);
  19352. if (cache) for (const p of visited) searchCache.set(p, transformed);
  19353. return transformed;
  19354. },
  19355. async load(filepath) {
  19356. validateFilePath(filepath);
  19357. const absPath = path$2.resolve(process.cwd(), filepath);
  19358. if (cache && loadCache.has(absPath)) return loadCache.get(absPath);
  19359. const { base, ext } = path$2.parse(absPath);
  19360. const loaderKey = ext || "noExt";
  19361. const loader = loaders[loaderKey];
  19362. validateLoader(loader, loaderKey);
  19363. const content = String(await fsReadFileAsync(absPath));
  19364. if (base === "package.json") return emplace(loadCache, absPath, transform({
  19365. config: getPackageProp(packageProp, await loader(absPath, content)),
  19366. filepath: absPath
  19367. }));
  19368. /** @type {import('./index').LilconfigResult} */
  19369. const result = {
  19370. config: null,
  19371. filepath: absPath
  19372. };
  19373. const isEmpty = content.trim() === "";
  19374. if (isEmpty && ignoreEmptySearchPlaces) return emplace(loadCache, absPath, transform({
  19375. config: void 0,
  19376. filepath: absPath,
  19377. isEmpty: true
  19378. }));
  19379. result.config = isEmpty ? void 0 : await loader(absPath, content);
  19380. return emplace(loadCache, absPath, transform(isEmpty ? {
  19381. ...result,
  19382. isEmpty,
  19383. config: void 0
  19384. } : result));
  19385. },
  19386. clearLoadCache() {
  19387. if (cache) loadCache.clear();
  19388. },
  19389. clearSearchCache() {
  19390. if (cache) searchCache.clear();
  19391. },
  19392. clearCaches() {
  19393. if (cache) {
  19394. loadCache.clear();
  19395. searchCache.clear();
  19396. }
  19397. }
  19398. };
  19399. };
  19400. /** @type {import('./index').lilconfigSync} */
  19401. module.exports.lilconfigSync = function lilconfigSync(name, options) {
  19402. const { ignoreEmptySearchPlaces, loaders, packageProp, searchPlaces, stopDir, transform, cache } = getOptions(name, options ?? {}, true);
  19403. const searchCache = /* @__PURE__ */ new Map();
  19404. const loadCache = /* @__PURE__ */ new Map();
  19405. const emplace = makeEmplace(cache);
  19406. return {
  19407. search(searchFrom = process.cwd()) {
  19408. /** @type {import('./index').LilconfigResult} */
  19409. const result = {
  19410. config: null,
  19411. filepath: ""
  19412. };
  19413. /** @type {Set<string>} */
  19414. const visited = /* @__PURE__ */ new Set();
  19415. let dir = searchFrom;
  19416. dirLoop: while (true) {
  19417. if (cache) {
  19418. const r = searchCache.get(dir);
  19419. if (r !== void 0) {
  19420. for (const p of visited) searchCache.set(p, r);
  19421. return r;
  19422. }
  19423. visited.add(dir);
  19424. }
  19425. for (const searchPlace of searchPlaces) {
  19426. const filepath = path$2.join(dir, searchPlace);
  19427. try {
  19428. fs$2.accessSync(filepath);
  19429. } catch {
  19430. continue;
  19431. }
  19432. const loaderKey = path$2.extname(searchPlace) || "noExt";
  19433. const loader = loaders[loaderKey];
  19434. const content = String(fs$2.readFileSync(filepath));
  19435. if (searchPlace === "package.json") {
  19436. const maybeConfig = getPackageProp(packageProp, loader(filepath, content));
  19437. if (maybeConfig != null) {
  19438. result.config = maybeConfig;
  19439. result.filepath = filepath;
  19440. break dirLoop;
  19441. }
  19442. continue;
  19443. }
  19444. const isEmpty = content.trim() === "";
  19445. if (isEmpty && ignoreEmptySearchPlaces) continue;
  19446. if (isEmpty) {
  19447. result.isEmpty = true;
  19448. result.config = void 0;
  19449. } else {
  19450. validateLoader(loader, loaderKey);
  19451. result.config = loader(filepath, content);
  19452. }
  19453. result.filepath = filepath;
  19454. break dirLoop;
  19455. }
  19456. if (dir === stopDir || dir === parentDir(dir)) break dirLoop;
  19457. dir = parentDir(dir);
  19458. }
  19459. const transformed = result.filepath === "" && result.config === null ? transform(null) : transform(result);
  19460. if (cache) for (const p of visited) searchCache.set(p, transformed);
  19461. return transformed;
  19462. },
  19463. load(filepath) {
  19464. validateFilePath(filepath);
  19465. const absPath = path$2.resolve(process.cwd(), filepath);
  19466. if (cache && loadCache.has(absPath)) return loadCache.get(absPath);
  19467. const { base, ext } = path$2.parse(absPath);
  19468. const loaderKey = ext || "noExt";
  19469. const loader = loaders[loaderKey];
  19470. validateLoader(loader, loaderKey);
  19471. const content = String(fs$2.readFileSync(absPath));
  19472. if (base === "package.json") return transform({
  19473. config: getPackageProp(packageProp, loader(absPath, content)),
  19474. filepath: absPath
  19475. });
  19476. const result = {
  19477. config: null,
  19478. filepath: absPath
  19479. };
  19480. const isEmpty = content.trim() === "";
  19481. if (isEmpty && ignoreEmptySearchPlaces) return emplace(loadCache, absPath, transform({
  19482. filepath: absPath,
  19483. config: void 0,
  19484. isEmpty: true
  19485. }));
  19486. result.config = isEmpty ? void 0 : loader(absPath, content);
  19487. return emplace(loadCache, absPath, transform(isEmpty ? {
  19488. ...result,
  19489. isEmpty,
  19490. config: void 0
  19491. } : result));
  19492. },
  19493. clearLoadCache() {
  19494. if (cache) loadCache.clear();
  19495. },
  19496. clearSearchCache() {
  19497. if (cache) searchCache.clear();
  19498. },
  19499. clearCaches() {
  19500. if (cache) {
  19501. loadCache.clear();
  19502. searchCache.clear();
  19503. }
  19504. }
  19505. };
  19506. };
  19507. }));
  19508. //#endregion
  19509. //#region ../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.6.1_postcss@8.5.8_tsx@4.21.0_yaml@2.8.2/node_modules/postcss-load-config/src/req.js
  19510. var require_req = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  19511. const { createRequire: createRequire$1 } = __require("node:module");
  19512. const { fileURLToPath: fileURLToPath$1, pathToFileURL: pathToFileURL$1 } = __require("node:url");
  19513. const TS_EXT_RE = /\.[mc]?ts$/;
  19514. let tsx;
  19515. let jiti;
  19516. let importError = [];
  19517. /**
  19518. * @param {string} name
  19519. * @param {string} rootFile
  19520. * @returns {Promise<any>}
  19521. */
  19522. async function req(name, rootFile = fileURLToPath$1(import.meta.url)) {
  19523. let url = createRequire$1(rootFile).resolve(name);
  19524. try {
  19525. return (await import(`${pathToFileURL$1(url)}?t=${Date.now()}`)).default;
  19526. } catch (err) {
  19527. if (!TS_EXT_RE.test(url))
  19528. /* c8 ignore start */
  19529. throw err;
  19530. }
  19531. if (tsx === void 0) try {
  19532. tsx = await import("tsx/cjs/api");
  19533. } catch (error) {
  19534. importError.push(error);
  19535. }
  19536. if (tsx) {
  19537. let loaded = tsx.require(name, rootFile);
  19538. return loaded && "__esModule" in loaded ? loaded.default : loaded;
  19539. }
  19540. if (jiti === void 0) try {
  19541. jiti = (await import("jiti")).default;
  19542. } catch (error) {
  19543. importError.push(error);
  19544. }
  19545. if (jiti) return jiti(rootFile, { interopDefault: true })(name);
  19546. throw new Error(`'tsx' or 'jiti' is required for the TypeScript configuration files. Make sure it is installed\nError: ${importError.map((error) => error.message).join("\n")}`);
  19547. }
  19548. module.exports = req;
  19549. }));
  19550. //#endregion
  19551. //#region ../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.6.1_postcss@8.5.8_tsx@4.21.0_yaml@2.8.2/node_modules/postcss-load-config/src/options.js
  19552. var require_options = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  19553. const req = require_req();
  19554. /**
  19555. * Load Options
  19556. *
  19557. * @private
  19558. * @method options
  19559. *
  19560. * @param {Object} config PostCSS Config
  19561. *
  19562. * @return {Promise<Object>} options PostCSS Options
  19563. */
  19564. async function options(config, file) {
  19565. if (config.parser && typeof config.parser === "string") try {
  19566. config.parser = await req(config.parser, file);
  19567. } catch (err) {
  19568. throw new Error(`Loading PostCSS Parser failed: ${err.message}\n\n(@${file})`);
  19569. }
  19570. if (config.syntax && typeof config.syntax === "string") try {
  19571. config.syntax = await req(config.syntax, file);
  19572. } catch (err) {
  19573. throw new Error(`Loading PostCSS Syntax failed: ${err.message}\n\n(@${file})`);
  19574. }
  19575. if (config.stringifier && typeof config.stringifier === "string") try {
  19576. config.stringifier = await req(config.stringifier, file);
  19577. } catch (err) {
  19578. throw new Error(`Loading PostCSS Stringifier failed: ${err.message}\n\n(@${file})`);
  19579. }
  19580. return config;
  19581. }
  19582. module.exports = options;
  19583. }));
  19584. //#endregion
  19585. //#region ../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.6.1_postcss@8.5.8_tsx@4.21.0_yaml@2.8.2/node_modules/postcss-load-config/src/plugins.js
  19586. var require_plugins = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  19587. const req = require_req();
  19588. /**
  19589. * Plugin Loader
  19590. *
  19591. * @private
  19592. * @method load
  19593. *
  19594. * @param {String} plugin PostCSS Plugin Name
  19595. * @param {Object} options PostCSS Plugin Options
  19596. *
  19597. * @return {Promise<Function>} PostCSS Plugin
  19598. */
  19599. async function load(plugin, options, file) {
  19600. try {
  19601. if (options === null || options === void 0 || Object.keys(options).length === 0) return await req(plugin, file);
  19602. else return (await req(plugin, file))(options);
  19603. } catch (err) {
  19604. throw new Error(`Loading PostCSS Plugin failed: ${err.message}\n\n(@${file})`);
  19605. }
  19606. }
  19607. /**
  19608. * Load Plugins
  19609. *
  19610. * @private
  19611. * @method plugins
  19612. *
  19613. * @param {Object} config PostCSS Config Plugins
  19614. *
  19615. * @return {Promise<Array>} plugins PostCSS Plugins
  19616. */
  19617. async function plugins(config, file) {
  19618. let list = [];
  19619. if (Array.isArray(config.plugins)) list = config.plugins.filter(Boolean);
  19620. else {
  19621. list = Object.entries(config.plugins).filter(([, options]) => {
  19622. return options !== false;
  19623. }).map(([plugin, options]) => {
  19624. return load(plugin, options, file);
  19625. });
  19626. list = await Promise.all(list);
  19627. }
  19628. if (list.length && list.length > 0) list.forEach((plugin, i) => {
  19629. if (plugin.default) plugin = plugin.default;
  19630. if (plugin.postcss === true) plugin = plugin();
  19631. else if (plugin.postcss) plugin = plugin.postcss;
  19632. if (!(typeof plugin === "object" && Array.isArray(plugin.plugins) || typeof plugin === "object" && plugin.postcssPlugin || typeof plugin === "function")) throw new TypeError(`Invalid PostCSS Plugin found at: plugins[${i}]\n\n(@${file})`);
  19633. });
  19634. return list;
  19635. }
  19636. module.exports = plugins;
  19637. }));
  19638. //#endregion
  19639. //#region ../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.6.1_postcss@8.5.8_tsx@4.21.0_yaml@2.8.2/node_modules/postcss-load-config/src/index.js
  19640. var require_src = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  19641. const { resolve: resolve$3 } = __require("node:path");
  19642. const config = require_src$1();
  19643. const loadOptions = require_options();
  19644. const loadPlugins = require_plugins();
  19645. const req = require_req();
  19646. const interopRequireDefault = (obj) => obj && obj.__esModule ? obj : { default: obj };
  19647. /**
  19648. * Process the result from cosmiconfig
  19649. *
  19650. * @param {Object} ctx Config Context
  19651. * @param {Object} result Cosmiconfig result
  19652. *
  19653. * @return {Promise<Object>} PostCSS Config
  19654. */
  19655. async function processResult(ctx, result) {
  19656. let file = result.filepath || "";
  19657. let projectConfig = interopRequireDefault(result.config).default || {};
  19658. if (typeof projectConfig === "function") projectConfig = projectConfig(ctx);
  19659. else projectConfig = Object.assign({}, projectConfig, ctx);
  19660. if (!projectConfig.plugins) projectConfig.plugins = [];
  19661. let res = {
  19662. file,
  19663. options: await loadOptions(projectConfig, file),
  19664. plugins: await loadPlugins(projectConfig, file)
  19665. };
  19666. delete projectConfig.plugins;
  19667. return res;
  19668. }
  19669. /**
  19670. * Builds the Config Context
  19671. *
  19672. * @param {Object} ctx Config Context
  19673. *
  19674. * @return {Object} Config Context
  19675. */
  19676. function createContext(ctx) {
  19677. /**
  19678. * @type {Object}
  19679. *
  19680. * @prop {String} cwd=process.cwd() Config search start location
  19681. * @prop {String} env=process.env.NODE_ENV Config Enviroment, will be set to `development` by `postcss-load-config` if `process.env.NODE_ENV` is `undefined`
  19682. */
  19683. ctx = Object.assign({
  19684. cwd: process.cwd(),
  19685. env: process.env.NODE_ENV
  19686. }, ctx);
  19687. if (!ctx.env) process.env.NODE_ENV = "development";
  19688. return ctx;
  19689. }
  19690. async function loader(filepath) {
  19691. return req(filepath);
  19692. }
  19693. let yaml;
  19694. async function yamlLoader(_, content) {
  19695. if (!yaml) try {
  19696. yaml = await import("yaml");
  19697. } catch (e) {
  19698. /* c8 ignore start */
  19699. throw new Error(`'yaml' is required for the YAML configuration files. Make sure it is installed\nError: ${e.message}`);
  19700. }
  19701. return yaml.parse(content);
  19702. }
  19703. /** @return {import('lilconfig').Options} */
  19704. const withLoaders = (options = {}) => {
  19705. let moduleName = "postcss";
  19706. return {
  19707. ...options,
  19708. loaders: {
  19709. ...options.loaders,
  19710. ".cjs": loader,
  19711. ".cts": loader,
  19712. ".js": loader,
  19713. ".mjs": loader,
  19714. ".mts": loader,
  19715. ".ts": loader,
  19716. ".yaml": yamlLoader,
  19717. ".yml": yamlLoader
  19718. },
  19719. searchPlaces: [
  19720. ...options.searchPlaces || [],
  19721. "package.json",
  19722. `.${moduleName}rc`,
  19723. `.${moduleName}rc.json`,
  19724. `.${moduleName}rc.yaml`,
  19725. `.${moduleName}rc.yml`,
  19726. `.${moduleName}rc.ts`,
  19727. `.${moduleName}rc.cts`,
  19728. `.${moduleName}rc.mts`,
  19729. `.${moduleName}rc.js`,
  19730. `.${moduleName}rc.cjs`,
  19731. `.${moduleName}rc.mjs`,
  19732. `${moduleName}.config.ts`,
  19733. `${moduleName}.config.cts`,
  19734. `${moduleName}.config.mts`,
  19735. `${moduleName}.config.js`,
  19736. `${moduleName}.config.cjs`,
  19737. `${moduleName}.config.mjs`
  19738. ]
  19739. };
  19740. };
  19741. /**
  19742. * Load Config
  19743. *
  19744. * @method rc
  19745. *
  19746. * @param {Object} ctx Config Context
  19747. * @param {String} path Config Path
  19748. * @param {Object} options Config Options
  19749. *
  19750. * @return {Promise} config PostCSS Config
  19751. */
  19752. function rc(ctx, path, options) {
  19753. /**
  19754. * @type {Object} The full Config Context
  19755. */
  19756. ctx = createContext(ctx);
  19757. /**
  19758. * @type {String} `process.cwd()`
  19759. */
  19760. path = path ? resolve$3(path) : process.cwd();
  19761. return config.lilconfig("postcss", withLoaders(options)).search(path).then((result) => {
  19762. if (!result) throw new Error(`No PostCSS Config found in: ${path}`);
  19763. return processResult(ctx, result);
  19764. });
  19765. }
  19766. /**
  19767. * Autoload Config for PostCSS
  19768. *
  19769. * @author Michael Ciniawsky @michael-ciniawsky <michael.ciniawsky@gmail.com>
  19770. * @license MIT
  19771. *
  19772. * @module postcss-load-config
  19773. * @version 2.1.0
  19774. *
  19775. * @requires comsiconfig
  19776. * @requires ./options
  19777. * @requires ./plugins
  19778. */
  19779. module.exports = rc;
  19780. }));
  19781. //#endregion
  19782. //#region src/node/server/sourcemap.ts
  19783. var import_convert_source_map = /* @__PURE__ */ __toESM((/* @__PURE__ */ __commonJSMin(((exports) => {
  19784. Object.defineProperty(exports, "commentRegex", { get: function getCommentRegex() {
  19785. return /^\s*?\/[\/\*][@#]\s+?sourceMappingURL=data:(((?:application|text)\/json)(?:;charset=([^;,]+?)?)?)?(?:;(base64))?,(.*?)$/gm;
  19786. } });
  19787. Object.defineProperty(exports, "mapFileCommentRegex", { get: function getMapFileCommentRegex() {
  19788. return /(?:\/\/[@#][ \t]+?sourceMappingURL=([^\s'"`]+?)[ \t]*?$)|(?:\/\*[@#][ \t]+sourceMappingURL=([^*]+?)[ \t]*?(?:\*\/){1}[ \t]*?$)/gm;
  19789. } });
  19790. var decodeBase64;
  19791. if (typeof Buffer !== "undefined") if (typeof Buffer.from === "function") decodeBase64 = decodeBase64WithBufferFrom;
  19792. else decodeBase64 = decodeBase64WithNewBuffer;
  19793. else decodeBase64 = decodeBase64WithAtob;
  19794. function decodeBase64WithBufferFrom(base64) {
  19795. return Buffer.from(base64, "base64").toString();
  19796. }
  19797. function decodeBase64WithNewBuffer(base64) {
  19798. if (typeof value === "number") throw new TypeError("The value to decode must not be of type number.");
  19799. return new Buffer(base64, "base64").toString();
  19800. }
  19801. function decodeBase64WithAtob(base64) {
  19802. return decodeURIComponent(escape(atob(base64)));
  19803. }
  19804. function stripComment(sm) {
  19805. return sm.split(",").pop();
  19806. }
  19807. function readFromFileMap(sm, read) {
  19808. var r = exports.mapFileCommentRegex.exec(sm);
  19809. var filename = r[1] || r[2];
  19810. try {
  19811. var sm = read(filename);
  19812. if (sm != null && typeof sm.catch === "function") return sm.catch(throwError);
  19813. else return sm;
  19814. } catch (e) {
  19815. throwError(e);
  19816. }
  19817. function throwError(e) {
  19818. throw new Error("An error occurred while trying to read the map file at " + filename + "\n" + e.stack);
  19819. }
  19820. }
  19821. function Converter(sm, opts) {
  19822. opts = opts || {};
  19823. if (opts.hasComment) sm = stripComment(sm);
  19824. if (opts.encoding === "base64") sm = decodeBase64(sm);
  19825. else if (opts.encoding === "uri") sm = decodeURIComponent(sm);
  19826. if (opts.isJSON || opts.encoding) sm = JSON.parse(sm);
  19827. this.sourcemap = sm;
  19828. }
  19829. Converter.prototype.toJSON = function(space) {
  19830. return JSON.stringify(this.sourcemap, null, space);
  19831. };
  19832. if (typeof Buffer !== "undefined") if (typeof Buffer.from === "function") Converter.prototype.toBase64 = encodeBase64WithBufferFrom;
  19833. else Converter.prototype.toBase64 = encodeBase64WithNewBuffer;
  19834. else Converter.prototype.toBase64 = encodeBase64WithBtoa;
  19835. function encodeBase64WithBufferFrom() {
  19836. var json = this.toJSON();
  19837. return Buffer.from(json, "utf8").toString("base64");
  19838. }
  19839. function encodeBase64WithNewBuffer() {
  19840. var json = this.toJSON();
  19841. if (typeof json === "number") throw new TypeError("The json to encode must not be of type number.");
  19842. return new Buffer(json, "utf8").toString("base64");
  19843. }
  19844. function encodeBase64WithBtoa() {
  19845. var json = this.toJSON();
  19846. return btoa(unescape(encodeURIComponent(json)));
  19847. }
  19848. Converter.prototype.toURI = function() {
  19849. var json = this.toJSON();
  19850. return encodeURIComponent(json);
  19851. };
  19852. Converter.prototype.toComment = function(options) {
  19853. var encoding, content, data;
  19854. if (options != null && options.encoding === "uri") {
  19855. encoding = "";
  19856. content = this.toURI();
  19857. } else {
  19858. encoding = ";base64";
  19859. content = this.toBase64();
  19860. }
  19861. data = "sourceMappingURL=data:application/json;charset=utf-8" + encoding + "," + content;
  19862. return options != null && options.multiline ? "/*# " + data + " */" : "//# " + data;
  19863. };
  19864. Converter.prototype.toObject = function() {
  19865. return JSON.parse(this.toJSON());
  19866. };
  19867. Converter.prototype.addProperty = function(key, value) {
  19868. if (this.sourcemap.hasOwnProperty(key)) throw new Error("property \"" + key + "\" already exists on the sourcemap, use set property instead");
  19869. return this.setProperty(key, value);
  19870. };
  19871. Converter.prototype.setProperty = function(key, value) {
  19872. this.sourcemap[key] = value;
  19873. return this;
  19874. };
  19875. Converter.prototype.getProperty = function(key) {
  19876. return this.sourcemap[key];
  19877. };
  19878. exports.fromObject = function(obj) {
  19879. return new Converter(obj);
  19880. };
  19881. exports.fromJSON = function(json) {
  19882. return new Converter(json, { isJSON: true });
  19883. };
  19884. exports.fromURI = function(uri) {
  19885. return new Converter(uri, { encoding: "uri" });
  19886. };
  19887. exports.fromBase64 = function(base64) {
  19888. return new Converter(base64, { encoding: "base64" });
  19889. };
  19890. exports.fromComment = function(comment) {
  19891. var m, encoding;
  19892. comment = comment.replace(/^\/\*/g, "//").replace(/\*\/$/g, "");
  19893. m = exports.commentRegex.exec(comment);
  19894. encoding = m && m[4] || "uri";
  19895. return new Converter(comment, {
  19896. encoding,
  19897. hasComment: true
  19898. });
  19899. };
  19900. function makeConverter(sm) {
  19901. return new Converter(sm, { isJSON: true });
  19902. }
  19903. exports.fromMapFileComment = function(comment, read) {
  19904. if (typeof read === "string") throw new Error("String directory paths are no longer supported with `fromMapFileComment`\nPlease review the Upgrading documentation at https://github.com/thlorenz/convert-source-map#upgrading");
  19905. var sm = readFromFileMap(comment, read);
  19906. if (sm != null && typeof sm.then === "function") return sm.then(makeConverter);
  19907. else return makeConverter(sm);
  19908. };
  19909. exports.fromSource = function(content) {
  19910. var m = content.match(exports.commentRegex);
  19911. return m ? exports.fromComment(m.pop()) : null;
  19912. };
  19913. exports.fromMapFileSource = function(content, read) {
  19914. if (typeof read === "string") throw new Error("String directory paths are no longer supported with `fromMapFileSource`\nPlease review the Upgrading documentation at https://github.com/thlorenz/convert-source-map#upgrading");
  19915. var m = content.match(exports.mapFileCommentRegex);
  19916. return m ? exports.fromMapFileComment(m.pop(), read) : null;
  19917. };
  19918. exports.removeComments = function(src) {
  19919. return src.replace(exports.commentRegex, "");
  19920. };
  19921. exports.removeMapFileComments = function(src) {
  19922. return src.replace(exports.mapFileCommentRegex, "");
  19923. };
  19924. exports.generateMapFileComment = function(file, options) {
  19925. var data = "sourceMappingURL=" + file;
  19926. return options && options.multiline ? "/*# " + data + " */" : "//# " + data;
  19927. };
  19928. })))(), 1);
  19929. const debug$10 = createDebugger("vite:sourcemap", { onlyWhenFocused: true });
  19930. /**
  19931. * Given a file path inside node_modules, returns the package root directory.
  19932. * For scoped packages like `node_modules/@scope/pkg/dist/foo.js`, returns `node_modules/@scope/pkg`.
  19933. * Returns `undefined` if the file is not inside node_modules.
  19934. */
  19935. function getNodeModulesPackageRoot(filePath) {
  19936. const normalized = normalizePath(filePath);
  19937. const nodeModulesIndex = normalized.lastIndexOf("/node_modules/");
  19938. if (nodeModulesIndex === -1) return void 0;
  19939. const packageStart = nodeModulesIndex + 14;
  19940. const rest = normalized.slice(packageStart);
  19941. const firstSlash = rest.indexOf("/");
  19942. let packageName;
  19943. if (rest.startsWith("@")) {
  19944. const secondSlash = rest.indexOf("/", firstSlash + 1);
  19945. packageName = secondSlash === -1 ? rest : rest.slice(0, secondSlash);
  19946. } else packageName = firstSlash === -1 ? rest : rest.slice(0, firstSlash);
  19947. return normalized.slice(0, packageStart) + packageName;
  19948. }
  19949. const virtualSourceRE = /^(?:dep:|browser-external:|virtual:)|\0/;
  19950. async function computeSourceRoute(map, file) {
  19951. let sourceRoot;
  19952. try {
  19953. sourceRoot = await fsp.realpath(path.resolve(path.dirname(file), map.sourceRoot || ""));
  19954. } catch {}
  19955. return sourceRoot;
  19956. }
  19957. async function injectSourcesContent(map, file, logger) {
  19958. let sourceRootPromise;
  19959. const packageRoot = getNodeModulesPackageRoot(file);
  19960. const missingSources = [];
  19961. const sourcesContent = map.sourcesContent || [];
  19962. const sourcesContentPromises = [];
  19963. for (let index = 0; index < map.sources.length; index++) {
  19964. const sourcePath = map.sources[index];
  19965. if (sourcesContent[index] == null && sourcePath && !virtualSourceRE.test(sourcePath)) sourcesContentPromises.push((async () => {
  19966. sourceRootPromise ??= computeSourceRoute(map, file);
  19967. const sourceRoot = await sourceRootPromise;
  19968. let resolvedSourcePath = cleanUrl(decodeURI(sourcePath));
  19969. if (sourceRoot) resolvedSourcePath = path.resolve(sourceRoot, resolvedSourcePath);
  19970. if (packageRoot) {
  19971. const resolvedSourcePathNormalized = normalizePath(path.resolve(resolvedSourcePath));
  19972. if (!isParentDirectory(packageRoot, resolvedSourcePathNormalized)) {
  19973. sourcesContent[index] = null;
  19974. logger.warnOnce(import_picocolors.default.yellow(`Sourcemap for ${JSON.stringify(file)} points to a source file outside its package: ${JSON.stringify(resolvedSourcePathNormalized)}`));
  19975. return;
  19976. }
  19977. }
  19978. sourcesContent[index] = await fsp.readFile(resolvedSourcePath, "utf-8").catch(() => {
  19979. missingSources.push(resolvedSourcePath);
  19980. return null;
  19981. });
  19982. })());
  19983. }
  19984. await Promise.all(sourcesContentPromises);
  19985. map.sourcesContent = sourcesContent;
  19986. if (missingSources.length) {
  19987. logger.warnOnce(`Sourcemap for "${file}" points to missing source files`);
  19988. debug$10?.(`Missing sources:\n ` + missingSources.join(`\n `));
  19989. }
  19990. }
  19991. function genSourceMapUrl(map) {
  19992. if (typeof map !== "string") map = JSON.stringify(map);
  19993. return `data:application/json;base64,${Buffer.from(map).toString("base64")}`;
  19994. }
  19995. function getCodeWithSourcemap(type, code, map) {
  19996. if (debug$10) code += `\n/*${JSON.stringify(map, null, 2).replace(/\*\//g, "*\\/")}*/\n`;
  19997. if (type === "js") code += `\n//# sourceMappingURL=${genSourceMapUrl(map)}`;
  19998. else if (type === "css") code += `\n/*# sourceMappingURL=${genSourceMapUrl(map)} */`;
  19999. return code;
  20000. }
  20001. function applySourcemapIgnoreList(map, sourcemapPath, sourcemapIgnoreList, logger) {
  20002. let { x_google_ignoreList } = map;
  20003. if (x_google_ignoreList === void 0) x_google_ignoreList = [];
  20004. if (map.sources) {
  20005. for (let sourcesIndex = 0; sourcesIndex < map.sources.length; ++sourcesIndex) {
  20006. const sourcePath = map.sources[sourcesIndex];
  20007. if (!sourcePath) continue;
  20008. const ignoreList = sourcemapIgnoreList(path.isAbsolute(sourcePath) ? sourcePath : path.resolve(path.dirname(sourcemapPath), sourcePath), sourcemapPath);
  20009. if (logger && typeof ignoreList !== "boolean") logger.warn("sourcemapIgnoreList function must return a boolean.");
  20010. if (ignoreList && !x_google_ignoreList.includes(sourcesIndex)) x_google_ignoreList.push(sourcesIndex);
  20011. }
  20012. if (x_google_ignoreList.length > 0) {
  20013. if (!map.x_google_ignoreList) map.x_google_ignoreList = x_google_ignoreList;
  20014. }
  20015. }
  20016. }
  20017. function extractSourcemapFromFile(code, filePath, logger) {
  20018. const map = (import_convert_source_map.fromSource(code) || import_convert_source_map.fromMapFileSource(code, createConvertSourceMapReadMap(filePath, logger)))?.toObject();
  20019. if (map) return {
  20020. code: code.replace(import_convert_source_map.default.mapFileCommentRegex, blankReplacer),
  20021. map
  20022. };
  20023. }
  20024. function createConvertSourceMapReadMap(originalFileName, logger) {
  20025. const packageRoot = getNodeModulesPackageRoot(originalFileName);
  20026. return (filename) => {
  20027. const resolvedPath = path.resolve(path.dirname(originalFileName), filename);
  20028. if (packageRoot && !isParentDirectory(packageRoot, normalizePath(resolvedPath))) {
  20029. logger.warnOnce(import_picocolors.default.yellow(`Sourcemap in "${originalFileName}" references a map file outside its package: "${filename}"`));
  20030. return "{}";
  20031. }
  20032. return fs.readFileSync(resolvedPath, "utf-8");
  20033. };
  20034. }
  20035. //#endregion
  20036. //#region src/node/idResolver.ts
  20037. /**
  20038. * Some projects like Astro were overriding config.createResolver to add a custom
  20039. * alias plugin. For the client and ssr environments, we root through it to avoid
  20040. * breaking changes for now.
  20041. */
  20042. function createBackCompatIdResolver(config, options) {
  20043. const compatResolve = config.createResolver(options);
  20044. let resolve;
  20045. return async (environment, id, importer, aliasOnly) => {
  20046. if (environment.name === "client" || environment.name === "ssr") return compatResolve(id, importer, aliasOnly, environment.name === "ssr");
  20047. resolve ??= createIdResolver(config, options);
  20048. return resolve(environment, id, importer, aliasOnly);
  20049. };
  20050. }
  20051. /**
  20052. * Create an internal resolver to be used in special scenarios, e.g.
  20053. * optimizer and handling css @imports
  20054. */
  20055. function createIdResolver(config, options) {
  20056. const scan = options?.scan;
  20057. const pluginContainerMap = /* @__PURE__ */ new Map();
  20058. async function resolve(environment, id, importer) {
  20059. let pluginContainer = pluginContainerMap.get(environment);
  20060. if (!pluginContainer) {
  20061. pluginContainer = await createEnvironmentPluginContainer(environment, [alias$1({ entries: environment.config.resolve.alias }), ...oxcResolvePlugin({
  20062. root: config.root,
  20063. isProduction: config.isProduction,
  20064. isBuild: config.command === "build",
  20065. asSrc: true,
  20066. preferRelative: false,
  20067. tryIndex: true,
  20068. ...options,
  20069. idOnly: true
  20070. }, environment.config)], void 0, false);
  20071. pluginContainerMap.set(environment, pluginContainer);
  20072. }
  20073. return await pluginContainer.resolveId(id, importer, { scan });
  20074. }
  20075. const aliasOnlyPluginContainerMap = /* @__PURE__ */ new Map();
  20076. async function resolveAlias(environment, id, importer) {
  20077. let pluginContainer = aliasOnlyPluginContainerMap.get(environment);
  20078. if (!pluginContainer) {
  20079. pluginContainer = await createEnvironmentPluginContainer(environment, [alias$1({ entries: environment.config.resolve.alias })], void 0, false);
  20080. aliasOnlyPluginContainerMap.set(environment, pluginContainer);
  20081. }
  20082. return await pluginContainer.resolveId(id, importer, { scan });
  20083. }
  20084. return async (environment, id, importer, aliasOnly) => {
  20085. return (await (aliasOnly ? resolveAlias : resolve)(environment, id, importer))?.id;
  20086. };
  20087. }
  20088. //#endregion
  20089. //#region src/node/baseEnvironment.ts
  20090. const environmentColors = [
  20091. import_picocolors.default.blue,
  20092. import_picocolors.default.magenta,
  20093. import_picocolors.default.green,
  20094. import_picocolors.default.gray
  20095. ];
  20096. var PartialEnvironment = class {
  20097. name;
  20098. getTopLevelConfig() {
  20099. return this._topLevelConfig;
  20100. }
  20101. config;
  20102. logger;
  20103. /**
  20104. * @internal
  20105. */
  20106. _options;
  20107. /**
  20108. * @internal
  20109. */
  20110. _topLevelConfig;
  20111. constructor(name, topLevelConfig, options = topLevelConfig.environments[name]) {
  20112. if (!/^[\w$]+$/.test(name)) throw new Error(`Invalid environment name "${name}". Environment names must only contain alphanumeric characters and "$", "_".`);
  20113. this.name = name;
  20114. this._topLevelConfig = topLevelConfig;
  20115. this._options = options;
  20116. this.config = new Proxy(options, { get: (target, prop) => {
  20117. if (prop === "logger") return this.logger;
  20118. if (prop in target) return this._options[prop];
  20119. return this._topLevelConfig[prop];
  20120. } });
  20121. const environment = import_picocolors.default.dim(`(${this.name})`);
  20122. const infoColor = environmentColors[[...this.name].reduce((acc, c) => acc + c.charCodeAt(0), 0) % environmentColors.length || 0];
  20123. this.logger = {
  20124. get hasWarned() {
  20125. return topLevelConfig.logger.hasWarned;
  20126. },
  20127. info(msg, opts) {
  20128. return topLevelConfig.logger.info(msg, {
  20129. ...opts,
  20130. environment: infoColor(environment)
  20131. });
  20132. },
  20133. warn(msg, opts) {
  20134. return topLevelConfig.logger.warn(msg, {
  20135. ...opts,
  20136. environment: import_picocolors.default.yellow(environment)
  20137. });
  20138. },
  20139. warnOnce(msg, opts) {
  20140. return topLevelConfig.logger.warnOnce(msg, {
  20141. ...opts,
  20142. environment: import_picocolors.default.yellow(environment)
  20143. });
  20144. },
  20145. error(msg, opts) {
  20146. return topLevelConfig.logger.error(msg, {
  20147. ...opts,
  20148. environment: import_picocolors.default.red(environment)
  20149. });
  20150. },
  20151. clearScreen(type) {
  20152. return topLevelConfig.logger.clearScreen(type);
  20153. },
  20154. hasErrorLogged(error) {
  20155. return topLevelConfig.logger.hasErrorLogged(error);
  20156. }
  20157. };
  20158. }
  20159. };
  20160. var BaseEnvironment = class extends PartialEnvironment {
  20161. get plugins() {
  20162. return this.config.plugins;
  20163. }
  20164. /**
  20165. * @internal
  20166. */
  20167. _initiated = false;
  20168. constructor(name, config, options = config.environments[name]) {
  20169. super(name, config, options);
  20170. }
  20171. };
  20172. //#endregion
  20173. //#region src/node/server/searchRoot.ts
  20174. const ROOT_FILES = ["pnpm-workspace.yaml", "lerna.json"];
  20175. function hasWorkspacePackageJSON(root) {
  20176. const path = join(root, "package.json");
  20177. if (!isFileReadable(path)) return false;
  20178. try {
  20179. return !!(JSON.parse(fs.readFileSync(path, "utf-8")) || {}).workspaces;
  20180. } catch {
  20181. return false;
  20182. }
  20183. }
  20184. function hasRootFile(root) {
  20185. return ROOT_FILES.some((file) => fs.existsSync(join(root, file)));
  20186. }
  20187. function hasPackageJSON(root) {
  20188. const path = join(root, "package.json");
  20189. return fs.existsSync(path);
  20190. }
  20191. /**
  20192. * Search up for the nearest `package.json`
  20193. */
  20194. function searchForPackageRoot(current, root = current) {
  20195. if (hasPackageJSON(current)) return current;
  20196. const dir = dirname(current);
  20197. if (!dir || dir === current) return root;
  20198. return searchForPackageRoot(dir, root);
  20199. }
  20200. /**
  20201. * Search up for the nearest workspace root
  20202. */
  20203. function searchForWorkspaceRoot(current, root = searchForPackageRoot(current)) {
  20204. if (hasRootFile(current)) return current;
  20205. if (hasWorkspacePackageJSON(current)) return current;
  20206. const dir = dirname(current);
  20207. if (!dir || dir === current) return root;
  20208. return searchForWorkspaceRoot(dir, root);
  20209. }
  20210. //#endregion
  20211. //#region src/node/plugins/manifest.ts
  20212. const endsWithJSRE = /\.[cm]?js$/;
  20213. function manifestPlugin() {
  20214. const getState = perEnvironmentState(() => {
  20215. return {
  20216. manifest: {},
  20217. outputCount: 0,
  20218. reset() {
  20219. this.manifest = {};
  20220. this.outputCount = 0;
  20221. }
  20222. };
  20223. });
  20224. return perEnvironmentPlugin("native:manifest", (environment) => {
  20225. if (!environment.config.build.manifest) return false;
  20226. const root = environment.config.root;
  20227. const outPath = environment.config.build.manifest === true ? ".vite/manifest.json" : environment.config.build.manifest;
  20228. const envs = {};
  20229. function getChunkName(chunk) {
  20230. return getChunkOriginalFileName(chunk, root, false) ?? `_${path.basename(chunk.fileName)}`;
  20231. }
  20232. return [
  20233. {
  20234. name: "native:manifest-envs",
  20235. buildStart() {
  20236. envs[environment.name] = this.environment;
  20237. }
  20238. },
  20239. viteManifestPlugin({
  20240. root,
  20241. outPath,
  20242. isOutputOptionsForLegacyChunks: environment.config.isOutputOptionsForLegacyChunks,
  20243. cssEntries() {
  20244. return Object.fromEntries(cssEntriesMap.get(envs[environment.name]).entries());
  20245. }
  20246. }),
  20247. {
  20248. name: "native:manifest-compatible",
  20249. generateBundle(_, bundle) {
  20250. const asset = bundle[outPath];
  20251. if (asset.type === "asset") {
  20252. let manifest;
  20253. for (const output of Object.values(bundle)) {
  20254. const importedCss = output.viteMetadata?.importedCss;
  20255. const importedAssets = output.viteMetadata?.importedAssets;
  20256. if (!importedCss?.size && !importedAssets?.size) continue;
  20257. manifest ??= JSON.parse(asset.source.toString());
  20258. if (output.type === "chunk") {
  20259. const item = manifest[getChunkName(output)];
  20260. if (!item) continue;
  20261. if (importedCss?.size) item.css = [...importedCss];
  20262. if (importedAssets?.size) item.assets = [...importedAssets];
  20263. } else if (output.type === "asset" && output.names.length > 0) {
  20264. const keys = output.originalFileNames.length > 0 ? output.originalFileNames : [`_${path.basename(output.fileName)}`];
  20265. for (const key of keys) {
  20266. const item = manifest[key];
  20267. if (!item) continue;
  20268. if (!(item.file && endsWithJSRE.test(item.file))) {
  20269. if (importedCss?.size) item.css = [...importedCss];
  20270. if (importedAssets?.size) item.assets = [...importedAssets];
  20271. }
  20272. }
  20273. }
  20274. }
  20275. const output = this.environment.config.build.rolldownOptions.output;
  20276. const outputLength = Array.isArray(output) ? output.length : 1;
  20277. if (manifest && outputLength === 1) {
  20278. asset.source = JSON.stringify(manifest, void 0, 2);
  20279. return;
  20280. }
  20281. const state = getState(this);
  20282. state.outputCount++;
  20283. state.manifest = Object.assign(state.manifest, manifest ?? JSON.parse(asset.source.toString()));
  20284. if (state.outputCount >= outputLength) {
  20285. asset.source = JSON.stringify(state.manifest, void 0, 2);
  20286. state.reset();
  20287. } else delete bundle[outPath];
  20288. }
  20289. }
  20290. }
  20291. ];
  20292. });
  20293. }
  20294. function getChunkOriginalFileName(chunk, root, isLegacy) {
  20295. if (chunk.facadeModuleId) {
  20296. let name = normalizePath(path.relative(root, chunk.facadeModuleId));
  20297. if (isLegacy && !chunk.name.includes("-legacy")) {
  20298. const ext = path.extname(name);
  20299. const endPos = ext.length !== 0 ? -ext.length : void 0;
  20300. name = `${name.slice(0, endPos)}-legacy${ext}`;
  20301. }
  20302. return name.replace(/\0/g, "");
  20303. }
  20304. }
  20305. //#endregion
  20306. //#region src/node/plugins/css.ts
  20307. var import_src = /* @__PURE__ */ __toESM(require_src(), 1);
  20308. const decoder = new TextDecoder();
  20309. const _cssConfigDefaults = Object.freeze({
  20310. transformer: "postcss",
  20311. preprocessorMaxWorkers: true,
  20312. devSourcemap: false
  20313. });
  20314. const cssConfigDefaults = _cssConfigDefaults;
  20315. function resolveCSSOptions(options) {
  20316. const resolved = mergeWithDefaults(_cssConfigDefaults, options ?? {});
  20317. if (resolved.transformer === "lightningcss") {
  20318. resolved.lightningcss ??= {};
  20319. resolved.lightningcss.targets ??= convertTargets(ESBUILD_BASELINE_WIDELY_AVAILABLE_TARGET);
  20320. }
  20321. return resolved;
  20322. }
  20323. const cssModuleRE = new RegExp(`\\.module${CSS_LANGS_RE.source}`);
  20324. const directRequestRE = /[?&]direct\b/;
  20325. const htmlProxyRE$1 = /[?&]html-proxy\b/;
  20326. const htmlProxyIndexRE = /&index=(\d+)/;
  20327. const commonjsProxyRE = /[?&]commonjs-proxy/;
  20328. const inlineRE$2 = /[?&]inline\b/;
  20329. const inlineCSSRE$1 = /[?&]inline-css\b/;
  20330. const styleAttrRE = /[?&]style-attr\b/;
  20331. const functionCallRE = /^[A-Z_][.\w-]*\(/i;
  20332. const transformOnlyRE = /[?&]transform-only\b/;
  20333. const nonEscapedDoubleQuoteRe = /(?<!\\)"/g;
  20334. const defaultCssBundleName = "style.css";
  20335. var PreprocessLang = /* @__PURE__ */ function(PreprocessLang) {
  20336. PreprocessLang["less"] = "less";
  20337. PreprocessLang["sass"] = "sass";
  20338. PreprocessLang["scss"] = "scss";
  20339. PreprocessLang["styl"] = "styl";
  20340. PreprocessLang["stylus"] = "stylus";
  20341. return PreprocessLang;
  20342. }(PreprocessLang || {});
  20343. var PostCssDialectLang = /* @__PURE__ */ function(PostCssDialectLang) {
  20344. PostCssDialectLang["sss"] = "sugarss";
  20345. return PostCssDialectLang;
  20346. }(PostCssDialectLang || {});
  20347. const isModuleCSSRequest = (request) => cssModuleRE.test(request);
  20348. const isDirectCSSRequest = (request) => CSS_LANGS_RE.test(request) && directRequestRE.test(request);
  20349. const isDirectRequest = (request) => directRequestRE.test(request);
  20350. const cssModulesCache = /* @__PURE__ */ new WeakMap();
  20351. const removedPureCssFilesCache = /* @__PURE__ */ new WeakMap();
  20352. const cssBundleNameCache = /* @__PURE__ */ new WeakMap();
  20353. const postcssConfigCache = /* @__PURE__ */ new WeakMap();
  20354. function encodePublicUrlsInCSS(config) {
  20355. return config.command === "build";
  20356. }
  20357. const cssUrlAssetRE = /__VITE_CSS_URL__([\da-f]+)__/g;
  20358. /**
  20359. * Plugin applied before user plugins
  20360. */
  20361. function cssPlugin(config) {
  20362. const isBuild = config.command === "build";
  20363. let moduleCache;
  20364. const idResolver = createBackCompatIdResolver(config, {
  20365. preferRelative: true,
  20366. tryIndex: false,
  20367. extensions: []
  20368. });
  20369. let preprocessorWorkerController;
  20370. if (config.css.transformer !== "lightningcss") resolvePostcssConfig(config).catch(() => {});
  20371. return {
  20372. name: "vite:css",
  20373. buildStart() {
  20374. moduleCache = /* @__PURE__ */ new Map();
  20375. cssModulesCache.set(config, moduleCache);
  20376. removedPureCssFilesCache.set(config, /* @__PURE__ */ new Map());
  20377. preprocessorWorkerController = createPreprocessorWorkerController(normalizeMaxWorkers(config.css.preprocessorMaxWorkers));
  20378. preprocessorWorkerControllerCache.set(config, preprocessorWorkerController);
  20379. },
  20380. buildEnd() {
  20381. preprocessorWorkerController?.close();
  20382. },
  20383. load: {
  20384. filter: { id: CSS_LANGS_RE },
  20385. async handler(id) {
  20386. if (urlRE$1.test(id)) {
  20387. if (isModuleCSSRequest(id)) throw new Error(`?url is not supported with CSS modules. (tried to import ${JSON.stringify(id)})`);
  20388. if (isBuild) {
  20389. id = injectQuery(removeUrlQuery(id), "transform-only");
  20390. return `import ${JSON.stringify(id)};export default "__VITE_CSS_URL__${Buffer.from(id).toString("hex")}__"`;
  20391. }
  20392. }
  20393. }
  20394. },
  20395. transform: {
  20396. filter: { id: {
  20397. include: CSS_LANGS_RE,
  20398. exclude: [commonjsProxyRE, SPECIAL_QUERY_RE]
  20399. } },
  20400. async handler(raw, id) {
  20401. const { environment } = this;
  20402. const resolveUrl = (url, importer) => idResolver(environment, url, importer);
  20403. const urlResolver = async (url, importer) => {
  20404. const decodedUrl = decodeURI(url);
  20405. if (checkPublicFile(decodedUrl, config)) if (encodePublicUrlsInCSS(config)) return [publicFileToBuiltUrl(decodedUrl, config), void 0];
  20406. else return [joinUrlSegments(joinUrlSegments(config.server.origin ?? "", config.base), decodedUrl), void 0];
  20407. const [id, fragment] = decodedUrl.split("#");
  20408. let resolved = await resolveUrl(id, importer);
  20409. if (resolved) {
  20410. if (fragment) resolved += "#" + fragment;
  20411. let url = await fileToUrl$1(this, resolved);
  20412. if (!url.startsWith("data:") && this.environment.mode === "dev") {
  20413. const mod = [...this.environment.moduleGraph.getModulesByFile(resolved) ?? []].find((mod) => mod.type === "asset");
  20414. if (mod?.lastHMRTimestamp) url = injectQuery(url, `t=${mod.lastHMRTimestamp}`);
  20415. }
  20416. return [url, cleanUrl(resolved)];
  20417. }
  20418. if (config.command === "build") {
  20419. if (!(config.build.rollupOptions.external ? resolveUserExternal(config.build.rollupOptions.external, decodedUrl, id, false) : false)) config.logger.warnOnce(`\n${decodedUrl} referenced in ${id} didn't resolve at build time, it will remain unchanged to be resolved at runtime`);
  20420. }
  20421. return [url, void 0];
  20422. };
  20423. const { code: css, modules, deps, map } = await compileCSS(environment, id, raw, preprocessorWorkerController, urlResolver);
  20424. if (modules) moduleCache.set(id, modules);
  20425. if (deps) for (const file of deps) this.addWatchFile(file);
  20426. return {
  20427. code: css,
  20428. map
  20429. };
  20430. }
  20431. }
  20432. };
  20433. }
  20434. /**
  20435. * Plugin applied after user plugins
  20436. */
  20437. function cssPostPlugin(config) {
  20438. const styles = /* @__PURE__ */ new Map();
  20439. let codeSplitEmitQueue = createSerialPromiseQueue();
  20440. const urlEmitQueue = createSerialPromiseQueue();
  20441. let pureCssChunks;
  20442. let hasEmitted = false;
  20443. let chunkCSSMap;
  20444. const rollupOptionsOutput = config.build.rollupOptions.output;
  20445. const assetFileNames = (Array.isArray(rollupOptionsOutput) ? rollupOptionsOutput[0] : rollupOptionsOutput)?.assetFileNames;
  20446. const getCssAssetDirname = (cssAssetName, originalFileName) => {
  20447. const cssAssetNameDir = path.dirname(cssAssetName);
  20448. if (!assetFileNames) return path.join(config.build.assetsDir, cssAssetNameDir);
  20449. else if (typeof assetFileNames === "string") return path.join(path.dirname(assetFileNames), cssAssetNameDir);
  20450. else return path.dirname(assetFileNames({
  20451. type: "asset",
  20452. names: [cssAssetName],
  20453. originalFileNames: originalFileName ? [originalFileName] : [],
  20454. source: "/* vite internal call, ignore */"
  20455. }));
  20456. };
  20457. function getCssBundleName() {
  20458. const cached = cssBundleNameCache.get(config);
  20459. if (cached) return cached;
  20460. const cssBundleName = config.build.lib ? resolveLibCssFilename(config.build.lib, config.root, config.packageCache) : defaultCssBundleName;
  20461. cssBundleNameCache.set(config, cssBundleName);
  20462. return cssBundleName;
  20463. }
  20464. return {
  20465. name: "vite:css-post",
  20466. renderStart() {
  20467. pureCssChunks = /* @__PURE__ */ new Set();
  20468. hasEmitted = false;
  20469. chunkCSSMap = /* @__PURE__ */ new Map();
  20470. codeSplitEmitQueue = createSerialPromiseQueue();
  20471. },
  20472. transform: {
  20473. filter: { id: {
  20474. include: CSS_LANGS_RE,
  20475. exclude: [commonjsProxyRE, SPECIAL_QUERY_RE]
  20476. } },
  20477. async handler(css, id) {
  20478. css = stripBomTag(css);
  20479. const inlineCSS = inlineCSSRE$1.test(id);
  20480. const isHTMLProxy = htmlProxyRE$1.test(id);
  20481. if (inlineCSS && isHTMLProxy) {
  20482. if (styleAttrRE.test(id)) css = css.replace(/"/g, "&quot;");
  20483. const index = htmlProxyIndexRE.exec(id)?.[1];
  20484. if (index == null) throw new Error(`HTML proxy index in "${id}" not found`);
  20485. addToHTMLProxyTransformResult(`${getHash(cleanUrl(id))}_${Number.parseInt(index)}`, css);
  20486. return `export default ''`;
  20487. }
  20488. const inlined = inlineRE$2.test(id);
  20489. const modules = cssModulesCache.get(config).get(id);
  20490. const modulesCode = modules && !inlined && dataToEsm(modules, {
  20491. namedExports: true,
  20492. preferConst: true
  20493. });
  20494. if (config.command === "serve") {
  20495. const getContentWithSourcemap = async (content) => {
  20496. if (config.css.devSourcemap) {
  20497. const sourcemap = this.getCombinedSourcemap();
  20498. if (sourcemap.mappings) await injectSourcesContent(sourcemap, cleanUrl(id), config.logger);
  20499. return getCodeWithSourcemap("css", content, sourcemap);
  20500. }
  20501. return content;
  20502. };
  20503. if (isDirectCSSRequest(id)) return null;
  20504. if (inlined) return `export default ${JSON.stringify(css)}`;
  20505. if (this.environment.config.consumer === "server") return modulesCode || "export {}";
  20506. const cssContent = await getContentWithSourcemap(css);
  20507. return {
  20508. code: [
  20509. config.isBundled ? `const { updateStyle: __vite__updateStyle, removeStyle: __vite__removeStyle } = import.meta.hot._internal` : `import { updateStyle as __vite__updateStyle, removeStyle as __vite__removeStyle } from ${JSON.stringify(path.posix.join(config.base, CLIENT_PUBLIC_PATH))}`,
  20510. `const __vite__id = ${JSON.stringify(id)}`,
  20511. `const __vite__css = ${JSON.stringify(cssContent)}`,
  20512. `__vite__updateStyle(__vite__id, __vite__css)`,
  20513. `${modulesCode || "import.meta.hot.accept()"}`,
  20514. `import.meta.hot.prune(() => __vite__removeStyle(__vite__id))`
  20515. ].join("\n"),
  20516. map: { mappings: "" },
  20517. moduleType: "js"
  20518. };
  20519. }
  20520. if (!inlined) styles.set(id, css);
  20521. let code;
  20522. if (modulesCode) code = modulesCode;
  20523. else if (inlined) {
  20524. let content = css;
  20525. if (config.build.cssMinify) content = await minifyCSS(content, config, true);
  20526. code = `export default ${JSON.stringify(content)}`;
  20527. } else code = "";
  20528. return {
  20529. code,
  20530. map: { mappings: "" },
  20531. moduleSideEffects: modulesCode || inlined ? false : "no-treeshake",
  20532. moduleType: "js"
  20533. };
  20534. }
  20535. },
  20536. ...config.command === "build" ? {
  20537. async renderChunk(code, chunk, opts, meta) {
  20538. let chunkCSS;
  20539. const renderedModules = new Proxy({}, { get(_target, p) {
  20540. for (const name in meta.chunks) {
  20541. const module = meta.chunks[name].modules[p];
  20542. if (module) return module;
  20543. }
  20544. } });
  20545. const isJsChunkEmpty = code === "" && !chunk.isEntry;
  20546. let isPureCssChunk = chunk.exports.length === 0;
  20547. const ids = Object.keys(chunk.modules);
  20548. for (const id of ids) if (styles.has(id)) {
  20549. if (transformOnlyRE.test(id)) continue;
  20550. const cssScopeTo = this.getModuleInfo(id)?.meta?.vite?.cssScopeTo;
  20551. if (cssScopeTo && !isCssScopeToRendered(cssScopeTo, renderedModules)) continue;
  20552. if (cssModuleRE.test(id)) isPureCssChunk = false;
  20553. chunkCSS = (chunkCSS || "") + styles.get(id);
  20554. } else if (!isJsChunkEmpty) isPureCssChunk = false;
  20555. const publicAssetUrlMap = publicAssetUrlCache.get(config);
  20556. const resolveAssetUrlsInCss = (chunkCSS, cssAssetName, originalFileName) => {
  20557. const encodedPublicUrls = encodePublicUrlsInCSS(config);
  20558. const cssAssetDirname = encodedPublicUrls || config.base === "./" || config.base === "" ? slash(getCssAssetDirname(cssAssetName, originalFileName)) : void 0;
  20559. const toRelative = (filename) => {
  20560. const relativePath = normalizePath(path.relative(cssAssetDirname, filename));
  20561. return relativePath[0] === "." ? relativePath : "./" + relativePath;
  20562. };
  20563. chunkCSS = chunkCSS.replace(assetUrlRE, (_, fileHash, postfix = "") => {
  20564. const filename = this.getFileName(fileHash) + postfix;
  20565. chunk.viteMetadata.importedAssets.add(cleanUrl(filename));
  20566. return encodeURIPath(toOutputFilePathInCss(filename, "asset", cssAssetName, "css", config, toRelative));
  20567. });
  20568. if (encodedPublicUrls) {
  20569. const relativePathToPublicFromCSS = normalizePath(path.relative(cssAssetDirname, ""));
  20570. chunkCSS = chunkCSS.replace(publicAssetUrlRE, (_, hash) => {
  20571. const publicUrl = publicAssetUrlMap.get(hash).slice(1);
  20572. return encodeURIPath(toOutputFilePathInCss(publicUrl, "public", cssAssetName, "css", config, () => `${relativePathToPublicFromCSS}/${publicUrl}`));
  20573. });
  20574. }
  20575. return chunkCSS;
  20576. };
  20577. function ensureFileExt(name, ext) {
  20578. return normalizePath(path.format({
  20579. ...path.parse(name),
  20580. base: void 0,
  20581. ext
  20582. }));
  20583. }
  20584. let s;
  20585. const urlEmitTasks = [];
  20586. if (code.includes("__VITE_CSS_URL__")) {
  20587. let match;
  20588. cssUrlAssetRE.lastIndex = 0;
  20589. while (match = cssUrlAssetRE.exec(code)) {
  20590. const [full, idHex] = match;
  20591. const id = Buffer.from(idHex, "hex").toString();
  20592. const originalFileName = cleanUrl(id);
  20593. const cssAssetName = ensureFileExt(path.basename(originalFileName), ".css");
  20594. if (!styles.has(id)) throw new Error(`css content for ${JSON.stringify(id)} was not found`);
  20595. let cssContent = styles.get(id);
  20596. cssContent = resolveAssetUrlsInCss(cssContent, cssAssetName, originalFileName);
  20597. urlEmitTasks.push({
  20598. cssAssetName,
  20599. originalFileName,
  20600. content: cssContent,
  20601. start: match.index,
  20602. end: match.index + full.length
  20603. });
  20604. }
  20605. }
  20606. await urlEmitQueue.run(async () => Promise.all(urlEmitTasks.map(async (info) => {
  20607. info.content = await finalizeCss(info.content, config);
  20608. })));
  20609. if (urlEmitTasks.length > 0) {
  20610. const toRelativeRuntime = createToImportMetaURLBasedRelativeRuntime(opts.format, config.isWorker);
  20611. s ||= new MagicString(code);
  20612. for (const { cssAssetName, originalFileName, content, start, end } of urlEmitTasks) {
  20613. const referenceId = this.emitFile({
  20614. type: "asset",
  20615. name: cssAssetName,
  20616. originalFileName,
  20617. source: content
  20618. });
  20619. const filename = this.getFileName(referenceId);
  20620. chunk.viteMetadata.importedAssets.add(cleanUrl(filename));
  20621. const replacement = toOutputFilePathInJS(this.environment, filename, "asset", chunk.fileName, "js", toRelativeRuntime);
  20622. const replacementString = typeof replacement === "string" ? JSON.stringify(encodeURIPath(replacement)).slice(1, -1) : `"+${replacement.runtime}+"`;
  20623. s.update(start, end, replacementString);
  20624. }
  20625. }
  20626. if (chunkCSS !== void 0) {
  20627. if (isPureCssChunk && (opts.format === "es" || opts.format === "cjs")) pureCssChunks.add(chunk);
  20628. if (this.environment.config.build.cssCodeSplit) {
  20629. if ((opts.format === "es" || opts.format === "cjs") && !chunk.fileName.includes("-legacy")) {
  20630. const isEntry = chunk.isEntry && isPureCssChunk;
  20631. const cssFullAssetName = ensureFileExt(chunk.name, ".css");
  20632. const cssAssetName = chunk.isEntry && (!chunk.facadeModuleId || !isCSSRequest(chunk.facadeModuleId)) ? path.basename(cssFullAssetName) : cssFullAssetName;
  20633. const originalFileName = getChunkOriginalFileName(chunk, config.root, this.environment.config.isOutputOptionsForLegacyChunks?.(opts) ?? false);
  20634. chunkCSS = resolveAssetUrlsInCss(chunkCSS, cssAssetName, originalFileName);
  20635. chunkCSS = await codeSplitEmitQueue.run(async () => {
  20636. return finalizeCss(chunkCSS, config);
  20637. });
  20638. const referenceId = this.emitFile({
  20639. type: "asset",
  20640. name: cssAssetName,
  20641. originalFileName,
  20642. source: chunkCSS
  20643. });
  20644. if (isEntry) cssEntriesMap.get(this.environment).set(chunk.name, referenceId);
  20645. chunk.viteMetadata.importedCss.add(this.getFileName(referenceId));
  20646. } else if (this.environment.config.consumer === "client") {
  20647. chunkCSS = await finalizeCss(chunkCSS, config);
  20648. let cssString = JSON.stringify(chunkCSS);
  20649. cssString = renderAssetUrlInJS(this, chunk, opts, cssString)?.toString() || cssString;
  20650. const style = `__vite_style__`;
  20651. const injectCode = `var ${style} = document.createElement('style');${style}.textContent = ${cssString};document.head.appendChild(${style});`;
  20652. s ||= new MagicString(code);
  20653. injectInlinedCSS(s, this, code, opts.format, injectCode);
  20654. }
  20655. } else {
  20656. chunkCSS = resolveAssetUrlsInCss(chunkCSS, getCssBundleName(), defaultCssBundleName);
  20657. chunkCSSMap.set(chunk.fileName, chunkCSS);
  20658. }
  20659. }
  20660. if (s) if (config.build.sourcemap) return {
  20661. code: s.toString(),
  20662. map: s.generateMap({ hires: "boundary" })
  20663. };
  20664. else return { code: s.toString() };
  20665. return null;
  20666. },
  20667. augmentChunkHash(chunk) {
  20668. if (chunk.viteMetadata?.importedCss.size) {
  20669. let hash = "";
  20670. for (const id of chunk.viteMetadata.importedCss) hash += id;
  20671. return hash;
  20672. }
  20673. }
  20674. } : {},
  20675. async generateBundle(opts, bundle) {
  20676. if (this.environment.config.isOutputOptionsForLegacyChunks?.(opts)) return;
  20677. if ((config.command !== "build" || this.environment.config.build.emitAssets) && !this.environment.config.build.cssCodeSplit && !hasEmitted) {
  20678. let extractedCss = "";
  20679. const collected = /* @__PURE__ */ new Set();
  20680. const dynamicImports = /* @__PURE__ */ new Set();
  20681. function collect(chunk) {
  20682. if (!chunk || chunk.type !== "chunk" || collected.has(chunk)) return;
  20683. collected.add(chunk);
  20684. chunk.imports.forEach((importName) => collect(bundle[importName]));
  20685. chunk.dynamicImports.forEach((importName) => dynamicImports.add(importName));
  20686. extractedCss += chunkCSSMap.get(chunk.preliminaryFileName) ?? "";
  20687. }
  20688. for (const chunk of Object.values(bundle)) if (chunk.type === "chunk" && chunk.isEntry) collect(chunk);
  20689. for (const chunkName of dynamicImports) collect(bundle[chunkName]);
  20690. if (extractedCss) {
  20691. hasEmitted = true;
  20692. extractedCss = await finalizeCss(extractedCss, config);
  20693. this.emitFile({
  20694. name: getCssBundleName(),
  20695. type: "asset",
  20696. source: extractedCss,
  20697. originalFileName: defaultCssBundleName
  20698. });
  20699. }
  20700. }
  20701. if (pureCssChunks.size) {
  20702. const prelimaryNameToChunkMap = Object.fromEntries(Object.values(bundle).filter((chunk) => chunk.type === "chunk").map((chunk) => [chunk.preliminaryFileName, chunk.fileName]));
  20703. const pureCssChunkNames = [...pureCssChunks].map((pureCssChunk) => prelimaryNameToChunkMap[pureCssChunk.fileName]).filter(Boolean);
  20704. const replaceEmptyChunk = getEmptyChunkReplacer(pureCssChunkNames, opts.format);
  20705. for (const file in bundle) {
  20706. const chunk = bundle[file];
  20707. if (chunk.type === "chunk") {
  20708. let chunkImportsPureCssChunk = false;
  20709. chunk.imports = chunk.imports.filter((file) => {
  20710. if (pureCssChunkNames.includes(file)) {
  20711. const { importedCss, importedAssets } = bundle[file].viteMetadata;
  20712. importedCss.forEach((file) => chunk.viteMetadata.importedCss.add(file));
  20713. importedAssets.forEach((file) => chunk.viteMetadata.importedAssets.add(file));
  20714. chunkImportsPureCssChunk = true;
  20715. return false;
  20716. }
  20717. return true;
  20718. });
  20719. if (chunkImportsPureCssChunk) chunk.code = replaceEmptyChunk(chunk.code);
  20720. }
  20721. }
  20722. const removedPureCssFiles = removedPureCssFilesCache.get(config);
  20723. pureCssChunkNames.forEach((fileName) => {
  20724. const emptyJsPlaceholder = bundle[fileName];
  20725. if (emptyJsPlaceholder.isEntry) {
  20726. const { importedAssets, importedCss } = emptyJsPlaceholder.viteMetadata;
  20727. const cssReferenceId = cssEntriesMap.get(this.environment).get(emptyJsPlaceholder.name);
  20728. const realCssEntryName = this.getFileName(cssReferenceId);
  20729. const realCssEntry = bundle[realCssEntryName];
  20730. importedCss.delete(realCssEntryName);
  20731. if (importedAssets.size) realCssEntry.viteMetadata.importedAssets = importedAssets;
  20732. if (importedCss.size) realCssEntry.viteMetadata.importedCss = importedCss;
  20733. }
  20734. removedPureCssFiles.set(fileName, emptyJsPlaceholder);
  20735. delete bundle[fileName];
  20736. delete bundle[`${fileName}.map`];
  20737. });
  20738. }
  20739. const cssAssets = Object.values(bundle).filter((asset) => asset.type === "asset" && asset.fileName.endsWith(".css"));
  20740. for (const cssAsset of cssAssets) if (typeof cssAsset.source === "string") cssAsset.source = cssAsset.source.replace(viteHashUpdateMarkerRE, "");
  20741. }
  20742. };
  20743. }
  20744. function injectInlinedCSS(s, ctx, code, format, injectCode) {
  20745. let injectionPoint;
  20746. if (format === "iife" || format === "umd") {
  20747. const m = (format === "iife" ? IIFE_BEGIN_RE : UMD_BEGIN_RE).exec(code);
  20748. if (!m) ctx.error("Injection point for inlined CSS not found");
  20749. injectionPoint = m.index + m[0].length;
  20750. } else if (format === "es") if (code.startsWith("#!")) {
  20751. let secondLinePos = code.indexOf("\n");
  20752. if (secondLinePos === -1) secondLinePos = 0;
  20753. injectionPoint = secondLinePos;
  20754. } else injectionPoint = 0;
  20755. else ctx.error("Non supported format");
  20756. s.appendRight(injectionPoint, injectCode);
  20757. }
  20758. function cssAnalysisPlugin(config) {
  20759. return {
  20760. name: "vite:css-analysis",
  20761. transform: {
  20762. filter: { id: {
  20763. include: CSS_LANGS_RE,
  20764. exclude: [commonjsProxyRE, SPECIAL_QUERY_RE]
  20765. } },
  20766. async handler(_, id) {
  20767. const { moduleGraph } = this.environment;
  20768. const thisModule = moduleGraph.getModuleById(id);
  20769. if (thisModule) {
  20770. const isSelfAccepting = !cssModulesCache.get(config)?.get(id) && !inlineRE$2.test(id) && !htmlProxyRE$1.test(id);
  20771. const pluginImports = this._addedImports;
  20772. if (pluginImports) {
  20773. const depModules = /* @__PURE__ */ new Set();
  20774. for (const file of pluginImports) depModules.add(moduleGraph.createFileOnlyEntry(file));
  20775. moduleGraph.updateModuleInfo(thisModule, depModules, null, /* @__PURE__ */ new Set(), null, isSelfAccepting);
  20776. } else thisModule.isSelfAccepting = isSelfAccepting;
  20777. }
  20778. }
  20779. }
  20780. };
  20781. }
  20782. function isCssScopeToRendered(cssScopeTo, renderedModules) {
  20783. const [importerId, exp] = cssScopeTo;
  20784. const importer = renderedModules[importerId];
  20785. return importer && (exp === void 0 || importer.renderedExports.includes(exp));
  20786. }
  20787. /**
  20788. * Create a replacer function that takes code and replaces given pure CSS chunk imports
  20789. * @param pureCssChunkNames The chunks that only contain pure CSS and should be replaced
  20790. * @param outputFormat The module output format to decide whether to replace `import` or `require`
  20791. */
  20792. function getEmptyChunkReplacer(pureCssChunkNames, outputFormat) {
  20793. const emptyChunkFiles = pureCssChunkNames.map((file) => escapeRegex(path.basename(file))).join("|");
  20794. const emptyChunkRE = new RegExp(outputFormat === "es" ? `\\bimport\\s*["'][^"']*(?:${emptyChunkFiles})["'];` : `(\\b|,\\s*)require\\(\\s*["'\`][^"'\`]*(?:${emptyChunkFiles})["'\`]\\)(;|,)`, "g");
  20795. return (code) => code.replace(emptyChunkRE, (m, p1, p2) => {
  20796. if (outputFormat === "es") return `/* empty css ${"".padEnd(m.length - 15)}*/`;
  20797. if (p2 === ";") return `${p2}/* empty css ${"".padEnd(m.length - 16)}*/`;
  20798. return `${p1}/* empty css ${"".padEnd(m.length - 15 - p1.length)}*/`;
  20799. });
  20800. }
  20801. const fileURLWithWindowsDriveRE = /^file:\/\/\/[a-zA-Z]:\//;
  20802. function createCSSResolvers(config) {
  20803. let cssResolve;
  20804. let sassResolve;
  20805. let lessResolve;
  20806. return {
  20807. get css() {
  20808. return cssResolve ??= createBackCompatIdResolver(config, {
  20809. extensions: [".css"],
  20810. mainFields: ["style"],
  20811. conditions: ["style", DEV_PROD_CONDITION],
  20812. tryIndex: false,
  20813. preferRelative: true
  20814. });
  20815. },
  20816. get sass() {
  20817. if (!sassResolve) {
  20818. const resolver = createBackCompatIdResolver(config, {
  20819. extensions: [
  20820. ".scss",
  20821. ".sass",
  20822. ".css"
  20823. ],
  20824. mainFields: ["sass", "style"],
  20825. conditions: [
  20826. "sass",
  20827. "style",
  20828. DEV_PROD_CONDITION
  20829. ],
  20830. tryIndex: true,
  20831. tryPrefix: "_",
  20832. preferRelative: true,
  20833. skipMainField: true
  20834. });
  20835. sassResolve = async (...args) => {
  20836. if (args[1].startsWith("file://")) args[1] = fileURLToPath(args[1], { windows: isWindows && !fileURLWithWindowsDriveRE.test(args[1]) ? false : void 0 });
  20837. return resolver(...args);
  20838. };
  20839. }
  20840. return sassResolve;
  20841. },
  20842. get less() {
  20843. return lessResolve ??= createBackCompatIdResolver(config, {
  20844. extensions: [".less", ".css"],
  20845. mainFields: ["less", "style"],
  20846. conditions: [
  20847. "less",
  20848. "style",
  20849. DEV_PROD_CONDITION
  20850. ],
  20851. tryIndex: false,
  20852. preferRelative: true
  20853. });
  20854. }
  20855. };
  20856. }
  20857. function getCssResolversKeys(resolvers) {
  20858. return Object.keys(resolvers);
  20859. }
  20860. async function compileCSSPreprocessors(environment, id, lang, code, workerController) {
  20861. const { config } = environment;
  20862. const { preprocessorOptions, devSourcemap } = config.css;
  20863. const atImportResolvers = getAtImportResolvers(environment.getTopLevelConfig());
  20864. const opts = {
  20865. ...preprocessorOptions && preprocessorOptions[lang] || {},
  20866. filename: cleanUrl(id),
  20867. enableSourcemap: devSourcemap ?? false
  20868. };
  20869. const preProcessor = workerController[lang];
  20870. const preprocessResult = await preProcessor(environment, code, config.root, opts, atImportResolvers);
  20871. if (preprocessResult.error) throw preprocessResult.error;
  20872. let deps;
  20873. if (preprocessResult.deps.length > 0) {
  20874. const normalizedFilename = normalizePath(opts.filename);
  20875. deps = new Set([...preprocessResult.deps].filter((dep) => normalizePath(dep) !== normalizedFilename));
  20876. }
  20877. return {
  20878. code: preprocessResult.code,
  20879. map: combineSourcemapsIfExists(opts.filename, preprocessResult.map, preprocessResult.additionalMap),
  20880. deps
  20881. };
  20882. }
  20883. const configToAtImportResolvers = /* @__PURE__ */ new WeakMap();
  20884. function getAtImportResolvers(config) {
  20885. let atImportResolvers = configToAtImportResolvers.get(config);
  20886. if (!atImportResolvers) {
  20887. atImportResolvers = createCSSResolvers(config);
  20888. configToAtImportResolvers.set(config, atImportResolvers);
  20889. }
  20890. return atImportResolvers;
  20891. }
  20892. async function compileCSS(environment, id, code, workerController, urlResolver) {
  20893. const { config } = environment;
  20894. const lang = CSS_LANGS_RE.exec(id)?.[1];
  20895. const deps = /* @__PURE__ */ new Set();
  20896. let preprocessorMap;
  20897. if (isPreProcessor(lang)) {
  20898. const preprocessorResult = await compileCSSPreprocessors(environment, id, lang, code, workerController);
  20899. code = preprocessorResult.code;
  20900. preprocessorMap = preprocessorResult.map;
  20901. preprocessorResult.deps?.forEach((dep) => deps.add(dep));
  20902. } else if (lang === "sss" && config.css.transformer === "lightningcss") {
  20903. const sssResult = await transformSugarSS(environment, id, code);
  20904. code = sssResult.code;
  20905. preprocessorMap = sssResult.map;
  20906. }
  20907. const transformResult = await (config.css.transformer === "lightningcss" ? compileLightningCSS(environment, id, code, deps, workerController, urlResolver) : compilePostCSS(environment, id, code, deps, lang, workerController, urlResolver));
  20908. if (!transformResult) return {
  20909. code,
  20910. map: config.css.devSourcemap ? preprocessorMap : { mappings: "" },
  20911. deps
  20912. };
  20913. return {
  20914. ...transformResult,
  20915. map: config.css.devSourcemap ? combineSourcemapsIfExists(cleanUrl(id), typeof transformResult.map === "string" ? JSON.parse(transformResult.map) : transformResult.map, preprocessorMap) : { mappings: "" },
  20916. deps
  20917. };
  20918. }
  20919. async function compilePostCSS(environment, id, code, deps, lang, workerController, urlResolver) {
  20920. const { config } = environment;
  20921. const { modules: modulesOptions, devSourcemap } = config.css;
  20922. const isModule = modulesOptions !== false && cssModuleRE.test(id);
  20923. const needInlineImport = code.includes("@import");
  20924. const hasUrl = cssUrlRE.test(code) || cssImageSetRE.test(code);
  20925. const postcssConfig = await resolvePostcssConfig(environment.getTopLevelConfig());
  20926. if (lang !== "sss" && !postcssConfig && !isModule && !needInlineImport && !hasUrl) return;
  20927. const atImportResolvers = getAtImportResolvers(environment.getTopLevelConfig());
  20928. const postcssPlugins = postcssConfig?.plugins.slice() ?? [];
  20929. if (needInlineImport) postcssPlugins.unshift((await importPostcssImport()).default({
  20930. async resolve(id, basedir) {
  20931. const publicFile = checkPublicFile(id, environment.getTopLevelConfig());
  20932. if (publicFile) return publicFile;
  20933. const resolved = await atImportResolvers.css(environment, id, path.join(basedir, "*"));
  20934. if (resolved) return path.resolve(resolved);
  20935. if (!path.isAbsolute(id)) environment.logger.error(import_picocolors.default.red(`Unable to resolve \`@import "${id}"\` from ${basedir}`));
  20936. return id;
  20937. },
  20938. async load(id) {
  20939. const code = await fs.promises.readFile(id, "utf-8");
  20940. const lang = CSS_LANGS_RE.exec(id)?.[1];
  20941. if (isPreProcessor(lang)) {
  20942. const result = await compileCSSPreprocessors(environment, id, lang, code, workerController);
  20943. result.deps?.forEach((dep) => deps.add(dep));
  20944. return result.code;
  20945. }
  20946. return code;
  20947. },
  20948. nameLayer(index) {
  20949. return `vite--anon-layer-${getHash(id)}-${index}`;
  20950. }
  20951. }));
  20952. if (urlResolver && (postcssPlugins.length > 0 || isModule || hasUrl)) postcssPlugins.push(UrlRewritePostcssPlugin({
  20953. resolver: urlResolver,
  20954. deps,
  20955. logger: environment.logger
  20956. }));
  20957. let modules;
  20958. if (isModule) postcssPlugins.unshift((await importPostcssModules()).default({
  20959. ...modulesOptions,
  20960. localsConvention: modulesOptions?.localsConvention,
  20961. getJSON(cssFileName, _modules, outputFileName) {
  20962. modules = _modules;
  20963. if (modulesOptions && typeof modulesOptions.getJSON === "function") modulesOptions.getJSON(cssFileName, _modules, outputFileName);
  20964. },
  20965. async resolve(id, importer) {
  20966. for (const key of getCssResolversKeys(atImportResolvers)) {
  20967. const resolved = await atImportResolvers[key](environment, id, importer);
  20968. if (resolved) return path.resolve(resolved);
  20969. }
  20970. return id;
  20971. }
  20972. }));
  20973. const postcssOptions = postcssConfig?.options ?? {};
  20974. const postcssParser = lang === "sss" ? await loadSss(config.root) : postcssOptions.parser;
  20975. if (!postcssPlugins.length && !postcssParser) return;
  20976. return {
  20977. ...await runPostCSS(id, code, postcssPlugins, {
  20978. ...postcssOptions,
  20979. parser: postcssParser
  20980. }, deps, environment.logger, devSourcemap),
  20981. modules
  20982. };
  20983. }
  20984. async function transformSugarSS(environment, id, code) {
  20985. const { config } = environment;
  20986. const { devSourcemap } = config.css;
  20987. return await runPostCSS(id, code, [], { parser: await loadSss(config.root) }, void 0, environment.logger, devSourcemap);
  20988. }
  20989. async function runPostCSS(id, code, plugins, options, deps, logger, enableSourcemap) {
  20990. let postcssResult;
  20991. try {
  20992. const source = removeDirectQuery(id);
  20993. postcssResult = await (await importPostcss()).default(plugins).process(code, {
  20994. ...options,
  20995. to: source,
  20996. from: source,
  20997. ...enableSourcemap ? { map: {
  20998. inline: false,
  20999. annotation: false,
  21000. sourcesContent: true
  21001. } } : {}
  21002. });
  21003. for (const message of postcssResult.messages) if (message.type === "dependency") deps?.add(normalizePath(message.file));
  21004. else if (message.type === "dir-dependency") {
  21005. const { dir, glob: globPattern = "**" } = message;
  21006. const files = globSync(globPattern, {
  21007. absolute: true,
  21008. cwd: path.resolve(path.dirname(id), dir),
  21009. expandDirectories: false,
  21010. ignore: ["**/node_modules/**"]
  21011. });
  21012. for (let i = 0; i < files.length; i++) deps?.add(files[i]);
  21013. } else if (message.type === "warning") {
  21014. const warning = message;
  21015. let msg = `[vite:css][postcss] ${warning.text}`;
  21016. msg += `\n${generateCodeFrame(code, {
  21017. line: warning.line,
  21018. column: warning.column - 1
  21019. }, warning.endLine !== void 0 && warning.endColumn !== void 0 ? {
  21020. line: warning.endLine,
  21021. column: warning.endColumn - 1
  21022. } : void 0)}`;
  21023. logger.warn(import_picocolors.default.yellow(msg));
  21024. }
  21025. } catch (e) {
  21026. e.message = `[postcss] ${e.message}`;
  21027. e.code = code;
  21028. e.loc = {
  21029. file: e.file,
  21030. line: e.line,
  21031. column: e.column - 1
  21032. };
  21033. throw e;
  21034. }
  21035. if (!enableSourcemap) return {
  21036. code: postcssResult.css,
  21037. map: { mappings: "" }
  21038. };
  21039. const postcssMap = await formatPostcssSourceMap(postcssResult.map.toJSON(), cleanUrl(id));
  21040. return {
  21041. code: postcssResult.css,
  21042. map: postcssMap
  21043. };
  21044. }
  21045. function createCachedImport(imp) {
  21046. let cached;
  21047. return () => {
  21048. if (!cached) cached = imp().then((module) => {
  21049. cached = module;
  21050. return module;
  21051. });
  21052. return cached;
  21053. };
  21054. }
  21055. const importPostcssImport = createCachedImport(() => import("./postcss-import.js").then((m) => /* @__PURE__ */ __toESM(m.default, 1)));
  21056. const importPostcssModules = createCachedImport(() => import("./build2.js").then((m) => /* @__PURE__ */ __toESM(m.default, 1)));
  21057. const importPostcss = createCachedImport(() => import("postcss"));
  21058. const preprocessorWorkerControllerCache = /* @__PURE__ */ new WeakMap();
  21059. let alwaysFakeWorkerWorkerControllerCache;
  21060. /**
  21061. * @experimental
  21062. */
  21063. async function preprocessCSS(code, filename, config) {
  21064. let workerController = preprocessorWorkerControllerCache.get(config);
  21065. if (!workerController) {
  21066. alwaysFakeWorkerWorkerControllerCache ||= createPreprocessorWorkerController(0);
  21067. workerController = alwaysFakeWorkerWorkerControllerCache;
  21068. }
  21069. return await compileCSS(new PartialEnvironment("client", config), filename, code, workerController);
  21070. }
  21071. async function formatPostcssSourceMap(rawMap, file) {
  21072. const inputFileDir = path.dirname(file);
  21073. const sources = rawMap.sources.map((source) => {
  21074. const cleanSource = cleanUrl(decodeURIComponent(source));
  21075. if (cleanSource[0] === "<" && cleanSource.endsWith(">")) return `\0${cleanSource}`;
  21076. return normalizePath(path.resolve(inputFileDir, cleanSource));
  21077. });
  21078. return {
  21079. file,
  21080. mappings: rawMap.mappings,
  21081. names: rawMap.names,
  21082. sources,
  21083. sourcesContent: rawMap.sourcesContent,
  21084. version: rawMap.version
  21085. };
  21086. }
  21087. function combineSourcemapsIfExists(filename, map1, map2) {
  21088. if (!map1 || !map2) return map1;
  21089. if (map1.mappings === "" || map2.mappings === "") return { mappings: "" };
  21090. return combineSourcemaps(filename, [map1, map2]);
  21091. }
  21092. const viteHashUpdateMarker = "/*$vite$:1*/";
  21093. const viteHashUpdateMarkerRE = /\/\*\$vite\$:\d+\*\//;
  21094. async function finalizeCss(css, config) {
  21095. if (css.includes("@import") || css.includes("@charset")) css = await hoistAtRules(css);
  21096. if (config.build.cssMinify) css = await minifyCSS(css, config, false);
  21097. css += viteHashUpdateMarker;
  21098. return css;
  21099. }
  21100. async function resolvePostcssConfig(config) {
  21101. let result = postcssConfigCache.get(config);
  21102. if (result !== void 0) return await result;
  21103. const inlineOptions = config.css.postcss;
  21104. if (isObject$1(inlineOptions)) {
  21105. const options = { ...inlineOptions };
  21106. delete options.plugins;
  21107. result = {
  21108. options,
  21109. plugins: inlineOptions.plugins || []
  21110. };
  21111. } else {
  21112. const searchPath = typeof inlineOptions === "string" ? inlineOptions : config.root;
  21113. result = (0, import_src.default)({}, searchPath, { stopDir: searchForWorkspaceRoot(config.root) }).catch((e) => {
  21114. if (!e.message.includes("No PostCSS Config found")) if (e instanceof Error) {
  21115. const { name, message, stack } = e;
  21116. e.name = "Failed to load PostCSS config";
  21117. e.message = `Failed to load PostCSS config (searchPath: ${searchPath}): [${name}] ${message}\n${stack}`;
  21118. e.stack = "";
  21119. throw e;
  21120. } else throw new Error(`Failed to load PostCSS config: ${e}`);
  21121. return null;
  21122. });
  21123. result.then((resolved) => {
  21124. postcssConfigCache.set(config, resolved);
  21125. }, () => {});
  21126. }
  21127. postcssConfigCache.set(config, result);
  21128. return result;
  21129. }
  21130. const cssUrlRE = /(?<!@import\s+)(?<=^|[^\w\-\u0080-\uffff])url\((\s*('[^']+'|"[^"]+")\s*|(?:\\.|[^'")\\])+)\)/;
  21131. const cssDataUriRE = /(?<=^|[^\w\-\u0080-\uffff])data-uri\((\s*('[^']+'|"[^"]+")\s*|[^'")]+)\)/;
  21132. const importCssRE = /@import\s+(?:url\()?('[^']+\.css'|"[^"]+\.css"|[^'"\s)]+\.css)/;
  21133. const cssImageSetRE = /(?<=image-set\()((?:[\w-]{1,256}\([^)]*\)|[^)])*)(?=\))/;
  21134. const UrlRewritePostcssPlugin = (opts) => {
  21135. if (!opts) throw new Error("base or replace is required");
  21136. return {
  21137. postcssPlugin: "vite-url-rewrite",
  21138. Once(root) {
  21139. const promises = [];
  21140. root.walkDecls((declaration) => {
  21141. const importer = declaration.source?.input.file;
  21142. if (!importer) opts.logger.warnOnce("\nA PostCSS plugin did not pass the `from` option to `postcss.parse`. This may cause imported assets to be incorrectly transformed. If you've recently added a PostCSS plugin that raised this warning, please contact the package author to fix the issue.");
  21143. const isCssUrl = cssUrlRE.test(declaration.value);
  21144. const isCssImageSet = cssImageSetRE.test(declaration.value);
  21145. if (isCssUrl || isCssImageSet) {
  21146. const replacerForDeclaration = async (rawUrl) => {
  21147. const [newUrl, resolvedId] = await opts.resolver(rawUrl, importer);
  21148. if (resolvedId) opts.deps.add(resolvedId);
  21149. return newUrl;
  21150. };
  21151. if (isCssUrl && isCssImageSet) promises.push(rewriteCssUrls(declaration.value, replacerForDeclaration).then((url) => rewriteCssImageSet(url, replacerForDeclaration)).then((url) => {
  21152. declaration.value = url;
  21153. }));
  21154. else promises.push((isCssImageSet ? rewriteCssImageSet : rewriteCssUrls)(declaration.value, replacerForDeclaration).then((url) => {
  21155. declaration.value = url;
  21156. }));
  21157. }
  21158. });
  21159. if (promises.length) return Promise.all(promises);
  21160. }
  21161. };
  21162. };
  21163. UrlRewritePostcssPlugin.postcss = true;
  21164. function rewriteCssUrls(css, replacer) {
  21165. return asyncReplace(css, cssUrlRE, async (match) => {
  21166. const [matched, rawUrl] = match;
  21167. return await doUrlReplace(rawUrl.trim(), matched, replacer);
  21168. });
  21169. }
  21170. function rewriteCssDataUris(css, replacer) {
  21171. return asyncReplace(css, cssDataUriRE, async (match) => {
  21172. const [matched, rawUrl] = match;
  21173. return await doUrlReplace(rawUrl.trim(), matched, replacer, "data-uri");
  21174. });
  21175. }
  21176. function rewriteImportCss(css, replacer) {
  21177. return asyncReplace(css, importCssRE, async (match) => {
  21178. const [matched, rawUrl] = match;
  21179. return await doImportCSSReplace(rawUrl, matched, replacer);
  21180. });
  21181. }
  21182. const cssNotProcessedRE = /(?:gradient|element|cross-fade|image)\(/;
  21183. async function rewriteCssImageSet(css, replacer) {
  21184. return await asyncReplace(css, cssImageSetRE, async (match) => {
  21185. const [, rawUrl] = match;
  21186. return await processSrcSet(rawUrl, async ({ url }) => {
  21187. if (cssUrlRE.test(url)) return await rewriteCssUrls(url, replacer);
  21188. if (!cssNotProcessedRE.test(url)) return await doUrlReplace(url, url, replacer);
  21189. return url;
  21190. });
  21191. });
  21192. }
  21193. function skipUrlReplacer(unquotedUrl) {
  21194. return isExternalUrl(unquotedUrl) || isDataUrl(unquotedUrl) || unquotedUrl[0] === "#" || functionCallRE.test(unquotedUrl) || unquotedUrl.startsWith("__VITE_ASSET__") || unquotedUrl.startsWith("__VITE_PUBLIC_ASSET__");
  21195. }
  21196. async function doUrlReplace(rawUrl, matched, replacer, funcName = "url") {
  21197. let wrap = "";
  21198. const first = rawUrl[0];
  21199. let unquotedUrl = rawUrl;
  21200. if (first === `"` || first === `'`) {
  21201. wrap = first;
  21202. unquotedUrl = rawUrl.slice(1, -1);
  21203. }
  21204. if (skipUrlReplacer(unquotedUrl)) return matched;
  21205. unquotedUrl = unquotedUrl.replace(/\\(\W)/g, "$1");
  21206. let newUrl = await replacer(unquotedUrl, rawUrl);
  21207. if (newUrl === false) return matched;
  21208. if (wrap === "" && (newUrl !== encodeURI(newUrl) || newUrl.includes(")"))) wrap = "\"";
  21209. if (wrap === "'" && newUrl.includes("'")) wrap = "\"";
  21210. if (wrap === "\"" && newUrl.includes("\"")) newUrl = newUrl.replace(nonEscapedDoubleQuoteRe, "\\\"");
  21211. return `${funcName}(${wrap}${newUrl}${wrap})`;
  21212. }
  21213. async function doImportCSSReplace(rawUrl, matched, replacer) {
  21214. let wrap = "";
  21215. const first = rawUrl[0];
  21216. let unquotedUrl = rawUrl;
  21217. if (first === `"` || first === `'`) {
  21218. wrap = first;
  21219. unquotedUrl = rawUrl.slice(1, -1);
  21220. }
  21221. if (skipUrlReplacer(unquotedUrl)) return matched;
  21222. const newUrl = await replacer(unquotedUrl, rawUrl);
  21223. if (newUrl === false) return matched;
  21224. return `@import ${matched.includes("url(") ? "url(" : ""}${wrap}${newUrl}${wrap}`;
  21225. }
  21226. async function minifyCSS(css, config, inlined) {
  21227. if (config.build.cssMinify === "esbuild") {
  21228. const { transform, formatMessages } = await importEsbuild();
  21229. try {
  21230. const { code, warnings } = await transform(css, {
  21231. loader: "css",
  21232. target: config.build.cssTarget || void 0,
  21233. ...resolveMinifyCssEsbuildOptions(config.esbuild || {})
  21234. });
  21235. if (warnings.length) {
  21236. const msgs = await formatMessages(warnings, { kind: "warning" });
  21237. config.logger.warn(import_picocolors.default.yellow(`[esbuild css minify]\n${msgs.join("\n")}`));
  21238. }
  21239. return inlined ? code.trimEnd() : code;
  21240. } catch (e) {
  21241. if (e.errors) {
  21242. e.message = "[esbuild css minify] " + e.message;
  21243. e.frame = "\n" + (await formatMessages(e.errors, { kind: "error" })).join("\n");
  21244. e.loc = e.errors[0].location;
  21245. }
  21246. throw e;
  21247. }
  21248. }
  21249. try {
  21250. const { code, warnings } = (await importLightningCSS()).transform({
  21251. ...config.css.lightningcss,
  21252. targets: convertTargets(config.build.cssTarget),
  21253. cssModules: void 0,
  21254. filename: defaultCssBundleName,
  21255. code: Buffer.from(css),
  21256. minify: true
  21257. });
  21258. for (const warning of warnings) {
  21259. let msg = `[lightningcss minify] ${warning.message}`;
  21260. msg += `\n${generateCodeFrame(css, {
  21261. line: warning.loc.line,
  21262. column: warning.loc.column - 1
  21263. })}`;
  21264. config.logger.warn(import_picocolors.default.yellow(msg));
  21265. }
  21266. return decoder.decode(code) + (inlined ? "" : "\n");
  21267. } catch (e) {
  21268. e.message = `[lightningcss minify] ${e.message}`;
  21269. const friendlyMessage = getLightningCssErrorMessageForIeSyntaxes(css);
  21270. if (friendlyMessage) e.message += friendlyMessage;
  21271. if (e.loc) {
  21272. e.loc = {
  21273. line: e.loc.line,
  21274. column: e.loc.column - 1
  21275. };
  21276. e.frame = generateCodeFrame(css, e.loc);
  21277. }
  21278. throw e;
  21279. }
  21280. }
  21281. function resolveMinifyCssEsbuildOptions(options) {
  21282. const base = {
  21283. charset: options.charset,
  21284. logLevel: options.logLevel,
  21285. logLimit: options.logLimit,
  21286. logOverride: options.logOverride,
  21287. legalComments: options.legalComments
  21288. };
  21289. if (options.minifyIdentifiers != null || options.minifySyntax != null || options.minifyWhitespace != null) return {
  21290. ...base,
  21291. minifyIdentifiers: options.minifyIdentifiers ?? true,
  21292. minifySyntax: options.minifySyntax ?? true,
  21293. minifyWhitespace: options.minifyWhitespace ?? true
  21294. };
  21295. else return {
  21296. ...base,
  21297. minify: true
  21298. };
  21299. }
  21300. const atImportRE = /@import(?:\s*(?:url\([^)]*\)|"(?:[^"]|(?<=\\)")*"|'(?:[^']|(?<=\\)')*').*?|[^;]*);/g;
  21301. const atCharsetRE = /@charset(?:\s*(?:"(?:[^"]|(?<=\\)")*"|'(?:[^']|(?<=\\)')*').*?|[^;]*);/g;
  21302. async function hoistAtRules(css) {
  21303. const s = new MagicString(css);
  21304. const cleanCss = emptyCssComments(css);
  21305. let match;
  21306. atImportRE.lastIndex = 0;
  21307. while (match = atImportRE.exec(cleanCss)) {
  21308. s.remove(match.index, match.index + match[0].length);
  21309. s.appendLeft(0, match[0]);
  21310. }
  21311. atCharsetRE.lastIndex = 0;
  21312. let foundCharset = false;
  21313. while (match = atCharsetRE.exec(cleanCss)) {
  21314. s.remove(match.index, match.index + match[0].length);
  21315. if (!foundCharset) {
  21316. s.prepend(match[0]);
  21317. foundCharset = true;
  21318. }
  21319. }
  21320. return s.toString();
  21321. }
  21322. const loadedPreprocessorPath = {};
  21323. function loadPreprocessorPath(lang, root) {
  21324. const cached = loadedPreprocessorPath[lang];
  21325. if (cached) return cached;
  21326. const resolved = nodeResolveWithVite(lang, void 0, { root }) ?? nodeResolveWithVite(lang, _dirname, { root });
  21327. if (resolved) return loadedPreprocessorPath[lang] = resolved;
  21328. const installCommand = getPackageManagerCommand("install");
  21329. throw new Error(`Preprocessor dependency "${lang}" not found. Did you install it? Try \`${installCommand} -D ${lang}\`.`);
  21330. }
  21331. function loadSassPackage(root, skipEmbedded = false) {
  21332. if (!skipEmbedded) try {
  21333. return {
  21334. name: "sass-embedded",
  21335. path: loadPreprocessorPath("sass-embedded", root)
  21336. };
  21337. } catch (e1) {
  21338. try {
  21339. return {
  21340. name: "sass",
  21341. path: loadPreprocessorPath(PreprocessLang.sass, root)
  21342. };
  21343. } catch {
  21344. throw e1;
  21345. }
  21346. }
  21347. return {
  21348. name: "sass",
  21349. path: loadPreprocessorPath(PreprocessLang.sass, root)
  21350. };
  21351. }
  21352. let cachedSss;
  21353. async function loadSss(root) {
  21354. if (!cachedSss) cachedSss = (async () => {
  21355. return cachedSss = (await import(pathToFileURL(loadPreprocessorPath(PostCssDialectLang.sss, root)).href)).default;
  21356. })();
  21357. return cachedSss;
  21358. }
  21359. function cleanScssBugUrl(url) {
  21360. if (typeof window !== "undefined" && typeof location !== "undefined" && typeof location.href === "string") {
  21361. const prefix = location.href.replace(/\/$/, "");
  21362. return url.replace(prefix, "");
  21363. } else return url;
  21364. }
  21365. const makeScssWorker = (environment, resolvers, _maxWorkers) => {
  21366. let compilerPromise;
  21367. return {
  21368. async run(sassPath, data, options) {
  21369. const sass = await import(sassPath);
  21370. compilerPromise ??= sass.initAsyncCompiler();
  21371. const compiler = await compilerPromise;
  21372. const sassOptions = { ...options };
  21373. sassOptions.url = pathToFileURL(options.filename);
  21374. sassOptions.sourceMap = options.enableSourcemap;
  21375. const skipRebaseUrls = (unquotedUrl, rawUrl) => {
  21376. if (!(rawUrl[0] === "\"" || rawUrl[0] === "'") && unquotedUrl[0] === "$") return true;
  21377. return unquotedUrl.startsWith("#{");
  21378. };
  21379. const internalImporter = {
  21380. async canonicalize(url, context) {
  21381. const importer = context.containingUrl ? fileURLToPath(context.containingUrl) : options.filename;
  21382. const resolved = await resolvers.sass(environment, url, cleanScssBugUrl(importer));
  21383. if (resolved && (resolved.endsWith(".css") || resolved.endsWith(".scss") || resolved.endsWith(".sass"))) return pathToFileURL(resolved);
  21384. return null;
  21385. },
  21386. async load(canonicalUrl) {
  21387. const ext = path.extname(canonicalUrl.pathname);
  21388. let syntax = "scss";
  21389. if (ext === ".sass") syntax = "indented";
  21390. else if (ext === ".css") syntax = "css";
  21391. const result = await rebaseUrls(environment, fileURLToPath(canonicalUrl), options.filename, resolvers.sass, skipRebaseUrls);
  21392. return {
  21393. contents: result.contents ?? await fsp.readFile(result.file, "utf-8"),
  21394. syntax,
  21395. sourceMapUrl: canonicalUrl
  21396. };
  21397. }
  21398. };
  21399. sassOptions.importers = [...sassOptions.importers ?? [], internalImporter];
  21400. sassOptions.importer ??= internalImporter;
  21401. const result = await compiler.compileStringAsync(data, sassOptions);
  21402. return {
  21403. css: result.css,
  21404. map: result.sourceMap ? JSON.stringify(result.sourceMap) : void 0,
  21405. stats: { includedFiles: result.loadedUrls.filter((url) => url.protocol === "file:").map((url) => fileURLToPath(url)) }
  21406. };
  21407. },
  21408. async stop() {
  21409. await (await compilerPromise)?.dispose();
  21410. compilerPromise = void 0;
  21411. }
  21412. };
  21413. };
  21414. const scssProcessor = (maxWorkers) => {
  21415. let worker;
  21416. let failedSassEmbedded;
  21417. const normalizedErrors = /* @__PURE__ */ new WeakSet();
  21418. return {
  21419. close() {
  21420. worker?.stop();
  21421. },
  21422. async process(environment, source, root, options, resolvers) {
  21423. let sassPackage = loadSassPackage(root, failedSassEmbedded ?? false);
  21424. if (failedSassEmbedded === void 0) {
  21425. failedSassEmbedded = false;
  21426. try {
  21427. await import(sassPackage.path);
  21428. } catch (e) {
  21429. if (/sass-embedded-[a-z0-9]+-[a-z0-9]+/i.test(e.message)) {
  21430. failedSassEmbedded = true;
  21431. sassPackage = loadSassPackage(root, failedSassEmbedded);
  21432. }
  21433. }
  21434. }
  21435. worker ??= makeScssWorker(environment, resolvers, maxWorkers);
  21436. const { content: data, map: additionalMap } = await getSource(source, options.filename, options.additionalData, options.enableSourcemap);
  21437. const optionsWithoutAdditionalData = {
  21438. ...options,
  21439. additionalData: void 0
  21440. };
  21441. try {
  21442. const result = await worker.run(pathToFileURL(sassPackage.path).href, data, optionsWithoutAdditionalData);
  21443. const deps = result.stats.includedFiles.map((f) => cleanScssBugUrl(f));
  21444. const map = result.map ? JSON.parse(result.map.toString()) : void 0;
  21445. if (map) map.sources = map.sources.map((url) => url.startsWith("file://") ? normalizePath(fileURLToPath(url)) : url);
  21446. return {
  21447. code: result.css.toString(),
  21448. map,
  21449. additionalMap,
  21450. deps
  21451. };
  21452. } catch (e) {
  21453. if (!normalizedErrors.has(e)) {
  21454. e.message = `[sass] ${e.message}`;
  21455. e.id = e.file;
  21456. e.frame = e.formatted;
  21457. if (e.span?.start) {
  21458. e.line = e.span.start.line + 1;
  21459. e.column = e.span.start.column + 1;
  21460. e.frame = e.message;
  21461. }
  21462. normalizedErrors.add(e);
  21463. }
  21464. return {
  21465. code: "",
  21466. error: e,
  21467. deps: []
  21468. };
  21469. }
  21470. }
  21471. };
  21472. };
  21473. /**
  21474. * relative url() inside \@imported sass and less files must be rebased to use
  21475. * root file as base.
  21476. */
  21477. async function rebaseUrls(environment, file, rootFile, resolver, ignoreUrl) {
  21478. file = path.resolve(file);
  21479. const fileDir = path.dirname(file);
  21480. const rootDir = path.dirname(rootFile);
  21481. if (fileDir === rootDir) return { file };
  21482. const content = await fsp.readFile(file, "utf-8");
  21483. const hasUrls = cssUrlRE.test(content);
  21484. const hasDataUris = cssDataUriRE.test(content);
  21485. const hasImportCss = importCssRE.test(content);
  21486. if (!hasUrls && !hasDataUris && !hasImportCss) return { file };
  21487. let rebased;
  21488. const rebaseFn = async (unquotedUrl, rawUrl) => {
  21489. if (ignoreUrl?.(unquotedUrl, rawUrl)) return false;
  21490. if (unquotedUrl[0] === "/") return unquotedUrl;
  21491. const absolute = await resolver(environment, unquotedUrl, file) || path.resolve(fileDir, unquotedUrl);
  21492. return normalizePath(path.relative(rootDir, absolute));
  21493. };
  21494. if (hasImportCss) rebased = await rewriteImportCss(content, rebaseFn);
  21495. if (hasUrls) rebased = await rewriteCssUrls(rebased || content, rebaseFn);
  21496. if (hasDataUris) rebased = await rewriteCssDataUris(rebased || content, rebaseFn);
  21497. return {
  21498. file,
  21499. contents: rebased
  21500. };
  21501. }
  21502. const makeLessWorker = (environment, resolvers, maxWorkers) => {
  21503. const skipRebaseUrls = (unquotedUrl, _rawUrl) => {
  21504. return unquotedUrl[0] === "@";
  21505. };
  21506. const viteLessResolve = async (filename, dir, rootFile, mime) => {
  21507. const resolved = await resolvers.less(environment, filename, path.join(dir, "*"));
  21508. if (!resolved) return void 0;
  21509. if (mime === "application/javascript") return { resolved: path.resolve(resolved) };
  21510. const result = await rebaseUrls(environment, resolved, rootFile, resolvers.less, skipRebaseUrls);
  21511. return {
  21512. resolved,
  21513. contents: "contents" in result ? result.contents : void 0
  21514. };
  21515. };
  21516. return new WorkerWithFallback(async () => {
  21517. const [fsp, path] = await Promise.all([import("node:fs/promises"), import("node:path")]);
  21518. let ViteLessManager;
  21519. const createViteLessPlugin = (less, rootFile) => {
  21520. const { FileManager } = less;
  21521. ViteLessManager ??= class ViteManager extends FileManager {
  21522. rootFile;
  21523. constructor(rootFile) {
  21524. super();
  21525. this.rootFile = rootFile;
  21526. }
  21527. supports(filename) {
  21528. return !/^(?:https?:)?\/\//.test(filename);
  21529. }
  21530. supportsSync() {
  21531. return false;
  21532. }
  21533. async loadFile(filename, dir, opts, env) {
  21534. const result = await viteLessResolve(filename, dir, this.rootFile, opts.mime);
  21535. if (result) return {
  21536. filename: path.resolve(result.resolved),
  21537. contents: result.contents ?? await fsp.readFile(result.resolved, "utf-8")
  21538. };
  21539. else return super.loadFile(filename, dir, opts, env);
  21540. }
  21541. };
  21542. return {
  21543. install(_, pluginManager) {
  21544. pluginManager.addFileManager(new ViteLessManager(rootFile));
  21545. },
  21546. minVersion: [
  21547. 3,
  21548. 0,
  21549. 0
  21550. ]
  21551. };
  21552. };
  21553. return async (lessPath, content, options) => {
  21554. const nodeLess = (await import(lessPath)).default;
  21555. const viteResolverPlugin = createViteLessPlugin(nodeLess, options.filename);
  21556. return await nodeLess.render(content, {
  21557. paths: ["node_modules"],
  21558. ...options,
  21559. plugins: [viteResolverPlugin, ...options.plugins || []],
  21560. ...options.enableSourcemap ? { sourceMap: {
  21561. outputSourceFiles: true,
  21562. disableSourcemapAnnotation: true,
  21563. sourceMapFileInline: false
  21564. } } : {}
  21565. });
  21566. };
  21567. }, {
  21568. parentFunctions: { viteLessResolve },
  21569. shouldUseFake(_lessPath, _content, options) {
  21570. return !!options.plugins && options.plugins.length > 0;
  21571. },
  21572. max: maxWorkers
  21573. });
  21574. };
  21575. const lessProcessor = (maxWorkers) => {
  21576. let worker;
  21577. return {
  21578. close() {
  21579. worker?.stop();
  21580. },
  21581. async process(environment, source, root, options, resolvers) {
  21582. const lessPath = loadPreprocessorPath(PreprocessLang.less, root);
  21583. worker ??= makeLessWorker(environment, resolvers, maxWorkers);
  21584. const { content, map: additionalMap } = await getSource(source, options.filename, options.additionalData, options.enableSourcemap);
  21585. let result;
  21586. const optionsWithoutAdditionalData = {
  21587. ...options,
  21588. additionalData: void 0
  21589. };
  21590. try {
  21591. result = await worker.run(pathToFileURL(lessPath).href, content, optionsWithoutAdditionalData);
  21592. } catch (e) {
  21593. const error = e;
  21594. const normalizedError = /* @__PURE__ */ new Error(`[less] ${error.message || error.type}`);
  21595. normalizedError.loc = {
  21596. file: error.filename || options.filename,
  21597. line: error.line,
  21598. column: error.column
  21599. };
  21600. return {
  21601. code: "",
  21602. error: normalizedError,
  21603. deps: []
  21604. };
  21605. }
  21606. const map = result.map && JSON.parse(result.map);
  21607. if (map) delete map.sourcesContent;
  21608. return {
  21609. code: result.css.toString(),
  21610. map,
  21611. additionalMap,
  21612. deps: result.imports
  21613. };
  21614. }
  21615. };
  21616. };
  21617. const makeStylWorker = (maxWorkers) => {
  21618. return new WorkerWithFallback(() => {
  21619. return async (stylusPath, content, root, options) => {
  21620. const stylus = (await import(stylusPath)).default;
  21621. const ref = stylus(content, {
  21622. paths: ["node_modules"],
  21623. ...options
  21624. });
  21625. if (options.define) for (const key in options.define) ref.define(key, options.define[key]);
  21626. if (options.enableSourcemap) ref.set("sourcemap", {
  21627. comment: false,
  21628. inline: false,
  21629. basePath: root
  21630. });
  21631. return {
  21632. code: ref.render(),
  21633. map: ref.sourcemap,
  21634. deps: ref.deps()
  21635. };
  21636. };
  21637. }, {
  21638. shouldUseFake(_stylusPath, _content, _root, options) {
  21639. return !!(options.define && Object.values(options.define).some((d) => typeof d === "function") || options.Evaluator);
  21640. },
  21641. max: maxWorkers
  21642. });
  21643. };
  21644. const stylProcessor = (maxWorkers) => {
  21645. let worker;
  21646. return {
  21647. close() {
  21648. worker?.stop();
  21649. },
  21650. async process(_environment, source, root, options, _resolvers) {
  21651. const stylusPath = loadPreprocessorPath(PreprocessLang.stylus, root);
  21652. worker ??= makeStylWorker(maxWorkers);
  21653. const { content, map: additionalMap } = await getSource(source, options.filename, options.additionalData, options.enableSourcemap, "\n");
  21654. const importsDeps = (options.imports ?? []).map((dep) => path.resolve(dep));
  21655. const optionsWithoutAdditionalData = {
  21656. ...options,
  21657. additionalData: void 0
  21658. };
  21659. try {
  21660. const { code, map, deps } = await worker.run(pathToFileURL(stylusPath).href, content, root, optionsWithoutAdditionalData);
  21661. return {
  21662. code,
  21663. map: formatStylusSourceMap(map, root),
  21664. additionalMap,
  21665. deps: [...deps, ...importsDeps]
  21666. };
  21667. } catch (e) {
  21668. const wrapped = /* @__PURE__ */ new Error(`[stylus] ${e.message}`);
  21669. wrapped.name = e.name;
  21670. wrapped.stack = e.stack;
  21671. return {
  21672. code: "",
  21673. error: wrapped,
  21674. deps: []
  21675. };
  21676. }
  21677. }
  21678. };
  21679. };
  21680. function formatStylusSourceMap(mapBefore, root) {
  21681. if (!mapBefore) return void 0;
  21682. const map = { ...mapBefore };
  21683. const resolveFromRoot = (p) => normalizePath(path.resolve(root, p));
  21684. if (map.file) map.file = resolveFromRoot(map.file);
  21685. map.sources = map.sources.map(resolveFromRoot);
  21686. return map;
  21687. }
  21688. async function getSource(source, filename, additionalData, enableSourcemap, sep = "") {
  21689. if (!additionalData) return { content: source };
  21690. if (typeof additionalData === "function") {
  21691. const newContent = await additionalData(source, filename);
  21692. if (typeof newContent === "string") return { content: newContent };
  21693. return newContent;
  21694. }
  21695. if (!enableSourcemap) return { content: additionalData + sep + source };
  21696. const ms = new MagicString(source);
  21697. ms.appendLeft(0, sep);
  21698. ms.appendLeft(0, additionalData);
  21699. const map = ms.generateMap({ hires: "boundary" });
  21700. map.file = filename;
  21701. map.sources = [filename];
  21702. return {
  21703. content: ms.toString(),
  21704. map
  21705. };
  21706. }
  21707. const createPreprocessorWorkerController = (maxWorkers) => {
  21708. const scss = scssProcessor(maxWorkers);
  21709. const less = lessProcessor(maxWorkers);
  21710. const styl = stylProcessor(maxWorkers);
  21711. const sassProcess = (environment, source, root, options, resolvers) => {
  21712. const opts = { ...options };
  21713. opts.syntax = "indented";
  21714. return scss.process(environment, source, root, opts, resolvers);
  21715. };
  21716. const close = () => {
  21717. less.close();
  21718. scss.close();
  21719. styl.close();
  21720. };
  21721. return {
  21722. [PreprocessLang.less]: less.process,
  21723. [PreprocessLang.scss]: scss.process,
  21724. [PreprocessLang.sass]: sassProcess,
  21725. [PreprocessLang.styl]: styl.process,
  21726. [PreprocessLang.stylus]: styl.process,
  21727. close
  21728. };
  21729. };
  21730. const normalizeMaxWorkers = (maxWorker) => {
  21731. if (maxWorker === void 0) return 0;
  21732. if (maxWorker === true) return void 0;
  21733. return maxWorker;
  21734. };
  21735. const preprocessorSet = new Set([
  21736. PreprocessLang.less,
  21737. PreprocessLang.sass,
  21738. PreprocessLang.scss,
  21739. PreprocessLang.styl,
  21740. PreprocessLang.stylus
  21741. ]);
  21742. function isPreProcessor(lang) {
  21743. return lang && preprocessorSet.has(lang);
  21744. }
  21745. const importEsbuild = createCachedImport(() => import("esbuild"));
  21746. const importLightningCSS = createCachedImport(() => import("lightningcss"));
  21747. async function compileLightningCSS(environment, id, src, deps, workerController, urlResolver) {
  21748. const { config } = environment;
  21749. const filename = removeDirectQuery(id).replace("\0", NULL_BYTE_PLACEHOLDER);
  21750. let res;
  21751. try {
  21752. res = styleAttrRE.test(id) ? (await importLightningCSS()).transformStyleAttribute({
  21753. filename,
  21754. code: Buffer.from(src),
  21755. targets: config.css.lightningcss?.targets,
  21756. minify: config.isProduction && !!config.build.cssMinify,
  21757. analyzeDependencies: true
  21758. }) : await (await importLightningCSS()).bundleAsync({
  21759. ...config.css.lightningcss,
  21760. filename,
  21761. projectRoot: config.root,
  21762. resolver: {
  21763. async read(filePath) {
  21764. if (filePath === filename) return src;
  21765. const code = fs.readFileSync(filePath, "utf-8");
  21766. const lang = CSS_LANGS_RE.exec(filePath)?.[1];
  21767. if (isPreProcessor(lang)) {
  21768. const result = await compileCSSPreprocessors(environment, id, lang, code, workerController);
  21769. result.deps?.forEach((dep) => deps.add(dep));
  21770. return result.code;
  21771. } else if (lang === "sss") return (await transformSugarSS(environment, id, code)).code;
  21772. return code;
  21773. },
  21774. async resolve(id, from) {
  21775. const publicFile = checkPublicFile(id, environment.getTopLevelConfig());
  21776. if (publicFile) return publicFile;
  21777. const atImportResolvers = getAtImportResolvers(environment.getTopLevelConfig());
  21778. const lang = CSS_LANGS_RE.exec(from)?.[1];
  21779. let resolver;
  21780. switch (lang) {
  21781. case "css":
  21782. case "sss":
  21783. case "styl":
  21784. case "stylus":
  21785. case void 0:
  21786. resolver = atImportResolvers.css;
  21787. break;
  21788. case "sass":
  21789. case "scss":
  21790. resolver = atImportResolvers.sass;
  21791. break;
  21792. case "less":
  21793. resolver = atImportResolvers.less;
  21794. break;
  21795. default: throw new Error(`Unknown lang: ${lang}`);
  21796. }
  21797. const resolved = await resolver(environment, id, from);
  21798. if (resolved) {
  21799. deps.add(resolved);
  21800. return resolved;
  21801. }
  21802. return id;
  21803. }
  21804. },
  21805. minify: config.isProduction && !!config.build.cssMinify,
  21806. sourceMap: config.command === "build" ? !!config.build.sourcemap : config.css.devSourcemap,
  21807. analyzeDependencies: true,
  21808. cssModules: cssModuleRE.test(id) ? config.css.lightningcss?.cssModules ?? true : void 0
  21809. });
  21810. } catch (e) {
  21811. e.message = `[lightningcss] ${e.message}`;
  21812. if (e.loc) {
  21813. e.loc = {
  21814. file: e.fileName.replace(NULL_BYTE_PLACEHOLDER, "\0"),
  21815. line: e.loc.line,
  21816. column: e.loc.column - 1
  21817. };
  21818. try {
  21819. const friendlyMessage = getLightningCssErrorMessageForIeSyntaxes(fs.readFileSync(e.fileName, "utf-8"));
  21820. if (friendlyMessage) e.message += friendlyMessage;
  21821. } catch {}
  21822. }
  21823. throw e;
  21824. }
  21825. for (const warning of res.warnings) {
  21826. let msg = `[vite:css][lightningcss] ${warning.message}`;
  21827. msg += `\n${generateCodeFrame(src, {
  21828. line: warning.loc.line,
  21829. column: warning.loc.column - 1
  21830. })}`;
  21831. environment.logger.warn(import_picocolors.default.yellow(msg));
  21832. }
  21833. let css = decoder.decode(res.code);
  21834. for (const dep of res.dependencies) switch (dep.type) {
  21835. case "url": {
  21836. let replaceUrl;
  21837. if (skipUrlReplacer(dep.url)) replaceUrl = dep.url;
  21838. else if (urlResolver) {
  21839. const [newUrl, resolvedId] = await urlResolver(dep.url, dep.loc.filePath.replace(NULL_BYTE_PLACEHOLDER, "\0"));
  21840. if (resolvedId) deps.add(resolvedId);
  21841. replaceUrl = newUrl;
  21842. } else replaceUrl = dep.url;
  21843. css = css.replace(dep.placeholder, () => replaceUrl.replaceAll("\"", "\\\""));
  21844. break;
  21845. }
  21846. default: throw new Error(`Unsupported dependency type: ${dep.type}`);
  21847. }
  21848. let modules;
  21849. if ("exports" in res && res.exports) {
  21850. modules = {};
  21851. const sortedEntries = Object.entries(res.exports).sort((a, b) => a[0].localeCompare(b[0]));
  21852. for (const [key, value] of sortedEntries) {
  21853. modules[key] = value.name;
  21854. for (const c of value.composes) modules[key] += " " + c.name;
  21855. }
  21856. }
  21857. return {
  21858. code: css,
  21859. map: "map" in res ? res.map?.toString() : void 0,
  21860. modules
  21861. };
  21862. }
  21863. function getLightningCssErrorMessageForIeSyntaxes(code) {
  21864. const commonIeMessage = ", which was used in the past to support old Internet Explorer versions. This is not a valid CSS syntax and will be ignored by modern browsers. \nWhile this is not supported by LightningCSS, you can set `css.lightningcss.errorRecovery: true` to strip these codes.";
  21865. if (/[\s;{]\*[a-zA-Z-][\w-]+\s*:/.test(code)) return ".\nThis file contains star property hack (e.g. `*zoom`)" + commonIeMessage;
  21866. if (/min-width:\s*0\\0/.test(code)) return ".\nThis file contains @media zero hack (e.g. `@media (min-width: 0\\0)`)" + commonIeMessage;
  21867. }
  21868. const map = {
  21869. chrome: "chrome",
  21870. edge: "edge",
  21871. firefox: "firefox",
  21872. hermes: false,
  21873. ie: "ie",
  21874. ios: "ios_saf",
  21875. node: false,
  21876. opera: "opera",
  21877. rhino: false,
  21878. safari: "safari"
  21879. };
  21880. const esMap = {
  21881. 2015: [
  21882. "chrome49",
  21883. "edge13",
  21884. "safari10",
  21885. "ios10",
  21886. "firefox44",
  21887. "opera36"
  21888. ],
  21889. 2016: [
  21890. "chrome50",
  21891. "edge13",
  21892. "safari10",
  21893. "ios10",
  21894. "firefox43",
  21895. "opera37"
  21896. ],
  21897. 2017: [
  21898. "chrome58",
  21899. "edge15",
  21900. "safari11",
  21901. "ios11",
  21902. "firefox52",
  21903. "opera45"
  21904. ],
  21905. 2018: [
  21906. "chrome63",
  21907. "edge79",
  21908. "safari12",
  21909. "ios12",
  21910. "firefox58",
  21911. "opera50"
  21912. ],
  21913. 2019: [
  21914. "chrome73",
  21915. "edge79",
  21916. "safari12.1",
  21917. "ios12.1",
  21918. "firefox64",
  21919. "opera60"
  21920. ],
  21921. 2020: [
  21922. "chrome80",
  21923. "edge80",
  21924. "safari14.1",
  21925. "ios14.5",
  21926. "firefox80",
  21927. "opera67"
  21928. ],
  21929. 2021: [
  21930. "chrome85",
  21931. "edge85",
  21932. "safari14.1",
  21933. "ios14.5",
  21934. "firefox80",
  21935. "opera71"
  21936. ],
  21937. 2022: [
  21938. "chrome94",
  21939. "edge94",
  21940. "safari16.4",
  21941. "ios16.4",
  21942. "firefox93",
  21943. "opera80"
  21944. ],
  21945. 2023: [
  21946. "chrome110",
  21947. "edge110",
  21948. "safari16.4",
  21949. "ios16.4",
  21950. "firefox146",
  21951. "opera96"
  21952. ],
  21953. 2024: [
  21954. "chrome119",
  21955. "edge119",
  21956. "safari17.4",
  21957. "ios17.4",
  21958. "firefox145",
  21959. "opera105"
  21960. ],
  21961. 2025: [
  21962. "chrome136",
  21963. "edge136",
  21964. "safari26.0",
  21965. "ios26.0",
  21966. "firefox138",
  21967. "opera121"
  21968. ]
  21969. };
  21970. const esRE = /es(6|\d{4})/;
  21971. const versionRE = /\d/;
  21972. const convertTargetsCache = /* @__PURE__ */ new Map();
  21973. const convertTargets = (esbuildTarget) => {
  21974. if (!esbuildTarget) return {};
  21975. const cached = convertTargetsCache.get(esbuildTarget);
  21976. if (cached) return cached;
  21977. const targets = {};
  21978. const entriesWithoutES = arraify(esbuildTarget).flatMap((e) => {
  21979. const match = esRE.exec(e);
  21980. if (!match) return e;
  21981. const year = match[1] === "6" ? 2015 : Number(match[1]);
  21982. if (!esMap[year]) throw new Error(`Unsupported target "${e}"`);
  21983. return esMap[year];
  21984. });
  21985. for (const entry of entriesWithoutES) {
  21986. if (entry === "esnext") continue;
  21987. const index = entry.search(versionRE);
  21988. if (index >= 0) {
  21989. const browser = map[entry.slice(0, index)];
  21990. if (browser === false) continue;
  21991. if (browser) {
  21992. const [major, minor = 0] = entry.slice(index).split(".").map((v) => parseInt(v, 10));
  21993. if (!isNaN(major) && !isNaN(minor)) {
  21994. const version = major << 16 | minor << 8;
  21995. if (!targets[browser] || version < targets[browser]) targets[browser] = version;
  21996. continue;
  21997. }
  21998. }
  21999. }
  22000. throw new Error(`Unsupported target "${entry}"`);
  22001. }
  22002. convertTargetsCache.set(esbuildTarget, targets);
  22003. return targets;
  22004. };
  22005. function resolveLibCssFilename(libOptions, root, packageCache) {
  22006. if (typeof libOptions.cssFileName === "string") return `${libOptions.cssFileName}.css`;
  22007. else if (typeof libOptions.fileName === "string") return `${libOptions.fileName}.css`;
  22008. const packageJson = findNearestMainPackageData(root, packageCache)?.data;
  22009. const name = packageJson ? getPkgName(packageJson.name) : void 0;
  22010. if (!name) throw new Error("Name in package.json is required if option \"build.lib.cssFileName\" is not provided.");
  22011. return `${name}.css`;
  22012. }
  22013. //#endregion
  22014. //#region src/node/plugins/modulePreloadPolyfill.ts
  22015. const modulePreloadPolyfillId = "vite/modulepreload-polyfill";
  22016. const resolvedModulePreloadPolyfillId = "\0" + modulePreloadPolyfillId + ".js";
  22017. function modulePreloadPolyfillPlugin(config) {
  22018. if (config.isBundled) return perEnvironmentPlugin("native:modulepreload-polyfill", (environment) => {
  22019. return viteModulePreloadPolyfillPlugin({ isServer: environment.config.consumer !== "client" });
  22020. });
  22021. return {
  22022. name: "vite:modulepreload-polyfill",
  22023. resolveId: {
  22024. filter: { id: exactRegex(modulePreloadPolyfillId) },
  22025. handler(_id) {
  22026. return resolvedModulePreloadPolyfillId;
  22027. }
  22028. },
  22029. load: {
  22030. filter: { id: exactRegex(resolvedModulePreloadPolyfillId) },
  22031. handler(_id) {
  22032. return "";
  22033. }
  22034. }
  22035. };
  22036. }
  22037. //#endregion
  22038. //#region src/node/plugins/html.ts
  22039. var import_escape_html = /* @__PURE__ */ __toESM(require_escape_html(), 1);
  22040. const htmlProxyRE = /[?&]html-proxy=?(?:&inline-css)?(?:&style-attr)?&index=(\d+)\.(?:js|css)$/;
  22041. const isHtmlProxyRE = /[?&]html-proxy\b/;
  22042. const inlineCSSRE = /__VITE_INLINE_CSS__([a-z\d]{8}_\d+)__/g;
  22043. const inlineImportRE = /(?<!(?<!\.\.)\.)\bimport\s*\(("(?:[^"]|(?<=\\)")*"|'(?:[^']|(?<=\\)')*')\)/dg;
  22044. const htmlLangRE = /\.(?:html|htm)$/;
  22045. const spaceRe = /[\t\n\f\r ]/;
  22046. const importMapRE = /[ \t]*<script[^>]*type\s*=\s*(?:"importmap"|'importmap'|importmap)[^>]*>.*?<\/script>/is;
  22047. const importMapAppendRE = new RegExp([/[ \t]*<script[^>]*type\s*=\s*(?:"module"|'module'|module)[^>]*>/i, /[ \t]*<link[^>]*rel\s*=\s*(?:"modulepreload"|'modulepreload'|modulepreload)[\s\S]*?\/>/i].map((r) => r.source).join("|"), "i");
  22048. const isHTMLProxy = (id) => isHtmlProxyRE.test(id);
  22049. const isHTMLRequest = (request) => htmlLangRE.test(request);
  22050. const htmlProxyMap = /* @__PURE__ */ new WeakMap();
  22051. const htmlProxyResult = /* @__PURE__ */ new Map();
  22052. function htmlInlineProxyPlugin(config) {
  22053. htmlProxyMap.set(config, /* @__PURE__ */ new Map());
  22054. return {
  22055. name: "vite:html-inline-proxy",
  22056. resolveId: {
  22057. filter: { id: isHtmlProxyRE },
  22058. handler(id) {
  22059. return id;
  22060. }
  22061. },
  22062. load: {
  22063. filter: { id: isHtmlProxyRE },
  22064. handler(id) {
  22065. const proxyMatch = htmlProxyRE.exec(id);
  22066. if (proxyMatch) {
  22067. const index = Number(proxyMatch[1]);
  22068. const url = cleanUrl(id).replace(normalizePath(config.root), "");
  22069. const result = htmlProxyMap.get(config).get(url)?.[index];
  22070. if (result) return {
  22071. ...result,
  22072. moduleSideEffects: true
  22073. };
  22074. else throw new Error(`No matching HTML proxy module found from ${id}`);
  22075. }
  22076. }
  22077. }
  22078. };
  22079. }
  22080. function addToHTMLProxyCache(config, filePath, index, result) {
  22081. if (!htmlProxyMap.get(config)) htmlProxyMap.set(config, /* @__PURE__ */ new Map());
  22082. if (!htmlProxyMap.get(config).get(filePath)) htmlProxyMap.get(config).set(filePath, []);
  22083. htmlProxyMap.get(config).get(filePath)[index] = result;
  22084. }
  22085. function addToHTMLProxyTransformResult(hash, code) {
  22086. htmlProxyResult.set(hash, code);
  22087. }
  22088. const noInlineLinkRels = new Set([
  22089. "icon",
  22090. "apple-touch-icon",
  22091. "apple-touch-startup-image",
  22092. "manifest"
  22093. ]);
  22094. const isAsyncScriptMap = /* @__PURE__ */ new WeakMap();
  22095. function nodeIsElement(node) {
  22096. return node.nodeName[0] !== "#";
  22097. }
  22098. function traverseNodes(node, visitor) {
  22099. if (node.nodeName === "template") node = node.content;
  22100. visitor(node);
  22101. if (nodeIsElement(node) || node.nodeName === "#document" || node.nodeName === "#document-fragment") node.childNodes.forEach((childNode) => traverseNodes(childNode, visitor));
  22102. }
  22103. async function traverseHtml(html, filePath, warn, visitor) {
  22104. const { parse } = await import("./dist.js");
  22105. const warnings = {};
  22106. traverseNodes(parse(html, {
  22107. scriptingEnabled: false,
  22108. sourceCodeLocationInfo: true,
  22109. onParseError: (e) => {
  22110. handleParseError(e, html, filePath, warnings);
  22111. }
  22112. }), visitor);
  22113. for (const message of Object.values(warnings)) warn(import_picocolors.default.yellow(`\n${message}`));
  22114. }
  22115. function getScriptInfo(node) {
  22116. let src;
  22117. let srcSourceCodeLocation;
  22118. let isModule = false;
  22119. let isAsync = false;
  22120. let isIgnored = false;
  22121. for (const p of node.attrs) {
  22122. if (p.prefix !== void 0) continue;
  22123. if (p.name === "src") {
  22124. if (!src) {
  22125. src = p;
  22126. srcSourceCodeLocation = node.sourceCodeLocation?.attrs["src"];
  22127. }
  22128. } else if (p.name === "type" && p.value === "module") isModule = true;
  22129. else if (p.name === "async") isAsync = true;
  22130. else if (p.name === "vite-ignore") isIgnored = true;
  22131. }
  22132. return {
  22133. src,
  22134. srcSourceCodeLocation,
  22135. isModule,
  22136. isAsync,
  22137. isIgnored
  22138. };
  22139. }
  22140. const attrValueStartRE = /=\s*(.)/;
  22141. function overwriteAttrValue(s, sourceCodeLocation, newValue) {
  22142. const srcString = s.slice(sourceCodeLocation.startOffset, sourceCodeLocation.endOffset);
  22143. const valueStart = attrValueStartRE.exec(srcString);
  22144. if (!valueStart) throw new Error(`[vite:html] internal error, failed to overwrite attribute value`);
  22145. const wrapOffset = valueStart[1] === "\"" || valueStart[1] === "'" ? 1 : 0;
  22146. const valueOffset = valueStart.index + valueStart[0].length - 1;
  22147. s.update(sourceCodeLocation.startOffset + valueOffset + wrapOffset, sourceCodeLocation.endOffset - wrapOffset, newValue);
  22148. return s;
  22149. }
  22150. function removeViteIgnoreAttr(s, sourceCodeLocation) {
  22151. const loc = sourceCodeLocation.attrs?.["vite-ignore"];
  22152. if (loc) s.remove(loc.startOffset, loc.endOffset);
  22153. return s;
  22154. }
  22155. /**
  22156. * Format parse5 @type {ParserError} to @type {RollupError}
  22157. */
  22158. function formatParseError(parserError, id, html) {
  22159. return {
  22160. code: parserError.code,
  22161. message: `parse5 error code ${parserError.code}`,
  22162. frame: generateCodeFrame(html, parserError.startOffset, parserError.endOffset),
  22163. loc: {
  22164. file: id,
  22165. line: parserError.startLine,
  22166. column: parserError.startCol
  22167. }
  22168. };
  22169. }
  22170. function handleParseError(parserError, html, filePath, warnings) {
  22171. switch (parserError.code) {
  22172. case "missing-doctype": return;
  22173. case "abandoned-head-element-child": return;
  22174. case "duplicate-attribute": return;
  22175. case "non-void-html-element-start-tag-with-trailing-solidus": return;
  22176. case "unexpected-question-mark-instead-of-tag-name": return;
  22177. }
  22178. const parseError = formatParseError(parserError, filePath, html);
  22179. warnings[parseError.code] ??= `Unable to parse HTML; ${parseError.message}\n at ${parseError.loc.file}:${parseError.loc.line}:${parseError.loc.column}\n` + parseError.frame;
  22180. }
  22181. /**
  22182. * Collects CSS files for a chunk by traversing its imports depth-first,
  22183. * using a cache to avoid re-analyzing chunks while still returning the
  22184. * correct files when the same chunk is reached via different entry points.
  22185. */
  22186. function getCssFilesForChunk(chunk, bundle, analyzedImportedCssFiles, seenChunks = /* @__PURE__ */ new Set(), seenCss = /* @__PURE__ */ new Set()) {
  22187. if (seenChunks.has(chunk.fileName)) return [];
  22188. seenChunks.add(chunk.fileName);
  22189. if (analyzedImportedCssFiles.has(chunk)) {
  22190. const additionals = analyzedImportedCssFiles.get(chunk).filter((file) => !seenCss.has(file));
  22191. additionals.forEach((file) => seenCss.add(file));
  22192. return additionals;
  22193. }
  22194. const allFiles = [];
  22195. const filteredFiles = [];
  22196. chunk.imports.forEach((file) => {
  22197. const importee = bundle[file];
  22198. if (importee?.type === "chunk") {
  22199. const importeeCss = getCssFilesForChunk(importee, bundle, analyzedImportedCssFiles, seenChunks, seenCss);
  22200. filteredFiles.push(...importeeCss);
  22201. if (analyzedImportedCssFiles.has(importee)) allFiles.push(...analyzedImportedCssFiles.get(importee));
  22202. else allFiles.push(...importeeCss);
  22203. }
  22204. });
  22205. chunk.viteMetadata.importedCss.forEach((file) => {
  22206. allFiles.push(file);
  22207. if (!seenCss.has(file)) {
  22208. seenCss.add(file);
  22209. filteredFiles.push(file);
  22210. }
  22211. });
  22212. analyzedImportedCssFiles.set(chunk, unique(allFiles));
  22213. return filteredFiles;
  22214. }
  22215. /**
  22216. * Compiles index.html into an entry js module
  22217. */
  22218. function buildHtmlPlugin(config) {
  22219. const [preHooks, normalHooks, postHooks] = resolveHtmlTransforms(config.plugins);
  22220. preHooks.unshift(injectCspNonceMetaTagHook(config));
  22221. preHooks.unshift(preImportMapHook(config));
  22222. preHooks.push(htmlEnvHook(config));
  22223. postHooks.push(injectNonceAttributeTagHook(config));
  22224. postHooks.push(postImportMapHook());
  22225. const processedHtml = perEnvironmentState(() => /* @__PURE__ */ new Map());
  22226. const isExcludedUrl = (url) => url[0] === "#" || isExternalUrl(url) || isDataUrl(url);
  22227. isAsyncScriptMap.set(config, /* @__PURE__ */ new Map());
  22228. return {
  22229. name: "vite:build-html",
  22230. transform: {
  22231. filter: { id: /\.html$/ },
  22232. async handler(html, id) {
  22233. id = normalizePath(id);
  22234. const relativeUrlPath = normalizePath(path.relative(config.root, id));
  22235. const publicPath = `/${relativeUrlPath}`;
  22236. const publicBase = getBaseInHTML(relativeUrlPath, config);
  22237. const publicToRelative = (filename) => publicBase + filename;
  22238. const toOutputPublicFilePath = (url) => toOutputFilePathInHtml(url.slice(1), "public", relativeUrlPath, "html", config, publicToRelative);
  22239. const nodeStartWithLeadingWhitespace = (node) => {
  22240. const startOffset = node.sourceCodeLocation.startOffset;
  22241. if (startOffset === 0) return 0;
  22242. const lineStartOffset = startOffset - node.sourceCodeLocation.startCol;
  22243. let isLineEmpty = false;
  22244. try {
  22245. isLineEmpty = !s.slice(Math.max(0, lineStartOffset), startOffset).trim();
  22246. } catch {}
  22247. return isLineEmpty ? lineStartOffset : startOffset;
  22248. };
  22249. html = await applyHtmlTransforms(html, preHooks, this, {
  22250. path: publicPath,
  22251. filename: id
  22252. });
  22253. let js = "";
  22254. const s = new MagicString(html);
  22255. const scriptUrls = [];
  22256. const styleUrls = [];
  22257. let inlineModuleIndex = -1;
  22258. let everyScriptIsAsync = true;
  22259. let someScriptsAreAsync = false;
  22260. let someScriptsAreDefer = false;
  22261. const assetUrlsPromises = [];
  22262. const namedOutput = Object.keys(config.build.rollupOptions.input || {});
  22263. const processAssetUrl = async (url, shouldInline) => {
  22264. if (url !== "" && !namedOutput.includes(url) && !namedOutput.includes(removeLeadingSlash(url))) try {
  22265. return await urlToBuiltUrl(this, url, id, shouldInline);
  22266. } catch (e) {
  22267. if (e.code !== "ENOENT") throw e;
  22268. }
  22269. return url;
  22270. };
  22271. const setModuleSideEffectPromises = [];
  22272. await traverseHtml(html, id, config.logger.warn, (node) => {
  22273. if (!nodeIsElement(node)) return;
  22274. let shouldRemove = false;
  22275. if (node.nodeName === "script") {
  22276. const { src, srcSourceCodeLocation, isModule, isAsync, isIgnored } = getScriptInfo(node);
  22277. if (isIgnored) removeViteIgnoreAttr(s, node.sourceCodeLocation);
  22278. else {
  22279. const url = src && src.value;
  22280. const isPublicFile = !!(url && checkPublicFile(url, config));
  22281. if (isPublicFile) overwriteAttrValue(s, srcSourceCodeLocation, partialEncodeURIPath(toOutputPublicFilePath(url)));
  22282. if (isModule) {
  22283. inlineModuleIndex++;
  22284. if (url && !isExcludedUrl(url) && !isPublicFile) {
  22285. setModuleSideEffectPromises.push(this.resolve(url, id).then((resolved) => {
  22286. if (!resolved) return Promise.reject(/* @__PURE__ */ new Error(`Failed to resolve ${url} from ${id}`));
  22287. const moduleInfo = this.getModuleInfo(resolved.id);
  22288. if (moduleInfo) moduleInfo.moduleSideEffects = true;
  22289. else if (!resolved.external) return this.load({
  22290. ...resolved,
  22291. moduleSideEffects: true
  22292. }).then(() => {});
  22293. }));
  22294. js += `\nimport ${JSON.stringify(url)}`;
  22295. shouldRemove = true;
  22296. } else if (node.childNodes.length) {
  22297. const contents = node.childNodes.pop().value;
  22298. addToHTMLProxyCache(config, id.replace(normalizePath(config.root), ""), inlineModuleIndex, { code: contents });
  22299. js += `\nimport "${id}?html-proxy&index=${inlineModuleIndex}.js"`;
  22300. shouldRemove = true;
  22301. }
  22302. everyScriptIsAsync &&= isAsync;
  22303. someScriptsAreAsync ||= isAsync;
  22304. someScriptsAreDefer ||= !isAsync;
  22305. } else if (url && !isPublicFile) {
  22306. if (!isExcludedUrl(url)) config.logger.warn(`<script src="${url}"> in "${publicPath}" can't be bundled without type="module" attribute`);
  22307. } else if (node.childNodes.length) {
  22308. const scriptNode = node.childNodes.pop();
  22309. scriptUrls.push(...extractImportExpressionFromClassicScript(scriptNode));
  22310. }
  22311. }
  22312. }
  22313. const assetAttributes = getNodeAssetAttributes(node);
  22314. for (const attr of assetAttributes) if (attr.type === "remove") {
  22315. s.remove(attr.location.startOffset, attr.location.endOffset);
  22316. continue;
  22317. } else if (attr.type === "srcset") assetUrlsPromises.push((async () => {
  22318. const processedEncodedUrl = await processSrcSet(attr.value, async ({ url }) => {
  22319. const decodedUrl = decodeURIIfPossible(url);
  22320. if (decodedUrl !== void 0 && !isExcludedUrl(decodedUrl)) {
  22321. const result = await processAssetUrl(url);
  22322. return result !== decodedUrl ? encodeURIPath(result) : url;
  22323. }
  22324. return url;
  22325. });
  22326. if (processedEncodedUrl !== attr.value) overwriteAttrValue(s, attr.location, processedEncodedUrl);
  22327. })());
  22328. else if (attr.type === "src") {
  22329. const url = decodeURIIfPossible(attr.value);
  22330. if (url === void 0) {} else if (checkPublicFile(url, config)) overwriteAttrValue(s, attr.location, partialEncodeURIPath(toOutputPublicFilePath(url)));
  22331. else if (!isExcludedUrl(url)) if (node.nodeName === "link" && isCSSRequest(url) && !("media" in attr.attributes || "disabled" in attr.attributes)) {
  22332. const importExpression = `\nimport ${JSON.stringify(url)}`;
  22333. styleUrls.push({
  22334. url,
  22335. start: nodeStartWithLeadingWhitespace(node),
  22336. end: node.sourceCodeLocation.endOffset
  22337. });
  22338. js += importExpression;
  22339. } else {
  22340. const shouldInline = node.nodeName === "link" && attr.attributes.rel && parseRelAttr(attr.attributes.rel).some((v) => noInlineLinkRels.has(v)) ? false : void 0;
  22341. assetUrlsPromises.push((async () => {
  22342. const processedUrl = await processAssetUrl(url, shouldInline);
  22343. if (processedUrl !== url) overwriteAttrValue(s, attr.location, partialEncodeURIPath(processedUrl));
  22344. })());
  22345. }
  22346. }
  22347. const inlineStyle = findNeedTransformStyleAttribute(node);
  22348. if (inlineStyle) {
  22349. inlineModuleIndex++;
  22350. const code = inlineStyle.attr.value;
  22351. addToHTMLProxyCache(config, id.replace(normalizePath(config.root), ""), inlineModuleIndex, { code });
  22352. js += `\nimport "${id}?html-proxy&inline-css&style-attr&index=${inlineModuleIndex}.css"`;
  22353. const hash = getHash(cleanUrl(id));
  22354. overwriteAttrValue(s, inlineStyle.location, `__VITE_INLINE_CSS__${hash}_${inlineModuleIndex}__`);
  22355. }
  22356. if (node.nodeName === "style" && node.childNodes.length) {
  22357. const styleNode = node.childNodes.pop();
  22358. const filePath = id.replace(normalizePath(config.root), "");
  22359. inlineModuleIndex++;
  22360. addToHTMLProxyCache(config, filePath, inlineModuleIndex, { code: styleNode.value });
  22361. js += `\nimport "${id}?html-proxy&inline-css&index=${inlineModuleIndex}.css"`;
  22362. const hash = getHash(cleanUrl(id));
  22363. s.update(styleNode.sourceCodeLocation.startOffset, styleNode.sourceCodeLocation.endOffset, `__VITE_INLINE_CSS__${hash}_${inlineModuleIndex}__`);
  22364. }
  22365. if (shouldRemove) s.remove(nodeStartWithLeadingWhitespace(node), node.sourceCodeLocation.endOffset);
  22366. });
  22367. isAsyncScriptMap.get(config).set(id, everyScriptIsAsync);
  22368. if (someScriptsAreAsync && someScriptsAreDefer) config.logger.warn(`\nMixed async and defer script modules in ${id}, output script will fallback to defer. Every script, including inline ones, need to be marked as async for your output script to be async.`);
  22369. await Promise.all(assetUrlsPromises);
  22370. for (const { start, end, url } of scriptUrls) if (checkPublicFile(url, config)) s.update(start, end, partialEncodeURIPath(toOutputPublicFilePath(url)));
  22371. else if (!isExcludedUrl(url)) s.update(start, end, partialEncodeURIPath(await urlToBuiltUrl(this, url, id)));
  22372. const resolvedStyleUrls = await Promise.all(styleUrls.map(async (styleUrl) => ({
  22373. ...styleUrl,
  22374. resolved: await this.resolve(styleUrl.url, id)
  22375. })));
  22376. for (const { start, end, url, resolved } of resolvedStyleUrls) if (resolved == null) {
  22377. config.logger.warnOnce(`\n${url} doesn't exist at build time, it will remain unchanged to be resolved at runtime`);
  22378. const importExpression = `\nimport ${JSON.stringify(url)}`;
  22379. js = js.replace(importExpression, "");
  22380. } else s.remove(start, end);
  22381. processedHtml(this).set(id, s.toString());
  22382. const { modulePreload } = this.environment.config.build;
  22383. if (modulePreload !== false && modulePreload.polyfill && (someScriptsAreAsync || someScriptsAreDefer)) js = `import "${modulePreloadPolyfillId}";\n${js}`;
  22384. await Promise.all(setModuleSideEffectPromises);
  22385. return {
  22386. code: js,
  22387. moduleSideEffects: "no-treeshake"
  22388. };
  22389. }
  22390. },
  22391. async generateBundle(options, bundle) {
  22392. const analyzedImportedCssFiles = /* @__PURE__ */ new Map();
  22393. const inlineEntryChunk = /* @__PURE__ */ new Set();
  22394. const getImportedChunks = (chunk, seen = /* @__PURE__ */ new Set()) => {
  22395. const chunks = [];
  22396. chunk.imports.forEach((file) => {
  22397. const importee = bundle[file];
  22398. if (importee) {
  22399. if (importee.type === "chunk" && !seen.has(file)) {
  22400. seen.add(file);
  22401. chunks.push(...getImportedChunks(importee, seen));
  22402. chunks.push(importee);
  22403. }
  22404. } else chunks.push(file);
  22405. });
  22406. return chunks;
  22407. };
  22408. const toScriptTag = (chunkOrUrl, toOutputPath, isAsync) => ({
  22409. tag: "script",
  22410. attrs: {
  22411. ...isAsync ? { async: true } : {},
  22412. type: "module",
  22413. crossorigin: true,
  22414. src: typeof chunkOrUrl === "string" ? chunkOrUrl : toOutputPath(chunkOrUrl.fileName)
  22415. }
  22416. });
  22417. const toPreloadTag = (filename, toOutputPath) => ({
  22418. tag: "link",
  22419. attrs: {
  22420. rel: "modulepreload",
  22421. crossorigin: true,
  22422. href: toOutputPath(filename)
  22423. }
  22424. });
  22425. const toStyleSheetLinkTag = (file, toOutputPath) => ({
  22426. tag: "link",
  22427. attrs: {
  22428. rel: "stylesheet",
  22429. crossorigin: true,
  22430. href: toOutputPath(file)
  22431. }
  22432. });
  22433. const getCssTagsForChunk = (chunk, toOutputPath) => getCssFilesForChunk(chunk, bundle, analyzedImportedCssFiles).map((file) => toStyleSheetLinkTag(file, toOutputPath));
  22434. for (const [normalizedId, html] of processedHtml(this)) {
  22435. const relativeUrlPath = normalizePath(path.relative(config.root, normalizedId));
  22436. const assetsBase = getBaseInHTML(relativeUrlPath, config);
  22437. const toOutputFilePath = (filename, type) => {
  22438. if (isExternalUrl(filename)) return filename;
  22439. else return toOutputFilePathInHtml(filename, type, relativeUrlPath, "html", config, (filename) => assetsBase + filename);
  22440. };
  22441. const toOutputAssetFilePath = (filename) => toOutputFilePath(filename, "asset");
  22442. const toOutputPublicAssetFilePath = (filename) => toOutputFilePath(filename, "public");
  22443. const isAsync = isAsyncScriptMap.get(config).get(normalizedId);
  22444. let result = html;
  22445. const chunk = Object.values(bundle).find((chunk) => chunk.type === "chunk" && chunk.isEntry && chunk.facadeModuleId && normalizePath(chunk.facadeModuleId) === normalizedId);
  22446. let canInlineEntry = false;
  22447. if (chunk) {
  22448. if (options.format === "es" && isEntirelyImport(chunk.code)) canInlineEntry = true;
  22449. const imports = getImportedChunks(chunk);
  22450. let assetTags;
  22451. if (canInlineEntry) assetTags = imports.map((chunk) => toScriptTag(chunk, toOutputAssetFilePath, isAsync));
  22452. else {
  22453. const { modulePreload } = this.environment.config.build;
  22454. assetTags = [toScriptTag(chunk, toOutputAssetFilePath, isAsync)];
  22455. if (modulePreload !== false) {
  22456. const resolveDependencies = typeof modulePreload === "object" && modulePreload.resolveDependencies;
  22457. const importsFileNames = imports.filter((chunkOrUrl) => typeof chunkOrUrl !== "string").map((chunk) => chunk.fileName);
  22458. const resolvedDeps = resolveDependencies ? resolveDependencies(chunk.fileName, importsFileNames, {
  22459. hostId: relativeUrlPath,
  22460. hostType: "html"
  22461. }) : importsFileNames;
  22462. assetTags.push(...resolvedDeps.map((i) => toPreloadTag(i, toOutputAssetFilePath)));
  22463. }
  22464. }
  22465. assetTags.push(...getCssTagsForChunk(chunk, toOutputAssetFilePath));
  22466. result = injectToHead(result, assetTags);
  22467. }
  22468. if (!this.environment.config.build.cssCodeSplit) {
  22469. const cssBundleName = cssBundleNameCache.get(config);
  22470. const cssChunk = cssBundleName && Object.values(bundle).find((chunk) => chunk.type === "asset" && chunk.names.includes(cssBundleName));
  22471. if (cssChunk) result = injectToHead(result, [{
  22472. tag: "link",
  22473. attrs: {
  22474. rel: "stylesheet",
  22475. crossorigin: true,
  22476. href: toOutputAssetFilePath(cssChunk.fileName)
  22477. }
  22478. }]);
  22479. }
  22480. let match;
  22481. let s;
  22482. inlineCSSRE.lastIndex = 0;
  22483. while (match = inlineCSSRE.exec(result)) {
  22484. s ||= new MagicString(result);
  22485. const { 0: full, 1: scopedName } = match;
  22486. const cssTransformedCode = htmlProxyResult.get(scopedName);
  22487. s.update(match.index, match.index + full.length, cssTransformedCode);
  22488. }
  22489. if (s) result = s.toString();
  22490. result = await applyHtmlTransforms(result, [...normalHooks, ...postHooks], this, {
  22491. path: "/" + relativeUrlPath,
  22492. filename: normalizedId,
  22493. bundle,
  22494. chunk
  22495. });
  22496. result = result.replace(assetUrlRE, (_, fileHash, postfix = "") => {
  22497. const file = this.getFileName(fileHash);
  22498. if (chunk) chunk.viteMetadata.importedAssets.add(cleanUrl(file));
  22499. return encodeURIPath(toOutputAssetFilePath(file)) + postfix;
  22500. });
  22501. result = result.replace(publicAssetUrlRE, (_, fileHash) => {
  22502. const publicAssetPath = toOutputPublicAssetFilePath(getPublicAssetFilename(fileHash, config));
  22503. return encodeURIPath(URL$1.canParse(publicAssetPath) ? publicAssetPath : normalizePath(publicAssetPath));
  22504. });
  22505. if (chunk && canInlineEntry) inlineEntryChunk.add(chunk.fileName);
  22506. const shortEmitName = normalizePath(path.relative(config.root, normalizedId));
  22507. this.emitFile({
  22508. type: "asset",
  22509. originalFileName: normalizedId,
  22510. fileName: shortEmitName,
  22511. source: result
  22512. });
  22513. }
  22514. for (const fileName of inlineEntryChunk) delete bundle[fileName];
  22515. }
  22516. };
  22517. }
  22518. function parseRelAttr(attr) {
  22519. return attr.split(spaceRe).map((v) => v.toLowerCase());
  22520. }
  22521. function findNeedTransformStyleAttribute(node) {
  22522. const attr = node.attrs.find((prop) => prop.prefix === void 0 && prop.name === "style" && (prop.value.includes("url(") || prop.value.includes("image-set(")));
  22523. if (!attr) return void 0;
  22524. return {
  22525. attr,
  22526. location: node.sourceCodeLocation?.attrs?.["style"]
  22527. };
  22528. }
  22529. function extractImportExpressionFromClassicScript(scriptTextNode) {
  22530. const startOffset = scriptTextNode.sourceCodeLocation.startOffset;
  22531. const cleanCode = stripLiteral(scriptTextNode.value);
  22532. const scriptUrls = [];
  22533. let match;
  22534. inlineImportRE.lastIndex = 0;
  22535. while (match = inlineImportRE.exec(cleanCode)) {
  22536. const [, [urlStart, urlEnd]] = match.indices;
  22537. const start = urlStart + 1;
  22538. const end = urlEnd - 1;
  22539. scriptUrls.push({
  22540. start: start + startOffset,
  22541. end: end + startOffset,
  22542. url: scriptTextNode.value.slice(start, end)
  22543. });
  22544. }
  22545. return scriptUrls;
  22546. }
  22547. function preImportMapHook(config) {
  22548. return (html, ctx) => {
  22549. const importMapIndex = html.search(importMapRE);
  22550. if (importMapIndex < 0) return;
  22551. const importMapAppendIndex = html.search(importMapAppendRE);
  22552. if (importMapAppendIndex < 0) return;
  22553. if (importMapAppendIndex < importMapIndex) {
  22554. const relativeHtml = normalizePath(path.relative(config.root, ctx.filename));
  22555. config.logger.warnOnce(import_picocolors.default.yellow(import_picocolors.default.bold(`(!) <script type="importmap"> should come before <script type="module"> and <link rel="modulepreload"> in /${relativeHtml}`)));
  22556. }
  22557. };
  22558. }
  22559. /**
  22560. * Move importmap before the first module script and modulepreload link
  22561. */
  22562. function postImportMapHook() {
  22563. return (html) => {
  22564. if (!importMapAppendRE.test(html)) return;
  22565. let importMap;
  22566. html = html.replace(importMapRE, (match) => {
  22567. importMap = match;
  22568. return "";
  22569. });
  22570. if (importMap) html = html.replace(importMapAppendRE, (match) => `${importMap}\n${match}`);
  22571. return html;
  22572. };
  22573. }
  22574. function injectCspNonceMetaTagHook(config) {
  22575. return () => {
  22576. if (!config.html?.cspNonce) return;
  22577. return [{
  22578. tag: "meta",
  22579. injectTo: "head",
  22580. attrs: {
  22581. property: "csp-nonce",
  22582. nonce: config.html.cspNonce
  22583. }
  22584. }];
  22585. };
  22586. }
  22587. /**
  22588. * Support `%ENV_NAME%` syntax in html files
  22589. */
  22590. function htmlEnvHook(config) {
  22591. const pattern = /%(\S+?)%/g;
  22592. const envPrefix = resolveEnvPrefix({ envPrefix: config.envPrefix });
  22593. const env = { ...config.env };
  22594. for (const key in config.define) if (key.startsWith(`import.meta.env.`)) {
  22595. const val = config.define[key];
  22596. if (typeof val === "string") try {
  22597. const parsed = JSON.parse(val);
  22598. env[key.slice(16)] = typeof parsed === "string" ? parsed : val;
  22599. } catch {
  22600. env[key.slice(16)] = val;
  22601. }
  22602. else env[key.slice(16)] = JSON.stringify(val);
  22603. }
  22604. return (html, ctx) => {
  22605. return html.replace(pattern, (text, key) => {
  22606. if (key in env) return env[key];
  22607. else {
  22608. if (envPrefix.some((prefix) => key.startsWith(prefix))) {
  22609. const relativeHtml = normalizePath(path.relative(config.root, ctx.filename));
  22610. config.logger.warn(import_picocolors.default.yellow(import_picocolors.default.bold(`(!) ${text} is not defined in env variables found in /${relativeHtml}. Is the variable mistyped?`)));
  22611. }
  22612. return text;
  22613. }
  22614. });
  22615. };
  22616. }
  22617. function injectNonceAttributeTagHook(config) {
  22618. const processRelType = new Set([
  22619. "stylesheet",
  22620. "modulepreload",
  22621. "preload"
  22622. ]);
  22623. return async (html, { filename }) => {
  22624. const nonce = config.html?.cspNonce;
  22625. if (!nonce) return;
  22626. const s = new MagicString(html);
  22627. await traverseHtml(html, filename, config.logger.warn, (node) => {
  22628. if (!nodeIsElement(node)) return;
  22629. const { nodeName, attrs, sourceCodeLocation } = node;
  22630. if (nodeName === "script" || nodeName === "style" || nodeName === "link" && attrs.some((attr) => attr.name === "rel" && parseRelAttr(attr.value).some((a) => processRelType.has(a)))) {
  22631. if (attrs.some(({ name }) => name === "nonce")) return;
  22632. const startTagEndOffset = sourceCodeLocation.startTag.endOffset;
  22633. const appendOffset = html[startTagEndOffset - 2] === "/" ? 2 : 1;
  22634. s.appendRight(startTagEndOffset - appendOffset, ` nonce="${nonce}"`);
  22635. }
  22636. });
  22637. return s.toString();
  22638. };
  22639. }
  22640. function resolveHtmlTransforms(plugins) {
  22641. const preHooks = [];
  22642. const normalHooks = [];
  22643. const postHooks = [];
  22644. for (const plugin of plugins) {
  22645. const hook = plugin.transformIndexHtml;
  22646. if (!hook) continue;
  22647. if (typeof hook === "function") normalHooks.push(hook);
  22648. else {
  22649. const handler = hook.handler;
  22650. if (hook.order === "pre") preHooks.push(handler);
  22651. else if (hook.order === "post") postHooks.push(handler);
  22652. else normalHooks.push(handler);
  22653. }
  22654. }
  22655. return [
  22656. preHooks,
  22657. normalHooks,
  22658. postHooks
  22659. ];
  22660. }
  22661. const elementsAllowedInHead = new Set([
  22662. "title",
  22663. "base",
  22664. "link",
  22665. "style",
  22666. "meta",
  22667. "script",
  22668. "noscript",
  22669. "template"
  22670. ]);
  22671. function headTagInsertCheck(tags, ctx) {
  22672. if (!tags.length) return;
  22673. const { logger } = ctx.server?.config || {};
  22674. const disallowedTags = tags.filter((tagDescriptor) => !elementsAllowedInHead.has(tagDescriptor.tag));
  22675. if (disallowedTags.length) {
  22676. const dedupedTags = unique(disallowedTags.map((tagDescriptor) => `<${tagDescriptor.tag}>`));
  22677. logger?.warn(import_picocolors.default.yellow(import_picocolors.default.bold(`[${dedupedTags.join(",")}] can not be used inside the <head> Element, please check the 'injectTo' value`)));
  22678. }
  22679. }
  22680. async function applyHtmlTransforms(html, hooks, pluginContext, ctx) {
  22681. for (const hook of hooks) {
  22682. const res = await hook.call(pluginContext, html, ctx);
  22683. if (!res) continue;
  22684. if (typeof res === "string") html = res;
  22685. else {
  22686. let tags;
  22687. if (Array.isArray(res)) tags = res;
  22688. else {
  22689. html = res.html || html;
  22690. tags = res.tags;
  22691. }
  22692. let headTags;
  22693. let headPrependTags;
  22694. let bodyTags;
  22695. let bodyPrependTags;
  22696. for (const tag of tags) switch (tag.injectTo) {
  22697. case "body":
  22698. (bodyTags ??= []).push(tag);
  22699. break;
  22700. case "body-prepend":
  22701. (bodyPrependTags ??= []).push(tag);
  22702. break;
  22703. case "head":
  22704. (headTags ??= []).push(tag);
  22705. break;
  22706. default: (headPrependTags ??= []).push(tag);
  22707. }
  22708. headTagInsertCheck([...headTags || [], ...headPrependTags || []], ctx);
  22709. if (headPrependTags) html = injectToHead(html, headPrependTags, true);
  22710. if (headTags) html = injectToHead(html, headTags);
  22711. if (bodyPrependTags) html = injectToBody(html, bodyPrependTags, true);
  22712. if (bodyTags) html = injectToBody(html, bodyTags);
  22713. }
  22714. }
  22715. return html;
  22716. }
  22717. const entirelyImportRE = /^(?:import\s*(?:"[^"\n]*[^\\\n]"|'[^'\n]*[^\\\n]');*|\/\*[\s\S]*?\*\/|\/\/.*[$\n])*$/;
  22718. function isEntirelyImport(code) {
  22719. return entirelyImportRE.test(code.trim());
  22720. }
  22721. function getBaseInHTML(urlRelativePath, config) {
  22722. return config.base === "./" || config.base === "" ? path.posix.join(path.posix.relative(urlRelativePath, "").slice(0, -2), "./") : config.base;
  22723. }
  22724. const headInjectRE = /([ \t]*)<\/head>/i;
  22725. const headPrependInjectRE = /([ \t]*)<head[^>]*>/i;
  22726. const htmlInjectRE = /<\/html>/i;
  22727. const htmlPrependInjectRE = /([ \t]*)<html[^>]*>/i;
  22728. const bodyInjectRE = /([ \t]*)<\/body>/i;
  22729. const bodyPrependInjectRE = /([ \t]*)<body[^>]*>/i;
  22730. const doctypePrependInjectRE = /<!doctype html>/i;
  22731. function injectToHead(html, tags, prepend = false) {
  22732. if (tags.length === 0) return html;
  22733. if (prepend) {
  22734. if (headPrependInjectRE.test(html)) return html.replace(headPrependInjectRE, (match, p1) => `${match}\n${serializeTags(tags, incrementIndent(p1))}`);
  22735. } else {
  22736. if (headInjectRE.test(html)) return html.replace(headInjectRE, (match, p1) => `${serializeTags(tags, incrementIndent(p1))}${match}`);
  22737. if (bodyPrependInjectRE.test(html)) return html.replace(bodyPrependInjectRE, (match, p1) => `${serializeTags(tags, p1)}\n${match}`);
  22738. }
  22739. return prependInjectFallback(html, tags);
  22740. }
  22741. function injectToBody(html, tags, prepend = false) {
  22742. if (tags.length === 0) return html;
  22743. if (prepend) {
  22744. if (bodyPrependInjectRE.test(html)) return html.replace(bodyPrependInjectRE, (match, p1) => `${match}\n${serializeTags(tags, incrementIndent(p1))}`);
  22745. if (headInjectRE.test(html)) return html.replace(headInjectRE, (match, p1) => `${match}\n${serializeTags(tags, p1)}`);
  22746. return prependInjectFallback(html, tags);
  22747. } else {
  22748. if (bodyInjectRE.test(html)) return html.replace(bodyInjectRE, (match, p1) => `${serializeTags(tags, incrementIndent(p1))}${match}`);
  22749. if (htmlInjectRE.test(html)) return html.replace(htmlInjectRE, `${serializeTags(tags)}\n$&`);
  22750. return html + `\n` + serializeTags(tags);
  22751. }
  22752. }
  22753. function prependInjectFallback(html, tags) {
  22754. if (htmlPrependInjectRE.test(html)) return html.replace(htmlPrependInjectRE, `$&\n${serializeTags(tags)}`);
  22755. if (doctypePrependInjectRE.test(html)) return html.replace(doctypePrependInjectRE, `$&\n${serializeTags(tags)}`);
  22756. return serializeTags(tags) + html;
  22757. }
  22758. const unaryTags = new Set([
  22759. "link",
  22760. "meta",
  22761. "base"
  22762. ]);
  22763. function serializeTag({ tag, attrs, children }, indent = "") {
  22764. if (unaryTags.has(tag)) return `<${tag}${serializeAttrs(attrs)}>`;
  22765. else return `<${tag}${serializeAttrs(attrs)}>${serializeTags(children, incrementIndent(indent))}</${tag}>`;
  22766. }
  22767. function serializeTags(tags, indent = "") {
  22768. if (typeof tags === "string") return tags;
  22769. else if (tags && tags.length) return tags.map((tag) => `${indent}${serializeTag(tag, indent)}\n`).join("");
  22770. return "";
  22771. }
  22772. function serializeAttrs(attrs) {
  22773. let res = "";
  22774. for (const key in attrs) if (typeof attrs[key] === "boolean") res += attrs[key] ? ` ${key}` : ``;
  22775. else res += ` ${key}="${(0, import_escape_html.default)(attrs[key])}"`;
  22776. return res;
  22777. }
  22778. function incrementIndent(indent = "") {
  22779. return `${indent}${indent[0] === " " ? " " : " "}`;
  22780. }
  22781. //#endregion
  22782. //#region src/node/plugins/define.ts
  22783. const nonJsRe = /\.json(?:$|\?)/;
  22784. const isNonJsRequest = (request) => nonJsRe.test(request);
  22785. const escapedDotRE = /(?<!\\)\\./g;
  22786. function definePlugin(config) {
  22787. const isBundled = config.isBundled;
  22788. const isBuild = config.command === "build";
  22789. const isBuildLib = isBuild && config.build.lib;
  22790. const processEnv = {};
  22791. if (!isBuildLib) {
  22792. const nodeEnv = process.env.NODE_ENV || config.mode;
  22793. Object.assign(processEnv, {
  22794. "process.env": `{}`,
  22795. "global.process.env": `{}`,
  22796. "globalThis.process.env": `{}`,
  22797. "process.env.NODE_ENV": JSON.stringify(nodeEnv),
  22798. "global.process.env.NODE_ENV": JSON.stringify(nodeEnv),
  22799. "globalThis.process.env.NODE_ENV": JSON.stringify(nodeEnv)
  22800. });
  22801. }
  22802. const importMetaKeys = {};
  22803. const importMetaEnvKeys = {};
  22804. const importMetaFallbackKeys = {};
  22805. if (isBuild) importMetaKeys["import.meta.hot"] = `undefined`;
  22806. if (isBundled) {
  22807. for (const key in config.env) {
  22808. const val = JSON.stringify(config.env[key]);
  22809. importMetaKeys[`import.meta.env.${key}`] = val;
  22810. importMetaEnvKeys[key] = val;
  22811. }
  22812. importMetaKeys["import.meta.env.SSR"] = `undefined`;
  22813. importMetaFallbackKeys["import.meta.env"] = `undefined`;
  22814. }
  22815. function generatePattern(environment) {
  22816. const keepProcessEnv = environment.config.keepProcessEnv;
  22817. const userDefine = {};
  22818. const userDefineEnv = {};
  22819. for (const key in environment.config.define) {
  22820. userDefine[key] = handleDefineValue(environment.config.define[key]);
  22821. if (isBuild && key.startsWith("import.meta.env.")) userDefineEnv[key.slice(16)] = environment.config.define[key];
  22822. }
  22823. const define = {
  22824. ...keepProcessEnv ? {} : processEnv,
  22825. ...importMetaKeys,
  22826. ...userDefine,
  22827. ...importMetaFallbackKeys
  22828. };
  22829. const ssr = environment.config.consumer === "server";
  22830. if ("import.meta.env.SSR" in define) define["import.meta.env.SSR"] = ssr + "";
  22831. const importMetaEnvVal = serializeDefine({
  22832. ...importMetaEnvKeys,
  22833. SSR: ssr + "",
  22834. ...userDefineEnv
  22835. });
  22836. const patternKeys = Object.keys(userDefine);
  22837. if (!keepProcessEnv && Object.keys(processEnv).length) patternKeys.push("process.env");
  22838. if (Object.keys(importMetaKeys).length) patternKeys.push("import.meta.env", "import.meta.hot");
  22839. return [
  22840. define,
  22841. patternKeys.length ? new RegExp(patternKeys.map((key) => escapeRegex(key).replaceAll(escapedDotRE, "\\??\\.")).join("|")) : null,
  22842. importMetaEnvVal
  22843. ];
  22844. }
  22845. const patternsCache = /* @__PURE__ */ new WeakMap();
  22846. function getPattern(environment) {
  22847. let pattern = patternsCache.get(environment);
  22848. if (!pattern) {
  22849. pattern = generatePattern(environment);
  22850. patternsCache.set(environment, pattern);
  22851. }
  22852. return pattern;
  22853. }
  22854. if (isBundled) return {
  22855. name: "vite:define",
  22856. options(option) {
  22857. const [define, _pattern, importMetaEnvVal] = getPattern(this.environment);
  22858. define["import.meta.env"] = importMetaEnvVal;
  22859. define["import.meta.env.*"] = "undefined";
  22860. option.transform ??= {};
  22861. option.transform.define = {
  22862. ...option.transform.define,
  22863. ...define
  22864. };
  22865. }
  22866. };
  22867. return {
  22868. name: "vite:define",
  22869. transform: { async handler(code, id) {
  22870. if (this.environment.config.consumer === "client") return;
  22871. if (isHTMLRequest(id) || isCSSRequest(id) || isNonJsRequest(id) || config.assetsInclude(id)) return;
  22872. const [define, pattern] = getPattern(this.environment);
  22873. if (!pattern) return;
  22874. pattern.lastIndex = 0;
  22875. if (!pattern.test(code)) return;
  22876. return await replaceDefine(this.environment, code, id, define);
  22877. } }
  22878. };
  22879. }
  22880. async function replaceDefine(environment, code, id, define) {
  22881. const result = transformSync(id, code, {
  22882. lang: "js",
  22883. sourceType: "module",
  22884. define,
  22885. sourcemap: environment.config.command === "build" ? !!environment.config.build.sourcemap : true,
  22886. tsconfig: false
  22887. });
  22888. if (result.errors.length > 0) throw new AggregateError(result.errors, "oxc transform error");
  22889. return {
  22890. code: result.code,
  22891. map: result.map || null
  22892. };
  22893. }
  22894. /**
  22895. * Like `JSON.stringify` but keeps raw string values as a literal
  22896. * in the generated code. For example: `"window"` would refer to
  22897. * the global `window` object directly.
  22898. */
  22899. function serializeDefine(define) {
  22900. let res = `{`;
  22901. const keys = Object.keys(define).sort();
  22902. for (let i = 0; i < keys.length; i++) {
  22903. const key = keys[i];
  22904. const val = define[key];
  22905. res += `${JSON.stringify(key)}: ${handleDefineValue(val)}`;
  22906. if (i !== keys.length - 1) res += `, `;
  22907. }
  22908. return res + `}`;
  22909. }
  22910. function handleDefineValue(value) {
  22911. if (typeof value === "undefined") return "undefined";
  22912. if (typeof value === "string") return value;
  22913. return JSON.stringify(value);
  22914. }
  22915. //#endregion
  22916. //#region src/node/plugins/clientInjections.ts
  22917. const normalizedClientEntry$1 = normalizePath(CLIENT_ENTRY);
  22918. const normalizedEnvEntry$1 = normalizePath(ENV_ENTRY);
  22919. /**
  22920. * some values used by the client needs to be dynamically injected by the server
  22921. * @server-only
  22922. */
  22923. function clientInjectionsPlugin(config) {
  22924. let injectConfigValues;
  22925. const getDefineReplacer = perEnvironmentState((environment) => {
  22926. const userDefine = {};
  22927. for (const key in environment.config.define) if (!key.startsWith("import.meta.env.")) userDefine[key] = environment.config.define[key];
  22928. const serializedDefines = serializeDefine(userDefine);
  22929. const definesReplacement = () => serializedDefines;
  22930. return (code) => code.replace(`__DEFINES__`, definesReplacement);
  22931. });
  22932. return {
  22933. name: "vite:client-inject",
  22934. async buildStart() {
  22935. injectConfigValues = await createClientConfigValueReplacer(config);
  22936. },
  22937. async transform(code, id) {
  22938. const ssr = this.environment.config.consumer === "server";
  22939. const cleanId = cleanUrl(id);
  22940. if (cleanId === normalizedClientEntry$1 || cleanId === normalizedEnvEntry$1) return getDefineReplacer(this)(injectConfigValues(code));
  22941. else if (!ssr && code.includes("process.env.NODE_ENV")) {
  22942. const nodeEnv = this.environment.config.define?.["process.env.NODE_ENV"] || JSON.stringify(process.env.NODE_ENV || config.mode);
  22943. return await replaceDefine(this.environment, code, id, {
  22944. "process.env.NODE_ENV": nodeEnv,
  22945. "global.process.env.NODE_ENV": nodeEnv,
  22946. "globalThis.process.env.NODE_ENV": nodeEnv
  22947. });
  22948. }
  22949. }
  22950. };
  22951. }
  22952. function escapeReplacement(value) {
  22953. const jsonValue = JSON.stringify(value);
  22954. return () => jsonValue;
  22955. }
  22956. async function createClientConfigValueReplacer(config) {
  22957. const resolvedServerHostname = (await resolveHostname(config.server.host)).name;
  22958. const resolvedServerPort = config.server.port;
  22959. const devBase = config.base;
  22960. const serverHost = `${resolvedServerHostname}:${resolvedServerPort}${devBase}`;
  22961. let hmrConfig = config.server.hmr;
  22962. hmrConfig = isObject$1(hmrConfig) ? hmrConfig : void 0;
  22963. const host = hmrConfig?.host || null;
  22964. const protocol = hmrConfig?.protocol || null;
  22965. const timeout = hmrConfig?.timeout || 3e4;
  22966. const overlay = hmrConfig?.overlay !== false;
  22967. const isHmrServerSpecified = !!hmrConfig?.server;
  22968. const hmrConfigName = path.basename(config.configFile || "vite.config.js");
  22969. let port = hmrConfig?.clientPort || hmrConfig?.port || null;
  22970. if (config.server.middlewareMode && !isHmrServerSpecified) port ||= 24678;
  22971. let directTarget = hmrConfig?.host || resolvedServerHostname;
  22972. directTarget += `:${hmrConfig?.port || resolvedServerPort}`;
  22973. directTarget += devBase;
  22974. let hmrBase = devBase;
  22975. if (hmrConfig?.path) hmrBase = path.posix.join(hmrBase, hmrConfig.path);
  22976. const modeReplacement = escapeReplacement(config.mode);
  22977. const baseReplacement = escapeReplacement(devBase);
  22978. const serverHostReplacement = escapeReplacement(serverHost);
  22979. const hmrProtocolReplacement = escapeReplacement(protocol);
  22980. const hmrHostnameReplacement = escapeReplacement(host);
  22981. const hmrPortReplacement = escapeReplacement(port);
  22982. const hmrDirectTargetReplacement = escapeReplacement(directTarget);
  22983. const hmrBaseReplacement = escapeReplacement(hmrBase);
  22984. const hmrTimeoutReplacement = escapeReplacement(timeout);
  22985. const hmrEnableOverlayReplacement = escapeReplacement(overlay);
  22986. const hmrConfigNameReplacement = escapeReplacement(hmrConfigName);
  22987. const wsTokenReplacement = escapeReplacement(config.webSocketToken);
  22988. const serverForwardConsoleReplacement = escapeReplacement(config.server.forwardConsole);
  22989. const bundleDevReplacement = escapeReplacement(config.experimental.bundledDev || false);
  22990. return (code) => code.replace(`__MODE__`, modeReplacement).replace(/__BASE__/g, baseReplacement).replace(`__SERVER_HOST__`, serverHostReplacement).replace(`__HMR_PROTOCOL__`, hmrProtocolReplacement).replace(`__HMR_HOSTNAME__`, hmrHostnameReplacement).replace(`__HMR_PORT__`, hmrPortReplacement).replace(`__HMR_DIRECT_TARGET__`, hmrDirectTargetReplacement).replace(`__HMR_BASE__`, hmrBaseReplacement).replace(`__HMR_TIMEOUT__`, hmrTimeoutReplacement).replace(`__HMR_ENABLE_OVERLAY__`, hmrEnableOverlayReplacement).replace(`__HMR_CONFIG_NAME__`, hmrConfigNameReplacement).replace(`__WS_TOKEN__`, wsTokenReplacement).replace(`__SERVER_FORWARD_CONSOLE__`, serverForwardConsoleReplacement).replaceAll(`__BUNDLED_DEV__`, bundleDevReplacement);
  22991. }
  22992. async function getHmrImplementation(config) {
  22993. const content = fs.readFileSync(normalizedClientEntry$1, "utf-8");
  22994. return (await createClientConfigValueReplacer(config))(content).replace(/import\s*['"]@vite\/env['"]/, "");
  22995. }
  22996. //#endregion
  22997. //#region src/node/ssr/fetchModule.ts
  22998. /**
  22999. * Fetch module information for Vite module runner.
  23000. * @experimental
  23001. */
  23002. async function fetchModule(environment, url, importer, options = {}) {
  23003. if (url.startsWith("data:") || isBuiltin(environment.config.resolve.builtins, url)) return {
  23004. externalize: url,
  23005. type: "builtin"
  23006. };
  23007. const isFileUrl = url.startsWith("file://");
  23008. if (isExternalUrl(url) && !isFileUrl) return {
  23009. externalize: url,
  23010. type: "network"
  23011. };
  23012. if (!isFileUrl && importer && url[0] !== "." && url[0] !== "/") {
  23013. const { isProduction, root } = environment.config;
  23014. const { externalConditions, dedupe, preserveSymlinks } = environment.config.resolve;
  23015. const resolved = tryNodeResolve(url, importer, {
  23016. mainFields: ["main"],
  23017. conditions: externalConditions,
  23018. externalConditions,
  23019. external: [],
  23020. noExternal: [],
  23021. extensions: [
  23022. ".js",
  23023. ".cjs",
  23024. ".json"
  23025. ],
  23026. dedupe,
  23027. preserveSymlinks,
  23028. tsconfigPaths: false,
  23029. isBuild: false,
  23030. isProduction,
  23031. root,
  23032. packageCache: environment.config.packageCache,
  23033. builtins: environment.config.resolve.builtins
  23034. });
  23035. if (!resolved) {
  23036. const err = /* @__PURE__ */ new Error(`Cannot find module '${url}' imported from '${importer}'`);
  23037. err.code = "ERR_MODULE_NOT_FOUND";
  23038. throw err;
  23039. }
  23040. return {
  23041. externalize: pathToFileURL(resolved.id).toString(),
  23042. type: isFilePathESM(resolved.id, environment.config.packageCache) ? "module" : "commonjs"
  23043. };
  23044. }
  23045. url = unwrapId(url);
  23046. const mod = await environment.moduleGraph.ensureEntryFromUrl(url);
  23047. const cached = !!mod.transformResult;
  23048. if (options.cached && cached) return { cache: true };
  23049. let result = await environment.transformRequest(url);
  23050. if (!result) throw new Error(`[vite] transform failed for module '${url}'${importer ? ` imported from '${importer}'` : ""}.`);
  23051. if (options.inlineSourceMap !== false) result = inlineSourceMap(mod, result, options.startOffset);
  23052. if (result.code[0] === "#") result.code = result.code.replace(/^#!.*/, (s) => " ".repeat(s.length));
  23053. return {
  23054. code: result.code,
  23055. file: mod.file,
  23056. id: mod.id,
  23057. url: mod.url,
  23058. invalidate: !cached
  23059. };
  23060. }
  23061. const OTHER_SOURCE_MAP_REGEXP = new RegExp(`//# ${SOURCEMAPPING_URL}=data:application/json[^,]+base64,([A-Za-z0-9+/=]+)$`, "gm");
  23062. function inlineSourceMap(mod, result, startOffset) {
  23063. const map = result.map;
  23064. let code = result.code;
  23065. if (!map || !("version" in map) || code.includes("//# sourceMappingSource=vite-generated")) return result;
  23066. OTHER_SOURCE_MAP_REGEXP.lastIndex = 0;
  23067. if (OTHER_SOURCE_MAP_REGEXP.test(code)) code = code.replace(OTHER_SOURCE_MAP_REGEXP, "");
  23068. const sourceMap = startOffset ? Object.assign({}, map, { mappings: ";".repeat(startOffset) + map.mappings }) : map;
  23069. result.code = `${code.trimEnd()}\n//# sourceURL=${mod.id}\n${MODULE_RUNNER_SOURCEMAPPING_SOURCE}\n//# ${SOURCEMAPPING_URL}=${genSourceMapUrl(sourceMap)}\n`;
  23070. return result;
  23071. }
  23072. //#endregion
  23073. //#region src/node/optimizer/optimizer.ts
  23074. const debug$9 = createDebugger("vite:deps");
  23075. /**
  23076. * The amount to wait for requests to register newly found dependencies before triggering
  23077. * a re-bundle + page reload
  23078. */
  23079. const debounceMs = 100;
  23080. function createDepsOptimizer(environment) {
  23081. const { logger } = environment;
  23082. const sessionTimestamp = Date.now().toString();
  23083. let debounceProcessingHandle;
  23084. let closed = false;
  23085. const options = environment.config.optimizeDeps;
  23086. const { noDiscovery, holdUntilCrawlEnd } = options;
  23087. let metadata = initDepsOptimizerMetadata(environment, sessionTimestamp);
  23088. const depsOptimizer = {
  23089. init,
  23090. metadata,
  23091. registerMissingImport,
  23092. run: () => debouncedProcessing(0),
  23093. isOptimizedDepFile: createIsOptimizedDepFile(environment),
  23094. isOptimizedDepUrl: createIsOptimizedDepUrl(environment),
  23095. getOptimizedDepId: (depInfo) => `${depInfo.file}?v=${depInfo.browserHash}`,
  23096. close,
  23097. options
  23098. };
  23099. let newDepsDiscovered = false;
  23100. let newDepsToLog = [];
  23101. let newDepsToLogHandle;
  23102. const logNewlyDiscoveredDeps = () => {
  23103. if (newDepsToLog.length) {
  23104. logger.info(import_picocolors.default.green(`✨ new dependencies optimized: ${depsLogString(newDepsToLog)}`), { timestamp: true });
  23105. newDepsToLog = [];
  23106. }
  23107. };
  23108. let discoveredDepsWhileScanning = [];
  23109. const logDiscoveredDepsWhileScanning = () => {
  23110. if (discoveredDepsWhileScanning.length) {
  23111. logger.info(import_picocolors.default.green(`✨ discovered while scanning: ${depsLogString(discoveredDepsWhileScanning)}`), { timestamp: true });
  23112. discoveredDepsWhileScanning = [];
  23113. }
  23114. };
  23115. let depOptimizationProcessing = promiseWithResolvers();
  23116. let depOptimizationProcessingQueue = [];
  23117. const resolveEnqueuedProcessingPromises = () => {
  23118. for (const processing of depOptimizationProcessingQueue) processing.resolve();
  23119. depOptimizationProcessingQueue = [];
  23120. };
  23121. let enqueuedRerun;
  23122. let currentlyProcessing = false;
  23123. let firstRunCalled = false;
  23124. let warnAboutMissedDependencies = false;
  23125. let waitingForCrawlEnd = false;
  23126. let optimizationResult;
  23127. let discover;
  23128. async function close() {
  23129. closed = true;
  23130. await Promise.allSettled([
  23131. discover?.cancel(),
  23132. depsOptimizer.scanProcessing,
  23133. optimizationResult?.cancel()
  23134. ]);
  23135. }
  23136. let inited = false;
  23137. async function init() {
  23138. if (inited) return;
  23139. inited = true;
  23140. const cachedMetadata = await loadCachedDepOptimizationMetadata(environment);
  23141. firstRunCalled = !!cachedMetadata;
  23142. metadata = depsOptimizer.metadata = cachedMetadata || initDepsOptimizerMetadata(environment, sessionTimestamp);
  23143. if (!cachedMetadata) {
  23144. waitingForCrawlEnd = true;
  23145. currentlyProcessing = true;
  23146. const manuallyIncludedDeps = {};
  23147. await addManuallyIncludedOptimizeDeps(environment, manuallyIncludedDeps);
  23148. const manuallyIncludedDepsInfo = toDiscoveredDependencies(environment, manuallyIncludedDeps, sessionTimestamp);
  23149. for (const depInfo of Object.values(manuallyIncludedDepsInfo)) {
  23150. addOptimizedDepInfo(metadata, "discovered", {
  23151. ...depInfo,
  23152. processing: depOptimizationProcessing.promise
  23153. });
  23154. newDepsDiscovered = true;
  23155. }
  23156. environment.waitForRequestsIdle().then(onCrawlEnd);
  23157. if (noDiscovery) runOptimizer();
  23158. else depsOptimizer.scanProcessing = new Promise((resolve) => {
  23159. (async () => {
  23160. try {
  23161. debug$9?.(import_picocolors.default.green(`scanning for dependencies...`));
  23162. const scanTimer = setTimeout(() => {
  23163. logger.info("[optimizer] scanning dependencies...", { timestamp: true });
  23164. }, 1e3);
  23165. let deps;
  23166. try {
  23167. discover = discoverProjectDependencies(devToScanEnvironment(environment));
  23168. deps = await discover.result;
  23169. discover = void 0;
  23170. } catch (e) {
  23171. environment.logger.error(import_picocolors.default.red("(!) Failed to run dependency scan. Skipping dependency pre-bundling. " + e.stack));
  23172. return;
  23173. } finally {
  23174. clearTimeout(scanTimer);
  23175. }
  23176. const manuallyIncluded = Object.keys(manuallyIncludedDepsInfo);
  23177. discoveredDepsWhileScanning.push(...Object.keys(metadata.discovered).filter((dep) => !deps[dep] && !manuallyIncluded.includes(dep)));
  23178. for (const id of Object.keys(deps)) if (!metadata.discovered[id]) addMissingDep(id, deps[id]);
  23179. const knownDeps = prepareKnownDeps();
  23180. startNextDiscoveredBatch();
  23181. optimizationResult = runOptimizeDeps(environment, knownDeps);
  23182. if (!holdUntilCrawlEnd) optimizationResult.result.then((result) => {
  23183. if (!waitingForCrawlEnd) return;
  23184. optimizationResult = void 0;
  23185. runOptimizer(result);
  23186. });
  23187. } catch (e) {
  23188. logger.error(e.stack || e.message);
  23189. } finally {
  23190. resolve();
  23191. depsOptimizer.scanProcessing = void 0;
  23192. }
  23193. })();
  23194. });
  23195. }
  23196. }
  23197. function startNextDiscoveredBatch() {
  23198. newDepsDiscovered = false;
  23199. depOptimizationProcessingQueue.push(depOptimizationProcessing);
  23200. depOptimizationProcessing = promiseWithResolvers();
  23201. }
  23202. function prepareKnownDeps() {
  23203. const knownDeps = {};
  23204. const metadata = depsOptimizer.metadata;
  23205. for (const dep of Object.keys(metadata.optimized)) knownDeps[dep] = { ...metadata.optimized[dep] };
  23206. for (const dep of Object.keys(metadata.discovered)) {
  23207. const { processing, ...info } = metadata.discovered[dep];
  23208. knownDeps[dep] = info;
  23209. }
  23210. return knownDeps;
  23211. }
  23212. async function runOptimizer(preRunResult) {
  23213. const isRerun = firstRunCalled;
  23214. firstRunCalled = true;
  23215. enqueuedRerun = void 0;
  23216. if (debounceProcessingHandle) clearTimeout(debounceProcessingHandle);
  23217. if (closed) {
  23218. currentlyProcessing = false;
  23219. depOptimizationProcessing.resolve();
  23220. resolveEnqueuedProcessingPromises();
  23221. return;
  23222. }
  23223. currentlyProcessing = true;
  23224. try {
  23225. let processingResult;
  23226. if (preRunResult) processingResult = preRunResult;
  23227. else {
  23228. const knownDeps = prepareKnownDeps();
  23229. startNextDiscoveredBatch();
  23230. optimizationResult = runOptimizeDeps(environment, knownDeps);
  23231. processingResult = await optimizationResult.result;
  23232. optimizationResult = void 0;
  23233. }
  23234. if (closed) {
  23235. currentlyProcessing = false;
  23236. processingResult.cancel();
  23237. resolveEnqueuedProcessingPromises();
  23238. return;
  23239. }
  23240. const newData = processingResult.metadata;
  23241. const needsInteropMismatch = findInteropMismatches(metadata.discovered, newData.optimized);
  23242. const needsReload = needsInteropMismatch.length > 0 || metadata.hash !== newData.hash || Object.keys(metadata.optimized).some((dep) => {
  23243. return metadata.optimized[dep].fileHash !== newData.optimized[dep].fileHash;
  23244. });
  23245. const commitProcessing = async () => {
  23246. await processingResult.commit();
  23247. for (const id in metadata.discovered) if (!newData.optimized[id]) addOptimizedDepInfo(newData, "discovered", metadata.discovered[id]);
  23248. if (!needsReload) {
  23249. newData.browserHash = metadata.browserHash;
  23250. for (const dep in newData.chunks) newData.chunks[dep].browserHash = metadata.browserHash;
  23251. for (const dep in newData.optimized) newData.optimized[dep].browserHash = (metadata.optimized[dep] || metadata.discovered[dep]).browserHash;
  23252. }
  23253. for (const o in newData.optimized) {
  23254. const discovered = metadata.discovered[o];
  23255. if (discovered) {
  23256. const optimized = newData.optimized[o];
  23257. discovered.browserHash = optimized.browserHash;
  23258. discovered.fileHash = optimized.fileHash;
  23259. discovered.needsInterop = optimized.needsInterop;
  23260. discovered.processing = void 0;
  23261. }
  23262. }
  23263. if (isRerun) newDepsToLog.push(...Object.keys(newData.optimized).filter((dep) => !metadata.optimized[dep]));
  23264. metadata = depsOptimizer.metadata = newData;
  23265. resolveEnqueuedProcessingPromises();
  23266. };
  23267. if (!needsReload) {
  23268. await commitProcessing();
  23269. if (!debug$9) {
  23270. if (newDepsToLogHandle) clearTimeout(newDepsToLogHandle);
  23271. newDepsToLogHandle = setTimeout(() => {
  23272. newDepsToLogHandle = void 0;
  23273. logNewlyDiscoveredDeps();
  23274. if (warnAboutMissedDependencies) {
  23275. logDiscoveredDepsWhileScanning();
  23276. logger.info(import_picocolors.default.magenta(`❗ add these dependencies to optimizeDeps.include to speed up cold start`), { timestamp: true });
  23277. warnAboutMissedDependencies = false;
  23278. }
  23279. }, 2 * debounceMs);
  23280. } else debug$9(import_picocolors.default.green(`✨ ${!isRerun ? `dependencies optimized` : `optimized dependencies unchanged`}`));
  23281. } else if (newDepsDiscovered) {
  23282. processingResult.cancel();
  23283. debug$9?.(import_picocolors.default.green(`✨ delaying reload as new dependencies have been found...`));
  23284. } else {
  23285. await commitProcessing();
  23286. if (!debug$9) {
  23287. if (newDepsToLogHandle) clearTimeout(newDepsToLogHandle);
  23288. newDepsToLogHandle = void 0;
  23289. logNewlyDiscoveredDeps();
  23290. if (warnAboutMissedDependencies) {
  23291. logDiscoveredDepsWhileScanning();
  23292. logger.info(import_picocolors.default.magenta(`❗ add these dependencies to optimizeDeps.include to avoid a full page reload during cold start`), { timestamp: true });
  23293. warnAboutMissedDependencies = false;
  23294. }
  23295. }
  23296. logger.info(import_picocolors.default.green(`✨ optimized dependencies changed. reloading`), { timestamp: true });
  23297. if (needsInteropMismatch.length > 0) logger.warn(`Mixed ESM and CJS detected in ${import_picocolors.default.yellow(needsInteropMismatch.join(", "))}, add ${needsInteropMismatch.length === 1 ? "it" : "them"} to optimizeDeps.needsInterop to speed up cold start`, { timestamp: true });
  23298. fullReload();
  23299. }
  23300. } catch (e) {
  23301. logger.error(import_picocolors.default.red(`error while updating dependencies:\n${e.stack}`), {
  23302. timestamp: true,
  23303. error: e
  23304. });
  23305. resolveEnqueuedProcessingPromises();
  23306. metadata.discovered = {};
  23307. }
  23308. currentlyProcessing = false;
  23309. enqueuedRerun?.();
  23310. }
  23311. function fullReload() {
  23312. environment.moduleGraph.invalidateAll();
  23313. environment.hot.send({
  23314. type: "full-reload",
  23315. path: "*"
  23316. });
  23317. }
  23318. async function rerun() {
  23319. const depsString = depsLogString(Object.keys(metadata.discovered));
  23320. debug$9?.(import_picocolors.default.green(`new dependencies found: ${depsString}`));
  23321. runOptimizer();
  23322. }
  23323. function getDiscoveredBrowserHash(hash, deps, missing) {
  23324. return getHash(hash + JSON.stringify(deps) + JSON.stringify(missing) + sessionTimestamp);
  23325. }
  23326. function registerMissingImport(id, resolved) {
  23327. const optimized = metadata.optimized[id];
  23328. if (optimized) return optimized;
  23329. const chunk = metadata.chunks[id];
  23330. if (chunk) return chunk;
  23331. let missing = metadata.discovered[id];
  23332. if (missing) return missing;
  23333. missing = addMissingDep(id, resolved);
  23334. if (!waitingForCrawlEnd) debouncedProcessing();
  23335. return missing;
  23336. }
  23337. function addMissingDep(id, resolved) {
  23338. newDepsDiscovered = true;
  23339. return addOptimizedDepInfo(metadata, "discovered", {
  23340. id,
  23341. file: getOptimizedDepPath(environment, id),
  23342. src: resolved,
  23343. browserHash: getDiscoveredBrowserHash(metadata.hash, depsFromOptimizedDepInfo(metadata.optimized), depsFromOptimizedDepInfo(metadata.discovered)),
  23344. processing: depOptimizationProcessing.promise,
  23345. exportsData: extractExportsData(environment, resolved)
  23346. });
  23347. }
  23348. function debouncedProcessing(timeout = debounceMs) {
  23349. enqueuedRerun = void 0;
  23350. if (debounceProcessingHandle) clearTimeout(debounceProcessingHandle);
  23351. if (newDepsToLogHandle) clearTimeout(newDepsToLogHandle);
  23352. newDepsToLogHandle = void 0;
  23353. debounceProcessingHandle = setTimeout(() => {
  23354. debounceProcessingHandle = void 0;
  23355. enqueuedRerun = rerun;
  23356. if (!currentlyProcessing) enqueuedRerun();
  23357. }, timeout);
  23358. }
  23359. async function onCrawlEnd() {
  23360. waitingForCrawlEnd = false;
  23361. debug$9?.(import_picocolors.default.green(`✨ static imports crawl ended`));
  23362. if (closed) return;
  23363. await depsOptimizer.scanProcessing;
  23364. if (optimizationResult && !options.noDiscovery) {
  23365. const afterScanResult = optimizationResult.result;
  23366. optimizationResult = void 0;
  23367. const result = await afterScanResult;
  23368. currentlyProcessing = false;
  23369. const crawlDeps = Object.keys(metadata.discovered);
  23370. const scanDeps = Object.keys(result.metadata.optimized);
  23371. if (scanDeps.length === 0 && crawlDeps.length === 0) {
  23372. debug$9?.(import_picocolors.default.green(`✨ no dependencies found by the scanner or crawling static imports`));
  23373. startNextDiscoveredBatch();
  23374. runOptimizer(result);
  23375. return;
  23376. }
  23377. const needsInteropMismatch = findInteropMismatches(metadata.discovered, result.metadata.optimized);
  23378. const scannerMissedDeps = crawlDeps.some((dep) => !scanDeps.includes(dep));
  23379. if (needsInteropMismatch.length > 0 || scannerMissedDeps) {
  23380. result.cancel();
  23381. for (const dep of scanDeps) if (!crawlDeps.includes(dep)) addMissingDep(dep, result.metadata.optimized[dep].src);
  23382. if (scannerMissedDeps) debug$9?.(import_picocolors.default.yellow(`✨ new dependencies were found while crawling that weren't detected by the scanner`));
  23383. debug$9?.(import_picocolors.default.green(`✨ re-running optimizer`));
  23384. debouncedProcessing(0);
  23385. } else {
  23386. debug$9?.(import_picocolors.default.green(`✨ using post-scan optimizer result, the scanner found every used dependency`));
  23387. startNextDiscoveredBatch();
  23388. runOptimizer(result);
  23389. }
  23390. } else if (!holdUntilCrawlEnd) {
  23391. if (newDepsDiscovered) {
  23392. debug$9?.(import_picocolors.default.green(`✨ new dependencies were found while crawling static imports, re-running optimizer`));
  23393. warnAboutMissedDependencies = true;
  23394. debouncedProcessing(0);
  23395. }
  23396. } else {
  23397. const crawlDeps = Object.keys(metadata.discovered);
  23398. currentlyProcessing = false;
  23399. if (crawlDeps.length === 0) {
  23400. debug$9?.(import_picocolors.default.green(`✨ no dependencies found while crawling the static imports`));
  23401. firstRunCalled = true;
  23402. }
  23403. debouncedProcessing(0);
  23404. }
  23405. }
  23406. return depsOptimizer;
  23407. }
  23408. function createExplicitDepsOptimizer(environment) {
  23409. const depsOptimizer = {
  23410. metadata: initDepsOptimizerMetadata(environment),
  23411. isOptimizedDepFile: createIsOptimizedDepFile(environment),
  23412. isOptimizedDepUrl: createIsOptimizedDepUrl(environment),
  23413. getOptimizedDepId: (depInfo) => `${depInfo.file}?v=${depInfo.browserHash}`,
  23414. registerMissingImport: () => {
  23415. throw new Error(`Vite Internal Error: registerMissingImport is not supported in dev ${environment.name}`);
  23416. },
  23417. init,
  23418. run: () => {},
  23419. close: async () => {},
  23420. options: environment.config.optimizeDeps
  23421. };
  23422. let inited = false;
  23423. async function init() {
  23424. if (inited) return;
  23425. inited = true;
  23426. depsOptimizer.metadata = await optimizeExplicitEnvironmentDeps(environment);
  23427. }
  23428. return depsOptimizer;
  23429. }
  23430. function findInteropMismatches(discovered, optimized) {
  23431. const needsInteropMismatch = [];
  23432. for (const dep in discovered) {
  23433. const discoveredDepInfo = discovered[dep];
  23434. if (discoveredDepInfo.needsInterop === void 0) continue;
  23435. const depInfo = optimized[dep];
  23436. if (!depInfo) continue;
  23437. if (depInfo.needsInterop !== discoveredDepInfo.needsInterop) {
  23438. needsInteropMismatch.push(dep);
  23439. debug$9?.(import_picocolors.default.cyan(`✨ needsInterop mismatch detected for ${dep}`));
  23440. }
  23441. }
  23442. return needsInteropMismatch;
  23443. }
  23444. //#endregion
  23445. //#region src/node/server/moduleGraph.ts
  23446. var EnvironmentModuleNode = class {
  23447. environment;
  23448. /**
  23449. * Public served url path, starts with /
  23450. */
  23451. url;
  23452. /**
  23453. * Resolved file system path + query
  23454. */
  23455. id = null;
  23456. file = null;
  23457. type;
  23458. info;
  23459. meta;
  23460. importers = /* @__PURE__ */ new Set();
  23461. importedModules = /* @__PURE__ */ new Set();
  23462. acceptedHmrDeps = /* @__PURE__ */ new Set();
  23463. acceptedHmrExports = null;
  23464. importedBindings = null;
  23465. isSelfAccepting;
  23466. transformResult = null;
  23467. ssrModule = null;
  23468. ssrError = null;
  23469. lastHMRTimestamp = 0;
  23470. /**
  23471. * `import.meta.hot.invalidate` is called by the client.
  23472. * If there's multiple clients, multiple `invalidate` request is received.
  23473. * This property is used to dedupe those request to avoid multiple updates happening.
  23474. * @internal
  23475. */
  23476. lastHMRInvalidationReceived = false;
  23477. lastInvalidationTimestamp = 0;
  23478. /**
  23479. * If the module only needs to update its imports timestamp (e.g. within an HMR chain),
  23480. * it is considered soft-invalidated. In this state, its `transformResult` should exist,
  23481. * and the next `transformRequest` for this module will replace the timestamps.
  23482. *
  23483. * By default the value is `undefined` if it's not soft/hard-invalidated. If it gets
  23484. * soft-invalidated, this will contain the previous `transformResult` value. If it gets
  23485. * hard-invalidated, this will be set to `'HARD_INVALIDATED'`.
  23486. * @internal
  23487. */
  23488. invalidationState;
  23489. /**
  23490. * The module urls that are statically imported in the code. This information is separated
  23491. * out from `importedModules` as only importers that statically import the module can be
  23492. * soft invalidated. Other imports (e.g. watched files) needs the importer to be hard invalidated.
  23493. * @internal
  23494. */
  23495. staticImportedUrls;
  23496. /**
  23497. * @param setIsSelfAccepting - set `false` to set `isSelfAccepting` later. e.g. #7870
  23498. */
  23499. constructor(url, environment, setIsSelfAccepting = true) {
  23500. this.environment = environment;
  23501. this.url = url;
  23502. this.type = isDirectCSSRequest(url) ? "css" : "js";
  23503. if (setIsSelfAccepting) this.isSelfAccepting = false;
  23504. }
  23505. };
  23506. var EnvironmentModuleGraph = class {
  23507. environment;
  23508. urlToModuleMap = /* @__PURE__ */ new Map();
  23509. idToModuleMap = /* @__PURE__ */ new Map();
  23510. etagToModuleMap = /* @__PURE__ */ new Map();
  23511. fileToModulesMap = /* @__PURE__ */ new Map();
  23512. /**
  23513. * @internal
  23514. */
  23515. _unresolvedUrlToModuleMap = /* @__PURE__ */ new Map();
  23516. /**
  23517. * @internal
  23518. */
  23519. _resolveId;
  23520. /** @internal */
  23521. _hasResolveFailedErrorModules = /* @__PURE__ */ new Set();
  23522. constructor(environment, resolveId) {
  23523. this.environment = environment;
  23524. this._resolveId = resolveId;
  23525. }
  23526. async getModuleByUrl(rawUrl) {
  23527. rawUrl = removeImportQuery(removeTimestampQuery(rawUrl));
  23528. const mod = this._getUnresolvedUrlToModule(rawUrl);
  23529. if (mod) return mod;
  23530. const [url] = await this._resolveUrl(rawUrl);
  23531. return this.urlToModuleMap.get(url);
  23532. }
  23533. getModuleById(id) {
  23534. return this.idToModuleMap.get(removeTimestampQuery(id));
  23535. }
  23536. getModulesByFile(file) {
  23537. return this.fileToModulesMap.get(file);
  23538. }
  23539. onFileChange(file) {
  23540. const mods = this.getModulesByFile(file);
  23541. if (mods) {
  23542. const seen = /* @__PURE__ */ new Set();
  23543. mods.forEach((mod) => {
  23544. this.invalidateModule(mod, seen);
  23545. });
  23546. }
  23547. }
  23548. onFileDelete(file) {
  23549. const mods = this.getModulesByFile(file);
  23550. if (mods) mods.forEach((mod) => {
  23551. mod.importedModules.forEach((importedMod) => {
  23552. importedMod.importers.delete(mod);
  23553. });
  23554. });
  23555. }
  23556. invalidateModule(mod, seen = /* @__PURE__ */ new Set(), timestamp = monotonicDateNow(), isHmr = false, softInvalidate = false) {
  23557. const prevInvalidationState = mod.invalidationState;
  23558. if (softInvalidate) mod.invalidationState ??= mod.transformResult ?? "HARD_INVALIDATED";
  23559. else mod.invalidationState = "HARD_INVALIDATED";
  23560. if (seen.has(mod) && prevInvalidationState === mod.invalidationState) return;
  23561. seen.add(mod);
  23562. if (isHmr) {
  23563. mod.lastHMRTimestamp = timestamp;
  23564. mod.lastHMRInvalidationReceived = false;
  23565. } else mod.lastInvalidationTimestamp = timestamp;
  23566. const etag = mod.transformResult?.etag;
  23567. if (etag) this.etagToModuleMap.delete(etag);
  23568. mod.transformResult = null;
  23569. mod.ssrModule = null;
  23570. mod.ssrError = null;
  23571. mod.importers.forEach((importer) => {
  23572. if (!importer.acceptedHmrDeps.has(mod)) {
  23573. const shouldSoftInvalidateImporter = (importer.staticImportedUrls?.has(mod.url) || softInvalidate) && importer.type === "js";
  23574. this.invalidateModule(importer, seen, timestamp, isHmr, shouldSoftInvalidateImporter);
  23575. }
  23576. });
  23577. this._hasResolveFailedErrorModules.delete(mod);
  23578. }
  23579. invalidateAll() {
  23580. const timestamp = monotonicDateNow();
  23581. const seen = /* @__PURE__ */ new Set();
  23582. this.idToModuleMap.forEach((mod) => {
  23583. this.invalidateModule(mod, seen, timestamp);
  23584. });
  23585. }
  23586. /**
  23587. * Update the module graph based on a module's updated imports information
  23588. * If there are dependencies that no longer have any importers, they are
  23589. * returned as a Set.
  23590. *
  23591. * @param staticImportedUrls Subset of `importedModules` where they're statically imported in code.
  23592. * This is only used for soft invalidations so `undefined` is fine but may cause more runtime processing.
  23593. */
  23594. async updateModuleInfo(mod, importedModules, importedBindings, acceptedModules, acceptedExports, isSelfAccepting, staticImportedUrls) {
  23595. mod.isSelfAccepting = isSelfAccepting;
  23596. const prevImports = mod.importedModules;
  23597. let noLongerImported;
  23598. let resolvePromises = [];
  23599. let resolveResults = new Array(importedModules.size);
  23600. let index = 0;
  23601. for (const imported of importedModules) {
  23602. const nextIndex = index++;
  23603. if (typeof imported === "string") resolvePromises.push(this.ensureEntryFromUrl(imported).then((dep) => {
  23604. dep.importers.add(mod);
  23605. resolveResults[nextIndex] = dep;
  23606. }));
  23607. else {
  23608. imported.importers.add(mod);
  23609. resolveResults[nextIndex] = imported;
  23610. }
  23611. }
  23612. if (resolvePromises.length) await Promise.all(resolvePromises);
  23613. mod.importedModules = new Set(resolveResults);
  23614. prevImports.forEach((dep) => {
  23615. if (!mod.importedModules.has(dep)) {
  23616. dep.importers.delete(mod);
  23617. if (!dep.importers.size) (noLongerImported || (noLongerImported = /* @__PURE__ */ new Set())).add(dep);
  23618. }
  23619. });
  23620. resolvePromises = [];
  23621. resolveResults = new Array(acceptedModules.size);
  23622. index = 0;
  23623. for (const accepted of acceptedModules) {
  23624. const nextIndex = index++;
  23625. if (typeof accepted === "string") resolvePromises.push(this.ensureEntryFromUrl(accepted).then((dep) => {
  23626. resolveResults[nextIndex] = dep;
  23627. }));
  23628. else resolveResults[nextIndex] = accepted;
  23629. }
  23630. if (resolvePromises.length) await Promise.all(resolvePromises);
  23631. mod.acceptedHmrDeps = new Set(resolveResults);
  23632. mod.staticImportedUrls = staticImportedUrls;
  23633. mod.acceptedHmrExports = acceptedExports;
  23634. mod.importedBindings = importedBindings;
  23635. return noLongerImported;
  23636. }
  23637. async ensureEntryFromUrl(rawUrl, setIsSelfAccepting = true) {
  23638. return this._ensureEntryFromUrl(rawUrl, setIsSelfAccepting);
  23639. }
  23640. /**
  23641. * @internal
  23642. */
  23643. async _ensureEntryFromUrl(rawUrl, setIsSelfAccepting = true, resolved) {
  23644. rawUrl = removeImportQuery(removeTimestampQuery(rawUrl));
  23645. let mod = this._getUnresolvedUrlToModule(rawUrl);
  23646. if (mod) return mod;
  23647. const modPromise = (async () => {
  23648. const [url, resolvedId, meta] = await this._resolveUrl(rawUrl, resolved);
  23649. mod = this.idToModuleMap.get(resolvedId);
  23650. if (!mod) {
  23651. mod = new EnvironmentModuleNode(url, this.environment, setIsSelfAccepting);
  23652. if (meta) mod.meta = meta;
  23653. this.urlToModuleMap.set(url, mod);
  23654. mod.id = resolvedId;
  23655. this.idToModuleMap.set(resolvedId, mod);
  23656. const file = mod.file = cleanUrl(resolvedId);
  23657. let fileMappedModules = this.fileToModulesMap.get(file);
  23658. if (!fileMappedModules) {
  23659. fileMappedModules = /* @__PURE__ */ new Set();
  23660. this.fileToModulesMap.set(file, fileMappedModules);
  23661. }
  23662. fileMappedModules.add(mod);
  23663. } else if (!this.urlToModuleMap.has(url)) this.urlToModuleMap.set(url, mod);
  23664. this._setUnresolvedUrlToModule(rawUrl, mod);
  23665. return mod;
  23666. })();
  23667. this._setUnresolvedUrlToModule(rawUrl, modPromise);
  23668. return modPromise;
  23669. }
  23670. createFileOnlyEntry(file) {
  23671. file = normalizePath(file);
  23672. let fileMappedModules = this.fileToModulesMap.get(file);
  23673. if (!fileMappedModules) {
  23674. fileMappedModules = /* @__PURE__ */ new Set();
  23675. this.fileToModulesMap.set(file, fileMappedModules);
  23676. }
  23677. const url = `${FS_PREFIX}${file}`;
  23678. for (const m of fileMappedModules) if ((m.url === url || m.id === file) && m.type === "asset") return m;
  23679. const mod = new EnvironmentModuleNode(url, this.environment);
  23680. mod.type = "asset";
  23681. mod.file = file;
  23682. fileMappedModules.add(mod);
  23683. return mod;
  23684. }
  23685. async resolveUrl(url) {
  23686. url = removeImportQuery(removeTimestampQuery(url));
  23687. const mod = await this._getUnresolvedUrlToModule(url);
  23688. if (mod?.id) return [
  23689. mod.url,
  23690. mod.id,
  23691. mod.meta
  23692. ];
  23693. return this._resolveUrl(url);
  23694. }
  23695. updateModuleTransformResult(mod, result) {
  23696. if (this.environment === "client") {
  23697. const prevEtag = mod.transformResult?.etag;
  23698. if (prevEtag) this.etagToModuleMap.delete(prevEtag);
  23699. if (result?.etag) this.etagToModuleMap.set(result.etag, mod);
  23700. }
  23701. mod.transformResult = result;
  23702. }
  23703. getModuleByEtag(etag) {
  23704. return this.etagToModuleMap.get(etag);
  23705. }
  23706. /**
  23707. * @internal
  23708. */
  23709. _getUnresolvedUrlToModule(url) {
  23710. return this._unresolvedUrlToModuleMap.get(url);
  23711. }
  23712. /**
  23713. * @internal
  23714. */
  23715. _setUnresolvedUrlToModule(url, mod) {
  23716. this._unresolvedUrlToModuleMap.set(url, mod);
  23717. }
  23718. /**
  23719. * @internal
  23720. */
  23721. async _resolveUrl(url, alreadyResolved) {
  23722. const resolved = alreadyResolved ?? await this._resolveId(url);
  23723. const resolvedId = resolved?.id || url;
  23724. if (url !== resolvedId && !url.includes("\0") && !url.startsWith(`virtual:`)) {
  23725. const ext = extname(cleanUrl(resolvedId));
  23726. if (ext) {
  23727. const pathname = cleanUrl(url);
  23728. if (!pathname.endsWith(ext)) url = pathname + ext + url.slice(pathname.length);
  23729. }
  23730. }
  23731. return [
  23732. url,
  23733. resolvedId,
  23734. resolved?.meta
  23735. ];
  23736. }
  23737. };
  23738. //#endregion
  23739. //#region ../../node_modules/.pnpm/totalist@3.0.1/node_modules/totalist/sync/index.mjs
  23740. function totalist(dir, callback, pre = "") {
  23741. dir = resolve$1(".", dir);
  23742. let arr = readdirSync(dir);
  23743. let i = 0, abs, stats;
  23744. for (; i < arr.length; i++) {
  23745. abs = join$1(dir, arr[i]);
  23746. stats = statSync(abs);
  23747. stats.isDirectory() ? totalist(abs, callback, join$1(pre, arr[i])) : callback(join$1(pre, arr[i]), abs, stats);
  23748. }
  23749. }
  23750. //#endregion
  23751. //#region ../../node_modules/.pnpm/@polka+url@1.0.0-next.29/node_modules/@polka/url/build.mjs
  23752. /**
  23753. * @typedef ParsedURL
  23754. * @type {import('.').ParsedURL}
  23755. */
  23756. /**
  23757. * @typedef Request
  23758. * @property {string} url
  23759. * @property {ParsedURL} _parsedUrl
  23760. */
  23761. /**
  23762. * @param {Request} req
  23763. * @returns {ParsedURL|void}
  23764. */
  23765. function parse$1(req) {
  23766. let raw = req.url;
  23767. if (raw == null) return;
  23768. let prev = req._parsedUrl;
  23769. if (prev && prev.raw === raw) return prev;
  23770. let pathname = raw, search = "", query, hash;
  23771. if (raw.length > 1) {
  23772. let idx = raw.indexOf("#", 1);
  23773. if (idx !== -1) {
  23774. hash = raw.substring(idx);
  23775. pathname = raw.substring(0, idx);
  23776. }
  23777. idx = pathname.indexOf("?", 1);
  23778. if (idx !== -1) {
  23779. search = pathname.substring(idx);
  23780. pathname = pathname.substring(0, idx);
  23781. if (search.length > 1) query = qs.parse(search.substring(1));
  23782. }
  23783. }
  23784. return req._parsedUrl = {
  23785. pathname,
  23786. search,
  23787. query,
  23788. hash,
  23789. raw
  23790. };
  23791. }
  23792. //#endregion
  23793. //#region ../../node_modules/.pnpm/sirv@3.0.2_patch_hash=c07c56eb72faea34341d465cde2314e89db472106ed378181e3447893af6bf95/node_modules/sirv/build.mjs
  23794. const noop = () => {};
  23795. function isMatch(uri, arr) {
  23796. for (let i = 0; i < arr.length; i++) if (arr[i].test(uri)) return true;
  23797. }
  23798. function toAssume(uri, extns) {
  23799. let i = 0, x, len = uri.length - 1;
  23800. if (uri.charCodeAt(len) === 47) uri = uri.substring(0, len);
  23801. let arr = [], tmp = `${uri}/index`;
  23802. for (; i < extns.length; i++) {
  23803. x = extns[i] ? `.${extns[i]}` : "";
  23804. if (uri) arr.push(uri + x);
  23805. arr.push(tmp + x);
  23806. }
  23807. return arr;
  23808. }
  23809. function viaCache(cache, uri, extns) {
  23810. let i = 0, data, arr = toAssume(uri, extns);
  23811. for (; i < arr.length; i++) if (data = cache[arr[i]]) return data;
  23812. }
  23813. function viaLocal(dir, isEtag, uri, extns, shouldServe) {
  23814. let i = 0, arr = toAssume(uri, extns);
  23815. let abs, stats, name, headers;
  23816. for (; i < arr.length; i++) {
  23817. abs = normalize(join(dir, name = arr[i]));
  23818. if (abs.startsWith(dir) && fs$1.existsSync(abs)) {
  23819. stats = fs$1.statSync(abs);
  23820. if (stats.isDirectory()) continue;
  23821. if (shouldServe && !shouldServe(abs)) continue;
  23822. headers = toHeaders(name, stats, isEtag);
  23823. headers["Cache-Control"] = isEtag ? "no-cache" : "no-store";
  23824. return {
  23825. abs,
  23826. stats,
  23827. headers
  23828. };
  23829. }
  23830. }
  23831. }
  23832. function is404(req, res) {
  23833. return res.statusCode = 404, res.end();
  23834. }
  23835. function send$1(req, res, file, stats, headers) {
  23836. let code = 200, tmp, opts = {};
  23837. headers = { ...headers };
  23838. for (let key in headers) {
  23839. tmp = res.getHeader(key);
  23840. if (tmp) headers[key] = tmp;
  23841. }
  23842. if (tmp = res.getHeader("content-type")) headers["Content-Type"] = tmp;
  23843. if (req.headers.range) {
  23844. code = 206;
  23845. let [x, y] = req.headers.range.replace("bytes=", "").split("-");
  23846. let end = opts.end = parseInt(y, 10) || stats.size - 1;
  23847. let start = opts.start = parseInt(x, 10) || 0;
  23848. if (end >= stats.size) end = stats.size - 1;
  23849. if (start >= stats.size) {
  23850. res.setHeader("Content-Range", `bytes */${stats.size}`);
  23851. res.statusCode = 416;
  23852. return res.end();
  23853. }
  23854. headers["Content-Range"] = `bytes ${start}-${end}/${stats.size}`;
  23855. headers["Content-Length"] = end - start + 1;
  23856. headers["Accept-Ranges"] = "bytes";
  23857. }
  23858. res.writeHead(code, headers);
  23859. fs$1.createReadStream(file, opts).pipe(res);
  23860. }
  23861. const ENCODING = {
  23862. ".br": "br",
  23863. ".gz": "gzip"
  23864. };
  23865. function toHeaders(name, stats, isEtag) {
  23866. let enc = ENCODING[name.slice(-3)];
  23867. let ctype = lookup(name.slice(0, enc && -3)) || "";
  23868. if (ctype === "text/html") ctype += ";charset=utf-8";
  23869. let headers = {
  23870. "Content-Length": stats.size,
  23871. "Content-Type": ctype,
  23872. "Last-Modified": stats.mtime.toUTCString()
  23873. };
  23874. if (enc) headers["Content-Encoding"] = enc;
  23875. if (isEtag) headers["ETag"] = `W/"${stats.size}-${stats.mtime.getTime()}"`;
  23876. return headers;
  23877. }
  23878. function build_default$1(dir, opts = {}) {
  23879. dir = resolve(dir || ".");
  23880. let isNotFound = opts.onNoMatch || is404;
  23881. let setHeaders = opts.setHeaders || noop;
  23882. let extensions = opts.extensions || ["html", "htm"];
  23883. let gzips = opts.gzip && extensions.map((x) => `${x}.gz`).concat("gz");
  23884. let brots = opts.brotli && extensions.map((x) => `${x}.br`).concat("br");
  23885. const FILES = {};
  23886. let fallback = "/";
  23887. let isEtag = !!opts.etag;
  23888. let isSPA = !!opts.single;
  23889. if (typeof opts.single === "string") {
  23890. let idx = opts.single.lastIndexOf(".");
  23891. fallback += !!~idx ? opts.single.substring(0, idx) : opts.single;
  23892. }
  23893. let ignores = [];
  23894. if (opts.ignores !== false) {
  23895. ignores.push(/[/]([A-Za-z\s\d~$._-]+\.\w+){1,}$/);
  23896. if (opts.dotfiles) ignores.push(/\/\.\w/);
  23897. else ignores.push(/\/\.well-known/);
  23898. [].concat(opts.ignores || []).forEach((x) => {
  23899. ignores.push(new RegExp(x, "i"));
  23900. });
  23901. }
  23902. let cc = opts.maxAge != null && `public,max-age=${opts.maxAge}`;
  23903. if (cc && opts.immutable) cc += ",immutable";
  23904. else if (cc && opts.maxAge === 0) cc += ",must-revalidate";
  23905. if (!opts.dev) totalist(dir, (name, abs, stats) => {
  23906. if (/\.well-known[\\+\/]/.test(name)) {} else if (!opts.dotfiles && /(^\.|[\\+|\/+]\.)/.test(name)) return;
  23907. let headers = toHeaders(name, stats, isEtag);
  23908. if (cc) headers["Cache-Control"] = cc;
  23909. FILES["/" + name.normalize().replace(/\\+/g, "/")] = {
  23910. abs,
  23911. stats,
  23912. headers
  23913. };
  23914. });
  23915. let lookup = opts.dev ? viaLocal.bind(0, dir.endsWith(sep) ? dir : dir + sep, isEtag) : viaCache.bind(0, FILES);
  23916. return function(req, res, next) {
  23917. let extns = [""];
  23918. let pathname = parse$1(req).pathname;
  23919. let val = req.headers["accept-encoding"] || "";
  23920. if (gzips && val.includes("gzip")) extns.unshift(...gzips);
  23921. if (brots && /(br|brotli)/i.test(val)) extns.unshift(...brots);
  23922. extns.push(...extensions);
  23923. if (pathname.indexOf("%") !== -1) try {
  23924. pathname = decodeURI(pathname);
  23925. } catch (err) {}
  23926. let data = lookup(pathname, extns, opts.shouldServe) || isSPA && !isMatch(pathname, ignores) && lookup(fallback, extns, opts.shouldServe);
  23927. if (!data) return next ? next() : isNotFound(req, res);
  23928. if (isEtag && req.headers["if-none-match"] === data.headers["ETag"]) {
  23929. res.writeHead(304);
  23930. return res.end();
  23931. }
  23932. if (gzips || brots) res.setHeader("Vary", "Accept-Encoding");
  23933. setHeaders(res, pathname, data.stats);
  23934. send$1(req, res, data.abs, data.stats, data.headers);
  23935. };
  23936. }
  23937. //#endregion
  23938. //#region src/node/server/middlewares/static.ts
  23939. const knownJavascriptExtensionRE = /\.(?:[tj]sx?|[cm][tj]s)$/;
  23940. const ERR_DENIED_FILE = "ERR_DENIED_FILE";
  23941. const sirvOptions = ({ config, getHeaders, disableFsServeCheck }) => {
  23942. return {
  23943. dev: true,
  23944. etag: true,
  23945. extensions: [],
  23946. setHeaders(res, pathname) {
  23947. if (knownJavascriptExtensionRE.test(pathname)) res.setHeader("Content-Type", "text/javascript");
  23948. const headers = getHeaders();
  23949. if (headers) for (const name in headers) res.setHeader(name, headers[name]);
  23950. },
  23951. shouldServe: disableFsServeCheck ? void 0 : (filePath) => {
  23952. const servingAccessResult = checkLoadingAccess(config, filePath);
  23953. if (servingAccessResult === "denied") {
  23954. const error = /* @__PURE__ */ new Error("denied access");
  23955. error.code = ERR_DENIED_FILE;
  23956. error.path = filePath;
  23957. throw error;
  23958. }
  23959. if (servingAccessResult === "fallback") return false;
  23960. return true;
  23961. }
  23962. };
  23963. };
  23964. function servePublicMiddleware(server, publicFiles) {
  23965. const dir = server.config.publicDir;
  23966. const serve = build_default$1(dir, sirvOptions({
  23967. config: server.config,
  23968. getHeaders: () => server.config.server.headers,
  23969. disableFsServeCheck: true
  23970. }));
  23971. const toFilePath = (url) => {
  23972. let filePath = cleanUrl(url);
  23973. if (filePath.indexOf("%") !== -1) try {
  23974. filePath = decodeURI(filePath);
  23975. } catch {}
  23976. return normalizePath(filePath);
  23977. };
  23978. return function viteServePublicMiddleware(req, res, next) {
  23979. if (publicFiles && !publicFiles.has(toFilePath(req.url)) || isImportRequest(req.url) || isInternalRequest(req.url) || urlRE$1.test(req.url)) return next();
  23980. serve(req, res, next);
  23981. };
  23982. }
  23983. function serveStaticMiddleware(server) {
  23984. const dir = server.config.root;
  23985. const serve = build_default$1(dir, sirvOptions({
  23986. config: server.config,
  23987. getHeaders: () => server.config.server.headers
  23988. }));
  23989. return function viteServeStaticMiddleware(req, res, next) {
  23990. const cleanedUrl = cleanUrl(req.url);
  23991. if (cleanedUrl.endsWith("/") || path.extname(cleanedUrl) === ".html" || isInternalRequest(req.url) || req.url?.startsWith("//")) return next();
  23992. const url = new URL(req.url, "http://example.com");
  23993. const pathname = decodeURIIfPossible(url.pathname);
  23994. if (pathname === void 0) return next();
  23995. let redirectedPathname;
  23996. for (const { find, replacement } of server.config.resolve.alias) if (typeof find === "string" ? pathname.startsWith(find) : find.test(pathname)) {
  23997. redirectedPathname = pathname.replace(find, replacement);
  23998. break;
  23999. }
  24000. if (redirectedPathname) {
  24001. if (redirectedPathname.startsWith(withTrailingSlash(dir))) redirectedPathname = redirectedPathname.slice(dir.length);
  24002. }
  24003. const resolvedPathname = redirectedPathname || pathname;
  24004. let fileUrl = path.resolve(dir, removeLeadingSlash(resolvedPathname));
  24005. if (resolvedPathname.endsWith("/") && fileUrl[fileUrl.length - 1] !== "/") fileUrl = withTrailingSlash(fileUrl);
  24006. if (redirectedPathname) {
  24007. url.pathname = encodeURI(redirectedPathname);
  24008. req.url = url.href.slice(url.origin.length);
  24009. }
  24010. try {
  24011. serve(req, res, next);
  24012. } catch (e) {
  24013. if (e && "code" in e && e.code === ERR_DENIED_FILE) {
  24014. respondWithAccessDenied(e.path, server, res);
  24015. return;
  24016. }
  24017. throw e;
  24018. }
  24019. };
  24020. }
  24021. function serveRawFsMiddleware(server) {
  24022. const serveFromRoot = build_default$1("/", sirvOptions({
  24023. config: server.config,
  24024. getHeaders: () => server.config.server.headers
  24025. }));
  24026. return function viteServeRawFsMiddleware(req, res, next) {
  24027. if (req.url.startsWith(FS_PREFIX)) {
  24028. const url = new URL(req.url, "http://example.com");
  24029. const pathname = decodeURIIfPossible(url.pathname);
  24030. if (pathname === void 0) return next();
  24031. let newPathname = pathname.slice(FS_PREFIX.length);
  24032. if (isWindows) newPathname = newPathname.replace(/^[A-Z]:/i, "");
  24033. url.pathname = encodeURI(newPathname);
  24034. req.url = url.href.slice(url.origin.length);
  24035. try {
  24036. serveFromRoot(req, res, next);
  24037. } catch (e) {
  24038. if (e && "code" in e && e.code === ERR_DENIED_FILE) {
  24039. respondWithAccessDenied(e.path, server, res);
  24040. return;
  24041. }
  24042. throw e;
  24043. }
  24044. } else next();
  24045. };
  24046. }
  24047. function isFileServingAllowed(configOrUrl, urlOrServer) {
  24048. const config = typeof urlOrServer === "string" ? configOrUrl : urlOrServer.config;
  24049. const url = typeof urlOrServer === "string" ? urlOrServer : configOrUrl;
  24050. if (!config.server.fs.strict) return true;
  24051. return isFileLoadingAllowed(config, fsPathFromUrl(url));
  24052. }
  24053. /**
  24054. * Warning: parameters are not validated, only works with normalized absolute paths
  24055. *
  24056. * @param targetPath - normalized absolute path
  24057. * @param filePath - normalized absolute path
  24058. */
  24059. function isFileInTargetPath(targetPath, filePath) {
  24060. return isSameFilePath(targetPath, filePath) || isParentDirectory(targetPath, filePath);
  24061. }
  24062. /**
  24063. * Warning: parameters are not validated, only works with normalized absolute paths
  24064. */
  24065. function isFileLoadingAllowed(config, filePath) {
  24066. const { fs } = config.server;
  24067. if (!fs.strict) return true;
  24068. const filePathWithoutTrailingSlash = filePath.endsWith("/") ? filePath.slice(0, -1) : filePath;
  24069. if (config.fsDenyGlob(filePathWithoutTrailingSlash)) return false;
  24070. if (config.safeModulePaths.has(filePath)) return true;
  24071. if (fs.allow.some((uri) => isFileInTargetPath(uri, filePath))) return true;
  24072. return false;
  24073. }
  24074. function checkLoadingAccess(config, path) {
  24075. if (isFileLoadingAllowed(config, slash(path))) return "allowed";
  24076. if (isFileReadable(path)) return "denied";
  24077. return "fallback";
  24078. }
  24079. function respondWithAccessDenied(id, server, res) {
  24080. const urlMessage = `The request id "${id}" is outside of Vite serving allow list.`;
  24081. const hintMessage = `
  24082. ${server.config.server.fs.allow.map((i) => `- ${i}`).join("\n")}
  24083. Refer to docs https://vite.dev/config/server-options.html#server-fs-allow for configurations and more details.`;
  24084. server.config.logger.error(urlMessage);
  24085. server.config.logger.warnOnce(hintMessage + "\n");
  24086. res.statusCode = 403;
  24087. res.write(renderRestrictedErrorHTML(urlMessage + "\n" + hintMessage));
  24088. res.end();
  24089. }
  24090. function renderRestrictedErrorHTML(msg) {
  24091. return String.raw`
  24092. <body>
  24093. <h1>403 Restricted</h1>
  24094. <p>${(0, import_escape_html.default)(msg).replace(/\n/g, "<br/>")}</p>
  24095. <style>
  24096. body {
  24097. padding: 1em 2em;
  24098. }
  24099. </style>
  24100. </body>
  24101. `;
  24102. }
  24103. //#endregion
  24104. //#region src/node/server/send.ts
  24105. var import_etag = /* @__PURE__ */ __toESM(require_etag(), 1);
  24106. const debug$8 = createDebugger("vite:send", { onlyWhenFocused: true });
  24107. const alias = {
  24108. js: "text/javascript",
  24109. css: "text/css",
  24110. html: "text/html",
  24111. json: "application/json"
  24112. };
  24113. function send(req, res, content, type, options) {
  24114. const { etag = (0, import_etag.default)(content, { weak: true }), cacheControl = "no-cache", headers, map } = options;
  24115. if (res.writableEnded) return;
  24116. if (req.headers["if-none-match"] === etag) {
  24117. res.statusCode = 304;
  24118. res.end();
  24119. return;
  24120. }
  24121. res.setHeader("Content-Type", alias[type] || type);
  24122. res.setHeader("Cache-Control", cacheControl);
  24123. res.setHeader("Etag", etag);
  24124. if (headers) for (const name in headers) res.setHeader(name, headers[name]);
  24125. if (map && "version" in map && map.mappings) {
  24126. if (type === "js" || type === "css") content = getCodeWithSourcemap(type, content.toString(), map);
  24127. } else if (type === "js" && (!map || map.mappings !== "")) {
  24128. const code = content.toString();
  24129. if (import_convert_source_map.default.mapFileCommentRegex.test(code)) debug$8?.(`Skipped injecting fallback sourcemap for ${req.url}`);
  24130. else {
  24131. const urlWithoutTimestamp = removeTimestampQuery(req.url);
  24132. content = getCodeWithSourcemap(type, code, new MagicString(code).generateMap({
  24133. source: path.basename(urlWithoutTimestamp),
  24134. hires: "boundary",
  24135. includeContent: true
  24136. }));
  24137. }
  24138. }
  24139. res.statusCode = 200;
  24140. if (req.method === "HEAD") res.end();
  24141. else res.end(content);
  24142. }
  24143. //#endregion
  24144. //#region src/node/server/middlewares/transform.ts
  24145. const debugCache$1 = createDebugger("vite:cache");
  24146. const knownIgnoreList = new Set(["/", "/favicon.ico"]);
  24147. const documentFetchDests = new Set([
  24148. "document",
  24149. "iframe",
  24150. "frame",
  24151. "fencedframe"
  24152. ]);
  24153. function isDocumentFetchDest(req) {
  24154. const fetchDest = req.headers["sec-fetch-dest"];
  24155. return fetchDest !== void 0 && documentFetchDests.has(fetchDest);
  24156. }
  24157. const urlRE = /[?&]url\b/;
  24158. const rawRE = /[?&]raw\b/;
  24159. const inlineRE$1 = /[?&]inline\b/;
  24160. const svgRE = /\.svg\b/;
  24161. function isServerAccessDeniedForTransform(config, id) {
  24162. if (rawRE.test(id) || urlRE.test(id) || inlineRE$1.test(id) || svgRE.test(id)) return checkLoadingAccess(config, cleanUrl(id)) !== "allowed" || checkLoadingAccess(config, id) !== "allowed";
  24163. return false;
  24164. }
  24165. /**
  24166. * A middleware that short-circuits the middleware chain to serve cached transformed modules
  24167. */
  24168. function cachedTransformMiddleware(server) {
  24169. return function viteCachedTransformMiddleware(req, res, next) {
  24170. const environment = server.environments.client;
  24171. if (isDocumentFetchDest(req)) {
  24172. res.appendHeader("Vary", "Sec-Fetch-Dest");
  24173. return next();
  24174. }
  24175. const ifNoneMatch = req.headers["if-none-match"];
  24176. if (ifNoneMatch) {
  24177. const moduleByEtag = environment.moduleGraph.getModuleByEtag(ifNoneMatch);
  24178. if (moduleByEtag?.transformResult?.etag === ifNoneMatch && moduleByEtag.url === req.url) {
  24179. if (!isCSSRequest(req.url)) {
  24180. debugCache$1?.(`[304] ${prettifyUrl(req.url, server.config.root)}`);
  24181. res.statusCode = 304;
  24182. return res.end();
  24183. }
  24184. }
  24185. }
  24186. next();
  24187. };
  24188. }
  24189. function transformMiddleware(server) {
  24190. const { root, publicDir } = server.config;
  24191. const publicDirInRoot = publicDir.startsWith(withTrailingSlash(root));
  24192. const publicPath = `${publicDir.slice(root.length)}/`;
  24193. return async function viteTransformMiddleware(req, res, next) {
  24194. const environment = server.environments.client;
  24195. if (req.method !== "GET" && req.method !== "HEAD" || knownIgnoreList.has(req.url) || isDocumentFetchDest(req)) return next();
  24196. let url;
  24197. try {
  24198. url = decodeURI(removeTimestampQuery(req.url)).replace(NULL_BYTE_PLACEHOLDER, "\0");
  24199. } catch (e) {
  24200. if (e instanceof URIError) {
  24201. server.config.logger.warn(import_picocolors.default.yellow(`Malformed URI sequence in request URL: ${removeTimestampQuery(req.url)}`));
  24202. return next();
  24203. }
  24204. return next(e);
  24205. }
  24206. const withoutQuery = cleanUrl(url);
  24207. try {
  24208. if (withoutQuery.endsWith(".map")) {
  24209. const depsOptimizer = environment.depsOptimizer;
  24210. if (depsOptimizer?.isOptimizedDepUrl(url)) {
  24211. const sourcemapPath = url.startsWith(FS_PREFIX) ? fsPathFromId(url) : normalizePath(path.resolve(server.config.root, url.slice(1)));
  24212. if (!depsOptimizer.isOptimizedDepFile(sourcemapPath)) return next();
  24213. try {
  24214. const map = JSON.parse(await fsp.readFile(sourcemapPath, "utf-8"));
  24215. applySourcemapIgnoreList(map, sourcemapPath, server.config.server.sourcemapIgnoreList, server.config.logger);
  24216. return send(req, res, JSON.stringify(map), "json", { headers: server.config.server.headers });
  24217. } catch {
  24218. const dummySourceMap = {
  24219. version: 3,
  24220. file: sourcemapPath.replace(/\.map$/, ""),
  24221. sources: [],
  24222. sourcesContent: [],
  24223. names: [],
  24224. mappings: ";;;;;;;;;"
  24225. };
  24226. return send(req, res, JSON.stringify(dummySourceMap), "json", {
  24227. cacheControl: "no-cache",
  24228. headers: server.config.server.headers
  24229. });
  24230. }
  24231. } else {
  24232. const originalUrl = url.replace(/\.map($|\?)/, "$1");
  24233. const map = (await environment.moduleGraph.getModuleByUrl(originalUrl))?.transformResult?.map;
  24234. if (map) return send(req, res, JSON.stringify(map), "json", { headers: server.config.server.headers });
  24235. else return next();
  24236. }
  24237. }
  24238. if (publicDirInRoot && url.startsWith(publicPath)) warnAboutExplicitPublicPathInUrl(url);
  24239. if (req.headers["sec-fetch-dest"] === "script" || isJSRequest(url) || isImportRequest(url) || isCSSRequest(url) || isHTMLProxy(url)) {
  24240. url = removeImportQuery(url);
  24241. url = unwrapId(url);
  24242. if (isCSSRequest(url)) {
  24243. if (req.headers.accept?.includes("text/css") && !isDirectRequest(url)) url = injectQuery(url, "direct");
  24244. const ifNoneMatch = req.headers["if-none-match"];
  24245. if (ifNoneMatch && (await environment.moduleGraph.getModuleByUrl(url))?.transformResult?.etag === ifNoneMatch) {
  24246. debugCache$1?.(`[304] ${prettifyUrl(url, server.config.root)}`);
  24247. res.statusCode = 304;
  24248. return res.end();
  24249. }
  24250. }
  24251. const result = await environment.transformRequest(url);
  24252. if (result) {
  24253. const depsOptimizer = environment.depsOptimizer;
  24254. const type = isDirectCSSRequest(url) ? "css" : "js";
  24255. const isDep = DEP_VERSION_RE.test(url) || depsOptimizer?.isOptimizedDepUrl(url);
  24256. return send(req, res, result.code, type, {
  24257. etag: result.etag,
  24258. cacheControl: isDep ? "max-age=31536000,immutable" : "no-cache",
  24259. headers: server.config.server.headers,
  24260. map: result.map
  24261. });
  24262. }
  24263. }
  24264. } catch (e) {
  24265. if (e?.code === "ERR_OPTIMIZE_DEPS_PROCESSING_ERROR") {
  24266. if (!res.writableEnded) {
  24267. res.statusCode = 504;
  24268. res.statusMessage = "Optimize Deps Processing Error";
  24269. res.end();
  24270. }
  24271. server.config.logger.error(e.message);
  24272. return;
  24273. }
  24274. if (e?.code === "ERR_OUTDATED_OPTIMIZED_DEP") {
  24275. if (!res.writableEnded) {
  24276. res.statusCode = 504;
  24277. res.statusMessage = "Outdated Optimize Dep";
  24278. res.end();
  24279. }
  24280. return;
  24281. }
  24282. if (e?.code === "ERR_CLOSED_SERVER") {
  24283. if (!res.writableEnded) {
  24284. res.statusCode = 504;
  24285. res.statusMessage = "Outdated Request";
  24286. res.end();
  24287. }
  24288. return;
  24289. }
  24290. if (e?.code === "ERR_FILE_NOT_FOUND_IN_OPTIMIZED_DEP_DIR") {
  24291. if (!res.writableEnded) {
  24292. res.statusCode = 404;
  24293. res.end();
  24294. }
  24295. server.config.logger.warn(import_picocolors.default.yellow(e.message));
  24296. return;
  24297. }
  24298. if (e?.code === "ERR_LOAD_URL") return next();
  24299. if (e?.code === "ERR_DENIED_ID") {
  24300. const id = e.id;
  24301. let servingAccessResult = checkLoadingAccess(server.config, cleanUrl(id));
  24302. if (servingAccessResult === "allowed") servingAccessResult = checkLoadingAccess(server.config, id);
  24303. if (servingAccessResult === "denied") {
  24304. respondWithAccessDenied(id, server, res);
  24305. return true;
  24306. }
  24307. if (servingAccessResult === "fallback") {
  24308. next();
  24309. return true;
  24310. }
  24311. throw new Error(`Unexpected access result for id ${id}`);
  24312. }
  24313. return next(e);
  24314. }
  24315. next();
  24316. };
  24317. function warnAboutExplicitPublicPathInUrl(url) {
  24318. let warning;
  24319. if (isImportRequest(url)) {
  24320. const rawUrl = removeImportQuery(url);
  24321. if (urlRE.test(url)) warning = `Assets in the public directory are served at the root path.\nInstead of ${import_picocolors.default.cyan(rawUrl)}, use ${import_picocolors.default.cyan(rawUrl.replace(publicPath, "/"))}.`;
  24322. else warning = `Assets in public directory cannot be imported from JavaScript.
  24323. If you intend to import that asset, put the file in the src directory, and use ${import_picocolors.default.cyan(rawUrl.replace(publicPath, "/src/"))} instead of ${import_picocolors.default.cyan(rawUrl)}.\nIf you intend to use the URL of that asset, use ${import_picocolors.default.cyan(injectQuery(rawUrl.replace(publicPath, "/"), "url"))}.`;
  24324. } else warning = `Files in the public directory are served at the root path.\nInstead of ${import_picocolors.default.cyan(url)}, use ${import_picocolors.default.cyan(url.replace(publicPath, "/"))}.`;
  24325. server.config.logger.warn(import_picocolors.default.yellow(warning));
  24326. }
  24327. }
  24328. //#endregion
  24329. //#region src/node/server/transformRequest.ts
  24330. const ERR_LOAD_URL = "ERR_LOAD_URL";
  24331. const ERR_LOAD_PUBLIC_URL = "ERR_LOAD_PUBLIC_URL";
  24332. const ERR_DENIED_ID = "ERR_DENIED_ID";
  24333. const debugLoad = createDebugger("vite:load");
  24334. const debugTransform = createDebugger("vite:transform");
  24335. const debugCache = createDebugger("vite:cache");
  24336. function transformRequest(environment, url, options) {
  24337. if (environment._closing && environment.config.dev.recoverable) throwClosedServerError();
  24338. const timestamp = monotonicDateNow();
  24339. url = removeTimestampQuery(url);
  24340. const pending = environment._pendingRequests.get(url);
  24341. if (pending) return environment.moduleGraph.getModuleByUrl(url).then((module) => {
  24342. if (!module || pending.timestamp > module.lastInvalidationTimestamp) return pending.request;
  24343. else {
  24344. pending.abort();
  24345. return transformRequest(environment, url, options);
  24346. }
  24347. });
  24348. const request = doTransform(environment, url, options, timestamp);
  24349. let cleared = false;
  24350. const clearCache = () => {
  24351. if (!cleared) {
  24352. environment._pendingRequests.delete(url);
  24353. cleared = true;
  24354. }
  24355. };
  24356. environment._pendingRequests.set(url, {
  24357. request,
  24358. timestamp,
  24359. abort: clearCache
  24360. });
  24361. return request.finally(clearCache);
  24362. }
  24363. async function doTransform(environment, url, options, timestamp) {
  24364. const { pluginContainer } = environment;
  24365. let module = await environment.moduleGraph.getModuleByUrl(url);
  24366. if (module) {
  24367. const cached = await getCachedTransformResult(environment, url, module, timestamp);
  24368. if (cached) return cached;
  24369. }
  24370. const resolved = module ? void 0 : await pluginContainer.resolveId(url, void 0) ?? void 0;
  24371. const id = module?.id ?? resolved?.id ?? url;
  24372. module ??= environment.moduleGraph.getModuleById(id);
  24373. if (module) {
  24374. await environment.moduleGraph._ensureEntryFromUrl(url, void 0, resolved);
  24375. const cached = await getCachedTransformResult(environment, url, module, timestamp);
  24376. if (cached) return cached;
  24377. }
  24378. const result = loadAndTransform(environment, id, url, options, timestamp, module, resolved);
  24379. const { depsOptimizer } = environment;
  24380. if (!depsOptimizer?.isOptimizedDepFile(id)) environment._registerRequestProcessing(id, () => result);
  24381. return result;
  24382. }
  24383. async function getCachedTransformResult(environment, url, module, timestamp) {
  24384. const prettyUrl = debugCache ? prettifyUrl(url, environment.config.root) : "";
  24385. const softInvalidatedTransformResult = await handleModuleSoftInvalidation(environment, module, timestamp);
  24386. if (softInvalidatedTransformResult) {
  24387. debugCache?.(`[memory-hmr] ${prettyUrl}`);
  24388. return softInvalidatedTransformResult;
  24389. }
  24390. const cached = module.transformResult;
  24391. if (cached) {
  24392. debugCache?.(`[memory] ${prettyUrl}`);
  24393. return cached;
  24394. }
  24395. }
  24396. async function loadAndTransform(environment, id, url, options, timestamp, mod, resolved) {
  24397. const { config, pluginContainer, logger } = environment;
  24398. const prettyUrl = debugLoad || debugTransform ? prettifyUrl(url, config.root) : "";
  24399. const moduleGraph = environment.moduleGraph;
  24400. if (!options.skipFsCheck && id[0] !== "\0" && isServerAccessDeniedForTransform(config, id)) {
  24401. const err = /* @__PURE__ */ new Error(`Denied ID ${id}`);
  24402. err.code = ERR_DENIED_ID;
  24403. err.id = id;
  24404. throw err;
  24405. }
  24406. let code = null;
  24407. let map = null;
  24408. let moduleType;
  24409. const loadStart = debugLoad ? performance$1.now() : 0;
  24410. const loadResult = await pluginContainer.load(id);
  24411. if (loadResult == null) {
  24412. const file = cleanUrl(id);
  24413. if (options.skipFsCheck || isFileLoadingAllowed(environment.getTopLevelConfig(), slash(file))) {
  24414. try {
  24415. code = await fsp.readFile(file, "utf-8");
  24416. debugLoad?.(`${timeFrom(loadStart)} [fs] ${prettyUrl}`);
  24417. } catch (e) {
  24418. if (e.code !== "ENOENT" && e.code !== "EISDIR") throw e;
  24419. }
  24420. if (code != null && environment.pluginContainer.watcher) ensureWatchedFile(environment.pluginContainer.watcher, file, config.root);
  24421. }
  24422. if (code) try {
  24423. const extracted = extractSourcemapFromFile(code, file, logger);
  24424. if (extracted) {
  24425. code = extracted.code;
  24426. map = extracted.map;
  24427. }
  24428. } catch (e) {
  24429. logger.warn(`Failed to load source map for ${file}.\n${e}`, { timestamp: true });
  24430. }
  24431. } else {
  24432. debugLoad?.(`${timeFrom(loadStart)} [plugin] ${prettyUrl}`);
  24433. if (isObject$1(loadResult)) {
  24434. code = loadResult.code;
  24435. map = loadResult.map;
  24436. moduleType = loadResult.moduleType;
  24437. } else code = loadResult;
  24438. }
  24439. if (code == null) {
  24440. const isPublicFile = checkPublicFile(url, environment.getTopLevelConfig());
  24441. let publicDirName = path.relative(config.root, config.publicDir);
  24442. if (publicDirName[0] !== ".") publicDirName = "/" + publicDirName;
  24443. const msg = isPublicFile ? `This file is in ${publicDirName} and will be copied as-is during build without going through the plugin transforms, and therefore should not be imported from source code. It can only be referenced via HTML tags.` : `Does the file exist?`;
  24444. const importerMod = moduleGraph.idToModuleMap.get(id)?.importers.values().next().value;
  24445. const importer = importerMod?.file || importerMod?.url;
  24446. const err = /* @__PURE__ */ new Error(`Failed to load url ${url} (resolved id: ${id})${importer ? ` in ${importer}` : ""}. ${msg}`);
  24447. err.code = isPublicFile ? ERR_LOAD_PUBLIC_URL : ERR_LOAD_URL;
  24448. throw err;
  24449. }
  24450. if (moduleType === void 0) {
  24451. const guessedModuleType = getModuleTypeFromId(id);
  24452. if (guessedModuleType && guessedModuleType !== "js") moduleType = guessedModuleType;
  24453. }
  24454. if (environment._closing && environment.config.dev.recoverable) throwClosedServerError();
  24455. mod ??= await moduleGraph._ensureEntryFromUrl(url, void 0, resolved);
  24456. const transformStart = debugTransform ? performance$1.now() : 0;
  24457. const transformResult = await pluginContainer.transform(code, id, {
  24458. inMap: map,
  24459. moduleType
  24460. });
  24461. const originalCode = code;
  24462. if (transformResult.code === originalCode) debugTransform?.(timeFrom(transformStart) + import_picocolors.default.dim(` [skipped] ${prettyUrl}`));
  24463. else {
  24464. debugTransform?.(`${timeFrom(transformStart)} ${prettyUrl}`);
  24465. code = transformResult.code;
  24466. map = transformResult.map;
  24467. }
  24468. let normalizedMap;
  24469. if (typeof map === "string") normalizedMap = JSON.parse(map);
  24470. else if (map) normalizedMap = map;
  24471. else normalizedMap = null;
  24472. if (normalizedMap && "version" in normalizedMap && mod.file) {
  24473. if (normalizedMap.mappings) await injectSourcesContent(normalizedMap, mod.file, logger);
  24474. const sourcemapPath = `${mod.file}.map`;
  24475. applySourcemapIgnoreList(normalizedMap, sourcemapPath, config.server.sourcemapIgnoreList, logger);
  24476. if (path.isAbsolute(mod.file)) {
  24477. let modDirname;
  24478. for (let sourcesIndex = 0; sourcesIndex < normalizedMap.sources.length; ++sourcesIndex) {
  24479. const sourcePath = normalizedMap.sources[sourcesIndex];
  24480. if (sourcePath) {
  24481. if (path.isAbsolute(sourcePath)) {
  24482. modDirname ??= path.dirname(mod.file);
  24483. normalizedMap.sources[sourcesIndex] = path.relative(modDirname, sourcePath);
  24484. }
  24485. }
  24486. }
  24487. }
  24488. }
  24489. if (environment._closing && environment.config.dev.recoverable) throwClosedServerError();
  24490. const topLevelConfig = environment.getTopLevelConfig();
  24491. const result = environment.config.dev.moduleRunnerTransform ? await ssrTransform(code, normalizedMap, url, originalCode, { json: { stringify: topLevelConfig.json.stringify === true && topLevelConfig.json.namedExports !== true } }) : {
  24492. code,
  24493. map: normalizedMap,
  24494. etag: (0, import_etag.default)(code, { weak: true })
  24495. };
  24496. if (timestamp > mod.lastInvalidationTimestamp) moduleGraph.updateModuleTransformResult(mod, result);
  24497. return result;
  24498. }
  24499. /**
  24500. * When a module is soft-invalidated, we can preserve its previous `transformResult` and
  24501. * return similar code to before:
  24502. *
  24503. * - Client: We need to transform the import specifiers with new timestamps
  24504. * - SSR: We don't need to change anything as `ssrLoadModule` controls it
  24505. */
  24506. async function handleModuleSoftInvalidation(environment, mod, timestamp) {
  24507. const transformResult = mod.invalidationState;
  24508. mod.invalidationState = void 0;
  24509. if (!transformResult || transformResult === "HARD_INVALIDATED") return;
  24510. if (mod.transformResult) throw new Error(`Internal server error: Soft-invalidated module "${mod.url}" should not have existing transform result`);
  24511. let result;
  24512. if (transformResult.ssr) result = transformResult;
  24513. else {
  24514. await init;
  24515. const source = transformResult.code;
  24516. const s = new MagicString(source);
  24517. const [imports] = parse$2(source, mod.id || void 0);
  24518. for (const imp of imports) {
  24519. let rawUrl = source.slice(imp.s, imp.e);
  24520. if (rawUrl === "import.meta") continue;
  24521. const hasQuotes = rawUrl[0] === "\"" || rawUrl[0] === "'";
  24522. if (hasQuotes) rawUrl = rawUrl.slice(1, -1);
  24523. const urlWithoutTimestamp = removeTimestampQuery(rawUrl);
  24524. const hmrUrl = unwrapId(stripBase(removeImportQuery(urlWithoutTimestamp), environment.config.base));
  24525. for (const importedMod of mod.importedModules) {
  24526. if (importedMod.url !== hmrUrl) continue;
  24527. if (importedMod.lastHMRTimestamp > 0) {
  24528. const replacedUrl = injectQuery(urlWithoutTimestamp, `t=${importedMod.lastHMRTimestamp}`);
  24529. const start = hasQuotes ? imp.s + 1 : imp.s;
  24530. const end = hasQuotes ? imp.e - 1 : imp.e;
  24531. s.overwrite(start, end, replacedUrl);
  24532. }
  24533. if (imp.d === -1 && environment.config.dev.preTransformRequests) environment.warmupRequest(hmrUrl);
  24534. break;
  24535. }
  24536. }
  24537. const code = s.toString();
  24538. result = {
  24539. ...transformResult,
  24540. code,
  24541. etag: (0, import_etag.default)(code, { weak: true })
  24542. };
  24543. }
  24544. if (timestamp > mod.lastInvalidationTimestamp) environment.moduleGraph.updateModuleTransformResult(mod, result);
  24545. return result;
  24546. }
  24547. const defaultModuleTypes = {
  24548. js: "js",
  24549. mjs: "js",
  24550. cjs: "js",
  24551. jsx: "jsx",
  24552. ts: "ts",
  24553. mts: "ts",
  24554. cts: "ts",
  24555. tsx: "tsx",
  24556. json: "json",
  24557. txt: "text",
  24558. css: "css"
  24559. };
  24560. function getModuleTypeFromId(id) {
  24561. let pos = -1;
  24562. while ((pos = id.indexOf(".", pos + 1)) >= 0) {
  24563. const moduleType = defaultModuleTypes[id.slice(pos + 1)];
  24564. if (moduleType) return moduleType;
  24565. }
  24566. }
  24567. //#endregion
  24568. //#region src/node/server/warmup.ts
  24569. function warmupFiles(server, environment) {
  24570. const { root } = server.config;
  24571. mapFiles(environment.config.dev.warmup, root).then((files) => {
  24572. for (const file of files) warmupFile(server, environment, file);
  24573. });
  24574. }
  24575. async function warmupFile(server, environment, file) {
  24576. if (file.endsWith(".html")) {
  24577. const url = htmlFileToUrl(file, server.config.root);
  24578. if (url) try {
  24579. const html = await fsp.readFile(file, "utf-8");
  24580. await server.transformIndexHtml(url, html);
  24581. } catch (e) {
  24582. environment.logger.error(`Pre-transform error (${import_picocolors.default.cyan(file)}): ${e.message}`, {
  24583. error: e,
  24584. timestamp: true
  24585. });
  24586. }
  24587. } else {
  24588. const url = fileToUrl(file, server.config.root);
  24589. await environment.warmupRequest(url);
  24590. }
  24591. }
  24592. function htmlFileToUrl(file, root) {
  24593. const url = path.relative(root, file);
  24594. if (url[0] === ".") return;
  24595. return "/" + normalizePath(url);
  24596. }
  24597. function fileToUrl(file, root) {
  24598. const url = path.relative(root, file);
  24599. if (url[0] === ".") return path.posix.join(FS_PREFIX, normalizePath(file));
  24600. return "/" + normalizePath(url);
  24601. }
  24602. async function mapFiles(files, root) {
  24603. if (!files.length) return [];
  24604. const result = [];
  24605. const globs = [];
  24606. for (const file of files) if (isDynamicPattern(file)) globs.push(file);
  24607. else if (path.isAbsolute(file)) result.push(file);
  24608. else result.push(path.resolve(root, file));
  24609. if (globs.length) result.push(...await glob(globs, {
  24610. absolute: true,
  24611. cwd: root,
  24612. expandDirectories: false,
  24613. ignore: ["**/.git/**", "**/node_modules/**"]
  24614. }));
  24615. return result;
  24616. }
  24617. //#endregion
  24618. //#region src/node/server/environment.ts
  24619. var DevEnvironment = class extends BaseEnvironment {
  24620. mode = "dev";
  24621. moduleGraph;
  24622. depsOptimizer;
  24623. /**
  24624. * @internal
  24625. */
  24626. _remoteRunnerOptions;
  24627. /**
  24628. * @internal
  24629. */
  24630. _skipFsCheck;
  24631. get pluginContainer() {
  24632. if (!this._pluginContainer) throw new Error(`${this.name} environment.pluginContainer called before initialized`);
  24633. return this._pluginContainer;
  24634. }
  24635. /**
  24636. * @internal
  24637. */
  24638. _pluginContainer;
  24639. /**
  24640. * @internal
  24641. */
  24642. _closing = false;
  24643. /**
  24644. * @internal
  24645. */
  24646. _pendingRequests;
  24647. /**
  24648. * @internal
  24649. */
  24650. _crawlEndFinder;
  24651. /**
  24652. * Hot channel for this environment. If not provided or disabled,
  24653. * it will be a noop channel that does nothing.
  24654. *
  24655. * @example
  24656. * environment.hot.send({ type: 'full-reload' })
  24657. */
  24658. hot;
  24659. constructor(name, config, context) {
  24660. let options = config.environments[name];
  24661. if (!options) throw new Error(`Environment "${name}" is not defined in the config.`);
  24662. if (context.options) options = mergeConfig(options, context.options);
  24663. super(name, config, options);
  24664. this._pendingRequests = /* @__PURE__ */ new Map();
  24665. this.moduleGraph = new EnvironmentModuleGraph(name, (url) => this.pluginContainer.resolveId(url, void 0));
  24666. this._crawlEndFinder = setupOnCrawlEnd();
  24667. this._remoteRunnerOptions = context.remoteRunner ?? {};
  24668. this._skipFsCheck = !!(context.transport && !(isWebSocketServer in context.transport) && context.transport.skipFsCheck);
  24669. this.hot = context.transport ? isWebSocketServer in context.transport ? context.transport : normalizeHotChannel(context.transport, context.hot) : normalizeHotChannel({}, context.hot);
  24670. this.hot.setInvokeHandler({
  24671. fetchModule: (id, importer, options) => {
  24672. if (context.disableFetchModule) throw new Error("fetchModule is disabled in this environment");
  24673. return this.fetchModule(id, importer, options);
  24674. },
  24675. getBuiltins: async () => {
  24676. return this.config.resolve.builtins.map((builtin) => typeof builtin === "string" ? {
  24677. type: "string",
  24678. value: builtin
  24679. } : {
  24680. type: "RegExp",
  24681. source: builtin.source,
  24682. flags: builtin.flags
  24683. });
  24684. }
  24685. });
  24686. this.hot.on("vite:invalidate", async ({ path, message, firstInvalidatedBy }, client) => {
  24687. this.invalidateModule({
  24688. path,
  24689. message,
  24690. firstInvalidatedBy
  24691. }, client);
  24692. });
  24693. if (!context.disableDepsOptimizer) {
  24694. const { optimizeDeps } = this.config;
  24695. if (context.depsOptimizer) this.depsOptimizer = context.depsOptimizer;
  24696. else if (isDepOptimizationDisabled(optimizeDeps)) this.depsOptimizer = void 0;
  24697. else this.depsOptimizer = (optimizeDeps.noDiscovery ? createExplicitDepsOptimizer : createDepsOptimizer)(this);
  24698. }
  24699. }
  24700. async init(options) {
  24701. if (this._initiated) return;
  24702. this._initiated = true;
  24703. this._pluginContainer = await createEnvironmentPluginContainer(this, this.config.plugins, options?.watcher);
  24704. }
  24705. /**
  24706. * When the dev server is restarted, the methods are called in the following order:
  24707. * - new instance `init`
  24708. * - previous instance `close`
  24709. * - new instance `listen`
  24710. */
  24711. async listen(server) {
  24712. this.hot.listen();
  24713. await this.depsOptimizer?.init();
  24714. warmupFiles(server, this);
  24715. }
  24716. /**
  24717. * Called by the module runner to retrieve information about the specified
  24718. * module. Internally calls `transformRequest` and wraps the result in the
  24719. * format that the module runner understands.
  24720. * This method is not meant to be called manually.
  24721. */
  24722. fetchModule(id, importer, options) {
  24723. return fetchModule(this, id, importer, {
  24724. ...this._remoteRunnerOptions,
  24725. ...options
  24726. });
  24727. }
  24728. async reloadModule(module) {
  24729. if (this.config.server.hmr !== false && module.file) updateModules(this, module.file, [module], monotonicDateNow());
  24730. }
  24731. transformRequest(url) {
  24732. return transformRequest(this, url, { skipFsCheck: this._skipFsCheck });
  24733. }
  24734. async warmupRequest(url) {
  24735. try {
  24736. await transformRequest(this, url, { skipFsCheck: true });
  24737. } catch (e) {
  24738. if (e?.code === "ERR_OUTDATED_OPTIMIZED_DEP" || e?.code === "ERR_CLOSED_SERVER") return;
  24739. this.logger.error(buildErrorMessage(e, [`Pre-transform error: ${e.message}`], false), {
  24740. error: e,
  24741. timestamp: true
  24742. });
  24743. }
  24744. }
  24745. invalidateModule(m, _client) {
  24746. const mod = this.moduleGraph.urlToModuleMap.get(m.path);
  24747. if (mod && mod.isSelfAccepting && mod.lastHMRTimestamp > 0 && !mod.lastHMRInvalidationReceived) {
  24748. mod.lastHMRInvalidationReceived = true;
  24749. this.logger.info(import_picocolors.default.yellow(`hmr invalidate `) + import_picocolors.default.dim(m.path) + (m.message ? ` ${m.message}` : ""), { timestamp: true });
  24750. const file = getShortName(mod.file, this.config.root);
  24751. updateModules(this, file, [...mod.importers].filter((imp) => imp !== mod), mod.lastHMRTimestamp, m.firstInvalidatedBy);
  24752. }
  24753. }
  24754. async close() {
  24755. this._closing = true;
  24756. this._crawlEndFinder.cancel();
  24757. await Promise.allSettled([
  24758. this.pluginContainer.close(),
  24759. this.depsOptimizer?.close(),
  24760. isWebSocketServer in this.hot ? Promise.resolve() : this.hot.close(),
  24761. (async () => {
  24762. while (this._pendingRequests.size > 0) await Promise.allSettled([...this._pendingRequests.values()].map((pending) => pending.request));
  24763. })()
  24764. ]);
  24765. }
  24766. /**
  24767. * Calling `await environment.waitForRequestsIdle(id)` will wait until all static imports
  24768. * are processed after the first transformRequest call. If called from a load or transform
  24769. * plugin hook, the id needs to be passed as a parameter to avoid deadlocks.
  24770. * Calling this function after the first static imports section of the module graph has been
  24771. * processed will resolve immediately.
  24772. * @experimental
  24773. */
  24774. waitForRequestsIdle(ignoredId) {
  24775. return this._crawlEndFinder.waitForRequestsIdle(ignoredId);
  24776. }
  24777. /**
  24778. * @internal
  24779. */
  24780. _registerRequestProcessing(id, done) {
  24781. this._crawlEndFinder.registerRequestProcessing(id, done);
  24782. }
  24783. };
  24784. const callCrawlEndIfIdleAfterMs = 50;
  24785. function setupOnCrawlEnd() {
  24786. const registeredIds = /* @__PURE__ */ new Set();
  24787. const seenIds = /* @__PURE__ */ new Set();
  24788. const onCrawlEndPromiseWithResolvers = promiseWithResolvers();
  24789. let timeoutHandle;
  24790. let cancelled = false;
  24791. function cancel() {
  24792. cancelled = true;
  24793. }
  24794. function registerRequestProcessing(id, done) {
  24795. if (!seenIds.has(id)) {
  24796. seenIds.add(id);
  24797. registeredIds.add(id);
  24798. done().catch(() => {}).finally(() => markIdAsDone(id));
  24799. }
  24800. }
  24801. function waitForRequestsIdle(ignoredId) {
  24802. if (ignoredId) {
  24803. seenIds.add(ignoredId);
  24804. markIdAsDone(ignoredId);
  24805. } else checkIfCrawlEndAfterTimeout();
  24806. return onCrawlEndPromiseWithResolvers.promise;
  24807. }
  24808. function markIdAsDone(id) {
  24809. registeredIds.delete(id);
  24810. checkIfCrawlEndAfterTimeout();
  24811. }
  24812. function checkIfCrawlEndAfterTimeout() {
  24813. if (cancelled || registeredIds.size > 0) return;
  24814. if (timeoutHandle) clearTimeout(timeoutHandle);
  24815. timeoutHandle = setTimeout(callOnCrawlEndWhenIdle, callCrawlEndIfIdleAfterMs);
  24816. }
  24817. async function callOnCrawlEndWhenIdle() {
  24818. if (cancelled || registeredIds.size > 0) return;
  24819. onCrawlEndPromiseWithResolvers.resolve();
  24820. }
  24821. return {
  24822. registerRequestProcessing,
  24823. waitForRequestsIdle,
  24824. cancel
  24825. };
  24826. }
  24827. //#endregion
  24828. //#region src/node/server/environments/fullBundleEnvironment.ts
  24829. const debug$7 = createDebugger("vite:full-bundle-mode");
  24830. var MemoryFiles = class {
  24831. files = /* @__PURE__ */ new Map();
  24832. get size() {
  24833. return this.files.size;
  24834. }
  24835. get(file) {
  24836. const result = this.files.get(file);
  24837. if (result === void 0) return;
  24838. if (typeof result === "function") {
  24839. const content = result();
  24840. this.files.set(file, content);
  24841. return content;
  24842. }
  24843. return result;
  24844. }
  24845. set(file, content) {
  24846. this.files.set(file, content);
  24847. }
  24848. has(file) {
  24849. return this.files.has(file);
  24850. }
  24851. clear() {
  24852. this.files.clear();
  24853. }
  24854. };
  24855. var FullBundleDevEnvironment = class extends DevEnvironment {
  24856. devEngine;
  24857. clients = new Clients();
  24858. invalidateCalledModules = /* @__PURE__ */ new Map();
  24859. debouncedFullReload = debounce(20, () => {
  24860. this.hot.send({
  24861. type: "full-reload",
  24862. path: "*"
  24863. });
  24864. this.logger.info(import_picocolors.default.green(`page reload`), { timestamp: true });
  24865. });
  24866. memoryFiles = new MemoryFiles();
  24867. constructor(name, config, context) {
  24868. if (name !== "client") throw new Error("currently full bundle mode is only available for client environment");
  24869. super(name, config, {
  24870. ...context,
  24871. disableDepsOptimizer: true
  24872. });
  24873. }
  24874. async listen(_server) {
  24875. this.hot.listen();
  24876. debug$7?.("INITIAL: setup bundle options");
  24877. const rollupOptions = await this.getRolldownOptions();
  24878. if (Array.isArray(rollupOptions.output) && rollupOptions.output.length > 1) throw new Error("multiple output options are not supported in dev mode");
  24879. const outputOptions = Array.isArray(rollupOptions.output) ? rollupOptions.output[0] : rollupOptions.output;
  24880. this.hot.on("vite:module-loaded", (payload, client) => {
  24881. const clientId = this.clients.setupIfNeeded(client);
  24882. this.devEngine.registerModules(clientId, payload.modules);
  24883. });
  24884. this.hot.on("vite:client:disconnect", (_payload, client) => {
  24885. const clientId = this.clients.delete(client);
  24886. if (clientId) this.devEngine.removeClient(clientId);
  24887. });
  24888. this.devEngine = await dev(rollupOptions, outputOptions, {
  24889. onHmrUpdates: (result) => {
  24890. if (result instanceof Error) {
  24891. for (const client of this.clients.getAll()) client.send({
  24892. type: "error",
  24893. err: prepareError(result)
  24894. });
  24895. return;
  24896. }
  24897. const { updates, changedFiles } = result;
  24898. if (changedFiles.length === 0) return;
  24899. if (updates.every((update) => update.update.type === "Noop")) {
  24900. debug$7?.(`ignored file change for ${changedFiles.join(", ")}`);
  24901. return;
  24902. }
  24903. for (const { clientId, update } of updates) {
  24904. const client = this.clients.get(clientId);
  24905. if (client) {
  24906. this.invalidateCalledModules.get(client)?.clear();
  24907. this.handleHmrOutput(client, changedFiles, update);
  24908. }
  24909. }
  24910. },
  24911. onOutput: (result) => {
  24912. if (result instanceof Error) {
  24913. this.logger.error(import_picocolors.default.red(`✘ Build error: ${result.message}`), { error: result });
  24914. this.hot.send({
  24915. type: "error",
  24916. err: prepareError(result)
  24917. });
  24918. return;
  24919. }
  24920. for (const outputFile of result.output) this.memoryFiles.set(outputFile.fileName, () => {
  24921. const source = outputFile.type === "chunk" ? outputFile.code : outputFile.source;
  24922. return {
  24923. source,
  24924. etag: (0, import_etag.default)(Buffer.from(source), { weak: true })
  24925. };
  24926. });
  24927. },
  24928. watch: { skipWrite: true }
  24929. });
  24930. debug$7?.("INITIAL: setup dev engine");
  24931. this.devEngine.run().then(() => {
  24932. debug$7?.("INITIAL: run done");
  24933. }, (e) => {
  24934. debug$7?.("INITIAL: run error", e);
  24935. });
  24936. this.waitForInitialBuildFinish().then(() => {
  24937. debug$7?.("INITIAL: build done");
  24938. this.hot.send({
  24939. type: "full-reload",
  24940. path: "*"
  24941. });
  24942. });
  24943. }
  24944. async waitForInitialBuildFinish() {
  24945. await this.devEngine.ensureCurrentBuildFinish();
  24946. while (this.memoryFiles.size === 0) {
  24947. await setTimeout$1(10);
  24948. await this.devEngine.ensureCurrentBuildFinish();
  24949. }
  24950. }
  24951. async warmupRequest(_url) {}
  24952. invalidateModule(m, client) {
  24953. (async () => {
  24954. const invalidateCalledModules = this.invalidateCalledModules.get(client);
  24955. if (invalidateCalledModules?.has(m.path)) {
  24956. debug$7?.(`INVALIDATE: invalidate received from ${m.path}, but ignored because it was already invalidated`);
  24957. return;
  24958. }
  24959. debug$7?.(`INVALIDATE: invalidate received from ${m.path}, re-triggering HMR`);
  24960. if (!invalidateCalledModules) this.invalidateCalledModules.set(client, /* @__PURE__ */ new Set([]));
  24961. this.invalidateCalledModules.get(client).add(m.path);
  24962. let update;
  24963. try {
  24964. update = (await this.devEngine.invalidate(m.path, m.firstInvalidatedBy)).find((u) => this.clients.get(u.clientId) === client)?.update;
  24965. } catch (e) {
  24966. client.send({
  24967. type: "error",
  24968. err: prepareError(e)
  24969. });
  24970. return;
  24971. }
  24972. if (!update) return;
  24973. if (update.type === "Patch") this.logger.info(import_picocolors.default.yellow(`hmr invalidate `) + import_picocolors.default.dim(m.path) + (m.message ? ` ${m.message}` : ""), { timestamp: true });
  24974. this.handleHmrOutput(client, [m.path], update, { firstInvalidatedBy: m.firstInvalidatedBy });
  24975. })();
  24976. }
  24977. async triggerBundleRegenerationIfStale() {
  24978. const bundleState = await this.devEngine.getBundleState();
  24979. const shouldTrigger = bundleState.hasStaleOutput && !bundleState.lastFullBuildFailed;
  24980. if (shouldTrigger) {
  24981. this.devEngine.ensureLatestBuildOutput().then(() => {
  24982. this.debouncedFullReload();
  24983. });
  24984. debug$7?.(`TRIGGER: access to stale bundle, triggered bundle re-generation`);
  24985. }
  24986. return shouldTrigger;
  24987. }
  24988. async close() {
  24989. this.memoryFiles.clear();
  24990. await Promise.all([super.close(), this.devEngine.close()]);
  24991. }
  24992. async getRolldownOptions() {
  24993. const chunkMetadataMap = new ChunkMetadataMap();
  24994. const rolldownOptions = resolveRolldownOptions(this, chunkMetadataMap);
  24995. rolldownOptions.experimental ??= {};
  24996. rolldownOptions.experimental.devMode = { implement: await getHmrImplementation(this.getTopLevelConfig()) };
  24997. rolldownOptions.optimization ??= {};
  24998. rolldownOptions.optimization.inlineConst = false;
  24999. if (Array.isArray(rolldownOptions.output)) for (const output of rolldownOptions.output) {
  25000. output.entryFileNames = "assets/[name].js";
  25001. output.chunkFileNames = "assets/[name]-[hash].js";
  25002. output.assetFileNames = "assets/[name]-[hash][extname]";
  25003. output.minify = false;
  25004. output.sourcemap = true;
  25005. }
  25006. else {
  25007. rolldownOptions.output ??= {};
  25008. rolldownOptions.output.entryFileNames = "assets/[name].js";
  25009. rolldownOptions.output.chunkFileNames = "assets/[name]-[hash].js";
  25010. rolldownOptions.output.assetFileNames = "assets/[name]-[hash][extname]";
  25011. rolldownOptions.output.minify = false;
  25012. rolldownOptions.output.sourcemap = true;
  25013. }
  25014. return rolldownOptions;
  25015. }
  25016. handleHmrOutput(client, files, hmrOutput, invalidateInformation) {
  25017. if (hmrOutput.type === "Noop") return;
  25018. const shortFile = files.map((file) => getShortName(file, this.config.root)).join(", ");
  25019. if (hmrOutput.type === "FullReload") {
  25020. const reason = hmrOutput.reason ? import_picocolors.default.dim(` (${hmrOutput.reason})`) : "";
  25021. this.logger.info(import_picocolors.default.green(`trigger page reload `) + import_picocolors.default.dim(shortFile) + reason, {
  25022. clear: !invalidateInformation,
  25023. timestamp: true
  25024. });
  25025. this.devEngine.ensureLatestBuildOutput().then(() => {
  25026. this.debouncedFullReload();
  25027. });
  25028. return;
  25029. }
  25030. debug$7?.(`handle hmr output for ${shortFile}`, {
  25031. ...hmrOutput,
  25032. code: typeof hmrOutput.code === "string" ? "[code]" : hmrOutput.code
  25033. });
  25034. this.memoryFiles.set(hmrOutput.filename, { source: hmrOutput.code });
  25035. if (hmrOutput.sourcemapFilename && hmrOutput.sourcemap) this.memoryFiles.set(hmrOutput.sourcemapFilename, { source: hmrOutput.sourcemap });
  25036. const updates = hmrOutput.hmrBoundaries.map((boundary) => {
  25037. return {
  25038. type: "js-update",
  25039. url: hmrOutput.filename,
  25040. path: boundary.boundary,
  25041. acceptedPath: boundary.acceptedVia,
  25042. firstInvalidatedBy: invalidateInformation?.firstInvalidatedBy,
  25043. timestamp: Date.now()
  25044. };
  25045. });
  25046. client.send({
  25047. type: "update",
  25048. updates
  25049. });
  25050. const filePaths = [...new Set(updates.map((u) => u.path))];
  25051. const { formatted, truncated } = formatAndTruncateFileList(filePaths);
  25052. if (truncated) debugHmr?.(`hmr update ${filePaths.join(", ")}`);
  25053. this.logger.info(import_picocolors.default.green(`hmr update `) + import_picocolors.default.dim(formatted), {
  25054. clear: !invalidateInformation,
  25055. timestamp: true
  25056. });
  25057. }
  25058. };
  25059. var Clients = class {
  25060. clientToId = /* @__PURE__ */ new Map();
  25061. idToClient = /* @__PURE__ */ new Map();
  25062. setupIfNeeded(client) {
  25063. const id = this.clientToId.get(client);
  25064. if (id) return id;
  25065. const newId = randomUUID();
  25066. this.clientToId.set(client, newId);
  25067. this.idToClient.set(newId, client);
  25068. return newId;
  25069. }
  25070. get(id) {
  25071. return this.idToClient.get(id);
  25072. }
  25073. getAll() {
  25074. return Array.from(this.idToClient.values());
  25075. }
  25076. delete(client) {
  25077. const id = this.clientToId.get(client);
  25078. if (id) {
  25079. this.clientToId.delete(client);
  25080. this.idToClient.delete(id);
  25081. return id;
  25082. }
  25083. }
  25084. };
  25085. function debounce(time, cb) {
  25086. let timer;
  25087. return () => {
  25088. if (timer) {
  25089. globalThis.clearTimeout(timer);
  25090. timer = null;
  25091. }
  25092. timer = globalThis.setTimeout(cb, time);
  25093. };
  25094. }
  25095. //#endregion
  25096. //#region src/node/server/middlewares/htmlFallback.ts
  25097. const debug$6 = createDebugger("vite:html-fallback");
  25098. function htmlFallbackMiddleware(root, spaFallback, clientEnvironment) {
  25099. const memoryFiles = clientEnvironment instanceof FullBundleDevEnvironment ? clientEnvironment.memoryFiles : void 0;
  25100. function checkFileExists(relativePath) {
  25101. return memoryFiles?.has(relativePath.slice(1)) ?? fs.existsSync(path.join(root, relativePath));
  25102. }
  25103. return function viteHtmlFallbackMiddleware(req, _res, next) {
  25104. if (req.method !== "GET" && req.method !== "HEAD" || req.url === "/favicon.ico" || !(req.headers.accept === void 0 || req.headers.accept === "" || req.headers.accept.includes("text/html") || req.headers.accept.includes("*/*"))) return next();
  25105. const url = cleanUrl(req.url);
  25106. let pathname;
  25107. try {
  25108. pathname = decodeURIComponent(url);
  25109. } catch {
  25110. return next();
  25111. }
  25112. if (pathname.endsWith(".html")) {
  25113. if (checkFileExists(pathname)) {
  25114. debug$6?.(`Rewriting ${req.method} ${req.url} to ${url}`);
  25115. req.url = url;
  25116. return next();
  25117. }
  25118. } else if (pathname.endsWith("/")) {
  25119. if (checkFileExists(joinUrlSegments(pathname, "index.html"))) {
  25120. const newUrl = url + "index.html";
  25121. debug$6?.(`Rewriting ${req.method} ${req.url} to ${newUrl}`);
  25122. req.url = newUrl;
  25123. return next();
  25124. }
  25125. } else if (checkFileExists(pathname + ".html")) {
  25126. const newUrl = url + ".html";
  25127. debug$6?.(`Rewriting ${req.method} ${req.url} to ${newUrl}`);
  25128. req.url = newUrl;
  25129. return next();
  25130. }
  25131. if (spaFallback) {
  25132. debug$6?.(`Rewriting ${req.method} ${req.url} to /index.html`);
  25133. req.url = "/index.html";
  25134. }
  25135. next();
  25136. };
  25137. }
  25138. //#endregion
  25139. //#region src/node/server/middlewares/indexHtml.ts
  25140. function createDevHtmlTransformFn(config) {
  25141. const [preHooks, normalHooks, postHooks] = resolveHtmlTransforms(config.plugins);
  25142. const transformHooks = [
  25143. preImportMapHook(config),
  25144. injectCspNonceMetaTagHook(config),
  25145. ...preHooks,
  25146. htmlEnvHook(config),
  25147. devHtmlHook,
  25148. ...normalHooks,
  25149. ...postHooks,
  25150. injectNonceAttributeTagHook(config),
  25151. postImportMapHook()
  25152. ];
  25153. const pluginContext = new BasicMinimalPluginContext({
  25154. ...basePluginContextMeta,
  25155. watchMode: true
  25156. }, config.logger);
  25157. return (server, url, html, originalUrl) => {
  25158. return applyHtmlTransforms(html, transformHooks, pluginContext, {
  25159. path: url,
  25160. filename: getHtmlFilename(url, server),
  25161. server,
  25162. originalUrl
  25163. });
  25164. };
  25165. }
  25166. function getHtmlFilename(url, server) {
  25167. if (url.startsWith(FS_PREFIX)) return decodeURIComponent(fsPathFromId(url));
  25168. else return decodeURIComponent(normalizePath(path.join(server.config.root, url.slice(1))));
  25169. }
  25170. function shouldPreTransform(url, config) {
  25171. return !checkPublicFile(url, config) && (isJSRequest(url) || isCSSRequest(url));
  25172. }
  25173. const wordCharRE = /\w/;
  25174. function isBareRelative(url) {
  25175. return wordCharRE.test(url[0]) && !url.includes(":");
  25176. }
  25177. const processNodeUrl = (url, useSrcSetReplacer, config, htmlPath, originalUrl, server, isClassicScriptLink) => {
  25178. const replacer = (url) => {
  25179. if (url[0] === "/" && url[1] !== "/" || (url[0] === "." || isBareRelative(url)) && originalUrl && originalUrl !== "/" && htmlPath === "/index.html") url = path.posix.join(config.base, url);
  25180. let preTransformUrl;
  25181. if (!isClassicScriptLink && shouldPreTransform(url, config)) {
  25182. if (url[0] === "/" && url[1] !== "/") preTransformUrl = url;
  25183. else if (url[0] === "." || isBareRelative(url)) preTransformUrl = path.posix.join(config.base, path.posix.dirname(htmlPath), url);
  25184. }
  25185. if (server) {
  25186. const mod = server.environments.client.moduleGraph.urlToModuleMap.get(preTransformUrl || url);
  25187. if (mod && mod.lastHMRTimestamp > 0) url = injectQuery(url, `t=${mod.lastHMRTimestamp}`);
  25188. }
  25189. if (server && preTransformUrl) {
  25190. try {
  25191. preTransformUrl = decodeURI(preTransformUrl);
  25192. } catch {
  25193. return url;
  25194. }
  25195. preTransformRequest(server, preTransformUrl, config.decodedBase);
  25196. }
  25197. return url;
  25198. };
  25199. return useSrcSetReplacer ? processSrcSetSync(url, ({ url }) => replacer(url)) : replacer(url);
  25200. };
  25201. const devHtmlHook = async (html, { path: htmlPath, filename, server, originalUrl }) => {
  25202. const { config, watcher } = server;
  25203. const base = config.base || "/";
  25204. const decodedBase = config.decodedBase || "/";
  25205. let proxyModulePath;
  25206. let proxyModuleUrl;
  25207. const trailingSlash = htmlPath.endsWith("/");
  25208. if (!trailingSlash && fs.existsSync(filename)) {
  25209. proxyModulePath = htmlPath;
  25210. proxyModuleUrl = proxyModulePath;
  25211. } else {
  25212. proxyModulePath = `\0${`${htmlPath}${trailingSlash ? "index.html" : ""}`}`;
  25213. proxyModuleUrl = wrapId(proxyModulePath);
  25214. }
  25215. proxyModuleUrl = joinUrlSegments(decodedBase, proxyModuleUrl);
  25216. const s = new MagicString(html);
  25217. let inlineModuleIndex = -1;
  25218. const proxyCacheUrl = decodeURI(cleanUrl(proxyModulePath).replace(normalizePath(config.root), ""));
  25219. const styleUrl = [];
  25220. const inlineStyles = [];
  25221. const inlineModulePaths = [];
  25222. const addInlineModule = (node, ext) => {
  25223. inlineModuleIndex++;
  25224. const contentNode = node.childNodes[0];
  25225. const code = contentNode.value;
  25226. let map;
  25227. if (proxyModulePath[0] !== "\0") {
  25228. map = new MagicString(html).snip(contentNode.sourceCodeLocation.startOffset, contentNode.sourceCodeLocation.endOffset).generateMap({ hires: "boundary" });
  25229. map.sources = [filename];
  25230. map.file = filename;
  25231. }
  25232. addToHTMLProxyCache(config, proxyCacheUrl, inlineModuleIndex, {
  25233. code,
  25234. map
  25235. });
  25236. const modulePath = `${proxyModuleUrl}?html-proxy&index=${inlineModuleIndex}.${ext}`;
  25237. inlineModulePaths.push(modulePath);
  25238. s.update(node.sourceCodeLocation.startOffset, node.sourceCodeLocation.endOffset, `<script type="module" src="${modulePath}"><\/script>`);
  25239. preTransformRequest(server, modulePath, decodedBase);
  25240. };
  25241. await traverseHtml(html, filename, config.logger.warn, (node) => {
  25242. if (!nodeIsElement(node)) return;
  25243. if (node.nodeName === "script") {
  25244. const { src, srcSourceCodeLocation, isModule, isIgnored } = getScriptInfo(node);
  25245. if (isIgnored) removeViteIgnoreAttr(s, node.sourceCodeLocation);
  25246. else if (src) {
  25247. const processedUrl = processNodeUrl(src.value, false, config, htmlPath, originalUrl, server, !isModule);
  25248. if (processedUrl !== src.value) overwriteAttrValue(s, srcSourceCodeLocation, processedUrl);
  25249. } else if (isModule && node.childNodes.length) addInlineModule(node, "js");
  25250. else if (node.childNodes.length) {
  25251. const scriptNode = node.childNodes[node.childNodes.length - 1];
  25252. for (const { url, start, end } of extractImportExpressionFromClassicScript(scriptNode)) {
  25253. const processedUrl = processNodeUrl(url, false, config, htmlPath, originalUrl);
  25254. if (processedUrl !== url) s.update(start, end, processedUrl);
  25255. }
  25256. }
  25257. }
  25258. const inlineStyle = findNeedTransformStyleAttribute(node);
  25259. if (inlineStyle) {
  25260. inlineModuleIndex++;
  25261. inlineStyles.push({
  25262. index: inlineModuleIndex,
  25263. location: inlineStyle.location,
  25264. code: inlineStyle.attr.value
  25265. });
  25266. }
  25267. if (node.nodeName === "style" && node.childNodes.length) {
  25268. const children = node.childNodes[0];
  25269. styleUrl.push({
  25270. start: children.sourceCodeLocation.startOffset,
  25271. end: children.sourceCodeLocation.endOffset,
  25272. code: children.value
  25273. });
  25274. }
  25275. const assetAttributes = getNodeAssetAttributes(node);
  25276. for (const attr of assetAttributes) if (attr.type === "remove") s.remove(attr.location.startOffset, attr.location.endOffset);
  25277. else {
  25278. const processedUrl = processNodeUrl(attr.value, attr.type === "srcset", config, htmlPath, originalUrl);
  25279. if (processedUrl !== attr.value) overwriteAttrValue(s, attr.location, processedUrl);
  25280. }
  25281. });
  25282. const clientModuleGraph = server?.environments.client.moduleGraph;
  25283. if (clientModuleGraph) await Promise.all(inlineModulePaths.map(async (url) => {
  25284. const module = await clientModuleGraph.getModuleByUrl(url);
  25285. if (module) clientModuleGraph.invalidateModule(module);
  25286. }));
  25287. await Promise.all([...styleUrl.map(async ({ start, end, code }, index) => {
  25288. const url = `${proxyModulePath}?html-proxy&direct&index=${index}.css`;
  25289. const mod = await server.environments.client.moduleGraph.ensureEntryFromUrl(url, false);
  25290. ensureWatchedFile(watcher, mod.file, config.root);
  25291. const result = await server.environments.client.pluginContainer.transform(code, mod.id);
  25292. let content = "";
  25293. if (result.map && "version" in result.map) {
  25294. if (result.map.mappings) await injectSourcesContent(result.map, proxyModulePath, config.logger);
  25295. content = getCodeWithSourcemap("css", result.code, result.map);
  25296. } else content = result.code;
  25297. s.overwrite(start, end, content);
  25298. }), ...inlineStyles.map(async ({ index, location, code }) => {
  25299. const url = `${proxyModulePath}?html-proxy&inline-css&style-attr&index=${index}.css`;
  25300. const mod = await server.environments.client.moduleGraph.ensureEntryFromUrl(url, false);
  25301. ensureWatchedFile(watcher, mod.file, config.root);
  25302. await server?.environments.client.pluginContainer.transform(code, mod.id);
  25303. const hash = getHash(cleanUrl(mod.id));
  25304. overwriteAttrValue(s, location, htmlProxyResult.get(`${hash}_${index}`) ?? "");
  25305. })]);
  25306. html = s.toString();
  25307. return {
  25308. html,
  25309. tags: [{
  25310. tag: "script",
  25311. attrs: {
  25312. type: "module",
  25313. src: path.posix.join(base, CLIENT_PUBLIC_PATH)
  25314. },
  25315. injectTo: "head-prepend"
  25316. }]
  25317. };
  25318. };
  25319. function indexHtmlMiddleware(root, server) {
  25320. const isDev = isDevServer(server);
  25321. const fullBundleEnv = isDev && server.environments.client instanceof FullBundleDevEnvironment ? server.environments.client : void 0;
  25322. return async function viteIndexHtmlMiddleware(req, res, next) {
  25323. if (res.writableEnded) return next();
  25324. const url = req.url && cleanUrl(req.url);
  25325. if (url?.endsWith(".html") && req.headers["sec-fetch-dest"] !== "script") {
  25326. if (fullBundleEnv) {
  25327. const filePath = decodeURIComponent(url).slice(1);
  25328. let file = fullBundleEnv.memoryFiles.get(filePath);
  25329. if (!file && fullBundleEnv.memoryFiles.size !== 0) return next();
  25330. if ([
  25331. "document",
  25332. "iframe",
  25333. "frame",
  25334. "fencedframe",
  25335. "",
  25336. void 0
  25337. ].includes(req.headers["sec-fetch-dest"]) && (await fullBundleEnv.triggerBundleRegenerationIfStale() || file === void 0)) file = { source: await generateFallbackHtml(server) };
  25338. if (!file) return next();
  25339. return send(req, res, typeof file.source === "string" ? file.source : Buffer.from(file.source), "html", {
  25340. headers: isDev ? server.config.server.headers : server.config.preview.headers,
  25341. etag: file.etag
  25342. });
  25343. }
  25344. let filePath;
  25345. if (isDev && url.startsWith(FS_PREFIX)) filePath = decodeURIComponent(fsPathFromId(url));
  25346. else filePath = normalizePath(path.resolve(path.join(root, decodeURIComponent(url))));
  25347. if (isDev) {
  25348. const servingAccessResult = checkLoadingAccess(server.config, filePath);
  25349. if (servingAccessResult === "denied") return respondWithAccessDenied(filePath, server, res);
  25350. if (servingAccessResult === "fallback") return next();
  25351. } else if (!isParentDirectory(root, filePath)) return next();
  25352. if (fs.existsSync(filePath)) {
  25353. const headers = isDev ? server.config.server.headers : server.config.preview.headers;
  25354. try {
  25355. let html = await fsp.readFile(filePath, "utf-8");
  25356. if (isDev) html = await server.transformIndexHtml(url, html, req.originalUrl);
  25357. return send(req, res, html, "html", { headers });
  25358. } catch (e) {
  25359. return next(e);
  25360. }
  25361. }
  25362. }
  25363. next();
  25364. };
  25365. }
  25366. function preTransformRequest(server, decodedUrl, decodedBase) {
  25367. if (!server.config.server.preTransformRequests) return;
  25368. decodedUrl = unwrapId(stripBase(decodedUrl, decodedBase));
  25369. server.warmupRequest(decodedUrl);
  25370. }
  25371. async function generateFallbackHtml(server) {
  25372. return `
  25373. <!DOCTYPE html>
  25374. <html lang="en">
  25375. <head>
  25376. <script type="module">
  25377. ${(await getHmrImplementation(server.config)).replaceAll("<\/script>", "<\\/script>")}
  25378. <\/script>
  25379. <style>
  25380. :root {
  25381. --page-bg: #ffffff;
  25382. --text-color: #1d1d1f;
  25383. --spinner-track: #f5f5f7;
  25384. --spinner-accent: #0071e3;
  25385. }
  25386. @media (prefers-color-scheme: dark) {
  25387. :root {
  25388. --page-bg: #1e1e1e;
  25389. --text-color: #f5f5f5;
  25390. --spinner-track: #424242;
  25391. }
  25392. }
  25393. body {
  25394. margin: 0;
  25395. min-height: 100vh;
  25396. display: flex;
  25397. background-color: var(--page-bg);
  25398. color: var(--text-color);
  25399. }
  25400. .container {
  25401. margin: auto;
  25402. padding: 2rem;
  25403. text-align: center;
  25404. border-radius: 1rem;
  25405. }
  25406. .spinner {
  25407. width: 3rem;
  25408. height: 3rem;
  25409. margin: 2rem auto;
  25410. border: 3px solid var(--spinner-track);
  25411. border-top-color: var(--spinner-accent);
  25412. border-radius: 50%;
  25413. animation: spin 1s linear infinite;
  25414. }
  25415. @keyframes spin { to { transform: rotate(360deg) } }
  25416. </style>
  25417. </head>
  25418. <body>
  25419. <div class="container">
  25420. <h1>Bundling in progress</h1>
  25421. <p>The page will automatically reload when ready.</p>
  25422. <div class="spinner"></div>
  25423. </div>
  25424. </body>
  25425. </html>
  25426. `;
  25427. }
  25428. //#endregion
  25429. //#region src/node/server/middlewares/time.ts
  25430. const logTime = createDebugger("vite:time");
  25431. function timeMiddleware(root) {
  25432. return function viteTimeMiddleware(req, res, next) {
  25433. const start = performance$1.now();
  25434. const end = res.end;
  25435. res.end = (...args) => {
  25436. logTime?.(`${timeFrom(start)} ${prettifyUrl(req.url, root)}`);
  25437. return end.call(res, ...args);
  25438. };
  25439. next();
  25440. };
  25441. }
  25442. //#endregion
  25443. //#region src/node/server/mixedModuleGraph.ts
  25444. /**
  25445. * Backward compatible ModuleNode and ModuleGraph with mixed nodes from both the client and ssr environments
  25446. * It would be good to take the types names for the new EnvironmentModuleNode and EnvironmentModuleGraph but we can't
  25447. * do that at this point without breaking to much code in the ecosystem.
  25448. * We are going to deprecate these types and we can try to use them back in the future.
  25449. */
  25450. const EMPTY_OBJECT$1 = Object.freeze({});
  25451. var ModuleNode = class {
  25452. _moduleGraph;
  25453. _clientModule;
  25454. _ssrModule;
  25455. constructor(moduleGraph, clientModule, ssrModule) {
  25456. this._moduleGraph = moduleGraph;
  25457. this._clientModule = clientModule;
  25458. this._ssrModule = ssrModule;
  25459. }
  25460. _get(prop) {
  25461. return this._clientModule?.[prop] ?? this._ssrModule?.[prop];
  25462. }
  25463. _set(prop, value) {
  25464. if (this._clientModule) this._clientModule[prop] = value;
  25465. if (this._ssrModule) this._ssrModule[prop] = value;
  25466. }
  25467. _wrapModuleSet(prop, module) {
  25468. if (!module) return /* @__PURE__ */ new Set();
  25469. return createBackwardCompatibleModuleSet(this._moduleGraph, prop, module);
  25470. }
  25471. _getModuleSetUnion(prop) {
  25472. const importedModules = /* @__PURE__ */ new Set();
  25473. const ids = /* @__PURE__ */ new Set();
  25474. if (this._clientModule) for (const mod of this._clientModule[prop]) {
  25475. if (mod.id) ids.add(mod.id);
  25476. importedModules.add(this._moduleGraph.getBackwardCompatibleModuleNode(mod));
  25477. }
  25478. if (this._ssrModule) {
  25479. for (const mod of this._ssrModule[prop]) if (mod.id && !ids.has(mod.id)) importedModules.add(this._moduleGraph.getBackwardCompatibleModuleNode(mod));
  25480. }
  25481. return importedModules;
  25482. }
  25483. _getModuleInfoUnion(prop) {
  25484. const _clientValue = this._clientModule?.[prop];
  25485. const _ssrValue = this._ssrModule?.[prop];
  25486. if (_clientValue == null && _ssrValue == null) return void 0;
  25487. return new Proxy({}, { get: (_, key) => {
  25488. if (key === "meta") return this.meta || EMPTY_OBJECT$1;
  25489. if (_clientValue) {
  25490. if (key in _clientValue) return _clientValue[key];
  25491. }
  25492. if (_ssrValue) {
  25493. if (key in _ssrValue) return _ssrValue[key];
  25494. }
  25495. } });
  25496. }
  25497. _getModuleObjectUnion(prop) {
  25498. const _clientValue = this._clientModule?.[prop];
  25499. const _ssrValue = this._ssrModule?.[prop];
  25500. if (_clientValue == null && _ssrValue == null) return void 0;
  25501. const info = {};
  25502. if (_ssrValue) Object.assign(info, _ssrValue);
  25503. if (_clientValue) Object.assign(info, _clientValue);
  25504. return info;
  25505. }
  25506. get url() {
  25507. return this._get("url");
  25508. }
  25509. set url(value) {
  25510. this._set("url", value);
  25511. }
  25512. get id() {
  25513. return this._get("id");
  25514. }
  25515. set id(value) {
  25516. this._set("id", value);
  25517. }
  25518. get file() {
  25519. return this._get("file");
  25520. }
  25521. set file(value) {
  25522. this._set("file", value);
  25523. }
  25524. get type() {
  25525. return this._get("type");
  25526. }
  25527. get info() {
  25528. return this._getModuleInfoUnion("info");
  25529. }
  25530. get meta() {
  25531. return this._getModuleObjectUnion("meta");
  25532. }
  25533. get importers() {
  25534. return this._getModuleSetUnion("importers");
  25535. }
  25536. get clientImportedModules() {
  25537. return this._wrapModuleSet("importedModules", this._clientModule);
  25538. }
  25539. get ssrImportedModules() {
  25540. return this._wrapModuleSet("importedModules", this._ssrModule);
  25541. }
  25542. get importedModules() {
  25543. return this._getModuleSetUnion("importedModules");
  25544. }
  25545. get acceptedHmrDeps() {
  25546. return this._wrapModuleSet("acceptedHmrDeps", this._clientModule);
  25547. }
  25548. get acceptedHmrExports() {
  25549. return this._clientModule?.acceptedHmrExports ?? null;
  25550. }
  25551. get importedBindings() {
  25552. return this._clientModule?.importedBindings ?? null;
  25553. }
  25554. get isSelfAccepting() {
  25555. return this._clientModule?.isSelfAccepting;
  25556. }
  25557. get transformResult() {
  25558. return this._clientModule?.transformResult ?? null;
  25559. }
  25560. set transformResult(value) {
  25561. if (this._clientModule) this._clientModule.transformResult = value;
  25562. }
  25563. get ssrTransformResult() {
  25564. return this._ssrModule?.transformResult ?? null;
  25565. }
  25566. set ssrTransformResult(value) {
  25567. if (this._ssrModule) this._ssrModule.transformResult = value;
  25568. }
  25569. get ssrModule() {
  25570. return this._ssrModule?.ssrModule ?? null;
  25571. }
  25572. get ssrError() {
  25573. return this._ssrModule?.ssrError ?? null;
  25574. }
  25575. get lastHMRTimestamp() {
  25576. return Math.max(this._clientModule?.lastHMRTimestamp ?? 0, this._ssrModule?.lastHMRTimestamp ?? 0);
  25577. }
  25578. set lastHMRTimestamp(value) {
  25579. if (this._clientModule) this._clientModule.lastHMRTimestamp = value;
  25580. if (this._ssrModule) this._ssrModule.lastHMRTimestamp = value;
  25581. }
  25582. get lastInvalidationTimestamp() {
  25583. return Math.max(this._clientModule?.lastInvalidationTimestamp ?? 0, this._ssrModule?.lastInvalidationTimestamp ?? 0);
  25584. }
  25585. get invalidationState() {
  25586. return this._clientModule?.invalidationState;
  25587. }
  25588. get ssrInvalidationState() {
  25589. return this._ssrModule?.invalidationState;
  25590. }
  25591. };
  25592. function mapIterator(iterable, transform) {
  25593. return {
  25594. [Symbol.iterator]() {
  25595. return this;
  25596. },
  25597. next() {
  25598. const r = iterable.next();
  25599. return r.done ? r : {
  25600. value: transform(r.value),
  25601. done: false
  25602. };
  25603. }
  25604. };
  25605. }
  25606. var ModuleGraph = class {
  25607. /** @internal */
  25608. _moduleGraphs;
  25609. /** @internal */
  25610. get _client() {
  25611. return this._moduleGraphs.client();
  25612. }
  25613. /** @internal */
  25614. get _ssr() {
  25615. return this._moduleGraphs.ssr();
  25616. }
  25617. urlToModuleMap;
  25618. idToModuleMap;
  25619. etagToModuleMap;
  25620. fileToModulesMap;
  25621. moduleNodeCache = new DualWeakMap();
  25622. constructor(moduleGraphs) {
  25623. this._moduleGraphs = moduleGraphs;
  25624. const getModuleMapUnion = (prop) => () => {
  25625. if (this._ssr[prop].size === 0) return this._client[prop];
  25626. const map = new Map(this._client[prop]);
  25627. for (const [key, module] of this._ssr[prop]) if (!map.has(key)) map.set(key, module);
  25628. return map;
  25629. };
  25630. this.urlToModuleMap = createBackwardCompatibleModuleMap(this, "urlToModuleMap", getModuleMapUnion("urlToModuleMap"));
  25631. this.idToModuleMap = createBackwardCompatibleModuleMap(this, "idToModuleMap", getModuleMapUnion("idToModuleMap"));
  25632. this.etagToModuleMap = createBackwardCompatibleModuleMap(this, "etagToModuleMap", () => this._client.etagToModuleMap);
  25633. this.fileToModulesMap = createBackwardCompatibleFileToModulesMap(this);
  25634. }
  25635. getModuleById(id) {
  25636. const clientModule = this._client.getModuleById(id);
  25637. const ssrModule = this._ssr.getModuleById(id);
  25638. if (!clientModule && !ssrModule) return;
  25639. return this.getBackwardCompatibleModuleNodeDual(clientModule, ssrModule);
  25640. }
  25641. async getModuleByUrl(url, _ssr) {
  25642. const [clientModule, ssrModule] = await Promise.all([this._client.getModuleByUrl(url), this._ssr.getModuleByUrl(url)]);
  25643. if (!clientModule && !ssrModule) return;
  25644. return this.getBackwardCompatibleModuleNodeDual(clientModule, ssrModule);
  25645. }
  25646. getModulesByFile(file) {
  25647. const clientModules = this._client.getModulesByFile(file);
  25648. const ssrModules = this._ssr.getModulesByFile(file);
  25649. if (!clientModules && !ssrModules) return;
  25650. const result = /* @__PURE__ */ new Set();
  25651. if (clientModules) for (const mod of clientModules) result.add(this.getBackwardCompatibleBrowserModuleNode(mod));
  25652. if (ssrModules) {
  25653. for (const mod of ssrModules) if (mod.id == null || !this._client.getModuleById(mod.id)) result.add(this.getBackwardCompatibleServerModuleNode(mod));
  25654. }
  25655. return result;
  25656. }
  25657. onFileChange(file) {
  25658. this._client.onFileChange(file);
  25659. this._ssr.onFileChange(file);
  25660. }
  25661. onFileDelete(file) {
  25662. this._client.onFileDelete(file);
  25663. this._ssr.onFileDelete(file);
  25664. }
  25665. /** @internal */
  25666. _getModuleGraph(environment) {
  25667. switch (environment) {
  25668. case "client": return this._client;
  25669. case "ssr": return this._ssr;
  25670. default: throw new Error(`Invalid module node environment ${environment}`);
  25671. }
  25672. }
  25673. invalidateModule(mod, seen = /* @__PURE__ */ new Set(), timestamp = monotonicDateNow(), isHmr = false, softInvalidate = false) {
  25674. if (mod._clientModule) this._client.invalidateModule(mod._clientModule, new Set([...seen].map((mod) => mod._clientModule).filter(Boolean)), timestamp, isHmr, softInvalidate);
  25675. if (mod._ssrModule) this._ssr.invalidateModule(mod._ssrModule, new Set([...seen].map((mod) => mod._ssrModule).filter(Boolean)), timestamp, isHmr, softInvalidate);
  25676. }
  25677. invalidateAll() {
  25678. this._client.invalidateAll();
  25679. this._ssr.invalidateAll();
  25680. }
  25681. async ensureEntryFromUrl(rawUrl, ssr, setIsSelfAccepting = true) {
  25682. const module = await (ssr ? this._ssr : this._client).ensureEntryFromUrl(rawUrl, setIsSelfAccepting);
  25683. return this.getBackwardCompatibleModuleNode(module);
  25684. }
  25685. createFileOnlyEntry(file) {
  25686. const clientModule = this._client.createFileOnlyEntry(file);
  25687. const ssrModule = this._ssr.createFileOnlyEntry(file);
  25688. return this.getBackwardCompatibleModuleNodeDual(clientModule, ssrModule);
  25689. }
  25690. async resolveUrl(url, ssr) {
  25691. return ssr ? this._ssr.resolveUrl(url) : this._client.resolveUrl(url);
  25692. }
  25693. updateModuleTransformResult(mod, result, ssr) {
  25694. const environment = ssr ? "ssr" : "client";
  25695. this._getModuleGraph(environment).updateModuleTransformResult(environment === "client" ? mod._clientModule : mod._ssrModule, result);
  25696. }
  25697. getModuleByEtag(etag) {
  25698. const mod = this._client.etagToModuleMap.get(etag);
  25699. return mod && this.getBackwardCompatibleBrowserModuleNode(mod);
  25700. }
  25701. getBackwardCompatibleBrowserModuleNode(clientModule) {
  25702. return this.getBackwardCompatibleModuleNodeDual(clientModule, clientModule.id ? this._ssr.getModuleById(clientModule.id) : void 0);
  25703. }
  25704. getBackwardCompatibleServerModuleNode(ssrModule) {
  25705. return this.getBackwardCompatibleModuleNodeDual(ssrModule.id ? this._client.getModuleById(ssrModule.id) : void 0, ssrModule);
  25706. }
  25707. getBackwardCompatibleModuleNode(mod) {
  25708. return mod.environment === "client" ? this.getBackwardCompatibleBrowserModuleNode(mod) : this.getBackwardCompatibleServerModuleNode(mod);
  25709. }
  25710. getBackwardCompatibleModuleNodeDual(clientModule, ssrModule) {
  25711. const cached = this.moduleNodeCache.get(clientModule, ssrModule);
  25712. if (cached) return cached;
  25713. const moduleNode = new ModuleNode(this, clientModule, ssrModule);
  25714. this.moduleNodeCache.set(clientModule, ssrModule, moduleNode);
  25715. return moduleNode;
  25716. }
  25717. };
  25718. var DualWeakMap = class {
  25719. map = /* @__PURE__ */ new WeakMap();
  25720. undefinedKey = {};
  25721. get(key1, key2) {
  25722. const k1 = key1 ?? this.undefinedKey;
  25723. const k2 = key2 ?? this.undefinedKey;
  25724. return this.map.get(k1)?.get(k2);
  25725. }
  25726. set(key1, key2, value) {
  25727. const k1 = key1 ?? this.undefinedKey;
  25728. const k2 = key2 ?? this.undefinedKey;
  25729. if (!this.map.has(k1)) this.map.set(k1, /* @__PURE__ */ new Map());
  25730. this.map.get(k1).set(k2, value);
  25731. }
  25732. };
  25733. function createBackwardCompatibleModuleSet(moduleGraph, prop, module) {
  25734. return {
  25735. [Symbol.iterator]() {
  25736. return this.keys();
  25737. },
  25738. has(key) {
  25739. if (!key.id) return false;
  25740. const keyModule = moduleGraph._getModuleGraph(module.environment).getModuleById(key.id);
  25741. return keyModule !== void 0 && module[prop].has(keyModule);
  25742. },
  25743. values() {
  25744. return this.keys();
  25745. },
  25746. keys() {
  25747. return mapIterator(module[prop].keys(), (mod) => moduleGraph.getBackwardCompatibleModuleNode(mod));
  25748. },
  25749. get size() {
  25750. return module[prop].size;
  25751. },
  25752. forEach(callback, thisArg) {
  25753. return module[prop].forEach((mod) => {
  25754. const backwardCompatibleMod = moduleGraph.getBackwardCompatibleModuleNode(mod);
  25755. callback.call(thisArg, backwardCompatibleMod, backwardCompatibleMod, this);
  25756. });
  25757. }
  25758. };
  25759. }
  25760. function createBackwardCompatibleModuleMap(moduleGraph, prop, getModuleMap) {
  25761. return {
  25762. [Symbol.iterator]() {
  25763. return this.entries();
  25764. },
  25765. get(key) {
  25766. const clientModule = moduleGraph._client[prop].get(key);
  25767. const ssrModule = moduleGraph._ssr[prop].get(key);
  25768. if (!clientModule && !ssrModule) return;
  25769. return moduleGraph.getBackwardCompatibleModuleNodeDual(clientModule, ssrModule);
  25770. },
  25771. set(key, mod) {
  25772. const clientModule = mod._clientModule;
  25773. if (clientModule) moduleGraph._client[prop].set(key, clientModule);
  25774. const ssrModule = mod._ssrModule;
  25775. if (ssrModule) moduleGraph._ssr[prop].set(key, ssrModule);
  25776. },
  25777. keys() {
  25778. return getModuleMap().keys();
  25779. },
  25780. values() {
  25781. return mapIterator(getModuleMap().values(), (mod) => moduleGraph.getBackwardCompatibleModuleNode(mod));
  25782. },
  25783. entries() {
  25784. return mapIterator(getModuleMap().entries(), ([key, mod]) => [key, moduleGraph.getBackwardCompatibleModuleNode(mod)]);
  25785. },
  25786. get size() {
  25787. return getModuleMap().size;
  25788. },
  25789. forEach(callback, thisArg) {
  25790. return getModuleMap().forEach((mod, key) => {
  25791. const backwardCompatibleMod = moduleGraph.getBackwardCompatibleModuleNode(mod);
  25792. callback.call(thisArg, backwardCompatibleMod, key, this);
  25793. });
  25794. }
  25795. };
  25796. }
  25797. function createBackwardCompatibleFileToModulesMap(moduleGraph) {
  25798. const getFileToModulesMap = () => {
  25799. if (!moduleGraph._ssr.fileToModulesMap.size) return moduleGraph._client.fileToModulesMap;
  25800. const map = new Map(moduleGraph._client.fileToModulesMap);
  25801. for (const [key, modules] of moduleGraph._ssr.fileToModulesMap) {
  25802. const modulesSet = map.get(key);
  25803. if (!modulesSet) map.set(key, modules);
  25804. else for (const ssrModule of modules) {
  25805. let hasModule = false;
  25806. for (const clientModule of modulesSet) {
  25807. hasModule ||= clientModule.id === ssrModule.id;
  25808. if (hasModule) break;
  25809. }
  25810. if (!hasModule) modulesSet.add(ssrModule);
  25811. }
  25812. }
  25813. return map;
  25814. };
  25815. const getBackwardCompatibleModules = (modules) => new Set([...modules].map((mod) => moduleGraph.getBackwardCompatibleModuleNode(mod)));
  25816. return {
  25817. [Symbol.iterator]() {
  25818. return this.entries();
  25819. },
  25820. get(key) {
  25821. const clientModules = moduleGraph._client.fileToModulesMap.get(key);
  25822. const ssrModules = moduleGraph._ssr.fileToModulesMap.get(key);
  25823. if (!clientModules && !ssrModules) return;
  25824. const modules = clientModules ?? /* @__PURE__ */ new Set();
  25825. if (ssrModules) {
  25826. for (const ssrModule of ssrModules) if (ssrModule.id) {
  25827. let found = false;
  25828. for (const mod of modules) {
  25829. found ||= mod.id === ssrModule.id;
  25830. if (found) break;
  25831. }
  25832. if (!found) modules.add(ssrModule);
  25833. }
  25834. }
  25835. return getBackwardCompatibleModules(modules);
  25836. },
  25837. keys() {
  25838. return getFileToModulesMap().keys();
  25839. },
  25840. values() {
  25841. return mapIterator(getFileToModulesMap().values(), getBackwardCompatibleModules);
  25842. },
  25843. entries() {
  25844. return mapIterator(getFileToModulesMap().entries(), ([key, modules]) => [key, getBackwardCompatibleModules(modules)]);
  25845. },
  25846. get size() {
  25847. return getFileToModulesMap().size;
  25848. },
  25849. forEach(callback, thisArg) {
  25850. return getFileToModulesMap().forEach((modules, key) => {
  25851. callback.call(thisArg, getBackwardCompatibleModules(modules), key, this);
  25852. });
  25853. }
  25854. };
  25855. }
  25856. //#endregion
  25857. //#region src/node/server/middlewares/notFound.ts
  25858. function notFoundMiddleware() {
  25859. return function vite404Middleware(_, res) {
  25860. res.statusCode = 404;
  25861. res.end();
  25862. };
  25863. }
  25864. //#endregion
  25865. //#region src/node/server/middlewares/hostCheck.ts
  25866. function getAdditionalAllowedHosts(resolvedServerOptions, resolvedPreviewOptions) {
  25867. const list = [];
  25868. if (typeof resolvedServerOptions.host === "string" && resolvedServerOptions.host) list.push(resolvedServerOptions.host);
  25869. if (typeof resolvedServerOptions.hmr === "object" && resolvedServerOptions.hmr.host) list.push(resolvedServerOptions.hmr.host);
  25870. if (typeof resolvedPreviewOptions.host === "string" && resolvedPreviewOptions.host) list.push(resolvedPreviewOptions.host);
  25871. if (resolvedServerOptions.origin) try {
  25872. const serverOriginUrl = new URL(resolvedServerOptions.origin);
  25873. list.push(serverOriginUrl.hostname);
  25874. } catch {}
  25875. return list;
  25876. }
  25877. function hostValidationMiddleware(allowedHosts, isPreview) {
  25878. return hostValidationMiddleware$1({
  25879. allowedHosts: Object.freeze([...allowedHosts]),
  25880. generateErrorMessage(hostname) {
  25881. const hostnameWithQuotes = JSON.stringify(hostname);
  25882. return `Blocked request. This host (${hostnameWithQuotes}) is not allowed.\nTo allow this host, add ${hostnameWithQuotes} to \`${`${isPreview ? "preview" : "server"}.allowedHosts`}\` in vite.config.js.`;
  25883. }
  25884. });
  25885. }
  25886. //#endregion
  25887. //#region src/node/server/middlewares/rejectInvalidRequest.ts
  25888. /**
  25889. * disallows request that contains `#` in the URL
  25890. */
  25891. function rejectInvalidRequestMiddleware() {
  25892. return function viteRejectInvalidRequestMiddleware(req, res, next) {
  25893. if (req.url?.includes("#")) {
  25894. res.writeHead(400);
  25895. res.end();
  25896. return;
  25897. }
  25898. return next();
  25899. };
  25900. }
  25901. //#endregion
  25902. //#region src/node/server/middlewares/memoryFiles.ts
  25903. function memoryFilesMiddleware(server) {
  25904. const memoryFiles = server.environments.client instanceof FullBundleDevEnvironment ? server.environments.client.memoryFiles : void 0;
  25905. if (!memoryFiles) throw new Error("memoryFilesMiddleware can only be used for fullBundleMode");
  25906. const headers = server.config.server.headers;
  25907. return function viteMemoryFilesMiddleware(req, res, next) {
  25908. const cleanedUrl = cleanUrl(req.url);
  25909. if (cleanedUrl.endsWith(".html")) return next();
  25910. const filePath = decodeURIComponent(cleanedUrl).slice(1);
  25911. const file = memoryFiles.get(filePath);
  25912. if (file) {
  25913. if (file.etag) {
  25914. if (req.headers["if-none-match"] === file.etag) {
  25915. res.statusCode = 304;
  25916. res.end();
  25917. return;
  25918. }
  25919. res.setHeader("Etag", file.etag);
  25920. }
  25921. const mime = lookup(filePath);
  25922. if (mime) res.setHeader("Content-Type", mime);
  25923. for (const name in headers) res.setHeader(name, headers[name]);
  25924. return res.end(file.source);
  25925. }
  25926. next();
  25927. };
  25928. }
  25929. //#endregion
  25930. //#region src/node/server/middlewares/rejectNoCorsRequest.ts
  25931. /**
  25932. * A middleware that rejects no-cors mode requests that are not same-origin.
  25933. *
  25934. * We should avoid untrusted sites to load the script to avoid attacks like GHSA-4v9v-hfq4-rm2v.
  25935. * This is because:
  25936. * - the path of HMR patch files / entry point files can be predictable
  25937. * - the HMR patch files may not include ESM syntax
  25938. * (if they include ESM syntax, loading as a classic script would fail)
  25939. * - the HMR runtime in the browser has the list of all loaded modules
  25940. *
  25941. * https://github.com/webpack/webpack-dev-server/security/advisories/GHSA-4v9v-hfq4-rm2v
  25942. * https://green.sapphi.red/blog/local-server-security-best-practices#_2-using-xssi-and-modifying-the-prototype
  25943. * https://green.sapphi.red/blog/local-server-security-best-practices#properly-check-the-request-origin
  25944. */
  25945. function rejectNoCorsRequestMiddleware() {
  25946. return function viteRejectNoCorsRequestMiddleware(req, res, next) {
  25947. if (req.headers["sec-fetch-mode"] === "no-cors" && req.headers["sec-fetch-site"] !== "same-origin" && req.headers["sec-fetch-dest"] === "script") {
  25948. res.setHeader("Content-Type", "text/javascript");
  25949. res.end(`throw new Error(${JSON.stringify("[Vite] Cross-origin requests for classic scripts must be made with CORS mode enabled. Make sure to set the \"crossorigin\" attribute on your <script> tag.")});`);
  25950. return;
  25951. }
  25952. return next();
  25953. };
  25954. }
  25955. //#endregion
  25956. //#region src/node/server/index.ts
  25957. var import_connect = /* @__PURE__ */ __toESM(require_connect(), 1);
  25958. var import_lib = /* @__PURE__ */ __toESM(require_lib$1(), 1);
  25959. var import_chokidar = /* @__PURE__ */ __toESM(require_chokidar(), 1);
  25960. var import_launch_editor_middleware = /* @__PURE__ */ __toESM(require_launch_editor_middleware(), 1);
  25961. var import_dist = require_dist();
  25962. const usedConfigs = /* @__PURE__ */ new WeakSet();
  25963. async function resolveForwardConsoleOptions(value) {
  25964. value ??= (await (0, import_dist.determineAgent)()).isAgent;
  25965. if (value === false) return {
  25966. enabled: false,
  25967. unhandledErrors: false,
  25968. logLevels: []
  25969. };
  25970. if (value === true) return {
  25971. enabled: true,
  25972. unhandledErrors: true,
  25973. logLevels: ["error", "warn"]
  25974. };
  25975. const unhandledErrors = value.unhandledErrors ?? true;
  25976. const logLevels = value.logLevels ?? [];
  25977. return {
  25978. enabled: unhandledErrors || logLevels.length > 0,
  25979. unhandledErrors,
  25980. logLevels
  25981. };
  25982. }
  25983. function createServer$2(inlineConfig = {}) {
  25984. return _createServer(inlineConfig, { listen: true });
  25985. }
  25986. async function _createServer(inlineConfig = {}, options) {
  25987. const config = isResolvedConfig(inlineConfig) ? inlineConfig : await resolveConfig(inlineConfig, "serve");
  25988. if (usedConfigs.has(config)) throw new Error(`There is already a server associated with the config.`);
  25989. if (config.command !== "serve") throw new Error(`Config was resolved for a "build", expected a "serve" command.`);
  25990. usedConfigs.add(config);
  25991. const initPublicFilesPromise = initPublicFiles(config);
  25992. const { root, server: serverConfig } = config;
  25993. const httpsOptions = await resolveHttpsConfig(config.server.https);
  25994. const { middlewareMode } = serverConfig;
  25995. const resolvedOutDirs = getResolvedOutDirs(config.root, config.build.outDir, config.build.rollupOptions.output);
  25996. const emptyOutDir = resolveEmptyOutDir(config.build.emptyOutDir, config.root, resolvedOutDirs);
  25997. const resolvedWatchOptions = resolveChokidarOptions({
  25998. disableGlobbing: true,
  25999. ...serverConfig.watch
  26000. }, resolvedOutDirs, emptyOutDir, config.cacheDir);
  26001. const middlewares = (0, import_connect.default)();
  26002. const httpServer = middlewareMode ? null : await resolveHttpServer(middlewares, httpsOptions);
  26003. const ws = createWebSocketServer(httpServer, config, httpsOptions);
  26004. const publicFiles = await initPublicFilesPromise;
  26005. const { publicDir } = config;
  26006. if (httpServer) setClientErrorHandler(httpServer, config.logger);
  26007. const watcher = serverConfig.watch !== null ? import_chokidar.watch([
  26008. ...config.experimental.bundledDev ? [] : [root],
  26009. ...config.configFileDependencies,
  26010. ...getEnvFilesForMode(config.mode, config.envDir),
  26011. ...publicDir && publicFiles ? [publicDir] : []
  26012. ], resolvedWatchOptions) : createNoopWatcher(resolvedWatchOptions);
  26013. const environments = {};
  26014. await Promise.all(Object.entries(config.environments).map(async ([name, environmentOptions]) => {
  26015. const environment = await environmentOptions.dev.createEnvironment(name, config, { ws });
  26016. environments[name] = environment;
  26017. await environment.init({
  26018. watcher,
  26019. previousInstance: options.previousEnvironments?.[environment.name]
  26020. });
  26021. }));
  26022. let moduleGraph = new ModuleGraph({
  26023. client: () => environments.client.moduleGraph,
  26024. ssr: () => environments.ssr.moduleGraph
  26025. });
  26026. let pluginContainer = createPluginContainer(environments);
  26027. const closeHttpServer = createServerCloseFn(httpServer);
  26028. const devHtmlTransformFn = createDevHtmlTransformFn(config);
  26029. let closeServerPromise;
  26030. const closeServer = async () => {
  26031. if (!middlewareMode) teardownSIGTERMListener(closeServerAndExit);
  26032. await Promise.allSettled([
  26033. watcher.close(),
  26034. ws.close(),
  26035. Promise.allSettled(Object.values(server.environments).map((environment) => environment.close())),
  26036. closeHttpServer(),
  26037. server._ssrCompatModuleRunner?.close()
  26038. ]);
  26039. server.resolvedUrls = null;
  26040. server._ssrCompatModuleRunner = void 0;
  26041. };
  26042. let hot = ws;
  26043. let server = {
  26044. config,
  26045. middlewares,
  26046. httpServer,
  26047. watcher,
  26048. ws,
  26049. get hot() {
  26050. warnFutureDeprecation(config, "removeServerHot");
  26051. return hot;
  26052. },
  26053. set hot(h) {
  26054. hot = h;
  26055. },
  26056. environments,
  26057. get pluginContainer() {
  26058. warnFutureDeprecation(config, "removeServerPluginContainer");
  26059. return pluginContainer;
  26060. },
  26061. set pluginContainer(p) {
  26062. pluginContainer = p;
  26063. },
  26064. get moduleGraph() {
  26065. warnFutureDeprecation(config, "removeServerModuleGraph");
  26066. return moduleGraph;
  26067. },
  26068. set moduleGraph(graph) {
  26069. moduleGraph = graph;
  26070. },
  26071. resolvedUrls: null,
  26072. ssrTransform(code, inMap, url, originalCode = code) {
  26073. return ssrTransform(code, inMap, url, originalCode, { json: { stringify: config.json.stringify === true && config.json.namedExports !== true } });
  26074. },
  26075. transformRequest(url, options) {
  26076. warnFutureDeprecation(config, "removeServerTransformRequest");
  26077. return server.environments[options?.ssr ? "ssr" : "client"].transformRequest(url);
  26078. },
  26079. warmupRequest(url, options) {
  26080. warnFutureDeprecation(config, "removeServerWarmupRequest");
  26081. return server.environments[options?.ssr ? "ssr" : "client"].warmupRequest(url);
  26082. },
  26083. transformIndexHtml(url, html, originalUrl) {
  26084. return devHtmlTransformFn(server, url, html, originalUrl);
  26085. },
  26086. async ssrLoadModule(url, opts) {
  26087. warnFutureDeprecation(config, "removeSsrLoadModule");
  26088. return ssrLoadModule(url, server, opts?.fixStacktrace);
  26089. },
  26090. ssrFixStacktrace(e) {
  26091. warnFutureDeprecation(config, "removeSsrLoadModule", "ssrFixStacktrace doesn't need to be used for Environment Module Runners.");
  26092. ssrFixStacktrace(e, server.environments.ssr.moduleGraph);
  26093. },
  26094. ssrRewriteStacktrace(stack) {
  26095. warnFutureDeprecation(config, "removeSsrLoadModule", "ssrRewriteStacktrace doesn't need to be used for Environment Module Runners.");
  26096. return ssrRewriteStacktrace(stack, server.environments.ssr.moduleGraph).result;
  26097. },
  26098. async reloadModule(module) {
  26099. warnFutureDeprecation(config, "removeServerReloadModule");
  26100. if (serverConfig.hmr !== false && module.file) {
  26101. const environmentModule = module._clientModule ?? module._ssrModule;
  26102. updateModules(environments[environmentModule.environment], module.file, [environmentModule], monotonicDateNow());
  26103. }
  26104. },
  26105. async listen(port, isRestart) {
  26106. const hostname = await resolveHostname(config.server.host);
  26107. if (httpServer) httpServer.prependListener("listening", () => {
  26108. server.resolvedUrls = resolveServerUrls(httpServer, config.server, hostname, httpsOptions, config);
  26109. });
  26110. await startServer(server, hostname, port);
  26111. if (httpServer) {
  26112. if (!isRestart && config.server.open) server.openBrowser();
  26113. }
  26114. return server;
  26115. },
  26116. openBrowser() {
  26117. const options = server.config.server;
  26118. const url = getServerUrlByHost(server.resolvedUrls, options.host);
  26119. if (url) {
  26120. const path = typeof options.open === "string" ? new URL(options.open, url).href : url;
  26121. if (server.config.server.preTransformRequests) setTimeout(() => {
  26122. (path.startsWith("https:") ? get$1 : get)(path, { headers: { Accept: "text/html" } }, (res) => {
  26123. res.on("end", () => {});
  26124. }).on("error", () => {}).end();
  26125. }, 0);
  26126. openBrowser(path, true, server.config.logger);
  26127. } else server.config.logger.warn("No URL available to open in browser");
  26128. },
  26129. async close() {
  26130. if (!closeServerPromise) closeServerPromise = closeServer();
  26131. return closeServerPromise;
  26132. },
  26133. printUrls() {
  26134. if (server.resolvedUrls) printServerUrls(server.resolvedUrls, serverConfig.host, config.logger.info);
  26135. else if (middlewareMode) throw new Error("cannot print server URLs in middleware mode.");
  26136. else throw new Error("cannot print server URLs before server.listen is called.");
  26137. },
  26138. bindCLIShortcuts(options) {
  26139. bindCLIShortcuts(server, options);
  26140. },
  26141. async restart(forceOptimize) {
  26142. if (!server._restartPromise) {
  26143. server._forceOptimizeOnRestart = !!forceOptimize;
  26144. server._restartPromise = restartServer(server).finally(() => {
  26145. server._restartPromise = null;
  26146. server._forceOptimizeOnRestart = false;
  26147. });
  26148. }
  26149. return server._restartPromise;
  26150. },
  26151. waitForRequestsIdle(ignoredId) {
  26152. return environments.client.waitForRequestsIdle(ignoredId);
  26153. },
  26154. _setInternalServer(_server) {
  26155. server = _server;
  26156. },
  26157. _restartPromise: options.previousRestartPromise ?? null,
  26158. _forceOptimizeOnRestart: options.previousForceOptimizeOnRestart ?? false,
  26159. _shortcutsState: options.previousShortcutsState
  26160. };
  26161. const reflexServer = new Proxy(server, {
  26162. get: (_, property) => {
  26163. return server[property];
  26164. },
  26165. set: (_, property, value) => {
  26166. server[property] = value;
  26167. return true;
  26168. }
  26169. });
  26170. const closeServerAndExit = async (_, exitCode) => {
  26171. try {
  26172. await server.close();
  26173. } finally {
  26174. process.exitCode ??= exitCode ? 128 + exitCode : void 0;
  26175. process.exit();
  26176. }
  26177. };
  26178. if (!middlewareMode) setupSIGTERMListener(closeServerAndExit);
  26179. const onHMRUpdate = async (type, file) => {
  26180. if (serverConfig.hmr !== false) await handleHMRUpdate(type, file, server);
  26181. };
  26182. const onFileAddUnlink = async (file, isUnlink) => {
  26183. file = normalizePath(file);
  26184. reloadOnTsconfigChange(server, file);
  26185. await Promise.all(Object.values(server.environments).map((environment) => environment.pluginContainer.watchChange(file, { event: isUnlink ? "delete" : "create" })));
  26186. if (publicDir && publicFiles) {
  26187. if (file.startsWith(publicDir)) {
  26188. const path = file.slice(publicDir.length);
  26189. publicFiles[isUnlink ? "delete" : "add"](path);
  26190. if (!isUnlink) {
  26191. const clientModuleGraph = server.environments.client.moduleGraph;
  26192. const etag = (await clientModuleGraph.getModuleByUrl(path))?.transformResult?.etag;
  26193. if (etag) clientModuleGraph.etagToModuleMap.delete(etag);
  26194. }
  26195. }
  26196. }
  26197. if (isUnlink) for (const environment of Object.values(server.environments)) environment.moduleGraph.onFileDelete(file);
  26198. await onHMRUpdate(isUnlink ? "delete" : "create", file);
  26199. };
  26200. watcher.on("change", async (file) => {
  26201. file = normalizePath(file);
  26202. reloadOnTsconfigChange(server, file);
  26203. await Promise.all(Object.values(server.environments).map((environment) => environment.pluginContainer.watchChange(file, { event: "update" })));
  26204. for (const environment of Object.values(server.environments)) environment.moduleGraph.onFileChange(file);
  26205. await onHMRUpdate("update", file);
  26206. });
  26207. watcher.on("add", (file) => {
  26208. onFileAddUnlink(file, false);
  26209. });
  26210. watcher.on("unlink", (file) => {
  26211. onFileAddUnlink(file, true);
  26212. });
  26213. if (!middlewareMode && httpServer) httpServer.once("listening", () => {
  26214. serverConfig.port = httpServer.address().port;
  26215. });
  26216. if (process.env.DEBUG) middlewares.use(timeMiddleware(root));
  26217. middlewares.use(rejectInvalidRequestMiddleware());
  26218. middlewares.use(rejectNoCorsRequestMiddleware());
  26219. const { cors } = serverConfig;
  26220. if (cors !== false) middlewares.use((0, import_lib.default)(typeof cors === "boolean" ? {} : cors));
  26221. const { allowedHosts } = serverConfig;
  26222. if (allowedHosts !== true && !serverConfig.https) middlewares.use(hostValidationMiddleware(allowedHosts, false));
  26223. const configureServerContext = new BasicMinimalPluginContext({
  26224. ...basePluginContextMeta,
  26225. watchMode: true
  26226. }, config.logger);
  26227. const postHooks = [];
  26228. for (const hook of config.getSortedPluginHooks("configureServer")) postHooks.push(await hook.call(configureServerContext, reflexServer));
  26229. if (!config.experimental.bundledDev) middlewares.use(cachedTransformMiddleware(server));
  26230. const { proxy } = serverConfig;
  26231. if (proxy) {
  26232. const middlewareServer = (isObject$1(middlewareMode) ? middlewareMode.server : null) || httpServer;
  26233. middlewares.use(proxyMiddleware(middlewareServer, proxy, config));
  26234. }
  26235. if (config.base !== "/") middlewares.use(baseMiddleware(config.rawBase, !!middlewareMode));
  26236. middlewares.use("/__open-in-editor", (0, import_launch_editor_middleware.default)());
  26237. middlewares.use(function viteHMRPingMiddleware(req, res, next) {
  26238. if (req.headers["accept"] === "text/x-vite-ping") res.writeHead(204).end();
  26239. else next();
  26240. });
  26241. if (publicDir) middlewares.use(servePublicMiddleware(server, publicFiles));
  26242. if (config.experimental.bundledDev) middlewares.use(memoryFilesMiddleware(server));
  26243. else {
  26244. middlewares.use(transformMiddleware(server));
  26245. middlewares.use(serveRawFsMiddleware(server));
  26246. middlewares.use(serveStaticMiddleware(server));
  26247. }
  26248. if (config.appType === "spa" || config.appType === "mpa") middlewares.use(htmlFallbackMiddleware(root, config.appType === "spa", server.environments.client));
  26249. postHooks.forEach((fn) => fn && fn());
  26250. if (config.appType === "spa" || config.appType === "mpa") {
  26251. middlewares.use(indexHtmlMiddleware(root, server));
  26252. middlewares.use(notFoundMiddleware());
  26253. }
  26254. middlewares.use(errorMiddleware(server, !!middlewareMode));
  26255. let initingServer;
  26256. let serverInited = false;
  26257. const initServer = async (onListen) => {
  26258. if (serverInited) return;
  26259. if (initingServer) return initingServer;
  26260. initingServer = (async function() {
  26261. if (!config.experimental.bundledDev) await environments.client.pluginContainer.buildStart();
  26262. if (onListen || options.listen) await Promise.all(Object.values(environments).map((e) => e.listen(server)));
  26263. initingServer = void 0;
  26264. serverInited = true;
  26265. })();
  26266. return initingServer;
  26267. };
  26268. if (!middlewareMode && httpServer) {
  26269. const listen = httpServer.listen.bind(httpServer);
  26270. httpServer.listen = (async (port, ...args) => {
  26271. try {
  26272. await initServer(true);
  26273. } catch (e) {
  26274. httpServer.emit("error", e);
  26275. return;
  26276. }
  26277. return listen(port, ...args);
  26278. });
  26279. } else await initServer(false);
  26280. return server;
  26281. }
  26282. async function startServer(server, hostname, inlinePort) {
  26283. const httpServer = server.httpServer;
  26284. if (!httpServer) throw new Error("Cannot call server.listen in middleware mode.");
  26285. const options = server.config.server;
  26286. const configPort = inlinePort ?? options.port;
  26287. const port = (!configPort || configPort === server._configServerPort ? server._currentServerPort : configPort) ?? 5173;
  26288. server._configServerPort = configPort;
  26289. server._currentServerPort = await httpServerStart(httpServer, {
  26290. port,
  26291. strictPort: options.strictPort,
  26292. host: hostname.host,
  26293. logger: server.config.logger
  26294. });
  26295. }
  26296. function createServerCloseFn(server) {
  26297. if (!server) return () => Promise.resolve();
  26298. let hasListened = false;
  26299. const openSockets = /* @__PURE__ */ new Set();
  26300. server.on("connection", (socket) => {
  26301. openSockets.add(socket);
  26302. socket.on("close", () => {
  26303. openSockets.delete(socket);
  26304. });
  26305. });
  26306. server.once("listening", () => {
  26307. hasListened = true;
  26308. });
  26309. return () => new Promise((resolve, reject) => {
  26310. openSockets.forEach((s) => s.destroy());
  26311. if (hasListened) server.close((err) => {
  26312. if (err) reject(err);
  26313. else resolve();
  26314. });
  26315. else resolve();
  26316. });
  26317. }
  26318. function resolvedAllowDir(root, dir) {
  26319. return normalizePath(path.resolve(root, dir));
  26320. }
  26321. const _serverConfigDefaults = Object.freeze({
  26322. port: DEFAULT_DEV_PORT,
  26323. strictPort: false,
  26324. host: "localhost",
  26325. allowedHosts: [],
  26326. https: void 0,
  26327. open: false,
  26328. proxy: void 0,
  26329. cors: { origin: defaultAllowedOrigins },
  26330. headers: {},
  26331. warmup: {
  26332. clientFiles: [],
  26333. ssrFiles: []
  26334. },
  26335. middlewareMode: false,
  26336. fs: {
  26337. strict: true,
  26338. deny: [
  26339. ".env",
  26340. ".env.*",
  26341. "*.{crt,pem}",
  26342. "**/.git/**"
  26343. ]
  26344. },
  26345. preTransformRequests: true,
  26346. perEnvironmentStartEndDuringDev: false,
  26347. perEnvironmentWatchChangeDuringDev: false,
  26348. forwardConsole: void 0
  26349. });
  26350. const serverConfigDefaults = _serverConfigDefaults;
  26351. async function resolveServerOptions(root, raw, logger) {
  26352. const _server = mergeWithDefaults({
  26353. ..._serverConfigDefaults,
  26354. host: void 0,
  26355. sourcemapIgnoreList: isInNodeModules
  26356. }, raw ?? {});
  26357. const server = {
  26358. ..._server,
  26359. fs: {
  26360. ..._server.fs,
  26361. allow: raw?.fs?.allow ?? [searchForWorkspaceRoot(root)]
  26362. },
  26363. sourcemapIgnoreList: _server.sourcemapIgnoreList === false ? () => false : _server.sourcemapIgnoreList,
  26364. forwardConsole: await resolveForwardConsoleOptions(_server.forwardConsole)
  26365. };
  26366. let allowDirs = server.fs.allow;
  26367. if (process.versions.pnp) {
  26368. const cwd = searchForPackageRoot(root);
  26369. try {
  26370. const yarnCacheDir = execSync(`yarn config get ${execSync("yarn config get enableGlobalCache", { cwd }).toString().trim() === "true" ? "globalFolder" : "cacheFolder"}`, { cwd }).toString().trim();
  26371. allowDirs.push(yarnCacheDir);
  26372. } catch (e) {
  26373. logger.warn(`Get yarn cache dir error: ${e.message}`, { timestamp: true });
  26374. }
  26375. }
  26376. allowDirs = allowDirs.map((i) => resolvedAllowDir(root, i));
  26377. const resolvedClientDir = resolvedAllowDir(root, CLIENT_DIR);
  26378. if (!allowDirs.some((dir) => isParentDirectory(dir, resolvedClientDir))) allowDirs.push(resolvedClientDir);
  26379. server.fs.allow = allowDirs;
  26380. if (server.origin?.endsWith("/")) {
  26381. server.origin = server.origin.slice(0, -1);
  26382. logger.warn(import_picocolors.default.yellow(`${import_picocolors.default.bold("(!)")} server.origin should not end with "/". Using "${server.origin}" instead.`));
  26383. }
  26384. if (process.env.__VITE_ADDITIONAL_SERVER_ALLOWED_HOSTS && Array.isArray(server.allowedHosts)) {
  26385. const additionalHost = process.env.__VITE_ADDITIONAL_SERVER_ALLOWED_HOSTS;
  26386. server.allowedHosts = [...server.allowedHosts, additionalHost];
  26387. }
  26388. return server;
  26389. }
  26390. async function restartServer(server) {
  26391. global.__vite_start_time = performance$1.now();
  26392. let inlineConfig = server.config.inlineConfig;
  26393. if (server._forceOptimizeOnRestart) inlineConfig = mergeConfig(inlineConfig, { forceOptimizeDeps: true });
  26394. {
  26395. let newServer = null;
  26396. try {
  26397. newServer = await _createServer(inlineConfig, {
  26398. listen: false,
  26399. previousEnvironments: server.environments,
  26400. previousShortcutsState: server._shortcutsState,
  26401. previousRestartPromise: server._restartPromise,
  26402. previousForceOptimizeOnRestart: server._forceOptimizeOnRestart
  26403. });
  26404. } catch (err) {
  26405. server.config.logger.error(err.message, { timestamp: true });
  26406. server.config.logger.error("server restart failed", { timestamp: true });
  26407. return;
  26408. }
  26409. server._shortcutsState = void 0;
  26410. await server.close();
  26411. const middlewares = server.middlewares;
  26412. newServer._configServerPort = server._configServerPort;
  26413. newServer._currentServerPort = server._currentServerPort;
  26414. Object.assign(server, newServer);
  26415. middlewares.stack = newServer.middlewares.stack;
  26416. server.middlewares = middlewares;
  26417. newServer._setInternalServer(server);
  26418. }
  26419. const { logger, server: { port, middlewareMode } } = server.config;
  26420. if (!middlewareMode) await server.listen(port, true);
  26421. else await Promise.all(Object.values(server.environments).map((e) => e.listen(server)));
  26422. logger.info("server restarted.", { timestamp: true });
  26423. if (server._shortcutsState?.options) bindCLIShortcuts(server, { print: false }, true);
  26424. }
  26425. /**
  26426. * Internal function to restart the Vite server and print URLs if changed
  26427. */
  26428. async function restartServerWithUrls(server) {
  26429. if (server.config.server.middlewareMode) {
  26430. await server.restart();
  26431. return;
  26432. }
  26433. const { port: prevPort, host: prevHost } = server.config.server;
  26434. const prevUrls = server.resolvedUrls;
  26435. await server.restart();
  26436. const { logger, server: { port, host } } = server.config;
  26437. if ((port ?? 5173) !== (prevPort ?? 5173) || host !== prevHost || diffDnsOrderChange(prevUrls, server.resolvedUrls)) {
  26438. logger.info("");
  26439. server.printUrls();
  26440. }
  26441. }
  26442. //#endregion
  26443. //#region src/node/server/hmr.ts
  26444. const debugHmr = createDebugger("vite:hmr");
  26445. const whitespaceRE = /\s/;
  26446. const normalizedClientDir = normalizePath(CLIENT_DIR);
  26447. function getShortName(file, root) {
  26448. return file.startsWith(withTrailingSlash(root)) ? path.posix.relative(root, file) : file;
  26449. }
  26450. const normalizeHotChannel = (channel, enableHmr, normalizeClient = true) => {
  26451. const normalizedListenerMap = /* @__PURE__ */ new WeakMap();
  26452. const normalizedClients = /* @__PURE__ */ new WeakMap();
  26453. let invokeHandlers;
  26454. let listenerForInvokeHandler;
  26455. const handleInvoke = async (payload) => {
  26456. if (!invokeHandlers) return { error: {
  26457. name: "TransportError",
  26458. message: "invokeHandlers is not set",
  26459. stack: (/* @__PURE__ */ new Error()).stack
  26460. } };
  26461. const { name, data: args } = payload.data;
  26462. try {
  26463. const invokeHandler = invokeHandlers[name];
  26464. return { result: await invokeHandler(...args) };
  26465. } catch (error) {
  26466. return { error: {
  26467. name: error.name,
  26468. message: error.message,
  26469. stack: error.stack,
  26470. ...error
  26471. } };
  26472. }
  26473. };
  26474. return {
  26475. ...channel,
  26476. on: (event, fn) => {
  26477. if (event === "connection" || !normalizeClient) {
  26478. channel.on?.(event, fn);
  26479. return;
  26480. }
  26481. const listenerWithNormalizedClient = (data, client) => {
  26482. if (!normalizedClients.has(client)) normalizedClients.set(client, { send: (...args) => {
  26483. let payload;
  26484. if (typeof args[0] === "string") payload = {
  26485. type: "custom",
  26486. event: args[0],
  26487. data: args[1]
  26488. };
  26489. else payload = args[0];
  26490. client.send(payload);
  26491. } });
  26492. fn(data, normalizedClients.get(client));
  26493. };
  26494. normalizedListenerMap.set(fn, listenerWithNormalizedClient);
  26495. channel.on?.(event, listenerWithNormalizedClient);
  26496. },
  26497. off: (event, fn) => {
  26498. if (event === "connection" || !normalizeClient) {
  26499. channel.off?.(event, fn);
  26500. return;
  26501. }
  26502. const normalizedListener = normalizedListenerMap.get(fn);
  26503. if (normalizedListener) channel.off?.(event, normalizedListener);
  26504. },
  26505. setInvokeHandler(_invokeHandlers) {
  26506. invokeHandlers = _invokeHandlers;
  26507. if (!_invokeHandlers) {
  26508. if (listenerForInvokeHandler) channel.off?.("vite:invoke", listenerForInvokeHandler);
  26509. return;
  26510. }
  26511. listenerForInvokeHandler = async (payload, client) => {
  26512. const responseInvoke = payload.id.replace("send", "response");
  26513. client.send({
  26514. type: "custom",
  26515. event: "vite:invoke",
  26516. data: {
  26517. name: payload.name,
  26518. id: responseInvoke,
  26519. data: await handleInvoke({
  26520. type: "custom",
  26521. event: "vite:invoke",
  26522. data: payload
  26523. })
  26524. }
  26525. });
  26526. };
  26527. channel.on?.("vite:invoke", listenerForInvokeHandler);
  26528. },
  26529. handleInvoke,
  26530. send: (...args) => {
  26531. let payload;
  26532. if (typeof args[0] === "string") payload = {
  26533. type: "custom",
  26534. event: args[0],
  26535. data: args[1]
  26536. };
  26537. else payload = args[0];
  26538. if (enableHmr || payload.type === "connected" || payload.type === "ping" || payload.type === "custom" || payload.type === "error") channel.send?.(payload);
  26539. },
  26540. listen() {
  26541. return channel.listen?.();
  26542. },
  26543. close() {
  26544. return channel.close?.();
  26545. }
  26546. };
  26547. };
  26548. function getSortedPluginsByHotUpdateHook(plugins) {
  26549. const sortedPlugins = [];
  26550. let pre = 0, normal = 0, post = 0;
  26551. for (const plugin of plugins) {
  26552. const hook = plugin["hotUpdate"] ?? plugin["handleHotUpdate"];
  26553. if (hook) {
  26554. if (typeof hook === "object") {
  26555. if (hook.order === "pre") {
  26556. sortedPlugins.splice(pre++, 0, plugin);
  26557. continue;
  26558. }
  26559. if (hook.order === "post") {
  26560. sortedPlugins.splice(pre + normal + post++, 0, plugin);
  26561. continue;
  26562. }
  26563. }
  26564. sortedPlugins.splice(pre + normal++, 0, plugin);
  26565. }
  26566. }
  26567. return sortedPlugins;
  26568. }
  26569. const sortedHotUpdatePluginsCache = /* @__PURE__ */ new WeakMap();
  26570. function getSortedHotUpdatePlugins(environment) {
  26571. let sortedPlugins = sortedHotUpdatePluginsCache.get(environment);
  26572. if (!sortedPlugins) {
  26573. sortedPlugins = getSortedPluginsByHotUpdateHook(environment.plugins);
  26574. sortedHotUpdatePluginsCache.set(environment, sortedPlugins);
  26575. }
  26576. return sortedPlugins;
  26577. }
  26578. async function handleHMRUpdate(type, file, server) {
  26579. const { config } = server;
  26580. const mixedModuleGraph = ignoreDeprecationWarnings(() => server.moduleGraph);
  26581. const environments = Object.values(server.environments);
  26582. const shortFile = getShortName(file, config.root);
  26583. const isConfig = file === config.configFile;
  26584. const isConfigDependency = config.configFileDependencies.some((name) => file === name);
  26585. const isEnv = config.envDir !== false && getEnvFilesForMode(config.mode, config.envDir).includes(file);
  26586. if (isConfig || isConfigDependency || isEnv) {
  26587. debugHmr?.(`[config change] ${import_picocolors.default.dim(shortFile)}`);
  26588. config.logger.info(import_picocolors.default.green(`${normalizePath(path.relative(process.cwd(), file))} changed, restarting server...`), {
  26589. clear: true,
  26590. timestamp: true
  26591. });
  26592. try {
  26593. await restartServerWithUrls(server);
  26594. } catch (e) {
  26595. config.logger.error(import_picocolors.default.red(e));
  26596. }
  26597. return;
  26598. }
  26599. debugHmr?.(`[file change] ${import_picocolors.default.dim(shortFile)}`);
  26600. if (file.startsWith(withTrailingSlash(normalizedClientDir))) {
  26601. environments.forEach(({ hot }) => hot.send({
  26602. type: "full-reload",
  26603. path: "*",
  26604. triggeredBy: path.resolve(config.root, file)
  26605. }));
  26606. return;
  26607. }
  26608. if (config.experimental.bundledDev) return;
  26609. const timestamp = monotonicDateNow();
  26610. const contextMeta = {
  26611. type,
  26612. file,
  26613. timestamp,
  26614. read: () => readModifiedFile(file),
  26615. server
  26616. };
  26617. const hotMap = /* @__PURE__ */ new Map();
  26618. for (const environment of Object.values(server.environments)) {
  26619. const mods = new Set(environment.moduleGraph.getModulesByFile(file));
  26620. if (type === "create") for (const mod of environment.moduleGraph._hasResolveFailedErrorModules) mods.add(mod);
  26621. const options = {
  26622. ...contextMeta,
  26623. modules: [...mods]
  26624. };
  26625. hotMap.set(environment, { options });
  26626. }
  26627. const mixedMods = new Set(mixedModuleGraph.getModulesByFile(file));
  26628. const mixedHmrContext = {
  26629. ...contextMeta,
  26630. modules: [...mixedMods]
  26631. };
  26632. const contextForHandleHotUpdate = new BasicMinimalPluginContext({
  26633. ...basePluginContextMeta,
  26634. watchMode: true
  26635. }, config.logger);
  26636. const clientEnvironment = server.environments.client;
  26637. const ssrEnvironment = server.environments.ssr;
  26638. const clientContext = clientEnvironment.pluginContainer.minimalContext;
  26639. const clientHotUpdateOptions = hotMap.get(clientEnvironment).options;
  26640. const ssrHotUpdateOptions = hotMap.get(ssrEnvironment)?.options;
  26641. try {
  26642. for (const plugin of getSortedHotUpdatePlugins(server.environments.client)) if (plugin.hotUpdate) {
  26643. const filteredModules = await getHookHandler(plugin.hotUpdate).call(clientContext, clientHotUpdateOptions);
  26644. if (filteredModules) {
  26645. clientHotUpdateOptions.modules = filteredModules;
  26646. mixedHmrContext.modules = mixedHmrContext.modules.filter((mixedMod) => filteredModules.some((mod) => mixedMod.id === mod.id) || ssrHotUpdateOptions?.modules.some((ssrMod) => ssrMod.id === mixedMod.id));
  26647. mixedHmrContext.modules.push(...filteredModules.filter((mod) => !mixedHmrContext.modules.some((mixedMod) => mixedMod.id === mod.id)).map((mod) => mixedModuleGraph.getBackwardCompatibleModuleNode(mod)));
  26648. }
  26649. } else if (type === "update") {
  26650. warnFutureDeprecation(config, "removePluginHookHandleHotUpdate", `Used in plugin "${plugin.name}".`, false);
  26651. const filteredModules = await getHookHandler(plugin.handleHotUpdate).call(contextForHandleHotUpdate, mixedHmrContext);
  26652. if (filteredModules) {
  26653. mixedHmrContext.modules = filteredModules;
  26654. clientHotUpdateOptions.modules = clientHotUpdateOptions.modules.filter((mod) => filteredModules.some((mixedMod) => mod.id === mixedMod.id));
  26655. clientHotUpdateOptions.modules.push(...filteredModules.filter((mixedMod) => !clientHotUpdateOptions.modules.some((mod) => mod.id === mixedMod.id)).map((mixedMod) => mixedMod._clientModule).filter(Boolean));
  26656. if (ssrHotUpdateOptions) {
  26657. ssrHotUpdateOptions.modules = ssrHotUpdateOptions.modules.filter((mod) => filteredModules.some((mixedMod) => mod.id === mixedMod.id));
  26658. ssrHotUpdateOptions.modules.push(...filteredModules.filter((mixedMod) => !ssrHotUpdateOptions.modules.some((mod) => mod.id === mixedMod.id)).map((mixedMod) => mixedMod._ssrModule).filter(Boolean));
  26659. }
  26660. }
  26661. }
  26662. } catch (error) {
  26663. hotMap.get(server.environments.client).error = error;
  26664. }
  26665. for (const environment of Object.values(server.environments)) {
  26666. if (environment.name === "client") continue;
  26667. const hot = hotMap.get(environment);
  26668. const context = environment.pluginContainer.minimalContext;
  26669. try {
  26670. for (const plugin of getSortedHotUpdatePlugins(environment)) if (plugin.hotUpdate) {
  26671. const filteredModules = await getHookHandler(plugin.hotUpdate).call(context, hot.options);
  26672. if (filteredModules) hot.options.modules = filteredModules;
  26673. }
  26674. } catch (error) {
  26675. hot.error = error;
  26676. }
  26677. }
  26678. async function hmr(environment) {
  26679. try {
  26680. const { options, error } = hotMap.get(environment);
  26681. if (error) throw error;
  26682. if (!options.modules.length) {
  26683. if (file.endsWith(".html") && environment.name === "client") {
  26684. environment.logger.info(import_picocolors.default.green(`page reload `) + import_picocolors.default.dim(shortFile), {
  26685. clear: true,
  26686. timestamp: true
  26687. });
  26688. environment.hot.send({
  26689. type: "full-reload",
  26690. path: config.server.middlewareMode ? "*" : "/" + normalizePath(path.relative(config.root, file))
  26691. });
  26692. } else debugHmr?.(`(${environment.name}) [no modules matched] ${import_picocolors.default.dim(shortFile)}`);
  26693. return;
  26694. }
  26695. updateModules(environment, shortFile, options.modules, timestamp);
  26696. } catch (err) {
  26697. environment.hot.send({
  26698. type: "error",
  26699. err: prepareError(err)
  26700. });
  26701. }
  26702. }
  26703. await (server.config.server.hotUpdateEnvironments ?? ((server, hmr) => {
  26704. return Promise.all(Object.values(server.environments).map((environment) => hmr(environment)));
  26705. }))(server, hmr);
  26706. }
  26707. function updateModules(environment, file, modules, timestamp, firstInvalidatedBy) {
  26708. const { hot } = environment;
  26709. const updates = [];
  26710. const invalidatedModules = /* @__PURE__ */ new Set();
  26711. const traversedModules = /* @__PURE__ */ new Set();
  26712. let needFullReload = modules.length === 0;
  26713. for (const mod of modules) {
  26714. const boundaries = [];
  26715. const hasDeadEnd = propagateUpdate(mod, traversedModules, boundaries);
  26716. environment.moduleGraph.invalidateModule(mod, invalidatedModules, timestamp, true);
  26717. if (needFullReload) continue;
  26718. if (hasDeadEnd) {
  26719. needFullReload = hasDeadEnd;
  26720. continue;
  26721. }
  26722. if (firstInvalidatedBy && boundaries.some(({ acceptedVia }) => normalizeHmrUrl(acceptedVia.url) === firstInvalidatedBy)) {
  26723. needFullReload = "circular import invalidate";
  26724. continue;
  26725. }
  26726. updates.push(...boundaries.map(({ boundary, acceptedVia, isWithinCircularImport }) => ({
  26727. type: `${boundary.type}-update`,
  26728. timestamp,
  26729. path: normalizeHmrUrl(boundary.url),
  26730. acceptedPath: normalizeHmrUrl(acceptedVia.url),
  26731. explicitImportRequired: boundary.type === "js" ? isExplicitImportRequired(acceptedVia.url) : false,
  26732. isWithinCircularImport,
  26733. firstInvalidatedBy
  26734. })));
  26735. }
  26736. const isClientHtmlChange = file.endsWith(".html") && environment.name === "client" && modules.every((mod) => mod.type !== "js");
  26737. if (needFullReload || isClientHtmlChange) {
  26738. const reason = typeof needFullReload === "string" ? import_picocolors.default.dim(` (${needFullReload})`) : "";
  26739. environment.logger.info(import_picocolors.default.green(`page reload `) + import_picocolors.default.dim(file) + reason, {
  26740. clear: !firstInvalidatedBy,
  26741. timestamp: true
  26742. });
  26743. hot.send({
  26744. type: "full-reload",
  26745. triggeredBy: path.resolve(environment.config.root, file),
  26746. path: !isClientHtmlChange || environment.config.server.middlewareMode || updates.length > 0 ? "*" : "/" + file
  26747. });
  26748. return;
  26749. }
  26750. if (updates.length === 0) {
  26751. debugHmr?.(import_picocolors.default.yellow(`no update happened `) + import_picocolors.default.dim(file));
  26752. return;
  26753. }
  26754. const filePaths = [...new Set(updates.map((u) => u.path))];
  26755. const { formatted, truncated } = formatAndTruncateFileList(filePaths);
  26756. if (truncated) debugHmr?.(`hmr update ${filePaths.join(", ")}`);
  26757. environment.logger.info(import_picocolors.default.green(`hmr update `) + import_picocolors.default.dim(formatted), {
  26758. clear: !firstInvalidatedBy,
  26759. timestamp: true
  26760. });
  26761. hot.send({
  26762. type: "update",
  26763. updates
  26764. });
  26765. }
  26766. function areAllImportsAccepted(importedBindings, acceptedExports) {
  26767. for (const binding of importedBindings) if (!acceptedExports.has(binding)) return false;
  26768. return true;
  26769. }
  26770. function propagateUpdate(node, traversedModules, boundaries, currentChain = [node]) {
  26771. if (traversedModules.has(node)) return false;
  26772. traversedModules.add(node);
  26773. if (node.id && node.isSelfAccepting === void 0) {
  26774. debugHmr?.(`[propagate update] stop propagation because not analyzed: ${import_picocolors.default.dim(node.id)}`);
  26775. return false;
  26776. }
  26777. if (node.isSelfAccepting) {
  26778. const boundary = node;
  26779. boundaries.push({
  26780. boundary,
  26781. acceptedVia: boundary,
  26782. isWithinCircularImport: isNodeWithinCircularImports(node, currentChain)
  26783. });
  26784. return false;
  26785. }
  26786. if (node.acceptedHmrExports) {
  26787. const boundary = node;
  26788. boundaries.push({
  26789. boundary,
  26790. acceptedVia: boundary,
  26791. isWithinCircularImport: isNodeWithinCircularImports(node, currentChain)
  26792. });
  26793. } else if (!node.importers.size) return true;
  26794. for (const importer of node.importers) {
  26795. const subChain = currentChain.concat(importer);
  26796. if (importer.acceptedHmrDeps.has(node)) {
  26797. boundaries.push({
  26798. boundary: importer,
  26799. acceptedVia: node,
  26800. isWithinCircularImport: isNodeWithinCircularImports(importer, subChain)
  26801. });
  26802. continue;
  26803. }
  26804. if (node.id && node.acceptedHmrExports && importer.importedBindings) {
  26805. const importedBindingsFromNode = importer.importedBindings.get(node.id);
  26806. if (importedBindingsFromNode && areAllImportsAccepted(importedBindingsFromNode, node.acceptedHmrExports)) continue;
  26807. }
  26808. if (!currentChain.includes(importer) && propagateUpdate(importer, traversedModules, boundaries, subChain)) return true;
  26809. }
  26810. return false;
  26811. }
  26812. /**
  26813. * Check importers recursively if it's an import loop. An accepted module within
  26814. * an import loop cannot recover its execution order and should be reloaded.
  26815. *
  26816. * @param node The node that accepts HMR and is a boundary
  26817. * @param nodeChain The chain of nodes/imports that lead to the node.
  26818. * (The last node in the chain imports the `node` parameter)
  26819. * @param currentChain The current chain tracked from the `node` parameter
  26820. * @param traversedModules The set of modules that have traversed
  26821. */
  26822. function isNodeWithinCircularImports(node, nodeChain, currentChain = [node], traversedModules = /* @__PURE__ */ new Set()) {
  26823. if (traversedModules.has(node)) return false;
  26824. traversedModules.add(node);
  26825. for (const importer of node.importers) {
  26826. if (importer === node) continue;
  26827. const importerIndex = nodeChain.indexOf(importer);
  26828. if (importerIndex > -1) {
  26829. if (debugHmr) {
  26830. const importChain = [
  26831. importer,
  26832. ...[...currentChain].reverse(),
  26833. ...nodeChain.slice(importerIndex, -1).reverse()
  26834. ];
  26835. debugHmr(import_picocolors.default.yellow(`circular imports detected: `) + importChain.map((m) => import_picocolors.default.dim(m.url)).join(" -> "));
  26836. }
  26837. return true;
  26838. }
  26839. if (!currentChain.includes(importer)) {
  26840. const result = isNodeWithinCircularImports(importer, nodeChain, currentChain.concat(importer), traversedModules);
  26841. if (result) return result;
  26842. }
  26843. }
  26844. return false;
  26845. }
  26846. function handlePrunedModules(mods, { hot }) {
  26847. const t = monotonicDateNow();
  26848. mods.forEach((mod) => {
  26849. mod.lastHMRTimestamp = t;
  26850. mod.lastHMRInvalidationReceived = false;
  26851. debugHmr?.(`[dispose] ${import_picocolors.default.dim(mod.file)}`);
  26852. });
  26853. hot.send({
  26854. type: "prune",
  26855. paths: [...mods].map((m) => m.url)
  26856. });
  26857. }
  26858. var LexerState = /* @__PURE__ */ function(LexerState) {
  26859. LexerState[LexerState["inCall"] = 0] = "inCall";
  26860. LexerState[LexerState["inSingleQuoteString"] = 1] = "inSingleQuoteString";
  26861. LexerState[LexerState["inDoubleQuoteString"] = 2] = "inDoubleQuoteString";
  26862. LexerState[LexerState["inTemplateString"] = 3] = "inTemplateString";
  26863. LexerState[LexerState["inArray"] = 4] = "inArray";
  26864. return LexerState;
  26865. }(LexerState || {});
  26866. /**
  26867. * Lex import.meta.hot.accept() for accepted deps.
  26868. * Since hot.accept() can only accept string literals or array of string
  26869. * literals, we don't really need a heavy @babel/parse call on the entire source.
  26870. *
  26871. * @returns selfAccepts
  26872. */
  26873. function lexAcceptedHmrDeps(code, start, urls) {
  26874. let state = LexerState.inCall;
  26875. let prevState = LexerState.inCall;
  26876. let currentDep = "";
  26877. function addDep(index) {
  26878. urls.add({
  26879. url: currentDep,
  26880. start: index - currentDep.length - 1,
  26881. end: index + 1
  26882. });
  26883. currentDep = "";
  26884. }
  26885. for (let i = start; i < code.length; i++) {
  26886. const char = code.charAt(i);
  26887. switch (state) {
  26888. case LexerState.inCall:
  26889. case LexerState.inArray:
  26890. if (char === `'`) {
  26891. prevState = state;
  26892. state = LexerState.inSingleQuoteString;
  26893. } else if (char === `"`) {
  26894. prevState = state;
  26895. state = LexerState.inDoubleQuoteString;
  26896. } else if (char === "`") {
  26897. prevState = state;
  26898. state = LexerState.inTemplateString;
  26899. } else if (whitespaceRE.test(char)) continue;
  26900. else if (state === LexerState.inCall) if (char === `[`) state = LexerState.inArray;
  26901. else return true;
  26902. else if (char === `]`) return false;
  26903. else if (char === ",") continue;
  26904. else error(i);
  26905. break;
  26906. case LexerState.inSingleQuoteString:
  26907. if (char === `'`) {
  26908. addDep(i);
  26909. if (prevState === LexerState.inCall) return false;
  26910. else state = prevState;
  26911. } else currentDep += char;
  26912. break;
  26913. case LexerState.inDoubleQuoteString:
  26914. if (char === `"`) {
  26915. addDep(i);
  26916. if (prevState === LexerState.inCall) return false;
  26917. else state = prevState;
  26918. } else currentDep += char;
  26919. break;
  26920. case LexerState.inTemplateString:
  26921. if (char === "`") {
  26922. addDep(i);
  26923. if (prevState === LexerState.inCall) return false;
  26924. else state = prevState;
  26925. } else if (char === "$" && code.charAt(i + 1) === "{") error(i);
  26926. else currentDep += char;
  26927. break;
  26928. default: throw new Error("unknown import.meta.hot lexer state");
  26929. }
  26930. }
  26931. return false;
  26932. }
  26933. function lexAcceptedHmrExports(code, start, exportNames) {
  26934. const urls = /* @__PURE__ */ new Set();
  26935. lexAcceptedHmrDeps(code, start, urls);
  26936. for (const { url } of urls) exportNames.add(url);
  26937. return urls.size > 0;
  26938. }
  26939. function normalizeHmrUrl(url) {
  26940. if (url[0] !== "." && url[0] !== "/") url = wrapId(url);
  26941. return url;
  26942. }
  26943. function error(pos) {
  26944. const err = /* @__PURE__ */ new Error("import.meta.hot.accept() can only accept string literals or an Array of string literals.");
  26945. err.pos = pos;
  26946. throw err;
  26947. }
  26948. async function readModifiedFile(file) {
  26949. const content = await fsp.readFile(file, "utf-8");
  26950. if (!content) {
  26951. const mtime = (await fsp.stat(file)).mtimeMs;
  26952. for (let n = 0; n < 10; n++) {
  26953. await new Promise((r) => setTimeout(r, 10));
  26954. if ((await fsp.stat(file)).mtimeMs !== mtime) break;
  26955. }
  26956. return await fsp.readFile(file, "utf-8");
  26957. } else return content;
  26958. }
  26959. function createServerHotChannel() {
  26960. const innerEmitter = new EventEmitter();
  26961. const outsideEmitter = new EventEmitter();
  26962. return {
  26963. skipFsCheck: true,
  26964. send(payload) {
  26965. outsideEmitter.emit("send", payload);
  26966. },
  26967. off(event, listener) {
  26968. innerEmitter.off(event, listener);
  26969. },
  26970. on: ((event, listener) => {
  26971. innerEmitter.on(event, listener);
  26972. }),
  26973. close() {
  26974. innerEmitter.removeAllListeners();
  26975. outsideEmitter.removeAllListeners();
  26976. },
  26977. listen() {
  26978. innerEmitter.emit("connection");
  26979. },
  26980. api: {
  26981. innerEmitter,
  26982. outsideEmitter
  26983. }
  26984. };
  26985. }
  26986. //#endregion
  26987. //#region src/node/external.ts
  26988. const debug$5 = createDebugger("vite:external");
  26989. const isExternalCache = /* @__PURE__ */ new WeakMap();
  26990. function shouldExternalize(environment, id, importer) {
  26991. let isExternal = isExternalCache.get(environment);
  26992. if (!isExternal) {
  26993. isExternal = createIsExternal(environment);
  26994. isExternalCache.set(environment, isExternal);
  26995. }
  26996. return isExternal(id, importer);
  26997. }
  26998. function createIsConfiguredAsExternal(environment) {
  26999. const { config } = environment;
  27000. const { root, resolve } = config;
  27001. const { external, noExternal } = resolve;
  27002. const noExternalFilter = typeof noExternal !== "boolean" && !(Array.isArray(noExternal) && noExternal.length === 0) && createFilter$1(void 0, noExternal, { resolve: false });
  27003. const targetConditions = resolve.externalConditions;
  27004. const resolveOptions = {
  27005. ...resolve,
  27006. root,
  27007. isProduction: false,
  27008. isBuild: true,
  27009. conditions: targetConditions
  27010. };
  27011. const isExternalizable = (id, importer, configuredAsExternal) => {
  27012. if (!bareImportRE.test(id) || id.includes("\0")) return false;
  27013. try {
  27014. const resolved = tryNodeResolve(id, config.command === "build" ? void 0 : importer, resolveOptions, void 0, false);
  27015. if (!resolved) return false;
  27016. if (!configuredAsExternal && !isInNodeModules(resolved.id)) return false;
  27017. return canExternalizeFile(resolved.id);
  27018. } catch {
  27019. debug$5?.(`Failed to node resolve "${id}". Skipping externalizing it by default.`);
  27020. return false;
  27021. }
  27022. };
  27023. return (id, importer) => {
  27024. if (external !== true && external.includes(id)) return true;
  27025. const pkgName = getNpmPackageName(id);
  27026. if (!pkgName) return isExternalizable(id, importer, false);
  27027. if (external !== true && external.includes(pkgName)) return isExternalizable(id, importer, true);
  27028. if (typeof noExternal === "boolean") return !noExternal;
  27029. if (noExternalFilter && !noExternalFilter(pkgName)) return false;
  27030. return isExternalizable(id, importer, external === true);
  27031. };
  27032. }
  27033. function createIsExternal(environment) {
  27034. const processedIds = /* @__PURE__ */ new Map();
  27035. const isConfiguredAsExternal = createIsConfiguredAsExternal(environment);
  27036. return (id, importer) => {
  27037. if (processedIds.has(id)) return processedIds.get(id);
  27038. let isExternal = false;
  27039. if (id[0] !== "." && !path.isAbsolute(id)) isExternal = isBuiltin(environment.config.resolve.builtins, id) || isConfiguredAsExternal(id, importer);
  27040. processedIds.set(id, isExternal);
  27041. return isExternal;
  27042. };
  27043. }
  27044. function canExternalizeFile(filePath) {
  27045. const ext = path.extname(filePath);
  27046. return !ext || ext === ".js" || ext === ".mjs" || ext === ".cjs";
  27047. }
  27048. //#endregion
  27049. //#region src/node/plugins/worker.ts
  27050. var WorkerOutputCache = class {
  27051. /**
  27052. * worker bundle information for each input id
  27053. * used to bundle the same worker file only once
  27054. */
  27055. bundles = /* @__PURE__ */ new Map();
  27056. /** list of assets emitted for the worker bundles */
  27057. assets = /* @__PURE__ */ new Map();
  27058. fileNameHash = /* @__PURE__ */ new Map();
  27059. invalidatedBundles = /* @__PURE__ */ new Set();
  27060. saveWorkerBundle(file, watchedFiles, outputEntryFilename, outputEntryCode, outputAssets, logger) {
  27061. for (const asset of outputAssets) this.saveAsset(asset, logger);
  27062. const bundle = {
  27063. entryFilename: outputEntryFilename,
  27064. entryCode: outputEntryCode,
  27065. entryUrlPlaceholder: this.generateEntryUrlPlaceholder(outputEntryFilename),
  27066. referencedAssets: new Set(outputAssets.map((asset) => asset.fileName)),
  27067. watchedFiles
  27068. };
  27069. this.bundles.set(file, bundle);
  27070. return bundle;
  27071. }
  27072. saveAsset(asset, logger) {
  27073. const duplicateAsset = this.assets.get(asset.fileName);
  27074. if (duplicateAsset) {
  27075. if (!isSameContent(duplicateAsset.source, asset.source)) logger.warn(`\n` + import_picocolors.default.yellow(`The emitted file ${JSON.stringify(asset.fileName)} overwrites a previously emitted file of the same name.`));
  27076. }
  27077. this.assets.set(asset.fileName, asset);
  27078. }
  27079. invalidateAffectedBundles(file) {
  27080. for (const [bundleInputFile, bundle] of this.bundles.entries()) if (bundle.watchedFiles.includes(file)) this.invalidatedBundles.add(bundleInputFile);
  27081. }
  27082. removeBundleIfInvalidated(file) {
  27083. if (this.invalidatedBundles.has(file)) {
  27084. this.invalidatedBundles.delete(file);
  27085. this.removeBundle(file);
  27086. }
  27087. }
  27088. removeBundle(file) {
  27089. const bundle = this.bundles.get(file);
  27090. if (!bundle) return;
  27091. this.bundles.delete(file);
  27092. this.fileNameHash.delete(getHash(bundle.entryFilename));
  27093. this.assets.delete(bundle.entryFilename);
  27094. const keptBundles = [...this.bundles.values()];
  27095. for (const asset of bundle.referencedAssets) if (keptBundles.every((b) => !b.referencedAssets.has(asset))) this.assets.delete(asset);
  27096. }
  27097. getWorkerBundle(file) {
  27098. return this.bundles.get(file);
  27099. }
  27100. getAssets() {
  27101. return this.assets.values();
  27102. }
  27103. getEntryFilenameFromHash(hash) {
  27104. return this.fileNameHash.get(hash);
  27105. }
  27106. generateEntryUrlPlaceholder(entryFilename) {
  27107. const hash = getHash(entryFilename);
  27108. if (!this.fileNameHash.has(hash)) this.fileNameHash.set(hash, entryFilename);
  27109. return `__VITE_WORKER_ASSET__${hash}__`;
  27110. }
  27111. };
  27112. const workerOrSharedWorkerRE = /(?:\?|&)(worker|sharedworker)(?:&|$)/;
  27113. const workerFileRE = /(?:\?|&)worker_file&type=(\w+)(?:&|$)/;
  27114. const inlineRE = /[?&]inline\b/;
  27115. const WORKER_FILE_ID = "worker_file";
  27116. const workerOutputCaches = /* @__PURE__ */ new WeakMap();
  27117. async function bundleWorkerEntry(config, id) {
  27118. const input = cleanUrl(id);
  27119. const workerOutput = workerOutputCaches.get(config.mainConfig || config);
  27120. workerOutput.removeBundleIfInvalidated(input);
  27121. const bundleInfo = workerOutput.getWorkerBundle(input);
  27122. if (bundleInfo) return bundleInfo;
  27123. const newBundleChain = [...config.bundleChain, input];
  27124. if (config.bundleChain.includes(input)) throw new Error(`Circular worker imports detected. Vite does not support it. Import chain: ${newBundleChain.map((id) => prettifyUrl(id, config.root)).join(" -> ")}`);
  27125. const { rolldown } = await import("rolldown");
  27126. const { plugins, rollupOptions, format } = config.worker;
  27127. const workerEnvironment = new BuildEnvironment("client", await plugins(newBundleChain));
  27128. await workerEnvironment.init();
  27129. const chunkMetadataMap = new ChunkMetadataMap();
  27130. const bundle = await rolldown({
  27131. ...rollupOptions,
  27132. input,
  27133. plugins: workerEnvironment.plugins.map((p) => injectEnvironmentToHooks(workerEnvironment, chunkMetadataMap, p)),
  27134. onLog(level, log) {
  27135. onRollupLog(level, log, workerEnvironment);
  27136. },
  27137. moduleTypes: {
  27138. ".css": "js",
  27139. ...rollupOptions.moduleTypes
  27140. },
  27141. preserveEntrySignatures: false,
  27142. experimental: {
  27143. ...rollupOptions.experimental,
  27144. viteMode: true
  27145. }
  27146. });
  27147. let result;
  27148. let watchedFiles;
  27149. try {
  27150. const workerOutputConfig = config.worker.rollupOptions.output;
  27151. const workerConfig = workerOutputConfig ? Array.isArray(workerOutputConfig) ? workerOutputConfig[0] || {} : workerOutputConfig : {};
  27152. result = await bundle.generate({
  27153. entryFileNames: path.posix.join(config.build.assetsDir, "[name]-[hash].js"),
  27154. chunkFileNames: path.posix.join(config.build.assetsDir, "[name]-[hash].js"),
  27155. assetFileNames: path.posix.join(config.build.assetsDir, "[name]-[hash].[ext]"),
  27156. minify: workerEnvironment.config.build.minify === "oxc" ? true : workerEnvironment.config.build.minify === false ? "dce-only" : void 0,
  27157. ...workerConfig,
  27158. format,
  27159. sourcemap: workerEnvironment.config.build.sourcemap
  27160. });
  27161. watchedFiles = (await bundle.watchFiles).map((f) => normalizePath(f));
  27162. } catch (e) {
  27163. if (e instanceof Error && e.name === "RollupError" && e.code === "INVALID_OPTION" && e.message.includes("\"output.format\"")) e.message = e.message.replace("output.format", "worker.format");
  27164. throw e;
  27165. } finally {
  27166. await bundle.close();
  27167. }
  27168. const { output: [outputChunk, ...outputChunks] } = result;
  27169. const assets = outputChunks.map((outputChunk) => outputChunk.type === "asset" ? outputChunk : {
  27170. fileName: outputChunk.fileName,
  27171. originalFileName: null,
  27172. originalFileNames: [],
  27173. source: outputChunk.code
  27174. });
  27175. if ((config.build.sourcemap === "hidden" || config.build.sourcemap === true) && outputChunk.map) assets.push({
  27176. fileName: outputChunk.fileName + ".map",
  27177. originalFileName: null,
  27178. originalFileNames: [],
  27179. source: outputChunk.map.toString()
  27180. });
  27181. return workerOutputCaches.get(config.mainConfig || config).saveWorkerBundle(input, watchedFiles, outputChunk.fileName, outputChunk.code, assets, config.logger);
  27182. }
  27183. const workerAssetUrlRE = /__VITE_WORKER_ASSET__([a-z\d]{8})__/g;
  27184. async function workerFileToUrl(config, id) {
  27185. const workerOutput = workerOutputCaches.get(config.mainConfig || config);
  27186. const bundle = await bundleWorkerEntry(config, id);
  27187. workerOutput.saveAsset({
  27188. fileName: bundle.entryFilename,
  27189. originalFileName: null,
  27190. originalFileNames: [],
  27191. source: bundle.entryCode
  27192. }, config.logger);
  27193. return bundle;
  27194. }
  27195. function webWorkerPostPlugin(config) {
  27196. if (config.isBundled) return perEnvironmentPlugin("native:web-worker-post-plugin", (environment) => {
  27197. if (environment.config.worker.format === "iife") return viteWebWorkerPostPlugin();
  27198. });
  27199. return {
  27200. name: "vite:worker-post",
  27201. transform: {
  27202. filter: { code: "import.meta" },
  27203. order: "post",
  27204. async handler(code, id) {
  27205. if (this.environment.config.worker.format === "iife") {
  27206. await init;
  27207. let imports;
  27208. try {
  27209. imports = parse$2(code)[0];
  27210. } catch {
  27211. return;
  27212. }
  27213. let injectedImportMeta = false;
  27214. let s;
  27215. for (const { s: start, e: end, d: dynamicIndex } of imports) if (dynamicIndex === -2) if (code.slice(end, end + 4) === ".url") {
  27216. s ||= new MagicString(code);
  27217. s.overwrite(start, end + 4, "self.location.href");
  27218. } else {
  27219. s ||= new MagicString(code);
  27220. if (!injectedImportMeta) {
  27221. s.prepend("const _vite_importMeta = { url: self.location.href };\n");
  27222. injectedImportMeta = true;
  27223. }
  27224. s.overwrite(start, end, "_vite_importMeta");
  27225. }
  27226. if (!s) return;
  27227. return {
  27228. code: s.toString(),
  27229. map: s.generateMap({
  27230. hires: "boundary",
  27231. source: id
  27232. })
  27233. };
  27234. }
  27235. }
  27236. }
  27237. };
  27238. }
  27239. function webWorkerPlugin(config) {
  27240. const isBuild = config.command === "build";
  27241. const isWorker = config.isWorker;
  27242. workerOutputCaches.set(config, new WorkerOutputCache());
  27243. const emittedAssets = /* @__PURE__ */ new Set();
  27244. return {
  27245. name: "vite:worker",
  27246. buildStart() {
  27247. if (isWorker) return;
  27248. emittedAssets.clear();
  27249. },
  27250. load: {
  27251. filter: { id: workerOrSharedWorkerRE },
  27252. async handler(id) {
  27253. const workerMatch = workerOrSharedWorkerRE.exec(id);
  27254. if (!workerMatch) return;
  27255. const { format } = config.worker;
  27256. const workerConstructor = workerMatch[1] === "sharedworker" ? "SharedWorker" : "Worker";
  27257. const workerType = config.isBundled ? format === "es" ? "module" : "classic" : "module";
  27258. const workerTypeOption = `{
  27259. ${workerType === "module" ? `type: "module",` : ""}
  27260. name: options?.name
  27261. }`;
  27262. let urlCode;
  27263. if (config.isBundled) if (isWorker && config.bundleChain.at(-1) === cleanUrl(id)) urlCode = "self.location.href";
  27264. else if (inlineRE.test(id)) {
  27265. const result = await bundleWorkerEntry(config, id);
  27266. for (const file of result.watchedFiles) this.addWatchFile(file);
  27267. const jsContent = `const jsContent = ${JSON.stringify(result.entryCode)};`;
  27268. return {
  27269. code: workerConstructor === "Worker" ? `${jsContent}
  27270. const blob = typeof self !== "undefined" && self.Blob && new Blob([${workerType === "classic" ? `'(self.URL || self.webkitURL).revokeObjectURL(self.location.href);',` : `'URL.revokeObjectURL(import.meta.url);',`}jsContent], { type: "text/javascript;charset=utf-8" });
  27271. export default function WorkerWrapper(options) {
  27272. let objURL;
  27273. try {
  27274. objURL = blob && (self.URL || self.webkitURL).createObjectURL(blob);
  27275. if (!objURL) throw ''
  27276. const worker = new ${workerConstructor}(objURL, ${workerTypeOption});
  27277. worker.addEventListener("error", () => {
  27278. (self.URL || self.webkitURL).revokeObjectURL(objURL);
  27279. });
  27280. return worker;
  27281. } catch(e) {
  27282. return new ${workerConstructor}(
  27283. 'data:text/javascript;charset=utf-8,' + encodeURIComponent(jsContent),
  27284. ${workerTypeOption}
  27285. );
  27286. }
  27287. }` : `${jsContent}
  27288. export default function WorkerWrapper(options) {
  27289. return new ${workerConstructor}(
  27290. 'data:text/javascript;charset=utf-8,' + encodeURIComponent(jsContent),
  27291. ${workerTypeOption}
  27292. );
  27293. }
  27294. `,
  27295. map: { mappings: "" }
  27296. };
  27297. } else {
  27298. const result = await workerFileToUrl(config, id);
  27299. let url;
  27300. if (this.environment.config.command === "serve" && this.environment.config.experimental.bundledDev) url = toOutputFilePathInJSForBundledDev(this.environment, result.entryFilename);
  27301. else url = result.entryUrlPlaceholder;
  27302. urlCode = JSON.stringify(url);
  27303. for (const file of result.watchedFiles) this.addWatchFile(file);
  27304. }
  27305. else {
  27306. let url = await fileToUrl$1(this, cleanUrl(id));
  27307. url = injectQuery(url, `${WORKER_FILE_ID}&type=${workerType}`);
  27308. urlCode = JSON.stringify(url);
  27309. }
  27310. if (urlRE$1.test(id)) return {
  27311. code: `export default ${urlCode}`,
  27312. map: { mappings: "" }
  27313. };
  27314. return {
  27315. code: `export default function WorkerWrapper(options) {
  27316. return new ${workerConstructor}(
  27317. ${urlCode},
  27318. ${workerTypeOption}
  27319. );
  27320. }`,
  27321. map: { mappings: "" }
  27322. };
  27323. }
  27324. },
  27325. transform: {
  27326. filter: { id: workerFileRE },
  27327. async handler(raw, id) {
  27328. const workerFileMatch = workerFileRE.exec(id);
  27329. if (workerFileMatch) {
  27330. const workerType = workerFileMatch[1];
  27331. let injectEnv = "";
  27332. if (workerType === "classic") injectEnv = `importScripts(${JSON.stringify(path.posix.join(config.base, ENV_PUBLIC_PATH))})\n`;
  27333. else if (workerType === "module") injectEnv = `import ${JSON.stringify(ENV_PUBLIC_PATH)}\n`;
  27334. else if (workerType === "ignore") if (config.isBundled) injectEnv = "";
  27335. else {
  27336. const environment = this.environment;
  27337. injectEnv = ((environment.mode === "dev" ? environment.moduleGraph : void 0)?.getModuleById(ENV_ENTRY))?.transformResult?.code || "";
  27338. }
  27339. if (injectEnv) {
  27340. const s = new MagicString(raw);
  27341. s.prepend(injectEnv + ";\n");
  27342. return {
  27343. code: s.toString(),
  27344. map: s.generateMap({ hires: "boundary" })
  27345. };
  27346. }
  27347. }
  27348. }
  27349. },
  27350. ...isBuild ? { renderChunk(code, chunk, outputOptions) {
  27351. let s;
  27352. const result = () => {
  27353. return s && {
  27354. code: s.toString(),
  27355. map: this.environment.config.build.sourcemap ? s.generateMap({ hires: "boundary" }) : null
  27356. };
  27357. };
  27358. workerAssetUrlRE.lastIndex = 0;
  27359. if (workerAssetUrlRE.test(code)) {
  27360. const toRelativeRuntime = createToImportMetaURLBasedRelativeRuntime(outputOptions.format, this.environment.config.isWorker);
  27361. let match;
  27362. s = new MagicString(code);
  27363. workerAssetUrlRE.lastIndex = 0;
  27364. const workerOutputCache = workerOutputCaches.get(config.mainConfig || config);
  27365. while (match = workerAssetUrlRE.exec(code)) {
  27366. const [full, hash] = match;
  27367. const filename = workerOutputCache.getEntryFilenameFromHash(hash);
  27368. if (!filename) {
  27369. this.warn(`Could not find worker asset for hash: ${hash}`);
  27370. continue;
  27371. }
  27372. const replacement = toOutputFilePathInJS(this.environment, filename, "asset", chunk.fileName, "js", toRelativeRuntime);
  27373. const replacementString = typeof replacement === "string" ? JSON.stringify(encodeURIPath(replacement)).slice(1, -1) : `"+${replacement.runtime}+"`;
  27374. s.update(match.index, match.index + full.length, replacementString);
  27375. }
  27376. }
  27377. return result();
  27378. } } : {},
  27379. generateBundle(opts, bundle) {
  27380. if (this.environment.config.isOutputOptionsForLegacyChunks?.(opts) || isWorker) return;
  27381. for (const asset of workerOutputCaches.get(config).getAssets()) {
  27382. if (emittedAssets.has(asset.fileName)) continue;
  27383. emittedAssets.add(asset.fileName);
  27384. const duplicateAsset = bundle[asset.fileName];
  27385. if (duplicateAsset) {
  27386. if (isSameContent(duplicateAsset.type === "asset" ? duplicateAsset.source : duplicateAsset.code, asset.source)) continue;
  27387. }
  27388. this.emitFile({
  27389. type: "asset",
  27390. fileName: asset.fileName,
  27391. source: asset.source
  27392. });
  27393. }
  27394. },
  27395. watchChange(file) {
  27396. if (isWorker) return;
  27397. workerOutputCaches.get(config).invalidateAffectedBundles(normalizePath(file));
  27398. }
  27399. };
  27400. }
  27401. function isSameContent(a, b) {
  27402. if (typeof a === "string") {
  27403. if (typeof b === "string") return a === b;
  27404. return Buffer.from(a).equals(b);
  27405. }
  27406. return Buffer.from(b).equals(a);
  27407. }
  27408. //#endregion
  27409. //#region src/node/plugins/preAlias.ts
  27410. /**
  27411. * A plugin to avoid an aliased AND optimized dep from being aliased in src
  27412. */
  27413. function preAliasPlugin(config) {
  27414. const findPatterns = getAliasPatterns(config.resolve.alias);
  27415. return {
  27416. name: "vite:pre-alias",
  27417. applyToEnvironment(environment) {
  27418. return !isDepOptimizationDisabled(environment.config.optimizeDeps);
  27419. },
  27420. async resolveId(id, importer, options) {
  27421. const environment = this.environment;
  27422. const ssr = environment.config.consumer === "server";
  27423. const depsOptimizer = environment.depsOptimizer;
  27424. if (importer && depsOptimizer && bareImportRE.test(id) && !options.scan && id !== "@vite/client" && id !== "@vite/env") {
  27425. if (findPatterns.find((pattern) => matches(pattern, id))) {
  27426. const optimizedId = await tryOptimizedResolve(depsOptimizer, id, importer, config.resolve.preserveSymlinks, config.packageCache);
  27427. if (optimizedId) return optimizedId;
  27428. if (depsOptimizer.options.noDiscovery) return;
  27429. const resolved = await this.resolve(id, importer, options);
  27430. if (resolved && !depsOptimizer.isOptimizedDepFile(resolved.id)) {
  27431. const optimizeDeps = depsOptimizer.options;
  27432. const resolvedId = cleanUrl(resolved.id);
  27433. if (!(resolvedId === id || resolvedId.includes("\0")) && fs.existsSync(resolvedId) && !moduleListContains(optimizeDeps.exclude, id) && path.isAbsolute(resolvedId) && (isInNodeModules(resolvedId) || optimizeDeps.include?.includes(id)) && isOptimizable(resolvedId, optimizeDeps) && (!ssr || optimizeAliasReplacementForSSR(resolvedId, optimizeDeps))) {
  27434. const optimizedInfo = depsOptimizer.registerMissingImport(id, resolvedId);
  27435. return { id: depsOptimizer.getOptimizedDepId(optimizedInfo) };
  27436. }
  27437. }
  27438. return resolved;
  27439. }
  27440. }
  27441. }
  27442. };
  27443. }
  27444. function optimizeAliasReplacementForSSR(id, optimizeDeps) {
  27445. if (optimizeDeps.include?.includes(id)) return true;
  27446. return false;
  27447. }
  27448. function matches(pattern, importee) {
  27449. if (pattern instanceof RegExp) return pattern.test(importee);
  27450. if (importee.length < pattern.length) return false;
  27451. if (importee === pattern) return true;
  27452. return importee.startsWith(withTrailingSlash(pattern));
  27453. }
  27454. function getAliasPatterns(entries) {
  27455. if (Array.isArray(entries)) return entries.map((entry) => entry.find);
  27456. return Object.entries(entries).map(([find]) => find);
  27457. }
  27458. function getAliasPatternMatcher(entries) {
  27459. const patterns = getAliasPatterns(entries);
  27460. return (importee) => patterns.some((pattern) => matches(pattern, importee));
  27461. }
  27462. //#endregion
  27463. //#region src/node/plugins/importAnalysis.ts
  27464. const debug$4 = createDebugger("vite:import-analysis");
  27465. const clientDir = normalizePath(CLIENT_DIR);
  27466. const skipRE = /\.(?:map|json)(?:$|\?)/;
  27467. const canSkipImportAnalysis = (id) => skipRE.test(id) || isDirectCSSRequest(id);
  27468. const optimizedDepChunkRE = /\/chunk-[A-Z\d]{8}\.js/;
  27469. const hasViteIgnoreRE = /\/\*\s*@vite-ignore\s*\*\//;
  27470. const urlIsStringRE = /^(?:'.*'|".*"|`.*`)$/;
  27471. const templateLiteralRE = /^\s*`(.*)`\s*$/;
  27472. function isExplicitImportRequired(url) {
  27473. return !isJSRequest(url) && !isCSSRequest(url);
  27474. }
  27475. function normalizeResolvedIdToUrl(environment, url, resolved) {
  27476. const root = environment.config.root;
  27477. const depsOptimizer = environment.depsOptimizer;
  27478. if (resolved.id.startsWith(withTrailingSlash(root))) url = resolved.id.slice(root.length);
  27479. else if (depsOptimizer?.isOptimizedDepFile(resolved.id) || resolved.id !== "/@react-refresh" && path.isAbsolute(resolved.id) && fs.existsSync(cleanUrl(resolved.id))) url = path.posix.join(FS_PREFIX, resolved.id);
  27480. else url = resolved.id;
  27481. if (url[0] !== "." && url[0] !== "/") url = wrapId(resolved.id);
  27482. return url;
  27483. }
  27484. function extractImportedBindings(id, source, importSpec, importedBindings) {
  27485. let bindings = importedBindings.get(id);
  27486. if (!bindings) {
  27487. bindings = /* @__PURE__ */ new Set();
  27488. importedBindings.set(id, bindings);
  27489. }
  27490. if (importSpec.d > -1 || importSpec.d === -2) {
  27491. bindings.add("*");
  27492. return;
  27493. }
  27494. const exp = source.slice(importSpec.ss, importSpec.se);
  27495. ESM_STATIC_IMPORT_RE.lastIndex = 0;
  27496. const match = ESM_STATIC_IMPORT_RE.exec(exp);
  27497. if (!match) return;
  27498. const parsed = parseStaticImport({
  27499. type: "static",
  27500. code: match[0],
  27501. start: match.index,
  27502. end: match.index + match[0].length,
  27503. imports: match.groups.imports,
  27504. specifier: match.groups.specifier
  27505. });
  27506. if (parsed.namespacedImport) bindings.add("*");
  27507. if (parsed.defaultImport) bindings.add("default");
  27508. if (parsed.namedImports) for (const name of Object.keys(parsed.namedImports)) bindings.add(name);
  27509. }
  27510. /**
  27511. * Dev-only plugin that lexes, resolves, rewrites and analyzes url imports.
  27512. *
  27513. * - Imports are resolved to ensure they exist on disk
  27514. *
  27515. * - Lexes HMR accept calls and updates import relationships in the module graph
  27516. *
  27517. * - Bare module imports are resolved (by @rollup-plugin/node-resolve) to
  27518. * absolute file paths, e.g.
  27519. *
  27520. * ```js
  27521. * import 'foo'
  27522. * ```
  27523. * is rewritten to
  27524. * ```js
  27525. * import '/@fs//project/node_modules/foo/dist/foo.js'
  27526. * ```
  27527. *
  27528. * - CSS imports are appended with `.js` since both the js module and the actual
  27529. * css (referenced via `<link>`) may go through the transform pipeline:
  27530. *
  27531. * ```js
  27532. * import './style.css'
  27533. * ```
  27534. * is rewritten to
  27535. * ```js
  27536. * import './style.css.js'
  27537. * ```
  27538. */
  27539. function importAnalysisPlugin(config) {
  27540. const { root, base } = config;
  27541. const clientPublicPath = path.posix.join(base, CLIENT_PUBLIC_PATH);
  27542. const enablePartialAccept = config.experimental.hmrPartialAccept;
  27543. const matchAlias = getAliasPatternMatcher(config.resolve.alias);
  27544. let _env;
  27545. let _ssrEnv;
  27546. function getEnv(ssr) {
  27547. if (!_ssrEnv || !_env) {
  27548. const importMetaEnvKeys = {};
  27549. const userDefineEnv = {};
  27550. for (const key in config.env) importMetaEnvKeys[key] = JSON.stringify(config.env[key]);
  27551. for (const key in config.define) if (key.startsWith("import.meta.env.")) userDefineEnv[key.slice(16)] = config.define[key];
  27552. const env = `import.meta.env = ${serializeDefine({
  27553. ...importMetaEnvKeys,
  27554. SSR: "__vite_ssr__",
  27555. ...userDefineEnv
  27556. })};`;
  27557. _ssrEnv = env.replace("__vite_ssr__", "true");
  27558. _env = env.replace("__vite_ssr__", "false");
  27559. }
  27560. return ssr ? _ssrEnv : _env;
  27561. }
  27562. return {
  27563. name: "vite:import-analysis",
  27564. async transform(source, importer) {
  27565. const environment = this.environment;
  27566. const ssr = environment.config.consumer === "server";
  27567. const moduleGraph = environment.moduleGraph;
  27568. if (canSkipImportAnalysis(importer)) {
  27569. debug$4?.(import_picocolors.default.dim(`[skipped] ${prettifyUrl(importer, root)}`));
  27570. return null;
  27571. }
  27572. const msAtStart = debug$4 ? performance$1.now() : 0;
  27573. await init;
  27574. let imports;
  27575. let exports;
  27576. source = stripBomTag(source);
  27577. try {
  27578. [imports, exports] = parse$2(source);
  27579. } catch (_e) {
  27580. const e = _e;
  27581. const { message, showCodeFrame } = createParseErrorInfo(importer, source);
  27582. this.error(message, showCodeFrame ? e.idx : void 0);
  27583. }
  27584. const depsOptimizer = environment.depsOptimizer;
  27585. const importerModule = moduleGraph.getModuleById(importer);
  27586. if (!importerModule) throwOutdatedRequest(importer);
  27587. if (!imports.length && !this._addedImports) {
  27588. const prunedImports = await moduleGraph.updateModuleInfo(importerModule, /* @__PURE__ */ new Set(), null, /* @__PURE__ */ new Set(), null, false);
  27589. if (prunedImports) handlePrunedModules(prunedImports, environment);
  27590. debug$4?.(`${timeFrom(msAtStart)} ${import_picocolors.default.dim(`[no imports] ${prettifyUrl(importer, root)}`)}`);
  27591. return source;
  27592. }
  27593. let hasHMR = false;
  27594. let isSelfAccepting = false;
  27595. let hasEnv = false;
  27596. let needQueryInjectHelper = false;
  27597. let s;
  27598. const str = () => s || (s = new MagicString(source));
  27599. let isPartiallySelfAccepting = false;
  27600. const importedBindings = enablePartialAccept ? /* @__PURE__ */ new Map() : null;
  27601. const normalizeUrl = async (url, pos, forceSkipImportAnalysis = false) => {
  27602. let importerFile = importer;
  27603. if (depsOptimizer && moduleListContains(depsOptimizer.options.exclude, url)) {
  27604. await depsOptimizer.scanProcessing;
  27605. for (const optimizedModule of depsOptimizer.metadata.depInfoList) {
  27606. if (!optimizedModule.src) continue;
  27607. if (optimizedModule.file === importerModule.file) importerFile = optimizedModule.src;
  27608. }
  27609. }
  27610. const resolved = await this.resolve(url, importerFile).catch((e) => {
  27611. if (e instanceof Error) e.pos ??= pos;
  27612. throw e;
  27613. });
  27614. if (!resolved || resolved.meta?.["vite:alias"]?.noResolved) {
  27615. if (ssr) return [url, null];
  27616. importerModule.isSelfAccepting = false;
  27617. moduleGraph._hasResolveFailedErrorModules.add(importerModule);
  27618. return this.error(`Failed to resolve import "${url}" from "${normalizePath(path.relative(process.cwd(), importerFile))}". Does the file exist?`, pos);
  27619. }
  27620. if (isExternalUrl(resolved.id)) return [resolved.id, resolved.id];
  27621. url = normalizeResolvedIdToUrl(environment, url, resolved);
  27622. try {
  27623. const depModule = await moduleGraph._ensureEntryFromUrl(unwrapId(url), canSkipImportAnalysis(url) || forceSkipImportAnalysis, resolved);
  27624. if (environment.config.consumer === "client" && depModule.lastHMRTimestamp > 0) url = injectQuery(url, `t=${depModule.lastHMRTimestamp}`);
  27625. } catch (e) {
  27626. e.pos = pos;
  27627. throw e;
  27628. }
  27629. if (environment.config.consumer === "client") {
  27630. const isRelative = url[0] === ".";
  27631. const isSelfImport = !isRelative && cleanUrl(url) === cleanUrl(importer);
  27632. if (isExplicitImportRequired(url)) url = injectQuery(url, "import");
  27633. else if ((isRelative || isSelfImport) && !DEP_VERSION_RE.test(url)) {
  27634. const versionMatch = DEP_VERSION_RE.exec(importer);
  27635. if (versionMatch) url = injectQuery(url, versionMatch[1]);
  27636. }
  27637. }
  27638. if (!ssr) url = joinUrlSegments(base, url);
  27639. return [url, resolved.id];
  27640. };
  27641. const orderedImportedUrls = new Array(imports.length);
  27642. const orderedAcceptedUrls = new Array(imports.length);
  27643. const orderedAcceptedExports = new Array(imports.length);
  27644. let _isNodeModeResult = config.legacy?.inconsistentCjsInterop ? false : void 0;
  27645. const isNodeMode = () => {
  27646. _isNodeModeResult ??= isFilePathESM(importer, config.packageCache);
  27647. return _isNodeModeResult;
  27648. };
  27649. await Promise.all(imports.map(async (importSpecifier, index) => {
  27650. const { s: start, e: end, ss: expStart, se: expEnd, d: dynamicIndex, a: attributeIndex } = importSpecifier;
  27651. let specifier = importSpecifier.n;
  27652. const rawUrl = source.slice(start, end);
  27653. if (rawUrl === "import.meta") {
  27654. const prop = source.slice(end, end + 4);
  27655. if (prop === ".hot") {
  27656. hasHMR = true;
  27657. const endHot = end + 4 + (source[end + 4] === "?" ? 1 : 0);
  27658. if (source.slice(endHot, endHot + 7) === ".accept") if (source.slice(endHot, endHot + 14) === ".acceptExports") {
  27659. const importAcceptedExports = orderedAcceptedExports[index] = /* @__PURE__ */ new Set();
  27660. lexAcceptedHmrExports(source, source.indexOf("(", endHot + 14) + 1, importAcceptedExports);
  27661. isPartiallySelfAccepting = true;
  27662. } else {
  27663. const importAcceptedUrls = orderedAcceptedUrls[index] = /* @__PURE__ */ new Set();
  27664. if (lexAcceptedHmrDeps(source, source.indexOf("(", endHot + 7) + 1, importAcceptedUrls)) isSelfAccepting = true;
  27665. }
  27666. } else if (prop === ".env") hasEnv = true;
  27667. return;
  27668. } else if (templateLiteralRE.test(rawUrl)) {
  27669. if (!(rawUrl.includes("${") && rawUrl.includes("}"))) specifier = rawUrl.replace(templateLiteralRE, "$1");
  27670. }
  27671. const isDynamicImport = dynamicIndex > -1;
  27672. if (!isDynamicImport && attributeIndex > -1) str().remove(end + 1, expEnd);
  27673. if (specifier !== void 0) {
  27674. if ((isExternalUrl(specifier) && !specifier.startsWith("file://") || isDataUrl(specifier)) && !matchAlias(specifier)) return;
  27675. if (ssr && !matchAlias(specifier)) {
  27676. if (shouldExternalize(environment, specifier, importer)) return;
  27677. if (isBuiltin(environment.config.resolve.builtins, specifier)) return;
  27678. }
  27679. if (specifier === clientPublicPath) return;
  27680. if (specifier[0] === "/" && !(config.assetsInclude(cleanUrl(specifier)) || urlRE$1.test(specifier)) && checkPublicFile(specifier, config)) throw new Error(`Cannot import non-asset file ${specifier} which is inside /public. JS/CSS files inside /public are copied as-is on build and can only be referenced via <script src> or <link href> in html. If you want to get the URL of that file, use ${injectQuery(specifier, "url")} instead.`);
  27681. let [url, resolvedId] = await normalizeUrl(specifier, start);
  27682. resolvedId = resolvedId || url;
  27683. config.safeModulePaths.add(fsPathFromUrl(stripBase(url, base)));
  27684. if (url !== specifier) {
  27685. let rewriteDone = false;
  27686. if (!depsOptimizer?.isOptimizedDepFile(importer) && depsOptimizer?.isOptimizedDepFile(resolvedId) && !optimizedDepChunkRE.test(resolvedId)) {
  27687. const file = cleanUrl(resolvedId);
  27688. const depInfo = optimizedDepInfoFromFile(depsOptimizer.metadata, file);
  27689. const needsInterop = await optimizedDepNeedsInterop(environment, depsOptimizer.metadata, file);
  27690. if (needsInterop === void 0) {
  27691. if (depInfo?.isDynamicEntry) config.logger.error(import_picocolors.default.red(`Vite Error, ${url} optimized info should be defined`));
  27692. } else if (needsInterop) {
  27693. debug$4?.(`${url} needs interop`);
  27694. interopNamedImports(str(), importSpecifier, url, index, importer, isNodeMode(), config);
  27695. rewriteDone = true;
  27696. }
  27697. } else if (url.startsWith(wrapId("__vite-browser-external")) && source.slice(expStart, start).includes("{")) {
  27698. interopNamedImports(str(), importSpecifier, url, index, importer, isNodeMode(), config);
  27699. rewriteDone = true;
  27700. }
  27701. if (!rewriteDone) {
  27702. const rewrittenUrl = JSON.stringify(url);
  27703. const s = isDynamicImport ? start : start - 1;
  27704. const e = isDynamicImport ? end : end + 1;
  27705. str().overwrite(s, e, rewrittenUrl, { contentOnly: true });
  27706. }
  27707. }
  27708. const hmrUrl = unwrapId(stripBase(url, base));
  27709. const isLocalImport = !isExternalUrl(hmrUrl) && !isDataUrl(hmrUrl);
  27710. if (isLocalImport) orderedImportedUrls[index] = hmrUrl;
  27711. if (enablePartialAccept && importedBindings) extractImportedBindings(resolvedId, source, importSpecifier, importedBindings);
  27712. if (!isDynamicImport && isLocalImport && environment.config.dev.preTransformRequests) {
  27713. const url = removeImportQuery(hmrUrl);
  27714. environment.warmupRequest(url);
  27715. }
  27716. } else if (!importer.startsWith(withTrailingSlash(clientDir))) {
  27717. if (!isInNodeModules(importer)) {
  27718. if (!hasViteIgnoreRE.test(source.slice(dynamicIndex + 1, end))) this.warn(`\n` + import_picocolors.default.cyan(importerModule.file) + `\n` + import_picocolors.default.reset(generateCodeFrame(source, start, end)) + import_picocolors.default.yellow(`\nThe above dynamic import cannot be analyzed by Vite.\nSee ${import_picocolors.default.blue(`https://github.com/rollup/plugins/tree/master/packages/dynamic-import-vars#limitations`)} for supported dynamic import formats. If this is intended to be left as-is, you can use the /* @vite-ignore */ comment inside the import() call to suppress this warning.\n`));
  27719. }
  27720. if (!ssr) {
  27721. if (!urlIsStringRE.test(rawUrl) || isExplicitImportRequired(rawUrl.slice(1, -1))) {
  27722. needQueryInjectHelper = true;
  27723. str().overwrite(start, end, `__vite__injectQuery(${rawUrl}, 'import')`, { contentOnly: true });
  27724. }
  27725. }
  27726. }
  27727. }));
  27728. const _orderedImportedUrls = orderedImportedUrls.filter(isDefined);
  27729. const importedUrls = new Set(_orderedImportedUrls);
  27730. const staticImportedUrls = new Set(_orderedImportedUrls.map((url) => removeTimestampQuery(url)));
  27731. const acceptedUrls = mergeAcceptedUrls(orderedAcceptedUrls);
  27732. const acceptedExports = mergeAcceptedUrls(orderedAcceptedExports);
  27733. const isClassicWorker = importer.includes("worker_file") && importer.includes("type=classic");
  27734. if (hasEnv && !isClassicWorker) str().prepend(getEnv(ssr));
  27735. if (hasHMR && !ssr && !isClassicWorker) {
  27736. debugHmr?.(`${isSelfAccepting ? `[self-accepts]` : isPartiallySelfAccepting ? `[accepts-exports]` : acceptedUrls.size ? `[accepts-deps]` : `[detected api usage]`} ${prettifyUrl(importer, root)}`);
  27737. str().prepend(`import { createHotContext as __vite__createHotContext } from "${clientPublicPath}";import.meta.hot = __vite__createHotContext(${JSON.stringify(normalizeHmrUrl(importerModule.url))});`);
  27738. }
  27739. if (needQueryInjectHelper) if (isClassicWorker) str().append("\n" + __vite__injectQuery.toString());
  27740. else str().prepend(`import { injectQuery as __vite__injectQuery } from "${clientPublicPath}";`);
  27741. const normalizedAcceptedUrls = /* @__PURE__ */ new Set();
  27742. for (const { url, start, end } of acceptedUrls) {
  27743. let [normalized, resolvedId] = await normalizeUrl(url, start).catch(() => []);
  27744. if (resolvedId) {
  27745. const mod = moduleGraph.getModuleById(resolvedId);
  27746. if (!mod) {
  27747. this.error(`module was not found for ${JSON.stringify(resolvedId)}`, start);
  27748. return;
  27749. }
  27750. normalized = mod.url;
  27751. } else this.error({
  27752. message: `Failed to resolve ${JSON.stringify(url)} from ${importer}.`,
  27753. pos: start
  27754. });
  27755. normalizedAcceptedUrls.add(normalized);
  27756. const hmrAccept = normalizeHmrUrl(normalized);
  27757. str().overwrite(start, end, JSON.stringify(hmrAccept), { contentOnly: true });
  27758. }
  27759. if (!isCSSRequest(importer) || SPECIAL_QUERY_RE.test(importer)) {
  27760. const pluginImports = this._addedImports;
  27761. if (pluginImports) (await Promise.all([...pluginImports].map((id) => normalizeUrl(id, 0, true)))).forEach(([url]) => importedUrls.add(stripBase(url, base)));
  27762. if (ssr && importerModule.isSelfAccepting) isSelfAccepting = true;
  27763. if (!isSelfAccepting && isPartiallySelfAccepting && acceptedExports.size >= exports.length && exports.every((e) => acceptedExports.has(e.n))) isSelfAccepting = true;
  27764. const prunedImports = await moduleGraph.updateModuleInfo(importerModule, importedUrls, importedBindings, normalizedAcceptedUrls, isPartiallySelfAccepting ? acceptedExports : null, isSelfAccepting, staticImportedUrls);
  27765. if (prunedImports) handlePrunedModules(prunedImports, environment);
  27766. }
  27767. debug$4?.(`${timeFrom(msAtStart)} ${import_picocolors.default.dim(`[${importedUrls.size} imports rewritten] ${prettifyUrl(importer, root)}`)}`);
  27768. if (s) return transformStableResult(s, importer, config);
  27769. else return source;
  27770. }
  27771. };
  27772. }
  27773. function mergeAcceptedUrls(orderedUrls) {
  27774. const acceptedUrls = /* @__PURE__ */ new Set();
  27775. for (const urls of orderedUrls) {
  27776. if (!urls) continue;
  27777. for (const url of urls) acceptedUrls.add(url);
  27778. }
  27779. return acceptedUrls;
  27780. }
  27781. function createParseErrorInfo(importer, source) {
  27782. const isVue = importer.endsWith(".vue");
  27783. const isJsx = importer.endsWith(".jsx") || importer.endsWith(".tsx");
  27784. const maybeJSX = !isVue && isJSRequest(importer);
  27785. const probablyBinary = source.includes("�");
  27786. return {
  27787. message: "Failed to parse source for import analysis because the content contains invalid JS syntax. " + (isVue ? `Install @vitejs/plugin-vue to handle .vue files.` : maybeJSX ? isJsx ? `If you use tsconfig.json, make sure to not set jsx to preserve.` : `If you are using JSX, make sure to name the file with the .jsx or .tsx extension.` : `You may need to install appropriate plugins to handle the ${path.extname(importer)} file format, or if it's an asset, add "**/*${path.extname(importer)}" to \`assetsInclude\` in your configuration.`),
  27788. showCodeFrame: !probablyBinary
  27789. };
  27790. }
  27791. const interopHelper = (m, n) => n || !m?.__esModule ? {
  27792. ...typeof m === "object" && !Array.isArray(m) || typeof m === "function" ? m : {},
  27793. default: m
  27794. } : m;
  27795. const interopHelperStr = interopHelper.toString().replaceAll("\n", "");
  27796. function interopNamedImports(str, importSpecifier, rewrittenUrl, importIndex, importer, isNodeMode, config) {
  27797. const source = str.original;
  27798. const { s: start, e: end, ss: expStart, se: expEnd, d: dynamicIndex } = importSpecifier;
  27799. const exp = source.slice(expStart, expEnd);
  27800. if (dynamicIndex > -1) str.overwrite(expStart, expEnd, `import('${rewrittenUrl}').then(m => (${interopHelperStr})(m.default, ${!!config.legacy?.inconsistentCjsInterop ? 0 : 1}))` + getLineBreaks(exp), { contentOnly: true });
  27801. else {
  27802. const rewritten = transformCjsImport(exp, rewrittenUrl, source.slice(start, end), importIndex, importer, isNodeMode, config);
  27803. if (rewritten) {
  27804. str.overwrite(expStart, expEnd, rewritten.importLine + getLineBreaks(exp), { contentOnly: true });
  27805. if (rewritten.hoistedAssignments) str.appendLeft(getFileStartIndex(source), rewritten.hoistedAssignments + ";");
  27806. } else str.overwrite(start, end, rewrittenUrl + getLineBreaks(source.slice(start, end)), { contentOnly: true });
  27807. }
  27808. }
  27809. function getLineBreaks(str) {
  27810. return str.includes("\n") ? "\n".repeat(str.split("\n").length - 1) : "";
  27811. }
  27812. /**
  27813. * Detect import statements to a known optimized CJS dependency and provide
  27814. * ES named imports interop. We do this by rewriting named imports to a variable
  27815. * assignment to the corresponding property on the `module.exports` of the cjs
  27816. * module. Note this doesn't support dynamic re-assignments from within the cjs
  27817. * module.
  27818. *
  27819. * Note that es-module-lexer treats `export * from '...'` as an import as well,
  27820. * so, we may encounter ExportAllDeclaration here, in which case `undefined`
  27821. * will be returned.
  27822. *
  27823. * Credits \@csr632 via #837
  27824. */
  27825. function transformCjsImport(importExp, url, rawUrl, importIndex, importer, isNodeMode, config) {
  27826. const node = parseAst(importExp).body[0];
  27827. if (config.command === "serve" && node.type === "ExportAllDeclaration" && !node.exported) config.logger.warn(import_picocolors.default.yellow(`\nUnable to interop \`${importExp}\` in ${importer}, this may lose module exports. Please export "${rawUrl}" as ESM or use named exports instead, e.g. \`export { A, B } from "${rawUrl}"\``));
  27828. else if (node.type === "ImportDeclaration" || node.type === "ExportNamedDeclaration") {
  27829. if (!node.specifiers.length) return { importLine: `import "${url}"` };
  27830. const importNames = [];
  27831. const exportNames = [];
  27832. let defaultExports = "";
  27833. for (const spec of node.specifiers) if (spec.type === "ImportSpecifier") {
  27834. const importedName = getIdentifierNameOrLiteralValue(spec.imported);
  27835. importNames.push({
  27836. importedName,
  27837. localName: spec.local.name
  27838. });
  27839. } else if (spec.type === "ImportDefaultSpecifier") importNames.push({
  27840. importedName: "default",
  27841. localName: spec.local.name
  27842. });
  27843. else if (spec.type === "ImportNamespaceSpecifier") importNames.push({
  27844. importedName: "*",
  27845. localName: spec.local.name
  27846. });
  27847. else if (spec.type === "ExportSpecifier") {
  27848. const importedName = getIdentifierNameOrLiteralValue(spec.local);
  27849. const exportedName = getIdentifierNameOrLiteralValue(spec.exported);
  27850. if (exportedName === "default") {
  27851. defaultExports = makeLegalIdentifier(`__vite__cjsExportDefault_${importIndex}`);
  27852. importNames.push({
  27853. importedName,
  27854. localName: defaultExports
  27855. });
  27856. } else {
  27857. const localName = `__vite__cjsExport${spec.exported.type === "Literal" ? `L_${getHash(spec.exported.value)}` : "I_" + spec.exported.name}`;
  27858. importNames.push({
  27859. importedName,
  27860. localName
  27861. });
  27862. exportNames.push(`${localName} as ${spec.exported.type === "Literal" ? JSON.stringify(exportedName) : exportedName}`);
  27863. }
  27864. }
  27865. const cjsModuleName = makeLegalIdentifier(`__vite__cjsImport${importIndex}_${rawUrl}`);
  27866. const importLine = `import ${cjsModuleName} from "${url}"`;
  27867. const lines = [];
  27868. importNames.forEach(({ importedName, localName }) => {
  27869. if (importedName === "*") lines.push(`const ${localName} = (${interopHelperStr})(${cjsModuleName}, ${+isNodeMode})`);
  27870. else if (importedName === "default") if (isNodeMode) lines.push(`const ${localName} = ${cjsModuleName}`);
  27871. else lines.push(`const ${localName} = !${cjsModuleName}.__esModule ? ${cjsModuleName} : ${cjsModuleName}.default`);
  27872. else lines.push(`const ${localName} = ${cjsModuleName}["${importedName}"]`);
  27873. });
  27874. if (defaultExports) lines.push(`export default ${defaultExports}`);
  27875. if (exportNames.length) lines.push(`export { ${exportNames.join(", ")} }`);
  27876. return {
  27877. importLine,
  27878. hoistedAssignments: lines.join("; ")
  27879. };
  27880. }
  27881. }
  27882. function getIdentifierNameOrLiteralValue(node) {
  27883. return node.type === "Identifier" ? node.name : node.value;
  27884. }
  27885. function __vite__injectQuery(url, queryToInject) {
  27886. if (url[0] !== "." && url[0] !== "/") return url;
  27887. const pathname = url.replace(/[?#].*$/, "");
  27888. const { search, hash } = new URL(url, "http://vite.dev");
  27889. return `${pathname}?${queryToInject}${search ? `&` + search.slice(1) : ""}${hash || ""}`;
  27890. }
  27891. //#endregion
  27892. //#region src/node/plugins/wasm.ts
  27893. const wasmHelperId = "\0vite/wasm-helper.js";
  27894. const wasmInitRE = /(?<![?#].*)\.wasm\?init/;
  27895. const wasmInitUrlRE = /__VITE_WASM_INIT__([\w$]+)__/g;
  27896. const wasmHelper = async (opts = {}, url) => {
  27897. let result;
  27898. if (url.startsWith("data:")) {
  27899. const urlContent = url.replace(/^data:.*?base64,/, "");
  27900. let bytes;
  27901. if (typeof Buffer === "function" && typeof Buffer.from === "function") bytes = Buffer.from(urlContent, "base64");
  27902. else if (typeof atob === "function") {
  27903. const binaryString = atob(urlContent);
  27904. bytes = new Uint8Array(binaryString.length);
  27905. for (let i = 0; i < binaryString.length; i++) bytes[i] = binaryString.charCodeAt(i);
  27906. } else throw new Error("Failed to decode base64-encoded data URL, Buffer and atob are not supported");
  27907. result = await WebAssembly.instantiate(bytes, opts);
  27908. } else result = await instantiateFromUrl(url, opts);
  27909. return result.instance;
  27910. };
  27911. const wasmHelperCode = wasmHelper.toString();
  27912. const instantiateFromUrl = async (url, opts) => {
  27913. const response = await fetch(url);
  27914. const contentType = response.headers.get("Content-Type") || "";
  27915. if ("instantiateStreaming" in WebAssembly && contentType.startsWith("application/wasm")) return WebAssembly.instantiateStreaming(response, opts);
  27916. else {
  27917. const buffer = await response.arrayBuffer();
  27918. return WebAssembly.instantiate(buffer, opts);
  27919. }
  27920. };
  27921. const instantiateFromUrlCode = instantiateFromUrl.toString();
  27922. const instantiateFromFile = async (fileUrlString, opts) => {
  27923. const { readFile } = await import("node:fs/promises");
  27924. const buffer = await readFile(new URL(
  27925. fileUrlString,
  27926. /** #__KEEP__ */
  27927. import.meta.url
  27928. ));
  27929. return WebAssembly.instantiate(buffer, opts);
  27930. };
  27931. const instantiateFromFileCode = instantiateFromFile.toString();
  27932. const wasmHelperPlugin = () => {
  27933. return perEnvironmentPlugin("vite:wasm-helper", (env) => {
  27934. return {
  27935. name: "vite:wasm-helper",
  27936. resolveId: {
  27937. filter: { id: exactRegex(wasmHelperId) },
  27938. handler(id) {
  27939. return id;
  27940. }
  27941. },
  27942. load: {
  27943. filter: { id: [exactRegex(wasmHelperId), wasmInitRE] },
  27944. async handler(id) {
  27945. const ssr = this.environment.config.consumer === "server";
  27946. if (id === wasmHelperId) return `
  27947. const instantiateFromUrl = ${ssr ? instantiateFromFileCode : instantiateFromUrlCode}
  27948. export default ${wasmHelperCode}
  27949. `;
  27950. id = id.split("?")[0];
  27951. let url = await fileToUrl$1(this, id, ssr);
  27952. assetUrlRE.lastIndex = 0;
  27953. if (ssr && assetUrlRE.test(url)) url = url.replace("__VITE_ASSET__", "__VITE_WASM_INIT__");
  27954. return `
  27955. import initWasm from "${wasmHelperId}"
  27956. export default opts => initWasm(opts, ${JSON.stringify(url)})
  27957. `;
  27958. }
  27959. },
  27960. renderChunk: env.config.consumer === "server" ? {
  27961. filter: { code: wasmInitUrlRE },
  27962. async handler(code, chunk, opts, meta) {
  27963. const toRelativeRuntime = createToImportMetaURLBasedRelativeRuntime(opts.format, this.environment.config.isWorker);
  27964. let match;
  27965. let s;
  27966. wasmInitUrlRE.lastIndex = 0;
  27967. while (match = wasmInitUrlRE.exec(code)) {
  27968. const [full, referenceId] = match;
  27969. const file = this.getFileName(referenceId);
  27970. chunk.viteMetadata.importedAssets.add(cleanUrl(file));
  27971. const { runtime } = toRelativeRuntime(file, chunk.fileName);
  27972. s ??= meta.magicString ?? new MagicString(code);
  27973. s.update(match.index, match.index + full.length, `"+${runtime}+"`);
  27974. }
  27975. if (!s) return null;
  27976. return meta.magicString ? { code: s } : {
  27977. code: s.toString(),
  27978. map: this.environment.config.build.sourcemap ? s.generateMap({ hires: "boundary" }) : null
  27979. };
  27980. }
  27981. } : void 0
  27982. };
  27983. });
  27984. };
  27985. //#endregion
  27986. //#region src/node/plugins/workerImportMetaUrl.ts
  27987. function err$1(e, pos) {
  27988. const error = new Error(e);
  27989. error.pos = pos;
  27990. return error;
  27991. }
  27992. function findClosingParen(input, fromIndex) {
  27993. let count = 1;
  27994. for (let i = fromIndex; i < input.length; i++) {
  27995. if (input[i] === "(") count++;
  27996. if (input[i] === ")") count--;
  27997. if (count === 0) return i;
  27998. }
  27999. return -1;
  28000. }
  28001. function extractWorkerTypeFromAst(expression, optsStartIndex) {
  28002. if (expression.type !== "ObjectExpression") return;
  28003. let lastSpreadElementIndex = -1;
  28004. let typeProperty = null;
  28005. let typePropertyIndex = -1;
  28006. for (let i = 0; i < expression.properties.length; i++) {
  28007. const property = expression.properties[i];
  28008. if (property.type === "SpreadElement") {
  28009. lastSpreadElementIndex = i;
  28010. continue;
  28011. }
  28012. if (property.type === "Property" && (property.key.type === "Identifier" && property.key.name === "type" || property.key.type === "Literal" && property.key.value === "type")) {
  28013. typeProperty = property;
  28014. typePropertyIndex = i;
  28015. }
  28016. }
  28017. if (typePropertyIndex === -1 && lastSpreadElementIndex === -1) return "classic";
  28018. if (typePropertyIndex < lastSpreadElementIndex) throw err$1("Expected object spread to be used before the definition of the type property. Vite needs a static value for the type property to correctly infer it.", optsStartIndex);
  28019. if (typeProperty?.value.type !== "Literal") throw err$1("Expected worker options type property to be a literal value.", optsStartIndex);
  28020. return typeProperty?.value.value === "module" ? "module" : "classic";
  28021. }
  28022. async function parseWorkerOptions(rawOpts, optsStartIndex) {
  28023. let opts = {};
  28024. try {
  28025. opts = evalValue(rawOpts);
  28026. } catch {
  28027. const optsNode = (await parseAstAsync(`(${rawOpts})`)).body[0].expression;
  28028. const type = extractWorkerTypeFromAst(optsNode, optsStartIndex);
  28029. if (type) return { type };
  28030. throw err$1("Vite is unable to parse the worker options as the value is not static. To ignore this error, please use /* @vite-ignore */ in the worker options.", optsStartIndex);
  28031. }
  28032. if (opts == null) return {};
  28033. if (typeof opts !== "object") throw err$1(`Expected worker options to be an object, got ${typeof opts}`, optsStartIndex);
  28034. return opts;
  28035. }
  28036. async function getWorkerType(raw, clean, i) {
  28037. const commaIndex = clean.indexOf(",", i);
  28038. if (commaIndex === -1) return "classic";
  28039. const endIndex = findClosingParen(clean, i);
  28040. if (commaIndex > endIndex) return "classic";
  28041. let workerOptString = raw.substring(commaIndex + 1, endIndex);
  28042. if (hasViteIgnoreRE.test(workerOptString)) return "ignore";
  28043. const cleanWorkerOptString = clean.substring(commaIndex + 1, endIndex);
  28044. const trimmedCleanWorkerOptString = cleanWorkerOptString.trim();
  28045. if (!trimmedCleanWorkerOptString.length) return "classic";
  28046. if (trimmedCleanWorkerOptString.endsWith(",")) workerOptString = workerOptString.slice(0, cleanWorkerOptString.lastIndexOf(","));
  28047. const workerOpts = await parseWorkerOptions(workerOptString, commaIndex + 1);
  28048. if (workerOpts.type && (workerOpts.type === "module" || workerOpts.type === "classic")) return workerOpts.type;
  28049. return "classic";
  28050. }
  28051. const workerImportMetaUrlRE = /\bnew\s+(?:Worker|SharedWorker)\s*\(\s*(new\s+URL\s*\(\s*('[^']+'|"[^"]+"|`[^`]+`)\s*,\s*import\.meta\.url\s*(?:,\s*)?\))/dg;
  28052. function workerImportMetaUrlPlugin(config) {
  28053. const isBundled = config.isBundled;
  28054. let workerResolver;
  28055. const fsResolveOptions = {
  28056. ...config.resolve,
  28057. root: config.root,
  28058. isProduction: config.isProduction,
  28059. isBuild: config.command === "build",
  28060. packageCache: config.packageCache,
  28061. asSrc: true
  28062. };
  28063. return {
  28064. name: "vite:worker-import-meta-url",
  28065. applyToEnvironment(environment) {
  28066. return environment.config.consumer === "client";
  28067. },
  28068. transform: {
  28069. filter: { code: workerImportMetaUrlRE },
  28070. async handler(code, id) {
  28071. let s;
  28072. const cleanString = stripLiteral(code);
  28073. const re = new RegExp(workerImportMetaUrlRE);
  28074. let match;
  28075. while (match = re.exec(cleanString)) {
  28076. const [[, endIndex], [expStart, expEnd], [urlStart, urlEnd]] = match.indices;
  28077. const rawUrl = code.slice(urlStart, urlEnd);
  28078. if (rawUrl[0] === "`" && rawUrl.includes("${")) this.error(`\`new URL(url, import.meta.url)\` is not supported in dynamic template string.`, expStart);
  28079. s ||= new MagicString(code);
  28080. const workerType = await getWorkerType(code, cleanString, endIndex);
  28081. const url = rawUrl.slice(1, -1);
  28082. let file;
  28083. if (url[0] === ".") {
  28084. file = path.resolve(path.dirname(id), url);
  28085. file = slash(tryFsResolve(file, fsResolveOptions) ?? file);
  28086. } else {
  28087. workerResolver ??= createBackCompatIdResolver(config, {
  28088. extensions: [],
  28089. tryIndex: false,
  28090. preferRelative: true
  28091. });
  28092. file = await workerResolver(this.environment, url, id);
  28093. file ??= url[0] === "/" ? slash(path.join(config.publicDir, url)) : slash(path.resolve(path.dirname(id), url));
  28094. }
  28095. if (isBundled && config.isWorker && config.bundleChain.at(-1) === cleanUrl(file)) s.update(expStart, expEnd, "self.location.href");
  28096. else {
  28097. let builtUrl;
  28098. if (isBundled) {
  28099. const result = await workerFileToUrl(config, file);
  28100. if (this.environment.config.command === "serve" && this.environment.config.experimental.bundledDev) builtUrl = toOutputFilePathInJSForBundledDev(this.environment, result.entryFilename);
  28101. else builtUrl = result.entryUrlPlaceholder;
  28102. for (const file of result.watchedFiles) this.addWatchFile(file);
  28103. } else {
  28104. builtUrl = await fileToUrl$1(this, cleanUrl(file));
  28105. builtUrl = injectQuery(builtUrl, `${WORKER_FILE_ID}&type=${workerType}`);
  28106. }
  28107. s.update(expStart, expEnd, `new URL(/* @vite-ignore */ ${JSON.stringify(builtUrl)}, '' + import.meta.url)`);
  28108. }
  28109. }
  28110. if (s) return transformStableResult(s, id, config);
  28111. return null;
  28112. }
  28113. }
  28114. };
  28115. }
  28116. //#endregion
  28117. //#region src/node/plugins/importAnalysisBuild.ts
  28118. /**
  28119. * A flag for injected helpers. This flag will be set to `false` if the output
  28120. * target is not native es - so that injected helper logic can be conditionally
  28121. * dropped.
  28122. */
  28123. const isModernFlag = `__VITE_IS_MODERN__`;
  28124. const preloadMethod = `__vitePreload`;
  28125. const preloadMarker = `__VITE_PRELOAD__`;
  28126. const preloadHelperId = "\0vite/preload-helper.js";
  28127. const preloadMarkerRE = new RegExp(preloadMarker, "g");
  28128. function toRelativePath(filename, importer) {
  28129. const relPath = path.posix.relative(path.posix.dirname(importer), filename);
  28130. return relPath[0] === "." ? relPath : `./${relPath}`;
  28131. }
  28132. function findPreloadMarker(str, pos = 0) {
  28133. preloadMarkerRE.lastIndex = pos;
  28134. return preloadMarkerRE.exec(str)?.index ?? -1;
  28135. }
  28136. /**
  28137. * Helper for preloading CSS and direct imports of async chunks in parallel to
  28138. * the async chunk itself.
  28139. */
  28140. function detectScriptRel() {
  28141. const relList = typeof document !== "undefined" && document.createElement("link").relList;
  28142. return relList && relList.supports && relList.supports("modulepreload") ? "modulepreload" : "preload";
  28143. }
  28144. function preload(baseModule, deps, importerUrl) {
  28145. let promise = Promise.resolve();
  28146. if (__VITE_IS_MODERN__ && deps && deps.length > 0) {
  28147. const links = document.getElementsByTagName("link");
  28148. const cspNonceMeta = document.querySelector("meta[property=csp-nonce]");
  28149. const cspNonce = cspNonceMeta?.nonce || cspNonceMeta?.getAttribute("nonce");
  28150. function allSettled(promises) {
  28151. return Promise.all(promises.map((p) => Promise.resolve(p).then((value) => ({
  28152. status: "fulfilled",
  28153. value
  28154. }), (reason) => ({
  28155. status: "rejected",
  28156. reason
  28157. }))));
  28158. }
  28159. promise = allSettled(deps.map((dep) => {
  28160. dep = assetsURL(dep, importerUrl);
  28161. if (dep in seen) return;
  28162. seen[dep] = true;
  28163. const isCss = dep.endsWith(".css");
  28164. const cssSelector = isCss ? "[rel=\"stylesheet\"]" : "";
  28165. if (!!importerUrl) for (let i = links.length - 1; i >= 0; i--) {
  28166. const link = links[i];
  28167. if (link.href === dep && (!isCss || link.rel === "stylesheet")) return;
  28168. }
  28169. else if (document.querySelector(`link[href="${dep}"]${cssSelector}`)) return;
  28170. const link = document.createElement("link");
  28171. link.rel = isCss ? "stylesheet" : scriptRel;
  28172. if (!isCss) link.as = "script";
  28173. link.crossOrigin = "";
  28174. link.href = dep;
  28175. if (cspNonce) link.setAttribute("nonce", cspNonce);
  28176. document.head.appendChild(link);
  28177. if (isCss) return new Promise((res, rej) => {
  28178. link.addEventListener("load", res);
  28179. link.addEventListener("error", () => rej(/* @__PURE__ */ new Error(`Unable to preload CSS for ${dep}`)));
  28180. });
  28181. }));
  28182. }
  28183. function handlePreloadError(err) {
  28184. const e = new Event("vite:preloadError", { cancelable: true });
  28185. e.payload = err;
  28186. window.dispatchEvent(e);
  28187. if (!e.defaultPrevented) throw err;
  28188. }
  28189. return promise.then((res) => {
  28190. for (const item of res || []) {
  28191. if (item.status !== "rejected") continue;
  28192. handlePreloadError(item.reason);
  28193. }
  28194. return baseModule().catch(handlePreloadError);
  28195. });
  28196. }
  28197. function getPreloadCode(environment, renderBuiltUrlBoolean, isRelativeBase) {
  28198. const { modulePreload } = environment.config.build;
  28199. return `const scriptRel = ${modulePreload && modulePreload.polyfill ? `'modulepreload'` : `/* @__PURE__ */ (${detectScriptRel.toString()})()`};const assetsURL = ${renderBuiltUrlBoolean || isRelativeBase ? `function(dep, importerUrl) { return new URL(dep, importerUrl).href }` : `function(dep) { return ${JSON.stringify(environment.config.base)}+dep }`};const seen = {};export const ${preloadMethod} = ${preload.toString()}`;
  28200. }
  28201. /**
  28202. * Build only. During serve this is performed as part of ./importAnalysis.
  28203. */
  28204. function buildImportAnalysisPlugin(config) {
  28205. const getInsertPreload = (environment) => environment.config.consumer === "client" && !config.isWorker && !config.build.lib;
  28206. const renderBuiltUrl = config.experimental.renderBuiltUrl;
  28207. const isRelativeBase = config.base === "./" || config.base === "";
  28208. return [{
  28209. name: "vite:build-import-analysis",
  28210. renderChunk(code, _, { format }) {
  28211. if (code.indexOf(isModernFlag) > -1) {
  28212. const re = new RegExp(isModernFlag, "g");
  28213. const isModern = String(format === "es");
  28214. const isModernWithPadding = isModern + " ".repeat(isModernFlag.length - isModern.length);
  28215. return {
  28216. code: code.replace(re, isModernWithPadding),
  28217. map: null
  28218. };
  28219. }
  28220. return null;
  28221. },
  28222. async generateBundle({ format }, bundle) {
  28223. if (format !== "es") return;
  28224. await init;
  28225. if (!getInsertPreload(this.environment)) {
  28226. const removedPureCssFiles = removedPureCssFilesCache.get(config);
  28227. if (removedPureCssFiles && removedPureCssFiles.size > 0) for (const file in bundle) {
  28228. const chunk = bundle[file];
  28229. if (chunk.type === "chunk" && chunk.code.includes("import")) {
  28230. const code = chunk.code;
  28231. let imports;
  28232. try {
  28233. imports = parse$2(code)[0].filter((i) => i.d > -1);
  28234. } catch (e) {
  28235. const loc = numberToPos(code, e.idx);
  28236. this.error({
  28237. name: e.name,
  28238. message: e.message,
  28239. stack: e.stack,
  28240. cause: e.cause,
  28241. pos: e.idx,
  28242. loc: {
  28243. ...loc,
  28244. file: chunk.fileName
  28245. },
  28246. frame: generateCodeFrame(code, loc)
  28247. });
  28248. }
  28249. for (const imp of imports) {
  28250. const { n: name, s: start, e: end, ss: expStart, se: expEnd } = imp;
  28251. let url = name;
  28252. if (!url) {
  28253. const rawUrl = code.slice(start, end);
  28254. if (rawUrl[0] === `"` && rawUrl[rawUrl.length - 1] === `"` || rawUrl[0] === "`" && rawUrl[rawUrl.length - 1] === "`") url = rawUrl.slice(1, -1);
  28255. }
  28256. if (!url) continue;
  28257. const normalizedFile = path.posix.join(path.posix.dirname(chunk.fileName), url);
  28258. if (removedPureCssFiles.has(normalizedFile)) chunk.code = chunk.code.slice(0, expStart) + `Promise.resolve({${"".padEnd(expEnd - expStart - 19, " ")}})` + chunk.code.slice(expEnd);
  28259. }
  28260. }
  28261. }
  28262. return;
  28263. }
  28264. const buildSourcemap = this.environment.config.build.sourcemap;
  28265. const { modulePreload } = this.environment.config.build;
  28266. for (const file in bundle) {
  28267. const chunk = bundle[file];
  28268. if (chunk.type === "chunk" && chunk.code.indexOf(preloadMarker) > -1) {
  28269. const code = chunk.code;
  28270. let imports;
  28271. try {
  28272. imports = parse$2(code)[0].filter((i) => i.d > -1);
  28273. } catch (e) {
  28274. const loc = numberToPos(code, e.idx);
  28275. this.error({
  28276. name: e.name,
  28277. message: e.message,
  28278. stack: e.stack,
  28279. cause: e.cause,
  28280. pos: e.idx,
  28281. loc: {
  28282. ...loc,
  28283. file: chunk.fileName
  28284. },
  28285. frame: generateCodeFrame(code, loc)
  28286. });
  28287. }
  28288. const s = new MagicString(code);
  28289. const rewroteMarkerStartPos = /* @__PURE__ */ new Set();
  28290. const fileDeps = [];
  28291. const addFileDep = (url, runtime = false) => {
  28292. const index = fileDeps.findIndex((dep) => dep.url === url);
  28293. if (index === -1) return fileDeps.push({
  28294. url,
  28295. runtime
  28296. }) - 1;
  28297. else return index;
  28298. };
  28299. if (imports.length) for (let index = 0; index < imports.length; index++) {
  28300. const { n: name, s: start, e: end, ss: expStart, se: expEnd } = imports[index];
  28301. let url = name;
  28302. if (!url) {
  28303. const rawUrl = code.slice(start, end);
  28304. if (rawUrl[0] === `"` && rawUrl[rawUrl.length - 1] === `"` || rawUrl[0] === "`" && rawUrl[rawUrl.length - 1] === "`") url = rawUrl.slice(1, -1);
  28305. }
  28306. const deps = /* @__PURE__ */ new Set();
  28307. let hasRemovedPureCssChunk = false;
  28308. let normalizedFile = void 0;
  28309. if (url) {
  28310. normalizedFile = path.posix.join(path.posix.dirname(chunk.fileName), url);
  28311. const ownerFilename = chunk.fileName;
  28312. const analyzed = /* @__PURE__ */ new Set();
  28313. const addDeps = (filename) => {
  28314. if (filename === ownerFilename) return;
  28315. if (analyzed.has(filename)) return;
  28316. analyzed.add(filename);
  28317. const chunk = bundle[filename];
  28318. if (chunk) {
  28319. deps.add(chunk.fileName);
  28320. if (chunk.type === "chunk") {
  28321. chunk.imports.forEach(addDeps);
  28322. chunk.viteMetadata.importedCss.forEach((file) => {
  28323. deps.add(file);
  28324. });
  28325. }
  28326. } else {
  28327. const chunk = removedPureCssFilesCache.get(config).get(filename);
  28328. if (chunk) {
  28329. if (chunk.viteMetadata.importedCss.size) {
  28330. chunk.viteMetadata.importedCss.forEach((file) => {
  28331. deps.add(file);
  28332. });
  28333. hasRemovedPureCssChunk = true;
  28334. }
  28335. s.update(expStart, expEnd, "Promise.resolve({})");
  28336. }
  28337. }
  28338. };
  28339. addDeps(normalizedFile);
  28340. }
  28341. let markerStartPos = findPreloadMarker(code, end);
  28342. if (markerStartPos === -1 && imports.length === 1) markerStartPos = findPreloadMarker(code);
  28343. if (markerStartPos > 0) {
  28344. let depsArray = deps.size > 1 || hasRemovedPureCssChunk && deps.size > 0 ? modulePreload === false ? [...deps].filter((d) => d.endsWith(".css")) : [...deps] : [];
  28345. const resolveDependencies = modulePreload ? modulePreload.resolveDependencies : void 0;
  28346. if (resolveDependencies && normalizedFile) {
  28347. const cssDeps = [];
  28348. const otherDeps = [];
  28349. for (const dep of depsArray) (dep.endsWith(".css") ? cssDeps : otherDeps).push(dep);
  28350. depsArray = [...resolveDependencies(normalizedFile, otherDeps, {
  28351. hostId: file,
  28352. hostType: "js"
  28353. }), ...cssDeps];
  28354. }
  28355. let renderedDeps;
  28356. if (renderBuiltUrl) renderedDeps = depsArray.map((dep) => {
  28357. const replacement = toOutputFilePathInJS(this.environment, dep, "asset", chunk.fileName, "js", toRelativePath);
  28358. if (typeof replacement === "string") return addFileDep(replacement);
  28359. return addFileDep(replacement.runtime, true);
  28360. });
  28361. else renderedDeps = depsArray.map((d) => isRelativeBase ? addFileDep(toRelativePath(d, file)) : addFileDep(d));
  28362. s.update(markerStartPos, markerStartPos + preloadMarker.length, renderedDeps.length > 0 ? `__vite__mapDeps([${renderedDeps.join(",")}])` : `[]`);
  28363. rewroteMarkerStartPos.add(markerStartPos);
  28364. }
  28365. }
  28366. if (fileDeps.length > 0) {
  28367. const mapDepsCode = `const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=${`[${fileDeps.map((fileDep) => fileDep.runtime ? fileDep.url : JSON.stringify(fileDep.url)).join(",")}]`})))=>i.map(i=>d[i]);\n`;
  28368. if (code.startsWith("#!")) s.prependLeft(code.indexOf("\n") + 1, mapDepsCode);
  28369. else s.prepend(mapDepsCode);
  28370. }
  28371. let markerStartPos = findPreloadMarker(code);
  28372. while (markerStartPos >= 0) {
  28373. if (!rewroteMarkerStartPos.has(markerStartPos)) s.update(markerStartPos, markerStartPos + preloadMarker.length, "void 0");
  28374. markerStartPos = findPreloadMarker(code, markerStartPos + preloadMarker.length);
  28375. }
  28376. if (s.hasChanged()) {
  28377. chunk.code = s.toString();
  28378. if (buildSourcemap && chunk.map) {
  28379. const nextMap = s.generateMap({
  28380. source: chunk.fileName,
  28381. hires: "boundary"
  28382. });
  28383. const originalFile = chunk.map.file;
  28384. const map = combineSourcemaps(chunk.fileName, [nextMap, chunk.map]);
  28385. map.toUrl = () => genSourceMapUrl(map);
  28386. if (originalFile) map.file = originalFile;
  28387. const originalDebugId = chunk.map.debugId;
  28388. chunk.map = map;
  28389. if (buildSourcemap === "inline") {
  28390. chunk.code = chunk.code.replace(import_convert_source_map.default.mapFileCommentRegex, "");
  28391. chunk.code += `\n//# sourceMappingURL=${genSourceMapUrl(map)}`;
  28392. } else {
  28393. if (originalDebugId) map.debugId = originalDebugId;
  28394. const mapAsset = bundle[chunk.fileName + ".map"];
  28395. if (mapAsset && mapAsset.type === "asset") mapAsset.source = map.toString();
  28396. }
  28397. }
  28398. }
  28399. }
  28400. }
  28401. }
  28402. }, perEnvironmentPlugin("native:import-analysis-build", (environment) => {
  28403. return viteBuildImportAnalysisPlugin({
  28404. preloadCode: getPreloadCode(environment, !!renderBuiltUrl, isRelativeBase),
  28405. insertPreload: getInsertPreload(environment),
  28406. optimizeModulePreloadRelativePaths: false,
  28407. renderBuiltUrl: !!renderBuiltUrl,
  28408. isRelativeBase
  28409. });
  28410. })];
  28411. }
  28412. //#endregion
  28413. //#region src/node/plugins/assetImportMetaUrl.ts
  28414. /**
  28415. * Convert `new URL('./foo.png', import.meta.url)` to its resolved built URL
  28416. *
  28417. * Supports template string with dynamic segments:
  28418. * ```
  28419. * new URL(`./dir/${name}.png`, import.meta.url)
  28420. * // transformed to
  28421. * import.meta.glob('./dir/**.png', { eager: true, import: 'default' })[`./dir/${name}.png`]
  28422. * ```
  28423. */
  28424. const assetImportMetaUrlRE = /\bnew\s+URL\s*\(\s*('[^']+'|"[^"]+"|`[^`]+`)\s*,\s*import\.meta\.url\s*(?:,\s*)?\)/dg;
  28425. function assetImportMetaUrlPlugin(config) {
  28426. const { publicDir } = config;
  28427. let assetResolver;
  28428. const fsResolveOptions = {
  28429. ...config.resolve,
  28430. root: config.root,
  28431. isProduction: config.isProduction,
  28432. isBuild: config.command === "build",
  28433. packageCache: config.packageCache,
  28434. asSrc: true
  28435. };
  28436. return {
  28437. name: "vite:asset-import-meta-url",
  28438. applyToEnvironment(environment) {
  28439. return environment.config.consumer === "client";
  28440. },
  28441. transform: {
  28442. filter: {
  28443. id: { exclude: [exactRegex(preloadHelperId), exactRegex(CLIENT_ENTRY)] },
  28444. code: assetImportMetaUrlRE
  28445. },
  28446. async handler(code, id) {
  28447. let s;
  28448. const re = new RegExp(assetImportMetaUrlRE);
  28449. const cleanString = stripLiteral(code);
  28450. let match;
  28451. while (match = re.exec(cleanString)) {
  28452. const [[startIndex, endIndex], [urlStart, urlEnd]] = match.indices;
  28453. if (hasViteIgnoreRE.test(code.slice(startIndex, urlStart))) continue;
  28454. const rawUrl = code.slice(urlStart, urlEnd);
  28455. if (!s) s = new MagicString(code);
  28456. if (rawUrl[0] === "`" && rawUrl.includes("${")) {
  28457. const queryDelimiterIndex = getQueryDelimiterIndex(rawUrl);
  28458. const hasQueryDelimiter = queryDelimiterIndex !== -1;
  28459. const pureUrl = hasQueryDelimiter ? rawUrl.slice(0, queryDelimiterIndex) + "`" : rawUrl;
  28460. const queryString = hasQueryDelimiter ? rawUrl.slice(queryDelimiterIndex, -1) : "";
  28461. const templateLiteral = this.parse(pureUrl).body[0].expression;
  28462. if (templateLiteral.expressions.length) {
  28463. const pattern = buildGlobPattern(templateLiteral);
  28464. if (pattern[0] === "*") continue;
  28465. const globOptions = {
  28466. eager: true,
  28467. import: "default",
  28468. query: injectQuery(queryString, "url")
  28469. };
  28470. s.update(startIndex, endIndex, `new URL((import.meta.glob(${JSON.stringify(pattern)}, ${JSON.stringify(globOptions)}))[${pureUrl}], import.meta.url)`);
  28471. continue;
  28472. }
  28473. }
  28474. const url = rawUrl.slice(1, -1);
  28475. if (isDataUrl(url)) continue;
  28476. let file;
  28477. if (url[0] === ".") {
  28478. file = slash(path.resolve(path.dirname(id), url));
  28479. file = tryFsResolve(file, fsResolveOptions) ?? file;
  28480. } else {
  28481. assetResolver ??= createBackCompatIdResolver(config, {
  28482. extensions: [],
  28483. mainFields: [],
  28484. tryIndex: false,
  28485. preferRelative: true
  28486. });
  28487. file = await assetResolver(this.environment, url, id);
  28488. file ??= url[0] === "/" ? slash(path.join(publicDir, url)) : slash(path.resolve(path.dirname(id), url));
  28489. }
  28490. let builtUrl;
  28491. if (file) try {
  28492. if (publicDir && isParentDirectory(publicDir, file)) {
  28493. const publicPath = "/" + path.posix.relative(publicDir, file);
  28494. builtUrl = await fileToUrl$1(this, publicPath);
  28495. } else {
  28496. builtUrl = await fileToUrl$1(this, file);
  28497. if (tryStatSync(file)?.isFile()) this.addWatchFile(file);
  28498. }
  28499. } catch {}
  28500. if (!builtUrl) {
  28501. const rawExp = code.slice(startIndex, endIndex);
  28502. config.logger.warnOnce(`\n${rawExp} doesn't exist at build time, it will remain unchanged to be resolved at runtime. If this is intended, you can use the /* @vite-ignore */ comment to suppress this warning.`);
  28503. builtUrl = url;
  28504. }
  28505. s.update(startIndex, endIndex, `new URL(${JSON.stringify(builtUrl)}, '' + import.meta.url)`);
  28506. }
  28507. if (s) return transformStableResult(s, id, config);
  28508. }
  28509. }
  28510. };
  28511. }
  28512. function buildGlobPattern(ast) {
  28513. let pattern = "";
  28514. let lastIsGlob = false;
  28515. for (let i = 0; i < ast.quasis.length; i++) {
  28516. const str = ast.quasis[i].value.raw;
  28517. if (str) {
  28518. pattern += str;
  28519. lastIsGlob = false;
  28520. }
  28521. if (ast.expressions[i] && !lastIsGlob) {
  28522. pattern += "*";
  28523. lastIsGlob = true;
  28524. }
  28525. }
  28526. return pattern;
  28527. }
  28528. function getQueryDelimiterIndex(rawUrl) {
  28529. let bracketsStack = 0;
  28530. for (let i = 0; i < rawUrl.length; i++) if (rawUrl[i] === "{") bracketsStack++;
  28531. else if (rawUrl[i] === "}") bracketsStack--;
  28532. else if (rawUrl[i] === "?" && bracketsStack === 0) return i;
  28533. return -1;
  28534. }
  28535. //#endregion
  28536. //#region ../../node_modules/.pnpm/@rollup+plugin-dynamic-import-vars@2.1.4_rollup@4.59.0/node_modules/@rollup/plugin-dynamic-import-vars/dist/es/index.js
  28537. var VariableDynamicImportError = class extends Error {};
  28538. const example = "For example: import(`./foo/${bar}.js`).";
  28539. function sanitizeString(str) {
  28540. if (str === "") return str;
  28541. if (str.includes("*")) throw new VariableDynamicImportError("A dynamic import cannot contain * characters.");
  28542. return escapePath(str);
  28543. }
  28544. function templateLiteralToGlob(node) {
  28545. let glob = "";
  28546. for (let i = 0; i < node.quasis.length; i += 1) {
  28547. glob += sanitizeString(node.quasis[i].value.raw);
  28548. if (node.expressions[i]) glob += expressionToGlob(node.expressions[i]);
  28549. }
  28550. return glob;
  28551. }
  28552. function callExpressionToGlob(node) {
  28553. const { callee } = node;
  28554. if (callee.type === "MemberExpression" && callee.property.type === "Identifier" && callee.property.name === "concat") return `${expressionToGlob(callee.object)}${node.arguments.map(expressionToGlob).join("")}`;
  28555. return "*";
  28556. }
  28557. function binaryExpressionToGlob(node) {
  28558. if (node.operator !== "+") throw new VariableDynamicImportError(`${node.operator} operator is not supported.`);
  28559. return `${expressionToGlob(node.left)}${expressionToGlob(node.right)}`;
  28560. }
  28561. function expressionToGlob(node) {
  28562. switch (node.type) {
  28563. case "TemplateLiteral": return templateLiteralToGlob(node);
  28564. case "CallExpression": return callExpressionToGlob(node);
  28565. case "BinaryExpression": return binaryExpressionToGlob(node);
  28566. case "Literal": return sanitizeString(node.value);
  28567. default: return "*";
  28568. }
  28569. }
  28570. const defaultProtocol = "file:";
  28571. const ignoredProtocols = [
  28572. "data:",
  28573. "http:",
  28574. "https:"
  28575. ];
  28576. function shouldIgnore(glob) {
  28577. const containsAsterisk = glob.includes("*");
  28578. const globURL = new URL(glob, defaultProtocol);
  28579. const containsIgnoredProtocol = ignoredProtocols.some((ignoredProtocol) => ignoredProtocol === globURL.protocol);
  28580. return !containsAsterisk || containsIgnoredProtocol;
  28581. }
  28582. function dynamicImportToGlob(node, sourceString) {
  28583. let glob = expressionToGlob(node);
  28584. if (shouldIgnore(glob)) return null;
  28585. glob = glob.replace(/\*\*/g, "*");
  28586. if (glob.startsWith("*")) throw new VariableDynamicImportError(`invalid import "${sourceString}". It cannot be statically analyzed. Variable dynamic imports must start with ./ and be limited to a specific directory. ${example}`);
  28587. if (glob.startsWith("/")) throw new VariableDynamicImportError(`invalid import "${sourceString}". Variable absolute imports are not supported, imports must start with ./ in the static part of the import. ${example}`);
  28588. if (!glob.startsWith("./") && !glob.startsWith("../")) throw new VariableDynamicImportError(`invalid import "${sourceString}". Variable bare imports are not supported, imports must start with ./ in the static part of the import. ${example}`);
  28589. if (/^\.\/\*\.\w+$/.test(glob)) throw new VariableDynamicImportError(`${`invalid import "${sourceString}". Variable imports cannot import their own directory, place imports in a separate directory or make the import filename more specific. `}${example}`);
  28590. if (path$1.extname(glob) === "") throw new VariableDynamicImportError(`invalid import "${sourceString}". A file extension must be included in the static part of the import. ${example}`);
  28591. return glob;
  28592. }
  28593. //#endregion
  28594. //#region src/node/plugins/dynamicImportVars.ts
  28595. const dynamicImportHelperId = "\0vite/dynamic-import-helper.js";
  28596. const relativePathRE = /^\.{1,2}\//;
  28597. const hasDynamicImportRE = /\bimport\s*[(/]/;
  28598. const dynamicImportHelper = (glob, path, segs) => {
  28599. const v = glob[path];
  28600. if (v) return typeof v === "function" ? v() : Promise.resolve(v);
  28601. return new Promise((_, reject) => {
  28602. (typeof queueMicrotask === "function" ? queueMicrotask : setTimeout)(reject.bind(null, /* @__PURE__ */ new Error("Unknown variable dynamic import: " + path + (path.split("/").length !== segs ? ". Note that variables only represent file names one level deep." : ""))));
  28603. });
  28604. };
  28605. function parseDynamicImportPattern(strings) {
  28606. const filename = strings.slice(1, -1);
  28607. const ast = parseAst(strings).body[0].expression;
  28608. const userPatternQuery = dynamicImportToGlob(ast, filename);
  28609. if (!userPatternQuery) return null;
  28610. const [userPattern] = userPatternQuery.split(requestQueryMaybeEscapedSplitRE, 2);
  28611. let [rawPattern, search] = filename.split(requestQuerySplitRE, 2);
  28612. let globParams = null;
  28613. if (search) {
  28614. search = "?" + search;
  28615. if (workerOrSharedWorkerRE.test(search) || urlRE$1.test(search) || rawRE$1.test(search)) globParams = {
  28616. query: search,
  28617. import: "*"
  28618. };
  28619. else globParams = { query: search };
  28620. }
  28621. return {
  28622. globParams,
  28623. userPattern,
  28624. rawPattern
  28625. };
  28626. }
  28627. async function transformDynamicImport(importSource, importer, resolve, root) {
  28628. if (importSource[1] !== "." && importSource[1] !== "/") {
  28629. const resolvedFileName = await resolve(importSource.slice(1, -1), importer);
  28630. if (!resolvedFileName) return null;
  28631. const relativeFileName = normalizePath(posix.relative(posix.dirname(normalizePath(importer)), normalizePath(resolvedFileName)));
  28632. importSource = "`" + (relativeFileName[0] === "." ? "" : "./") + relativeFileName + "`";
  28633. }
  28634. const dynamicImportPattern = parseDynamicImportPattern(importSource);
  28635. if (!dynamicImportPattern) return null;
  28636. const { globParams, rawPattern, userPattern } = dynamicImportPattern;
  28637. const params = globParams ? `, ${JSON.stringify(globParams)}` : "";
  28638. const dir = importer ? posix.dirname(importer) : root;
  28639. const normalized = rawPattern[0] === "/" ? posix.join(root, rawPattern.slice(1)) : posix.join(dir, rawPattern);
  28640. let newRawPattern = posix.relative(posix.dirname(importer), normalized);
  28641. if (!relativePathRE.test(newRawPattern)) newRawPattern = `./${newRawPattern}`;
  28642. const exp = `(import.meta.glob(${JSON.stringify(userPattern)}${params}))`;
  28643. return {
  28644. rawPattern: newRawPattern,
  28645. pattern: userPattern,
  28646. glob: exp
  28647. };
  28648. }
  28649. function dynamicImportVarsPlugin(config) {
  28650. const resolve = createBackCompatIdResolver(config, {
  28651. preferRelative: true,
  28652. tryIndex: false,
  28653. extensions: []
  28654. });
  28655. if (config.isBundled) return perEnvironmentPlugin("native:dynamic-import-vars", (environment) => {
  28656. const { include, exclude } = environment.config.build.dynamicImportVarsOptions;
  28657. return viteDynamicImportVarsPlugin({
  28658. include,
  28659. exclude,
  28660. resolver(id, importer) {
  28661. return resolve(environment, id, importer);
  28662. },
  28663. sourcemap: !!environment.config.build.sourcemap
  28664. });
  28665. });
  28666. const getFilter = perEnvironmentState((environment) => {
  28667. const { include, exclude } = environment.config.build.dynamicImportVarsOptions;
  28668. return createFilter$1(include, exclude);
  28669. });
  28670. return {
  28671. name: "vite:dynamic-import-vars",
  28672. resolveId: {
  28673. filter: { id: exactRegex(dynamicImportHelperId) },
  28674. handler(id) {
  28675. return id;
  28676. }
  28677. },
  28678. load: {
  28679. filter: { id: exactRegex(dynamicImportHelperId) },
  28680. handler(_id) {
  28681. return `export default ${dynamicImportHelper.toString()}`;
  28682. }
  28683. },
  28684. transform: {
  28685. filter: {
  28686. id: { exclude: exactRegex(CLIENT_ENTRY) },
  28687. code: hasDynamicImportRE
  28688. },
  28689. async handler(source, importer) {
  28690. const { environment } = this;
  28691. if (!getFilter(this)(importer)) return;
  28692. await init;
  28693. let imports = [];
  28694. try {
  28695. imports = parse$2(source)[0];
  28696. } catch {
  28697. return null;
  28698. }
  28699. if (!imports.length) return null;
  28700. let s;
  28701. let needDynamicImportHelper = false;
  28702. for (let index = 0; index < imports.length; index++) {
  28703. const { s: start, e: end, ss: expStart, se: expEnd, d: dynamicIndex } = imports[index];
  28704. if (dynamicIndex === -1 || source[start] !== "`") continue;
  28705. if (hasViteIgnoreRE.test(source.slice(expStart, expEnd))) continue;
  28706. s ||= new MagicString(source);
  28707. let result;
  28708. try {
  28709. result = await transformDynamicImport(source.slice(start, end), importer, (id, importer) => resolve(environment, id, importer), config.root);
  28710. } catch (error) {
  28711. this.warn(error);
  28712. }
  28713. if (!result) continue;
  28714. const { rawPattern, glob } = result;
  28715. needDynamicImportHelper = true;
  28716. s.overwrite(expStart, expEnd, `__variableDynamicImportRuntimeHelper(${glob}, \`${rawPattern}\`, ${rawPattern.split("/").length})`);
  28717. }
  28718. if (s) {
  28719. if (needDynamicImportHelper) s.prepend(`import __variableDynamicImportRuntimeHelper from "${dynamicImportHelperId}";`);
  28720. return transformStableResult(s, importer, config);
  28721. }
  28722. }
  28723. }
  28724. };
  28725. }
  28726. //#endregion
  28727. //#region src/node/plugins/importMetaGlob.ts
  28728. function importGlobPlugin(config) {
  28729. if (config.isBundled) return viteImportGlobPlugin({
  28730. root: config.root,
  28731. sourcemap: !!config.build.sourcemap,
  28732. restoreQueryExtension: config.experimental.importGlobRestoreExtension
  28733. });
  28734. const importGlobMaps = /* @__PURE__ */ new Map();
  28735. return {
  28736. name: "vite:import-glob",
  28737. buildStart() {
  28738. importGlobMaps.clear();
  28739. },
  28740. transform: {
  28741. filter: { code: "import.meta.glob" },
  28742. async handler(code, id) {
  28743. const result = await transformGlobImport(code, id, config.root, (im, _, options) => this.resolve(im, id, options).then((i) => i?.id || im), config.experimental.importGlobRestoreExtension, config.logger);
  28744. if (result) {
  28745. const allGlobs = result.matches.map((i) => i.globsResolved);
  28746. if (!importGlobMaps.has(this.environment)) importGlobMaps.set(this.environment, /* @__PURE__ */ new Map());
  28747. const globMatchers = allGlobs.map((globs) => {
  28748. const affirmed = [];
  28749. const negated = [];
  28750. for (const glob of globs) if (glob[0] === "!") negated.push(glob.slice(1));
  28751. else affirmed.push(glob);
  28752. const affirmedMatcher = picomatch(affirmed);
  28753. const negatedMatcher = picomatch(negated);
  28754. return (file) => {
  28755. return (affirmed.length === 0 || affirmedMatcher(file)) && !(negated.length > 0 && negatedMatcher(file));
  28756. };
  28757. });
  28758. importGlobMaps.get(this.environment).set(id, globMatchers);
  28759. return transformStableResult(result.s, id, config);
  28760. }
  28761. }
  28762. },
  28763. hotUpdate({ type, file, modules: oldModules }) {
  28764. if (type === "update") return;
  28765. const importGlobMap = importGlobMaps.get(this.environment);
  28766. if (!importGlobMap) return;
  28767. const modules = [];
  28768. for (const [id, globMatchers] of importGlobMap) if (globMatchers.some((matcher) => matcher(file))) {
  28769. const mod = this.environment.moduleGraph.getModuleById(id);
  28770. if (mod) modules.push(mod);
  28771. }
  28772. return modules.length > 0 ? [...oldModules, ...modules] : void 0;
  28773. }
  28774. };
  28775. }
  28776. const importGlobRE = /\bimport\.meta\.glob(?:<\w+>)?\s*\(/g;
  28777. const objectKeysRE = /\bObject\.keys\(\s*$/;
  28778. const objectValuesRE = /\bObject\.values\(\s*$/;
  28779. const knownOptions = {
  28780. as: ["string"],
  28781. eager: ["boolean"],
  28782. import: ["string"],
  28783. exhaustive: ["boolean"],
  28784. query: ["object", "string"],
  28785. base: ["string"]
  28786. };
  28787. const forceDefaultAs = ["raw", "url"];
  28788. function err(e, pos) {
  28789. const error = new Error(e);
  28790. error.pos = pos;
  28791. return error;
  28792. }
  28793. function parseGlobOptions(rawOpts, optsStartIndex, logger) {
  28794. let opts = {};
  28795. try {
  28796. opts = evalValue(rawOpts);
  28797. } catch {
  28798. throw err("Vite is unable to parse the glob options as the value is not static", optsStartIndex);
  28799. }
  28800. if (opts == null) return {};
  28801. for (const key in opts) {
  28802. if (!(key in knownOptions)) throw err(`Unknown glob option "${key}"`, optsStartIndex);
  28803. const allowedTypes = knownOptions[key];
  28804. const valueType = typeof opts[key];
  28805. if (!allowedTypes.includes(valueType)) throw err(`Expected glob option "${key}" to be of type ${allowedTypes.join(" or ")}, but got ${valueType}`, optsStartIndex);
  28806. }
  28807. if (opts.base) {
  28808. if (opts.base[0] === "!") throw err("Option \"base\" cannot start with \"!\"", optsStartIndex);
  28809. else if (opts.base[0] !== "/" && !opts.base.startsWith("./") && !opts.base.startsWith("../")) throw err(`Option "base" must start with '/', './' or '../', but got "${opts.base}"`, optsStartIndex);
  28810. }
  28811. if (typeof opts.query === "object") {
  28812. for (const key in opts.query) {
  28813. const value = opts.query[key];
  28814. if (![
  28815. "string",
  28816. "number",
  28817. "boolean"
  28818. ].includes(typeof value)) throw err(`Expected glob option "query.${key}" to be of type string, number, or boolean, but got ${typeof value}`, optsStartIndex);
  28819. }
  28820. opts.query = stringifyQuery(opts.query);
  28821. }
  28822. if (opts.as && logger) {
  28823. const importSuggestion = forceDefaultAs.includes(opts.as) ? `, import: 'default'` : "";
  28824. logger.warn(import_picocolors.default.yellow(`The glob option "as" has been deprecated in favour of "query". Please update \`as: '${opts.as}'\` to \`query: '?${opts.as}'${importSuggestion}\`.`));
  28825. }
  28826. if (opts.as && forceDefaultAs.includes(opts.as)) {
  28827. if (opts.import && opts.import !== "default" && opts.import !== "*") throw err(`Option "import" can only be "default" or "*" when "as" is "${opts.as}", but got "${opts.import}"`, optsStartIndex);
  28828. opts.import = opts.import || "default";
  28829. }
  28830. if (opts.as && opts.query) throw err("Options \"as\" and \"query\" cannot be used together", optsStartIndex);
  28831. if (opts.as) opts.query = opts.as;
  28832. if (opts.query && opts.query[0] !== "?") opts.query = `?${opts.query}`;
  28833. return opts;
  28834. }
  28835. async function parseImportGlob(code, importer, root, resolveId, logger) {
  28836. let cleanCode;
  28837. try {
  28838. cleanCode = stripLiteral(code);
  28839. } catch {
  28840. return [];
  28841. }
  28842. const tasks = Array.from(cleanCode.matchAll(importGlobRE)).map(async (match, index) => {
  28843. const start = match.index;
  28844. const err = (msg) => {
  28845. const e = /* @__PURE__ */ new Error(`Invalid glob import syntax: ${msg}`);
  28846. e.pos = start;
  28847. return e;
  28848. };
  28849. const end = findCorrespondingCloseParenthesisPosition(cleanCode, start + match[0].length) + 1;
  28850. if (end <= 0) throw err("Close parenthesis not found");
  28851. const rootAst = (await parseAstAsync(code.slice(start, end))).body[0];
  28852. if (rootAst.type !== "ExpressionStatement") throw err(`Expect CallExpression, got ${rootAst.type}`);
  28853. const ast = rootAst.expression;
  28854. if (ast.type !== "CallExpression") throw err(`Expect CallExpression, got ${ast.type}`);
  28855. if (ast.arguments.length < 1 || ast.arguments.length > 2) throw err(`Expected 1-2 arguments, but got ${ast.arguments.length}`);
  28856. const arg1 = ast.arguments[0];
  28857. const arg2 = ast.arguments[1];
  28858. const globs = [];
  28859. const validateLiteral = (element) => {
  28860. if (!element) return;
  28861. if (element.type === "Literal") {
  28862. if (typeof element.value !== "string") throw err(`Expected glob to be a string, but got "${typeof element.value}"`);
  28863. globs.push(element.value);
  28864. } else if (element.type === "TemplateLiteral") {
  28865. if (element.expressions.length !== 0) throw err(`Expected glob to be a string, but got dynamic template literal`);
  28866. globs.push(element.quasis[0].value.raw);
  28867. } else throw err("Could only use literals");
  28868. };
  28869. if (arg1.type === "ArrayExpression") for (const element of arg1.elements) validateLiteral(element);
  28870. else validateLiteral(arg1);
  28871. let options = {};
  28872. if (arg2) {
  28873. if (arg2.type !== "ObjectExpression") throw err(`Expected the second argument to be an object literal, but got "${arg2.type}"`);
  28874. options = parseGlobOptions(code.slice(start + arg2.start, start + arg2.end), start + arg2.start, logger);
  28875. }
  28876. const globsResolved = await Promise.all(globs.map((glob) => toAbsoluteGlob(glob, root, importer, resolveId, options.base)));
  28877. const isRelative = globs.every((i) => ".!".includes(i[0]));
  28878. const sliceCode = cleanCode.slice(0, start);
  28879. const onlyKeys = objectKeysRE.test(sliceCode);
  28880. let onlyValues = false;
  28881. if (!onlyKeys) onlyValues = objectValuesRE.test(sliceCode);
  28882. return {
  28883. index,
  28884. globs,
  28885. globsResolved,
  28886. isRelative,
  28887. options,
  28888. start,
  28889. end,
  28890. onlyKeys,
  28891. onlyValues
  28892. };
  28893. });
  28894. return (await Promise.all(tasks)).filter(Boolean);
  28895. }
  28896. function findCorrespondingCloseParenthesisPosition(cleanCode, openPos) {
  28897. const closePos = cleanCode.indexOf(")", openPos);
  28898. if (closePos < 0) return -1;
  28899. if (!cleanCode.slice(openPos, closePos).includes("(")) return closePos;
  28900. let remainingParenthesisCount = 0;
  28901. const cleanCodeLen = cleanCode.length;
  28902. for (let pos = openPos; pos < cleanCodeLen; pos++) switch (cleanCode[pos]) {
  28903. case "(":
  28904. remainingParenthesisCount++;
  28905. break;
  28906. case ")":
  28907. remainingParenthesisCount--;
  28908. if (remainingParenthesisCount <= 0) return pos;
  28909. }
  28910. return -1;
  28911. }
  28912. const importPrefix = "__vite_glob_";
  28913. const { basename: basename$1, dirname: dirname$1, relative: relative$1 } = posix;
  28914. /**
  28915. * @param optimizeExport for dynamicImportVar plugin don't need to optimize export.
  28916. */
  28917. async function transformGlobImport(code, id, root, resolveId, restoreQueryExtension = false, logger) {
  28918. id = slash(id);
  28919. root = slash(root);
  28920. const isVirtual = isVirtualModule(id);
  28921. const dir = isVirtual ? void 0 : dirname$1(id);
  28922. const matches = await parseImportGlob(code, isVirtual ? void 0 : id, root, resolveId, logger);
  28923. const matchedFiles = /* @__PURE__ */ new Set();
  28924. if (!matches.length) return null;
  28925. const s = new MagicString(code);
  28926. const staticImports = (await Promise.all(matches.map(async ({ globsResolved, isRelative, options, index, start, end, onlyKeys, onlyValues }) => {
  28927. const files = (await glob(globsResolved, {
  28928. absolute: true,
  28929. cwd: getCommonBase(globsResolved) ?? root,
  28930. dot: !!options.exhaustive,
  28931. expandDirectories: false,
  28932. ignore: options.exhaustive ? [] : ["**/node_modules/**"],
  28933. extglob: false
  28934. })).filter((file) => file !== id).sort();
  28935. const objectProps = [];
  28936. const staticImports = [];
  28937. const resolvePaths = (file) => {
  28938. if (!dir) {
  28939. if (!options.base && isRelative) throw new Error("In virtual modules, all globs must start with '/'");
  28940. const importPath = `/${relative$1(root, file)}`;
  28941. let filePath = options.base ? `${relative$1(posix.join(root, options.base), file)}` : importPath;
  28942. if (options.base && !filePath.startsWith("./") && !filePath.startsWith("../")) filePath = `./${filePath}`;
  28943. return {
  28944. filePath,
  28945. importPath
  28946. };
  28947. }
  28948. let importPath = relative$1(dir, file);
  28949. if (!importPath.startsWith("./") && !importPath.startsWith("../")) importPath = `./${importPath}`;
  28950. let filePath;
  28951. if (options.base) {
  28952. filePath = relative$1(posix.join(options.base[0] === "/" ? root : dir, options.base), file);
  28953. if (!filePath.startsWith("./") && !filePath.startsWith("../")) filePath = `./${filePath}`;
  28954. if (options.base[0] === "/") importPath = `/${relative$1(root, file)}`;
  28955. } else if (isRelative) filePath = importPath;
  28956. else {
  28957. filePath = relative$1(root, file);
  28958. if (!filePath.startsWith("./") && !filePath.startsWith("../")) filePath = `/${filePath}`;
  28959. }
  28960. return {
  28961. filePath,
  28962. importPath
  28963. };
  28964. };
  28965. files.forEach((file, i) => {
  28966. const paths = resolvePaths(file);
  28967. const filePath = paths.filePath;
  28968. let importPath = paths.importPath;
  28969. let importQuery = options.query ?? "";
  28970. if (onlyKeys) {
  28971. objectProps.push(`${JSON.stringify(filePath)}: 0`);
  28972. return;
  28973. }
  28974. if (importQuery && importQuery !== "?raw") {
  28975. const fileExtension = basename$1(file).split(".").slice(-1)[0];
  28976. if (fileExtension && restoreQueryExtension) importQuery = `${importQuery}&lang.${fileExtension}`;
  28977. }
  28978. importPath = `${importPath}${importQuery}`;
  28979. const importKey = options.import && options.import !== "*" ? options.import : void 0;
  28980. if (options.eager) {
  28981. const variableName = `${importPrefix}${index}_${i}`;
  28982. const expression = importKey ? `{ ${importKey} as ${variableName} }` : `* as ${variableName}`;
  28983. staticImports.push(`import ${expression} from ${JSON.stringify(importPath)}`);
  28984. objectProps.push(onlyValues ? `${variableName}` : `${JSON.stringify(filePath)}: ${variableName}`);
  28985. } else {
  28986. let importStatement = `import(${JSON.stringify(importPath)})`;
  28987. if (importKey) importStatement += `.then(m => m[${JSON.stringify(importKey)}])`;
  28988. objectProps.push(onlyValues ? `() => ${importStatement}` : `${JSON.stringify(filePath)}: () => ${importStatement}`);
  28989. }
  28990. });
  28991. files.forEach((i) => matchedFiles.add(i));
  28992. const originalLineBreakCount = code.slice(start, end).match(/\n/g)?.length ?? 0;
  28993. const lineBreaks = originalLineBreakCount > 0 ? "\n".repeat(originalLineBreakCount) : "";
  28994. let replacement = "";
  28995. if (onlyKeys) replacement = `{${objectProps.join(",")}${lineBreaks}}`;
  28996. else if (onlyValues) replacement = `[${objectProps.join(",")}${lineBreaks}]`;
  28997. else replacement = `/* #__PURE__ */ Object.assign({${objectProps.join(",")}${lineBreaks}})`;
  28998. s.overwrite(start, end, replacement);
  28999. return staticImports;
  29000. }))).flat();
  29001. if (staticImports.length) s.prepend(`${staticImports.join(";")};`);
  29002. return {
  29003. s,
  29004. matches,
  29005. files: matchedFiles
  29006. };
  29007. }
  29008. function globSafePath(path) {
  29009. return escapePath(normalizePath(path));
  29010. }
  29011. function lastNthChar(str, n) {
  29012. return str.charAt(str.length - 1 - n);
  29013. }
  29014. function globSafeResolvedPath(resolved, glob) {
  29015. let numEqual = 0;
  29016. const maxEqual = Math.min(resolved.length, glob.length);
  29017. while (numEqual < maxEqual && lastNthChar(resolved, numEqual) === lastNthChar(glob, numEqual)) numEqual += 1;
  29018. const staticPartEnd = resolved.length - numEqual;
  29019. const staticPart = resolved.slice(0, staticPartEnd);
  29020. const dynamicPart = resolved.slice(staticPartEnd);
  29021. return globSafePath(staticPart) + dynamicPart;
  29022. }
  29023. async function toAbsoluteGlob(glob, root, importer, resolveId, base) {
  29024. let pre = "";
  29025. if (glob[0] === "!") {
  29026. pre = "!";
  29027. glob = glob.slice(1);
  29028. }
  29029. root = globSafePath(root);
  29030. let dir;
  29031. if (base) if (base[0] === "/") dir = posix.join(root, base);
  29032. else dir = posix.resolve(importer ? globSafePath(dirname$1(importer)) : root, base);
  29033. else dir = importer ? globSafePath(dirname$1(importer)) : root;
  29034. if (glob[0] === "/") return pre + posix.join(root, glob.slice(1));
  29035. if (glob.startsWith("./")) return pre + posix.join(dir, glob.slice(2));
  29036. if (glob.startsWith("../")) return pre + posix.join(dir, glob);
  29037. if (glob.startsWith("**")) return pre + glob;
  29038. const isSubImportsPattern = glob[0] === "#" && glob.includes("*");
  29039. const resolved = normalizePath(await resolveId(glob, importer, { custom: { "vite:import-glob": { isSubImportsPattern } } }) || glob);
  29040. if (isAbsolute(resolved)) return pre + globSafeResolvedPath(resolved, glob);
  29041. throw new Error(`Invalid glob: "${glob}" (resolved: "${resolved}"). It must start with '/' or './'`);
  29042. }
  29043. function getCommonBase(globsResolved) {
  29044. const bases = globsResolved.filter((g) => g[0] !== "!").map((glob) => {
  29045. let { base } = picomatch.scan(glob);
  29046. if (posix.basename(base).includes(".")) base = posix.dirname(base);
  29047. return base;
  29048. });
  29049. if (!bases.length) return null;
  29050. let commonAncestor = "";
  29051. const dirS = bases[0].split("/");
  29052. for (let i = 0; i < dirS.length; i++) {
  29053. const candidate = dirS.slice(0, i + 1).join("/");
  29054. if (bases.every((base) => base.startsWith(candidate))) commonAncestor = candidate;
  29055. else break;
  29056. }
  29057. if (!commonAncestor) commonAncestor = "/";
  29058. return commonAncestor;
  29059. }
  29060. function isVirtualModule(id) {
  29061. return id.startsWith("virtual:") || id[0] === "\0" || !id.includes("/");
  29062. }
  29063. //#endregion
  29064. //#region src/node/plugins/pluginFilter.ts
  29065. function getMatcherString(glob, cwd) {
  29066. if (glob.startsWith("**") || path.isAbsolute(glob)) return slash(glob);
  29067. return slash(path.join(cwd, glob));
  29068. }
  29069. function patternToIdFilter(pattern, cwd) {
  29070. if (pattern instanceof RegExp) return (id) => {
  29071. const normalizedId = slash(id);
  29072. const result = pattern.test(normalizedId);
  29073. pattern.lastIndex = 0;
  29074. return result;
  29075. };
  29076. const matcher = picomatch(getMatcherString(pattern, cwd), { dot: true });
  29077. return (id) => {
  29078. return matcher(slash(id));
  29079. };
  29080. }
  29081. function patternToCodeFilter(pattern) {
  29082. if (pattern instanceof RegExp) return (code) => {
  29083. const result = pattern.test(code);
  29084. pattern.lastIndex = 0;
  29085. return result;
  29086. };
  29087. return (code) => code.includes(pattern);
  29088. }
  29089. function createFilter(exclude, include) {
  29090. if (!exclude && !include) return;
  29091. return (input) => {
  29092. if (exclude?.some((filter) => filter(input))) return false;
  29093. if (include?.some((filter) => filter(input))) return true;
  29094. return !(include && include.length > 0);
  29095. };
  29096. }
  29097. function normalizeFilter(filter) {
  29098. if (typeof filter === "string" || filter instanceof RegExp) return { include: [filter] };
  29099. if (Array.isArray(filter)) return { include: filter };
  29100. return {
  29101. include: filter.include ? arraify(filter.include) : void 0,
  29102. exclude: filter.exclude ? arraify(filter.exclude) : void 0
  29103. };
  29104. }
  29105. function createIdFilter(filter, cwd = process.cwd()) {
  29106. if (!filter) return;
  29107. const { exclude, include } = normalizeFilter(filter);
  29108. const excludeFilter = exclude?.map((p) => patternToIdFilter(p, cwd));
  29109. const includeFilter = include?.map((p) => patternToIdFilter(p, cwd));
  29110. return createFilter(excludeFilter, includeFilter);
  29111. }
  29112. function createCodeFilter(filter) {
  29113. if (!filter) return;
  29114. const { exclude, include } = normalizeFilter(filter);
  29115. const excludeFilter = exclude?.map(patternToCodeFilter);
  29116. const includeFilter = include?.map(patternToCodeFilter);
  29117. return createFilter(excludeFilter, includeFilter);
  29118. }
  29119. function createModuleTypeFilter(filter) {
  29120. if (!filter) return;
  29121. const include = Array.isArray(filter) ? filter : filter.include ?? [];
  29122. return (moduleType) => include.includes(moduleType);
  29123. }
  29124. function createFilterForTransform(idFilter, codeFilter, moduleTypeFilter, cwd) {
  29125. if (!idFilter && !codeFilter && !moduleTypeFilter) return;
  29126. const idFilterFn = createIdFilter(idFilter, cwd);
  29127. const codeFilterFn = createCodeFilter(codeFilter);
  29128. const moduleTypeFilterFn = createModuleTypeFilter(moduleTypeFilter);
  29129. return (id, code, moduleType) => {
  29130. let fallback = moduleTypeFilterFn?.(moduleType) ?? true;
  29131. if (!fallback) return false;
  29132. if (idFilterFn) fallback &&= idFilterFn(id);
  29133. if (!fallback) return false;
  29134. if (codeFilterFn) fallback &&= codeFilterFn(code);
  29135. return fallback;
  29136. };
  29137. }
  29138. //#endregion
  29139. //#region ../../node_modules/.pnpm/@vitest+utils@4.1.2/node_modules/@vitest/utils/dist/helpers.js
  29140. function notNullish(v) {
  29141. return v != null;
  29142. }
  29143. function isPrimitive(value) {
  29144. return value === null || typeof value !== "function" && typeof value !== "object";
  29145. }
  29146. //#endregion
  29147. //#region ../../node_modules/.pnpm/@vitest+utils@4.1.2/node_modules/@vitest/utils/dist/chunk-pathe.M-eThtNZ.js
  29148. const _DRIVE_LETTER_START_RE = /^[A-Za-z]:\//;
  29149. function normalizeWindowsPath(input = "") {
  29150. if (!input) return input;
  29151. return input.replace(/\\/g, "/").replace(_DRIVE_LETTER_START_RE, (r) => r.toUpperCase());
  29152. }
  29153. const _IS_ABSOLUTE_RE = /^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/;
  29154. function cwd() {
  29155. if (typeof process !== "undefined" && typeof process.cwd === "function") return process.cwd().replace(/\\/g, "/");
  29156. return "/";
  29157. }
  29158. const resolve$2 = function(...arguments_) {
  29159. arguments_ = arguments_.map((argument) => normalizeWindowsPath(argument));
  29160. let resolvedPath = "";
  29161. let resolvedAbsolute = false;
  29162. for (let index = arguments_.length - 1; index >= -1 && !resolvedAbsolute; index--) {
  29163. const path = index >= 0 ? arguments_[index] : cwd();
  29164. if (!path || path.length === 0) continue;
  29165. resolvedPath = `${path}/${resolvedPath}`;
  29166. resolvedAbsolute = isAbsolute$2(path);
  29167. }
  29168. resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute);
  29169. if (resolvedAbsolute && !isAbsolute$2(resolvedPath)) return `/${resolvedPath}`;
  29170. return resolvedPath.length > 0 ? resolvedPath : ".";
  29171. };
  29172. function normalizeString(path, allowAboveRoot) {
  29173. let res = "";
  29174. let lastSegmentLength = 0;
  29175. let lastSlash = -1;
  29176. let dots = 0;
  29177. let char = null;
  29178. for (let index = 0; index <= path.length; ++index) {
  29179. if (index < path.length) char = path[index];
  29180. else if (char === "/") break;
  29181. else char = "/";
  29182. if (char === "/") {
  29183. if (lastSlash === index - 1 || dots === 1);
  29184. else if (dots === 2) {
  29185. if (res.length < 2 || lastSegmentLength !== 2 || res[res.length - 1] !== "." || res[res.length - 2] !== ".") {
  29186. if (res.length > 2) {
  29187. const lastSlashIndex = res.lastIndexOf("/");
  29188. if (lastSlashIndex === -1) {
  29189. res = "";
  29190. lastSegmentLength = 0;
  29191. } else {
  29192. res = res.slice(0, lastSlashIndex);
  29193. lastSegmentLength = res.length - 1 - res.lastIndexOf("/");
  29194. }
  29195. lastSlash = index;
  29196. dots = 0;
  29197. continue;
  29198. } else if (res.length > 0) {
  29199. res = "";
  29200. lastSegmentLength = 0;
  29201. lastSlash = index;
  29202. dots = 0;
  29203. continue;
  29204. }
  29205. }
  29206. if (allowAboveRoot) {
  29207. res += res.length > 0 ? "/.." : "..";
  29208. lastSegmentLength = 2;
  29209. }
  29210. } else {
  29211. if (res.length > 0) res += `/${path.slice(lastSlash + 1, index)}`;
  29212. else res = path.slice(lastSlash + 1, index);
  29213. lastSegmentLength = index - lastSlash - 1;
  29214. }
  29215. lastSlash = index;
  29216. dots = 0;
  29217. } else if (char === "." && dots !== -1) ++dots;
  29218. else dots = -1;
  29219. }
  29220. return res;
  29221. }
  29222. const isAbsolute$2 = function(p) {
  29223. return _IS_ABSOLUTE_RE.test(p);
  29224. };
  29225. //#endregion
  29226. //#region ../../node_modules/.pnpm/@vitest+utils@4.1.2/node_modules/@vitest/utils/dist/source-map.js
  29227. var comma = ",".charCodeAt(0);
  29228. var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  29229. var intToChar = new Uint8Array(64);
  29230. var charToInt = new Uint8Array(128);
  29231. for (let i = 0; i < chars.length; i++) {
  29232. const c = chars.charCodeAt(i);
  29233. intToChar[i] = c;
  29234. charToInt[c] = i;
  29235. }
  29236. function decodeInteger(reader, relative) {
  29237. let value = 0;
  29238. let shift = 0;
  29239. let integer = 0;
  29240. do {
  29241. integer = charToInt[reader.next()];
  29242. value |= (integer & 31) << shift;
  29243. shift += 5;
  29244. } while (integer & 32);
  29245. const shouldNegate = value & 1;
  29246. value >>>= 1;
  29247. if (shouldNegate) value = -2147483648 | -value;
  29248. return relative + value;
  29249. }
  29250. function hasMoreVlq(reader, max) {
  29251. if (reader.pos >= max) return false;
  29252. return reader.peek() !== comma;
  29253. }
  29254. var StringReader = class {
  29255. constructor(buffer) {
  29256. this.pos = 0;
  29257. this.buffer = buffer;
  29258. }
  29259. next() {
  29260. return this.buffer.charCodeAt(this.pos++);
  29261. }
  29262. peek() {
  29263. return this.buffer.charCodeAt(this.pos);
  29264. }
  29265. indexOf(char) {
  29266. const { buffer, pos } = this;
  29267. const idx = buffer.indexOf(char, pos);
  29268. return idx === -1 ? buffer.length : idx;
  29269. }
  29270. };
  29271. function decode(mappings) {
  29272. const { length } = mappings;
  29273. const reader = new StringReader(mappings);
  29274. const decoded = [];
  29275. let genColumn = 0;
  29276. let sourcesIndex = 0;
  29277. let sourceLine = 0;
  29278. let sourceColumn = 0;
  29279. let namesIndex = 0;
  29280. do {
  29281. const semi = reader.indexOf(";");
  29282. const line = [];
  29283. let sorted = true;
  29284. let lastCol = 0;
  29285. genColumn = 0;
  29286. while (reader.pos < semi) {
  29287. let seg;
  29288. genColumn = decodeInteger(reader, genColumn);
  29289. if (genColumn < lastCol) sorted = false;
  29290. lastCol = genColumn;
  29291. if (hasMoreVlq(reader, semi)) {
  29292. sourcesIndex = decodeInteger(reader, sourcesIndex);
  29293. sourceLine = decodeInteger(reader, sourceLine);
  29294. sourceColumn = decodeInteger(reader, sourceColumn);
  29295. if (hasMoreVlq(reader, semi)) {
  29296. namesIndex = decodeInteger(reader, namesIndex);
  29297. seg = [
  29298. genColumn,
  29299. sourcesIndex,
  29300. sourceLine,
  29301. sourceColumn,
  29302. namesIndex
  29303. ];
  29304. } else seg = [
  29305. genColumn,
  29306. sourcesIndex,
  29307. sourceLine,
  29308. sourceColumn
  29309. ];
  29310. } else seg = [genColumn];
  29311. line.push(seg);
  29312. reader.pos++;
  29313. }
  29314. if (!sorted) sort(line);
  29315. decoded.push(line);
  29316. reader.pos = semi + 1;
  29317. } while (reader.pos <= length);
  29318. return decoded;
  29319. }
  29320. function sort(line) {
  29321. line.sort(sortComparator);
  29322. }
  29323. function sortComparator(a, b) {
  29324. return a[0] - b[0];
  29325. }
  29326. var COLUMN = 0;
  29327. var SOURCES_INDEX = 1;
  29328. var SOURCE_LINE = 2;
  29329. var SOURCE_COLUMN = 3;
  29330. var NAMES_INDEX = 4;
  29331. var found = false;
  29332. function binarySearch(haystack, needle, low, high) {
  29333. while (low <= high) {
  29334. const mid = low + (high - low >> 1);
  29335. const cmp = haystack[mid][COLUMN] - needle;
  29336. if (cmp === 0) {
  29337. found = true;
  29338. return mid;
  29339. }
  29340. if (cmp < 0) low = mid + 1;
  29341. else high = mid - 1;
  29342. }
  29343. found = false;
  29344. return low - 1;
  29345. }
  29346. function upperBound(haystack, needle, index) {
  29347. for (let i = index + 1; i < haystack.length; index = i++) if (haystack[i][COLUMN] !== needle) break;
  29348. return index;
  29349. }
  29350. function lowerBound(haystack, needle, index) {
  29351. for (let i = index - 1; i >= 0; index = i--) if (haystack[i][COLUMN] !== needle) break;
  29352. return index;
  29353. }
  29354. function memoizedBinarySearch(haystack, needle, state, key) {
  29355. const { lastKey, lastNeedle, lastIndex } = state;
  29356. let low = 0;
  29357. let high = haystack.length - 1;
  29358. if (key === lastKey) {
  29359. if (needle === lastNeedle) {
  29360. found = lastIndex !== -1 && haystack[lastIndex][COLUMN] === needle;
  29361. return lastIndex;
  29362. }
  29363. if (needle >= lastNeedle) low = lastIndex === -1 ? 0 : lastIndex;
  29364. else high = lastIndex;
  29365. }
  29366. state.lastKey = key;
  29367. state.lastNeedle = needle;
  29368. return state.lastIndex = binarySearch(haystack, needle, low, high);
  29369. }
  29370. var LINE_GTR_ZERO = "`line` must be greater than 0 (lines start at line 1)";
  29371. var COL_GTR_EQ_ZERO = "`column` must be greater than or equal to 0 (columns start at column 0)";
  29372. var LEAST_UPPER_BOUND = -1;
  29373. var GREATEST_LOWER_BOUND = 1;
  29374. function cast(map) {
  29375. return map;
  29376. }
  29377. function decodedMappings(map) {
  29378. var _a;
  29379. return (_a = cast(map))._decoded || (_a._decoded = decode(cast(map)._encoded));
  29380. }
  29381. function originalPositionFor(map, needle) {
  29382. let { line, column, bias } = needle;
  29383. line--;
  29384. if (line < 0) throw new Error(LINE_GTR_ZERO);
  29385. if (column < 0) throw new Error(COL_GTR_EQ_ZERO);
  29386. const decoded = decodedMappings(map);
  29387. if (line >= decoded.length) return OMapping(null, null, null, null);
  29388. const segments = decoded[line];
  29389. const index = traceSegmentInternal(segments, cast(map)._decodedMemo, line, column, bias || GREATEST_LOWER_BOUND);
  29390. if (index === -1) return OMapping(null, null, null, null);
  29391. const segment = segments[index];
  29392. if (segment.length === 1) return OMapping(null, null, null, null);
  29393. const { names, resolvedSources } = map;
  29394. return OMapping(resolvedSources[segment[SOURCES_INDEX]], segment[SOURCE_LINE] + 1, segment[SOURCE_COLUMN], segment.length === 5 ? names[segment[NAMES_INDEX]] : null);
  29395. }
  29396. function OMapping(source, line, column, name) {
  29397. return {
  29398. source,
  29399. line,
  29400. column,
  29401. name
  29402. };
  29403. }
  29404. function traceSegmentInternal(segments, memo, line, column, bias) {
  29405. let index = memoizedBinarySearch(segments, column, memo, line);
  29406. if (found) index = (bias === LEAST_UPPER_BOUND ? upperBound : lowerBound)(segments, column, index);
  29407. else if (bias === LEAST_UPPER_BOUND) index++;
  29408. if (index === -1 || index === segments.length) return -1;
  29409. return index;
  29410. }
  29411. const CHROME_IE_STACK_REGEXP = /^\s*at .*(?:\S:\d+|\(native\))/m;
  29412. const SAFARI_NATIVE_CODE_REGEXP = /^(?:eval@)?(?:\[native code\])?$/;
  29413. const stackIgnorePatterns = [
  29414. "node:internal",
  29415. /\/packages\/\w+\/dist\//,
  29416. /\/@vitest\/\w+\/dist\//,
  29417. "/vitest/dist/",
  29418. "/vitest/src/",
  29419. "/node_modules/chai/",
  29420. "/node_modules/tinyspy/",
  29421. "/vite/dist/node/module-runner",
  29422. "/rolldown-vite/dist/node/module-runner",
  29423. "/deps/chunk-",
  29424. "/deps/@vitest",
  29425. "/deps/loupe",
  29426. "/deps/chai",
  29427. "/browser-playwright/dist/locators.js",
  29428. "/browser-webdriverio/dist/locators.js",
  29429. "/browser-preview/dist/locators.js",
  29430. /node:\w+/,
  29431. /__vitest_test__/,
  29432. /__vitest_browser__/,
  29433. "/@id/__x00__vitest/browser",
  29434. /\/deps\/vitest_/
  29435. ];
  29436. const NOW_LENGTH = Date.now().toString().length;
  29437. const REGEXP_VITEST = new RegExp(`vitest=\\d{${NOW_LENGTH}}`);
  29438. function extractLocation(urlLike) {
  29439. if (!urlLike.includes(":")) return [urlLike];
  29440. const parts = /(.+?)(?::(\d+))?(?::(\d+))?$/.exec(urlLike.replace(/^\(|\)$/g, ""));
  29441. if (!parts) return [urlLike];
  29442. let url = parts[1];
  29443. if (url.startsWith("async ")) url = url.slice(6);
  29444. if (url.startsWith("http:") || url.startsWith("https:")) {
  29445. const urlObj = new URL(url);
  29446. urlObj.searchParams.delete("import");
  29447. urlObj.searchParams.delete("browserv");
  29448. url = urlObj.pathname + urlObj.hash + urlObj.search;
  29449. }
  29450. if (url.startsWith("/@fs/")) {
  29451. const isWindows = /^\/@fs\/[a-zA-Z]:\//.test(url);
  29452. url = url.slice(isWindows ? 5 : 4);
  29453. }
  29454. if (url.includes("vitest=")) url = url.replace(REGEXP_VITEST, "").replace(/[?&]$/, "");
  29455. return [
  29456. url,
  29457. parts[2] || void 0,
  29458. parts[3] || void 0
  29459. ];
  29460. }
  29461. function parseSingleFFOrSafariStack(raw) {
  29462. let line = raw.trim();
  29463. if (SAFARI_NATIVE_CODE_REGEXP.test(line)) return null;
  29464. if (line.includes(" > eval")) line = line.replace(/ line (\d+)(?: > eval line \d+)* > eval:\d+:\d+/g, ":$1");
  29465. if (!line.includes("@")) return null;
  29466. let atIndex = -1;
  29467. let locationPart = "";
  29468. let functionName;
  29469. for (let i = 0; i < line.length; i++) if (line[i] === "@") {
  29470. const candidateLocation = line.slice(i + 1);
  29471. if (candidateLocation.includes(":") && candidateLocation.length >= 3) {
  29472. atIndex = i;
  29473. locationPart = candidateLocation;
  29474. functionName = i > 0 ? line.slice(0, i) : void 0;
  29475. break;
  29476. }
  29477. }
  29478. if (atIndex === -1 || !locationPart.includes(":") || locationPart.length < 3) return null;
  29479. const [url, lineNumber, columnNumber] = extractLocation(locationPart);
  29480. if (!url || !lineNumber || !columnNumber) return null;
  29481. return {
  29482. file: url,
  29483. method: functionName || "",
  29484. line: Number.parseInt(lineNumber),
  29485. column: Number.parseInt(columnNumber)
  29486. };
  29487. }
  29488. function parseSingleV8Stack(raw) {
  29489. let line = raw.trim();
  29490. if (!CHROME_IE_STACK_REGEXP.test(line)) return null;
  29491. if (line.includes("(eval ")) line = line.replace(/eval code/g, "eval").replace(/(\(eval at [^()]*)|(,.*$)/g, "");
  29492. let sanitizedLine = line.replace(/^\s+/, "").replace(/\(eval code/g, "(").replace(/^.*?\s+/, "");
  29493. const location = sanitizedLine.match(/ (\(.+\)$)/);
  29494. sanitizedLine = location ? sanitizedLine.replace(location[0], "") : sanitizedLine;
  29495. const [url, lineNumber, columnNumber] = extractLocation(location ? location[1] : sanitizedLine);
  29496. let method = location && sanitizedLine || "";
  29497. let file = url && ["eval", "<anonymous>"].includes(url) ? void 0 : url;
  29498. if (!file || !lineNumber || !columnNumber) return null;
  29499. if (method.startsWith("async ")) method = method.slice(6);
  29500. if (file.startsWith("file://")) file = file.slice(7);
  29501. file = file.startsWith("node:") || file.startsWith("internal:") ? file : resolve$2(file);
  29502. if (method) method = method.replace(/\(0\s?,\s?__vite_ssr_import_\d+__.(\w+)\)/g, "$1").replace(/__(vite_ssr_import|vi_import)_\d+__\./g, "").replace(/(Object\.)?__vite_ssr_export_default__\s?/g, "");
  29503. return {
  29504. method,
  29505. file,
  29506. line: Number.parseInt(lineNumber),
  29507. column: Number.parseInt(columnNumber)
  29508. };
  29509. }
  29510. function parseStacktrace(stack, options = {}) {
  29511. const { ignoreStackEntries = stackIgnorePatterns } = options;
  29512. let stacks = !CHROME_IE_STACK_REGEXP.test(stack) ? parseFFOrSafariStackTrace(stack) : parseV8Stacktrace(stack);
  29513. const helperIndex = stacks.findLastIndex((s) => s.method === "__VITEST_HELPER__" || s.method === "async*__VITEST_HELPER__");
  29514. if (helperIndex >= 0) stacks = stacks.slice(helperIndex + 1);
  29515. return stacks.map((stack) => {
  29516. if (options.getUrlId) stack.file = options.getUrlId(stack.file);
  29517. const map = options.getSourceMap?.(stack.file);
  29518. if (!map || typeof map !== "object" || !map.version) return shouldFilter(ignoreStackEntries, stack.file) ? null : stack;
  29519. const position = getOriginalPosition(new DecodedMap(map, stack.file), stack);
  29520. if (!position) return stack;
  29521. const { line, column, source, name } = position;
  29522. let file = source || stack.file;
  29523. if (file.match(/\/\w:\//)) file = file.slice(1);
  29524. if (shouldFilter(ignoreStackEntries, file)) return null;
  29525. if (line != null && column != null) return {
  29526. line,
  29527. column,
  29528. file,
  29529. method: name || stack.method
  29530. };
  29531. return stack;
  29532. }).filter((s) => s != null);
  29533. }
  29534. function shouldFilter(ignoreStackEntries, file) {
  29535. return ignoreStackEntries.some((p) => file.match(p));
  29536. }
  29537. function parseFFOrSafariStackTrace(stack) {
  29538. return stack.split("\n").map((line) => parseSingleFFOrSafariStack(line)).filter(notNullish);
  29539. }
  29540. function parseV8Stacktrace(stack) {
  29541. return stack.split("\n").map((line) => parseSingleV8Stack(line)).filter(notNullish);
  29542. }
  29543. function parseErrorStacktrace(e, options = {}) {
  29544. if (!e || isPrimitive(e)) return [];
  29545. if ("stacks" in e && e.stacks) return e.stacks;
  29546. const stackStr = e.stack || "";
  29547. let stackFrames = typeof stackStr === "string" ? parseStacktrace(stackStr, options) : [];
  29548. if (!stackFrames.length) {
  29549. const e_ = e;
  29550. if (e_.fileName != null && e_.lineNumber != null && e_.columnNumber != null) stackFrames = parseStacktrace(`${e_.fileName}:${e_.lineNumber}:${e_.columnNumber}`, options);
  29551. if (e_.sourceURL != null && e_.line != null && e_._column != null) stackFrames = parseStacktrace(`${e_.sourceURL}:${e_.line}:${e_.column}`, options);
  29552. }
  29553. if (options.frameFilter) stackFrames = stackFrames.filter((f) => options.frameFilter(e, f) !== false);
  29554. e.stacks = stackFrames;
  29555. return stackFrames;
  29556. }
  29557. var DecodedMap = class {
  29558. _encoded;
  29559. _decoded;
  29560. _decodedMemo;
  29561. url;
  29562. version;
  29563. names = [];
  29564. resolvedSources;
  29565. constructor(map, from) {
  29566. this.map = map;
  29567. const { mappings, names, sources } = map;
  29568. this.version = map.version;
  29569. this.names = names || [];
  29570. this._encoded = mappings || "";
  29571. this._decodedMemo = memoizedState();
  29572. this.url = from;
  29573. this.resolvedSources = (sources || []).map((s) => resolve$2(from, "..", s || ""));
  29574. }
  29575. };
  29576. function memoizedState() {
  29577. return {
  29578. lastKey: -1,
  29579. lastNeedle: -1,
  29580. lastIndex: -1
  29581. };
  29582. }
  29583. function getOriginalPosition(map, needle) {
  29584. const result = originalPositionFor(map, needle);
  29585. if (result.column == null) return null;
  29586. return result;
  29587. }
  29588. //#endregion
  29589. //#region src/node/plugins/forwardConsole.ts
  29590. function forwardConsolePlugin(pluginOpts) {
  29591. const sourceMapCache = /* @__PURE__ */ new Map();
  29592. return {
  29593. name: "vite:forward-console",
  29594. apply: "serve",
  29595. configureServer(server) {
  29596. for (const name of pluginOpts.environments) {
  29597. const environment = server.environments[name];
  29598. environment.hot.on("vite:forward-console", (payload) => {
  29599. if (payload.type === "error" || payload.type === "unhandled-rejection") {
  29600. const output = formatError(payload, environment, sourceMapCache);
  29601. environment.config.logger.error(output, { timestamp: true });
  29602. } else {
  29603. const output = import_picocolors.default.dim(`[console.${payload.data.level}] `) + payload.data.message;
  29604. if (payload.data.level === "error") environment.config.logger.error(output, { timestamp: true });
  29605. else if (payload.data.level === "warn") environment.config.logger.warn(output, { timestamp: true });
  29606. else environment.config.logger.info(output, { timestamp: true });
  29607. }
  29608. });
  29609. }
  29610. }
  29611. };
  29612. }
  29613. function formatError(payload, environment, sourceMapCache) {
  29614. const error = payload.data;
  29615. const stacks = parseErrorStacktrace(error, {
  29616. getUrlId(id) {
  29617. const moduleGraph = environment.moduleGraph;
  29618. if (moduleGraph.getModuleById(id)) return id;
  29619. const resolvedPath = normalizePath(path.resolve(environment.config.root, id.slice(1)));
  29620. if (moduleGraph.getModuleById(resolvedPath)) return resolvedPath;
  29621. const files = moduleGraph.getModulesByFile(resolvedPath);
  29622. if (files && files.size) return files.values().next().value.id;
  29623. return id;
  29624. },
  29625. getSourceMap(id) {
  29626. if (sourceMapCache.has(id)) return sourceMapCache.get(id);
  29627. const result = environment.moduleGraph.getModuleById(id)?.transformResult;
  29628. if (result && !result.map) try {
  29629. const filePath = id.split("?")[0];
  29630. const extracted = extractSourcemapFromFile(result.code, filePath, environment.config.logger);
  29631. sourceMapCache.set(id, extracted?.map);
  29632. return extracted?.map;
  29633. } catch {
  29634. sourceMapCache.set(id, null);
  29635. return null;
  29636. }
  29637. sourceMapCache.set(id, result?.map);
  29638. return result?.map;
  29639. },
  29640. ignoreStackEntries: []
  29641. });
  29642. const nearest = stacks.find((stack) => {
  29643. return [...environment.moduleGraph.getModulesByFile(stack.file) || []].some((m) => m.transformResult) && fs.existsSync(stack.file);
  29644. });
  29645. let output = "";
  29646. output += import_picocolors.default.red(`${payload.type === "unhandled-rejection" ? "[Unhandled rejection]" : "[Unhandled error]"} ${import_picocolors.default.bold(error.name)}: ${error.message}\n`);
  29647. for (const stack of stacks) {
  29648. const file = normalizePath(path.relative(environment.config.root, stack.file));
  29649. output += ` > ${[stack.method, `${file}:${stack.line}:${stack.column}`].filter(Boolean).join(" ")}\n`;
  29650. if (stack === nearest) {
  29651. const code = fs.readFileSync(stack.file, "utf-8");
  29652. output += generateCodeFrame(code, stack).replace(/^/gm, " ");
  29653. output += "\n";
  29654. }
  29655. }
  29656. return output;
  29657. }
  29658. //#endregion
  29659. //#region src/node/plugins/esbuildBannerFooterCompatPlugin.ts
  29660. /**
  29661. * This plugin supports `esbuild.banner` and `esbuild.footer` options.
  29662. * esbuild supported these options and Vite exposed them.
  29663. * But this should be done by plugin with transform hook.
  29664. * This plugin makes these options work in rolldown-vite as a backward compat for now.
  29665. */
  29666. function esbuildBannerFooterCompatPlugin(config) {
  29667. const options = config.esbuild;
  29668. if (!options) return;
  29669. const { include, exclude, banner, footer } = options;
  29670. if (!banner && !footer) return;
  29671. const filter = createFilter$1(include || /\.(m?ts|[jt]sx)$/, exclude || /\.js$/);
  29672. return {
  29673. name: "vite:esbuild-banner-footer-compat",
  29674. transform(code, id) {
  29675. if (filter(id) || filter(cleanUrl(id))) {
  29676. if (!(this.environment.mode === "dev" || this.environment.mode === "build" && this.environment.config.build.sourcemap)) {
  29677. if (banner) code = `${banner}\n${code}`;
  29678. if (footer) code = `${code}\n${footer}`;
  29679. return code;
  29680. }
  29681. let s;
  29682. const str = () => s || (s = new MagicString(code));
  29683. if (banner) str().prepend(`${banner}\n`);
  29684. if (footer) str().append(`${footer}\n`);
  29685. if (s) return {
  29686. code: s.toString(),
  29687. map: s.generateMap({ hires: "boundary" })
  29688. };
  29689. }
  29690. }
  29691. };
  29692. }
  29693. //#endregion
  29694. //#region src/node/plugins/index.ts
  29695. async function resolvePlugins(config, prePlugins, normalPlugins, postPlugins) {
  29696. const isBuild = config.command === "build";
  29697. const isBundled = config.isBundled;
  29698. const isWorker = config.isWorker;
  29699. const buildPlugins = isBundled ? await (await import("./build.js")).resolveBuildPlugins(config) : {
  29700. pre: [],
  29701. post: []
  29702. };
  29703. const { modulePreload } = config.build;
  29704. return [
  29705. !isBundled ? optimizedDepsPlugin() : null,
  29706. !isWorker ? watchPackageDataPlugin(config.packageCache) : null,
  29707. !isBundled ? preAliasPlugin(config) : null,
  29708. isBundled && !config.resolve.alias.some((v) => v.customResolver) ? viteAliasPlugin({ entries: config.resolve.alias.map((item) => {
  29709. return {
  29710. find: item.find,
  29711. replacement: item.replacement
  29712. };
  29713. }) }) : alias$1({
  29714. entries: config.resolve.alias,
  29715. customResolver: viteAliasCustomResolver
  29716. }),
  29717. ...prePlugins,
  29718. modulePreload !== false && modulePreload.polyfill ? modulePreloadPolyfillPlugin(config) : null,
  29719. ...oxcResolvePlugin({
  29720. root: config.root,
  29721. isProduction: config.isProduction,
  29722. isBuild,
  29723. packageCache: config.packageCache,
  29724. asSrc: true,
  29725. optimizeDeps: true,
  29726. externalize: true,
  29727. legacyInconsistentCjsInterop: config.legacy?.inconsistentCjsInterop
  29728. }, isWorker ? {
  29729. ...config,
  29730. consumer: "client",
  29731. optimizeDepsPluginNames: []
  29732. } : void 0),
  29733. htmlInlineProxyPlugin(config),
  29734. cssPlugin(config),
  29735. esbuildBannerFooterCompatPlugin(config),
  29736. config.oxc !== false && !isBundled ? oxcRuntimePlugin() : null,
  29737. config.oxc !== false ? oxcPlugin(config) : null,
  29738. viteJsonPlugin({
  29739. ...config.json,
  29740. minify: isBuild
  29741. }),
  29742. wasmHelperPlugin(),
  29743. webWorkerPlugin(config),
  29744. assetPlugin(config),
  29745. config.server.forwardConsole.enabled && forwardConsolePlugin({ environments: ["client"] }),
  29746. ...normalPlugins,
  29747. viteWasmFallbackPlugin(),
  29748. definePlugin(config),
  29749. cssPostPlugin(config),
  29750. isBundled && buildHtmlPlugin(config),
  29751. workerImportMetaUrlPlugin(config),
  29752. assetImportMetaUrlPlugin(config),
  29753. ...buildPlugins.pre,
  29754. dynamicImportVarsPlugin(config),
  29755. importGlobPlugin(config),
  29756. ...postPlugins,
  29757. ...buildPlugins.post,
  29758. ...isBundled ? [] : [
  29759. clientInjectionsPlugin(config),
  29760. cssAnalysisPlugin(config),
  29761. importAnalysisPlugin(config)
  29762. ]
  29763. ].filter(Boolean);
  29764. }
  29765. function createPluginHookUtils(plugins) {
  29766. const sortedPluginsCache = /* @__PURE__ */ new Map();
  29767. function getSortedPlugins(hookName) {
  29768. if (sortedPluginsCache.has(hookName)) return sortedPluginsCache.get(hookName);
  29769. const sorted = getSortedPluginsByHook(hookName, plugins);
  29770. sortedPluginsCache.set(hookName, sorted);
  29771. return sorted;
  29772. }
  29773. function getSortedPluginHooks(hookName) {
  29774. return getSortedPlugins(hookName).map((p) => getHookHandler(p[hookName])).filter(Boolean);
  29775. }
  29776. return {
  29777. getSortedPlugins,
  29778. getSortedPluginHooks
  29779. };
  29780. }
  29781. function getSortedPluginsByHook(hookName, plugins) {
  29782. const sortedPlugins = [];
  29783. let pre = 0, normal = 0, post = 0;
  29784. for (const plugin of plugins) {
  29785. const hook = plugin[hookName];
  29786. if (hook) {
  29787. if (typeof hook === "object") {
  29788. if (hook.order === "pre") {
  29789. sortedPlugins.splice(pre++, 0, plugin);
  29790. continue;
  29791. }
  29792. if (hook.order === "post") {
  29793. sortedPlugins.splice(pre + normal + post++, 0, plugin);
  29794. continue;
  29795. }
  29796. }
  29797. sortedPlugins.splice(pre + normal++, 0, plugin);
  29798. }
  29799. }
  29800. return sortedPlugins;
  29801. }
  29802. function getHookHandler(hook) {
  29803. return typeof hook === "object" ? hook.handler : hook;
  29804. }
  29805. const filterForPlugin = /* @__PURE__ */ new WeakMap();
  29806. function getCachedFilterForPlugin(plugin, hookName) {
  29807. let filters = filterForPlugin.get(plugin);
  29808. if (filters && hookName in filters) return filters[hookName];
  29809. if (!filters) {
  29810. filters = {};
  29811. filterForPlugin.set(plugin, filters);
  29812. }
  29813. let filter;
  29814. switch (hookName) {
  29815. case "resolveId": {
  29816. const rawFilter = extractFilter(plugin.resolveId)?.id;
  29817. filters.resolveId = createIdFilter(rawFilter);
  29818. filter = filters.resolveId;
  29819. break;
  29820. }
  29821. case "load": {
  29822. const rawFilter = extractFilter(plugin.load)?.id;
  29823. filters.load = createIdFilter(rawFilter);
  29824. filter = filters.load;
  29825. break;
  29826. }
  29827. case "transform": {
  29828. const rawFilters = extractFilter(plugin.transform);
  29829. filters.transform = createFilterForTransform(rawFilters?.id, rawFilters?.code, rawFilters?.moduleType);
  29830. filter = filters.transform;
  29831. break;
  29832. }
  29833. }
  29834. return filter;
  29835. }
  29836. function extractFilter(hook) {
  29837. return hook && "filter" in hook && hook.filter ? hook.filter : void 0;
  29838. }
  29839. const viteAliasCustomResolver = async function(id, importer, options) {
  29840. return await this.resolve(id, importer, options) || {
  29841. id,
  29842. meta: { "vite:alias": { noResolved: true } }
  29843. };
  29844. };
  29845. //#endregion
  29846. //#region src/node/server/pluginContainer.ts
  29847. /**
  29848. * This file is refactored into TypeScript based on
  29849. * https://github.com/preactjs/wmr/blob/main/packages/wmr/src/lib/rollup-plugin-container.js
  29850. */
  29851. /**
  29852. https://github.com/preactjs/wmr/blob/master/LICENSE
  29853. MIT License
  29854. Copyright (c) 2020 The Preact Authors
  29855. Permission is hereby granted, free of charge, to any person obtaining a copy
  29856. of this software and associated documentation files (the "Software"), to deal
  29857. in the Software without restriction, including without limitation the rights
  29858. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  29859. copies of the Software, and to permit persons to whom the Software is
  29860. furnished to do so, subject to the following conditions:
  29861. The above copyright notice and this permission notice shall be included in all
  29862. copies or substantial portions of the Software.
  29863. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  29864. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  29865. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  29866. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  29867. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  29868. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  29869. SOFTWARE.
  29870. */
  29871. const EMPTY_OBJECT = Object.freeze({});
  29872. const debugSourcemapCombineFilter = process.env.DEBUG_VITE_SOURCEMAP_COMBINE_FILTER;
  29873. const debugSourcemapCombine = createDebugger("vite:sourcemap-combine", { onlyWhenFocused: true });
  29874. const debugResolve = createDebugger("vite:resolve");
  29875. const debugPluginResolve = createDebugger("vite:plugin-resolve", { onlyWhenFocused: "vite:plugin" });
  29876. const debugPluginTransform = createDebugger("vite:plugin-transform", { onlyWhenFocused: "vite:plugin" });
  29877. const debugPluginContainerContext = createDebugger("vite:plugin-container-context");
  29878. const ERR_CLOSED_SERVER = "ERR_CLOSED_SERVER";
  29879. function throwClosedServerError() {
  29880. const err = /* @__PURE__ */ new Error("The server is being restarted or closed. Request is outdated");
  29881. err.code = ERR_CLOSED_SERVER;
  29882. throw err;
  29883. }
  29884. /**
  29885. * Create a plugin container with a set of plugins. We pass them as a parameter
  29886. * instead of using environment.plugins to allow the creation of different
  29887. * pipelines working with the same environment (used for createIdResolver).
  29888. */
  29889. async function createEnvironmentPluginContainer(environment, plugins, watcher, autoStart = true) {
  29890. const container = new EnvironmentPluginContainer(environment, plugins, watcher, autoStart);
  29891. await container.resolveRollupOptions();
  29892. return container;
  29893. }
  29894. var EnvironmentPluginContainer = class {
  29895. _pluginContextMap = /* @__PURE__ */ new Map();
  29896. _resolvedRollupOptions;
  29897. _processesing = /* @__PURE__ */ new Set();
  29898. _seenResolves = {};
  29899. _moduleNodeToLoadAddedImports = /* @__PURE__ */ new WeakMap();
  29900. getSortedPluginHooks;
  29901. getSortedPlugins;
  29902. moduleGraph;
  29903. watchFiles = /* @__PURE__ */ new Set();
  29904. minimalContext;
  29905. _started = false;
  29906. _buildStartPromise;
  29907. _closed = false;
  29908. /**
  29909. * @internal use `createEnvironmentPluginContainer` instead
  29910. */
  29911. constructor(environment, plugins, watcher, autoStart = true) {
  29912. this.environment = environment;
  29913. this.plugins = plugins;
  29914. this.watcher = watcher;
  29915. this._started = !autoStart;
  29916. this.minimalContext = new MinimalPluginContext({
  29917. ...basePluginContextMeta,
  29918. watchMode: true
  29919. }, environment);
  29920. const utils = createPluginHookUtils(plugins);
  29921. this.getSortedPlugins = utils.getSortedPlugins;
  29922. this.getSortedPluginHooks = utils.getSortedPluginHooks;
  29923. this.moduleGraph = environment.mode === "dev" ? environment.moduleGraph : void 0;
  29924. }
  29925. _updateModuleLoadAddedImports(id, addedImports) {
  29926. const module = this.moduleGraph?.getModuleById(id);
  29927. if (module) this._moduleNodeToLoadAddedImports.set(module, addedImports);
  29928. }
  29929. _getAddedImports(id) {
  29930. const module = this.moduleGraph?.getModuleById(id);
  29931. return module ? this._moduleNodeToLoadAddedImports.get(module) || null : null;
  29932. }
  29933. getModuleInfo(id) {
  29934. const module = this.moduleGraph?.getModuleById(id);
  29935. if (!module) return null;
  29936. if (!module.info) module.info = new Proxy({
  29937. id,
  29938. meta: module.meta || EMPTY_OBJECT
  29939. }, { get(info, key) {
  29940. if (key in info) return info[key];
  29941. if (key === "then") return;
  29942. throw Error(`[vite] The "${key}" property of ModuleInfo is not supported.`);
  29943. } });
  29944. return module.info ?? null;
  29945. }
  29946. handleHookPromise(maybePromise) {
  29947. if (!maybePromise?.then) return maybePromise;
  29948. const promise = maybePromise;
  29949. this._processesing.add(promise);
  29950. return promise.finally(() => this._processesing.delete(promise));
  29951. }
  29952. get options() {
  29953. return this._resolvedRollupOptions;
  29954. }
  29955. async resolveRollupOptions() {
  29956. if (!this._resolvedRollupOptions) {
  29957. let options = this.environment.config.build.rollupOptions;
  29958. for (const optionsHook of this.getSortedPluginHooks("options")) {
  29959. if (this._closed) throwClosedServerError();
  29960. options = await this.handleHookPromise(optionsHook.call(this.minimalContext, options)) || options;
  29961. }
  29962. this._resolvedRollupOptions = options;
  29963. }
  29964. return this._resolvedRollupOptions;
  29965. }
  29966. _getPluginContext(plugin) {
  29967. if (!this._pluginContextMap.has(plugin)) this._pluginContextMap.set(plugin, new PluginContext(plugin, this));
  29968. return this._pluginContextMap.get(plugin);
  29969. }
  29970. async hookParallel(hookName, context, args, condition) {
  29971. const parallelPromises = [];
  29972. for (const plugin of this.getSortedPlugins(hookName)) {
  29973. if (condition && !condition(plugin)) continue;
  29974. const hook = plugin[hookName];
  29975. const handler = getHookHandler(hook);
  29976. if (hook.sequential) {
  29977. await Promise.all(parallelPromises);
  29978. parallelPromises.length = 0;
  29979. await handler.apply(context(plugin), args(plugin));
  29980. } else parallelPromises.push(handler.apply(context(plugin), args(plugin)));
  29981. }
  29982. await Promise.all(parallelPromises);
  29983. }
  29984. async buildStart(_options) {
  29985. if (this._started) {
  29986. if (this._buildStartPromise) await this._buildStartPromise;
  29987. return;
  29988. }
  29989. this._started = true;
  29990. const config = this.environment.getTopLevelConfig();
  29991. this._buildStartPromise = this.handleHookPromise(this.hookParallel("buildStart", (plugin) => this._getPluginContext(plugin), () => [this.options], (plugin) => this.environment.name === "client" || config.server.perEnvironmentStartEndDuringDev || plugin.perEnvironmentStartEndDuringDev));
  29992. await this._buildStartPromise;
  29993. this._buildStartPromise = void 0;
  29994. }
  29995. async resolveId(rawId, importer = join(this.environment.config.root, "index.html"), options) {
  29996. if (!this._started) {
  29997. this.buildStart();
  29998. await this._buildStartPromise;
  29999. }
  30000. const skip = options?.skip;
  30001. const skipCalls = options?.skipCalls;
  30002. const scan = !!options?.scan;
  30003. const ssr = this.environment.config.consumer === "server";
  30004. const ctx = new ResolveIdContext(this, skip, skipCalls, scan);
  30005. const topLevelConfig = this.environment.getTopLevelConfig();
  30006. const mergedSkip = new Set(skip);
  30007. for (const call of skipCalls ?? []) if (call.called || call.id === rawId && call.importer === importer) mergedSkip.add(call.plugin);
  30008. const resolveStart = debugResolve ? performance$1.now() : 0;
  30009. let id = null;
  30010. const partial = {};
  30011. for (const plugin of this.getSortedPlugins("resolveId")) {
  30012. if (this._closed && this.environment.config.dev.recoverable) throwClosedServerError();
  30013. if (mergedSkip?.has(plugin)) continue;
  30014. const filter = getCachedFilterForPlugin(plugin, "resolveId");
  30015. if (filter && !filter(rawId)) continue;
  30016. ctx._plugin = plugin;
  30017. const normalizedOptions = {
  30018. kind: options?.kind,
  30019. attributes: options?.attributes ?? {},
  30020. custom: options?.custom,
  30021. isEntry: !!options?.isEntry,
  30022. ssr,
  30023. scan
  30024. };
  30025. if (isFutureDeprecationEnabled(topLevelConfig, "removePluginHookSsrArgument")) {
  30026. let ssrTemp = ssr;
  30027. Object.defineProperty(normalizedOptions, "ssr", {
  30028. get() {
  30029. warnFutureDeprecation(topLevelConfig, "removePluginHookSsrArgument", `Used in plugin "${plugin.name}".`);
  30030. return ssrTemp;
  30031. },
  30032. set(v) {
  30033. ssrTemp = v;
  30034. }
  30035. });
  30036. }
  30037. const pluginResolveStart = debugPluginResolve ? performance$1.now() : 0;
  30038. const handler = getHookHandler(plugin.resolveId);
  30039. const result = await this.handleHookPromise(handler.call(ctx, rawId, importer, normalizedOptions));
  30040. if (!result) continue;
  30041. if (typeof result === "string") id = result;
  30042. else {
  30043. id = result.id;
  30044. Object.assign(partial, result);
  30045. }
  30046. debugPluginResolve?.(timeFrom(pluginResolveStart), plugin.name, prettifyUrl(id, this.environment.config.root));
  30047. break;
  30048. }
  30049. if (debugResolve && rawId !== id && !rawId.startsWith(FS_PREFIX)) {
  30050. const key = rawId + id;
  30051. if (!this._seenResolves[key]) {
  30052. this._seenResolves[key] = true;
  30053. debugResolve(`${timeFrom(resolveStart)} ${import_picocolors.default.cyan(rawId)} -> ${import_picocolors.default.dim(id)}`);
  30054. }
  30055. }
  30056. if (id) {
  30057. partial.id = isExternalUrl(id) || id[0] === "\0" ? id : normalizePath(id);
  30058. return partial;
  30059. } else return null;
  30060. }
  30061. async load(id) {
  30062. let ssr = this.environment.config.consumer === "server";
  30063. const topLevelConfig = this.environment.getTopLevelConfig();
  30064. const options = { ssr };
  30065. const ctx = new LoadPluginContext(this);
  30066. for (const plugin of this.getSortedPlugins("load")) {
  30067. if (this._closed && this.environment.config.dev.recoverable) throwClosedServerError();
  30068. const filter = getCachedFilterForPlugin(plugin, "load");
  30069. if (filter && !filter(id)) continue;
  30070. ctx._plugin = plugin;
  30071. if (isFutureDeprecationEnabled(topLevelConfig, "removePluginHookSsrArgument")) Object.defineProperty(options, "ssr", {
  30072. get() {
  30073. warnFutureDeprecation(topLevelConfig, "removePluginHookSsrArgument", `Used in plugin "${plugin.name}".`);
  30074. return ssr;
  30075. },
  30076. set(v) {
  30077. ssr = v;
  30078. }
  30079. });
  30080. const handler = getHookHandler(plugin.load);
  30081. const result = await this.handleHookPromise(handler.call(ctx, id, options));
  30082. if (result != null) {
  30083. if (isObject$1(result)) ctx._updateModuleInfo(id, result);
  30084. this._updateModuleLoadAddedImports(id, ctx._addedImports);
  30085. return result;
  30086. }
  30087. }
  30088. this._updateModuleLoadAddedImports(id, ctx._addedImports);
  30089. return null;
  30090. }
  30091. async transform(code, id, options) {
  30092. let ssr = this.environment.config.consumer === "server";
  30093. const topLevelConfig = this.environment.getTopLevelConfig();
  30094. const optionsWithSSR = options ? {
  30095. ...options,
  30096. ssr,
  30097. moduleType: options.moduleType ?? "js"
  30098. } : {
  30099. ssr,
  30100. moduleType: "js"
  30101. };
  30102. const inMap = options?.inMap;
  30103. const ctx = new TransformPluginContext(this, id, code, inMap);
  30104. ctx._addedImports = this._getAddedImports(id);
  30105. for (const plugin of this.getSortedPlugins("transform")) {
  30106. if (this._closed && this.environment.config.dev.recoverable) throwClosedServerError();
  30107. const filter = getCachedFilterForPlugin(plugin, "transform");
  30108. if (filter && !filter(id, code, optionsWithSSR.moduleType)) continue;
  30109. if (isFutureDeprecationEnabled(topLevelConfig, "removePluginHookSsrArgument")) Object.defineProperty(optionsWithSSR, "ssr", {
  30110. get() {
  30111. warnFutureDeprecation(topLevelConfig, "removePluginHookSsrArgument", `Used in plugin "${plugin.name}".`);
  30112. return ssr;
  30113. },
  30114. set(v) {
  30115. ssr = v;
  30116. }
  30117. });
  30118. ctx._updateActiveInfo(plugin, id, code);
  30119. const start = debugPluginTransform ? performance$1.now() : 0;
  30120. let result;
  30121. const handler = getHookHandler(plugin.transform);
  30122. try {
  30123. result = await this.handleHookPromise(handler.call(ctx, code, id, optionsWithSSR));
  30124. } catch (e) {
  30125. ctx.error(e);
  30126. }
  30127. if (!result) continue;
  30128. debugPluginTransform?.(timeFrom(start), plugin.name, prettifyUrl(id, this.environment.config.root));
  30129. if (isObject$1(result)) {
  30130. if (result.code !== void 0) {
  30131. code = result.code;
  30132. if (result.map) {
  30133. if (debugSourcemapCombine) result.map.name = plugin.name;
  30134. ctx.sourcemapChain.push(result.map);
  30135. }
  30136. }
  30137. if (result.moduleType !== void 0) optionsWithSSR.moduleType = result.moduleType;
  30138. ctx._updateModuleInfo(id, result);
  30139. } else code = result;
  30140. }
  30141. return {
  30142. code,
  30143. map: ctx._getCombinedSourcemap(),
  30144. moduleType: optionsWithSSR.moduleType
  30145. };
  30146. }
  30147. async watchChange(id, change) {
  30148. const config = this.environment.getTopLevelConfig();
  30149. await this.hookParallel("watchChange", (plugin) => this._getPluginContext(plugin), () => [id, change], (plugin) => this.environment.name === "client" || config.server.perEnvironmentWatchChangeDuringDev || plugin.perEnvironmentWatchChangeDuringDev);
  30150. }
  30151. async close() {
  30152. if (this._closed) return;
  30153. this._closed = true;
  30154. await Promise.allSettled(Array.from(this._processesing));
  30155. const config = this.environment.getTopLevelConfig();
  30156. await this.hookParallel("buildEnd", (plugin) => this._getPluginContext(plugin), () => [], (plugin) => this.environment.name === "client" || config.server.perEnvironmentStartEndDuringDev || plugin.perEnvironmentStartEndDuringDev);
  30157. await this.hookParallel("closeBundle", (plugin) => this._getPluginContext(plugin), () => []);
  30158. }
  30159. };
  30160. const basePluginContextMeta = {
  30161. viteVersion: VERSION,
  30162. rollupVersion,
  30163. rolldownVersion
  30164. };
  30165. var BasicMinimalPluginContext = class {
  30166. constructor(meta, _logger) {
  30167. this.meta = meta;
  30168. this._logger = _logger;
  30169. }
  30170. get pluginName() {
  30171. return "";
  30172. }
  30173. debug(rawLog) {
  30174. const log = this._normalizeRawLog(rawLog);
  30175. const msg = buildErrorMessage(log, [`debug: ${log.message}`], false);
  30176. debugPluginContainerContext?.(msg);
  30177. }
  30178. info(rawLog) {
  30179. const log = this._normalizeRawLog(rawLog);
  30180. const msg = buildErrorMessage(log, [`info: ${log.message}`], false);
  30181. this._logger.info(msg, {
  30182. clear: true,
  30183. timestamp: true
  30184. });
  30185. }
  30186. warn(rawLog) {
  30187. const log = this._normalizeRawLog(rawLog);
  30188. const msg = buildErrorMessage(log, [import_picocolors.default.yellow(`warning: ${log.message}`)], false);
  30189. this._logger.warn(msg, {
  30190. clear: true,
  30191. timestamp: true
  30192. });
  30193. }
  30194. error(e) {
  30195. throw typeof e === "string" ? new Error(e) : e;
  30196. }
  30197. _normalizeRawLog(rawLog) {
  30198. const logValue = typeof rawLog === "function" ? rawLog() : rawLog;
  30199. return typeof logValue === "string" ? new Error(logValue) : logValue;
  30200. }
  30201. };
  30202. var MinimalPluginContext = class extends BasicMinimalPluginContext {
  30203. environment;
  30204. constructor(meta, environment) {
  30205. super(meta, environment.logger);
  30206. this.environment = environment;
  30207. }
  30208. };
  30209. const fsModule = {
  30210. appendFile: fsp.appendFile,
  30211. copyFile: fsp.copyFile,
  30212. mkdir: fsp.mkdir,
  30213. mkdtemp: fsp.mkdtemp,
  30214. readdir: fsp.readdir,
  30215. readFile: fsp.readFile,
  30216. realpath: fsp.realpath,
  30217. rename: fsp.rename,
  30218. rmdir: fsp.rmdir,
  30219. stat: fsp.stat,
  30220. lstat: fsp.lstat,
  30221. unlink: fsp.unlink,
  30222. writeFile: fsp.writeFile
  30223. };
  30224. var PluginContext = class extends MinimalPluginContext {
  30225. ssr = false;
  30226. _scan = false;
  30227. _activeId = null;
  30228. _activeCode = null;
  30229. _resolveSkips;
  30230. _resolveSkipCalls;
  30231. get pluginName() {
  30232. return this._plugin.name;
  30233. }
  30234. constructor(_plugin, _container) {
  30235. super(_container.minimalContext.meta, _container.environment);
  30236. this._plugin = _plugin;
  30237. this._container = _container;
  30238. }
  30239. fs = fsModule;
  30240. parse(code, opts) {
  30241. return parseAst(code, opts);
  30242. }
  30243. async resolve(id, importer, options) {
  30244. let skipCalls;
  30245. if (options?.skipSelf === false) skipCalls = this._resolveSkipCalls;
  30246. else if (this._resolveSkipCalls) {
  30247. const skipCallsTemp = [...this._resolveSkipCalls];
  30248. const sameCallIndex = this._resolveSkipCalls.findIndex((c) => c.id === id && c.importer === importer && c.plugin === this._plugin);
  30249. if (sameCallIndex !== -1) skipCallsTemp[sameCallIndex] = {
  30250. ...skipCallsTemp[sameCallIndex],
  30251. called: true
  30252. };
  30253. else skipCallsTemp.push({
  30254. id,
  30255. importer,
  30256. plugin: this._plugin
  30257. });
  30258. skipCalls = skipCallsTemp;
  30259. } else skipCalls = [{
  30260. id,
  30261. importer,
  30262. plugin: this._plugin
  30263. }];
  30264. let out = await this._container.resolveId(id, importer, {
  30265. attributes: options?.attributes,
  30266. custom: options?.custom,
  30267. isEntry: !!options?.isEntry,
  30268. skip: this._resolveSkips,
  30269. skipCalls,
  30270. scan: this._scan
  30271. });
  30272. if (typeof out === "string") out = { id: out };
  30273. return out;
  30274. }
  30275. async load(options) {
  30276. await this._container.moduleGraph?.ensureEntryFromUrl(unwrapId(options.id));
  30277. this._updateModuleInfo(options.id, options);
  30278. const loadResult = await this._container.load(options.id);
  30279. const code = typeof loadResult === "object" ? loadResult?.code : loadResult;
  30280. if (code != null) await this._container.transform(code, options.id);
  30281. const moduleInfo = this.getModuleInfo(options.id);
  30282. if (!moduleInfo) throw Error(`Failed to load module with id ${options.id}`);
  30283. return moduleInfo;
  30284. }
  30285. getModuleInfo(id) {
  30286. return this._container.getModuleInfo(id);
  30287. }
  30288. _updateModuleInfo(id, { meta }) {
  30289. if (meta) {
  30290. const moduleInfo = this.getModuleInfo(id);
  30291. if (moduleInfo) moduleInfo.meta = {
  30292. ...moduleInfo.meta,
  30293. ...meta
  30294. };
  30295. }
  30296. }
  30297. getModuleIds() {
  30298. return this._container.moduleGraph ? this._container.moduleGraph.idToModuleMap.keys() : Array.prototype[Symbol.iterator]();
  30299. }
  30300. addWatchFile(id) {
  30301. this._container.watchFiles.add(id);
  30302. if (this._container.watcher) ensureWatchedFile(this._container.watcher, id, this.environment.config.root);
  30303. }
  30304. getWatchFiles() {
  30305. return [...this._container.watchFiles];
  30306. }
  30307. emitFile(_assetOrFile) {
  30308. this._warnIncompatibleMethod(`emitFile`);
  30309. return "";
  30310. }
  30311. setAssetSource() {
  30312. this._warnIncompatibleMethod(`setAssetSource`);
  30313. }
  30314. getFileName() {
  30315. this._warnIncompatibleMethod(`getFileName`);
  30316. return "";
  30317. }
  30318. debug(log) {
  30319. const err = this._formatLog(typeof log === "function" ? log() : log);
  30320. super.debug(err);
  30321. }
  30322. info(log) {
  30323. const err = this._formatLog(typeof log === "function" ? log() : log);
  30324. super.info(err);
  30325. }
  30326. warn(log, position) {
  30327. const err = this._formatLog(typeof log === "function" ? log() : log, position);
  30328. super.warn(err);
  30329. }
  30330. error(e, position) {
  30331. throw this._formatLog(e, position);
  30332. }
  30333. _formatLog(e, position) {
  30334. const err = typeof e === "string" ? new Error(e) : e;
  30335. if (err.pluginCode) return err;
  30336. err.plugin = this._plugin.name;
  30337. if (this._activeId && !err.id) err.id = this._activeId;
  30338. if (this._activeCode) {
  30339. err.pluginCode = this._activeCode;
  30340. const pos = position ?? err.pos ?? err.position;
  30341. if (pos != null) {
  30342. let errLocation;
  30343. try {
  30344. errLocation = numberToPos(this._activeCode, pos);
  30345. } catch (err2) {
  30346. this.environment.logger.error(import_picocolors.default.red(`Error in error handler:\n${err2.stack || err2.message}\n`), { error: err2 });
  30347. throw err;
  30348. }
  30349. err.loc = err.loc || {
  30350. file: err.id,
  30351. ...errLocation
  30352. };
  30353. err.frame = err.frame || generateCodeFrame(this._activeCode, pos);
  30354. } else if (err.loc) {
  30355. if (!err.frame) {
  30356. let code = this._activeCode;
  30357. if (err.loc.file) {
  30358. err.id = normalizePath(err.loc.file);
  30359. try {
  30360. code = fs.readFileSync(err.loc.file, "utf-8");
  30361. } catch {}
  30362. }
  30363. err.frame = generateCodeFrame(code, err.loc);
  30364. }
  30365. } else if (err.line && err.column) {
  30366. err.loc = {
  30367. file: err.id,
  30368. line: err.line,
  30369. column: err.column
  30370. };
  30371. err.frame = err.frame || generateCodeFrame(this._activeCode, err.loc);
  30372. }
  30373. if (this instanceof TransformPluginContext && typeof err.loc?.line === "number" && typeof err.loc.column === "number") {
  30374. const rawSourceMap = this._getCombinedSourcemap();
  30375. if (rawSourceMap && "version" in rawSourceMap) {
  30376. const { source, line, column } = originalPositionFor$2(new TraceMap(rawSourceMap), {
  30377. line: Number(err.loc.line),
  30378. column: Number(err.loc.column)
  30379. });
  30380. if (source) err.loc = {
  30381. file: source,
  30382. line,
  30383. column
  30384. };
  30385. }
  30386. }
  30387. } else if (err.loc) {
  30388. if (!err.frame) {
  30389. let code = err.pluginCode;
  30390. if (err.loc.file) {
  30391. err.id = normalizePath(err.loc.file);
  30392. if (!code) try {
  30393. code = fs.readFileSync(err.loc.file, "utf-8");
  30394. } catch {}
  30395. }
  30396. if (code) err.frame = generateCodeFrame(`${code}`, err.loc);
  30397. }
  30398. }
  30399. if (typeof err.loc?.column !== "number" && typeof err.loc?.line !== "number" && !err.loc?.file) delete err.loc;
  30400. return err;
  30401. }
  30402. _warnIncompatibleMethod(method) {
  30403. this.environment.logger.warn(import_picocolors.default.cyan(`[plugin:${this._plugin.name}] `) + import_picocolors.default.yellow(`context method ${import_picocolors.default.bold(`${method}()`)} is not supported in serve mode. This plugin is likely not vite-compatible.`));
  30404. }
  30405. };
  30406. var ResolveIdContext = class extends PluginContext {
  30407. constructor(container, skip, skipCalls, scan) {
  30408. super(null, container);
  30409. this._resolveSkips = skip;
  30410. this._resolveSkipCalls = skipCalls;
  30411. this._scan = scan;
  30412. }
  30413. };
  30414. var LoadPluginContext = class extends PluginContext {
  30415. _addedImports = null;
  30416. constructor(container) {
  30417. super(null, container);
  30418. }
  30419. addWatchFile(id) {
  30420. if (!this._addedImports) this._addedImports = /* @__PURE__ */ new Set();
  30421. this._addedImports.add(id);
  30422. super.addWatchFile(id);
  30423. }
  30424. };
  30425. var TransformPluginContext = class extends LoadPluginContext {
  30426. filename;
  30427. originalCode;
  30428. originalSourcemap = null;
  30429. sourcemapChain = [];
  30430. combinedMap = null;
  30431. constructor(container, id, code, inMap) {
  30432. super(container);
  30433. this.filename = id;
  30434. this.originalCode = code;
  30435. if (inMap) {
  30436. if (debugSourcemapCombine) inMap.name = "$inMap";
  30437. this.sourcemapChain.push(inMap);
  30438. }
  30439. }
  30440. _getCombinedSourcemap() {
  30441. if (debugSourcemapCombine && debugSourcemapCombineFilter && this.filename.includes(debugSourcemapCombineFilter)) {
  30442. debugSourcemapCombine("----------", this.filename);
  30443. debugSourcemapCombine(this.combinedMap);
  30444. debugSourcemapCombine(this.sourcemapChain);
  30445. debugSourcemapCombine("----------");
  30446. }
  30447. let combinedMap = this.combinedMap;
  30448. if (combinedMap && !("version" in combinedMap) && combinedMap.mappings === "") {
  30449. this.sourcemapChain.length = 0;
  30450. return combinedMap;
  30451. }
  30452. for (let m of this.sourcemapChain) {
  30453. if (typeof m === "string") m = JSON.parse(m);
  30454. if (!("version" in m)) {
  30455. if (m.mappings === "") {
  30456. combinedMap = { mappings: "" };
  30457. break;
  30458. }
  30459. combinedMap = null;
  30460. break;
  30461. }
  30462. if (!combinedMap) {
  30463. const sm = m;
  30464. if (sm.sources.length === 1 && !sm.sources[0]) combinedMap = {
  30465. ...sm,
  30466. sources: [this.filename],
  30467. sourcesContent: [this.originalCode]
  30468. };
  30469. else combinedMap = sm;
  30470. } else combinedMap = combineSourcemaps(cleanUrl(this.filename), [m, combinedMap]);
  30471. }
  30472. if (combinedMap !== this.combinedMap) {
  30473. this.combinedMap = combinedMap;
  30474. this.sourcemapChain.length = 0;
  30475. }
  30476. return this.combinedMap;
  30477. }
  30478. getCombinedSourcemap() {
  30479. const map = this._getCombinedSourcemap();
  30480. if (!map || !("version" in map) && map.mappings === "") return new MagicString(this.originalCode).generateMap({
  30481. includeContent: true,
  30482. hires: "boundary",
  30483. source: cleanUrl(this.filename)
  30484. });
  30485. return map;
  30486. }
  30487. _updateActiveInfo(plugin, id, code) {
  30488. this._plugin = plugin;
  30489. this._activeId = id;
  30490. this._activeCode = code;
  30491. }
  30492. };
  30493. var PluginContainer = class {
  30494. constructor(environments) {
  30495. this.environments = environments;
  30496. }
  30497. _getEnvironment(options) {
  30498. return options?.environment ? options.environment : this.environments[options?.ssr ? "ssr" : "client"];
  30499. }
  30500. _getPluginContainer(options) {
  30501. return this._getEnvironment(options).pluginContainer;
  30502. }
  30503. getModuleInfo(id) {
  30504. const clientModuleInfo = this.environments.client.pluginContainer.getModuleInfo(id);
  30505. const ssrModuleInfo = this.environments.ssr.pluginContainer.getModuleInfo(id);
  30506. if (clientModuleInfo == null && ssrModuleInfo == null) return null;
  30507. return new Proxy({}, { get: (_, key) => {
  30508. if (key === "meta") {
  30509. const meta = {};
  30510. if (ssrModuleInfo) Object.assign(meta, ssrModuleInfo.meta);
  30511. if (clientModuleInfo) Object.assign(meta, clientModuleInfo.meta);
  30512. return meta;
  30513. }
  30514. if (clientModuleInfo) {
  30515. if (key in clientModuleInfo) return clientModuleInfo[key];
  30516. }
  30517. if (ssrModuleInfo) {
  30518. if (key in ssrModuleInfo) return ssrModuleInfo[key];
  30519. }
  30520. } });
  30521. }
  30522. get options() {
  30523. return this.environments.client.pluginContainer.options;
  30524. }
  30525. async buildStart(_options) {
  30526. return this.environments.client.pluginContainer.buildStart(_options);
  30527. }
  30528. async watchChange(id, change) {
  30529. return this.environments.client.pluginContainer.watchChange(id, change);
  30530. }
  30531. async resolveId(rawId, importer, options) {
  30532. return this._getPluginContainer(options).resolveId(rawId, importer, options);
  30533. }
  30534. async load(id, options) {
  30535. return this._getPluginContainer(options).load(id);
  30536. }
  30537. async transform(code, id, options) {
  30538. return this._getPluginContainer(options).transform(code, id, options);
  30539. }
  30540. async close() {}
  30541. };
  30542. /**
  30543. * server.pluginContainer compatibility
  30544. *
  30545. * The default environment is in buildStart, buildEnd, watchChange, and closeBundle hooks,
  30546. * which are called once for all environments, or when no environment is passed in other hooks.
  30547. * The ssrEnvironment is needed for backward compatibility when the ssr flag is passed without
  30548. * an environment. The defaultEnvironment in the main pluginContainer in the server should be
  30549. * the client environment for backward compatibility.
  30550. **/
  30551. function createPluginContainer(environments) {
  30552. return new PluginContainer(environments);
  30553. }
  30554. //#endregion
  30555. //#region src/node/optimizer/scan.ts
  30556. var ScanEnvironment = class extends BaseEnvironment {
  30557. mode = "scan";
  30558. get pluginContainer() {
  30559. if (!this._pluginContainer) throw new Error(`${this.name} environment.pluginContainer called before initialized`);
  30560. return this._pluginContainer;
  30561. }
  30562. /**
  30563. * @internal
  30564. */
  30565. _pluginContainer;
  30566. async init() {
  30567. if (this._initiated) return;
  30568. this._initiated = true;
  30569. this._pluginContainer = await createEnvironmentPluginContainer(this, this.plugins, void 0, false);
  30570. }
  30571. };
  30572. function devToScanEnvironment(environment) {
  30573. return {
  30574. mode: "scan",
  30575. get name() {
  30576. return environment.name;
  30577. },
  30578. getTopLevelConfig() {
  30579. return environment.getTopLevelConfig();
  30580. },
  30581. get config() {
  30582. return environment.config;
  30583. },
  30584. get logger() {
  30585. return environment.logger;
  30586. },
  30587. get pluginContainer() {
  30588. return environment.pluginContainer;
  30589. },
  30590. get plugins() {
  30591. return environment.plugins;
  30592. }
  30593. };
  30594. }
  30595. const debug$3 = createDebugger("vite:deps");
  30596. const htmlTypesRE = /\.(?:html|vue|svelte|astro|imba)$/;
  30597. const importsRE = /(?<!\/\/.*)(?<=^|;|\*\/)\s*import(?!\s+type)(?:[\w*{}\n\r\t, ]+from)?\s*("[^"]+"|'[^']+')\s*(?=$|;|\/\/|\/\*)/gm;
  30598. function scanImports(environment) {
  30599. const start = performance$1.now();
  30600. const { config } = environment;
  30601. const scanContext = { cancelled: false };
  30602. async function cancel() {
  30603. scanContext.cancelled = true;
  30604. }
  30605. async function scan() {
  30606. const entries = await computeEntries(environment);
  30607. if (!entries.length) {
  30608. if (!config.optimizeDeps.entries && !config.optimizeDeps.include) environment.logger.warn(import_picocolors.default.yellow("(!) Could not auto-determine entry point from rollupOptions or html files and there are no explicit optimizeDeps.include patterns. Skipping dependency pre-bundling."));
  30609. return;
  30610. }
  30611. if (scanContext.cancelled) return;
  30612. debug$3?.(`Crawling dependencies using entries: ${entries.map((entry) => `\n ${import_picocolors.default.dim(entry)}`).join("")}`);
  30613. const deps = {};
  30614. const missing = {};
  30615. const context = await prepareRolldownScanner(environment, entries, deps, missing);
  30616. if (scanContext.cancelled) return;
  30617. try {
  30618. await context.build();
  30619. return {
  30620. deps: orderedDependencies(deps),
  30621. missing
  30622. };
  30623. } catch (e) {
  30624. e.message = import_picocolors.default.red(`\
  30625. Failed to scan for dependencies from entries:
  30626. ${entries.join("\n")}
  30627. `) + e.message;
  30628. throw e;
  30629. } finally {
  30630. if (debug$3) debug$3(`Scan completed in ${(performance$1.now() - start).toFixed(2)}ms: ${Object.keys(orderedDependencies(deps)).sort().map((id) => `\n ${import_picocolors.default.cyan(id)} -> ${import_picocolors.default.dim(deps[id])}`).join("") || import_picocolors.default.dim("no dependencies found")}`);
  30631. }
  30632. }
  30633. return {
  30634. cancel,
  30635. result: scan().then((res) => res ?? {
  30636. deps: {},
  30637. missing: {}
  30638. })
  30639. };
  30640. }
  30641. async function computeEntries(environment) {
  30642. let entries = [];
  30643. const explicitEntryPatterns = environment.config.optimizeDeps.entries;
  30644. const buildInput = environment.config.build.rollupOptions.input;
  30645. if (explicitEntryPatterns) entries = await globEntries(explicitEntryPatterns, environment);
  30646. else if (buildInput) {
  30647. const resolvePath = async (p) => {
  30648. const id = (await environment.pluginContainer.resolveId(p, path.join(process.cwd(), "*"), {
  30649. isEntry: true,
  30650. scan: true
  30651. }))?.id;
  30652. if (id === void 0) throw new Error(`failed to resolve rollupOptions.input value: ${JSON.stringify(p)}.`);
  30653. return id;
  30654. };
  30655. if (typeof buildInput === "string") entries = [await resolvePath(buildInput)];
  30656. else if (Array.isArray(buildInput)) entries = await Promise.all(buildInput.map(resolvePath));
  30657. else if (isObject$1(buildInput)) entries = await Promise.all(Object.values(buildInput).map(resolvePath));
  30658. else throw new Error("invalid rollupOptions.input value.");
  30659. } else entries = await globEntries("**/*.html", environment);
  30660. entries = entries.filter((entry) => isScannable(entry, environment.config.optimizeDeps.extensions) && fs.existsSync(entry));
  30661. return entries;
  30662. }
  30663. async function prepareRolldownScanner(environment, entries, deps, missing) {
  30664. const { plugins: pluginsFromConfig = [], ...rolldownOptions } = environment.config.optimizeDeps.rolldownOptions ?? {};
  30665. const plugins = await asyncFlatten(arraify(pluginsFromConfig));
  30666. plugins.push(...rolldownScanPlugin(environment, deps, missing, entries));
  30667. const transformOptions = deepClone(rolldownOptions.transform) ?? {};
  30668. if (transformOptions.jsx === void 0) transformOptions.jsx = {};
  30669. else if (transformOptions.jsx === "react" || transformOptions.jsx === "react-jsx") transformOptions.jsx = getRollupJsxPresets(transformOptions.jsx);
  30670. if (typeof transformOptions.jsx === "object") transformOptions.jsx.development ??= !environment.config.isProduction;
  30671. async function build() {
  30672. await scan({
  30673. ...rolldownOptions,
  30674. transform: transformOptions,
  30675. input: entries,
  30676. logLevel: "silent",
  30677. plugins
  30678. });
  30679. }
  30680. return { build };
  30681. }
  30682. function orderedDependencies(deps) {
  30683. const depsList = Object.entries(deps);
  30684. depsList.sort((a, b) => a[0].localeCompare(b[0]));
  30685. return Object.fromEntries(depsList);
  30686. }
  30687. async function globEntries(patterns, environment) {
  30688. const nodeModulesPatterns = [];
  30689. const regularPatterns = [];
  30690. for (const pattern of arraify(patterns)) if (pattern.includes("node_modules")) nodeModulesPatterns.push(pattern);
  30691. else regularPatterns.push(pattern);
  30692. const sharedOptions = {
  30693. absolute: true,
  30694. cwd: environment.config.root,
  30695. ignore: [`**/${environment.config.build.outDir}/**`, ...environment.config.optimizeDeps.entries ? [] : [`**/__tests__/**`, `**/coverage/**`]]
  30696. };
  30697. return (await Promise.all([glob(nodeModulesPatterns, sharedOptions), glob(regularPatterns, {
  30698. ...sharedOptions,
  30699. ignore: [...sharedOptions.ignore, "**/node_modules/**"]
  30700. })])).flat();
  30701. }
  30702. const scriptRE = /(<script(?:\s+[a-z_:][-\w:]*(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^"'<>=\s]+))?)*\s*>)(.*?)<\/script>/gis;
  30703. const commentRE = /<!--.*?-->/gs;
  30704. const srcRE = /\bsrc\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s'">]+))/i;
  30705. const typeRE = /\btype\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s'">]+))/i;
  30706. const langRE = /\blang\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s'">]+))/i;
  30707. const svelteScriptModuleRE = /\bcontext\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s'">]+))/i;
  30708. const svelteModuleRE = /\smodule\b/i;
  30709. function rolldownScanPlugin(environment, depImports, missing, entries) {
  30710. const seen = /* @__PURE__ */ new Map();
  30711. async function resolveId(id, importer, options) {
  30712. return environment.pluginContainer.resolveId(id, importer && normalizePath(importer), {
  30713. scan: true,
  30714. ...options
  30715. });
  30716. }
  30717. const resolve = async (id, importer, options) => {
  30718. const key = JSON.stringify([
  30719. id,
  30720. importer && path.dirname(importer),
  30721. options
  30722. ]);
  30723. if (seen.has(key)) return seen.get(key);
  30724. const res = (await resolveId(id, importer, options))?.id;
  30725. seen.set(key, res);
  30726. return res;
  30727. };
  30728. const optimizeDepsOptions = environment.config.optimizeDeps;
  30729. const include = optimizeDepsOptions.include;
  30730. const exclude = [
  30731. ...optimizeDepsOptions.exclude ?? [],
  30732. "@vite/client",
  30733. "@vite/env"
  30734. ];
  30735. const externalUnlessEntry = ({ path }) => ({
  30736. id: path,
  30737. external: !entries.includes(path)
  30738. });
  30739. const doTransformGlobImport = async (contents, id, loader) => {
  30740. let transpiledContents;
  30741. if (loader !== "js") {
  30742. const result = transformSync(id, contents, {
  30743. lang: loader,
  30744. tsconfig: false
  30745. });
  30746. if (result.errors.length > 0) throw new AggregateError(result.errors, "oxc transform error");
  30747. transpiledContents = result.code;
  30748. } else transpiledContents = contents;
  30749. return (await transformGlobImport(transpiledContents, id, environment.config.root, resolve))?.s.toString() || transpiledContents;
  30750. };
  30751. const scripts = {};
  30752. const htmlTypeOnLoadCallback = async (id) => {
  30753. let raw = await fsp.readFile(id, "utf-8");
  30754. raw = raw.replace(commentRE, "<!---->");
  30755. const isHtml = id.endsWith(".html");
  30756. let js = "";
  30757. let scriptId = 0;
  30758. const matches = raw.matchAll(scriptRE);
  30759. for (const [, openTag, content] of matches) {
  30760. const typeMatch = typeRE.exec(openTag);
  30761. const type = typeMatch && (typeMatch[1] || typeMatch[2] || typeMatch[3]);
  30762. const langMatch = langRE.exec(openTag);
  30763. const lang = langMatch && (langMatch[1] || langMatch[2] || langMatch[3]);
  30764. if (isHtml && type !== "module") continue;
  30765. if (type && !(type.includes("javascript") || type.includes("ecmascript") || type === "module")) continue;
  30766. let loader = "js";
  30767. if (lang === "ts" || lang === "tsx" || lang === "jsx") loader = lang;
  30768. else if (id.endsWith(".astro")) loader = "ts";
  30769. const srcMatch = srcRE.exec(openTag);
  30770. if (srcMatch) js += `import ${JSON.stringify(srcMatch[1] || srcMatch[2] || srcMatch[3])}\n`;
  30771. else if (content.trim()) {
  30772. const contents = content + (loader.startsWith("ts") ? extractImportPaths(content) : "");
  30773. const key = `${id}?id=${scriptId++}`;
  30774. if (contents.includes("import.meta.glob")) scripts[key] = {
  30775. loader: "js",
  30776. contents: await doTransformGlobImport(contents, id, loader)
  30777. };
  30778. else scripts[key] = {
  30779. loader,
  30780. contents
  30781. };
  30782. const virtualModulePath = JSON.stringify(virtualModulePrefix + key);
  30783. let addedImport = false;
  30784. if (id.endsWith(".svelte")) {
  30785. let isModule = svelteModuleRE.test(openTag);
  30786. if (!isModule) {
  30787. const contextMatch = svelteScriptModuleRE.exec(openTag);
  30788. isModule = (contextMatch && (contextMatch[1] || contextMatch[2] || contextMatch[3])) === "module";
  30789. }
  30790. if (!isModule) {
  30791. addedImport = true;
  30792. js += `import ${virtualModulePath}\n`;
  30793. }
  30794. }
  30795. if (!addedImport) js += `export * from ${virtualModulePath}\n`;
  30796. }
  30797. }
  30798. if (!id.endsWith(".vue") || !js.includes("export default")) js += "\nexport default {}";
  30799. return js;
  30800. };
  30801. const ASSET_TYPE_RE = new RegExp(`\\.(${KNOWN_ASSET_TYPES.join("|")})$`);
  30802. return [
  30803. {
  30804. name: "vite:dep-scan:resolve-external-url",
  30805. resolveId: {
  30806. filter: { id: externalRE },
  30807. handler: (id) => ({
  30808. id,
  30809. external: true
  30810. })
  30811. }
  30812. },
  30813. {
  30814. name: "vite:dep-scan:resolve-data-url",
  30815. resolveId: {
  30816. filter: { id: dataUrlRE },
  30817. handler: (id) => ({
  30818. id,
  30819. external: true
  30820. })
  30821. }
  30822. },
  30823. {
  30824. name: "vite:dep-scan:local-scripts",
  30825. resolveId: {
  30826. filter: { id: virtualModuleRE },
  30827. handler: (id) => ({ id })
  30828. },
  30829. load: {
  30830. filter: { id: virtualModuleRE },
  30831. handler(id) {
  30832. const script = scripts[id.replace(virtualModulePrefix, "")];
  30833. return {
  30834. code: script.contents,
  30835. moduleType: script.loader
  30836. };
  30837. }
  30838. }
  30839. },
  30840. {
  30841. name: "vite:dep-scan:resolve",
  30842. async resolveId(id, importer) {
  30843. importer = importer && virtualModuleRE.test(importer) ? importer.replace(virtualModulePrefix, "") : importer;
  30844. if (htmlTypesRE.test(id)) {
  30845. const resolved = await resolve(id, importer);
  30846. if (!resolved) return;
  30847. if (isInNodeModules(resolved) && isOptimizable(resolved, optimizeDepsOptions)) return;
  30848. if (shouldExternalizeDep(resolved, id)) return externalUnlessEntry({ path: id });
  30849. return resolved;
  30850. }
  30851. if (/^[\w@][^:]/.test(id)) {
  30852. if (moduleListContains(exclude, id)) return externalUnlessEntry({ path: id });
  30853. if (depImports[id]) return externalUnlessEntry({ path: id });
  30854. const resolved = await resolve(id, importer);
  30855. if (resolved) {
  30856. if (shouldExternalizeDep(resolved, id)) return externalUnlessEntry({ path: id });
  30857. if (isInNodeModules(resolved) || include?.includes(id)) {
  30858. if (isOptimizable(resolved, optimizeDepsOptions)) depImports[id] = resolved;
  30859. return externalUnlessEntry({ path: id });
  30860. } else if (isScannable(resolved, optimizeDepsOptions.extensions)) return path.resolve(resolved);
  30861. else return externalUnlessEntry({ path: id });
  30862. } else missing[id] = normalizePath(importer);
  30863. }
  30864. if (CSS_LANGS_RE.test(id)) return externalUnlessEntry({ path: id });
  30865. if (/\.(?:json|json5|wasm)$/.test(id)) return externalUnlessEntry({ path: id });
  30866. if (ASSET_TYPE_RE.test(id)) return externalUnlessEntry({ path: id });
  30867. if (SPECIAL_QUERY_RE.test(id)) return {
  30868. id,
  30869. external: true
  30870. };
  30871. const resolved = await resolve(id, importer);
  30872. if (resolved) {
  30873. if (shouldExternalizeDep(resolved, id) || !isScannable(resolved, optimizeDepsOptions.extensions)) return externalUnlessEntry({ path: id });
  30874. return path.resolve(cleanUrl(resolved));
  30875. }
  30876. return externalUnlessEntry({ path: id });
  30877. }
  30878. },
  30879. {
  30880. name: "vite:dep-scan:load:html",
  30881. load: {
  30882. filter: { id: htmlTypesRE },
  30883. async handler(id) {
  30884. return {
  30885. code: await htmlTypeOnLoadCallback(id),
  30886. moduleType: "js"
  30887. };
  30888. }
  30889. }
  30890. },
  30891. ...environment.config.esbuild && environment.config.esbuild.jsxInject ? [{
  30892. name: "vite:dep-scan:transform:jsx-inject",
  30893. transform: {
  30894. filter: { id: /\.[jt]sx$/ },
  30895. handler(code) {
  30896. const esbuildConfig = environment.config.esbuild;
  30897. if (esbuildConfig && esbuildConfig.jsxInject) code = esbuildConfig.jsxInject + `\n` + code;
  30898. return code;
  30899. }
  30900. }
  30901. }] : [],
  30902. {
  30903. name: "vite:dep-scan:transform:js-glob",
  30904. transform: {
  30905. filter: { code: "import.meta.glob" },
  30906. async handler(code, id) {
  30907. if (JS_TYPES_RE.test(id)) {
  30908. let ext = path.extname(id).slice(1);
  30909. if (ext === "mjs") ext = "js";
  30910. return {
  30911. moduleType: "js",
  30912. code: await doTransformGlobImport(code, id, ext)
  30913. };
  30914. }
  30915. }
  30916. }
  30917. }
  30918. ];
  30919. }
  30920. /**
  30921. * when using TS + (Vue + `<script setup>`) or Svelte, imports may seem
  30922. * unused to esbuild and dropped in the build output, which prevents
  30923. * esbuild from crawling further.
  30924. * the solution is to add `import 'x'` for every source to force
  30925. * esbuild to keep crawling due to potential side effects.
  30926. */
  30927. function extractImportPaths(code) {
  30928. code = code.replace(multilineCommentsRE, "/* */").replace(singlelineCommentsRE, "");
  30929. let js = "";
  30930. let m;
  30931. importsRE.lastIndex = 0;
  30932. while ((m = importsRE.exec(code)) != null) js += `\nimport ${m[1]}`;
  30933. return js;
  30934. }
  30935. function shouldExternalizeDep(resolvedId, rawId) {
  30936. if (!path.isAbsolute(resolvedId)) return true;
  30937. if (resolvedId === rawId || resolvedId.includes("\0")) return true;
  30938. return false;
  30939. }
  30940. function isScannable(id, extensions) {
  30941. return JS_TYPES_RE.test(id) || htmlTypesRE.test(id) || extensions?.includes(path.extname(id)) || false;
  30942. }
  30943. //#endregion
  30944. //#region src/node/optimizer/resolve.ts
  30945. function createOptimizeDepsIncludeResolver(environment) {
  30946. const topLevelConfig = environment.getTopLevelConfig();
  30947. const resolve = createBackCompatIdResolver(topLevelConfig, {
  30948. asSrc: false,
  30949. scan: true,
  30950. packageCache: /* @__PURE__ */ new Map()
  30951. });
  30952. return async (id) => {
  30953. const lastArrowIndex = id.lastIndexOf(">");
  30954. if (lastArrowIndex === -1) return await resolve(environment, id, void 0);
  30955. const nestedRoot = id.substring(0, lastArrowIndex).trim();
  30956. const nestedPath = id.substring(lastArrowIndex + 1).trim();
  30957. const basedir = nestedResolveBasedir(nestedRoot, topLevelConfig.root, topLevelConfig.resolve.preserveSymlinks);
  30958. return await resolve(environment, nestedPath, path.resolve(basedir, "package.json"));
  30959. };
  30960. }
  30961. /**
  30962. * Expand the glob syntax in `optimizeDeps.include` to proper import paths
  30963. */
  30964. function expandGlobIds(id, config) {
  30965. const pkgName = getNpmPackageName(id);
  30966. if (!pkgName) return [];
  30967. const pkgData = resolvePackageData(pkgName, config.root, config.resolve.preserveSymlinks, config.packageCache);
  30968. if (!pkgData) return [];
  30969. const pattern = "." + id.slice(pkgName.length);
  30970. const exports = pkgData.data.exports;
  30971. if (exports) {
  30972. if (typeof exports === "string" || Array.isArray(exports)) return [pkgName];
  30973. const possibleExportPaths = [];
  30974. for (const key in exports) if (key[0] === ".") if (key.includes("*")) {
  30975. const exportsValue = getFirstExportStringValue(exports[key]);
  30976. if (!exportsValue) continue;
  30977. const exportValuePattern = exportsValue.replace(/\*/g, "**/*");
  30978. const exportsValueGlobRe = new RegExp(exportsValue.split("*").map(escapeRegex).join("(.*)"));
  30979. possibleExportPaths.push(...globSync(exportValuePattern, {
  30980. cwd: pkgData.dir,
  30981. expandDirectories: false,
  30982. ignore: ["node_modules"]
  30983. }).map((filePath) => {
  30984. if (exportsValue.startsWith("./")) filePath = "./" + filePath;
  30985. const matched = exportsValueGlobRe.exec(slash(filePath));
  30986. if (matched) {
  30987. let allGlobSame = matched.length === 2;
  30988. if (!allGlobSame) {
  30989. allGlobSame = true;
  30990. for (let i = 2; i < matched.length; i++) if (matched[i] !== matched[i - 1]) {
  30991. allGlobSame = false;
  30992. break;
  30993. }
  30994. }
  30995. if (allGlobSame) return key.replace("*", matched[1]).slice(2);
  30996. }
  30997. return "";
  30998. }).filter(Boolean));
  30999. } else possibleExportPaths.push(key.slice(2));
  31000. const isMatch = picomatch(pattern);
  31001. const matched = possibleExportPaths.filter((p) => isMatch(p)).map((match) => path.posix.join(pkgName, match));
  31002. matched.unshift(pkgName);
  31003. return matched;
  31004. } else {
  31005. const matched = globSync(pattern, {
  31006. cwd: pkgData.dir,
  31007. expandDirectories: false,
  31008. ignore: ["node_modules"]
  31009. }).map((match) => path.posix.join(pkgName, slash(match)));
  31010. matched.unshift(pkgName);
  31011. return matched;
  31012. }
  31013. }
  31014. function getFirstExportStringValue(obj) {
  31015. if (typeof obj === "string") return obj;
  31016. else if (Array.isArray(obj)) return obj[0];
  31017. else for (const key in obj) return getFirstExportStringValue(obj[key]);
  31018. }
  31019. /**
  31020. * Continuously resolve the basedir of packages separated by '>'
  31021. */
  31022. function nestedResolveBasedir(id, basedir, preserveSymlinks = false) {
  31023. const pkgs = id.split(">").map((pkg) => pkg.trim());
  31024. for (const pkg of pkgs) basedir = resolvePackageData(pkg, basedir, preserveSymlinks)?.dir || basedir;
  31025. return basedir;
  31026. }
  31027. //#endregion
  31028. //#region src/node/optimizer/rolldownDepPlugin.ts
  31029. const externalWithConversionNamespace = "vite:dep-pre-bundle:external-conversion";
  31030. const convertedExternalPrefix = "vite-dep-pre-bundle-external:";
  31031. const cjsExternalFacadeNamespace = "vite:cjs-external-facade";
  31032. const nonFacadePrefix = "vite-cjs-external-facade:";
  31033. const externalTypes = [
  31034. "css",
  31035. "less",
  31036. "sass",
  31037. "scss",
  31038. "styl",
  31039. "stylus",
  31040. "pcss",
  31041. "postcss",
  31042. "wasm",
  31043. "vue",
  31044. "svelte",
  31045. "marko",
  31046. "astro",
  31047. "imba",
  31048. "jsx",
  31049. "tsx",
  31050. ...KNOWN_ASSET_TYPES
  31051. ];
  31052. const optionalPeerDepNamespace = "optional-peer-dep:";
  31053. const browserExternalNamespace = "browser-external:";
  31054. function rolldownDepPlugin(environment, qualified, external) {
  31055. const { isProduction } = environment.config;
  31056. const { extensions } = environment.config.optimizeDeps;
  31057. const allExternalTypes = extensions ? externalTypes.filter((type) => !extensions.includes("." + type)) : externalTypes;
  31058. const esmPackageCache = /* @__PURE__ */ new Map();
  31059. const cjsPackageCache = /* @__PURE__ */ new Map();
  31060. const resolveAssets = (resolved, kind) => {
  31061. if (kind === "require-call") return { id: externalWithConversionNamespace + resolved };
  31062. return {
  31063. id: resolved,
  31064. external: "absolute"
  31065. };
  31066. };
  31067. const _resolve = createBackCompatIdResolver(environment.getTopLevelConfig(), {
  31068. asSrc: false,
  31069. scan: true,
  31070. packageCache: esmPackageCache
  31071. });
  31072. const _resolveRequire = createBackCompatIdResolver(environment.getTopLevelConfig(), {
  31073. asSrc: false,
  31074. isRequire: true,
  31075. scan: true,
  31076. packageCache: cjsPackageCache
  31077. });
  31078. const resolve = (id, importer, kind) => {
  31079. const _importer = importer && importer in qualified ? qualified[importer] : importer;
  31080. return (kind.startsWith("require") ? _resolveRequire : _resolve)(environment, id, _importer);
  31081. };
  31082. const resolveResult = (id, resolved, kind) => {
  31083. if (resolved.startsWith("__vite-browser-external")) return { id: browserExternalNamespace + id };
  31084. if (resolved.startsWith("__vite-optional-peer-dep")) return { id: optionalPeerDepNamespace + resolved };
  31085. if (allExternalTypesReg.test(resolved)) return resolveAssets(resolved, kind);
  31086. if (isBuiltin(environment.config.resolve.builtins, resolved)) return;
  31087. if (isExternalUrl(resolved)) return {
  31088. id: resolved,
  31089. external: "absolute"
  31090. };
  31091. return { id: path.resolve(resolved) };
  31092. };
  31093. const allExternalTypesReg = new RegExp(`\\.(` + allExternalTypes.join("|") + `)(\\?.*)?$`);
  31094. function resolveEntry(id) {
  31095. const flatId = flattenId(id);
  31096. if (flatId in qualified) return { id: qualified[flatId] };
  31097. }
  31098. const bundleOutputDir = path.join(environment.config.cacheDir, "deps");
  31099. return [{
  31100. name: "vite:dep-pre-bundle-assets",
  31101. resolveId: {
  31102. filter: { id: allExternalTypesReg },
  31103. async handler(id, importer, options) {
  31104. const kind = options.kind;
  31105. if (id.startsWith(convertedExternalPrefix)) return {
  31106. id: id.slice(29),
  31107. external: "absolute"
  31108. };
  31109. const resolved = await resolve(id, importer, kind);
  31110. if (resolved) {
  31111. if (JS_TYPES_RE.test(resolved)) return {
  31112. id: isWindows ? resolved.replaceAll("/", "\\") : resolved,
  31113. external: false
  31114. };
  31115. return resolveAssets(resolved, kind);
  31116. }
  31117. }
  31118. },
  31119. load: {
  31120. filter: { id: prefixRegex(externalWithConversionNamespace) },
  31121. handler(id) {
  31122. const path = id.slice(39);
  31123. const modulePath = `"${convertedExternalPrefix}${path}"`;
  31124. return { code: isCSSRequest(path) && !isModuleCSSRequest(path) ? `import ${modulePath};` : `export { default } from ${modulePath};export * from ${modulePath};` };
  31125. }
  31126. }
  31127. }, {
  31128. name: "vite:dep-pre-bundle",
  31129. buildEnd() {
  31130. esmPackageCache.clear();
  31131. cjsPackageCache.clear();
  31132. },
  31133. resolveId: {
  31134. filter: { id: /^[\w@][^:]/ },
  31135. async handler(id, importer, options) {
  31136. const kind = options.kind;
  31137. if (moduleListContains(external, id)) return {
  31138. id,
  31139. external: "absolute"
  31140. };
  31141. let entry;
  31142. if (!importer) {
  31143. if (entry = resolveEntry(id)) return entry;
  31144. const aliased = await _resolve(environment, id, void 0, true);
  31145. if (aliased && (entry = resolveEntry(aliased))) return entry;
  31146. }
  31147. const resolved = await resolve(id, importer, kind);
  31148. if (resolved) return resolveResult(id, resolved, kind);
  31149. }
  31150. },
  31151. load: {
  31152. filter: { id: [prefixRegex(browserExternalNamespace), prefixRegex(optionalPeerDepNamespace)] },
  31153. handler(id) {
  31154. if (id.startsWith(browserExternalNamespace)) {
  31155. const path = id.slice(17);
  31156. if (isProduction) return { code: "module.exports = {}" };
  31157. else return { code: `\
  31158. module.exports = Object.create(new Proxy({}, {
  31159. get(_, key) {
  31160. if (
  31161. key !== '__esModule' &&
  31162. key !== '__proto__' &&
  31163. key !== 'constructor' &&
  31164. key !== 'splice'
  31165. ) {
  31166. console.warn(\`Module "${path}" has been externalized for browser compatibility. Cannot access "${path}.\${key}" in client code. See https://vite.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.\`)
  31167. }
  31168. }
  31169. }))` };
  31170. }
  31171. if (id.startsWith(optionalPeerDepNamespace)) {
  31172. const [, peerDep, parentDep] = id.slice(18).split(":");
  31173. return { code: `module.exports = {};throw new Error(\`Could not resolve "${peerDep}" imported by "${parentDep}". Is it installed?\`)` };
  31174. }
  31175. }
  31176. },
  31177. transform: {
  31178. filter: { code: assetImportMetaUrlRE },
  31179. async handler(code, id) {
  31180. let s;
  31181. const re = new RegExp(assetImportMetaUrlRE);
  31182. const cleanString = stripLiteral(code);
  31183. let match;
  31184. while (match = re.exec(cleanString)) {
  31185. const [[startIndex, endIndex], [urlStart, urlEnd]] = match.indices;
  31186. if (hasViteIgnoreRE.test(code.slice(startIndex, urlStart))) continue;
  31187. const rawUrl = code.slice(urlStart, urlEnd);
  31188. if (rawUrl[0] === "`" && rawUrl.includes("${")) continue;
  31189. const url = rawUrl.slice(1, -1);
  31190. if (isDataUrl(url) || isExternalUrl(url) || url.startsWith("/")) continue;
  31191. if (!s) s = new MagicString(code);
  31192. const absolutePath = path.resolve(path.dirname(id), url);
  31193. const normalizedRelativePath = normalizePath(path.relative(bundleOutputDir, absolutePath));
  31194. s.update(startIndex, endIndex, `new URL('' + ${JSON.stringify(normalizedRelativePath)}, import.meta.url)`);
  31195. }
  31196. if (s) return {
  31197. code: s.toString(),
  31198. map: s.generateMap({ hires: "boundary" })
  31199. };
  31200. }
  31201. }
  31202. }];
  31203. }
  31204. const matchesEntireLine = (text) => `^${escapeRegex(text)}$`;
  31205. function rolldownCjsExternalPlugin(externals, platform) {
  31206. if (platform === "node") return;
  31207. if (platform === "neutral") return;
  31208. const filter = new RegExp(externals.map(matchesEntireLine).join("|"));
  31209. return {
  31210. name: "cjs-external",
  31211. resolveId: {
  31212. filter: { id: [prefixRegex(nonFacadePrefix), filter] },
  31213. handler(id, _importer, options) {
  31214. if (id.startsWith(nonFacadePrefix)) return {
  31215. id: id.slice(25),
  31216. external: "absolute"
  31217. };
  31218. if (options.kind === "require-call") return { id: cjsExternalFacadeNamespace + id };
  31219. return {
  31220. id,
  31221. external: "absolute"
  31222. };
  31223. }
  31224. },
  31225. load: {
  31226. filter: { id: prefixRegex(cjsExternalFacadeNamespace) },
  31227. handler(id) {
  31228. const idWithoutNamespace = id.slice(24);
  31229. return { code: `\
  31230. import * as m from ${JSON.stringify(nonFacadePrefix + idWithoutNamespace)};
  31231. module.exports = ${isNodeBuiltin(idWithoutNamespace) ? "m.default" : "{ ...m }"};
  31232. ` };
  31233. }
  31234. }
  31235. };
  31236. }
  31237. //#endregion
  31238. //#region src/node/optimizer/index.ts
  31239. const debug$2 = createDebugger("vite:deps");
  31240. const jsExtensionRE = /\.js$/i;
  31241. function isDepOptimizationDisabled(optimizeDeps) {
  31242. return optimizeDeps.disabled === true || optimizeDeps.disabled === "dev" || !!optimizeDeps.noDiscovery && !optimizeDeps.include?.length;
  31243. }
  31244. /**
  31245. * Scan and optimize dependencies within a project.
  31246. * Used by Vite CLI when running `vite optimize`.
  31247. *
  31248. * @deprecated the optimization process runs automatically and does not need to be called
  31249. */
  31250. async function optimizeDeps(config, force = config.optimizeDeps.force, asCommand = false) {
  31251. const log = asCommand ? config.logger.info : debug$2;
  31252. config.logger.warn(import_picocolors.default.yellow("manually calling optimizeDeps is deprecated. This is done automatically and does not need to be called manually."));
  31253. const environment = new ScanEnvironment("client", config);
  31254. await environment.init();
  31255. const cachedMetadata = await loadCachedDepOptimizationMetadata(environment, force, asCommand);
  31256. if (cachedMetadata) return cachedMetadata;
  31257. const deps = await discoverProjectDependencies(environment).result;
  31258. await addManuallyIncludedOptimizeDeps(environment, deps);
  31259. const depsString = depsLogString(Object.keys(deps));
  31260. log?.(import_picocolors.default.green(`Optimizing dependencies:\n ${depsString}`));
  31261. const result = await runOptimizeDeps(environment, toDiscoveredDependencies(environment, deps)).result;
  31262. await result.commit();
  31263. return result.metadata;
  31264. }
  31265. async function optimizeExplicitEnvironmentDeps(environment) {
  31266. const cachedMetadata = await loadCachedDepOptimizationMetadata(environment, environment.config.optimizeDeps.force ?? false, false);
  31267. if (cachedMetadata) return cachedMetadata;
  31268. const deps = {};
  31269. await addManuallyIncludedOptimizeDeps(environment, deps);
  31270. const result = await runOptimizeDeps(environment, toDiscoveredDependencies(environment, deps)).result;
  31271. await result.commit();
  31272. return result.metadata;
  31273. }
  31274. function initDepsOptimizerMetadata(environment, timestamp) {
  31275. const { lockfileHash, configHash, hash } = getDepHash(environment);
  31276. return {
  31277. hash,
  31278. lockfileHash,
  31279. configHash,
  31280. browserHash: getOptimizedBrowserHash(hash, {}, timestamp),
  31281. optimized: {},
  31282. chunks: {},
  31283. discovered: {},
  31284. depInfoList: []
  31285. };
  31286. }
  31287. function addOptimizedDepInfo(metadata, type, depInfo) {
  31288. metadata[type][depInfo.id] = depInfo;
  31289. metadata.depInfoList.push(depInfo);
  31290. return depInfo;
  31291. }
  31292. let firstLoadCachedDepOptimizationMetadata = true;
  31293. /**
  31294. * Creates the initial dep optimization metadata, loading it from the deps cache
  31295. * if it exists and pre-bundling isn't forced
  31296. */
  31297. async function loadCachedDepOptimizationMetadata(environment, force = environment.config.optimizeDeps.force ?? false, asCommand = false) {
  31298. const log = asCommand ? environment.logger.info : debug$2;
  31299. if (firstLoadCachedDepOptimizationMetadata) {
  31300. firstLoadCachedDepOptimizationMetadata = false;
  31301. setTimeout(() => cleanupDepsCacheStaleDirs(environment.getTopLevelConfig()), 0).unref();
  31302. }
  31303. const depsCacheDir = getDepsCacheDir(environment);
  31304. if (!force) {
  31305. let cachedMetadata;
  31306. try {
  31307. const cachedMetadataPath = path.join(depsCacheDir, METADATA_FILENAME);
  31308. cachedMetadata = parseDepsOptimizerMetadata(await fsp.readFile(cachedMetadataPath, "utf-8"), depsCacheDir);
  31309. } catch {}
  31310. if (cachedMetadata) if (cachedMetadata.lockfileHash !== getLockfileHash(environment)) environment.logger.info("Re-optimizing dependencies because lockfile has changed", { timestamp: true });
  31311. else if (cachedMetadata.configHash !== getConfigHash(environment)) environment.logger.info("Re-optimizing dependencies because vite config has changed", { timestamp: true });
  31312. else {
  31313. log?.(`(${environment.name}) Hash is consistent. Skipping. Use --force to override.`);
  31314. return cachedMetadata;
  31315. }
  31316. } else environment.logger.info("Forced re-optimization of dependencies", { timestamp: true });
  31317. debug$2?.(`(${environment.name}) ${import_picocolors.default.green(`removing old cache dir ${depsCacheDir}`)}`);
  31318. await fsp.rm(depsCacheDir, {
  31319. recursive: true,
  31320. force: true
  31321. });
  31322. }
  31323. /**
  31324. * Initial optimizeDeps at server start. Perform a fast scan using esbuild to
  31325. * find deps to pre-bundle and include user hard-coded dependencies
  31326. */
  31327. function discoverProjectDependencies(environment) {
  31328. const { cancel, result } = scanImports(environment);
  31329. return {
  31330. cancel,
  31331. result: result.then(({ deps, missing }) => {
  31332. const missingIds = Object.keys(missing);
  31333. if (missingIds.length) throw new Error(`The following dependencies are imported but could not be resolved:\n\n ${missingIds.map((id) => `${import_picocolors.default.cyan(id)} ${import_picocolors.default.white(import_picocolors.default.dim(`(imported by ${missing[id]})`))}`).join(`\n `)}\n\nAre they installed?`);
  31334. return deps;
  31335. })
  31336. };
  31337. }
  31338. function toDiscoveredDependencies(environment, deps, timestamp) {
  31339. const browserHash = getOptimizedBrowserHash(getDepHash(environment).hash, deps, timestamp);
  31340. const discovered = {};
  31341. for (const id in deps) {
  31342. const src = deps[id];
  31343. discovered[id] = {
  31344. id,
  31345. file: getOptimizedDepPath(environment, id),
  31346. src,
  31347. browserHash,
  31348. exportsData: extractExportsData(environment, src)
  31349. };
  31350. }
  31351. return discovered;
  31352. }
  31353. function depsLogString(qualifiedIds) {
  31354. return import_picocolors.default.yellow(qualifiedIds.join(`, `));
  31355. }
  31356. /**
  31357. * Internally, Vite uses this function to prepare a optimizeDeps run. When Vite starts, we can get
  31358. * the metadata and start the server without waiting for the optimizeDeps processing to be completed
  31359. */
  31360. function runOptimizeDeps(environment, depsInfo) {
  31361. const optimizerContext = { cancelled: false };
  31362. const depsCacheDir = getDepsCacheDir(environment);
  31363. const processingCacheDir = getProcessingDepsCacheDir(environment);
  31364. fs.mkdirSync(processingCacheDir, { recursive: true });
  31365. debug$2?.(import_picocolors.default.green(`creating package.json in ${processingCacheDir}`));
  31366. fs.writeFileSync(path.resolve(processingCacheDir, "package.json"), `{\n "type": "module"\n}\n`);
  31367. const metadata = initDepsOptimizerMetadata(environment);
  31368. metadata.browserHash = getOptimizedBrowserHash(metadata.hash, depsFromOptimizedDepInfo(depsInfo));
  31369. const qualifiedIds = Object.keys(depsInfo);
  31370. let cleaned = false;
  31371. let committed = false;
  31372. const cleanUp = () => {
  31373. if (!cleaned && !committed) {
  31374. cleaned = true;
  31375. debug$2?.(import_picocolors.default.green(`removing cache dir ${processingCacheDir}`));
  31376. try {
  31377. fs.rmSync(processingCacheDir, {
  31378. recursive: true,
  31379. force: true
  31380. });
  31381. } catch {}
  31382. }
  31383. };
  31384. const successfulResult = {
  31385. metadata,
  31386. cancel: cleanUp,
  31387. commit: async () => {
  31388. if (cleaned) throw new Error("Can not commit a Deps Optimization run as it was cancelled");
  31389. committed = true;
  31390. const dataPath = path.join(processingCacheDir, METADATA_FILENAME);
  31391. debug$2?.(import_picocolors.default.green(`creating ${METADATA_FILENAME} in ${processingCacheDir}`));
  31392. fs.writeFileSync(dataPath, stringifyDepsOptimizerMetadata(metadata, depsCacheDir));
  31393. const temporaryPath = depsCacheDir + getTempSuffix();
  31394. const depsCacheDirPresent = fs.existsSync(depsCacheDir);
  31395. if (isWindows) {
  31396. if (depsCacheDirPresent) {
  31397. debug$2?.(import_picocolors.default.green(`renaming ${depsCacheDir} to ${temporaryPath}`));
  31398. await safeRename(depsCacheDir, temporaryPath);
  31399. }
  31400. debug$2?.(import_picocolors.default.green(`renaming ${processingCacheDir} to ${depsCacheDir}`));
  31401. await safeRename(processingCacheDir, depsCacheDir);
  31402. } else {
  31403. if (depsCacheDirPresent) {
  31404. debug$2?.(import_picocolors.default.green(`renaming ${depsCacheDir} to ${temporaryPath}`));
  31405. fs.renameSync(depsCacheDir, temporaryPath);
  31406. }
  31407. debug$2?.(import_picocolors.default.green(`renaming ${processingCacheDir} to ${depsCacheDir}`));
  31408. fs.renameSync(processingCacheDir, depsCacheDir);
  31409. }
  31410. if (depsCacheDirPresent) {
  31411. debug$2?.(import_picocolors.default.green(`removing cache temp dir ${temporaryPath}`));
  31412. fsp.rm(temporaryPath, {
  31413. recursive: true,
  31414. force: true
  31415. });
  31416. }
  31417. }
  31418. };
  31419. if (!qualifiedIds.length) return {
  31420. cancel: async () => cleanUp(),
  31421. result: Promise.resolve(successfulResult)
  31422. };
  31423. const cancelledResult = {
  31424. metadata,
  31425. commit: async () => cleanUp(),
  31426. cancel: cleanUp
  31427. };
  31428. const start = performance$1.now();
  31429. const bundleTimer = setTimeout(() => {
  31430. environment.logger.info("[optimizer] bundling dependencies...", { timestamp: true });
  31431. }, 1e3);
  31432. const preparedRun = prepareRolldownOptimizerRun(environment, depsInfo, processingCacheDir, optimizerContext);
  31433. const runResult = preparedRun.then(({ context, idToExports }) => {
  31434. if (!context || optimizerContext.cancelled) {
  31435. clearTimeout(bundleTimer);
  31436. return cancelledResult;
  31437. }
  31438. return context.build().then((result) => {
  31439. const depForEntryFileName = {};
  31440. for (const dep of Object.values(depsInfo)) {
  31441. const entryFileName = flattenId(dep.id) + ".js";
  31442. depForEntryFileName[entryFileName] = dep;
  31443. }
  31444. for (const chunk of result.output) {
  31445. if (chunk.type !== "chunk") continue;
  31446. if (chunk.isEntry) {
  31447. const { exportsData, file, id, ...info } = depForEntryFileName[chunk.fileName];
  31448. addOptimizedDepInfo(metadata, "optimized", {
  31449. id,
  31450. file,
  31451. ...info,
  31452. fileHash: getHash(metadata.hash + file + JSON.stringify(chunk.imports)),
  31453. browserHash: metadata.browserHash,
  31454. needsInterop: needsInterop(environment, id, idToExports[id], chunk)
  31455. });
  31456. } else {
  31457. const id = chunk.fileName.replace(jsExtensionRE, "");
  31458. const file = normalizePath(path.resolve(getDepsCacheDir(environment), chunk.fileName));
  31459. if (!findOptimizedDepInfoInRecord(metadata.optimized, (depInfo) => depInfo.file === file)) addOptimizedDepInfo(metadata, "chunks", {
  31460. id,
  31461. file,
  31462. needsInterop: false,
  31463. browserHash: metadata.browserHash,
  31464. isDynamicEntry: chunk.isDynamicEntry
  31465. });
  31466. }
  31467. }
  31468. clearTimeout(bundleTimer);
  31469. debug$2?.(`Dependencies bundled in ${(performance$1.now() - start).toFixed(2)}ms`);
  31470. return successfulResult;
  31471. }).catch((e) => {
  31472. clearTimeout(bundleTimer);
  31473. if (e.errors && e.message.includes("The build was canceled")) return cancelledResult;
  31474. e.message = import_picocolors.default.red("Error during dependency optimization:\n\n") + e.message;
  31475. throw e;
  31476. });
  31477. });
  31478. runResult.catch(() => {
  31479. cleanUp();
  31480. });
  31481. return {
  31482. async cancel() {
  31483. optimizerContext.cancelled = true;
  31484. const { context } = await preparedRun;
  31485. context?.cancel();
  31486. cleanUp();
  31487. },
  31488. result: runResult
  31489. };
  31490. }
  31491. async function prepareRolldownOptimizerRun(environment, depsInfo, processingCacheDir, optimizerContext) {
  31492. const flatIdDeps = {};
  31493. const idToExports = {};
  31494. const { optimizeDeps } = environment.config;
  31495. const { plugins: pluginsFromConfig = [], ...rolldownOptions } = optimizeDeps.rolldownOptions ?? {};
  31496. let jsxLoader = false;
  31497. await Promise.all(Object.keys(depsInfo).map(async (id) => {
  31498. const src = depsInfo[id].src;
  31499. const exportsData = await (depsInfo[id].exportsData ?? extractExportsData(environment, src));
  31500. if (exportsData.jsxLoader) jsxLoader = true;
  31501. const flatId = flattenId(id);
  31502. flatIdDeps[flatId] = isWindows ? src.replaceAll("/", "\\") : src;
  31503. idToExports[id] = exportsData;
  31504. }));
  31505. if (optimizerContext.cancelled) return {
  31506. context: void 0,
  31507. idToExports
  31508. };
  31509. const define = {
  31510. "process.env.NODE_ENV": environment.config.keepProcessEnv ? "process.env.NODE_ENV" : JSON.stringify(process.env.NODE_ENV || environment.config.mode),
  31511. ...rolldownOptions.transform?.define
  31512. };
  31513. const platform = optimizeDeps.rolldownOptions?.platform ?? (environment.config.consumer === "client" || environment.config.ssr.target === "webworker" ? "browser" : "node");
  31514. const external = [...optimizeDeps.exclude ?? []];
  31515. const plugins = await asyncFlatten(arraify(pluginsFromConfig));
  31516. if (external.length) plugins.push(rolldownCjsExternalPlugin(external, platform));
  31517. plugins.push(...rolldownDepPlugin(environment, flatIdDeps, external));
  31518. let canceled = false;
  31519. async function build() {
  31520. const bundle = await rolldown({
  31521. ...rolldownOptions,
  31522. input: flatIdDeps,
  31523. logLevel: "silent",
  31524. plugins,
  31525. platform,
  31526. transform: {
  31527. ...rolldownOptions.transform,
  31528. target: ESBUILD_BASELINE_WIDELY_AVAILABLE_TARGET,
  31529. define
  31530. },
  31531. resolve: {
  31532. extensions: [
  31533. ".tsx",
  31534. ".ts",
  31535. ".jsx",
  31536. ".js",
  31537. ".css",
  31538. ".json"
  31539. ],
  31540. ...rolldownOptions.resolve
  31541. },
  31542. moduleTypes: {
  31543. ".css": "js",
  31544. ...rolldownOptions.moduleTypes,
  31545. ...jsxLoader ? { ".js": "jsx" } : {}
  31546. }
  31547. });
  31548. if (canceled) {
  31549. await bundle.close();
  31550. throw new Error("The build was canceled");
  31551. }
  31552. const result = await bundle.write({
  31553. ...rolldownOptions.output,
  31554. format: "esm",
  31555. sourcemap: true,
  31556. dir: processingCacheDir,
  31557. entryFileNames: "[name].js"
  31558. });
  31559. await bundle.close();
  31560. return result;
  31561. }
  31562. function cancel() {
  31563. canceled = true;
  31564. }
  31565. return {
  31566. context: {
  31567. build,
  31568. cancel
  31569. },
  31570. idToExports
  31571. };
  31572. }
  31573. async function addManuallyIncludedOptimizeDeps(environment, deps) {
  31574. const { logger } = environment;
  31575. const { optimizeDeps } = environment.config;
  31576. const optimizeDepsInclude = optimizeDeps.include ?? [];
  31577. if (optimizeDepsInclude.length) {
  31578. const unableToOptimize = (id, msg) => {
  31579. if (optimizeDepsInclude.includes(id)) logger.warn(`${msg}: ${import_picocolors.default.cyan(id)}, present in ${environment.name} 'optimizeDeps.include'`);
  31580. };
  31581. const includes = [...optimizeDepsInclude];
  31582. for (let i = 0; i < includes.length; i++) {
  31583. const id = includes[i];
  31584. if (isDynamicPattern(id)) {
  31585. const globIds = expandGlobIds(id, environment.getTopLevelConfig());
  31586. includes.splice(i, 1, ...globIds);
  31587. i += globIds.length - 1;
  31588. }
  31589. }
  31590. const resolve = createOptimizeDepsIncludeResolver(environment);
  31591. for (const id of includes) {
  31592. const normalizedId = normalizeId(id);
  31593. if (!deps[normalizedId]) {
  31594. const entry = await resolve(id);
  31595. if (entry) if (isOptimizable(entry, optimizeDeps)) deps[normalizedId] = entry;
  31596. else unableToOptimize(id, "Cannot optimize dependency");
  31597. else unableToOptimize(id, "Failed to resolve dependency");
  31598. }
  31599. }
  31600. }
  31601. }
  31602. function depsFromOptimizedDepInfo(depsInfo) {
  31603. const obj = {};
  31604. for (const key in depsInfo) obj[key] = depsInfo[key].src;
  31605. return obj;
  31606. }
  31607. function getOptimizedDepPath(environment, id) {
  31608. return normalizePath(path.resolve(getDepsCacheDir(environment), flattenId(id) + ".js"));
  31609. }
  31610. function getDepsCacheSuffix(environment) {
  31611. return environment.name === "client" ? "" : `_${environment.name}`;
  31612. }
  31613. function getDepsCacheDir(environment) {
  31614. return getDepsCacheDirPrefix(environment) + getDepsCacheSuffix(environment);
  31615. }
  31616. function getProcessingDepsCacheDir(environment) {
  31617. return getDepsCacheDirPrefix(environment) + getDepsCacheSuffix(environment) + getTempSuffix();
  31618. }
  31619. function getTempSuffix() {
  31620. return "_temp_" + getHash(`${process.pid}:${Date.now().toString()}:${Math.random().toString(16).slice(2)}`);
  31621. }
  31622. function getDepsCacheDirPrefix(environment) {
  31623. return normalizePath(path.resolve(environment.config.cacheDir, "deps"));
  31624. }
  31625. function createIsOptimizedDepFile(environment) {
  31626. const depsCacheDirPrefix = getDepsCacheDirPrefix(environment);
  31627. return (id) => id.startsWith(depsCacheDirPrefix);
  31628. }
  31629. function createIsOptimizedDepUrl(environment) {
  31630. const { root } = environment.config;
  31631. const depsCacheDir = getDepsCacheDirPrefix(environment);
  31632. const depsCacheDirRelative = normalizePath(path.relative(root, depsCacheDir));
  31633. const depsCacheDirPrefix = depsCacheDirRelative.startsWith("../") ? `/@fs/${removeLeadingSlash(normalizePath(depsCacheDir))}` : `/${depsCacheDirRelative}`;
  31634. return function isOptimizedDepUrl(url) {
  31635. return url.startsWith(depsCacheDirPrefix);
  31636. };
  31637. }
  31638. function parseDepsOptimizerMetadata(jsonMetadata, depsCacheDir) {
  31639. const { hash, lockfileHash, configHash, browserHash, optimized, chunks } = JSON.parse(jsonMetadata, (key, value) => {
  31640. if (key === "file" || key === "src") return normalizePath(path.resolve(depsCacheDir, value));
  31641. return value;
  31642. });
  31643. if (!chunks || Object.values(optimized).some((depInfo) => !depInfo.fileHash)) return;
  31644. const metadata = {
  31645. hash,
  31646. lockfileHash,
  31647. configHash,
  31648. browserHash,
  31649. optimized: {},
  31650. discovered: {},
  31651. chunks: {},
  31652. depInfoList: []
  31653. };
  31654. for (const id of Object.keys(optimized)) addOptimizedDepInfo(metadata, "optimized", {
  31655. ...optimized[id],
  31656. id,
  31657. browserHash
  31658. });
  31659. for (const id of Object.keys(chunks)) addOptimizedDepInfo(metadata, "chunks", {
  31660. ...chunks[id],
  31661. id,
  31662. browserHash,
  31663. needsInterop: false
  31664. });
  31665. return metadata;
  31666. }
  31667. /**
  31668. * Stringify metadata for deps cache. Remove processing promises
  31669. * and individual dep info browserHash. Once the cache is reload
  31670. * the next time the server start we need to use the global
  31671. * browserHash to allow long term caching
  31672. */
  31673. function stringifyDepsOptimizerMetadata(metadata, depsCacheDir) {
  31674. const { hash, configHash, lockfileHash, browserHash, optimized, chunks } = metadata;
  31675. return JSON.stringify({
  31676. hash,
  31677. configHash,
  31678. lockfileHash,
  31679. browserHash,
  31680. optimized: Object.fromEntries(Object.values(optimized).map(({ id, src, file, fileHash, needsInterop, isDynamicEntry }) => [id, {
  31681. src,
  31682. file,
  31683. fileHash,
  31684. needsInterop,
  31685. isDynamicEntry
  31686. }])),
  31687. chunks: Object.fromEntries(Object.values(chunks).map(({ id, file, isDynamicEntry }) => [id, {
  31688. file,
  31689. isDynamicEntry
  31690. }]))
  31691. }, (key, value) => {
  31692. if (key === "file" || key === "src") return normalizePath(path.relative(depsCacheDir, value));
  31693. return value;
  31694. }, 2);
  31695. }
  31696. async function extractExportsData(environment, filePath) {
  31697. await init;
  31698. const { optimizeDeps } = environment.config;
  31699. const rolldownOptions = optimizeDeps.rolldownOptions ?? {};
  31700. if (optimizeDeps.extensions?.some((ext) => filePath.endsWith(ext))) {
  31701. const { plugins: pluginsFromConfig = [], ...remainingRolldownOptions } = rolldownOptions;
  31702. const plugins = await asyncFlatten(arraify(pluginsFromConfig));
  31703. plugins.unshift({
  31704. name: "externalize",
  31705. resolveId(id, importer) {
  31706. if (importer !== void 0) return {
  31707. id,
  31708. external: true
  31709. };
  31710. }
  31711. });
  31712. const [, exports, , hasModuleSyntax] = parse$2((await (await rolldown({
  31713. ...remainingRolldownOptions,
  31714. plugins,
  31715. input: [filePath],
  31716. moduleTypes: {
  31717. ".css": "js",
  31718. ...remainingRolldownOptions.moduleTypes
  31719. }
  31720. })).generate({
  31721. ...rolldownOptions.output,
  31722. format: "esm",
  31723. sourcemap: false
  31724. })).output[0].code);
  31725. return {
  31726. hasModuleSyntax,
  31727. exports: exports.map((e) => e.n)
  31728. };
  31729. }
  31730. let parseResult;
  31731. let usedJsxLoader = false;
  31732. const entryContent = fs.readFileSync(filePath, "utf-8");
  31733. try {
  31734. parseResult = parse$2(entryContent);
  31735. } catch {
  31736. const lang = rolldownOptions.moduleTypes?.[path.extname(filePath)] || "jsx";
  31737. debug$2?.(`Unable to parse: ${filePath}.\n Trying again with a ${lang} transform.`);
  31738. if (lang !== "jsx" && lang !== "tsx" && lang !== "ts") throw new Error(`Unable to parse : ${filePath}.`);
  31739. parseResult = parse$2((await transformWithOxc(entryContent, filePath, { lang }, void 0, environment.config)).code);
  31740. usedJsxLoader = true;
  31741. }
  31742. const [, exports, , hasModuleSyntax] = parseResult;
  31743. return {
  31744. hasModuleSyntax,
  31745. exports: exports.map((e) => e.n),
  31746. jsxLoader: usedJsxLoader
  31747. };
  31748. }
  31749. function needsInterop(environment, id, exportsData, output) {
  31750. if (environment.config.optimizeDeps.needsInterop?.includes(id)) return true;
  31751. const { hasModuleSyntax, exports } = exportsData;
  31752. if (!hasModuleSyntax) return true;
  31753. if (output) {
  31754. const generatedExports = output.exports;
  31755. if (isSingleDefaultExport(generatedExports) && !isSingleDefaultExport(exports)) return true;
  31756. }
  31757. return false;
  31758. }
  31759. function isSingleDefaultExport(exports) {
  31760. return exports.length === 1 && exports[0] === "default";
  31761. }
  31762. const lockfileFormats = [
  31763. {
  31764. path: "node_modules/.package-lock.json",
  31765. checkPatchesDir: "patches",
  31766. manager: "npm"
  31767. },
  31768. {
  31769. path: "node_modules/.yarn-state.yml",
  31770. checkPatchesDir: false,
  31771. manager: "yarn"
  31772. },
  31773. {
  31774. path: ".pnp.cjs",
  31775. checkPatchesDir: ".yarn/patches",
  31776. manager: "yarn"
  31777. },
  31778. {
  31779. path: ".pnp.js",
  31780. checkPatchesDir: ".yarn/patches",
  31781. manager: "yarn"
  31782. },
  31783. {
  31784. path: "node_modules/.yarn-integrity",
  31785. checkPatchesDir: "patches",
  31786. manager: "yarn"
  31787. },
  31788. {
  31789. path: "node_modules/.pnpm/lock.yaml",
  31790. checkPatchesDir: false,
  31791. manager: "pnpm"
  31792. },
  31793. {
  31794. path: ".rush/temp/shrinkwrap-deps.json",
  31795. checkPatchesDir: false,
  31796. manager: "pnpm"
  31797. },
  31798. {
  31799. path: "bun.lock",
  31800. checkPatchesDir: "patches",
  31801. manager: "bun"
  31802. },
  31803. {
  31804. path: "bun.lockb",
  31805. checkPatchesDir: "patches",
  31806. manager: "bun"
  31807. }
  31808. ].sort((_, { manager }) => {
  31809. return process.env.npm_config_user_agent?.startsWith(manager) ? 1 : -1;
  31810. });
  31811. const lockfilePaths = lockfileFormats.map((l) => l.path);
  31812. function getConfigHash(environment) {
  31813. const { config } = environment;
  31814. const { optimizeDeps } = config;
  31815. return getHash(JSON.stringify({
  31816. define: !config.keepProcessEnv ? process.env.NODE_ENV || config.mode : null,
  31817. root: config.root,
  31818. resolve: config.resolve,
  31819. assetsInclude: config.assetsInclude,
  31820. plugins: config.plugins.map((p) => p.name),
  31821. optimizeDeps: {
  31822. include: optimizeDeps.include ? unique(optimizeDeps.include).sort() : void 0,
  31823. exclude: optimizeDeps.exclude ? unique(optimizeDeps.exclude).sort() : void 0,
  31824. rolldownOptions: {
  31825. ...optimizeDeps.rolldownOptions,
  31826. plugins: void 0,
  31827. onLog: void 0,
  31828. onwarn: void 0,
  31829. checks: void 0,
  31830. output: {
  31831. ...optimizeDeps.rolldownOptions?.output,
  31832. plugins: void 0
  31833. }
  31834. }
  31835. },
  31836. optimizeDepsPluginNames: config.optimizeDepsPluginNames
  31837. }, (_, value) => {
  31838. if (typeof value === "function" || value instanceof RegExp) return value.toString();
  31839. return value;
  31840. }));
  31841. }
  31842. function getLockfileHash(environment) {
  31843. const lockfilePath = lookupFile(environment.config.root, lockfilePaths);
  31844. let content = lockfilePath ? fs.readFileSync(lockfilePath, "utf-8") : "";
  31845. if (lockfilePath) {
  31846. const normalizedLockfilePath = lockfilePath.replaceAll("\\", "/");
  31847. const lockfileFormat = lockfileFormats.find((f) => normalizedLockfilePath.endsWith(f.path));
  31848. if (lockfileFormat.checkPatchesDir) {
  31849. const baseDir = lockfilePath.slice(0, -lockfileFormat.path.length);
  31850. const stat = tryStatSync(path.join(baseDir, lockfileFormat.checkPatchesDir));
  31851. if (stat?.isDirectory()) content += stat.mtimeMs.toString();
  31852. }
  31853. }
  31854. return getHash(content);
  31855. }
  31856. function getDepHash(environment) {
  31857. const lockfileHash = getLockfileHash(environment);
  31858. const configHash = getConfigHash(environment);
  31859. return {
  31860. hash: getHash(lockfileHash + configHash),
  31861. lockfileHash,
  31862. configHash
  31863. };
  31864. }
  31865. function getOptimizedBrowserHash(hash, deps, timestamp = "") {
  31866. return getHash(hash + JSON.stringify(deps) + timestamp);
  31867. }
  31868. function optimizedDepInfoFromId(metadata, id) {
  31869. return metadata.optimized[id] || metadata.discovered[id] || metadata.chunks[id];
  31870. }
  31871. function optimizedDepInfoFromFile(metadata, file) {
  31872. return metadata.depInfoList.find((depInfo) => depInfo.file === file);
  31873. }
  31874. function findOptimizedDepInfoInRecord(dependenciesInfo, callbackFn) {
  31875. for (const o of Object.keys(dependenciesInfo)) {
  31876. const info = dependenciesInfo[o];
  31877. if (callbackFn(info, o)) return info;
  31878. }
  31879. }
  31880. async function optimizedDepNeedsInterop(environment, metadata, file) {
  31881. const depInfo = optimizedDepInfoFromFile(metadata, file);
  31882. if (depInfo?.src && depInfo.needsInterop === void 0) {
  31883. depInfo.exportsData ??= extractExportsData(environment, depInfo.src);
  31884. depInfo.needsInterop = needsInterop(environment, depInfo.id, await depInfo.exportsData);
  31885. }
  31886. return depInfo?.needsInterop;
  31887. }
  31888. const MAX_TEMP_DIR_AGE_MS = 1440 * 60 * 1e3;
  31889. async function cleanupDepsCacheStaleDirs(config) {
  31890. try {
  31891. const cacheDir = path.resolve(config.cacheDir);
  31892. if (fs.existsSync(cacheDir)) {
  31893. const dirents = await fsp.readdir(cacheDir, { withFileTypes: true });
  31894. for (const dirent of dirents) if (dirent.isDirectory() && dirent.name.includes("_temp_")) {
  31895. const tempDirPath = path.resolve(config.cacheDir, dirent.name);
  31896. const stats = await fsp.stat(tempDirPath).catch(() => null);
  31897. if (stats?.mtime && Date.now() - stats.mtime.getTime() > MAX_TEMP_DIR_AGE_MS) {
  31898. debug$2?.(`removing stale cache temp dir ${tempDirPath}`);
  31899. await fsp.rm(tempDirPath, {
  31900. recursive: true,
  31901. force: true
  31902. });
  31903. }
  31904. }
  31905. }
  31906. } catch (err) {
  31907. config.logger.error(err);
  31908. }
  31909. }
  31910. const GRACEFUL_RENAME_TIMEOUT = 5e3;
  31911. const safeRename = promisify(function gracefulRename(from, to, cb) {
  31912. const start = Date.now();
  31913. let backoff = 0;
  31914. fs.rename(from, to, function CB(er) {
  31915. if (er && (er.code === "EACCES" || er.code === "EPERM") && Date.now() - start < GRACEFUL_RENAME_TIMEOUT) {
  31916. setTimeout(function() {
  31917. fs.stat(to, function(stater, _st) {
  31918. if (stater && stater.code === "ENOENT") fs.rename(from, to, CB);
  31919. else CB(er);
  31920. });
  31921. }, backoff);
  31922. if (backoff < 100) backoff += 10;
  31923. return;
  31924. }
  31925. cb(er);
  31926. });
  31927. });
  31928. //#endregion
  31929. //#region src/node/plugins/resolve.ts
  31930. const normalizedClientEntry = normalizePath(CLIENT_ENTRY);
  31931. const normalizedEnvEntry = normalizePath(ENV_ENTRY);
  31932. const ERR_RESOLVE_PACKAGE_ENTRY_FAIL = "ERR_RESOLVE_PACKAGE_ENTRY_FAIL";
  31933. const browserExternalId = "__vite-browser-external";
  31934. const optionalPeerDepId = "__vite-optional-peer-dep";
  31935. const subpathImportsPrefix = "#";
  31936. const relativePrefixRE = /^\.\.?(?:[/\\]|$)/;
  31937. const startsWithWordCharRE = /^\w/;
  31938. const debug$1 = createDebugger("vite:resolve-details", { onlyWhenFocused: true });
  31939. const perEnvironmentOrWorkerPlugin = (name, overrideEnvConfig, f) => {
  31940. const envs = {};
  31941. const getEnvironmentPlugin = {
  31942. name: `${name}:get-environment`,
  31943. buildStart() {
  31944. envs[this.environment.name] = this.environment;
  31945. },
  31946. perEnvironmentStartEndDuringDev: true
  31947. };
  31948. const createGetEnvironment = (name) => () => envs[name];
  31949. if (overrideEnvConfig) return [getEnvironmentPlugin, f({
  31950. name: "client",
  31951. config: overrideEnvConfig
  31952. }, createGetEnvironment("client"))];
  31953. return [getEnvironmentPlugin, {
  31954. name,
  31955. applyToEnvironment(environment) {
  31956. return f(environment, createGetEnvironment(environment.name));
  31957. }
  31958. }];
  31959. };
  31960. function oxcResolvePlugin(resolveOptions, overrideEnvConfig) {
  31961. return [...resolveOptions.optimizeDeps && !resolveOptions.isBuild ? [optimizerResolvePlugin(resolveOptions)] : [], ...perEnvironmentOrWorkerPlugin("vite:resolve-builtin", overrideEnvConfig, (partialEnv, getEnv) => {
  31962. const depsOptimizerEnabled = resolveOptions.optimizeDeps && !resolveOptions.isBuild && !partialEnv.config.experimental.bundledDev && !isDepOptimizationDisabled(partialEnv.config.optimizeDeps);
  31963. const getDepsOptimizer = () => {
  31964. const env = getEnv();
  31965. if (env.mode !== "dev") throw new Error("The environment mode should be dev");
  31966. if (!env.depsOptimizer) throw new Error("The environment should have a depsOptimizer");
  31967. return env.depsOptimizer;
  31968. };
  31969. const options = {
  31970. ...partialEnv.config.resolve,
  31971. ...resolveOptions
  31972. };
  31973. const noExternal = Array.isArray(options.noExternal) || options.noExternal === true ? options.noExternal : [options.noExternal];
  31974. const plugin = viteResolvePlugin({
  31975. resolveOptions: {
  31976. isBuild: options.isBuild,
  31977. isProduction: options.isProduction,
  31978. asSrc: options.asSrc ?? false,
  31979. preferRelative: options.preferRelative ?? false,
  31980. isRequire: options.isRequire,
  31981. root: options.root,
  31982. scan: options.scan ?? false,
  31983. mainFields: options.skipMainField ? options.mainFields : options.mainFields.concat(["main"]),
  31984. conditions: options.conditions,
  31985. externalConditions: options.externalConditions,
  31986. extensions: options.extensions,
  31987. tryIndex: options.tryIndex ?? true,
  31988. tryPrefix: options.tryPrefix,
  31989. preserveSymlinks: options.preserveSymlinks,
  31990. tsconfigPaths: options.tsconfigPaths
  31991. },
  31992. environmentConsumer: partialEnv.config.consumer,
  31993. environmentName: partialEnv.name,
  31994. builtins: partialEnv.config.resolve.builtins,
  31995. external: options.external,
  31996. noExternal,
  31997. dedupe: options.dedupe,
  31998. disableCache: partialEnv.config.command === "serve" && partialEnv.config.server.watch === null,
  31999. legacyInconsistentCjsInterop: options.legacyInconsistentCjsInterop,
  32000. finalizeBareSpecifier: !depsOptimizerEnabled ? void 0 : (resolvedId, rawId, importer) => {
  32001. const depsOptimizer = getDepsOptimizer();
  32002. const isJsType = isOptimizable(resolvedId, depsOptimizer.options);
  32003. const exclude = depsOptimizer?.options.exclude;
  32004. const deepMatch = deepImportRE.exec(rawId);
  32005. const pkgId = deepMatch ? deepMatch[1] || deepMatch[2] : cleanUrl(rawId);
  32006. const skipOptimization = depsOptimizer.options.noDiscovery || !isJsType || importer && isInNodeModules(importer) || exclude?.includes(pkgId) || exclude?.includes(rawId) || SPECIAL_QUERY_RE.test(resolvedId);
  32007. let newId = resolvedId;
  32008. if (skipOptimization) {
  32009. const versionHash = depsOptimizer.metadata.browserHash;
  32010. if (versionHash && isJsType) newId = injectQuery(newId, `v=${versionHash}`);
  32011. } else {
  32012. const optimizedInfo = depsOptimizer.registerMissingImport(rawId, newId);
  32013. newId = depsOptimizer.getOptimizedDepId(optimizedInfo);
  32014. }
  32015. return newId;
  32016. },
  32017. finalizeOtherSpecifiers: !depsOptimizerEnabled ? void 0 : (resolvedId, rawId) => {
  32018. const newResolvedId = ensureVersionQuery(resolvedId, rawId, options, getDepsOptimizer());
  32019. return newResolvedId === resolvedId ? void 0 : newResolvedId;
  32020. },
  32021. resolveSubpathImports(id, importer, isRequire, scan) {
  32022. return resolveSubpathImports(id, importer, {
  32023. ...options,
  32024. isRequire: resolveOptions.isRequire ?? isRequire,
  32025. scan
  32026. });
  32027. },
  32028. ...partialEnv.config.command === "serve" ? { async onWarn(msg) {
  32029. getEnv().logger.warn(`warning: ${msg}`, {
  32030. clear: true,
  32031. timestamp: true
  32032. });
  32033. } } : {},
  32034. ...debug$1 ? { async onDebug(message) {
  32035. debug$1(message);
  32036. } } : {}
  32037. });
  32038. plugin.perEnvironmentWatchChangeDuringDev = true;
  32039. return plugin;
  32040. })];
  32041. }
  32042. function optimizerResolvePlugin(resolveOptions) {
  32043. const { root, asSrc } = resolveOptions;
  32044. return {
  32045. name: "vite:resolve-dev",
  32046. applyToEnvironment(environment) {
  32047. return !environment.config.experimental.bundledDev && !isDepOptimizationDisabled(environment.config.optimizeDeps);
  32048. },
  32049. resolveId: {
  32050. filter: { id: { exclude: [
  32051. /^\0/,
  32052. /^virtual:/,
  32053. /^\/virtual:/,
  32054. /^__vite-/
  32055. ] } },
  32056. async handler(id, importer, resolveOpts) {
  32057. const depsOptimizer = resolveOptions.optimizeDeps && this.environment.mode === "dev" ? this.environment.depsOptimizer : void 0;
  32058. if (!depsOptimizer) return;
  32059. const options = {
  32060. isRequire: resolveOpts.kind === "require-call",
  32061. ...this.environment.config.resolve,
  32062. ...resolveOptions,
  32063. scan: resolveOpts.scan ?? resolveOptions.scan
  32064. };
  32065. options.preferRelative ||= importer?.endsWith(".html");
  32066. if (asSrc && depsOptimizer.isOptimizedDepUrl(id)) return id.startsWith(FS_PREFIX) ? fsPathFromId(id) : normalizePath(path.resolve(root, id.slice(1)));
  32067. if (!isDataUrl(id) && !isExternalUrl(id)) {
  32068. if (id[0] === "." || options.preferRelative && startsWithWordCharRE.test(id)) {
  32069. const basedir = importer ? path.dirname(importer) : root;
  32070. const normalizedFsPath = normalizePath(path.resolve(basedir, id));
  32071. if (depsOptimizer.isOptimizedDepFile(normalizedFsPath)) {
  32072. if (!DEP_VERSION_RE.test(normalizedFsPath)) {
  32073. const browserHash = optimizedDepInfoFromFile(depsOptimizer.metadata, normalizedFsPath)?.browserHash;
  32074. if (browserHash) return injectQuery(normalizedFsPath, `v=${browserHash}`);
  32075. }
  32076. return normalizedFsPath;
  32077. }
  32078. }
  32079. if (bareImportRE.test(id)) {
  32080. let res;
  32081. if (asSrc && !options.scan && (res = await tryOptimizedResolve(depsOptimizer, id, importer, options.preserveSymlinks, options.packageCache))) return res;
  32082. }
  32083. }
  32084. }
  32085. }
  32086. };
  32087. }
  32088. function resolveSubpathImports(id, importer, options) {
  32089. if (!importer || !id.startsWith(subpathImportsPrefix)) return;
  32090. const basedir = path.dirname(importer);
  32091. const pkgData = findNearestPackageData(basedir, options.packageCache);
  32092. if (!pkgData) return;
  32093. let { file: idWithoutPostfix, postfix } = splitFileAndPostfix(id.slice(1));
  32094. idWithoutPostfix = "#" + idWithoutPostfix;
  32095. let importsPath = resolveExportsOrImports(pkgData.data, idWithoutPostfix, options, "imports");
  32096. if (importsPath?.[0] === ".") {
  32097. importsPath = path.relative(basedir, path.join(pkgData.dir, importsPath));
  32098. if (!relativePrefixRE.test(importsPath)) importsPath = `./${importsPath}`;
  32099. }
  32100. if (importsPath == null) return;
  32101. return importsPath + postfix;
  32102. }
  32103. function ensureVersionQuery(resolved, id, options, depsOptimizer) {
  32104. if (!options.isBuild && !options.scan && depsOptimizer && !(resolved === normalizedClientEntry || resolved === normalizedEnvEntry)) {
  32105. if ((isInNodeModules(id) || isInNodeModules(resolved)) && !DEP_VERSION_RE.test(resolved)) {
  32106. const versionHash = depsOptimizer.metadata.browserHash;
  32107. if (versionHash && isOptimizable(resolved, depsOptimizer.options)) resolved = injectQuery(resolved, `v=${versionHash}`);
  32108. }
  32109. }
  32110. return resolved;
  32111. }
  32112. function tryFsResolve(fsPath, options, tryIndex = true, skipPackageJson = false) {
  32113. const hashIndex = fsPath.indexOf("#");
  32114. if (hashIndex >= 0 && isInNodeModules(fsPath)) {
  32115. const queryIndex = fsPath.indexOf("?");
  32116. if (queryIndex < 0 || queryIndex > hashIndex) {
  32117. const file = queryIndex > hashIndex ? fsPath.slice(0, queryIndex) : fsPath;
  32118. const res = tryCleanFsResolve(file, options, tryIndex, skipPackageJson);
  32119. if (res) return res + fsPath.slice(file.length);
  32120. }
  32121. }
  32122. const { file, postfix } = splitFileAndPostfix(fsPath);
  32123. const res = tryCleanFsResolve(file, options, tryIndex, skipPackageJson);
  32124. if (res) return res + postfix;
  32125. }
  32126. const knownTsOutputRE = /\.(?:js|mjs|cjs|jsx)$/;
  32127. const isPossibleTsOutput = (url) => knownTsOutputRE.test(url);
  32128. function tryCleanFsResolve(file, options, tryIndex = true, skipPackageJson = false) {
  32129. const { tryPrefix, extensions, preserveSymlinks } = options;
  32130. const fileResult = tryResolveRealFileOrType(file, options.preserveSymlinks);
  32131. if (fileResult?.path) return fileResult.path;
  32132. let res;
  32133. const possibleJsToTs = isPossibleTsOutput(file);
  32134. if (possibleJsToTs || options.extensions.length || tryPrefix) {
  32135. const dirPath = path.dirname(file);
  32136. if (isDirectory(dirPath)) {
  32137. if (possibleJsToTs) {
  32138. const fileExt = path.extname(file);
  32139. const fileName = file.slice(0, -fileExt.length);
  32140. if (res = tryResolveRealFile(fileName + fileExt.replace("js", "ts"), preserveSymlinks)) return res;
  32141. if (fileExt === ".js" && (res = tryResolveRealFile(fileName + ".tsx", preserveSymlinks))) return res;
  32142. }
  32143. if (res = tryResolveRealFileWithExtensions(file, extensions, preserveSymlinks)) return res;
  32144. if (tryPrefix) {
  32145. const prefixed = `${dirPath}/${options.tryPrefix}${path.basename(file)}`;
  32146. if (res = tryResolveRealFile(prefixed, preserveSymlinks)) return res;
  32147. if (res = tryResolveRealFileWithExtensions(prefixed, extensions, preserveSymlinks)) return res;
  32148. }
  32149. }
  32150. }
  32151. if (tryIndex && fileResult?.type === "directory") {
  32152. const dirPath = file;
  32153. if (!skipPackageJson) {
  32154. let pkgPath = `${dirPath}/package.json`;
  32155. try {
  32156. if (fs.existsSync(pkgPath)) {
  32157. if (!options.preserveSymlinks) pkgPath = safeRealpathSync(pkgPath);
  32158. return resolvePackageEntry(dirPath, loadPackageData(pkgPath), options);
  32159. }
  32160. } catch (e) {
  32161. if (e.code !== ERR_RESOLVE_PACKAGE_ENTRY_FAIL && e.code !== "ENOENT") throw e;
  32162. }
  32163. }
  32164. if (res = tryResolveRealFileWithExtensions(`${dirPath}/index`, extensions, preserveSymlinks)) return res;
  32165. if (tryPrefix) {
  32166. if (res = tryResolveRealFileWithExtensions(`${dirPath}/${options.tryPrefix}index`, extensions, preserveSymlinks)) return res;
  32167. }
  32168. }
  32169. }
  32170. function tryNodeResolve(id, importer, options, depsOptimizer, externalize) {
  32171. const { root, dedupe, isBuild, preserveSymlinks, packageCache } = options;
  32172. const deepMatch = deepImportRE.exec(id);
  32173. const pkgId = deepMatch ? deepMatch[1] || deepMatch[2] : cleanUrl(id);
  32174. let basedir;
  32175. if (dedupe.includes(pkgId)) basedir = root;
  32176. else if (importer && path.isAbsolute(importer) && (importer.endsWith("*") || fs.existsSync(cleanUrl(importer)))) basedir = path.dirname(importer);
  32177. else basedir = root;
  32178. const isModuleBuiltin = (id) => isBuiltin(options.builtins, id);
  32179. let selfPkg = null;
  32180. if (!isModuleBuiltin(id) && !id.includes("\0") && bareImportRE.test(id)) {
  32181. const selfPackageData = findNearestPackageData(basedir, packageCache);
  32182. selfPkg = selfPackageData?.data.exports && selfPackageData.data.name === pkgId ? selfPackageData : null;
  32183. }
  32184. const pkg = selfPkg || resolvePackageData(pkgId, basedir, preserveSymlinks, packageCache);
  32185. if (!pkg) {
  32186. if (!options.disableOptionalPeerDepHandling && basedir !== root && !isModuleBuiltin(id) && !id.includes("\0") && bareImportRE.test(id)) {
  32187. const mainPkg = findNearestMainPackageData(basedir, packageCache)?.data;
  32188. if (mainPkg) {
  32189. const pkgName = getNpmPackageName(id);
  32190. if (pkgName != null && mainPkg.peerDependencies?.[pkgName] && mainPkg.peerDependenciesMeta?.[pkgName]?.optional) return { id: `${optionalPeerDepId}:${id}:${mainPkg.name}` };
  32191. }
  32192. }
  32193. return;
  32194. }
  32195. let resolved = (deepMatch ? resolveDeepImport : resolvePackageEntry)(deepMatch ? "." + id.slice(pkgId.length) : id, pkg, options, externalize);
  32196. if (!resolved) return;
  32197. const processResult = (resolved) => {
  32198. if (!externalize) return resolved;
  32199. if (!canExternalizeFile(resolved.id)) return resolved;
  32200. let resolvedId = id;
  32201. if (deepMatch && !pkg.data.exports && path.extname(id) !== path.extname(resolved.id)) {
  32202. const index = resolved.id.indexOf(id);
  32203. if (index > -1) {
  32204. resolvedId = resolved.id.slice(index);
  32205. debug$1?.(`[processResult] ${import_picocolors.default.cyan(id)} -> ${import_picocolors.default.dim(resolvedId)}`);
  32206. }
  32207. }
  32208. return {
  32209. ...resolved,
  32210. id: resolvedId,
  32211. external: true
  32212. };
  32213. };
  32214. if (!options.idOnly && (!options.scan && isBuild || externalize)) return processResult({
  32215. id: resolved,
  32216. moduleSideEffects: pkg.hasSideEffects(resolved),
  32217. packageJsonPath: findNearestPackagePath(resolved, options.legacyInconsistentCjsInterop, options.packageCache, isBuild)
  32218. });
  32219. if (!isInNodeModules(resolved) || !depsOptimizer || options.scan) return { id: resolved };
  32220. const isJsType = isOptimizable(resolved, depsOptimizer.options);
  32221. const exclude = depsOptimizer.options.exclude;
  32222. if (depsOptimizer.options.noDiscovery || !isJsType || importer && isInNodeModules(importer) || exclude?.includes(pkgId) || exclude?.includes(id) || SPECIAL_QUERY_RE.test(resolved)) {
  32223. const versionHash = depsOptimizer.metadata.browserHash;
  32224. if (versionHash && isJsType) resolved = injectQuery(resolved, `v=${versionHash}`);
  32225. } else {
  32226. const optimizedInfo = depsOptimizer.registerMissingImport(id, resolved);
  32227. resolved = depsOptimizer.getOptimizedDepId(optimizedInfo);
  32228. }
  32229. return { id: resolved };
  32230. }
  32231. async function tryOptimizedResolve(depsOptimizer, id, importer, preserveSymlinks, packageCache) {
  32232. await depsOptimizer.scanProcessing;
  32233. const metadata = depsOptimizer.metadata;
  32234. const depInfo = optimizedDepInfoFromId(metadata, id);
  32235. if (depInfo) return depsOptimizer.getOptimizedDepId(depInfo);
  32236. if (!importer) return;
  32237. let idPkgDir;
  32238. const nestedIdMatch = `> ${id}`;
  32239. for (const optimizedData of metadata.depInfoList) {
  32240. if (!optimizedData.src) continue;
  32241. if (!optimizedData.id.endsWith(nestedIdMatch)) continue;
  32242. if (idPkgDir == null) {
  32243. const pkgName = getNpmPackageName(id);
  32244. if (!pkgName) break;
  32245. idPkgDir = resolvePackageData(pkgName, importer, preserveSymlinks, packageCache)?.dir;
  32246. if (idPkgDir == null) break;
  32247. idPkgDir = normalizePath(idPkgDir);
  32248. }
  32249. if (optimizedData.src.startsWith(withTrailingSlash(idPkgDir))) return depsOptimizer.getOptimizedDepId(optimizedData);
  32250. }
  32251. }
  32252. function resolvePackageEntry(id, { dir, data, setResolvedCache, getResolvedCache }, options, externalize) {
  32253. const { file: idWithoutPostfix, postfix } = splitFileAndPostfix(id);
  32254. const cached = getResolvedCache(".", options);
  32255. if (cached) return cached + postfix;
  32256. try {
  32257. let entryPoint;
  32258. if (data.exports) entryPoint = resolveExportsOrImports(data, ".", options, "exports", externalize);
  32259. if (!entryPoint) {
  32260. for (const field of options.mainFields) if (field === "browser") {
  32261. entryPoint = tryResolveBrowserEntry(dir, data, options);
  32262. if (entryPoint) break;
  32263. } else if (typeof data[field] === "string") {
  32264. entryPoint = data[field];
  32265. break;
  32266. }
  32267. }
  32268. entryPoint ||= data.main;
  32269. const entryPoints = entryPoint ? [entryPoint] : [
  32270. "index.js",
  32271. "index.json",
  32272. "index.node"
  32273. ];
  32274. for (let entry of entryPoints) {
  32275. let skipPackageJson = false;
  32276. if (options.mainFields[0] === "sass" && !options.extensions.includes(path.extname(entry))) {
  32277. entry = "";
  32278. skipPackageJson = true;
  32279. } else {
  32280. const { browser: browserField } = data;
  32281. if (options.mainFields.includes("browser") && isObject$1(browserField)) entry = mapWithBrowserField(entry, browserField) || entry;
  32282. }
  32283. const resolvedEntryPoint = tryFsResolve(path.join(dir, entry), options, true, skipPackageJson);
  32284. if (resolvedEntryPoint) {
  32285. debug$1?.(`[package entry] ${import_picocolors.default.cyan(idWithoutPostfix)} -> ${import_picocolors.default.dim(resolvedEntryPoint)}${postfix !== "" ? ` (postfix: ${postfix})` : ""}`);
  32286. setResolvedCache(".", resolvedEntryPoint, options);
  32287. return resolvedEntryPoint + postfix;
  32288. }
  32289. }
  32290. } catch (e) {
  32291. packageEntryFailure(id, e.message);
  32292. }
  32293. packageEntryFailure(id);
  32294. }
  32295. function packageEntryFailure(id, details) {
  32296. const err = /* @__PURE__ */ new Error(`Failed to resolve entry for package "${id}". The package may have incorrect main/module/exports specified in its package.json` + (details ? ": " + details : "."));
  32297. err.code = ERR_RESOLVE_PACKAGE_ENTRY_FAIL;
  32298. throw err;
  32299. }
  32300. function getConditions(conditions, isProduction, isRequire) {
  32301. const resolvedConditions = conditions.map((condition) => {
  32302. if (condition === DEV_PROD_CONDITION) return isProduction ? "production" : "development";
  32303. return condition;
  32304. });
  32305. if (isRequire) resolvedConditions.push("require");
  32306. else resolvedConditions.push("import");
  32307. return resolvedConditions;
  32308. }
  32309. function resolveExportsOrImports(pkg, key, options, type, externalize) {
  32310. const conditions = getConditions(externalize ? options.externalConditions : options.conditions, options.isProduction, options.isRequire);
  32311. const result = (type === "imports" ? f : o)(pkg, key, {
  32312. conditions,
  32313. unsafe: true
  32314. });
  32315. return result ? result[0] : void 0;
  32316. }
  32317. function resolveDeepImport(id, { setResolvedCache, getResolvedCache, dir, data }, options, externalize) {
  32318. const cache = getResolvedCache(id, options);
  32319. if (cache) return cache;
  32320. let relativeId = id;
  32321. const { exports: exportsField, browser: browserField } = data;
  32322. if (exportsField) {
  32323. if (isObject$1(exportsField) && !Array.isArray(exportsField)) {
  32324. const { file, postfix } = splitFileAndPostfix(relativeId);
  32325. const exportsId = resolveExportsOrImports(data, file, options, "exports", externalize);
  32326. if (exportsId !== void 0) relativeId = exportsId + postfix;
  32327. else relativeId = void 0;
  32328. } else relativeId = void 0;
  32329. if (!relativeId) throw new Error(`Package subpath '${relativeId}' is not defined by "exports" in ${path.join(dir, "package.json")}.`);
  32330. } else if (options.mainFields.includes("browser") && isObject$1(browserField)) {
  32331. const { file, postfix } = splitFileAndPostfix(relativeId);
  32332. const mapped = mapWithBrowserField(file, browserField);
  32333. if (mapped) relativeId = mapped + postfix;
  32334. else if (mapped === false) {
  32335. setResolvedCache(id, browserExternalId, options);
  32336. return browserExternalId;
  32337. }
  32338. }
  32339. if (relativeId) {
  32340. const resolved = tryFsResolve(path.join(dir, relativeId), options, !exportsField);
  32341. if (resolved) {
  32342. debug$1?.(`[node/deep-import] ${import_picocolors.default.cyan(id)} -> ${import_picocolors.default.dim(resolved)}`);
  32343. setResolvedCache(id, resolved, options);
  32344. return resolved;
  32345. }
  32346. }
  32347. }
  32348. function tryResolveBrowserEntry(dir, data, options) {
  32349. const browserEntry = typeof data.browser === "string" ? data.browser : isObject$1(data.browser) && data.browser["."];
  32350. if (browserEntry) if (!options.isRequire && options.mainFields.includes("module") && typeof data.module === "string" && data.module !== browserEntry) {
  32351. const resolvedBrowserEntry = tryFsResolve(path.join(dir, browserEntry), options);
  32352. if (resolvedBrowserEntry) if (hasESMSyntax(fs.readFileSync(resolvedBrowserEntry, "utf-8"))) return browserEntry;
  32353. else return data.module;
  32354. } else return browserEntry;
  32355. }
  32356. /**
  32357. * given a relative path in pkg dir,
  32358. * return a relative path in pkg dir,
  32359. * mapped with the "map" object
  32360. *
  32361. * - Returning `undefined` means there is no browser mapping for this id
  32362. * - Returning `false` means this id is explicitly externalized for browser
  32363. */
  32364. function mapWithBrowserField(relativePathInPkgDir, map) {
  32365. const normalizedPath = path.posix.normalize(relativePathInPkgDir);
  32366. for (const key in map) {
  32367. const normalizedKey = path.posix.normalize(key);
  32368. if (normalizedPath === normalizedKey || equalWithoutSuffix(normalizedPath, normalizedKey, ".js") || equalWithoutSuffix(normalizedPath, normalizedKey, "/index.js")) return map[key];
  32369. }
  32370. }
  32371. function equalWithoutSuffix(path, key, suffix) {
  32372. return key.endsWith(suffix) && key.slice(0, -suffix.length) === path;
  32373. }
  32374. function tryResolveRealFile(file, preserveSymlinks) {
  32375. if (tryStatSync(file)?.isFile()) return getRealPath(file, preserveSymlinks);
  32376. }
  32377. function tryResolveRealFileWithExtensions(filePath, extensions, preserveSymlinks) {
  32378. for (const ext of extensions) {
  32379. const res = tryResolveRealFile(filePath + ext, preserveSymlinks);
  32380. if (res) return res;
  32381. }
  32382. }
  32383. function tryResolveRealFileOrType(file, preserveSymlinks) {
  32384. const fileStat = tryStatSync(file);
  32385. if (fileStat?.isFile()) return {
  32386. path: getRealPath(file, preserveSymlinks),
  32387. type: "file"
  32388. };
  32389. if (fileStat?.isDirectory()) return { type: "directory" };
  32390. }
  32391. function getRealPath(resolved, preserveSymlinks) {
  32392. if (!preserveSymlinks) resolved = safeRealpathSync(resolved);
  32393. return normalizePath(resolved);
  32394. }
  32395. function isDirectory(path) {
  32396. return tryStatSync(path)?.isDirectory() ?? false;
  32397. }
  32398. function findNearestPackagePath(file, legacyInconsistentCjsInterop, packageCache, isBuild) {
  32399. if (!isBuild || legacyInconsistentCjsInterop) return;
  32400. const pkgData = findNearestPackageData(file, packageCache);
  32401. return pkgData ? path.join(pkgData.dir, "package.json") : null;
  32402. }
  32403. //#endregion
  32404. //#region src/node/nodeResolve.ts
  32405. /**
  32406. * Resolve like Node.js using Vite's resolution algorithm with preconfigured options.
  32407. */
  32408. function nodeResolveWithVite(id, importer, options) {
  32409. return tryNodeResolve(id, importer, {
  32410. root: options.root,
  32411. isBuild: true,
  32412. isProduction: true,
  32413. preferRelative: false,
  32414. tryIndex: true,
  32415. mainFields: [],
  32416. conditions: ["node", ...isModuleSyncConditionEnabled ? ["module-sync"] : []],
  32417. externalConditions: [],
  32418. external: [],
  32419. noExternal: [],
  32420. dedupe: [],
  32421. extensions: DEFAULT_EXTENSIONS,
  32422. preserveSymlinks: false,
  32423. tsconfigPaths: false,
  32424. packageCache: void 0,
  32425. isRequire: options.isRequire,
  32426. builtins: nodeLikeBuiltins,
  32427. disableOptionalPeerDepHandling: true
  32428. })?.id;
  32429. }
  32430. //#endregion
  32431. //#region src/node/plugins/terser.ts
  32432. let terserPath;
  32433. function loadTerserPath(root) {
  32434. if (terserPath) return terserPath;
  32435. const resolved = nodeResolveWithVite("terser", void 0, { root }) ?? nodeResolveWithVite("terser", _dirname, { root });
  32436. if (resolved) return terserPath = resolved;
  32437. throw new Error("terser not found. Since Vite v3, terser has become an optional dependency. You need to install it.");
  32438. }
  32439. function terserPlugin(config) {
  32440. const { maxWorkers, ...terserOptions } = config.build.terserOptions;
  32441. const makeWorker = () => new WorkerWithFallback(() => async (terserPath, code, options) => {
  32442. const terser = await import(terserPath);
  32443. try {
  32444. return await terser.minify(code, options);
  32445. } catch (e) {
  32446. throw {
  32447. stack: e.stack,
  32448. ...e
  32449. };
  32450. }
  32451. }, {
  32452. shouldUseFake(_terserPath, _code, options) {
  32453. return !!(typeof options.mangle === "object" && (options.mangle.nth_identifier?.get || typeof options.mangle.properties === "object" && options.mangle.properties.nth_identifier?.get) || typeof options.format?.comments === "function" || typeof options.output?.comments === "function" || options.nameCache);
  32454. },
  32455. max: maxWorkers
  32456. });
  32457. let worker;
  32458. return {
  32459. name: "vite:terser",
  32460. applyToEnvironment(environment) {
  32461. return !!environment.config.build.minify;
  32462. },
  32463. async renderChunk(code, chunk, outputOptions) {
  32464. if (config.build.minify !== "terser" && !this.environment.config.isOutputOptionsForLegacyChunks?.(outputOptions)) return null;
  32465. worker ||= makeWorker();
  32466. const terserPath = pathToFileURL(loadTerserPath(config.root)).href;
  32467. try {
  32468. const res = await worker.run(terserPath, code, {
  32469. safari10: true,
  32470. ...terserOptions,
  32471. format: {
  32472. ...terserOptions.format,
  32473. preserve_annotations: config.build.lib && outputOptions.format === "es" ? true : terserOptions.format?.preserve_annotations
  32474. },
  32475. sourceMap: !!outputOptions.sourcemap,
  32476. module: outputOptions.format.startsWith("es"),
  32477. toplevel: outputOptions.format === "cjs"
  32478. });
  32479. return {
  32480. code: res.code,
  32481. map: res.map
  32482. };
  32483. } catch (e) {
  32484. if (e.line !== void 0 && e.col !== void 0) e.loc = {
  32485. file: chunk.fileName,
  32486. line: e.line,
  32487. column: e.col
  32488. };
  32489. if (e.pos !== void 0) e.frame = generateCodeFrame(code, e.pos);
  32490. throw e;
  32491. }
  32492. },
  32493. closeBundle() {
  32494. worker?.stop();
  32495. }
  32496. };
  32497. }
  32498. //#endregion
  32499. //#region src/node/ssr/ssrManifestPlugin.ts
  32500. function ssrManifestPlugin() {
  32501. const getSsrManifest = perEnvironmentState(() => {
  32502. return {};
  32503. });
  32504. return {
  32505. name: "vite:ssr-manifest",
  32506. applyToEnvironment(environment) {
  32507. return !!environment.config.build.ssrManifest;
  32508. },
  32509. generateBundle(_options, bundle) {
  32510. const config = this.environment.config;
  32511. const ssrManifest = getSsrManifest(this);
  32512. const { base } = config;
  32513. for (const file in bundle) {
  32514. const chunk = bundle[file];
  32515. if (chunk.type === "chunk") {
  32516. for (const id in chunk.modules) {
  32517. const normalizedId = normalizePath(relative(config.root, id));
  32518. const mappedChunks = ssrManifest[normalizedId] ?? (ssrManifest[normalizedId] = []);
  32519. if (!chunk.isEntry) {
  32520. mappedChunks.push(joinUrlSegments(base, chunk.fileName));
  32521. chunk.viteMetadata.importedCss.forEach((file) => {
  32522. mappedChunks.push(joinUrlSegments(base, file));
  32523. });
  32524. }
  32525. chunk.viteMetadata.importedAssets.forEach((file) => {
  32526. mappedChunks.push(joinUrlSegments(base, file));
  32527. });
  32528. }
  32529. if (chunk.code.includes(preloadMethod)) {
  32530. const code = chunk.code;
  32531. let imports = [];
  32532. try {
  32533. imports = parse$2(code)[0].filter((i) => i.n && i.d > -1);
  32534. } catch (_e) {
  32535. const e = _e;
  32536. const loc = numberToPos(code, e.idx);
  32537. this.error({
  32538. name: e.name,
  32539. message: e.message,
  32540. stack: e.stack,
  32541. cause: e.cause,
  32542. pos: e.idx,
  32543. loc: {
  32544. ...loc,
  32545. file: chunk.fileName
  32546. },
  32547. frame: generateCodeFrame(code, loc)
  32548. });
  32549. }
  32550. if (imports.length) for (let index = 0; index < imports.length; index++) {
  32551. const { s: start, e: end, n: name } = imports[index];
  32552. const url = code.slice(start, end);
  32553. const deps = [];
  32554. const ownerFilename = chunk.fileName;
  32555. const analyzed = /* @__PURE__ */ new Set();
  32556. const addDeps = (filename) => {
  32557. if (filename === ownerFilename) return;
  32558. if (analyzed.has(filename)) return;
  32559. analyzed.add(filename);
  32560. const chunk = bundle[filename];
  32561. if (chunk) {
  32562. chunk.viteMetadata.importedCss.forEach((file) => {
  32563. deps.push(joinUrlSegments(base, file));
  32564. });
  32565. chunk.imports.forEach(addDeps);
  32566. }
  32567. };
  32568. addDeps(normalizePath(join(dirname(chunk.fileName), url.slice(1, -1))));
  32569. ssrManifest[basename(name)] = deps;
  32570. }
  32571. }
  32572. }
  32573. }
  32574. this.emitFile({
  32575. fileName: typeof config.build.ssrManifest === "string" ? config.build.ssrManifest : ".vite/ssr-manifest.json",
  32576. type: "asset",
  32577. source: JSON.stringify(sortObjectKeys(ssrManifest), void 0, 2)
  32578. });
  32579. }
  32580. };
  32581. }
  32582. //#endregion
  32583. //#region src/node/plugins/license.ts
  32584. const licenseConfigDefaults = Object.freeze({ fileName: ".vite/license.md" });
  32585. const licenseFiles = [
  32586. /^license/i,
  32587. /^licence/i,
  32588. /^copying/i
  32589. ];
  32590. function licensePlugin() {
  32591. return {
  32592. name: "vite:license",
  32593. async generateBundle(_, bundle) {
  32594. const licenseOption = this.environment.config.build.license;
  32595. if (licenseOption === false) return;
  32596. const packageCache = /* @__PURE__ */ new Map();
  32597. const licenses = {};
  32598. for (const file in bundle) {
  32599. const chunk = bundle[file];
  32600. if (chunk.type === "asset") continue;
  32601. for (const moduleId of chunk.moduleIds) {
  32602. if (moduleId.startsWith("\0") || !isInNodeModules(moduleId)) continue;
  32603. const pkgData = findNearestMainPackageData(path.dirname(moduleId), packageCache);
  32604. if (!pkgData) continue;
  32605. const { name, version = "0.0.0", license } = pkgData.data;
  32606. const key = `${name}@${version}`;
  32607. if (licenses[key]) continue;
  32608. const entry = {
  32609. name,
  32610. version
  32611. };
  32612. if (license) entry.identifier = license.trim();
  32613. const licenseFile = findLicenseFile(pkgData.dir);
  32614. if (licenseFile) entry.text = fs.readFileSync(licenseFile, "utf-8").trim();
  32615. licenses[key] = entry;
  32616. }
  32617. }
  32618. const licenseEntries = Object.values(sortObjectKeys(licenses));
  32619. const licenseOutputFileName = typeof licenseOption === "object" ? licenseOption.fileName : licenseConfigDefaults.fileName;
  32620. if (licenseOutputFileName.endsWith(".json")) {
  32621. this.emitFile({
  32622. fileName: licenseOutputFileName,
  32623. type: "asset",
  32624. source: JSON.stringify(licenseEntries, null, 2)
  32625. });
  32626. return;
  32627. }
  32628. const markdown = licenseEntryToMarkdown(licenseEntries);
  32629. this.emitFile({
  32630. fileName: licenseOutputFileName,
  32631. type: "asset",
  32632. source: markdown
  32633. });
  32634. }
  32635. };
  32636. }
  32637. function licenseEntryToMarkdown(licenses) {
  32638. if (licenses.length === 0) return `\
  32639. # Licenses
  32640. The app does not bundle any dependencies with licenses.
  32641. `;
  32642. let text = `\
  32643. # Licenses
  32644. The app bundles dependencies which contain the following licenses:
  32645. `;
  32646. for (const license of licenses) {
  32647. const nameAndVersionText = `${license.name} - ${license.version}`;
  32648. const identifierText = license.identifier ? ` (${license.identifier})` : "";
  32649. text += `\n## ${nameAndVersionText}${identifierText}\n`;
  32650. if (license.text) text += `\n${license.text}\n`;
  32651. }
  32652. return text;
  32653. }
  32654. function findLicenseFile(pkgDir) {
  32655. const matchedFile = fs.readdirSync(pkgDir).find((file) => licenseFiles.some((re) => re.test(file)));
  32656. if (matchedFile) return path.join(pkgDir, matchedFile);
  32657. }
  32658. //#endregion
  32659. //#region src/node/plugins/prepareOutDir.ts
  32660. function prepareOutDirPlugin() {
  32661. const rendered = /* @__PURE__ */ new Set();
  32662. return {
  32663. name: "vite:prepare-out-dir",
  32664. options() {
  32665. rendered.delete(this.environment);
  32666. },
  32667. renderStart: {
  32668. order: "pre",
  32669. handler() {
  32670. if (rendered.has(this.environment)) return;
  32671. rendered.add(this.environment);
  32672. const { config } = this.environment;
  32673. if (config.build.write) {
  32674. const { root, build: options } = config;
  32675. const resolvedOutDirs = getResolvedOutDirs(root, options.outDir, options.rollupOptions.output);
  32676. prepareOutDir(resolvedOutDirs, resolveEmptyOutDir(options.emptyOutDir, root, resolvedOutDirs, this.environment.logger), this.environment);
  32677. }
  32678. }
  32679. }
  32680. };
  32681. }
  32682. function prepareOutDir(outDirs, emptyOutDir, environment) {
  32683. const { publicDir } = environment.config;
  32684. const outDirsArray = [...outDirs];
  32685. for (const outDir of outDirs) {
  32686. if (emptyOutDir !== false && fs.existsSync(outDir)) emptyDir(outDir, [...outDirsArray.map((dir) => {
  32687. const relative = path.relative(outDir, dir);
  32688. if (relative && !relative.startsWith("..") && !path.isAbsolute(relative)) return relative;
  32689. return "";
  32690. }).filter(Boolean), ".git"]);
  32691. if (environment.config.build.copyPublicDir && publicDir && fs.existsSync(publicDir)) {
  32692. if (!areSeparateFolders(outDir, publicDir)) environment.logger.warn(import_picocolors.default.yellow(`\n${import_picocolors.default.bold(`(!)`)} The public directory feature may not work correctly. outDir ${import_picocolors.default.white(import_picocolors.default.dim(outDir))} and publicDir ${import_picocolors.default.white(import_picocolors.default.dim(publicDir))} are not separate folders.\n`));
  32693. copyDir(publicDir, outDir);
  32694. }
  32695. }
  32696. }
  32697. function areSeparateFolders(a, b) {
  32698. const na = normalizePath(a);
  32699. const nb = normalizePath(b);
  32700. return na !== nb && !na.startsWith(withTrailingSlash(nb)) && !nb.startsWith(withTrailingSlash(na));
  32701. }
  32702. //#endregion
  32703. //#region src/node/build.ts
  32704. const _buildEnvironmentOptionsDefaults = Object.freeze({
  32705. target: "baseline-widely-available",
  32706. polyfillModulePreload: true,
  32707. modulePreload: true,
  32708. outDir: "dist",
  32709. assetsDir: "assets",
  32710. assetsInlineLimit: DEFAULT_ASSETS_INLINE_LIMIT,
  32711. sourcemap: false,
  32712. terserOptions: {},
  32713. rolldownOptions: {},
  32714. commonjsOptions: {
  32715. include: [/node_modules/],
  32716. extensions: [".js", ".cjs"]
  32717. },
  32718. dynamicImportVarsOptions: { exclude: [/node_modules/] },
  32719. write: true,
  32720. emptyOutDir: null,
  32721. copyPublicDir: true,
  32722. license: false,
  32723. manifest: false,
  32724. lib: false,
  32725. ssrManifest: false,
  32726. ssrEmitAssets: false,
  32727. reportCompressedSize: true,
  32728. chunkSizeWarningLimit: 500,
  32729. watch: null
  32730. });
  32731. const buildEnvironmentOptionsDefaults = _buildEnvironmentOptionsDefaults;
  32732. function resolveBuildEnvironmentOptions(raw, logger, consumer, isBundledDev, isSsrTargetWebworkerEnvironment) {
  32733. const deprecatedPolyfillModulePreload = raw.polyfillModulePreload;
  32734. const { polyfillModulePreload, ...rest } = raw;
  32735. raw = rest;
  32736. if (deprecatedPolyfillModulePreload !== void 0) logger.warn("polyfillModulePreload is deprecated. Use modulePreload.polyfill instead.");
  32737. if (deprecatedPolyfillModulePreload === false && raw.modulePreload === void 0) raw.modulePreload = { polyfill: false };
  32738. const merged = mergeWithDefaults({
  32739. ..._buildEnvironmentOptionsDefaults,
  32740. cssCodeSplit: !raw.lib,
  32741. minify: consumer === "server" || isBundledDev ? false : "oxc",
  32742. rollupOptions: {},
  32743. rolldownOptions: void 0,
  32744. ssr: consumer === "server",
  32745. emitAssets: consumer === "client",
  32746. createEnvironment: (name, config) => new BuildEnvironment(name, config)
  32747. }, raw);
  32748. setupRollupOptionCompat(merged, "build");
  32749. merged.rolldownOptions = {
  32750. platform: consumer === "client" || isSsrTargetWebworkerEnvironment ? "browser" : "node",
  32751. ...merged.rolldownOptions
  32752. };
  32753. if (merged.target === "baseline-widely-available") merged.target = ESBUILD_BASELINE_WIDELY_AVAILABLE_TARGET;
  32754. if (Array.isArray(merged.target)) merged.target = unique(merged.target);
  32755. if (merged.minify === "false") merged.minify = false;
  32756. else if (merged.minify === true) merged.minify = "oxc";
  32757. const defaultModulePreload = { polyfill: true };
  32758. return {
  32759. ...merged,
  32760. cssTarget: merged.cssTarget ?? merged.target,
  32761. cssMinify: merged.cssMinify ?? (consumer === "server" ? "lightningcss" : !!merged.minify),
  32762. modulePreload: merged.modulePreload === false ? false : merged.modulePreload === true ? defaultModulePreload : {
  32763. ...defaultModulePreload,
  32764. ...merged.modulePreload
  32765. }
  32766. };
  32767. }
  32768. async function resolveBuildPlugins(config) {
  32769. const isBuild = config.command === "build";
  32770. return {
  32771. pre: [
  32772. ...isBuild && !config.isWorker ? [prepareOutDirPlugin()] : [],
  32773. perEnvironmentPlugin("vite:rollup-options-plugins", async (environment) => (await asyncFlatten(arraify(environment.config.build.rollupOptions.plugins))).filter(Boolean)),
  32774. ...config.isWorker ? [webWorkerPostPlugin(config)] : []
  32775. ],
  32776. post: [
  32777. ...isBuild ? buildImportAnalysisPlugin(config) : [],
  32778. ...config.build.minify === "esbuild" ? [buildEsbuildPlugin()] : [],
  32779. ...isBuild ? [terserPlugin(config)] : [],
  32780. ...isBuild && !config.isWorker ? [
  32781. licensePlugin(),
  32782. manifestPlugin(),
  32783. ssrManifestPlugin(),
  32784. buildReporterPlugin(config)
  32785. ] : [],
  32786. viteLoadFallbackPlugin()
  32787. ]
  32788. };
  32789. }
  32790. /**
  32791. * Bundles a single environment for production.
  32792. * Returns a Promise containing the build result.
  32793. */
  32794. async function build(inlineConfig = {}) {
  32795. const builder = await createBuilder(inlineConfig, true);
  32796. const environment = Object.values(builder.environments)[0];
  32797. if (!environment) throw new Error("No environment found");
  32798. return builder.build(environment);
  32799. }
  32800. function resolveConfigToBuild(inlineConfig = {}, patchConfig, patchPlugins) {
  32801. return resolveConfig(inlineConfig, "build", "production", "production", false, patchConfig, patchPlugins);
  32802. }
  32803. function resolveRolldownOptions(environment, chunkMetadataMap) {
  32804. const { root, packageCache, build: options } = environment.config;
  32805. const libOptions = options.lib;
  32806. const { logger } = environment;
  32807. const ssr = environment.config.consumer === "server";
  32808. const resolve = (p) => path.resolve(root, p);
  32809. const input = libOptions ? options.rollupOptions.input || (typeof libOptions.entry === "string" ? resolve(libOptions.entry) : Array.isArray(libOptions.entry) ? libOptions.entry.map(resolve) : Object.fromEntries(Object.entries(libOptions.entry).map(([alias, file]) => [alias, resolve(file)]))) : typeof options.ssr === "string" ? resolve(options.ssr) : options.rollupOptions.input || resolve("index.html");
  32810. if (ssr && typeof input === "string" && input.endsWith(".html")) throw new Error("rollupOptions.input should not be an html file when building for SSR. Please specify a dedicated SSR entry.");
  32811. if (options.cssCodeSplit === false) {
  32812. if ((typeof input === "string" ? [input] : Array.isArray(input) ? input : Object.values(input)).some((input) => input.endsWith(".css"))) throw new Error(`When "build.cssCodeSplit: false" is set, "rollupOptions.input" should not include CSS files.`);
  32813. }
  32814. const outDir = resolve(options.outDir);
  32815. const plugins = environment.plugins.map((p) => injectEnvironmentToHooks(environment, chunkMetadataMap, p));
  32816. const rollupOptions = {
  32817. preserveEntrySignatures: ssr ? "allow-extension" : libOptions ? "strict" : false,
  32818. ...options.rollupOptions,
  32819. output: options.rollupOptions.output,
  32820. input,
  32821. plugins,
  32822. external: options.rollupOptions.external,
  32823. onLog(level, log) {
  32824. onRollupLog(level, log, environment);
  32825. },
  32826. transform: {
  32827. target: options.target === false ? void 0 : options.target,
  32828. ...options.rollupOptions.transform,
  32829. define: {
  32830. ...options.rollupOptions.transform?.define,
  32831. "process.env.NODE_ENV": "process.env.NODE_ENV"
  32832. }
  32833. },
  32834. moduleTypes: {
  32835. ...options.rollupOptions.moduleTypes,
  32836. ".css": "js"
  32837. },
  32838. experimental: {
  32839. ...options.rollupOptions.experimental,
  32840. viteMode: true
  32841. }
  32842. };
  32843. const isSsrTargetWebworkerEnvironment = environment.name === "ssr" && environment.getTopLevelConfig().ssr?.target === "webworker";
  32844. if (isSsrTargetWebworkerEnvironment) plugins.push(esmExternalRequirePlugin());
  32845. const buildOutputOptions = (output = {}) => {
  32846. if (output.output) logger.warn("You've set \"rollupOptions.output.output\" in your config. This is deprecated and will override all Vite.js default output options. Please use \"rollupOptions.output\" instead.");
  32847. if (output.file) throw new Error("Vite does not support \"rollupOptions.output.file\". Please use \"rollupOptions.output.dir\" and \"rollupOptions.output.entryFileNames\" instead.");
  32848. if (output.sourcemap) logger.warnOnce(import_picocolors.default.yellow("Vite does not support \"rollupOptions.output.sourcemap\". Please use \"build.sourcemap\" instead."));
  32849. const format = output.format || "es";
  32850. const jsExt = ssr && !isSsrTargetWebworkerEnvironment || libOptions ? resolveOutputJsExtension(format, findNearestPackageData(root, packageCache)?.data.type) : "js";
  32851. return {
  32852. dir: outDir,
  32853. format,
  32854. exports: "auto",
  32855. sourcemap: options.sourcemap,
  32856. name: libOptions ? libOptions.name : void 0,
  32857. generatedCode: { preset: "es2015" },
  32858. entryFileNames: ssr ? `[name].${jsExt}` : libOptions ? ({ name }) => resolveLibFilename(libOptions, format, name, root, jsExt, packageCache) : path.posix.join(options.assetsDir, `[name]-[hash].${jsExt}`),
  32859. chunkFileNames: libOptions ? `[name]-[hash].${jsExt}` : path.posix.join(options.assetsDir, `[name]-[hash].${jsExt}`),
  32860. assetFileNames: libOptions ? `[name].[ext]` : path.posix.join(options.assetsDir, `[name]-[hash].[ext]`),
  32861. codeSplitting: output.codeSplitting ?? (output.format === "umd" || output.format === "iife" || isSsrTargetWebworkerEnvironment && (typeof input === "string" || Object.keys(input).length === 1) ? false : void 0),
  32862. comments: typeof output.comments === "boolean" ? output.comments : {
  32863. annotation: !options.minify || libOptions && (format === "es" || format === "esm"),
  32864. jsdoc: !options.minify,
  32865. legal: !options.minify,
  32866. ...output.comments
  32867. },
  32868. minify: options.minify === "oxc" ? libOptions && (format === "es" || format === "esm") ? {
  32869. compress: true,
  32870. mangle: true,
  32871. codegen: false
  32872. } : true : options.minify === false ? "dce-only" : false,
  32873. topLevelVar: true,
  32874. ...output
  32875. };
  32876. };
  32877. const outputs = resolveBuildOutputs(options.rollupOptions.output, libOptions, logger);
  32878. if (Array.isArray(outputs)) rollupOptions.output = outputs.map(buildOutputOptions);
  32879. else rollupOptions.output = buildOutputOptions(outputs);
  32880. return rollupOptions;
  32881. }
  32882. /**
  32883. * Build an App environment, or a App library (if libraryOptions is provided)
  32884. **/
  32885. async function buildEnvironment(environment) {
  32886. const { logger, config } = environment;
  32887. const { root, build: options } = config;
  32888. logger.info(import_picocolors.default.cyan(`vite v${VERSION} ${import_picocolors.default.green(`building ${environment.name} environment for ${environment.config.mode}...`)}`));
  32889. let bundle;
  32890. let startTime;
  32891. try {
  32892. const chunkMetadataMap = new ChunkMetadataMap();
  32893. const rollupOptions = resolveRolldownOptions(environment, chunkMetadataMap);
  32894. if (options.watch) {
  32895. logger.info(import_picocolors.default.cyan(`\nwatching for file changes...`));
  32896. const resolvedOutDirs = getResolvedOutDirs(root, options.outDir, options.rollupOptions.output);
  32897. const emptyOutDir = resolveEmptyOutDir(options.emptyOutDir, root, resolvedOutDirs, logger);
  32898. const resolvedChokidarOptions = resolveChokidarOptions({
  32899. ...(rollupOptions.watch || {}).chokidar,
  32900. ...options.watch.chokidar
  32901. }, resolvedOutDirs, emptyOutDir, environment.config.cacheDir);
  32902. const { watch } = await import("rolldown");
  32903. const watcher = watch({
  32904. ...rollupOptions,
  32905. watch: {
  32906. ...rollupOptions.watch,
  32907. ...options.watch,
  32908. watcher: convertToWatcherOptions(resolvedChokidarOptions)
  32909. }
  32910. });
  32911. watcher.on("event", (event) => {
  32912. if (event.code === "BUNDLE_START") {
  32913. logger.info(import_picocolors.default.cyan(`\nbuild started...`));
  32914. chunkMetadataMap.clearResetChunks();
  32915. } else if (event.code === "BUNDLE_END") {
  32916. event.result.close();
  32917. logger.info(import_picocolors.default.cyan(`built in ${event.duration}ms.`));
  32918. } else if (event.code === "ERROR") {
  32919. const e = event.error;
  32920. enhanceRollupError(e);
  32921. clearLine();
  32922. logger.error(e.message, { error: e });
  32923. }
  32924. });
  32925. return watcher;
  32926. }
  32927. const { rolldown } = await import("rolldown");
  32928. startTime = Date.now();
  32929. bundle = await rolldown(rollupOptions);
  32930. const res = [];
  32931. for (const output of arraify(rollupOptions.output)) res.push(await bundle[options.write ? "write" : "generate"](output));
  32932. for (const output of res) for (const chunk of output.output) injectChunkMetadata(chunkMetadataMap, chunk);
  32933. logger.info(`${import_picocolors.default.green(`✓ built in ${displayTime(Date.now() - startTime)}`)}`);
  32934. return Array.isArray(rollupOptions.output) ? res : res[0];
  32935. } catch (e) {
  32936. enhanceRollupError(e);
  32937. clearLine();
  32938. if (startTime) {
  32939. logger.error(`${import_picocolors.default.red("✗")} Build failed in ${displayTime(Date.now() - startTime)}`);
  32940. startTime = void 0;
  32941. }
  32942. throw e;
  32943. } finally {
  32944. if (bundle) await bundle.close();
  32945. }
  32946. }
  32947. function enhanceRollupError(e) {
  32948. const stackOnly = extractStack(e);
  32949. let msg = import_picocolors.default.red((e.plugin ? `[${e.plugin}] ` : "") + e.message);
  32950. if (e.loc && e.loc.file && e.loc.file !== e.id) msg += `\nfile: ${import_picocolors.default.cyan(`${e.loc.file}:${e.loc.line}:${e.loc.column}` + (e.id ? ` (${e.id})` : ""))}`;
  32951. else if (e.id) msg += `\nfile: ${import_picocolors.default.cyan(e.id + (e.loc ? `:${e.loc.line}:${e.loc.column}` : ""))}`;
  32952. if (e.frame) msg += `\n` + import_picocolors.default.yellow(normalizeCodeFrame(e.frame));
  32953. e.message = msg;
  32954. if (stackOnly !== void 0) e.stack = `${e.message}\n${stackOnly}`;
  32955. }
  32956. /**
  32957. * The stack string usually contains a copy of the message at the start of the stack.
  32958. * If the stack starts with the message, we remove it and just return the stack trace
  32959. * portion. Otherwise the original stack trace is used.
  32960. */
  32961. function extractStack(e) {
  32962. const { stack, name = "Error", message } = e;
  32963. if (!stack) return stack;
  32964. const expectedPrefix = `${name}: ${message}\n`;
  32965. if (stack.startsWith(expectedPrefix)) return stack.slice(expectedPrefix.length);
  32966. return stack;
  32967. }
  32968. /**
  32969. * Esbuild code frames have newlines at the start and end of the frame, rollup doesn't
  32970. * This function normalizes the frame to match the esbuild format which has more pleasing padding
  32971. */
  32972. function normalizeCodeFrame(frame) {
  32973. return `\n${frame.replace(/^\n|\n$/g, "")}\n`;
  32974. }
  32975. function resolveOutputJsExtension(format, type = "commonjs") {
  32976. if (type === "module") return format === "cjs" || format === "umd" ? "cjs" : "js";
  32977. else return format === "es" ? "mjs" : "js";
  32978. }
  32979. function resolveLibFilename(libOptions, format, entryName, root, extension, packageCache) {
  32980. if (typeof libOptions.fileName === "function") return libOptions.fileName(format, entryName);
  32981. const packageJson = findNearestMainPackageData(root, packageCache)?.data;
  32982. const name = libOptions.fileName || (packageJson && typeof libOptions.entry === "string" ? getPkgName(packageJson.name) : entryName);
  32983. if (!name) throw new Error("Name in package.json is required if option \"build.lib.fileName\" is not provided.");
  32984. extension ??= resolveOutputJsExtension(format, packageJson?.type);
  32985. if (format === "cjs" || format === "es") return `${name}.${extension}`;
  32986. return `${name}.${format}.${extension}`;
  32987. }
  32988. function resolveBuildOutputs(outputs, libOptions, logger) {
  32989. if (libOptions) {
  32990. const libHasMultipleEntries = typeof libOptions.entry !== "string" && Object.values(libOptions.entry).length > 1;
  32991. const libFormats = libOptions.formats || (libHasMultipleEntries ? ["es", "cjs"] : ["es", "umd"]);
  32992. if (!Array.isArray(outputs)) {
  32993. if (libFormats.includes("umd") || libFormats.includes("iife")) {
  32994. if (libHasMultipleEntries) throw new Error("Multiple entry points are not supported when output formats include \"umd\" or \"iife\".");
  32995. if (!libOptions.name) throw new Error("Option \"build.lib.name\" is required when output formats include \"umd\" or \"iife\".");
  32996. }
  32997. return libFormats.map((format) => ({
  32998. ...outputs,
  32999. format
  33000. }));
  33001. }
  33002. if (libOptions.formats) logger.warn(import_picocolors.default.yellow("\"build.lib.formats\" will be ignored because \"build.rollupOptions.output\" is already an array format."));
  33003. outputs.forEach((output) => {
  33004. if ((output.format === "umd" || output.format === "iife") && !output.name) throw new Error("Entries in \"build.rollupOptions.output\" must specify \"name\" when the format is \"umd\" or \"iife\".");
  33005. });
  33006. }
  33007. return outputs;
  33008. }
  33009. const warningIgnoreList = [`CIRCULAR_DEPENDENCY`, `THIS_IS_UNDEFINED`];
  33010. const dynamicImportWarningIgnoreList = [`Unsupported expression`, `statically analyzed`];
  33011. function clearLine() {
  33012. if (process.stdout.isTTY && !process.env.CI) {
  33013. process.stdout.clearLine(0);
  33014. process.stdout.cursorTo(0);
  33015. }
  33016. }
  33017. function onRollupLog(level, log, environment) {
  33018. const debugLogger = createDebugger("vite:build");
  33019. const viteLog = (logLeveling, rawLogging) => {
  33020. const logging = typeof rawLogging === "object" ? rawLogging : { message: rawLogging };
  33021. if (logging.code === "UNRESOLVED_IMPORT") {
  33022. const id = logging.id;
  33023. const exporter = logging.exporter;
  33024. if (!id || !id.endsWith("?commonjs-external")) throw new Error(`[vite]: Rolldown failed to resolve import "${exporter}" from "${id}".\nThis is most likely unintended because it can break your application at runtime.\nIf you do want to externalize this module explicitly add it to\n\`build.rollupOptions.external\``);
  33025. }
  33026. if (logLeveling === "warn") {
  33027. if (logging.plugin === "rollup-plugin-dynamic-import-variables" && dynamicImportWarningIgnoreList.some((msg) => logging.message.includes(msg))) return;
  33028. if (warningIgnoreList.includes(logging.code)) return;
  33029. }
  33030. let message = logging.message;
  33031. if (logging.plugin) message = `[plugin ${logging.plugin}] ${message}`;
  33032. switch (logLeveling) {
  33033. case "info":
  33034. environment.logger.info(message);
  33035. return;
  33036. case "warn":
  33037. environment.logger.warn(import_picocolors.default.yellow(message));
  33038. return;
  33039. case "error":
  33040. environment.logger.error(import_picocolors.default.red(message));
  33041. return;
  33042. case "debug":
  33043. debugLogger?.(message);
  33044. return;
  33045. default:
  33046. environment.logger.info(message);
  33047. return;
  33048. }
  33049. };
  33050. clearLine();
  33051. const userOnLog = environment.config.build.rollupOptions?.onLog;
  33052. const userOnWarn = environment.config.build.rollupOptions?.onwarn;
  33053. if (userOnLog) if (userOnWarn) userOnLog(level, log, normalizeUserOnWarn(userOnWarn, viteLog));
  33054. else userOnLog(level, log, viteLog);
  33055. else if (userOnWarn) normalizeUserOnWarn(userOnWarn, viteLog)(level, log);
  33056. else viteLog(level, log);
  33057. }
  33058. function normalizeUserOnWarn(userOnWarn, defaultHandler) {
  33059. return (logLevel, logging) => {
  33060. if (logLevel === "warn") userOnWarn(normalizeLog(logging), (log) => defaultHandler("warn", typeof log === "function" ? log() : log));
  33061. else defaultHandler(logLevel, logging);
  33062. };
  33063. }
  33064. const normalizeLog = (log) => typeof log === "string" ? { message: log } : log;
  33065. function resolveUserExternal(user, id, parentId, isResolved) {
  33066. if (typeof user === "function") return user(id, parentId, isResolved);
  33067. else if (Array.isArray(user)) return user.some((test) => isExternal(id, test));
  33068. else return isExternal(id, user);
  33069. }
  33070. function isExternal(id, test) {
  33071. if (typeof test === "string") return id === test;
  33072. else return test.test(id);
  33073. }
  33074. var ChunkMetadataMap = class {
  33075. _inner = /* @__PURE__ */ new Map();
  33076. _resetChunks = /* @__PURE__ */ new Set();
  33077. _getKey(chunk) {
  33078. return "preliminaryFileName" in chunk ? chunk.preliminaryFileName : chunk.fileName;
  33079. }
  33080. _getDefaultValue(chunk) {
  33081. return chunk.type === "chunk" ? {
  33082. importedAssets: /* @__PURE__ */ new Set(),
  33083. importedCss: /* @__PURE__ */ new Set(),
  33084. __modules: chunk.modules
  33085. } : {
  33086. importedAssets: /* @__PURE__ */ new Set(),
  33087. importedCss: /* @__PURE__ */ new Set()
  33088. };
  33089. }
  33090. get(chunk) {
  33091. const key = this._getKey(chunk);
  33092. if (!this._inner.has(key)) this._inner.set(key, this._getDefaultValue(chunk));
  33093. return this._inner.get(key);
  33094. }
  33095. reset(chunk) {
  33096. const key = this._getKey(chunk);
  33097. if (this._resetChunks.has(key)) return;
  33098. this._resetChunks.add(key);
  33099. this._inner.set(key, this._getDefaultValue(chunk));
  33100. }
  33101. clearResetChunks() {
  33102. this._resetChunks.clear();
  33103. }
  33104. };
  33105. function injectEnvironmentToHooks(environment, chunkMetadataMap, plugin) {
  33106. const { resolveId, load, transform } = plugin;
  33107. const clone = Object.assign(Object.create(Object.getPrototypeOf(plugin)), plugin);
  33108. for (const hook of Object.keys(clone)) switch (hook) {
  33109. case "resolveId":
  33110. clone[hook] = wrapEnvironmentResolveId(environment, resolveId, plugin.name);
  33111. break;
  33112. case "load":
  33113. clone[hook] = wrapEnvironmentLoad(environment, load, plugin.name);
  33114. break;
  33115. case "transform":
  33116. clone[hook] = wrapEnvironmentTransform(environment, transform, plugin.name);
  33117. break;
  33118. default:
  33119. if (ROLLUP_HOOKS.includes(hook)) clone[hook] = wrapEnvironmentHook(environment, chunkMetadataMap, plugin, hook);
  33120. break;
  33121. }
  33122. return clone;
  33123. }
  33124. const wrappedHookMap = /* @__PURE__ */ new WeakMap();
  33125. function wrapHookObject(hook, handler) {
  33126. const newHook = {
  33127. ...hook,
  33128. handler
  33129. };
  33130. if (!wrappedHookMap.has(hook)) {
  33131. wrappedHookMap.set(hook, []);
  33132. Object.defineProperty(hook, "filter", {
  33133. get() {
  33134. return wrappedHookMap.get(hook)[0].filter;
  33135. },
  33136. set(v) {
  33137. for (const h of wrappedHookMap.get(hook)) h.filter = v;
  33138. }
  33139. });
  33140. Object.defineProperty(hook, "order", {
  33141. get() {
  33142. return wrappedHookMap.get(hook)[0].order;
  33143. },
  33144. set(v) {
  33145. for (const h of wrappedHookMap.get(hook)) h.order = v;
  33146. }
  33147. });
  33148. }
  33149. wrappedHookMap.get(hook).push(newHook);
  33150. return newHook;
  33151. }
  33152. function wrapEnvironmentResolveId(environment, hook, pluginName) {
  33153. if (!hook) return;
  33154. const fn = getHookHandler(hook);
  33155. const handler = function(id, importer, options) {
  33156. return fn.call(injectEnvironmentInContext(this, environment), id, importer, injectSsrFlag(options, environment, pluginName));
  33157. };
  33158. if ("handler" in hook) return wrapHookObject(hook, handler);
  33159. else return handler;
  33160. }
  33161. function wrapEnvironmentLoad(environment, hook, pluginName) {
  33162. if (!hook) return;
  33163. const fn = getHookHandler(hook);
  33164. const handler = function(id, ...args) {
  33165. return fn.call(injectEnvironmentInContext(this, environment), id, injectSsrFlag(args[0], environment, pluginName));
  33166. };
  33167. if ("handler" in hook) return wrapHookObject(hook, handler);
  33168. else return handler;
  33169. }
  33170. function wrapEnvironmentTransform(environment, hook, pluginName) {
  33171. if (!hook) return;
  33172. const fn = getHookHandler(hook);
  33173. const handler = function(code, importer, ...args) {
  33174. return fn.call(injectEnvironmentInContext(this, environment), code, importer, injectSsrFlag(args[0], environment, pluginName));
  33175. };
  33176. if ("handler" in hook) return wrapHookObject(hook, handler);
  33177. else return handler;
  33178. }
  33179. function wrapEnvironmentHook(environment, chunkMetadataMap, plugin, hookName) {
  33180. const hook = plugin[hookName];
  33181. if (!hook) return;
  33182. const fn = getHookHandler(hook);
  33183. if (typeof fn !== "function") return hook;
  33184. const handler = function(...args) {
  33185. if (hookName === "renderChunk") injectChunkMetadata(chunkMetadataMap, args[1], true);
  33186. if (hookName === "augmentChunkHash") injectChunkMetadata(chunkMetadataMap, args[0]);
  33187. if (hookName === "generateBundle" || hookName === "writeBundle") {
  33188. const bundle = args[1];
  33189. for (const chunk of Object.values(bundle)) injectChunkMetadata(chunkMetadataMap, chunk);
  33190. }
  33191. return fn.call(injectEnvironmentInContext(this, environment), ...args);
  33192. };
  33193. if ("handler" in hook) return wrapHookObject(hook, handler);
  33194. else return handler;
  33195. }
  33196. function injectChunkMetadata(chunkMetadataMap, chunk, resetChunkMetadata = false) {
  33197. if (resetChunkMetadata) chunkMetadataMap.reset(chunk);
  33198. Object.defineProperty(chunk, "viteMetadata", {
  33199. value: chunkMetadataMap.get(chunk),
  33200. enumerable: true
  33201. });
  33202. if (chunk.type === "chunk") Object.defineProperty(chunk, "modules", {
  33203. get() {
  33204. return chunk.viteMetadata.__modules;
  33205. },
  33206. enumerable: true
  33207. });
  33208. }
  33209. function injectEnvironmentInContext(context, environment) {
  33210. context.meta.viteVersion ??= VERSION;
  33211. context.environment ??= environment;
  33212. return context;
  33213. }
  33214. function injectSsrFlag(options, environment, pluginName) {
  33215. let ssr = environment.config.consumer === "server";
  33216. const newOptions = {
  33217. ...options ?? {},
  33218. ssr
  33219. };
  33220. if (isFutureDeprecationEnabled(environment?.getTopLevelConfig(), "removePluginHookSsrArgument")) Object.defineProperty(newOptions, "ssr", {
  33221. get() {
  33222. warnFutureDeprecation(environment?.getTopLevelConfig(), "removePluginHookSsrArgument", `Used in plugin "${pluginName}".`);
  33223. return ssr;
  33224. },
  33225. set(v) {
  33226. ssr = v;
  33227. }
  33228. });
  33229. return newOptions;
  33230. }
  33231. const needsEscapeRegEx = /[\n\r'\\\u2028\u2029]/;
  33232. const quoteNewlineRegEx = /([\n\r'\u2028\u2029])/g;
  33233. const backSlashRegEx = /\\/g;
  33234. function escapeId(id) {
  33235. if (!needsEscapeRegEx.test(id)) return id;
  33236. return id.replace(backSlashRegEx, "\\\\").replace(quoteNewlineRegEx, "\\$1");
  33237. }
  33238. const getResolveUrl = (path, URL = "URL") => `new ${URL}(${path}).href`;
  33239. const getRelativeUrlFromDocument = (relativePath, umd = false) => getResolveUrl(`'${escapeId(partialEncodeURIPath(relativePath))}', ${umd ? `typeof document === 'undefined' ? location.href : ` : ""}document.currentScript && document.currentScript.tagName.toUpperCase() === 'SCRIPT' && document.currentScript.src || document.baseURI`);
  33240. const getFileUrlFromFullPath = (path) => `require('u' + 'rl').pathToFileURL(${path}).href`;
  33241. const getFileUrlFromRelativePath = (path) => getFileUrlFromFullPath(`__dirname + '/${escapeId(path)}'`);
  33242. const customRelativeUrlMechanisms = {
  33243. cjs: (relativePath) => `(typeof document === 'undefined' ? ${getFileUrlFromRelativePath(relativePath)} : ${getRelativeUrlFromDocument(relativePath)})`,
  33244. es: (relativePath) => getResolveUrl(`'${escapeId(partialEncodeURIPath(relativePath))}', import.meta.url`),
  33245. iife: (relativePath) => getRelativeUrlFromDocument(relativePath),
  33246. umd: (relativePath) => `(typeof document === 'undefined' && typeof location === 'undefined' ? ${getFileUrlFromRelativePath(relativePath)} : ${getRelativeUrlFromDocument(relativePath, true)})`,
  33247. "worker-iife": (relativePath) => getResolveUrl(`'${escapeId(partialEncodeURIPath(relativePath))}', self.location.href`)
  33248. };
  33249. function toOutputFilePathInJS(environment, filename, type, hostId, hostType, toRelative) {
  33250. const { experimental, base, decodedBase } = environment.config;
  33251. const ssr = environment.config.consumer === "server";
  33252. const { renderBuiltUrl } = experimental;
  33253. let relative = base === "" || base === "./";
  33254. if (renderBuiltUrl) {
  33255. const result = renderBuiltUrl(filename, {
  33256. hostId,
  33257. hostType,
  33258. type,
  33259. ssr
  33260. });
  33261. if (typeof result === "object") {
  33262. if (result.runtime) return { runtime: result.runtime };
  33263. if (typeof result.relative === "boolean") relative = result.relative;
  33264. } else if (result) return result;
  33265. }
  33266. if (relative && !ssr) return toRelative(filename, hostId);
  33267. return joinUrlSegments(decodedBase, filename);
  33268. }
  33269. function createToImportMetaURLBasedRelativeRuntime(format, isWorker) {
  33270. const toRelativePath = customRelativeUrlMechanisms[isWorker && format === "iife" ? "worker-iife" : format];
  33271. return (filename, importer) => ({ runtime: toRelativePath(path.posix.relative(path.dirname(importer), filename)) });
  33272. }
  33273. function toOutputFilePathWithoutRuntime(filename, type, hostId, hostType, config, toRelative) {
  33274. const { renderBuiltUrl } = config.experimental;
  33275. let relative = config.base === "" || config.base === "./";
  33276. if (renderBuiltUrl) {
  33277. const result = renderBuiltUrl(filename, {
  33278. hostId,
  33279. hostType,
  33280. type,
  33281. ssr: !!config.build.ssr
  33282. });
  33283. if (typeof result === "object") {
  33284. if (result.runtime) throw new Error(`{ runtime: "${result.runtime}" } is not supported for assets in ${hostType} files: ${filename}`);
  33285. if (typeof result.relative === "boolean") relative = result.relative;
  33286. } else if (result) return result;
  33287. }
  33288. if (relative && !config.build.ssr) return toRelative(filename, hostId);
  33289. else return joinUrlSegments(config.decodedBase, filename);
  33290. }
  33291. const toOutputFilePathInCss = toOutputFilePathWithoutRuntime;
  33292. const toOutputFilePathInHtml = toOutputFilePathWithoutRuntime;
  33293. var BuildEnvironment = class extends BaseEnvironment {
  33294. mode = "build";
  33295. isBuilt = false;
  33296. constructor(name, config, setup) {
  33297. let options = config.environments[name];
  33298. if (!options) throw new Error(`Environment "${name}" is not defined in the config.`);
  33299. if (setup?.options) options = mergeConfig(options, setup.options);
  33300. super(name, config, options);
  33301. }
  33302. async init() {
  33303. if (this._initiated) return;
  33304. this._initiated = true;
  33305. }
  33306. };
  33307. const _builderOptionsDefaults = Object.freeze({
  33308. sharedConfigBuild: false,
  33309. sharedPlugins: false
  33310. });
  33311. const builderOptionsDefaults = _builderOptionsDefaults;
  33312. function resolveBuilderOptions(options) {
  33313. if (!options) return;
  33314. return mergeWithDefaults({
  33315. ..._builderOptionsDefaults,
  33316. buildApp: async () => {}
  33317. }, options);
  33318. }
  33319. /**
  33320. * Creates a ViteBuilder to orchestrate building multiple environments.
  33321. * @experimental
  33322. */
  33323. async function createBuilder(inlineConfig = {}, useLegacyBuilder = false) {
  33324. const patchConfig = (resolved) => {
  33325. if (!(useLegacyBuilder ?? !resolved.builder)) return;
  33326. resolved.build = { ...resolved.environments[resolved.build.ssr ? "ssr" : "client"].build };
  33327. };
  33328. const config = await resolveConfigToBuild(inlineConfig, patchConfig);
  33329. useLegacyBuilder ??= !config.builder;
  33330. const configBuilder = config.builder ?? resolveBuilderOptions({});
  33331. const environments = {};
  33332. const builder = {
  33333. environments,
  33334. config,
  33335. async buildApp() {
  33336. const pluginContext = new BasicMinimalPluginContext({
  33337. ...basePluginContextMeta,
  33338. watchMode: false
  33339. }, config.logger);
  33340. let configBuilderBuildAppCalled = false;
  33341. for (const p of config.getSortedPlugins("buildApp")) {
  33342. const hook = p.buildApp;
  33343. if (!configBuilderBuildAppCalled && typeof hook === "object" && hook.order === "post") {
  33344. configBuilderBuildAppCalled = true;
  33345. await configBuilder.buildApp(builder);
  33346. }
  33347. await getHookHandler(hook).call(pluginContext, builder);
  33348. }
  33349. if (!configBuilderBuildAppCalled) await configBuilder.buildApp(builder);
  33350. if (Object.values(builder.environments).every((environment) => !environment.isBuilt)) for (const environment of Object.values(builder.environments)) await builder.build(environment);
  33351. },
  33352. async build(environment) {
  33353. const output = await buildEnvironment(environment);
  33354. environment.isBuilt = true;
  33355. return output;
  33356. },
  33357. async runDevTools() {
  33358. const devtoolsConfig = config.devtools;
  33359. if (devtoolsConfig.enabled) try {
  33360. const { start } = await import(`@vitejs/devtools/cli-commands`);
  33361. await start(devtoolsConfig.config);
  33362. } catch (e) {
  33363. config.logger.error(import_picocolors.default.red(`Failed to run Vite DevTools: ${e.message || e.stack}`), { error: e });
  33364. }
  33365. }
  33366. };
  33367. async function setupEnvironment(name, config) {
  33368. const environment = await config.build.createEnvironment(name, config);
  33369. await environment.init();
  33370. environments[name] = environment;
  33371. }
  33372. if (useLegacyBuilder) await setupEnvironment(config.build.ssr ? "ssr" : "client", config);
  33373. else {
  33374. const environmentConfigs = [];
  33375. for (const environmentName of Object.keys(config.environments)) {
  33376. let environmentConfig = config;
  33377. if (!configBuilder.sharedConfigBuild) {
  33378. const patchConfig = (resolved) => {
  33379. resolved.build = { ...resolved.environments[environmentName].build };
  33380. };
  33381. const patchPlugins = (resolvedPlugins) => {
  33382. let j = 0;
  33383. for (let i = 0; i < resolvedPlugins.length; i++) {
  33384. const environmentPlugin = resolvedPlugins[i];
  33385. if (configBuilder.sharedPlugins || environmentPlugin.sharedDuringBuild) {
  33386. for (let k = j; k < config.plugins.length; k++) if (environmentPlugin.name === config.plugins[k].name) {
  33387. resolvedPlugins[i] = config.plugins[k];
  33388. j = k + 1;
  33389. break;
  33390. }
  33391. }
  33392. }
  33393. };
  33394. environmentConfig = await resolveConfigToBuild(inlineConfig, patchConfig, patchPlugins);
  33395. }
  33396. environmentConfigs.push([environmentName, environmentConfig]);
  33397. }
  33398. await Promise.all(environmentConfigs.map(async ([environmentName, environmentConfig]) => await setupEnvironment(environmentName, environmentConfig)));
  33399. }
  33400. return builder;
  33401. }
  33402. //#endregion
  33403. //#region src/node/server/environments/runnableEnvironment.ts
  33404. function createRunnableDevEnvironment(name, config, context = {}) {
  33405. if (context.transport == null) context.transport = createServerHotChannel();
  33406. if (context.hot == null) context.hot = true;
  33407. return new RunnableDevEnvironment(name, config, context);
  33408. }
  33409. function isRunnableDevEnvironment(environment) {
  33410. return environment instanceof RunnableDevEnvironment;
  33411. }
  33412. var RunnableDevEnvironment = class extends DevEnvironment {
  33413. _runner;
  33414. _runnerFactory;
  33415. _runnerOptions;
  33416. constructor(name, config, context) {
  33417. super(name, config, context);
  33418. this._runnerFactory = context.runner;
  33419. this._runnerOptions = context.runnerOptions;
  33420. }
  33421. get runner() {
  33422. if (this._runner) return this._runner;
  33423. this._runner = (this._runnerFactory || createServerModuleRunner)(this, this._runnerOptions);
  33424. return this._runner;
  33425. }
  33426. async close() {
  33427. await super.close();
  33428. if (this._runner) await this._runner.close();
  33429. }
  33430. };
  33431. //#endregion
  33432. //#region ../../node_modules/.pnpm/@polka+compression@1.0.0-next.25/node_modules/@polka/compression/build.mjs
  33433. const NOOP = () => {};
  33434. const MIMES = /text|javascript|\/json|xml/i;
  33435. /**
  33436. * @param {any} chunk
  33437. * @param {BufferEncoding} enc
  33438. * @returns {number}
  33439. */
  33440. function getChunkSize(chunk, enc) {
  33441. return chunk ? Buffer.byteLength(chunk, enc) : 0;
  33442. }
  33443. /**
  33444. * @param {import('./index.d.mts').Options} [options]
  33445. * @returns {import('./index.d.mts').Middleware}
  33446. */
  33447. function build_default({ threshold = 1024, level = -1, brotli = false, gzip = true, mimes = MIMES } = {}) {
  33448. const brotliOpts = typeof brotli === "object" && brotli || {};
  33449. const gzipOpts = typeof gzip === "object" && gzip || {};
  33450. if (!zlib.createBrotliCompress) brotli = false;
  33451. return (req, res, next = NOOP) => {
  33452. const accept = req.headers["accept-encoding"] + "";
  33453. const encoding = (brotli && accept.match(/\bbr\b/) || gzip && accept.match(/\bgzip\b/) || [])[0];
  33454. if (req.method === "HEAD" || !encoding) return next();
  33455. /** @type {zlib.Gzip | zlib.BrotliCompress} */
  33456. let compress;
  33457. /** @type {Array<[string, function]>?} */
  33458. let pendingListeners = [];
  33459. let pendingStatus = 0;
  33460. let started = false;
  33461. let size = 0;
  33462. function start() {
  33463. started = true;
  33464. size = res.getHeader("Content-Length") | 0 || size;
  33465. const compressible = mimes.test(String(res.getHeader("Content-Type") || "text/plain"));
  33466. const cleartext = !res.getHeader("Content-Encoding");
  33467. const listeners = pendingListeners || [];
  33468. if (compressible && cleartext && size >= threshold) {
  33469. res.setHeader("Content-Encoding", encoding);
  33470. res.removeHeader("Content-Length");
  33471. if (encoding === "br") compress = zlib.createBrotliCompress({ params: Object.assign({
  33472. [zlib.constants.BROTLI_PARAM_QUALITY]: level,
  33473. [zlib.constants.BROTLI_PARAM_SIZE_HINT]: size
  33474. }, brotliOpts) });
  33475. else compress = zlib.createGzip(Object.assign({ level }, gzipOpts));
  33476. compress.on("data", (chunk) => write.call(res, chunk) || compress.pause());
  33477. on.call(res, "drain", () => compress.resume());
  33478. compress.on("end", () => end.call(res));
  33479. listeners.forEach((p) => compress.on.apply(compress, p));
  33480. } else {
  33481. pendingListeners = null;
  33482. listeners.forEach((p) => on.apply(res, p));
  33483. }
  33484. writeHead.call(res, pendingStatus || res.statusCode);
  33485. }
  33486. const { end, write, on, writeHead } = res;
  33487. res.writeHead = function(status, reason, headers) {
  33488. if (typeof reason !== "string") [headers, reason] = [reason, headers];
  33489. if (headers) for (let k in headers) res.setHeader(k, headers[k]);
  33490. pendingStatus = status;
  33491. return this;
  33492. };
  33493. res.write = function(chunk, enc) {
  33494. size += getChunkSize(chunk, enc);
  33495. if (!started) start();
  33496. if (!compress) return write.apply(this, arguments);
  33497. return compress.write.apply(compress, arguments);
  33498. };
  33499. res.end = function(chunk, enc) {
  33500. if (arguments.length > 0 && typeof chunk !== "function") size += getChunkSize(chunk, enc);
  33501. if (!started) start();
  33502. if (!compress) return end.apply(this, arguments);
  33503. return compress.end.apply(compress, arguments);
  33504. };
  33505. res.on = function(type, listener) {
  33506. if (!pendingListeners) on.call(this, type, listener);
  33507. else if (compress) compress.on(type, listener);
  33508. else pendingListeners.push([type, listener]);
  33509. return this;
  33510. };
  33511. next();
  33512. };
  33513. }
  33514. //#endregion
  33515. //#region src/node/preview.ts
  33516. function resolvePreviewOptions(preview, server) {
  33517. return {
  33518. port: preview?.port ?? 4173,
  33519. strictPort: preview?.strictPort ?? server.strictPort,
  33520. host: preview?.host ?? server.host,
  33521. allowedHosts: preview?.allowedHosts ?? server.allowedHosts,
  33522. https: preview?.https ?? server.https,
  33523. open: preview?.open ?? server.open,
  33524. proxy: preview?.proxy ?? server.proxy,
  33525. cors: preview?.cors ?? server.cors,
  33526. headers: preview?.headers ?? server.headers
  33527. };
  33528. }
  33529. /**
  33530. * Starts the Vite server in preview mode, to simulate a production deployment
  33531. */
  33532. async function preview(inlineConfig = {}) {
  33533. const config = await resolveConfig(inlineConfig, "serve", "production", "production", true);
  33534. const clientOutDir = config.environments.client.build.outDir;
  33535. const distDir = path.resolve(config.root, clientOutDir);
  33536. if (!fs.existsSync(distDir) && config.plugins.every((plugin) => !plugin.configurePreviewServer) && process.argv[1]?.endsWith(path.normalize("bin/vite.js")) && process.argv[2] === "preview") throw new Error(`The directory "${clientOutDir}" does not exist. Did you build your project?`);
  33537. const httpsOptions = await resolveHttpsConfig(config.preview.https);
  33538. const app = (0, import_connect.default)();
  33539. const httpServer = await resolveHttpServer(app, httpsOptions);
  33540. setClientErrorHandler(httpServer, config.logger);
  33541. const options = config.preview;
  33542. const logger = config.logger;
  33543. const closeHttpServer = createServerCloseFn(httpServer);
  33544. let closeServerPromise;
  33545. const closeServer = async () => {
  33546. teardownSIGTERMListener(closeServerAndExit);
  33547. await closeHttpServer();
  33548. server.resolvedUrls = null;
  33549. };
  33550. const server = {
  33551. config,
  33552. middlewares: app,
  33553. httpServer,
  33554. async close() {
  33555. if (!closeServerPromise) closeServerPromise = closeServer();
  33556. return closeServerPromise;
  33557. },
  33558. resolvedUrls: null,
  33559. printUrls() {
  33560. if (server.resolvedUrls) printServerUrls(server.resolvedUrls, options.host, logger.info);
  33561. else throw new Error("cannot print server URLs before server is listening.");
  33562. },
  33563. bindCLIShortcuts(options) {
  33564. bindCLIShortcuts(server, options);
  33565. }
  33566. };
  33567. const closeServerAndExit = async (_, exitCode) => {
  33568. try {
  33569. await server.close();
  33570. } finally {
  33571. process.exitCode ??= exitCode ? 128 + exitCode : void 0;
  33572. process.exit();
  33573. }
  33574. };
  33575. setupSIGTERMListener(closeServerAndExit);
  33576. const { cors } = config.preview;
  33577. if (cors !== false) app.use((0, import_lib.default)(typeof cors === "boolean" ? {} : cors));
  33578. const { allowedHosts } = config.preview;
  33579. if (allowedHosts !== true && !config.preview.https) app.use(hostValidationMiddleware(allowedHosts, true));
  33580. const configurePreviewServerContext = new BasicMinimalPluginContext({
  33581. ...basePluginContextMeta,
  33582. watchMode: false
  33583. }, config.logger);
  33584. const postHooks = [];
  33585. for (const hook of config.getSortedPluginHooks("configurePreviewServer")) postHooks.push(await hook.call(configurePreviewServerContext, server));
  33586. const { proxy } = config.preview;
  33587. if (proxy) app.use(proxyMiddleware(httpServer, proxy, config));
  33588. app.use(build_default());
  33589. if (config.base !== "/") app.use(baseMiddleware(config.rawBase, false));
  33590. const headers = config.preview.headers;
  33591. const viteAssetMiddleware = (...args) => build_default$1(distDir, {
  33592. etag: true,
  33593. dev: true,
  33594. extensions: [],
  33595. ignores: false,
  33596. setHeaders(res) {
  33597. if (headers) for (const name in headers) res.setHeader(name, headers[name]);
  33598. },
  33599. shouldServe(filePath) {
  33600. return shouldServeFile(filePath, distDir);
  33601. }
  33602. })(...args);
  33603. app.use(viteAssetMiddleware);
  33604. if (config.appType === "spa" || config.appType === "mpa") app.use(htmlFallbackMiddleware(distDir, config.appType === "spa"));
  33605. postHooks.forEach((fn) => fn && fn());
  33606. if (config.appType === "spa" || config.appType === "mpa") {
  33607. const normalizedDistDir = normalizePath(distDir);
  33608. app.use(indexHtmlMiddleware(normalizedDistDir, server));
  33609. app.use(notFoundMiddleware());
  33610. }
  33611. const hostname = await resolveHostname(options.host);
  33612. await httpServerStart(httpServer, {
  33613. port: options.port,
  33614. strictPort: options.strictPort,
  33615. host: hostname.host,
  33616. logger
  33617. });
  33618. server.resolvedUrls = resolveServerUrls(httpServer, config.preview, hostname, httpsOptions, config);
  33619. if (options.open) {
  33620. const url = getServerUrlByHost(server.resolvedUrls, options.host);
  33621. if (url) openBrowser(typeof options.open === "string" ? new URL(options.open, url).href : url, true, logger);
  33622. }
  33623. return server;
  33624. }
  33625. //#endregion
  33626. //#region src/node/ssr/index.ts
  33627. const _ssrConfigDefaults = Object.freeze({
  33628. target: "node",
  33629. optimizeDeps: {}
  33630. });
  33631. const ssrConfigDefaults = _ssrConfigDefaults;
  33632. function resolveSSROptions(ssr, preserveSymlinks) {
  33633. return mergeWithDefaults(mergeWithDefaults(_ssrConfigDefaults, { optimizeDeps: { esbuildOptions: { preserveSymlinks } } }), ssr ?? {});
  33634. }
  33635. //#endregion
  33636. //#region src/node/ssr/runnerImport.ts
  33637. /**
  33638. * Import any file using the default Vite environment.
  33639. * @experimental
  33640. */
  33641. async function runnerImport(moduleId, inlineConfig) {
  33642. const isModuleSyncConditionEnabled = (await import("#module-sync-enabled")).default;
  33643. const environment = createRunnableDevEnvironment("inline", await resolveConfig(mergeConfig(inlineConfig || {}, {
  33644. configFile: false,
  33645. envDir: false,
  33646. cacheDir: process.cwd(),
  33647. environments: { inline: {
  33648. consumer: "server",
  33649. dev: { moduleRunnerTransform: true },
  33650. resolve: {
  33651. external: true,
  33652. mainFields: [],
  33653. conditions: ["node", ...isModuleSyncConditionEnabled ? ["module-sync"] : []]
  33654. }
  33655. } }
  33656. }), "serve"), {
  33657. runnerOptions: { hmr: { logger: false } },
  33658. hot: false
  33659. });
  33660. await environment.init();
  33661. try {
  33662. const module = await environment.runner.import(moduleId);
  33663. return {
  33664. module,
  33665. dependencies: [...environment.runner.evaluatedModules.urlToIdModuleMap.values()].filter((m) => {
  33666. if (!m.meta || "externalize" in m.meta) return false;
  33667. return m.exports !== module;
  33668. }).map((m) => m.file)
  33669. };
  33670. } finally {
  33671. await environment.close();
  33672. }
  33673. }
  33674. //#endregion
  33675. //#region src/node/optimizer/pluginConverter.ts
  33676. function convertEsbuildPluginToRolldownPlugin(esbuildPlugin) {
  33677. const onStartCallbacks = [];
  33678. const onEndCallbacks = [];
  33679. const onDisposeCallbacks = [];
  33680. let resolveIdHandlers;
  33681. let loadHandlers;
  33682. let isSetupDone = false;
  33683. const setup = async (plugins, platform) => {
  33684. const onResolveCallbacks = [];
  33685. const onLoadCallbacks = [];
  33686. const pluginBuild = {
  33687. initialOptions: new Proxy({
  33688. platform,
  33689. plugins: plugins?.flatMap((p) => p && "name" in p ? [{
  33690. name: p.name,
  33691. setup() {}
  33692. }] : []) ?? []
  33693. }, { get(target, p, _receiver) {
  33694. if (p in target) return target[p];
  33695. throw new Error("Not implemented");
  33696. } }),
  33697. resolve() {
  33698. throw new Error("Not implemented");
  33699. },
  33700. onStart(callback) {
  33701. onStartCallbacks.push(callback);
  33702. },
  33703. onEnd(callback) {
  33704. onEndCallbacks.push(callback);
  33705. },
  33706. onResolve(options, callback) {
  33707. onResolveCallbacks.push([options, callback]);
  33708. },
  33709. onLoad(options, callback) {
  33710. onLoadCallbacks.push([options, callback]);
  33711. },
  33712. onDispose(callback) {
  33713. onDisposeCallbacks.push(callback);
  33714. },
  33715. get esbuild() {
  33716. throw new Error("Not implemented");
  33717. },
  33718. set esbuild(_) {
  33719. throw new Error("Not implemented");
  33720. }
  33721. };
  33722. await esbuildPlugin.setup(pluginBuild);
  33723. resolveIdHandlers = onResolveCallbacks.map(([options, callback]) => createResolveIdHandler(options, callback));
  33724. loadHandlers = onLoadCallbacks.map(([options, callback]) => createLoadHandler(options, callback));
  33725. isSetupDone = true;
  33726. };
  33727. const usedNamespaces = /* @__PURE__ */ new Set();
  33728. return {
  33729. name: esbuildPlugin.name,
  33730. async options(inputOptions) {
  33731. await setup(inputOptions.plugins, inputOptions.platform ?? "node");
  33732. },
  33733. async buildStart(inputOptions) {
  33734. if (!isSetupDone) await setup([{ name: "vite:dep-scan" }], inputOptions.platform ?? "node");
  33735. for (const cb of onStartCallbacks) cb();
  33736. },
  33737. generateBundle() {
  33738. const buildResult = new Proxy({}, { get(_target, _prop) {
  33739. throw new Error("Not implemented");
  33740. } });
  33741. for (const cb of onEndCallbacks) cb(buildResult);
  33742. },
  33743. async resolveId(id, importer, opts) {
  33744. for (const handler of resolveIdHandlers) {
  33745. const result = await handler.call(this, id, importer, opts);
  33746. if (result) {
  33747. if (typeof result === "object" && result.namespace) usedNamespaces.add(result.namespace);
  33748. return result;
  33749. }
  33750. }
  33751. if (usedNamespaces.size) {
  33752. const [importerWithoutNamespace, namespaceFromImporter] = idToPathAndNamespace(importer);
  33753. if (usedNamespaces.has(namespaceFromImporter)) return await this.resolve(id, importerWithoutNamespace, opts);
  33754. }
  33755. },
  33756. async load(id) {
  33757. for (const handler of loadHandlers) {
  33758. const result = await handler.call(this, id);
  33759. if (result) return result;
  33760. }
  33761. },
  33762. closeBundle() {
  33763. if (!this.meta.watchMode) for (const cb of onDisposeCallbacks) cb();
  33764. },
  33765. closeWatcher() {
  33766. for (const cb of onDisposeCallbacks) cb();
  33767. }
  33768. };
  33769. }
  33770. function createResolveIdHandler(options, callback) {
  33771. return async function(id, importer, opts) {
  33772. const [importerWithoutNamespace, importerNamespace] = idToPathAndNamespace(importer);
  33773. if (options.namespace !== void 0 && options.namespace !== importerNamespace) return;
  33774. if (options.filter !== void 0 && !options.filter.test(id)) return;
  33775. const result = await callback({
  33776. path: id,
  33777. importer: importerWithoutNamespace ?? "",
  33778. namespace: importerNamespace,
  33779. resolveDir: dirname(importerWithoutNamespace ?? ""),
  33780. kind: importerWithoutNamespace === void 0 ? "entry-point" : opts.kind === "new-url" || opts.kind === "hot-accept" ? "dynamic-import" : opts.kind,
  33781. pluginData: {},
  33782. with: {}
  33783. });
  33784. if (!result) return;
  33785. if (result.errors && result.errors.length > 0) throw new AggregateError(result.errors);
  33786. if (result.warnings && result.warnings.length > 0 || result.watchDirs && result.watchDirs.length > 0 || !result.path) throw new Error("not implemented");
  33787. for (const file of result.watchFiles ?? []) this.addWatchFile(file);
  33788. return {
  33789. id: result.namespace ? `${result.namespace}:${result.path}` : result.path,
  33790. external: result.external,
  33791. moduleSideEffects: result.sideEffects,
  33792. namespace: result.namespace
  33793. };
  33794. };
  33795. }
  33796. function createLoadHandler(options, callback) {
  33797. const textDecoder = new TextDecoder();
  33798. return async function(id) {
  33799. const [idWithoutNamespace, idNamespace] = idToPathAndNamespace(id);
  33800. if (options.namespace !== void 0 && options.namespace !== "file" && options.namespace !== idNamespace) return;
  33801. if (options.filter !== void 0 && !options.filter.test(id)) return;
  33802. const result = await callback.call(this, {
  33803. path: idWithoutNamespace,
  33804. namespace: idNamespace,
  33805. suffix: "",
  33806. pluginData: {},
  33807. with: {}
  33808. });
  33809. if (!result) return;
  33810. if (result.errors && result.errors.length > 0) throw new AggregateError(result.errors);
  33811. if (result.warnings && result.warnings.length > 0 || result.watchDirs && result.watchDirs.length > 0 || result.contents == null) throw new Error("not implemented");
  33812. for (const file of result.watchFiles ?? []) this.addWatchFile(file);
  33813. return {
  33814. code: typeof result.contents === "string" ? result.contents : textDecoder.decode(result.contents),
  33815. moduleType: result.loader
  33816. };
  33817. };
  33818. }
  33819. function idToPathAndNamespace(id) {
  33820. if (id === void 0) return [void 0, "file"];
  33821. const namespaceIndex = id.indexOf(":");
  33822. if (namespaceIndex >= 0) return [id.slice(namespaceIndex + 1), id.slice(0, namespaceIndex)];
  33823. else return [id, "file"];
  33824. }
  33825. //#endregion
  33826. //#region src/node/config.ts
  33827. const debug = createDebugger("vite:config", { depth: 10 });
  33828. const promisifiedRealpath = promisify(fs.realpath);
  33829. const SYMBOL_RESOLVED_CONFIG = Symbol("vite:resolved-config");
  33830. function defineConfig(config) {
  33831. return config;
  33832. }
  33833. function defaultCreateClientDevEnvironment(name, config, context) {
  33834. if (config.experimental.bundledDev) return new FullBundleDevEnvironment(name, config, {
  33835. hot: true,
  33836. transport: context.ws
  33837. });
  33838. return new DevEnvironment(name, config, {
  33839. hot: true,
  33840. transport: context.ws,
  33841. disableFetchModule: true
  33842. });
  33843. }
  33844. function defaultCreateDevEnvironment(name, config) {
  33845. return createRunnableDevEnvironment(name, config);
  33846. }
  33847. async function resolveDevToolsConfig(config, host, logger) {
  33848. const isEnabled = config === true || !!(config && config.enabled);
  33849. const fallbackHostname = (await resolveHostname(host)).host ?? "localhost";
  33850. const fallbackConfig = {
  33851. config: { host: fallbackHostname },
  33852. enabled: false
  33853. };
  33854. if (!isEnabled) return fallbackConfig;
  33855. try {
  33856. const { normalizeDevToolsConfig } = await import("@vitejs/devtools/config");
  33857. return normalizeDevToolsConfig(config, fallbackHostname);
  33858. } catch (e) {
  33859. logger.error(import_picocolors.default.red(`Failed to load Vite DevTools config: ${e.message || e.stack}`), { error: e });
  33860. return fallbackConfig;
  33861. }
  33862. }
  33863. const configDefaults = Object.freeze({
  33864. define: {},
  33865. dev: {
  33866. warmup: [],
  33867. sourcemap: { js: true },
  33868. sourcemapIgnoreList: void 0
  33869. },
  33870. build: buildEnvironmentOptionsDefaults,
  33871. resolve: {
  33872. externalConditions: [...DEFAULT_EXTERNAL_CONDITIONS],
  33873. extensions: DEFAULT_EXTENSIONS,
  33874. dedupe: [],
  33875. noExternal: [],
  33876. external: [],
  33877. preserveSymlinks: false,
  33878. tsconfigPaths: false,
  33879. alias: []
  33880. },
  33881. base: "/",
  33882. publicDir: "public",
  33883. plugins: [],
  33884. html: { cspNonce: void 0 },
  33885. css: cssConfigDefaults,
  33886. json: {
  33887. namedExports: true,
  33888. stringify: "auto"
  33889. },
  33890. assetsInclude: void 0,
  33891. builder: builderOptionsDefaults,
  33892. server: serverConfigDefaults,
  33893. preview: { port: DEFAULT_PREVIEW_PORT },
  33894. experimental: {
  33895. importGlobRestoreExtension: false,
  33896. renderBuiltUrl: void 0,
  33897. hmrPartialAccept: false,
  33898. bundledDev: false
  33899. },
  33900. future: {
  33901. removePluginHookHandleHotUpdate: void 0,
  33902. removePluginHookSsrArgument: void 0,
  33903. removeServerModuleGraph: void 0,
  33904. removeServerHot: void 0,
  33905. removeServerTransformRequest: void 0,
  33906. removeServerWarmupRequest: void 0,
  33907. removeSsrLoadModule: void 0
  33908. },
  33909. legacy: { skipWebSocketTokenCheck: false },
  33910. logLevel: "info",
  33911. customLogger: void 0,
  33912. clearScreen: true,
  33913. envDir: void 0,
  33914. envPrefix: "VITE_",
  33915. worker: {
  33916. format: "iife",
  33917. plugins: () => []
  33918. },
  33919. optimizeDeps: {
  33920. include: [],
  33921. exclude: [],
  33922. needsInterop: [],
  33923. rolldownOptions: {},
  33924. extensions: [],
  33925. disabled: "build",
  33926. holdUntilCrawlEnd: true,
  33927. force: false,
  33928. ignoreOutdatedRequests: false
  33929. },
  33930. ssr: ssrConfigDefaults,
  33931. environments: {},
  33932. appType: "spa"
  33933. });
  33934. function resolveDevEnvironmentOptions(dev, environmentName, consumer, preTransformRequest) {
  33935. const resolved = mergeWithDefaults({
  33936. ...configDefaults.dev,
  33937. sourcemapIgnoreList: isInNodeModules,
  33938. preTransformRequests: preTransformRequest ?? consumer === "client",
  33939. createEnvironment: environmentName === "client" ? defaultCreateClientDevEnvironment : defaultCreateDevEnvironment,
  33940. recoverable: consumer === "client",
  33941. moduleRunnerTransform: consumer === "server"
  33942. }, dev ?? {});
  33943. return {
  33944. ...resolved,
  33945. sourcemapIgnoreList: resolved.sourcemapIgnoreList === false ? () => false : resolved.sourcemapIgnoreList
  33946. };
  33947. }
  33948. function resolveEnvironmentOptions(options, alias, preserveSymlinks, forceOptimizeDeps, logger, environmentName, isBundledDev, isSsrTargetWebworkerSet, preTransformRequests) {
  33949. const consumer = options.consumer ?? (environmentName === "client" ? "client" : "server");
  33950. const isSsrTargetWebworkerEnvironment = isSsrTargetWebworkerSet && environmentName === "ssr";
  33951. if (options.define?.["process.env"]) {
  33952. const processEnvDefine = options.define["process.env"];
  33953. if (typeof processEnvDefine === "object") {
  33954. const pathKey = Object.entries(processEnvDefine).find(([key, value]) => key.toLowerCase() === "path" && !!value)?.[0];
  33955. if (pathKey) logger.warnOnce(import_picocolors.default.yellow(`The \`define\` option contains an object with ${JSON.stringify(pathKey)} for "process.env" key. It looks like you may have passed the entire \`process.env\` object to \`define\`, which can unintentionally expose all environment variables. This poses a security risk and is discouraged.`));
  33956. }
  33957. }
  33958. const resolve = resolveEnvironmentResolveOptions(options.resolve, alias, preserveSymlinks, logger, consumer, isSsrTargetWebworkerEnvironment);
  33959. return {
  33960. define: options.define,
  33961. resolve,
  33962. keepProcessEnv: options.keepProcessEnv ?? (isSsrTargetWebworkerEnvironment ? false : consumer === "server"),
  33963. consumer,
  33964. optimizeDeps: resolveDepOptimizationOptions(options.optimizeDeps, resolve.preserveSymlinks, forceOptimizeDeps, consumer, logger),
  33965. dev: resolveDevEnvironmentOptions(options.dev, environmentName, consumer, preTransformRequests),
  33966. build: resolveBuildEnvironmentOptions(options.build ?? {}, logger, consumer, isBundledDev, isSsrTargetWebworkerEnvironment),
  33967. plugins: void 0,
  33968. optimizeDepsPluginNames: void 0
  33969. };
  33970. }
  33971. function getDefaultEnvironmentOptions(config) {
  33972. return {
  33973. define: config.define,
  33974. resolve: {
  33975. ...config.resolve,
  33976. mainFields: void 0,
  33977. conditions: void 0
  33978. },
  33979. dev: config.dev,
  33980. build: config.build
  33981. };
  33982. }
  33983. /**
  33984. * Check and warn if `path` includes characters that don't work well in Vite,
  33985. * such as `#` and `?` and `*`.
  33986. */
  33987. function checkBadCharactersInPath(name, path, logger) {
  33988. const badChars = [];
  33989. if (path.includes("#")) badChars.push("#");
  33990. if (path.includes("?")) badChars.push("?");
  33991. if (path.includes("*")) badChars.push("*");
  33992. if (badChars.length > 0) {
  33993. const charString = badChars.map((c) => `"${c}"`).join(" and ");
  33994. logger.warn(import_picocolors.default.yellow(`${name} contains the ${charString} ${badChars.length > 1 ? "characters" : "character"} (${import_picocolors.default.cyan(path)}), which may not work when running Vite. Consider renaming the directory / file to remove the characters.`));
  33995. }
  33996. }
  33997. const clientAlias = [{
  33998. find: /^\/?@vite\/env/,
  33999. replacement: path.posix.join(FS_PREFIX, normalizePath(ENV_ENTRY))
  34000. }, {
  34001. find: /^\/?@vite\/client/,
  34002. replacement: path.posix.join(FS_PREFIX, normalizePath(CLIENT_ENTRY))
  34003. }];
  34004. /**
  34005. * alias and preserveSymlinks are not per-environment options, but they are
  34006. * included in the resolved environment options for convenience.
  34007. */
  34008. function resolveEnvironmentResolveOptions(resolve, alias, preserveSymlinks, logger, consumer, isSsrTargetWebworkerEnvironment) {
  34009. const resolvedResolve = mergeWithDefaults({
  34010. ...configDefaults.resolve,
  34011. mainFields: consumer === void 0 || consumer === "client" || isSsrTargetWebworkerEnvironment ? DEFAULT_CLIENT_MAIN_FIELDS : DEFAULT_SERVER_MAIN_FIELDS,
  34012. conditions: consumer === void 0 || consumer === "client" || isSsrTargetWebworkerEnvironment ? DEFAULT_CLIENT_CONDITIONS : DEFAULT_SERVER_CONDITIONS.filter((c) => c !== "browser"),
  34013. builtins: resolve?.builtins ?? (consumer === "server" ? isSsrTargetWebworkerEnvironment && resolve?.noExternal === true ? [] : nodeLikeBuiltins : [])
  34014. }, resolve ?? {});
  34015. resolvedResolve.preserveSymlinks = preserveSymlinks;
  34016. resolvedResolve.alias = alias;
  34017. if (resolve?.browserField === false && resolvedResolve.mainFields.includes("browser")) logger.warn(import_picocolors.default.yellow("`resolve.browserField` is set to false, but the option is removed in favour of the 'browser' string in `resolve.mainFields`. You may want to update `resolve.mainFields` to remove the 'browser' string and preserve the previous browser behaviour."));
  34018. return resolvedResolve;
  34019. }
  34020. function resolveResolveOptions(resolve, logger) {
  34021. const alias = normalizeAlias(mergeAlias(clientAlias, resolve?.alias || configDefaults.resolve.alias));
  34022. const preserveSymlinks = resolve?.preserveSymlinks ?? configDefaults.resolve.preserveSymlinks;
  34023. if (alias.some((a) => a.find === "/")) logger.warn(import_picocolors.default.yellow("`resolve.alias` contains an alias that maps `/`. This is not recommended as it can cause unexpected behavior when resolving paths."));
  34024. if (alias.some((a) => a.customResolver)) logger.warn(import_picocolors.default.yellow("`resolve.alias` contains an alias with `customResolver` option. This is deprecated and will be removed in Vite 9. Please use a custom plugin with a resolveId hook and `enforce: 'pre'` instead."));
  34025. return resolveEnvironmentResolveOptions(resolve, alias, preserveSymlinks, logger, void 0);
  34026. }
  34027. function resolveDepOptimizationOptions(optimizeDeps, preserveSymlinks, forceOptimizeDeps, consumer, logger) {
  34028. if (optimizeDeps?.rolldownOptions && optimizeDeps?.rolldownOptions === optimizeDeps?.rollupOptions) delete optimizeDeps?.rollupOptions;
  34029. const merged = mergeWithDefaults({
  34030. ...configDefaults.optimizeDeps,
  34031. disabled: void 0,
  34032. noDiscovery: consumer !== "client",
  34033. force: forceOptimizeDeps ?? configDefaults.optimizeDeps.force
  34034. }, optimizeDeps ?? {});
  34035. setupRollupOptionCompat(merged, "optimizeDeps");
  34036. const rolldownOptions = merged.rolldownOptions;
  34037. if (merged.esbuildOptions && Object.keys(merged.esbuildOptions).length > 0) {
  34038. logger.warn(import_picocolors.default.yellow("You or a plugin you are using have set `optimizeDeps.esbuildOptions` but this option is now deprecated. Vite now uses Rolldown to optimize the dependencies. Please use `optimizeDeps.rolldownOptions` instead."));
  34039. rolldownOptions.resolve ??= {};
  34040. rolldownOptions.output ??= {};
  34041. rolldownOptions.transform ??= {};
  34042. const setResolveOptions = (key, value) => {
  34043. if (value !== void 0 && rolldownOptions.resolve[key] === void 0) rolldownOptions.resolve[key] = value;
  34044. };
  34045. if (merged.esbuildOptions.minify !== void 0 && rolldownOptions.output.minify === void 0) rolldownOptions.output.minify = merged.esbuildOptions.minify;
  34046. if (merged.esbuildOptions.treeShaking !== void 0 && rolldownOptions.treeshake === void 0) rolldownOptions.treeshake = merged.esbuildOptions.treeShaking;
  34047. if (merged.esbuildOptions.define !== void 0 && rolldownOptions.transform.define === void 0) rolldownOptions.transform.define = merged.esbuildOptions.define;
  34048. if (merged.esbuildOptions.loader !== void 0) {
  34049. const loader = merged.esbuildOptions.loader;
  34050. rolldownOptions.moduleTypes ??= {};
  34051. for (const [key, value] of Object.entries(loader)) if (rolldownOptions.moduleTypes[key] === void 0 && value !== "copy" && value !== "css" && value !== "default" && value !== "file" && value !== "local-css") rolldownOptions.moduleTypes[key] = value;
  34052. }
  34053. if (merged.esbuildOptions.preserveSymlinks !== void 0 && rolldownOptions.resolve.symlinks === void 0) rolldownOptions.resolve.symlinks = !merged.esbuildOptions.preserveSymlinks;
  34054. setResolveOptions("extensions", merged.esbuildOptions.resolveExtensions);
  34055. setResolveOptions("mainFields", merged.esbuildOptions.mainFields);
  34056. setResolveOptions("conditionNames", merged.esbuildOptions.conditions);
  34057. if (merged.esbuildOptions.keepNames !== void 0 && rolldownOptions.output.keepNames === void 0) rolldownOptions.output.keepNames = merged.esbuildOptions.keepNames;
  34058. if (merged.esbuildOptions.platform !== void 0 && rolldownOptions.platform === void 0) rolldownOptions.platform = merged.esbuildOptions.platform;
  34059. }
  34060. merged.esbuildOptions ??= {};
  34061. merged.esbuildOptions.preserveSymlinks ??= preserveSymlinks;
  34062. rolldownOptions.resolve ??= {};
  34063. rolldownOptions.resolve.symlinks ??= !preserveSymlinks;
  34064. rolldownOptions.output ??= {};
  34065. rolldownOptions.output.topLevelVar ??= true;
  34066. return merged;
  34067. }
  34068. async function setOptimizeDepsPluginNames(resolvedConfig) {
  34069. await Promise.all(Object.values(resolvedConfig.environments).map(async (environment) => {
  34070. const flattenedPlugins = await asyncFlatten([environment.optimizeDeps.rolldownOptions?.plugins ?? [], environment.optimizeDeps.rolldownOptions?.output?.plugins ?? []]);
  34071. const pluginNames = [];
  34072. for (const plugin of flattenedPlugins) if (plugin && "name" in plugin) pluginNames.push(plugin.name);
  34073. environment.optimizeDepsPluginNames = pluginNames;
  34074. }));
  34075. }
  34076. function applyDepOptimizationOptionCompat(resolvedConfig) {
  34077. if (resolvedConfig.optimizeDeps.esbuildOptions?.plugins && resolvedConfig.optimizeDeps.esbuildOptions.plugins.length > 0) {
  34078. resolvedConfig.optimizeDeps.rolldownOptions ??= {};
  34079. resolvedConfig.optimizeDeps.rolldownOptions.plugins ||= [];
  34080. resolvedConfig.optimizeDeps.rolldownOptions.plugins.push(...resolvedConfig.optimizeDeps.esbuildOptions.plugins.map((plugin) => convertEsbuildPluginToRolldownPlugin(plugin)));
  34081. }
  34082. }
  34083. function isResolvedConfig(inlineConfig) {
  34084. return SYMBOL_RESOLVED_CONFIG in inlineConfig && inlineConfig[SYMBOL_RESOLVED_CONFIG];
  34085. }
  34086. async function resolveConfig(inlineConfig, command, defaultMode = "development", defaultNodeEnv = "development", isPreview = false, patchConfig = void 0, patchPlugins = void 0) {
  34087. let config = inlineConfig;
  34088. config.build ??= {};
  34089. setupRollupOptionCompat(config.build, "build");
  34090. config.worker ??= {};
  34091. setupRollupOptionCompat(config.worker, "worker");
  34092. config.optimizeDeps ??= {};
  34093. setupRollupOptionCompat(config.optimizeDeps, "optimizeDeps");
  34094. if (config.ssr) {
  34095. config.ssr.optimizeDeps ??= {};
  34096. setupRollupOptionCompat(config.ssr.optimizeDeps, "ssr.optimizeDeps");
  34097. }
  34098. let configFileDependencies = [];
  34099. let mode = inlineConfig.mode || defaultMode;
  34100. const isNodeEnvSet = !!process.env.NODE_ENV;
  34101. const packageCache = /* @__PURE__ */ new Map();
  34102. if (!isNodeEnvSet) process.env.NODE_ENV = defaultNodeEnv;
  34103. const configEnv = {
  34104. mode,
  34105. command,
  34106. isSsrBuild: command === "build" && !!config.build?.ssr,
  34107. isPreview
  34108. };
  34109. let { configFile } = config;
  34110. if (configFile !== false) {
  34111. const loadResult = await loadConfigFromFile(configEnv, configFile, config.root, config.logLevel, config.customLogger, config.configLoader);
  34112. if (loadResult) {
  34113. config = mergeConfig(loadResult.config, config);
  34114. configFile = loadResult.path;
  34115. configFileDependencies = loadResult.dependencies;
  34116. }
  34117. }
  34118. mode = inlineConfig.mode || config.mode || mode;
  34119. configEnv.mode = mode;
  34120. const filterPlugin = (p) => {
  34121. if (!p) return false;
  34122. else if (!p.apply) return true;
  34123. else if (typeof p.apply === "function") return p.apply({
  34124. ...config,
  34125. mode
  34126. }, configEnv);
  34127. else return p.apply === command;
  34128. };
  34129. const [prePlugins, normalPlugins, postPlugins] = sortUserPlugins((await asyncFlatten(config.plugins || [])).filter(filterPlugin));
  34130. const isBuild = command === "build";
  34131. const userPlugins = [
  34132. ...prePlugins,
  34133. ...normalPlugins,
  34134. ...postPlugins
  34135. ];
  34136. config = await runConfigHook(config, userPlugins, configEnv);
  34137. config.environments ??= {};
  34138. if (!config.environments.ssr && (!isBuild || config.ssr || config.build?.ssr)) config.environments = {
  34139. ssr: {},
  34140. ...config.environments
  34141. };
  34142. if (!config.environments.client) config.environments = {
  34143. client: {},
  34144. ...config.environments
  34145. };
  34146. const logger = createLogger(config.logLevel, {
  34147. allowClearScreen: config.clearScreen,
  34148. customLogger: config.customLogger
  34149. });
  34150. const tsconfigPathsPlugin = userPlugins.find((p) => p.name === "vite-tsconfig-paths" || p.name === "vite-plugin-tsconfig-paths");
  34151. if (tsconfigPathsPlugin) logger.warnOnce(import_picocolors.default.yellow(`The plugin ${JSON.stringify(tsconfigPathsPlugin.name)} is detected. Vite now supports tsconfig paths resolution natively via the ${import_picocolors.default.bold("resolve.tsconfigPaths")} option. You can remove the plugin and set ${import_picocolors.default.bold("resolve.tsconfigPaths: true")} in your Vite config instead.`));
  34152. const resolvedRoot = normalizePath(config.root ? path.resolve(config.root) : process.cwd());
  34153. checkBadCharactersInPath("The project root", resolvedRoot, logger);
  34154. const configEnvironmentsClient = config.environments.client;
  34155. configEnvironmentsClient.dev ??= {};
  34156. const deprecatedSsrOptimizeDepsConfig = config.ssr?.optimizeDeps ?? {};
  34157. let configEnvironmentsSsr = config.environments.ssr;
  34158. const warmupOptions = config.server?.warmup;
  34159. if (warmupOptions?.clientFiles) configEnvironmentsClient.dev.warmup = warmupOptions.clientFiles;
  34160. if (warmupOptions?.ssrFiles) {
  34161. configEnvironmentsSsr ??= {};
  34162. configEnvironmentsSsr.dev ??= {};
  34163. configEnvironmentsSsr.dev.warmup = warmupOptions.ssrFiles;
  34164. }
  34165. if (configEnvironmentsSsr) {
  34166. configEnvironmentsSsr.optimizeDeps = mergeConfig(deprecatedSsrOptimizeDepsConfig, configEnvironmentsSsr.optimizeDeps ?? {});
  34167. configEnvironmentsSsr.resolve = mergeConfig({ resolve: {
  34168. conditions: config.ssr?.resolve?.conditions,
  34169. externalConditions: config.ssr?.resolve?.externalConditions,
  34170. mainFields: config.ssr?.resolve?.mainFields,
  34171. external: config.ssr?.external,
  34172. noExternal: config.ssr?.noExternal
  34173. } }, { resolve: configEnvironmentsSsr.resolve ?? {} }).resolve;
  34174. }
  34175. if (config.build?.ssrEmitAssets !== void 0) {
  34176. configEnvironmentsSsr ??= {};
  34177. configEnvironmentsSsr.build ??= {};
  34178. configEnvironmentsSsr.build.emitAssets = config.build.ssrEmitAssets;
  34179. }
  34180. if (!config.environments.client || !config.environments.ssr && !isBuild) throw new Error("Required environments configuration were stripped out in the config hook");
  34181. const defaultEnvironmentOptions = getDefaultEnvironmentOptions(config);
  34182. const defaultClientEnvironmentOptions = {
  34183. ...defaultEnvironmentOptions,
  34184. resolve: config.resolve,
  34185. optimizeDeps: config.optimizeDeps
  34186. };
  34187. const defaultNonClientEnvironmentOptions = {
  34188. ...defaultEnvironmentOptions,
  34189. dev: {
  34190. ...defaultEnvironmentOptions.dev,
  34191. createEnvironment: void 0,
  34192. warmup: void 0
  34193. },
  34194. build: {
  34195. ...defaultEnvironmentOptions.build,
  34196. createEnvironment: void 0
  34197. }
  34198. };
  34199. for (const name of Object.keys(config.environments)) config.environments[name] = mergeConfig(name === "client" ? defaultClientEnvironmentOptions : defaultNonClientEnvironmentOptions, config.environments[name]);
  34200. await runConfigEnvironmentHook(config.environments, userPlugins, logger, configEnv, config.ssr?.target === "webworker");
  34201. const isBundledDev = command === "serve" && !!config.experimental?.bundledDev;
  34202. config.resolve ??= {};
  34203. config.resolve.conditions = config.environments.client.resolve?.conditions;
  34204. config.resolve.mainFields = config.environments.client.resolve?.mainFields;
  34205. const resolvedDefaultResolve = resolveResolveOptions(config.resolve, logger);
  34206. const resolvedEnvironments = {};
  34207. for (const environmentName of Object.keys(config.environments)) resolvedEnvironments[environmentName] = resolveEnvironmentOptions(config.environments[environmentName], resolvedDefaultResolve.alias, resolvedDefaultResolve.preserveSymlinks, inlineConfig.forceOptimizeDeps, logger, environmentName, isBundledDev, config.ssr?.target === "webworker", config.server?.preTransformRequests);
  34208. const backwardCompatibleOptimizeDeps = resolvedEnvironments.client.optimizeDeps;
  34209. const resolvedDevEnvironmentOptions = resolveDevEnvironmentOptions(config.dev, void 0, void 0);
  34210. const resolvedBuildOptions = resolveBuildEnvironmentOptions(config.build ?? {}, logger, void 0, isBundledDev);
  34211. const ssr = resolveSSROptions({
  34212. ...config.ssr,
  34213. external: resolvedEnvironments.ssr?.resolve.external,
  34214. noExternal: resolvedEnvironments.ssr?.resolve.noExternal,
  34215. optimizeDeps: resolvedEnvironments.ssr?.optimizeDeps,
  34216. resolve: {
  34217. ...config.ssr?.resolve,
  34218. conditions: resolvedEnvironments.ssr?.resolve.conditions,
  34219. externalConditions: resolvedEnvironments.ssr?.resolve.externalConditions
  34220. }
  34221. }, resolvedDefaultResolve.preserveSymlinks);
  34222. let envDir = config.envFile === false ? false : config.envDir;
  34223. if (envDir !== false) envDir = config.envDir ? normalizePath(path.resolve(resolvedRoot, config.envDir)) : resolvedRoot;
  34224. const userEnv = loadEnv(mode, envDir, resolveEnvPrefix(config));
  34225. const userNodeEnv = process.env.VITE_USER_NODE_ENV;
  34226. if (!isNodeEnvSet && userNodeEnv) if (userNodeEnv === "development") process.env.NODE_ENV = "development";
  34227. else logger.warn(`NODE_ENV=${userNodeEnv} is not supported in the .env file. Only NODE_ENV=development is supported to create a development build of your project. If you need to set process.env.NODE_ENV, you can set it in the Vite config instead.`);
  34228. const isProduction = process.env.NODE_ENV === "production";
  34229. const resolvedBase = config.base === "" || config.base === "./" ? !isBuild || config.build?.ssr ? "/" : "./" : resolveBaseUrl(config.base, isBuild, logger);
  34230. const pkgDir = findNearestPackageData(resolvedRoot, packageCache)?.dir;
  34231. const cacheDir = normalizePath(config.cacheDir ? path.resolve(resolvedRoot, config.cacheDir) : pkgDir ? path.join(pkgDir, `node_modules/.vite`) : path.join(resolvedRoot, `.vite`));
  34232. const assetsFilter = config.assetsInclude && (!Array.isArray(config.assetsInclude) || config.assetsInclude.length) ? createFilter$1(config.assetsInclude) : () => false;
  34233. const { publicDir } = config;
  34234. const resolvedPublicDir = publicDir !== false && publicDir !== "" ? normalizePath(path.resolve(resolvedRoot, typeof publicDir === "string" ? publicDir : configDefaults.publicDir)) : "";
  34235. const server = await resolveServerOptions(resolvedRoot, config.server, logger);
  34236. const builder = resolveBuilderOptions(config.builder);
  34237. const BASE_URL = resolvedBase;
  34238. const resolvedConfigContext = new BasicMinimalPluginContext({
  34239. ...basePluginContextMeta,
  34240. watchMode: command === "serve" && !isPreview || command === "build" && !!resolvedBuildOptions.watch
  34241. }, logger);
  34242. let resolved;
  34243. let createUserWorkerPlugins = config.worker?.plugins;
  34244. if (Array.isArray(createUserWorkerPlugins)) {
  34245. createUserWorkerPlugins = () => config.worker?.plugins;
  34246. logger.warn(import_picocolors.default.yellow("worker.plugins is now a function that returns an array of plugins. Please update your Vite config accordingly.\n"));
  34247. }
  34248. const createWorkerPlugins = async function(bundleChain) {
  34249. const rawWorkerUserPlugins = (await asyncFlatten(createUserWorkerPlugins?.() || [])).filter(filterPlugin);
  34250. let workerConfig = mergeConfig({}, config);
  34251. const [workerPrePlugins, workerNormalPlugins, workerPostPlugins] = sortUserPlugins(rawWorkerUserPlugins);
  34252. const workerUserPlugins = [
  34253. ...workerPrePlugins,
  34254. ...workerNormalPlugins,
  34255. ...workerPostPlugins
  34256. ];
  34257. workerConfig = await runConfigHook(workerConfig, workerUserPlugins, configEnv);
  34258. const workerResolved = {
  34259. ...workerConfig,
  34260. ...resolved,
  34261. isWorker: true,
  34262. mainConfig: resolved,
  34263. bundleChain
  34264. };
  34265. workerResolved.plugins = await resolvePlugins(workerResolved, workerPrePlugins, workerNormalPlugins, workerPostPlugins);
  34266. await Promise.all(createPluginHookUtils(workerResolved.plugins).getSortedPluginHooks("configResolved").map((hook) => hook.call(resolvedConfigContext, workerResolved)));
  34267. workerResolved.environments = {
  34268. ...workerResolved.environments,
  34269. client: {
  34270. ...workerResolved.environments.client,
  34271. plugins: await resolveEnvironmentPlugins(new PartialEnvironment("client", workerResolved))
  34272. }
  34273. };
  34274. return workerResolved;
  34275. };
  34276. const resolvedWorkerOptions = {
  34277. format: config.worker?.format || "iife",
  34278. plugins: createWorkerPlugins,
  34279. rollupOptions: config.worker?.rollupOptions || {},
  34280. rolldownOptions: config.worker?.rolldownOptions
  34281. };
  34282. setupRollupOptionCompat(resolvedWorkerOptions, "worker");
  34283. const base = withTrailingSlash(resolvedBase);
  34284. const preview = resolvePreviewOptions(config.preview, server);
  34285. const additionalAllowedHosts = getAdditionalAllowedHosts(server, preview);
  34286. if (Array.isArray(server.allowedHosts)) server.allowedHosts.push(...additionalAllowedHosts);
  34287. if (Array.isArray(preview.allowedHosts)) preview.allowedHosts.push(...additionalAllowedHosts);
  34288. let oxc = config.oxc;
  34289. if (config.esbuild) if (config.oxc) logger.warn(import_picocolors.default.yellow(`Both esbuild and oxc options were set. oxc options will be used and esbuild options will be ignored.`) + ` The following esbuild options were set: \`${inspect(config.esbuild)}\``);
  34290. else oxc = convertEsbuildConfigToOxcConfig(config.esbuild, logger);
  34291. else if (config.esbuild === false && config.oxc !== false) logger.warn(import_picocolors.default.yellow("`esbuild` option is set to false, but `oxc` option was not set to false. `esbuild: false` does not have effect any more. If you want to disable the default transformation, which is now handled by Oxc, please set `oxc: false` instead."));
  34292. const experimental = mergeWithDefaults(configDefaults.experimental, config.experimental ?? {});
  34293. if (command === "serve" && experimental.bundledDev) experimental.renderBuiltUrl = void 0;
  34294. const resolvedDevToolsConfig = await resolveDevToolsConfig(config.devtools, server.host, logger);
  34295. resolved = {
  34296. configFile: configFile ? normalizePath(configFile) : void 0,
  34297. configFileDependencies: configFileDependencies.map((name) => normalizePath(path.resolve(name))),
  34298. inlineConfig,
  34299. root: resolvedRoot,
  34300. base,
  34301. decodedBase: decodeBase(base),
  34302. rawBase: resolvedBase,
  34303. publicDir: resolvedPublicDir,
  34304. cacheDir,
  34305. command,
  34306. mode,
  34307. isBundled: config.experimental?.bundledDev || isBuild,
  34308. isWorker: false,
  34309. mainConfig: null,
  34310. bundleChain: [],
  34311. isProduction,
  34312. plugins: userPlugins,
  34313. css: resolveCSSOptions(config.css),
  34314. json: mergeWithDefaults(configDefaults.json, config.json ?? {}),
  34315. esbuild: config.esbuild === false ? false : {
  34316. jsxDev: !isProduction,
  34317. charset: "utf8",
  34318. legalComments: "none",
  34319. ...config.esbuild
  34320. },
  34321. oxc: oxc === false ? false : {
  34322. ...oxc,
  34323. jsx: typeof oxc?.jsx === "string" ? oxc.jsx : {
  34324. development: oxc?.jsx?.development ?? !isProduction,
  34325. ...oxc?.jsx
  34326. }
  34327. },
  34328. server,
  34329. builder,
  34330. preview,
  34331. envDir,
  34332. env: {
  34333. ...userEnv,
  34334. BASE_URL,
  34335. MODE: mode,
  34336. DEV: !isProduction,
  34337. PROD: isProduction
  34338. },
  34339. assetsInclude(file) {
  34340. return DEFAULT_ASSETS_RE.test(file) || assetsFilter(file);
  34341. },
  34342. rawAssetsInclude: config.assetsInclude ? arraify(config.assetsInclude) : [],
  34343. logger,
  34344. packageCache,
  34345. worker: resolvedWorkerOptions,
  34346. appType: config.appType ?? "spa",
  34347. experimental,
  34348. future: config.future === "warn" ? {
  34349. removePluginHookHandleHotUpdate: "warn",
  34350. removePluginHookSsrArgument: "warn",
  34351. removeServerModuleGraph: "warn",
  34352. removeServerReloadModule: "warn",
  34353. removeServerPluginContainer: "warn",
  34354. removeServerHot: "warn",
  34355. removeServerTransformRequest: "warn",
  34356. removeServerWarmupRequest: "warn",
  34357. removeSsrLoadModule: "warn"
  34358. } : config.future,
  34359. ssr,
  34360. optimizeDeps: backwardCompatibleOptimizeDeps,
  34361. resolve: resolvedDefaultResolve,
  34362. dev: resolvedDevEnvironmentOptions,
  34363. build: resolvedBuildOptions,
  34364. devtools: resolvedDevToolsConfig,
  34365. environments: resolvedEnvironments,
  34366. webSocketToken: Buffer.from(crypto.getRandomValues(new Uint8Array(9))).toString("base64url"),
  34367. getSortedPlugins: void 0,
  34368. getSortedPluginHooks: void 0,
  34369. createResolver(options) {
  34370. const resolve = createIdResolver(this, options);
  34371. const clientEnvironment = new PartialEnvironment("client", this);
  34372. let ssrEnvironment;
  34373. return async (id, importer, aliasOnly, ssr) => {
  34374. if (ssr) ssrEnvironment ??= new PartialEnvironment("ssr", this);
  34375. return await resolve(ssr ? ssrEnvironment : clientEnvironment, id, importer, aliasOnly);
  34376. };
  34377. },
  34378. fsDenyGlob: picomatch(server.fs.deny.map((pattern) => pattern.includes("/") ? pattern : `**/${pattern}`), {
  34379. matchBase: false,
  34380. nocase: true,
  34381. dot: true
  34382. }),
  34383. safeModulePaths: /* @__PURE__ */ new Set(),
  34384. [SYMBOL_RESOLVED_CONFIG]: true
  34385. };
  34386. resolved = {
  34387. ...config,
  34388. ...resolved
  34389. };
  34390. patchConfig?.(resolved);
  34391. const resolvedPlugins = await resolvePlugins(resolved, prePlugins, normalPlugins, postPlugins);
  34392. patchPlugins?.(resolvedPlugins);
  34393. resolved.plugins = resolvedPlugins;
  34394. Object.assign(resolved, createPluginHookUtils(resolved.plugins));
  34395. await Promise.all(resolved.getSortedPluginHooks("configResolved").map((hook) => hook.call(resolvedConfigContext, resolved)));
  34396. for (const name of Object.keys(resolved.environments)) resolved.environments[name].plugins = await resolveEnvironmentPlugins(new PartialEnvironment(name, resolved));
  34397. optimizeDepsDisabledBackwardCompatibility(resolved, resolved.optimizeDeps);
  34398. optimizeDepsDisabledBackwardCompatibility(resolved, resolved.ssr.optimizeDeps, "ssr.");
  34399. if (!resolved.builder?.sharedConfigBuild && resolved.environments.ssr) resolved.environments.ssr.build.emitAssets = resolved.build.ssrEmitAssets || resolved.build.emitAssets;
  34400. if (resolved.devtools.enabled) resolved.build.rolldownOptions.devtools ??= {};
  34401. applyDepOptimizationOptionCompat(resolved);
  34402. await setOptimizeDepsPluginNames(resolved);
  34403. debug?.(`using resolved config: %O`, {
  34404. ...resolved,
  34405. plugins: resolved.plugins.map((p) => p.name),
  34406. worker: {
  34407. ...resolved.worker,
  34408. plugins: `() => plugins`
  34409. }
  34410. });
  34411. const outputOption = config.build?.rollupOptions?.output ?? [];
  34412. if (Array.isArray(outputOption)) {
  34413. const assetFileNamesList = outputOption.map((output) => output.assetFileNames);
  34414. if (assetFileNamesList.length > 1) {
  34415. const firstAssetFileNames = assetFileNamesList[0];
  34416. if (assetFileNamesList.some((assetFileNames) => assetFileNames !== firstAssetFileNames)) resolved.logger.warn(import_picocolors.default.yellow(`
  34417. assetFileNames isn't equal for every build.rollupOptions.output. A single pattern across all outputs is supported by Vite.
  34418. `));
  34419. }
  34420. }
  34421. if (config.legacy?.buildSsrCjsExternalHeuristics || config.ssr?.format === "cjs") resolved.logger.warn(import_picocolors.default.yellow(`
  34422. (!) Experimental legacy.buildSsrCjsExternalHeuristics and ssr.format were be removed in Vite 5.
  34423. The only SSR Output format is ESM. Find more information at https://github.com/vitejs/vite/discussions/13816.
  34424. `));
  34425. const resolvedBuildOutDir = normalizePath(path.resolve(resolved.root, resolved.build.outDir));
  34426. if (isParentDirectory(resolvedBuildOutDir, resolved.root) || resolvedBuildOutDir === resolved.root) resolved.logger.warn(import_picocolors.default.yellow(`
  34427. (!) build.outDir must not be the same directory of root or a parent directory of root as this could cause Vite to overwriting source files with build outputs.
  34428. `));
  34429. return resolved;
  34430. }
  34431. /**
  34432. * Resolve base url. Note that some users use Vite to build for non-web targets like
  34433. * electron or expects to deploy
  34434. */
  34435. function resolveBaseUrl(base = configDefaults.base, isBuild, logger) {
  34436. if (base[0] === ".") {
  34437. logger.warn(import_picocolors.default.yellow(import_picocolors.default.bold(`(!) invalid "base" option: "${base}". The value can only be an absolute URL, "./", or an empty string.`)));
  34438. return "/";
  34439. }
  34440. const isExternal = isExternalUrl(base);
  34441. if (!isExternal && base[0] !== "/") logger.warn(import_picocolors.default.yellow(import_picocolors.default.bold(`(!) "base" option should start with a slash.`)));
  34442. if (!isBuild || !isExternal) {
  34443. base = new URL(base, "http://vite.dev").pathname;
  34444. if (base[0] !== "/") base = "/" + base;
  34445. }
  34446. return base;
  34447. }
  34448. function decodeBase(base) {
  34449. try {
  34450. return decodeURI(base);
  34451. } catch {
  34452. throw new Error("The value passed to \"base\" option was malformed. It should be a valid URL.");
  34453. }
  34454. }
  34455. function sortUserPlugins(plugins) {
  34456. const prePlugins = [];
  34457. const postPlugins = [];
  34458. const normalPlugins = [];
  34459. if (plugins) plugins.flat().forEach((p) => {
  34460. if (p.enforce === "pre") prePlugins.push(p);
  34461. else if (p.enforce === "post") postPlugins.push(p);
  34462. else normalPlugins.push(p);
  34463. });
  34464. return [
  34465. prePlugins,
  34466. normalPlugins,
  34467. postPlugins
  34468. ];
  34469. }
  34470. async function loadConfigFromFile(configEnv, configFile, configRoot = process.cwd(), logLevel, customLogger, configLoader = "bundle") {
  34471. if (configLoader !== "bundle" && configLoader !== "runner" && configLoader !== "native") throw new Error(`Unsupported configLoader: ${configLoader}. Accepted values are 'bundle', 'runner', and 'native'.`);
  34472. const start = performance$1.now();
  34473. const getTime = () => `${(performance$1.now() - start).toFixed(2)}ms`;
  34474. let resolvedPath;
  34475. if (configFile) resolvedPath = path.resolve(configFile);
  34476. else for (const filename of DEFAULT_CONFIG_FILES) {
  34477. const filePath = path.resolve(configRoot, filename);
  34478. if (!fs.existsSync(filePath)) continue;
  34479. resolvedPath = filePath;
  34480. break;
  34481. }
  34482. if (!resolvedPath) {
  34483. debug?.("no config file found.");
  34484. return null;
  34485. }
  34486. try {
  34487. const { configExport, dependencies } = await (configLoader === "bundle" ? bundleAndLoadConfigFile : configLoader === "runner" ? runnerImportConfigFile : nativeImportConfigFile)(resolvedPath);
  34488. debug?.(`config file loaded in ${getTime()}`);
  34489. const config = await (typeof configExport === "function" ? configExport(configEnv) : configExport);
  34490. if (!isObject$1(config)) throw new Error(`config must export or return an object.`);
  34491. return {
  34492. path: normalizePath(resolvedPath),
  34493. config,
  34494. dependencies
  34495. };
  34496. } catch (e) {
  34497. const logger = createLogger(logLevel, { customLogger });
  34498. checkBadCharactersInPath("The config path", resolvedPath, logger);
  34499. logger.error(import_picocolors.default.red(`failed to load config from ${resolvedPath}`), { error: e });
  34500. throw e;
  34501. }
  34502. }
  34503. async function nativeImportConfigFile(resolvedPath) {
  34504. return {
  34505. configExport: (await import(pathToFileURL(resolvedPath).href + "?t=" + Date.now())).default,
  34506. dependencies: []
  34507. };
  34508. }
  34509. async function runnerImportConfigFile(resolvedPath) {
  34510. const { module, dependencies } = await runnerImport(resolvedPath);
  34511. return {
  34512. configExport: module.default,
  34513. dependencies
  34514. };
  34515. }
  34516. async function bundleAndLoadConfigFile(resolvedPath) {
  34517. const isESM = typeof process.versions.deno === "string" || isFilePathESM(resolvedPath);
  34518. const bundled = await bundleConfigFile(resolvedPath, isESM);
  34519. return {
  34520. configExport: await loadConfigFromBundledFile(resolvedPath, bundled.code, isESM),
  34521. dependencies: bundled.dependencies
  34522. };
  34523. }
  34524. async function bundleConfigFile(fileName, isESM) {
  34525. let importMetaResolverRegistered = false;
  34526. const root = path.dirname(fileName);
  34527. const dirnameVarName = "__vite_injected_original_dirname";
  34528. const filenameVarName = "__vite_injected_original_filename";
  34529. const importMetaUrlVarName = "__vite_injected_original_import_meta_url";
  34530. const importMetaResolveVarName = "__vite_injected_original_import_meta_resolve";
  34531. const importMetaResolveRegex = /import\.meta\s*\.\s*resolve/;
  34532. const bundle = await rolldown({
  34533. input: fileName,
  34534. platform: "node",
  34535. resolve: { mainFields: ["main"] },
  34536. transform: { define: {
  34537. __dirname: dirnameVarName,
  34538. __filename: filenameVarName,
  34539. "import.meta.url": importMetaUrlVarName,
  34540. "import.meta.dirname": dirnameVarName,
  34541. "import.meta.filename": filenameVarName,
  34542. "import.meta.resolve": importMetaResolveVarName,
  34543. "import.meta.main": "false"
  34544. } },
  34545. treeshake: false,
  34546. tsconfig: false,
  34547. plugins: [{
  34548. name: "externalize-deps",
  34549. resolveId: {
  34550. filter: { id: /^[^.#].*/ },
  34551. async handler(id, importer, { kind }) {
  34552. if (!importer || path.isAbsolute(id) || isNodeBuiltin(id)) return;
  34553. if (isNodeLikeBuiltin(id) || id.startsWith("npm:")) return {
  34554. id,
  34555. external: true
  34556. };
  34557. const isImport = isESM || kind === "dynamic-import";
  34558. let idFsPath;
  34559. try {
  34560. idFsPath = nodeResolveWithVite(id, importer, {
  34561. root,
  34562. isRequire: !isImport
  34563. });
  34564. } catch (e) {
  34565. if (!isImport) {
  34566. let canResolveWithImport = false;
  34567. try {
  34568. canResolveWithImport = !!nodeResolveWithVite(id, importer, { root });
  34569. } catch {}
  34570. if (canResolveWithImport) throw new Error(`Failed to resolve ${JSON.stringify(id)}. This package is ESM only but it was tried to load by \`require\`. See https://vite.dev/guide/troubleshooting.html#this-package-is-esm-only for more details.`);
  34571. }
  34572. throw e;
  34573. }
  34574. if (!idFsPath) return;
  34575. if (idFsPath.endsWith(".json")) return idFsPath;
  34576. if (idFsPath && isImport) idFsPath = pathToFileURL(idFsPath).href;
  34577. return {
  34578. id: idFsPath,
  34579. external: true
  34580. };
  34581. }
  34582. }
  34583. }, {
  34584. name: "inject-file-scope-variables",
  34585. transform: {
  34586. filter: { id: /\.[cm]?[jt]s$/ },
  34587. handler(code, id) {
  34588. let injectValues = `const ${dirnameVarName} = ${JSON.stringify(path.dirname(id))};const ${filenameVarName} = ${JSON.stringify(id)};const ${importMetaUrlVarName} = ${JSON.stringify(pathToFileURL(id).href)};`;
  34589. if (importMetaResolveRegex.test(code)) if (isESM) {
  34590. if (!importMetaResolverRegistered) {
  34591. importMetaResolverRegistered = true;
  34592. createImportMetaResolver();
  34593. }
  34594. injectValues += `const ${importMetaResolveVarName} = (specifier, importer = ${importMetaUrlVarName}) => (${importMetaResolveWithCustomHookString})(specifier, importer);`;
  34595. } else injectValues += `const ${importMetaResolveVarName} = (specifier, importer = ${importMetaUrlVarName}) => { throw new Error('import.meta.resolve is not supported in CJS config files') };`;
  34596. let injectedContents;
  34597. if (code.startsWith("#!")) {
  34598. let firstLineEndIndex = code.indexOf("\n");
  34599. if (firstLineEndIndex < 0) firstLineEndIndex = code.length;
  34600. injectedContents = code.slice(0, firstLineEndIndex + 1) + injectValues + code.slice(firstLineEndIndex + 1);
  34601. } else injectedContents = injectValues + code;
  34602. return {
  34603. code: injectedContents,
  34604. map: null
  34605. };
  34606. }
  34607. }
  34608. }]
  34609. });
  34610. const result = await bundle.generate({
  34611. format: isESM ? "esm" : "cjs",
  34612. sourcemap: "inline",
  34613. sourcemapPathTransform(relative) {
  34614. return path.resolve(fileName, relative);
  34615. },
  34616. codeSplitting: false
  34617. });
  34618. await bundle.close();
  34619. const entryChunk = result.output.find((chunk) => chunk.type === "chunk" && chunk.isEntry);
  34620. const bundleChunks = Object.fromEntries(result.output.flatMap((c) => c.type === "chunk" ? [[c.fileName, c]] : []));
  34621. const allModules = /* @__PURE__ */ new Set();
  34622. collectAllModules(bundleChunks, entryChunk.fileName, allModules);
  34623. return {
  34624. code: entryChunk.code,
  34625. dependencies: [...allModules].filter((m) => !m.startsWith("\0"))
  34626. };
  34627. }
  34628. function collectAllModules(bundle, fileName, allModules, analyzedModules = /* @__PURE__ */ new Set()) {
  34629. if (analyzedModules.has(fileName)) return;
  34630. analyzedModules.add(fileName);
  34631. const chunk = bundle[fileName];
  34632. for (const mod of chunk.moduleIds) allModules.add(mod);
  34633. for (const i of chunk.imports) {
  34634. analyzedModules.add(i);
  34635. collectAllModules(bundle, i, allModules, analyzedModules);
  34636. }
  34637. for (const i of chunk.dynamicImports) {
  34638. analyzedModules.add(i);
  34639. collectAllModules(bundle, i, allModules, analyzedModules);
  34640. }
  34641. }
  34642. const _require = createRequire(
  34643. /** #__KEEP__ */
  34644. import.meta.url
  34645. );
  34646. async function loadConfigFromBundledFile(fileName, bundledCode, isESM) {
  34647. if (isESM) {
  34648. let nodeModulesDir = typeof process.versions.deno === "string" ? void 0 : findNearestNodeModules(path.dirname(fileName));
  34649. if (nodeModulesDir) try {
  34650. await fsp.mkdir(path.resolve(nodeModulesDir, ".vite-temp/"), { recursive: true });
  34651. } catch (e) {
  34652. if (e.code === "EACCES") nodeModulesDir = void 0;
  34653. else throw e;
  34654. }
  34655. const hash = `timestamp-${Date.now()}-${Math.random().toString(16).slice(2)}`;
  34656. const tempFileName = nodeModulesDir ? path.resolve(nodeModulesDir, `.vite-temp/${path.basename(fileName)}.${hash}.mjs`) : `${fileName}.${hash}.mjs`;
  34657. await fsp.writeFile(tempFileName, bundledCode);
  34658. try {
  34659. return (await import(pathToFileURL(tempFileName).href)).default;
  34660. } finally {
  34661. fs.unlink(tempFileName, () => {});
  34662. }
  34663. } else {
  34664. const extension = path.extname(fileName);
  34665. const realFileName = await promisifiedRealpath(fileName);
  34666. const loaderExt = extension in _require.extensions ? extension : ".js";
  34667. const defaultLoader = _require.extensions[loaderExt];
  34668. _require.extensions[loaderExt] = (module, filename) => {
  34669. if (filename === realFileName) module._compile(bundledCode, filename);
  34670. else defaultLoader(module, filename);
  34671. };
  34672. delete _require.cache[_require.resolve(fileName)];
  34673. const raw = _require(fileName);
  34674. _require.extensions[loaderExt] = defaultLoader;
  34675. return raw.__esModule ? raw.default : raw;
  34676. }
  34677. }
  34678. async function runConfigHook(config, plugins, configEnv) {
  34679. let conf = config;
  34680. const context = new BasicMinimalPluginContext(basePluginContextMeta, createLogger(config.logLevel, {
  34681. allowClearScreen: config.clearScreen,
  34682. customLogger: config.customLogger
  34683. }));
  34684. for (const p of getSortedPluginsByHook("config", plugins)) {
  34685. const hook = p.config;
  34686. const res = await getHookHandler(hook).call(context, conf, configEnv);
  34687. if (res && res !== conf) {
  34688. if (hasBothRollupOptionsAndRolldownOptions(res)) context.warn(`Both \`rollupOptions\` and \`rolldownOptions\` were specified by ${JSON.stringify(p.name)} plugin. \`rollupOptions\` specified by that plugin will be ignored.`);
  34689. if (res.esbuild) context.warn(`\`esbuild\` option was specified by ${JSON.stringify(p.name)} plugin. This option is deprecated, please use \`oxc\` instead.`);
  34690. if (res.optimizeDeps?.esbuildOptions) context.warn(`\`optimizeDeps.esbuildOptions\` option was specified by ${JSON.stringify(p.name)} plugin. This option is deprecated, please use \`optimizeDeps.rolldownOptions\` instead.`);
  34691. conf = mergeConfig(conf, res);
  34692. }
  34693. }
  34694. return conf;
  34695. }
  34696. async function runConfigEnvironmentHook(environments, plugins, logger, configEnv, isSsrTargetWebworkerSet) {
  34697. const context = new BasicMinimalPluginContext(basePluginContextMeta, logger);
  34698. const environmentNames = Object.keys(environments);
  34699. for (const p of getSortedPluginsByHook("configEnvironment", plugins)) {
  34700. const hook = p.configEnvironment;
  34701. const handler = getHookHandler(hook);
  34702. for (const name of environmentNames) {
  34703. const res = await handler.call(context, name, environments[name], {
  34704. ...configEnv,
  34705. isSsrTargetWebworker: isSsrTargetWebworkerSet && name === "ssr"
  34706. });
  34707. if (res) environments[name] = mergeConfig(environments[name], res);
  34708. }
  34709. }
  34710. }
  34711. function optimizeDepsDisabledBackwardCompatibility(resolved, optimizeDeps, optimizeDepsPath = "") {
  34712. const optimizeDepsDisabled = optimizeDeps.disabled;
  34713. if (optimizeDepsDisabled !== void 0) {
  34714. if (optimizeDepsDisabled === true || optimizeDepsDisabled === "dev") {
  34715. const commonjsOptionsInclude = resolved.build.commonjsOptions.include;
  34716. const commonjsPluginDisabled = Array.isArray(commonjsOptionsInclude) && commonjsOptionsInclude.length === 0;
  34717. optimizeDeps.noDiscovery = true;
  34718. optimizeDeps.include = void 0;
  34719. if (commonjsPluginDisabled) resolved.build.commonjsOptions.include = void 0;
  34720. resolved.logger.warn(import_picocolors.default.yellow(`(!) Experimental ${optimizeDepsPath}optimizeDeps.disabled and deps pre-bundling during build were removed in Vite 5.1.
  34721. To disable the deps optimizer, set ${optimizeDepsPath}optimizeDeps.noDiscovery to true and ${optimizeDepsPath}optimizeDeps.include as undefined or empty.
  34722. Please remove ${optimizeDepsPath}optimizeDeps.disabled from your config.
  34723. ${commonjsPluginDisabled ? "Empty config.build.commonjsOptions.include will be ignored to support CJS during build. This config should also be removed." : ""}
  34724. `));
  34725. } else if (optimizeDepsDisabled === false || optimizeDepsDisabled === "build") resolved.logger.warn(import_picocolors.default.yellow(`(!) Experimental ${optimizeDepsPath}optimizeDeps.disabled and deps pre-bundling during build were removed in Vite 5.1.
  34726. Setting it to ${optimizeDepsDisabled} now has no effect.
  34727. Please remove ${optimizeDepsPath}optimizeDeps.disabled from your config.
  34728. `));
  34729. }
  34730. }
  34731. //#endregion
  34732. //#region src/node/server/environments/fetchableEnvironments.ts
  34733. function createFetchableDevEnvironment(name, config, context) {
  34734. if (typeof Request === "undefined" || typeof Response === "undefined") throw new TypeError("FetchableDevEnvironment requires a global `Request` and `Response` object.");
  34735. if (!context.handleRequest) throw new TypeError("FetchableDevEnvironment requires a `handleRequest` method during initialisation.");
  34736. return new FetchableDevEnvironment(name, config, context);
  34737. }
  34738. function isFetchableDevEnvironment(environment) {
  34739. return environment instanceof FetchableDevEnvironment;
  34740. }
  34741. var FetchableDevEnvironment = class extends DevEnvironment {
  34742. _handleRequest;
  34743. constructor(name, config, context) {
  34744. super(name, config, context);
  34745. this._handleRequest = context.handleRequest;
  34746. }
  34747. async dispatchFetch(request) {
  34748. if (!(request instanceof Request)) throw new TypeError("FetchableDevEnvironment `dispatchFetch` must receive a `Request` object.");
  34749. const response = await this._handleRequest(request);
  34750. if (!(response instanceof Response)) throw new TypeError("FetchableDevEnvironment `context.handleRequest` must return a `Response` object.");
  34751. return response;
  34752. }
  34753. };
  34754. //#endregion
  34755. //#region src/node/index.ts
  34756. /** @deprecated - use `parse` instead */
  34757. const parseAst$1 = parseAst;
  34758. /** @deprecated - use `parseAsync` instead */
  34759. const parseAstAsync$1 = parseAstAsync;
  34760. const esbuildVersion = "0.25.0";
  34761. //#endregion
  34762. export { depsFromOptimizedDepInfo as $, builderOptionsDefaults as A, searchForWorkspaceRoot as At, resolveBuilderOptions as B, transformWithEsbuild as Bt, resolvePreviewOptions as C, DevEnvironment as Ct, ChunkMetadataMap as D, fetchModule as Dt, BuildEnvironment as E, isFileServingAllowed as Et, injectEnvironmentToHooks as F, createServerModuleRunnerTransport as Ft, toOutputFilePathInHtml as G, mergeConfig as Gt, resolveRolldownOptions as H, createFilter$1 as Ht, onRollupLog as I, buildErrorMessage as It, addManuallyIncludedOptimizeDeps as J, rollupVersion as Jt, toOutputFilePathInJS as K, normalizePath as Kt, resolveBuildEnvironmentOptions as L, loadEnv as Lt, createBuilder as M, perEnvironmentState as Mt, createToImportMetaURLBasedRelativeRuntime as N, ssrTransform as Nt, build as O, formatPostcssSourceMap as Ot, enhanceRollupError as P, createServerModuleRunner as Pt, createIsOptimizedDepUrl as Q, resolveBuildOutputs as R, resolveEnvPrefix as Rt, preview as S, serverConfigDefaults as St, isRunnableDevEnvironment as T, isFileLoadingAllowed as Tt, resolveUserExternal as U, isCSSRequest as Ut, resolveLibFilename as V, perEnvironmentPlugin as Vt, toOutputFilePathInCss as W, mergeAlias as Wt, cleanupDepsCacheStaleDirs as X, addOptimizedDepInfo as Y, withFilter as Yt, createIsOptimizedDepFile as Z, resolveConfig as _, createServer$2 as _t, minifySync as a, initDepsOptimizerMetadata as at, sortUserPlugins as b, resolveServerOptions as bt, parseAstAsync$1 as c, optimizeDeps as ct, isFetchableDevEnvironment as d, optimizedDepInfoFromId as dt, depsLogString as et, defineConfig as f, optimizedDepNeedsInterop as ft, resolveBaseUrl as g, _createServer as gt, loadConfigFromFile as h, createServerHotChannel as ht, minify as i, getOptimizedDepPath as it, clearLine as j, createIdResolver as jt, buildEnvironmentOptionsDefaults as k, preprocessCSS as kt, parseSync as l, optimizeExplicitEnvironmentDeps as lt, isResolvedConfig as m, toDiscoveredDependencies as mt, esbuildVersion as n, extractExportsData as nt, parse as o, isDepOptimizationDisabled as ot, getDefaultEnvironmentOptions as p, runOptimizeDeps as pt, toOutputFilePathWithoutRuntime as q, rolldownVersion as qt, esmExternalRequirePlugin$1 as r, getDepsCacheDir as rt, parseAst$1 as s, loadCachedDepOptimizationMetadata as st, Visitor as t, discoverProjectDependencies as tt, createFetchableDevEnvironment as u, optimizedDepInfoFromFile as ut, resolveDevEnvironmentOptions as v, createServerCloseFn as vt, createRunnableDevEnvironment as w, send as wt, runnerImport as x, restartServerWithUrls as xt, resolveDevToolsConfig as y, resolveForwardConsoleOptions as yt, resolveBuildPlugins as z, transformWithOxc as zt };