node.js 1.2 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624
  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 } 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, 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. const value = args[index];
  979. match = formatter.call(debug, value);
  980. args.splice(index, 1);
  981. index--;
  982. }
  983. return match;
  984. });
  985. createDebug.formatArgs.call(debug, args);
  986. (debug.log || createDebug.log).apply(debug, args);
  987. };
  988. function extend(namespace$1, delimiter = ":") {
  989. const newDebug = createDebug(this.namespace + delimiter + namespace$1);
  990. newDebug.log = this.log;
  991. return newDebug;
  992. }
  993. debug.namespace = namespace;
  994. debug.useColors = useColors;
  995. debug.color = selectColor(colors, namespace);
  996. debug.extend = extend;
  997. debug.log = log;
  998. Object.defineProperty(debug, "enabled", {
  999. enumerable: true,
  1000. configurable: false,
  1001. get: () => {
  1002. if (enableOverride != null) return enableOverride;
  1003. if (namespacesCache !== createDebug.namespaces) {
  1004. namespacesCache = createDebug.namespaces;
  1005. enabledCache = createDebug.enabled(namespace);
  1006. }
  1007. return enabledCache;
  1008. },
  1009. set: (v) => {
  1010. enableOverride = v;
  1011. }
  1012. });
  1013. init && init(debug);
  1014. return debug;
  1015. };
  1016. function enable(namespaces) {
  1017. save(namespaces);
  1018. createDebug.namespaces = namespaces;
  1019. createDebug.names = [];
  1020. createDebug.skips = [];
  1021. const split = namespaces.trim().replace(/\s+/g, ",").split(",").filter(Boolean);
  1022. for (const ns of split) if (ns[0] === "-") createDebug.skips.push(ns.slice(1));
  1023. else createDebug.names.push(ns);
  1024. }
  1025. function disable() {
  1026. const namespaces = [...createDebug.names, ...createDebug.skips.map((namespace) => `-${namespace}`)].join(",");
  1027. createDebug.enable("");
  1028. return namespaces;
  1029. }
  1030. function enabled(name) {
  1031. for (const skip of createDebug.skips) if (matchesTemplate(name, skip)) return false;
  1032. for (const ns of createDebug.names) if (matchesTemplate(name, ns)) return true;
  1033. return false;
  1034. }
  1035. createDebug.namespaces = "";
  1036. createDebug.formatters = {};
  1037. createDebug.enable = enable;
  1038. createDebug.disable = disable;
  1039. createDebug.enabled = enabled;
  1040. createDebug.names = [];
  1041. createDebug.skips = [];
  1042. createDebug.selectColor = (ns) => selectColor(colors, ns);
  1043. createDebug.formatArgs = formatArgs;
  1044. createDebug.log = log;
  1045. createDebug.enable(load());
  1046. return createDebug;
  1047. }
  1048. var init_core = __esmMin((() => {}));
  1049. //#endregion
  1050. //#region ../../node_modules/.pnpm/obug@1.0.2_ms@2.1.3/node_modules/obug/dist/node.js
  1051. var node_exports = /* @__PURE__ */ __exportAll({
  1052. createDebug: () => createDebug,
  1053. default: () => node_default,
  1054. formatArgs: () => formatArgs,
  1055. log: () => log,
  1056. "module.exports": () => createDebug
  1057. });
  1058. function log(...args) {
  1059. process.stderr.write(`${formatWithOptions(inspectOpts, ...args)}\n`);
  1060. }
  1061. function load() {
  1062. return process.env.DEBUG || "";
  1063. }
  1064. function save(namespaces) {
  1065. if (namespaces) process.env.DEBUG = namespaces;
  1066. else delete process.env.DEBUG;
  1067. }
  1068. function useColors() {
  1069. return "colors" in inspectOpts ? Boolean(inspectOpts.colors) : isatty(process.stderr.fd);
  1070. }
  1071. function formatArgs(args) {
  1072. const { namespace: name, useColors: useColors$1 } = this;
  1073. if (useColors$1) {
  1074. const c = this.color;
  1075. const colorCode = `\u001B[3${c < 8 ? c : `8;5;${c}`}`;
  1076. const prefix = ` ${colorCode};1m${name} \u001B[0m`;
  1077. args[0] = prefix + args[0].split("\n").join(`\n${prefix}`);
  1078. args.push(`${colorCode}m+${humanize$1(this.diff)}\u001B[0m`);
  1079. } else args[0] = `${getDate()}${name} ${args[0]}`;
  1080. }
  1081. function getDate() {
  1082. if (inspectOpts.hideDate) return "";
  1083. return `${(/* @__PURE__ */ new Date()).toISOString()} `;
  1084. }
  1085. function init$1(debug) {
  1086. debug.inspectOpts = Object.assign({}, inspectOpts);
  1087. }
  1088. var require$1, colors$36, inspectOpts, humanize$1, createDebug, node_default;
  1089. var init_node = __esmMin((() => {
  1090. init_core();
  1091. require$1 = createRequire(import.meta.url);
  1092. colors$36 = process.stderr.getColorDepth && process.stderr.getColorDepth() > 2 ? [
  1093. 20,
  1094. 21,
  1095. 26,
  1096. 27,
  1097. 32,
  1098. 33,
  1099. 38,
  1100. 39,
  1101. 40,
  1102. 41,
  1103. 42,
  1104. 43,
  1105. 44,
  1106. 45,
  1107. 56,
  1108. 57,
  1109. 62,
  1110. 63,
  1111. 68,
  1112. 69,
  1113. 74,
  1114. 75,
  1115. 76,
  1116. 77,
  1117. 78,
  1118. 79,
  1119. 80,
  1120. 81,
  1121. 92,
  1122. 93,
  1123. 98,
  1124. 99,
  1125. 112,
  1126. 113,
  1127. 128,
  1128. 129,
  1129. 134,
  1130. 135,
  1131. 148,
  1132. 149,
  1133. 160,
  1134. 161,
  1135. 162,
  1136. 163,
  1137. 164,
  1138. 165,
  1139. 166,
  1140. 167,
  1141. 168,
  1142. 169,
  1143. 170,
  1144. 171,
  1145. 172,
  1146. 173,
  1147. 178,
  1148. 179,
  1149. 184,
  1150. 185,
  1151. 196,
  1152. 197,
  1153. 198,
  1154. 199,
  1155. 200,
  1156. 201,
  1157. 202,
  1158. 203,
  1159. 204,
  1160. 205,
  1161. 206,
  1162. 207,
  1163. 208,
  1164. 209,
  1165. 214,
  1166. 215,
  1167. 220,
  1168. 221
  1169. ] : [
  1170. 6,
  1171. 2,
  1172. 3,
  1173. 4,
  1174. 5,
  1175. 1
  1176. ];
  1177. inspectOpts = Object.keys(process.env).filter((key) => {
  1178. return /^debug_/i.test(key);
  1179. }).reduce((obj, key) => {
  1180. const prop = key.slice(6).toLowerCase().replace(/_([a-z])/g, (_, k) => k.toUpperCase());
  1181. let value = process.env[key];
  1182. if (value === "null") value = null;
  1183. else if (/^yes|on|true|enabled$/i.test(value)) value = true;
  1184. else if (/^no|off|false|disabled$/i.test(value)) value = false;
  1185. else value = Number(value);
  1186. obj[prop] = value;
  1187. return obj;
  1188. }, {});
  1189. try {
  1190. humanize$1 = require$1("ms");
  1191. } catch (_unused) {
  1192. humanize$1 = humanize;
  1193. }
  1194. createDebug = setup(useColors(), colors$36, log, load, save, formatArgs, init$1);
  1195. createDebug.inspectOpts = inspectOpts;
  1196. createDebug.formatters.o = function(v) {
  1197. this.inspectOpts.colors = this.useColors;
  1198. return inspect(v, this.inspectOpts).split("\n").map((str) => str.trim()).join(" ");
  1199. };
  1200. createDebug.formatters.O = function(v) {
  1201. this.inspectOpts.colors = this.useColors;
  1202. return inspect(v, this.inspectOpts);
  1203. };
  1204. node_default = createDebug;
  1205. createDebug.default = createDebug;
  1206. createDebug.debug = createDebug;
  1207. }));
  1208. //#endregion
  1209. //#region ../../node_modules/.pnpm/@rollup+pluginutils@5.3.0_rollup@4.59.0/node_modules/@rollup/pluginutils/dist/es/index.js
  1210. function isArray(arg) {
  1211. return Array.isArray(arg);
  1212. }
  1213. function ensureArray(thing) {
  1214. if (isArray(thing)) return thing;
  1215. if (thing == null) return [];
  1216. return [thing];
  1217. }
  1218. const normalizePathRegExp = new RegExp(`\\${win32.sep}`, "g");
  1219. const normalizePath$1 = function normalizePath(filename) {
  1220. return filename.replace(normalizePathRegExp, posix$1.sep);
  1221. };
  1222. function getMatcherString$1(id, resolutionBase) {
  1223. if (resolutionBase === false || isAbsolute$1(id) || id.startsWith("**")) return normalizePath$1(id);
  1224. const basePath = normalizePath$1(resolve$1(resolutionBase || "")).replace(/[-^$*+?.()|[\]{}]/g, "\\$&");
  1225. return posix$1.join(basePath, normalizePath$1(id));
  1226. }
  1227. const createFilter$2 = function createFilter(include, exclude, options) {
  1228. const resolutionBase = options && options.resolve;
  1229. const getMatcher = (id) => id instanceof RegExp ? id : { test: (what) => {
  1230. return picomatch(getMatcherString$1(id, resolutionBase), { dot: true })(what);
  1231. } };
  1232. const includeMatchers = ensureArray(include).map(getMatcher);
  1233. const excludeMatchers = ensureArray(exclude).map(getMatcher);
  1234. if (!includeMatchers.length && !excludeMatchers.length) return (id) => typeof id === "string" && !id.includes("\0");
  1235. return function result(id) {
  1236. if (typeof id !== "string") return false;
  1237. if (id.includes("\0")) return false;
  1238. const pathId = normalizePath$1(id);
  1239. for (let i = 0; i < excludeMatchers.length; ++i) {
  1240. const matcher = excludeMatchers[i];
  1241. if (matcher instanceof RegExp) matcher.lastIndex = 0;
  1242. if (matcher.test(pathId)) return false;
  1243. }
  1244. for (let i = 0; i < includeMatchers.length; ++i) {
  1245. const matcher = includeMatchers[i];
  1246. if (matcher instanceof RegExp) matcher.lastIndex = 0;
  1247. if (matcher.test(pathId)) return true;
  1248. }
  1249. return !includeMatchers.length;
  1250. };
  1251. };
  1252. 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(" "));
  1253. forbiddenIdentifiers.add("");
  1254. const makeLegalIdentifier = function makeLegalIdentifier(str) {
  1255. let identifier = str.replace(/-(\w)/g, (_, letter) => letter.toUpperCase()).replace(/[^$_a-zA-Z0-9]/g, "_");
  1256. if (/\d/.test(identifier[0]) || forbiddenIdentifiers.has(identifier)) identifier = `_${identifier}`;
  1257. return identifier || "_";
  1258. };
  1259. function stringify(obj) {
  1260. return (JSON.stringify(obj) || "undefined").replace(/[\u2028\u2029]/g, (char) => `\\u${`000${char.charCodeAt(0).toString(16)}`.slice(-4)}`);
  1261. }
  1262. function serializeArray(arr, indent, baseIndent) {
  1263. let output = "[";
  1264. const separator = indent ? `\n${baseIndent}${indent}` : "";
  1265. for (let i = 0; i < arr.length; i++) {
  1266. const key = arr[i];
  1267. output += `${i > 0 ? "," : ""}${separator}${serialize(key, indent, baseIndent + indent)}`;
  1268. }
  1269. return `${output}${indent ? `\n${baseIndent}` : ""}]`;
  1270. }
  1271. function serializeObject(obj, indent, baseIndent) {
  1272. let output = "{";
  1273. const separator = indent ? `\n${baseIndent}${indent}` : "";
  1274. const entries = Object.entries(obj);
  1275. for (let i = 0; i < entries.length; i++) {
  1276. const [key, value] = entries[i];
  1277. const stringKey = makeLegalIdentifier(key) === key ? key : stringify(key);
  1278. output += `${i > 0 ? "," : ""}${separator}${stringKey}:${indent ? " " : ""}${serialize(value, indent, baseIndent + indent)}`;
  1279. }
  1280. return `${output}${indent ? `\n${baseIndent}` : ""}}`;
  1281. }
  1282. function serialize(obj, indent, baseIndent) {
  1283. if (typeof obj === "object" && obj !== null) {
  1284. if (Array.isArray(obj)) return serializeArray(obj, indent, baseIndent);
  1285. if (obj instanceof Date) return `new Date(${obj.getTime()})`;
  1286. if (obj instanceof RegExp) return obj.toString();
  1287. return serializeObject(obj, indent, baseIndent);
  1288. }
  1289. if (typeof obj === "number") {
  1290. if (obj === Infinity) return "Infinity";
  1291. if (obj === -Infinity) return "-Infinity";
  1292. if (obj === 0) return 1 / obj === Infinity ? "0" : "-0";
  1293. if (obj !== obj) return "NaN";
  1294. }
  1295. if (typeof obj === "symbol") {
  1296. const key = Symbol.keyFor(obj);
  1297. if (key !== void 0) return `Symbol.for(${stringify(key)})`;
  1298. }
  1299. if (typeof obj === "bigint") return `${obj}n`;
  1300. return stringify(obj);
  1301. }
  1302. const hasStringIsWellFormed = "isWellFormed" in String.prototype;
  1303. function isWellFormedString(input) {
  1304. if (hasStringIsWellFormed) return input.isWellFormed();
  1305. return !/\p{Surrogate}/u.test(input);
  1306. }
  1307. const dataToEsm = function dataToEsm(data, options = {}) {
  1308. var _a, _b;
  1309. const t = options.compact ? "" : "indent" in options ? options.indent : " ";
  1310. const _ = options.compact ? "" : " ";
  1311. const n = options.compact ? "" : "\n";
  1312. const declarationType = options.preferConst ? "const" : "var";
  1313. if (options.namedExports === false || typeof data !== "object" || Array.isArray(data) || data instanceof Date || data instanceof RegExp || data === null) {
  1314. const code = serialize(data, options.compact ? null : t, "");
  1315. return `export default${_ || (/^[{[\-\/]/.test(code) ? "" : " ")}${code};`;
  1316. }
  1317. let maxUnderbarPrefixLength = 0;
  1318. for (const key of Object.keys(data)) {
  1319. const underbarPrefixLength = (_b = (_a = /^(_+)/.exec(key)) === null || _a === void 0 ? void 0 : _a[0].length) !== null && _b !== void 0 ? _b : 0;
  1320. if (underbarPrefixLength > maxUnderbarPrefixLength) maxUnderbarPrefixLength = underbarPrefixLength;
  1321. }
  1322. const arbitraryNamePrefix = `${"_".repeat(maxUnderbarPrefixLength + 1)}arbitrary`;
  1323. let namedExportCode = "";
  1324. const defaultExportRows = [];
  1325. const arbitraryNameExportRows = [];
  1326. for (const [key, value] of Object.entries(data)) if (key === makeLegalIdentifier(key)) {
  1327. if (options.objectShorthand) defaultExportRows.push(key);
  1328. else defaultExportRows.push(`${key}:${_}${key}`);
  1329. namedExportCode += `export ${declarationType} ${key}${_}=${_}${serialize(value, options.compact ? null : t, "")};${n}`;
  1330. } else {
  1331. defaultExportRows.push(`${stringify(key)}:${_}${serialize(value, options.compact ? null : t, "")}`);
  1332. if (options.includeArbitraryNames && isWellFormedString(key)) {
  1333. const variableName = `${arbitraryNamePrefix}${arbitraryNameExportRows.length}`;
  1334. namedExportCode += `${declarationType} ${variableName}${_}=${_}${serialize(value, options.compact ? null : t, "")};${n}`;
  1335. arbitraryNameExportRows.push(`${variableName} as ${JSON.stringify(key)}`);
  1336. }
  1337. }
  1338. const arbitraryExportCode = arbitraryNameExportRows.length > 0 ? `export${_}{${n}${t}${arbitraryNameExportRows.join(`,${n}${t}`)}${n}};${n}` : "";
  1339. const defaultExportCode = `export default${_}{${n}${t}${defaultExportRows.join(`,${n}${t}`)}${n}};${n}`;
  1340. return `${namedExportCode}${arbitraryExportCode}${defaultExportCode}`;
  1341. };
  1342. //#endregion
  1343. //#region src/shared/builtin.ts
  1344. function createIsBuiltin(builtins) {
  1345. const plainBuiltinsSet = new Set(builtins.filter((builtin) => typeof builtin === "string"));
  1346. const regexBuiltins = builtins.filter((builtin) => typeof builtin !== "string");
  1347. return (id) => plainBuiltinsSet.has(id) || regexBuiltins.some((regexp) => regexp.test(id));
  1348. }
  1349. //#endregion
  1350. //#region src/node/packages.ts
  1351. let pnp;
  1352. if (process.versions.pnp) try {
  1353. pnp = createRequire(
  1354. /** #__KEEP__ */
  1355. import.meta.url
  1356. )("pnpapi");
  1357. } catch {}
  1358. function invalidatePackageData(packageCache, pkgPath) {
  1359. const pkgDir = normalizePath(path.dirname(pkgPath));
  1360. packageCache.forEach((pkg, cacheKey) => {
  1361. if (pkg.dir === pkgDir) packageCache.delete(cacheKey);
  1362. });
  1363. }
  1364. function resolvePackageData(pkgName, basedir, preserveSymlinks = false, packageCache) {
  1365. if (pnp) {
  1366. const cacheKey = getRpdCacheKey(pkgName, basedir, preserveSymlinks);
  1367. if (packageCache?.has(cacheKey)) return packageCache.get(cacheKey);
  1368. try {
  1369. const pkg = pnp.resolveToUnqualified(pkgName, basedir, { considerBuiltins: false });
  1370. if (!pkg) return null;
  1371. const pkgData = loadPackageData(path.join(pkg, "package.json"));
  1372. packageCache?.set(cacheKey, pkgData);
  1373. return pkgData;
  1374. } catch {
  1375. return null;
  1376. }
  1377. }
  1378. const originalBasedir = basedir;
  1379. while (basedir) {
  1380. if (packageCache) {
  1381. const cached = getRpdCache(packageCache, pkgName, basedir, originalBasedir, preserveSymlinks);
  1382. if (cached) return cached;
  1383. }
  1384. const pkg = path.join(basedir, "node_modules", pkgName, "package.json");
  1385. try {
  1386. if (fs.existsSync(pkg)) {
  1387. const pkgData = loadPackageData(preserveSymlinks ? pkg : safeRealpathSync(pkg));
  1388. if (packageCache) setRpdCache(packageCache, pkgData, pkgName, basedir, originalBasedir, preserveSymlinks);
  1389. return pkgData;
  1390. }
  1391. } catch {}
  1392. const nextBasedir = path.dirname(basedir);
  1393. if (nextBasedir === basedir) break;
  1394. basedir = nextBasedir;
  1395. }
  1396. return null;
  1397. }
  1398. function findNearestPackageData(basedir, packageCache) {
  1399. const originalBasedir = basedir;
  1400. while (basedir) {
  1401. if (packageCache) {
  1402. const cached = getFnpdCache(packageCache, basedir, originalBasedir);
  1403. if (cached) return cached;
  1404. }
  1405. const pkgPath = path.join(basedir, "package.json");
  1406. if (tryStatSync(pkgPath)?.isFile()) try {
  1407. const pkgData = loadPackageData(pkgPath);
  1408. if (packageCache) setFnpdCache(packageCache, pkgData, basedir, originalBasedir);
  1409. return pkgData;
  1410. } catch {}
  1411. const nextBasedir = path.dirname(basedir);
  1412. if (nextBasedir === basedir) break;
  1413. basedir = nextBasedir;
  1414. }
  1415. return null;
  1416. }
  1417. function findNearestMainPackageData(basedir, packageCache) {
  1418. const nearestPackage = findNearestPackageData(basedir, packageCache);
  1419. return nearestPackage && (nearestPackage.data.name ? nearestPackage : findNearestMainPackageData(path.dirname(nearestPackage.dir), packageCache));
  1420. }
  1421. function loadPackageData(pkgPath) {
  1422. const data = JSON.parse(stripBomTag(fs.readFileSync(pkgPath, "utf-8")));
  1423. const pkgDir = normalizePath(path.dirname(pkgPath));
  1424. const { sideEffects } = data;
  1425. let hasSideEffects;
  1426. if (typeof sideEffects === "boolean") hasSideEffects = () => sideEffects;
  1427. else if (Array.isArray(sideEffects)) if (sideEffects.length <= 0) hasSideEffects = () => false;
  1428. else hasSideEffects = createFilter$1(sideEffects.map((sideEffect) => {
  1429. if (sideEffect.includes("/")) return sideEffect;
  1430. return `**/${sideEffect}`;
  1431. }), null, { resolve: pkgDir });
  1432. else hasSideEffects = () => null;
  1433. const resolvedCache = {};
  1434. return {
  1435. dir: pkgDir,
  1436. data,
  1437. hasSideEffects,
  1438. setResolvedCache(key, entry, options) {
  1439. resolvedCache[getResolveCacheKey(key, options)] = entry;
  1440. },
  1441. getResolvedCache(key, options) {
  1442. return resolvedCache[getResolveCacheKey(key, options)];
  1443. }
  1444. };
  1445. }
  1446. function getResolveCacheKey(key, options) {
  1447. return [
  1448. key,
  1449. options.isRequire ? "1" : "0",
  1450. options.conditions.join("_"),
  1451. options.extensions.join("_"),
  1452. options.mainFields.join("_")
  1453. ].join("|");
  1454. }
  1455. function findNearestNodeModules(basedir) {
  1456. while (basedir) {
  1457. const pkgPath = path.join(basedir, "node_modules");
  1458. if (tryStatSync(pkgPath)?.isDirectory()) return pkgPath;
  1459. const nextBasedir = path.dirname(basedir);
  1460. if (nextBasedir === basedir) break;
  1461. basedir = nextBasedir;
  1462. }
  1463. return null;
  1464. }
  1465. function watchPackageDataPlugin(packageCache) {
  1466. const watchQueue = /* @__PURE__ */ new Set();
  1467. const watchedDirs = /* @__PURE__ */ new Set();
  1468. const watchFileStub = (id) => {
  1469. watchQueue.add(id);
  1470. };
  1471. let watchFile = watchFileStub;
  1472. const setPackageData = packageCache.set.bind(packageCache);
  1473. packageCache.set = (id, pkg) => {
  1474. if (!isInNodeModules(pkg.dir) && !watchedDirs.has(pkg.dir)) {
  1475. watchedDirs.add(pkg.dir);
  1476. watchFile(path.join(pkg.dir, "package.json"));
  1477. }
  1478. return setPackageData(id, pkg);
  1479. };
  1480. return {
  1481. name: "vite:watch-package-data",
  1482. buildStart() {
  1483. watchFile = this.addWatchFile.bind(this);
  1484. watchQueue.forEach(watchFile);
  1485. watchQueue.clear();
  1486. },
  1487. buildEnd() {
  1488. watchFile = watchFileStub;
  1489. },
  1490. watchChange(id) {
  1491. if (id.endsWith("/package.json")) invalidatePackageData(packageCache, path.normalize(id));
  1492. }
  1493. };
  1494. }
  1495. /**
  1496. * Get cached `resolvePackageData` value based on `basedir`. When one is found,
  1497. * and we've already traversed some directories between `basedir` and `originalBasedir`,
  1498. * we cache the value for those in-between directories as well.
  1499. *
  1500. * This makes it so the fs is only read once for a shared `basedir`.
  1501. */
  1502. function getRpdCache(packageCache, pkgName, basedir, originalBasedir, preserveSymlinks) {
  1503. const cacheKey = getRpdCacheKey(pkgName, basedir, preserveSymlinks);
  1504. const pkgData = packageCache.get(cacheKey);
  1505. if (pkgData) {
  1506. traverseBetweenDirs(originalBasedir, basedir, (dir) => {
  1507. packageCache.set(getRpdCacheKey(pkgName, dir, preserveSymlinks), pkgData);
  1508. });
  1509. return pkgData;
  1510. }
  1511. }
  1512. function setRpdCache(packageCache, pkgData, pkgName, basedir, originalBasedir, preserveSymlinks) {
  1513. packageCache.set(getRpdCacheKey(pkgName, basedir, preserveSymlinks), pkgData);
  1514. traverseBetweenDirs(originalBasedir, basedir, (dir) => {
  1515. packageCache.set(getRpdCacheKey(pkgName, dir, preserveSymlinks), pkgData);
  1516. });
  1517. }
  1518. function getRpdCacheKey(pkgName, basedir, preserveSymlinks) {
  1519. return `rpd_${pkgName}_${basedir}_${preserveSymlinks}`;
  1520. }
  1521. /**
  1522. * Get cached `findNearestPackageData` value based on `basedir`. When one is found,
  1523. * and we've already traversed some directories between `basedir` and `originalBasedir`,
  1524. * we cache the value for those in-between directories as well.
  1525. *
  1526. * This makes it so the fs is only read once for a shared `basedir`.
  1527. */
  1528. function getFnpdCache(packageCache, basedir, originalBasedir) {
  1529. const cacheKey = getFnpdCacheKey(basedir);
  1530. const pkgData = packageCache.get(cacheKey);
  1531. if (pkgData) {
  1532. traverseBetweenDirs(originalBasedir, basedir, (dir) => {
  1533. packageCache.set(getFnpdCacheKey(dir), pkgData);
  1534. });
  1535. return pkgData;
  1536. }
  1537. }
  1538. function setFnpdCache(packageCache, pkgData, basedir, originalBasedir) {
  1539. packageCache.set(getFnpdCacheKey(basedir), pkgData);
  1540. traverseBetweenDirs(originalBasedir, basedir, (dir) => {
  1541. packageCache.set(getFnpdCacheKey(dir), pkgData);
  1542. });
  1543. }
  1544. function getFnpdCacheKey(basedir) {
  1545. return `fnpd_${basedir}`;
  1546. }
  1547. /**
  1548. * Traverse between `longerDir` (inclusive) and `shorterDir` (exclusive) and call `cb` for each dir.
  1549. * @param longerDir Longer dir path, e.g. `/User/foo/bar/baz`
  1550. * @param shorterDir Shorter dir path, e.g. `/User/foo`
  1551. */
  1552. function traverseBetweenDirs(longerDir, shorterDir, cb) {
  1553. while (longerDir !== shorterDir) {
  1554. cb(longerDir);
  1555. longerDir = path.dirname(longerDir);
  1556. }
  1557. }
  1558. //#endregion
  1559. //#region src/node/utils.ts
  1560. var import_picocolors = /* @__PURE__ */ __toESM(require_picocolors(), 1);
  1561. init_node();
  1562. const createFilter$1 = createFilter$2;
  1563. const replaceSlashOrColonRE = /[/:]/g;
  1564. const replaceDotRE = /\./g;
  1565. const replaceNestedIdRE = /\s*>\s*/g;
  1566. const replaceHashRE = /#/g;
  1567. const flattenId = (id) => {
  1568. return limitFlattenIdLength(id.replace(replaceSlashOrColonRE, "_").replace(replaceDotRE, "__").replace(replaceNestedIdRE, "___").replace(replaceHashRE, "____"));
  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 internalPrefixes = [
  1689. FS_PREFIX,
  1690. VALID_ID_PREFIX,
  1691. CLIENT_PUBLIC_PATH,
  1692. ENV_PUBLIC_PATH
  1693. ];
  1694. const InternalPrefixRE = new RegExp(`^(?:${internalPrefixes.join("|")})`);
  1695. const trailingSeparatorRE = /[?&]$/;
  1696. const isImportRequest = (url) => importQueryRE.test(url);
  1697. const isInternalRequest = (url) => InternalPrefixRE.test(url);
  1698. function removeImportQuery(url) {
  1699. return url.replace(importQueryRE, "$1").replace(trailingSeparatorRE, "");
  1700. }
  1701. function removeDirectQuery(url) {
  1702. return url.replace(directRequestRE$1, "$1").replace(trailingSeparatorRE, "");
  1703. }
  1704. const urlRE$1 = /(\?|&)url(?:&|$)/;
  1705. const rawRE$1 = /(\?|&)raw(?:&|$)/;
  1706. function removeUrlQuery(url) {
  1707. return url.replace(urlRE$1, "$1").replace(trailingSeparatorRE, "");
  1708. }
  1709. function injectQuery(url, queryToInject) {
  1710. const { file, postfix } = splitFileAndPostfix(url);
  1711. return `${isWindows ? slash(file) : file}?${queryToInject}${postfix[0] === "?" ? `&${postfix.slice(1)}` : postfix}`;
  1712. }
  1713. const timestampRE = /\bt=\d{13}&?\b/;
  1714. function removeTimestampQuery(url) {
  1715. return url.replace(timestampRE, "").replace(trailingSeparatorRE, "");
  1716. }
  1717. async function asyncReplace(input, re, replacer) {
  1718. let match;
  1719. let remaining = input;
  1720. let rewritten = "";
  1721. while (match = re.exec(remaining)) {
  1722. rewritten += remaining.slice(0, match.index);
  1723. rewritten += await replacer(match);
  1724. remaining = remaining.slice(match.index + match[0].length);
  1725. }
  1726. rewritten += remaining;
  1727. return rewritten;
  1728. }
  1729. function timeFrom(start, subtract = 0) {
  1730. const time = performance$1.now() - start - subtract;
  1731. const timeString = (time.toFixed(2) + `ms`).padEnd(5, " ");
  1732. if (time < 10) return import_picocolors.default.green(timeString);
  1733. else if (time < 50) return import_picocolors.default.yellow(timeString);
  1734. else return import_picocolors.default.red(timeString);
  1735. }
  1736. /**
  1737. * pretty url for logging.
  1738. */
  1739. function prettifyUrl(url, root) {
  1740. url = removeTimestampQuery(url);
  1741. const isAbsoluteFile = url.startsWith(root);
  1742. if (isAbsoluteFile || url.startsWith(FS_PREFIX)) {
  1743. const file = path.posix.relative(root, isAbsoluteFile ? url : fsPathFromId(url));
  1744. return import_picocolors.default.dim(file);
  1745. } else return import_picocolors.default.dim(url);
  1746. }
  1747. function isObject$1(value) {
  1748. return Object.prototype.toString.call(value) === "[object Object]";
  1749. }
  1750. function isDefined(value) {
  1751. return value != null;
  1752. }
  1753. function tryStatSync(file) {
  1754. try {
  1755. return fs.statSync(file, { throwIfNoEntry: false });
  1756. } catch {}
  1757. }
  1758. function lookupFile(dir, fileNames) {
  1759. while (dir) {
  1760. for (const fileName of fileNames) {
  1761. const fullPath = path.join(dir, fileName);
  1762. if (tryStatSync(fullPath)?.isFile()) return fullPath;
  1763. }
  1764. const parentDir = path.dirname(dir);
  1765. if (parentDir === dir) return;
  1766. dir = parentDir;
  1767. }
  1768. }
  1769. function isFilePathESM(filePath, packageCache) {
  1770. if (/\.m[jt]s$/.test(filePath)) return true;
  1771. else if (/\.c[jt]s$/.test(filePath)) return false;
  1772. else try {
  1773. return findNearestPackageData(path.dirname(filePath), packageCache)?.data.type === "module";
  1774. } catch {
  1775. return false;
  1776. }
  1777. }
  1778. const splitRE = /\r?\n/g;
  1779. const range = 2;
  1780. function pad(source, n = 2) {
  1781. return source.split(splitRE).map((l) => ` `.repeat(n) + l).join(`\n`);
  1782. }
  1783. function posToNumber(source, pos) {
  1784. if (typeof pos === "number") return pos;
  1785. const lines = source.split(splitRE);
  1786. const { line, column } = pos;
  1787. let start = 0;
  1788. for (let i = 0; i < line - 1 && i < lines.length; i++) start += lines[i].length + 1;
  1789. return start + column;
  1790. }
  1791. function numberToPos(source, offset) {
  1792. if (typeof offset !== "number") return offset;
  1793. if (offset > source.length) throw new Error(`offset is longer than source length! offset ${offset} > length ${source.length}`);
  1794. const lines = source.slice(0, offset).split(splitRE);
  1795. return {
  1796. line: lines.length,
  1797. column: lines[lines.length - 1].length
  1798. };
  1799. }
  1800. const MAX_DISPLAY_LEN = 120;
  1801. const ELLIPSIS = "...";
  1802. function generateCodeFrame(source, start = 0, end) {
  1803. start = Math.max(posToNumber(source, start), 0);
  1804. end = Math.min(end !== void 0 ? posToNumber(source, end) : start, source.length);
  1805. const lastPosLine = end !== void 0 ? numberToPos(source, end).line : numberToPos(source, start).line + range;
  1806. const lineNumberWidth = Math.max(3, String(lastPosLine).length + 1);
  1807. const lines = source.split(splitRE);
  1808. let count = 0;
  1809. const res = [];
  1810. for (let i = 0; i < lines.length; i++) {
  1811. count += lines[i].length;
  1812. if (count >= start) {
  1813. for (let j = i - range; j <= i + range || end > count; j++) {
  1814. if (j < 0 || j >= lines.length) continue;
  1815. const line = j + 1;
  1816. const lineLength = lines[j].length;
  1817. const pad = Math.max(start - (count - lineLength), 0);
  1818. const underlineLength = Math.max(1, end > count ? lineLength - pad : end - start);
  1819. let displayLine = lines[j];
  1820. let underlinePad = pad;
  1821. if (lineLength > MAX_DISPLAY_LEN) {
  1822. let startIdx = 0;
  1823. if (j === i) {
  1824. if (underlineLength > MAX_DISPLAY_LEN) startIdx = pad;
  1825. else {
  1826. const center = pad + Math.floor(underlineLength / 2);
  1827. startIdx = Math.max(0, center - Math.floor(MAX_DISPLAY_LEN / 2));
  1828. }
  1829. underlinePad = Math.max(0, pad - startIdx) + (startIdx > 0 ? 3 : 0);
  1830. }
  1831. const prefix = startIdx > 0 ? ELLIPSIS : "";
  1832. const suffix = lineLength - startIdx > MAX_DISPLAY_LEN ? ELLIPSIS : "";
  1833. const sliceLen = MAX_DISPLAY_LEN - prefix.length - suffix.length;
  1834. displayLine = prefix + displayLine.slice(startIdx, startIdx + sliceLen) + suffix;
  1835. }
  1836. res.push(`${line}${" ".repeat(lineNumberWidth - String(line).length)}| ${displayLine}`);
  1837. if (j === i) {
  1838. const underline = "^".repeat(Math.min(underlineLength, MAX_DISPLAY_LEN));
  1839. res.push(`${" ".repeat(lineNumberWidth)}| ` + " ".repeat(underlinePad) + underline);
  1840. } else if (j > i) {
  1841. if (end > count) {
  1842. const length = Math.max(Math.min(end - count, lineLength), 1);
  1843. const underline = "^".repeat(Math.min(length, MAX_DISPLAY_LEN));
  1844. res.push(`${" ".repeat(lineNumberWidth)}| ` + underline);
  1845. }
  1846. count += lineLength + 1;
  1847. }
  1848. }
  1849. break;
  1850. }
  1851. count++;
  1852. }
  1853. return res.join("\n");
  1854. }
  1855. function isFileReadable(filename) {
  1856. if (!tryStatSync(filename)) return false;
  1857. try {
  1858. fs.accessSync(filename, fs.constants.R_OK);
  1859. return true;
  1860. } catch {
  1861. return false;
  1862. }
  1863. }
  1864. const splitFirstDirRE = /(.+?)[\\/](.+)/;
  1865. /**
  1866. * Delete every file and subdirectory. **The given directory must exist.**
  1867. * Pass an optional `skip` array to preserve files under the root directory.
  1868. */
  1869. function emptyDir(dir, skip) {
  1870. const skipInDir = [];
  1871. let nested = null;
  1872. if (skip?.length) for (const file of skip) if (path.dirname(file) !== ".") {
  1873. const matched = splitFirstDirRE.exec(file);
  1874. if (matched) {
  1875. nested ??= /* @__PURE__ */ new Map();
  1876. const [, nestedDir, skipPath] = matched;
  1877. let nestedSkip = nested.get(nestedDir);
  1878. if (!nestedSkip) {
  1879. nestedSkip = [];
  1880. nested.set(nestedDir, nestedSkip);
  1881. }
  1882. if (!nestedSkip.includes(skipPath)) nestedSkip.push(skipPath);
  1883. }
  1884. } else skipInDir.push(file);
  1885. for (const file of fs.readdirSync(dir)) {
  1886. if (skipInDir.includes(file)) continue;
  1887. if (nested?.has(file)) emptyDir(path.resolve(dir, file), nested.get(file));
  1888. else fs.rmSync(path.resolve(dir, file), {
  1889. recursive: true,
  1890. force: true
  1891. });
  1892. }
  1893. }
  1894. function copyDir(srcDir, destDir) {
  1895. fs.mkdirSync(destDir, { recursive: true });
  1896. for (const file of fs.readdirSync(srcDir)) {
  1897. const srcFile = path.resolve(srcDir, file);
  1898. if (srcFile === destDir) continue;
  1899. const destFile = path.resolve(destDir, file);
  1900. if (fs.statSync(srcFile).isDirectory()) copyDir(srcFile, destFile);
  1901. else fs.copyFileSync(srcFile, destFile);
  1902. }
  1903. }
  1904. const ERR_SYMLINK_IN_RECURSIVE_READDIR = "ERR_SYMLINK_IN_RECURSIVE_READDIR";
  1905. async function recursiveReaddir(dir) {
  1906. if (!fs.existsSync(dir)) return [];
  1907. let dirents;
  1908. try {
  1909. dirents = await fsp.readdir(dir, { withFileTypes: true });
  1910. } catch (e) {
  1911. if (e.code === "EACCES") return [];
  1912. throw e;
  1913. }
  1914. if (dirents.some((dirent) => dirent.isSymbolicLink())) {
  1915. const err = /* @__PURE__ */ new Error("Symbolic links are not supported in recursiveReaddir");
  1916. err.code = ERR_SYMLINK_IN_RECURSIVE_READDIR;
  1917. throw err;
  1918. }
  1919. return (await Promise.all(dirents.map((dirent) => {
  1920. const res = path.resolve(dir, dirent.name);
  1921. return dirent.isDirectory() ? recursiveReaddir(res) : normalizePath(res);
  1922. }))).flat(1);
  1923. }
  1924. let safeRealpathSync = isWindows ? windowsSafeRealPathSync : fs.realpathSync.native;
  1925. const windowsNetworkMap = /* @__PURE__ */ new Map();
  1926. function windowsMappedRealpathSync(path) {
  1927. const realPath = fs.realpathSync.native(path);
  1928. if (realPath.startsWith("\\\\")) {
  1929. for (const [network, volume] of windowsNetworkMap) if (realPath.startsWith(network)) return realPath.replace(network, volume);
  1930. }
  1931. return realPath;
  1932. }
  1933. const parseNetUseRE = /^\w* +(\w:) +([^ ]+)\s/;
  1934. let firstSafeRealPathSyncRun = false;
  1935. function windowsSafeRealPathSync(path) {
  1936. if (!firstSafeRealPathSyncRun) {
  1937. optimizeSafeRealPathSync();
  1938. firstSafeRealPathSyncRun = true;
  1939. }
  1940. return fs.realpathSync(path);
  1941. }
  1942. function optimizeSafeRealPathSync() {
  1943. try {
  1944. fs.realpathSync.native(path.resolve("./"));
  1945. } catch (error) {
  1946. if (error.message.includes("EISDIR: illegal operation on a directory")) {
  1947. safeRealpathSync = fs.realpathSync;
  1948. return;
  1949. }
  1950. }
  1951. exec("net use", (error, stdout) => {
  1952. if (error) return;
  1953. const lines = stdout.split("\n");
  1954. for (const line of lines) {
  1955. const m = parseNetUseRE.exec(line);
  1956. if (m) windowsNetworkMap.set(m[2], m[1]);
  1957. }
  1958. if (windowsNetworkMap.size === 0) safeRealpathSync = fs.realpathSync.native;
  1959. else safeRealpathSync = windowsMappedRealpathSync;
  1960. });
  1961. }
  1962. function ensureWatchedFile(watcher, file, root) {
  1963. if (file && !file.startsWith(withTrailingSlash(root)) && !file.includes("\0") && fs.existsSync(file)) watcher.add(path.resolve(file));
  1964. }
  1965. function joinSrcset(ret) {
  1966. return ret.map(({ url, descriptor }) => url + (descriptor ? ` ${descriptor}` : "")).join(", ");
  1967. }
  1968. /**
  1969. This regex represents a loose rule of an “image candidate string” and "image set options".
  1970. @see https://html.spec.whatwg.org/multipage/images.html#srcset-attribute
  1971. @see https://drafts.csswg.org/css-images-4/#image-set-notation
  1972. The Regex has named capturing groups `url` and `descriptor`.
  1973. The `url` group can be:
  1974. * any CSS function
  1975. * CSS string (single or double-quoted)
  1976. * URL string (unquoted)
  1977. The `descriptor` is anything after the space and before the comma.
  1978. */
  1979. const imageCandidateRegex = /(?:^|\s|(?<=,))(?<url>[\w-]+\([^)]*\)|"[^"]*"|'[^']*'|[^,]\S*[^,])\s*(?:\s(?<descriptor>\w[^,]+))?(?:,|$)/g;
  1980. const escapedSpaceCharacters = /(?: |\\t|\\n|\\f|\\r)+/g;
  1981. function parseSrcset(string) {
  1982. const matches = string.trim().replace(escapedSpaceCharacters, " ").replace(/\r?\n/, "").replace(/,\s+/, ", ").replaceAll(/\s+/g, " ").matchAll(imageCandidateRegex);
  1983. return Array.from(matches, ({ groups }) => ({
  1984. url: groups?.url?.trim() ?? "",
  1985. descriptor: groups?.descriptor?.trim() ?? ""
  1986. })).filter(({ url }) => !!url);
  1987. }
  1988. function processSrcSet(srcs, replacer) {
  1989. return Promise.all(parseSrcset(srcs).map(async ({ url, descriptor }) => ({
  1990. url: await replacer({
  1991. url,
  1992. descriptor
  1993. }),
  1994. descriptor
  1995. }))).then(joinSrcset);
  1996. }
  1997. function processSrcSetSync(srcs, replacer) {
  1998. return joinSrcset(parseSrcset(srcs).map(({ url, descriptor }) => ({
  1999. url: replacer({
  2000. url,
  2001. descriptor
  2002. }),
  2003. descriptor
  2004. })));
  2005. }
  2006. const windowsDriveRE = /^[A-Z]:/;
  2007. const replaceWindowsDriveRE = /^([A-Z]):\//;
  2008. const linuxAbsolutePathRE = /^\/[^/]/;
  2009. function escapeToLinuxLikePath(path) {
  2010. if (windowsDriveRE.test(path)) return path.replace(replaceWindowsDriveRE, "/windows/$1/");
  2011. if (linuxAbsolutePathRE.test(path)) return `/linux${path}`;
  2012. return path;
  2013. }
  2014. const revertWindowsDriveRE = /^\/windows\/([A-Z])\//;
  2015. function unescapeToLinuxLikePath(path) {
  2016. if (path.startsWith("/linux/")) return path.slice(6);
  2017. if (path.startsWith("/windows/")) return path.replace(revertWindowsDriveRE, "$1:/");
  2018. return path;
  2019. }
  2020. const nullSourceMap = {
  2021. names: [],
  2022. sources: [],
  2023. mappings: "",
  2024. version: 3
  2025. };
  2026. /**
  2027. * Combines multiple sourcemaps into a single sourcemap.
  2028. * Note that the length of sourcemapList must be 2.
  2029. */
  2030. function combineSourcemaps(filename, sourcemapList) {
  2031. if (sourcemapList.length === 0 || sourcemapList.every((m) => m.sources.length === 0)) return { ...nullSourceMap };
  2032. sourcemapList = sourcemapList.map((sourcemap) => {
  2033. const newSourcemaps = { ...sourcemap };
  2034. newSourcemaps.sources = sourcemap.sources.map((source) => source ? escapeToLinuxLikePath(source) : null);
  2035. if (sourcemap.sourceRoot) newSourcemaps.sourceRoot = escapeToLinuxLikePath(sourcemap.sourceRoot);
  2036. return newSourcemaps;
  2037. });
  2038. const escapedFilename = escapeToLinuxLikePath(filename);
  2039. let map;
  2040. let mapIndex = 1;
  2041. if (sourcemapList.slice(0, -1).find((m) => m.sources.length !== 1) === void 0) map = remapping(sourcemapList, () => null);
  2042. else map = remapping(sourcemapList[0], function loader(sourcefile) {
  2043. if (sourcefile === escapedFilename && sourcemapList[mapIndex]) return sourcemapList[mapIndex++];
  2044. else return null;
  2045. });
  2046. if (!map.file) delete map.file;
  2047. map.sources = map.sources.map((source) => source ? unescapeToLinuxLikePath(source) : source);
  2048. map.file = filename;
  2049. return map;
  2050. }
  2051. function unique(arr) {
  2052. return Array.from(new Set(arr));
  2053. }
  2054. /**
  2055. * Returns resolved localhost address when `dns.lookup` result differs from DNS
  2056. *
  2057. * `dns.lookup` result is same when defaultResultOrder is `verbatim`.
  2058. * Even if defaultResultOrder is `ipv4first`, `dns.lookup` result maybe same.
  2059. * For example, when IPv6 is not supported on that machine/network.
  2060. */
  2061. async function getLocalhostAddressIfDiffersFromDNS() {
  2062. const [nodeResult, dnsResult] = await Promise.all([promises.lookup("localhost"), promises.lookup("localhost", { verbatim: true })]);
  2063. return nodeResult.family === dnsResult.family && nodeResult.address === dnsResult.address ? void 0 : nodeResult.address;
  2064. }
  2065. function diffDnsOrderChange(oldUrls, newUrls) {
  2066. return !(oldUrls === newUrls || oldUrls && newUrls && arrayEqual(oldUrls.local, newUrls.local) && arrayEqual(oldUrls.network, newUrls.network));
  2067. }
  2068. async function resolveHostname(optionsHost) {
  2069. let host;
  2070. if (optionsHost === void 0 || optionsHost === false) host = "localhost";
  2071. else if (optionsHost === true) host = void 0;
  2072. else host = optionsHost;
  2073. let name = host === void 0 || wildcardHosts.has(host) ? "localhost" : host;
  2074. if (host === "localhost") {
  2075. const localhostAddr = await getLocalhostAddressIfDiffersFromDNS();
  2076. if (localhostAddr) name = localhostAddr;
  2077. }
  2078. return {
  2079. host,
  2080. name
  2081. };
  2082. }
  2083. function extractHostnamesFromCerts(certs) {
  2084. const certList = certs ? arraify(certs) : [];
  2085. if (certList.length === 0) return [];
  2086. return unique(certList.map((cert) => {
  2087. try {
  2088. return new crypto.X509Certificate(cert);
  2089. } catch {
  2090. return null;
  2091. }
  2092. }).flatMap((cert) => cert?.subjectAltName ? extractHostnamesFromSubjectAltName(cert.subjectAltName) : []));
  2093. }
  2094. function resolveServerUrls(server, options, hostname, httpsOptions, config) {
  2095. const address = server.address();
  2096. const isAddressInfo = (x) => x?.address;
  2097. if (!isAddressInfo(address)) return {
  2098. local: [],
  2099. network: []
  2100. };
  2101. const local = [];
  2102. const network = [];
  2103. const protocol = options.https ? "https" : "http";
  2104. const port = address.port;
  2105. const base = config.rawBase === "./" || config.rawBase === "" ? "/" : config.rawBase;
  2106. if (hostname.host !== void 0 && !wildcardHosts.has(hostname.host)) {
  2107. let hostnameName = hostname.name;
  2108. if (hostnameName.includes(":")) hostnameName = `[${hostnameName}]`;
  2109. const address = `${protocol}://${hostnameName}:${port}${base}`;
  2110. if (loopbackHosts.has(hostname.host)) local.push(address);
  2111. else network.push(address);
  2112. } else Object.values(os.networkInterfaces()).flatMap((nInterface) => nInterface ?? []).filter((detail) => detail.address && detail.family === "IPv4").forEach((detail) => {
  2113. let host = detail.address.replace("127.0.0.1", hostname.name);
  2114. if (host.includes(":")) host = `[${host}]`;
  2115. const url = `${protocol}://${host}:${port}${base}`;
  2116. if (detail.address.includes("127.0.0.1")) local.push(url);
  2117. else network.push(url);
  2118. });
  2119. const hostnamesFromCert = extractHostnamesFromCerts(httpsOptions?.cert);
  2120. if (hostnamesFromCert.length > 0) {
  2121. const existings = new Set([...local, ...network]);
  2122. local.push(...hostnamesFromCert.map((hostname) => `${protocol}://${hostname}:${port}${base}`).filter((url) => !existings.has(url)));
  2123. }
  2124. return {
  2125. local,
  2126. network
  2127. };
  2128. }
  2129. function extractHostnamesFromSubjectAltName(subjectAltName) {
  2130. const hostnames = [];
  2131. let remaining = subjectAltName;
  2132. while (remaining) {
  2133. const nameEndIndex = remaining.indexOf(":");
  2134. const name = remaining.slice(0, nameEndIndex);
  2135. remaining = remaining.slice(nameEndIndex + 1);
  2136. if (!remaining) break;
  2137. const isQuoted = remaining[0] === "\"";
  2138. let value;
  2139. if (isQuoted) {
  2140. const endQuoteIndex = remaining.indexOf("\"", 1);
  2141. value = JSON.parse(remaining.slice(0, endQuoteIndex + 1));
  2142. remaining = remaining.slice(endQuoteIndex + 1);
  2143. } else {
  2144. const maybeEndIndex = remaining.indexOf(",");
  2145. const endIndex = maybeEndIndex === -1 ? remaining.length : maybeEndIndex;
  2146. value = remaining.slice(0, endIndex);
  2147. remaining = remaining.slice(endIndex);
  2148. }
  2149. remaining = remaining.slice(1).trimStart();
  2150. if (name === "DNS" && value !== "[::1]" && !(value.startsWith("*.") && net.isIPv4(value.slice(2)))) hostnames.push(value.replace("*", "vite"));
  2151. }
  2152. return hostnames;
  2153. }
  2154. function arraify(target) {
  2155. return Array.isArray(target) ? target : [target];
  2156. }
  2157. const multilineCommentsRE = /\/\*[^*]*\*+(?:[^/*][^*]*\*+)*\//g;
  2158. const singlelineCommentsRE = /\/\/.*/g;
  2159. const requestQuerySplitRE = /\?(?!.*[/|}])/;
  2160. const requestQueryMaybeEscapedSplitRE = /\\?\?(?!.*[/|}])/;
  2161. const blankReplacer = (match) => " ".repeat(match.length);
  2162. function getHash(text, length = 8) {
  2163. const h = crypto.hash("sha256", text, "hex").substring(0, length);
  2164. if (length <= 64) return h;
  2165. return h.padEnd(length, "_");
  2166. }
  2167. function emptyCssComments(raw) {
  2168. return raw.replace(multilineCommentsRE, blankReplacer);
  2169. }
  2170. function backwardCompatibleWorkerPlugins(plugins) {
  2171. if (Array.isArray(plugins)) return plugins;
  2172. if (typeof plugins === "function") return plugins();
  2173. return [];
  2174. }
  2175. function deepClone(value) {
  2176. if (Array.isArray(value)) return value.map((v) => deepClone(v));
  2177. if (isObject$1(value)) {
  2178. const cloned = {};
  2179. for (const key in value) cloned[key] = deepClone(value[key]);
  2180. return cloned;
  2181. }
  2182. if (typeof value === "function") return value;
  2183. if (value instanceof RegExp) return new RegExp(value);
  2184. if (typeof value === "object" && value != null) throw new Error("Cannot deep clone non-plain object");
  2185. return value;
  2186. }
  2187. function mergeWithDefaultsRecursively(defaults, values) {
  2188. const merged = defaults;
  2189. for (const key in values) {
  2190. const value = values[key];
  2191. if (value === void 0) continue;
  2192. const existing = merged[key];
  2193. if (existing === void 0) {
  2194. merged[key] = value;
  2195. continue;
  2196. }
  2197. if (isObject$1(existing) && isObject$1(value)) {
  2198. merged[key] = mergeWithDefaultsRecursively(existing, value);
  2199. continue;
  2200. }
  2201. merged[key] = value;
  2202. }
  2203. return merged;
  2204. }
  2205. const environmentPathRE = /^environments\.[^.]+$/;
  2206. function mergeWithDefaults(defaults, values) {
  2207. return mergeWithDefaultsRecursively(deepClone(defaults), values);
  2208. }
  2209. const runtimeDeprecatedPath = new Set(["optimizeDeps", "ssr.optimizeDeps"]);
  2210. const rollupOptionsDeprecationCall = () => {
  2211. const method = process.env.VITE_DEPRECATION_TRACE ? "trace" : "warn";
  2212. 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."));
  2213. };
  2214. function setupRollupOptionCompat(buildConfig, path) {
  2215. buildConfig.rolldownOptions ??= buildConfig.rollupOptions;
  2216. if (runtimeDeprecatedPath.has(path) && buildConfig.rollupOptions && buildConfig.rolldownOptions !== buildConfig.rollupOptions) rollupOptionsDeprecationCall();
  2217. Object.defineProperty(buildConfig, "rollupOptions", {
  2218. get() {
  2219. return buildConfig.rolldownOptions;
  2220. },
  2221. set(newValue) {
  2222. if (runtimeDeprecatedPath.has(path)) rollupOptionsDeprecationCall();
  2223. buildConfig.rolldownOptions = newValue;
  2224. },
  2225. configurable: true,
  2226. enumerable: true
  2227. });
  2228. }
  2229. const rollupOptionsRootPaths = new Set([
  2230. "build",
  2231. "worker",
  2232. "optimizeDeps",
  2233. "ssr.optimizeDeps"
  2234. ]);
  2235. /**
  2236. * Sets up `rollupOptions` compat proxies for an environment.
  2237. */
  2238. function setupRollupOptionCompatForEnvironment(environment) {
  2239. if (!isObject$1(environment)) return environment;
  2240. const merged = { ...environment };
  2241. if (isObject$1(merged.build)) setupRollupOptionCompat(merged.build, "build");
  2242. return merged;
  2243. }
  2244. function hasBothRollupOptionsAndRolldownOptions(options) {
  2245. for (const opt of [
  2246. options.build,
  2247. options.worker,
  2248. options.optimizeDeps,
  2249. options.ssr?.optimizeDeps
  2250. ]) if (opt != null && opt.rollupOptions != null && opt.rolldownOptions != null) return true;
  2251. return false;
  2252. }
  2253. function mergeConfigRecursively(defaults, overrides, rootPath) {
  2254. const merged = { ...defaults };
  2255. if (rollupOptionsRootPaths.has(rootPath)) setupRollupOptionCompat(merged, rootPath);
  2256. for (const key in overrides) {
  2257. const value = overrides[key];
  2258. if (value == null) continue;
  2259. let existing = merged[key];
  2260. if (key === "rollupOptions" && rollupOptionsRootPaths.has(rootPath)) {
  2261. if (overrides.rolldownOptions) continue;
  2262. existing = merged.rolldownOptions;
  2263. }
  2264. if (existing == null) {
  2265. if (rootPath === "" && key === "environments" && isObject$1(value)) {
  2266. const environments = { ...value };
  2267. for (const envName in environments) environments[envName] = setupRollupOptionCompatForEnvironment(environments[envName]);
  2268. merged[key] = environments;
  2269. } else if (rootPath === "environments") merged[key] = setupRollupOptionCompatForEnvironment(value);
  2270. else merged[key] = value;
  2271. continue;
  2272. }
  2273. if (key === "alias" && (rootPath === "resolve" || rootPath === "")) {
  2274. merged[key] = mergeAlias(existing, value);
  2275. continue;
  2276. } else if (key === "assetsInclude" && rootPath === "") {
  2277. merged[key] = [].concat(existing, value);
  2278. continue;
  2279. } else if (((key === "noExternal" || key === "external") && (rootPath === "ssr" || rootPath === "resolve") || key === "allowedHosts" && rootPath === "server") && (existing === true || value === true)) {
  2280. merged[key] = true;
  2281. continue;
  2282. } else if (key === "plugins" && rootPath === "worker") {
  2283. merged[key] = () => [...backwardCompatibleWorkerPlugins(existing), ...backwardCompatibleWorkerPlugins(value)];
  2284. continue;
  2285. } else if (key === "server" && rootPath === "server.hmr") {
  2286. merged[key] = value;
  2287. continue;
  2288. }
  2289. if (Array.isArray(existing) || Array.isArray(value)) {
  2290. merged[key] = [...arraify(existing), ...arraify(value)];
  2291. continue;
  2292. }
  2293. if (isObject$1(existing) && isObject$1(value)) {
  2294. merged[key] = mergeConfigRecursively(existing, value, rootPath && !environmentPathRE.test(rootPath) ? `${rootPath}.${key}` : key);
  2295. continue;
  2296. }
  2297. merged[key] = value;
  2298. }
  2299. return merged;
  2300. }
  2301. function mergeConfig(defaults, overrides, isRoot = true) {
  2302. if (typeof defaults === "function" || typeof overrides === "function") throw new Error(`Cannot merge config in form of callback`);
  2303. return mergeConfigRecursively(defaults, overrides, isRoot ? "" : ".");
  2304. }
  2305. function mergeAlias(a, b) {
  2306. if (!a) return b;
  2307. if (!b) return a;
  2308. if (isObject$1(a) && isObject$1(b)) return {
  2309. ...a,
  2310. ...b
  2311. };
  2312. return [...normalizeAlias(b), ...normalizeAlias(a)];
  2313. }
  2314. function normalizeAlias(o = []) {
  2315. return Array.isArray(o) ? o.map(normalizeSingleAlias) : Object.keys(o).map((find) => normalizeSingleAlias({
  2316. find,
  2317. replacement: o[find]
  2318. }));
  2319. }
  2320. function normalizeSingleAlias({ find, replacement, customResolver }) {
  2321. if (typeof find === "string" && find.endsWith("/") && replacement.endsWith("/")) {
  2322. find = find.slice(0, find.length - 1);
  2323. replacement = replacement.slice(0, replacement.length - 1);
  2324. }
  2325. const alias = {
  2326. find,
  2327. replacement
  2328. };
  2329. if (customResolver) alias.customResolver = customResolver;
  2330. return alias;
  2331. }
  2332. /**
  2333. * Transforms transpiled code result where line numbers aren't altered,
  2334. * so we can skip sourcemap generation during dev
  2335. */
  2336. function transformStableResult(s, id, config) {
  2337. return {
  2338. code: s.toString(),
  2339. map: config.command === "build" && config.build.sourcemap ? s.generateMap({
  2340. hires: "boundary",
  2341. source: id
  2342. }) : null
  2343. };
  2344. }
  2345. async function asyncFlatten(arr) {
  2346. do
  2347. arr = (await Promise.all(arr)).flat(Infinity);
  2348. while (arr.some((v) => v?.then));
  2349. return arr;
  2350. }
  2351. function stripBomTag(content) {
  2352. if (content.charCodeAt(0) === 65279) return content.slice(1);
  2353. return content;
  2354. }
  2355. /**
  2356. * Determine if a file is being requested with the correct case, to ensure
  2357. * consistent behavior between dev and prod and across operating systems.
  2358. */
  2359. function shouldServeFile(filePath, root) {
  2360. if (!isCaseInsensitiveFS) return true;
  2361. return hasCorrectCase(filePath, root);
  2362. }
  2363. /**
  2364. * Note that we can't use realpath here, because we don't want to follow
  2365. * symlinks.
  2366. */
  2367. function hasCorrectCase(file, assets) {
  2368. if (file === assets) return true;
  2369. const parent = path.dirname(file);
  2370. if (fs.readdirSync(parent).includes(path.basename(file))) return hasCorrectCase(parent, assets);
  2371. return false;
  2372. }
  2373. function joinUrlSegments(a, b) {
  2374. if (!a || !b) return a || b || "";
  2375. if (a.endsWith("/")) a = a.substring(0, a.length - 1);
  2376. if (b[0] !== "/") b = "/" + b;
  2377. return a + b;
  2378. }
  2379. function removeLeadingSlash(str) {
  2380. return str[0] === "/" ? str.slice(1) : str;
  2381. }
  2382. function stripBase(path, base) {
  2383. if (path === base) return "/";
  2384. const devBase = withTrailingSlash(base);
  2385. return path.startsWith(devBase) ? path.slice(devBase.length - 1) : path;
  2386. }
  2387. function arrayEqual(a, b) {
  2388. if (a === b) return true;
  2389. if (a.length !== b.length) return false;
  2390. for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;
  2391. return true;
  2392. }
  2393. function evalValue(rawValue) {
  2394. return new Function(`
  2395. var console, exports, global, module, process, require
  2396. return (\n${rawValue}\n)
  2397. `)();
  2398. }
  2399. function getNpmPackageName(importPath) {
  2400. const parts = importPath.split("/");
  2401. if (parts[0][0] === "@") {
  2402. if (!parts[1]) return null;
  2403. return `${parts[0]}/${parts[1]}`;
  2404. } else return parts[0];
  2405. }
  2406. function getPkgName(name) {
  2407. return name[0] === "@" ? name.split("/")[1] : name;
  2408. }
  2409. const escapeRegexRE = /[-/\\^$*+?.()|[\]{}]/g;
  2410. function escapeRegex(str) {
  2411. return str.replace(escapeRegexRE, "\\$&");
  2412. }
  2413. function getPackageManagerCommand(type = "install") {
  2414. const packageManager = process.env.npm_config_user_agent?.split(" ")[0].split("/")[0] || "npm";
  2415. switch (type) {
  2416. case "install": return packageManager === "npm" ? "npm install" : `${packageManager} add`;
  2417. case "uninstall": return packageManager === "npm" ? "npm uninstall" : `${packageManager} remove`;
  2418. case "update": return packageManager === "yarn" ? "yarn upgrade" : `${packageManager} update`;
  2419. default: throw new TypeError(`Unknown command type: ${type}`);
  2420. }
  2421. }
  2422. function isDevServer(server) {
  2423. return "pluginContainer" in server;
  2424. }
  2425. function createSerialPromiseQueue() {
  2426. let previousTask;
  2427. return { async run(f) {
  2428. const thisTask = f();
  2429. const depTasks = Promise.all([previousTask, thisTask]);
  2430. previousTask = depTasks;
  2431. const [, result] = await depTasks;
  2432. if (previousTask === depTasks) previousTask = void 0;
  2433. return result;
  2434. } };
  2435. }
  2436. function sortObjectKeys(obj) {
  2437. const sorted = {};
  2438. for (const key of Object.keys(obj).sort()) sorted[key] = obj[key];
  2439. return sorted;
  2440. }
  2441. function displayTime(time) {
  2442. if (time < 1e3) return `${time}ms`;
  2443. time = time / 1e3;
  2444. if (time < 60) return `${time.toFixed(2)}s`;
  2445. const mins = Math.floor(time / 60);
  2446. const seconds = Math.round(time % 60);
  2447. if (seconds === 60) return `${mins + 1}m`;
  2448. return `${mins}m${seconds < 1 ? "" : ` ${seconds}s`}`;
  2449. }
  2450. /**
  2451. * Encodes the URI path portion (ignores part after ? or #)
  2452. */
  2453. function encodeURIPath(uri) {
  2454. if (uri.startsWith("data:")) return uri;
  2455. const filePath = cleanUrl(uri);
  2456. const postfix = filePath !== uri ? uri.slice(filePath.length) : "";
  2457. return encodeURI(filePath) + postfix;
  2458. }
  2459. /**
  2460. * Like `encodeURIPath`, but only replacing `%` as `%25`. This is useful for environments
  2461. * that can handle un-encoded URIs, where `%` is the only ambiguous character.
  2462. */
  2463. function partialEncodeURIPath(uri) {
  2464. if (uri.startsWith("data:")) return uri;
  2465. const filePath = cleanUrl(uri);
  2466. const postfix = filePath !== uri ? uri.slice(filePath.length) : "";
  2467. return filePath.replaceAll("%", "%25") + postfix;
  2468. }
  2469. function decodeURIIfPossible(input) {
  2470. try {
  2471. return decodeURI(input);
  2472. } catch {
  2473. return;
  2474. }
  2475. }
  2476. const sigtermCallbacks = /* @__PURE__ */ new Set();
  2477. const parentSigtermCallback = async (signal, exitCode) => {
  2478. await Promise.all([...sigtermCallbacks].map((cb) => cb(signal, exitCode)));
  2479. };
  2480. const setupSIGTERMListener = (callback) => {
  2481. if (sigtermCallbacks.size === 0) {
  2482. process.once("SIGTERM", parentSigtermCallback);
  2483. if (process.env.CI !== "true") process.stdin.on("end", parentSigtermCallback);
  2484. }
  2485. sigtermCallbacks.add(callback);
  2486. };
  2487. const teardownSIGTERMListener = (callback) => {
  2488. sigtermCallbacks.delete(callback);
  2489. if (sigtermCallbacks.size === 0) {
  2490. process.off("SIGTERM", parentSigtermCallback);
  2491. if (process.env.CI !== "true") process.stdin.off("end", parentSigtermCallback);
  2492. }
  2493. };
  2494. function getServerUrlByHost(resolvedUrls, host) {
  2495. if (typeof host === "string") {
  2496. const matchedUrl = [...resolvedUrls?.local ?? [], ...resolvedUrls?.network ?? []].find((url) => url.includes(host));
  2497. if (matchedUrl) return matchedUrl;
  2498. }
  2499. return resolvedUrls?.local[0] ?? resolvedUrls?.network[0];
  2500. }
  2501. let lastDateNow = 0;
  2502. /**
  2503. * Similar to `Date.now()`, but strictly monotonically increasing.
  2504. *
  2505. * This function will never return the same value.
  2506. * Thus, the value may differ from the actual time.
  2507. *
  2508. * related: https://github.com/vitejs/vite/issues/19804
  2509. */
  2510. function monotonicDateNow() {
  2511. const now = Date.now();
  2512. if (now > lastDateNow) {
  2513. lastDateNow = now;
  2514. return lastDateNow;
  2515. }
  2516. lastDateNow++;
  2517. return lastDateNow;
  2518. }
  2519. //#endregion
  2520. //#region src/node/plugin.ts
  2521. async function resolveEnvironmentPlugins(environment) {
  2522. const environmentPlugins = [];
  2523. for (const plugin of environment.getTopLevelConfig().plugins) {
  2524. if (plugin.applyToEnvironment) {
  2525. const applied = await plugin.applyToEnvironment(environment);
  2526. if (!applied) continue;
  2527. if (applied !== true) {
  2528. environmentPlugins.push(...(await asyncFlatten(arraify(applied))).filter(Boolean));
  2529. continue;
  2530. }
  2531. }
  2532. environmentPlugins.push(plugin);
  2533. }
  2534. return environmentPlugins;
  2535. }
  2536. /**
  2537. * @experimental
  2538. */
  2539. function perEnvironmentPlugin(name, applyToEnvironment) {
  2540. return {
  2541. name,
  2542. applyToEnvironment
  2543. };
  2544. }
  2545. //#endregion
  2546. //#region src/node/plugins/reporter.ts
  2547. function buildReporterPlugin(config) {
  2548. return perEnvironmentPlugin("native:reporter", (env) => {
  2549. const tty = process.stdout.isTTY && !process.env.CI;
  2550. const shouldLogInfo = LogLevels[config.logLevel || "info"] >= LogLevels.info;
  2551. const assetsDir = path.join(env.config.build.assetsDir, "/");
  2552. return viteReporterPlugin({
  2553. root: env.config.root,
  2554. isTty: !!tty,
  2555. isLib: !!env.config.build.lib,
  2556. assetsDir,
  2557. chunkLimit: env.config.build.chunkSizeWarningLimit,
  2558. logInfo: shouldLogInfo ? (msg) => env.logger.info(msg) : void 0,
  2559. reportCompressedSize: env.config.build.reportCompressedSize,
  2560. warnLargeChunks: env.config.build.minify && !env.config.build.lib && env.config.consumer === "client"
  2561. });
  2562. });
  2563. }
  2564. //#endregion
  2565. //#region src/node/plugins/esbuild.ts
  2566. const debug$14 = createDebugger("vite:esbuild");
  2567. const IIFE_BEGIN_RE$1 = /(?:const|var)\s+\S+\s*=\s*\(?function\([^()]*\)\s*\{\s*"use strict";/;
  2568. const validExtensionRE$1 = /\.\w+$/;
  2569. const defaultEsbuildSupported = {
  2570. "dynamic-import": true,
  2571. "import-meta": true
  2572. };
  2573. let esbuild;
  2574. const importEsbuild$1 = () => {
  2575. esbuild ||= import("esbuild");
  2576. return esbuild;
  2577. };
  2578. let warnedTransformWithEsbuild = false;
  2579. const warnTransformWithEsbuildUsageOnce = () => {
  2580. if (warnedTransformWithEsbuild) return;
  2581. warnedTransformWithEsbuild = true;
  2582. console.warn(import_picocolors.default.yellow("`transformWithEsbuild` is deprecated and will be removed in the future. Please migrate to `transformWithOxc`."));
  2583. };
  2584. async function transformWithEsbuild(code, filename, options, inMap, config, watcher, ignoreEsbuildWarning = false) {
  2585. let loader = options?.loader;
  2586. if (!loader) {
  2587. const ext = path.extname(validExtensionRE$1.test(filename) ? filename : cleanUrl(filename)).slice(1);
  2588. if (ext === "cjs" || ext === "mjs") loader = "js";
  2589. else if (ext === "cts" || ext === "mts") loader = "ts";
  2590. else loader = ext;
  2591. }
  2592. let tsconfigRaw = options?.tsconfigRaw;
  2593. if (typeof tsconfigRaw !== "string") {
  2594. const meaningfulFields = [
  2595. "alwaysStrict",
  2596. "experimentalDecorators",
  2597. "importsNotUsedAsValues",
  2598. "jsx",
  2599. "jsxFactory",
  2600. "jsxFragmentFactory",
  2601. "jsxImportSource",
  2602. "preserveValueImports",
  2603. "target",
  2604. "useDefineForClassFields",
  2605. "verbatimModuleSyntax"
  2606. ];
  2607. const compilerOptionsForFile = {};
  2608. if (loader === "ts" || loader === "tsx") {
  2609. const result = resolveTsconfig(filename, getTSConfigResolutionCache(config));
  2610. if (result) {
  2611. const { tsconfig: loadedTsconfig, tsconfigFilePaths } = result;
  2612. if (watcher && config) for (const tsconfigFile of tsconfigFilePaths) ensureWatchedFile(watcher, tsconfigFile, config.root);
  2613. const loadedCompilerOptions = loadedTsconfig.compilerOptions ?? {};
  2614. for (const field of meaningfulFields) if (field in loadedCompilerOptions) compilerOptionsForFile[field] = loadedCompilerOptions[field];
  2615. }
  2616. }
  2617. const compilerOptions = {
  2618. ...compilerOptionsForFile,
  2619. ...tsconfigRaw?.compilerOptions
  2620. };
  2621. if (compilerOptions.useDefineForClassFields === void 0 && compilerOptions.target === void 0) compilerOptions.useDefineForClassFields = false;
  2622. if (options) {
  2623. if (options.jsx) compilerOptions.jsx = void 0;
  2624. if (options.jsxFactory) compilerOptions.jsxFactory = void 0;
  2625. if (options.jsxFragment) compilerOptions.jsxFragmentFactory = void 0;
  2626. if (options.jsxImportSource) compilerOptions.jsxImportSource = void 0;
  2627. }
  2628. tsconfigRaw = {
  2629. ...tsconfigRaw,
  2630. compilerOptions
  2631. };
  2632. }
  2633. const resolvedOptions = {
  2634. sourcemap: true,
  2635. sourcefile: filename,
  2636. ...options,
  2637. loader,
  2638. tsconfigRaw
  2639. };
  2640. delete resolvedOptions.include;
  2641. delete resolvedOptions.exclude;
  2642. delete resolvedOptions.jsxInject;
  2643. let transform;
  2644. try {
  2645. transform = (await importEsbuild$1()).transform;
  2646. } catch (e) {
  2647. 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 });
  2648. }
  2649. if (!ignoreEsbuildWarning) warnTransformWithEsbuildUsageOnce();
  2650. try {
  2651. const result = await transform(code, resolvedOptions);
  2652. let map;
  2653. if (inMap && resolvedOptions.sourcemap) {
  2654. const nextMap = JSON.parse(result.map);
  2655. nextMap.sourcesContent = [];
  2656. map = combineSourcemaps(filename, [nextMap, inMap]);
  2657. } else map = resolvedOptions.sourcemap && resolvedOptions.sourcemap !== "inline" ? JSON.parse(result.map) : { mappings: "" };
  2658. return {
  2659. ...result,
  2660. map
  2661. };
  2662. } catch (e) {
  2663. debug$14?.(`esbuild error with options used: `, resolvedOptions);
  2664. if (e.errors) {
  2665. e.frame = "";
  2666. e.errors.forEach((m) => {
  2667. 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.";
  2668. e.frame += `\n` + prettifyMessage(m, code);
  2669. });
  2670. e.loc = e.errors[0].location;
  2671. }
  2672. throw e;
  2673. }
  2674. }
  2675. const rollupToEsbuildFormatMap = {
  2676. es: "esm",
  2677. cjs: "cjs",
  2678. iife: void 0
  2679. };
  2680. const injectEsbuildHelpers = (esbuildCode, format) => {
  2681. const contentIndex = format === "iife" ? Math.max(esbuildCode.search(IIFE_BEGIN_RE$1), 0) : format === "umd" ? esbuildCode.indexOf(`(function(`) : 0;
  2682. if (contentIndex > 0) {
  2683. const esbuildHelpers = esbuildCode.slice(0, contentIndex);
  2684. return esbuildCode.slice(contentIndex).replace("\"use strict\";", (m) => m + esbuildHelpers);
  2685. }
  2686. return esbuildCode;
  2687. };
  2688. const buildEsbuildPlugin = () => {
  2689. return {
  2690. name: "vite:esbuild-transpile",
  2691. applyToEnvironment(environment) {
  2692. return environment.config.esbuild !== false;
  2693. },
  2694. async renderChunk(code, chunk, opts) {
  2695. if (this.environment.config.isOutputOptionsForLegacyChunks?.(opts)) return null;
  2696. const config = this.environment.config;
  2697. const options = resolveEsbuildTranspileOptions(config, opts.format);
  2698. if (!options) return null;
  2699. const res = await transformWithEsbuild(code, chunk.fileName, options, void 0, config, void 0, true);
  2700. if (config.build.lib) res.code = injectEsbuildHelpers(res.code, opts.format);
  2701. return res;
  2702. }
  2703. };
  2704. };
  2705. function resolveEsbuildTranspileOptions(config, format) {
  2706. const target = config.build.target;
  2707. const minify = config.build.minify === "esbuild";
  2708. if ((!target || target === "esnext") && !minify) return null;
  2709. const isEsLibBuild = config.build.lib && format === "es";
  2710. const esbuildOptions = config.esbuild || {};
  2711. const options = {
  2712. ...esbuildOptions,
  2713. loader: "js",
  2714. target: target || void 0,
  2715. format: rollupToEsbuildFormatMap[format],
  2716. supported: {
  2717. ...defaultEsbuildSupported,
  2718. ...esbuildOptions.supported
  2719. }
  2720. };
  2721. if (!minify) return {
  2722. ...options,
  2723. minify: false,
  2724. minifyIdentifiers: false,
  2725. minifySyntax: false,
  2726. minifyWhitespace: false,
  2727. treeShaking: false
  2728. };
  2729. if (options.minifyIdentifiers != null || options.minifySyntax != null || options.minifyWhitespace != null) if (isEsLibBuild) return {
  2730. ...options,
  2731. minify: false,
  2732. minifyIdentifiers: options.minifyIdentifiers ?? true,
  2733. minifySyntax: options.minifySyntax ?? true,
  2734. minifyWhitespace: false,
  2735. treeShaking: true
  2736. };
  2737. else return {
  2738. ...options,
  2739. minify: false,
  2740. minifyIdentifiers: options.minifyIdentifiers ?? true,
  2741. minifySyntax: options.minifySyntax ?? true,
  2742. minifyWhitespace: options.minifyWhitespace ?? true,
  2743. treeShaking: true
  2744. };
  2745. if (isEsLibBuild) return {
  2746. ...options,
  2747. minify: false,
  2748. minifyIdentifiers: true,
  2749. minifySyntax: true,
  2750. minifyWhitespace: false,
  2751. treeShaking: true
  2752. };
  2753. else return {
  2754. ...options,
  2755. minify: true,
  2756. treeShaking: true
  2757. };
  2758. }
  2759. function prettifyMessage(m, code) {
  2760. let res = import_picocolors.default.yellow(m.text);
  2761. if (m.location) res += `\n` + generateCodeFrame(code, m.location);
  2762. return res + `\n`;
  2763. }
  2764. let globalTSConfigResolutionCache;
  2765. const tsconfigResolutionCacheMap = /* @__PURE__ */ new WeakMap();
  2766. function getTSConfigResolutionCache(config) {
  2767. if (!config) return globalTSConfigResolutionCache ??= new TsconfigCache();
  2768. let cache = tsconfigResolutionCacheMap.get(config);
  2769. if (!cache) {
  2770. cache = new TsconfigCache();
  2771. tsconfigResolutionCacheMap.set(config, cache);
  2772. }
  2773. return cache;
  2774. }
  2775. async function reloadOnTsconfigChange(server, changedFile) {
  2776. if (changedFile.endsWith(".json")) {
  2777. const cache = getTSConfigResolutionCache(server.config);
  2778. if (changedFile.endsWith("/tsconfig.json")) {
  2779. server.config.logger.info(`changed tsconfig file detected: ${changedFile} - Clearing cache and forcing full-reload to ensure TypeScript is compiled with updated config values.`, {
  2780. clear: server.config.clearScreen,
  2781. timestamp: true
  2782. });
  2783. for (const environment of Object.values(server.environments)) environment.moduleGraph.invalidateAll();
  2784. cache.clear();
  2785. for (const environment of Object.values(server.environments)) environment.hot.send({
  2786. type: "full-reload",
  2787. path: "*"
  2788. });
  2789. }
  2790. }
  2791. }
  2792. //#endregion
  2793. //#region ../../node_modules/.pnpm/artichokie@0.4.2/node_modules/artichokie/dist/index.js
  2794. const AsyncFunction = async function() {}.constructor;
  2795. const codeToDataUrl = (code) => `data:application/javascript,${encodeURIComponent(code + "\n//# sourceURL=[worker-eval(artichokie)]")}`;
  2796. const viteSsrDynamicImport = "__vite_ssr_dynamic_import__";
  2797. const stackBlitzImport = "𝐢𝐦𝐩𝐨𝐫𝐭";
  2798. var Worker$1 = class {
  2799. /** @internal */
  2800. _isModule;
  2801. /** @internal */
  2802. _code;
  2803. /** @internal */
  2804. _parentFunctions;
  2805. /** @internal */
  2806. _max;
  2807. /** @internal */
  2808. _pool;
  2809. /** @internal */
  2810. _idlePool;
  2811. /** @internal */
  2812. _queue;
  2813. constructor(fn, options = {}) {
  2814. this._isModule = options.type === "module";
  2815. this._code = genWorkerCode(fn, this._isModule, 5 * 1e3, options.parentFunctions ?? {});
  2816. this._parentFunctions = options.parentFunctions ?? {};
  2817. const defaultMax = Math.max(1, (os.availableParallelism?.() ?? os.cpus().length) - 1);
  2818. this._max = options.max || defaultMax;
  2819. this._pool = [];
  2820. this._idlePool = [];
  2821. this._queue = [];
  2822. }
  2823. async run(...args) {
  2824. const worker = await this._getAvailableWorker();
  2825. return new Promise((resolve, reject) => {
  2826. worker.currentResolve = resolve;
  2827. worker.currentReject = reject;
  2828. worker.postMessage({ args });
  2829. });
  2830. }
  2831. stop() {
  2832. this._pool.forEach((w) => w.unref());
  2833. this._queue.forEach(([, reject]) => reject(/* @__PURE__ */ new Error("Main worker pool stopped before a worker was available.")));
  2834. this._pool = [];
  2835. this._idlePool = [];
  2836. this._queue = [];
  2837. }
  2838. /** @internal */
  2839. _createWorker(parentFunctionSyncMessagePort, parentFunctionAsyncMessagePort, lockState) {
  2840. const options = {
  2841. workerData: [
  2842. parentFunctionSyncMessagePort,
  2843. parentFunctionAsyncMessagePort,
  2844. lockState
  2845. ],
  2846. transferList: [parentFunctionSyncMessagePort, parentFunctionAsyncMessagePort]
  2847. };
  2848. if (this._isModule) return new Worker(new URL(codeToDataUrl(this._code)), options);
  2849. return new Worker(this._code, {
  2850. ...options,
  2851. eval: true
  2852. });
  2853. }
  2854. /** @internal */
  2855. async _getAvailableWorker() {
  2856. if (this._idlePool.length) return this._idlePool.shift();
  2857. if (this._pool.length < this._max) {
  2858. const parentFunctionResponder = createParentFunctionResponder(this._parentFunctions);
  2859. const worker = this._createWorker(parentFunctionResponder.workerPorts.sync, parentFunctionResponder.workerPorts.async, parentFunctionResponder.lockState);
  2860. worker.on("message", async (args) => {
  2861. if ("result" in args) {
  2862. worker.currentResolve?.(args.result);
  2863. worker.currentResolve = null;
  2864. } else {
  2865. if (args.error instanceof ReferenceError) args.error.message += ". Maybe you forgot to pass the function to parentFunction?";
  2866. worker.currentReject?.(args.error);
  2867. worker.currentReject = null;
  2868. }
  2869. this._assignDoneWorker(worker);
  2870. });
  2871. worker.on("error", (err) => {
  2872. worker.currentReject?.(err);
  2873. worker.currentReject = null;
  2874. parentFunctionResponder.close();
  2875. });
  2876. worker.on("exit", (code) => {
  2877. const i = this._pool.indexOf(worker);
  2878. if (i > -1) this._pool.splice(i, 1);
  2879. if (code !== 0 && worker.currentReject) {
  2880. worker.currentReject(/* @__PURE__ */ new Error(`Worker stopped with non-0 exit code ${code}`));
  2881. worker.currentReject = null;
  2882. parentFunctionResponder.close();
  2883. }
  2884. });
  2885. this._pool.push(worker);
  2886. return worker;
  2887. }
  2888. let resolve;
  2889. let reject;
  2890. const onWorkerAvailablePromise = new Promise((r, rj) => {
  2891. resolve = r;
  2892. reject = rj;
  2893. });
  2894. this._queue.push([resolve, reject]);
  2895. return onWorkerAvailablePromise;
  2896. }
  2897. /** @internal */
  2898. _assignDoneWorker(worker) {
  2899. if (this._queue.length) {
  2900. const [resolve] = this._queue.shift();
  2901. resolve(worker);
  2902. return;
  2903. }
  2904. this._idlePool.push(worker);
  2905. }
  2906. };
  2907. function createParentFunctionResponder(parentFunctions) {
  2908. const lockState = new Int32Array(new SharedArrayBuffer(4));
  2909. const unlock = () => {
  2910. Atomics.store(lockState, 0, 0);
  2911. Atomics.notify(lockState, 0);
  2912. };
  2913. const parentFunctionSyncMessageChannel = new MessageChannel();
  2914. const parentFunctionAsyncMessageChannel = new MessageChannel();
  2915. const parentFunctionSyncMessagePort = parentFunctionSyncMessageChannel.port1;
  2916. const parentFunctionAsyncMessagePort = parentFunctionAsyncMessageChannel.port1;
  2917. const syncResponse = (data) => {
  2918. parentFunctionSyncMessagePort.postMessage(data);
  2919. unlock();
  2920. };
  2921. parentFunctionSyncMessagePort.on("message", async (args) => {
  2922. let syncResult;
  2923. try {
  2924. syncResult = parentFunctions[args.name](...args.args);
  2925. } catch (error) {
  2926. syncResponse({
  2927. id: args.id,
  2928. error
  2929. });
  2930. return;
  2931. }
  2932. if (!(typeof syncResult === "object" && syncResult !== null && "then" in syncResult && typeof syncResult.then === "function")) {
  2933. syncResponse({
  2934. id: args.id,
  2935. result: syncResult
  2936. });
  2937. return;
  2938. }
  2939. syncResponse({
  2940. id: args.id,
  2941. isAsync: true
  2942. });
  2943. try {
  2944. const result = await syncResult;
  2945. parentFunctionAsyncMessagePort.postMessage({
  2946. id: args.id,
  2947. result
  2948. });
  2949. } catch (error) {
  2950. parentFunctionAsyncMessagePort.postMessage({
  2951. id: args.id,
  2952. error
  2953. });
  2954. }
  2955. });
  2956. parentFunctionSyncMessagePort.unref();
  2957. return {
  2958. close: () => {
  2959. parentFunctionSyncMessagePort.close();
  2960. parentFunctionAsyncMessagePort.close();
  2961. },
  2962. lockState,
  2963. workerPorts: {
  2964. sync: parentFunctionSyncMessageChannel.port2,
  2965. async: parentFunctionAsyncMessageChannel.port2
  2966. }
  2967. };
  2968. }
  2969. function genWorkerCode(fn, isModule, waitTimeout, parentFunctions) {
  2970. const createLock = (performance, lockState) => {
  2971. return {
  2972. lock: () => {
  2973. Atomics.store(lockState, 0, 1);
  2974. },
  2975. waitUnlock: () => {
  2976. let utilizationBefore;
  2977. while (true) {
  2978. const status = Atomics.wait(lockState, 0, 1, waitTimeout);
  2979. if (status === "timed-out") {
  2980. if (utilizationBefore === void 0) {
  2981. utilizationBefore = performance.eventLoopUtilization();
  2982. continue;
  2983. }
  2984. utilizationBefore = performance.eventLoopUtilization(utilizationBefore);
  2985. if (utilizationBefore.utilization > .9) continue;
  2986. throw new Error(status);
  2987. }
  2988. break;
  2989. }
  2990. }
  2991. };
  2992. };
  2993. const createParentFunctionRequester = (syncPort, asyncPort, receive, lock) => {
  2994. let id = 0;
  2995. const resolvers = /* @__PURE__ */ new Map();
  2996. const call = (key) => (...args) => {
  2997. id++;
  2998. lock.lock();
  2999. syncPort.postMessage({
  3000. id,
  3001. name: key,
  3002. args
  3003. });
  3004. lock.waitUnlock();
  3005. const resArgs = receive(syncPort).message;
  3006. if (resArgs.isAsync) {
  3007. let resolve, reject;
  3008. const promise = new Promise((res, rej) => {
  3009. resolve = res;
  3010. reject = rej;
  3011. });
  3012. resolvers.set(id, {
  3013. resolve,
  3014. reject
  3015. });
  3016. return promise;
  3017. }
  3018. if ("error" in resArgs) throw resArgs.error;
  3019. else return resArgs.result;
  3020. };
  3021. asyncPort.on("message", (args) => {
  3022. const id$1 = args.id;
  3023. if (resolvers.has(id$1)) {
  3024. const { resolve, reject } = resolvers.get(id$1);
  3025. resolvers.delete(id$1);
  3026. if ("result" in args) resolve(args.result);
  3027. else reject(args.error);
  3028. }
  3029. });
  3030. return { call };
  3031. };
  3032. const fnString = fn.toString().replaceAll(stackBlitzImport, "import").replaceAll(viteSsrDynamicImport, "import");
  3033. return `
  3034. ${isModule ? "import { parentPort, receiveMessageOnPort, workerData } from 'worker_threads'" : "const { parentPort, receiveMessageOnPort, workerData } = require('worker_threads')"}
  3035. ${isModule ? "import { performance } from 'node:perf_hooks'" : "const { performance } = require('node:perf_hooks')"}
  3036. const [parentFunctionSyncMessagePort, parentFunctionAsyncMessagePort, lockState] = workerData
  3037. const waitTimeout = ${waitTimeout}
  3038. const createLock = ${createLock.toString()}
  3039. const parentFunctionRequester = (${createParentFunctionRequester.toString()})(
  3040. parentFunctionSyncMessagePort,
  3041. parentFunctionAsyncMessagePort,
  3042. receiveMessageOnPort,
  3043. createLock(performance, lockState)
  3044. )
  3045. const doWorkPromise = (async () => {
  3046. ${Object.keys(parentFunctions).map((key) => `const ${key} = parentFunctionRequester.call(${JSON.stringify(key)});`).join("\n")}
  3047. return await (${fnString})()
  3048. })()
  3049. let doWork
  3050. parentPort.on('message', async (args) => {
  3051. doWork ||= await doWorkPromise
  3052. try {
  3053. const res = await doWork(...args.args)
  3054. parentPort.postMessage({ result: res })
  3055. } catch (e) {
  3056. parentPort.postMessage({ error: e })
  3057. }
  3058. })
  3059. `;
  3060. }
  3061. const importRe = /\bimport\s*\(/g;
  3062. const internalImportName = "__artichokie_local_import__";
  3063. var FakeWorker = class {
  3064. /** @internal */
  3065. _fn;
  3066. constructor(fn, options = {}) {
  3067. const declareRequire = options.type !== "module";
  3068. const argsAndCode = genFakeWorkerArgsAndCode(fn, declareRequire, options.parentFunctions ?? {});
  3069. const localImport = (specifier) => import(specifier);
  3070. const args = [
  3071. ...declareRequire ? [createRequire(import.meta.url)] : [],
  3072. localImport,
  3073. options.parentFunctions
  3074. ];
  3075. this._fn = new AsyncFunction(...argsAndCode)(...args);
  3076. }
  3077. async run(...args) {
  3078. try {
  3079. return await (await this._fn)(...args);
  3080. } catch (err) {
  3081. if (err instanceof ReferenceError) err.message += ". Maybe you forgot to pass the function to parentFunction?";
  3082. throw err;
  3083. }
  3084. }
  3085. stop() {}
  3086. };
  3087. function genFakeWorkerArgsAndCode(fn, declareRequire, parentFunctions) {
  3088. const fnString = fn.toString().replace(importRe, `${internalImportName}(`).replaceAll(stackBlitzImport, internalImportName).replaceAll(viteSsrDynamicImport, internalImportName);
  3089. return [
  3090. ...declareRequire ? ["require"] : [],
  3091. internalImportName,
  3092. "parentFunctions",
  3093. `
  3094. ${Object.keys(parentFunctions).map((key) => `const ${key} = parentFunctions[${JSON.stringify(key)}];`).join("\n")}
  3095. return await (${fnString})()
  3096. `
  3097. ];
  3098. }
  3099. var WorkerWithFallback = class {
  3100. /** @internal */
  3101. _disableReal;
  3102. /** @internal */
  3103. _realWorker;
  3104. /** @internal */
  3105. _fakeWorker;
  3106. /** @internal */
  3107. _shouldUseFake;
  3108. constructor(fn, options) {
  3109. this._disableReal = options.max !== void 0 && options.max <= 0;
  3110. this._realWorker = new Worker$1(fn, options);
  3111. this._fakeWorker = new FakeWorker(fn, options);
  3112. this._shouldUseFake = options.shouldUseFake;
  3113. }
  3114. async run(...args) {
  3115. const useFake = this._disableReal || this._shouldUseFake(...args);
  3116. return this[useFake ? "_fakeWorker" : "_realWorker"].run(...args);
  3117. }
  3118. stop() {
  3119. this._realWorker.stop();
  3120. this._fakeWorker.stop();
  3121. }
  3122. };
  3123. //#endregion
  3124. //#region ../../node_modules/.pnpm/resolve.exports@2.0.3/node_modules/resolve.exports/dist/index.mjs
  3125. function e(e, n, r) {
  3126. throw new Error(r ? `No known conditions for "${n}" specifier in "${e}" package` : `Missing "${n}" specifier in "${e}" package`);
  3127. }
  3128. function n$1(n, i, o, f) {
  3129. let s, u, l = r(n, o), c = function(e) {
  3130. let n = new Set(["default", ...e.conditions || []]);
  3131. return e.unsafe || n.add(e.require ? "require" : "import"), e.unsafe || n.add(e.browser ? "browser" : "node"), n;
  3132. }(f || {}), a = i[l];
  3133. if (void 0 === a) {
  3134. let e, n, r, t;
  3135. 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))));
  3136. a = i[n];
  3137. }
  3138. return a || e(n, l), s = t(a, c), s || e(n, l, 1), u && function(e, n) {
  3139. let r, t = 0, i = e.length, o = /[*]/g, f = /[/]$/;
  3140. for (; t < i; t++) e[t] = o.test(r = e[t]) ? r.replace(o, n) : f.test(r) ? r + n : r;
  3141. }(s, u), s;
  3142. }
  3143. function r(e, n, r) {
  3144. if (e === n || "." === n) return ".";
  3145. let t = e + "/", i = t.length, o = n.slice(0, i) === t, f = o ? n.slice(i) : n;
  3146. return "#" === f[0] ? f : o || !r ? "./" === f.slice(0, 2) ? f : "./" + f : f;
  3147. }
  3148. function t(e, n, r) {
  3149. if (e) {
  3150. if ("string" == typeof e) return r && r.add(e), [e];
  3151. let i, o;
  3152. if (Array.isArray(e)) {
  3153. for (o = r || /* @__PURE__ */ new Set(), i = 0; i < e.length; i++) t(e[i], n, o);
  3154. if (!r && o.size) return [...o];
  3155. } else for (i in e) if (n.has(i)) return t(e[i], n, r);
  3156. }
  3157. }
  3158. function o(e, r, t) {
  3159. let i, o = e.exports;
  3160. if (o) {
  3161. if ("string" == typeof o) o = { ".": o };
  3162. else for (i in o) {
  3163. "." !== i[0] && (o = { ".": o });
  3164. break;
  3165. }
  3166. return n$1(e.name, o, r || ".", t);
  3167. }
  3168. }
  3169. function f(e, r, t) {
  3170. if (e.imports) return n$1(e.name, e.imports, r, t);
  3171. }
  3172. //#endregion
  3173. //#region ../../node_modules/.pnpm/ufo@1.6.3/node_modules/ufo/dist/index.mjs
  3174. const HASH_RE = /#/g;
  3175. const AMPERSAND_RE = /&/g;
  3176. const SLASH_RE = /\//g;
  3177. const EQUAL_RE = /=/g;
  3178. const PLUS_RE = /\+/g;
  3179. const ENC_CARET_RE = /%5e/gi;
  3180. const ENC_BACKTICK_RE = /%60/gi;
  3181. const ENC_PIPE_RE = /%7c/gi;
  3182. const ENC_SPACE_RE = /%20/gi;
  3183. function encode(text) {
  3184. return encodeURI("" + text).replace(ENC_PIPE_RE, "|");
  3185. }
  3186. function encodeQueryValue(input) {
  3187. 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");
  3188. }
  3189. function encodeQueryKey(text) {
  3190. return encodeQueryValue(text).replace(EQUAL_RE, "%3D");
  3191. }
  3192. function encodeQueryItem(key, value) {
  3193. if (typeof value === "number" || typeof value === "boolean") value = String(value);
  3194. if (!value) return encodeQueryKey(key);
  3195. if (Array.isArray(value)) return value.map((_value) => `${encodeQueryKey(key)}=${encodeQueryValue(_value)}`).join("&");
  3196. return `${encodeQueryKey(key)}=${encodeQueryValue(value)}`;
  3197. }
  3198. function stringifyQuery(query) {
  3199. return Object.keys(query).filter((k) => query[k] !== void 0).map((k) => encodeQueryItem(k, query[k])).filter(Boolean).join("&");
  3200. }
  3201. function clearImports(imports) {
  3202. return (imports || "").replace(/\/\/[^\n]*\n|\/\*.*\*\//g, "").replace(/\s+/g, " ");
  3203. }
  3204. function getImportNames(cleanedImports) {
  3205. const topLevelImports = cleanedImports.replace(/{[^}]*}/, "");
  3206. return {
  3207. namespacedImport: topLevelImports.match(/\* as \s*(\S*)/)?.[1],
  3208. defaultImport: topLevelImports.split(",").find((index) => !/[*{}]/.test(index))?.trim() || void 0
  3209. };
  3210. }
  3211. /**
  3212. * @typedef ErrnoExceptionFields
  3213. * @property {number | undefined} [errnode]
  3214. * @property {string | undefined} [code]
  3215. * @property {string | undefined} [path]
  3216. * @property {string | undefined} [syscall]
  3217. * @property {string | undefined} [url]
  3218. *
  3219. * @typedef {Error & ErrnoExceptionFields} ErrnoException
  3220. */
  3221. const own$1 = {}.hasOwnProperty;
  3222. const classRegExp = /^([A-Z][a-z\d]*)+$/;
  3223. const kTypes = new Set([
  3224. "string",
  3225. "function",
  3226. "number",
  3227. "object",
  3228. "Function",
  3229. "Object",
  3230. "boolean",
  3231. "bigint",
  3232. "symbol"
  3233. ]);
  3234. const codes = {};
  3235. /**
  3236. * Create a list string in the form like 'A and B' or 'A, B, ..., and Z'.
  3237. * We cannot use Intl.ListFormat because it's not available in
  3238. * --without-intl builds.
  3239. *
  3240. * @param {Array<string>} array
  3241. * An array of strings.
  3242. * @param {string} [type]
  3243. * The list type to be inserted before the last element.
  3244. * @returns {string}
  3245. */
  3246. function formatList(array, type = "and") {
  3247. return array.length < 3 ? array.join(` ${type} `) : `${array.slice(0, -1).join(", ")}, ${type} ${array[array.length - 1]}`;
  3248. }
  3249. /** @type {Map<string, MessageFunction | string>} */
  3250. const messages = /* @__PURE__ */ new Map();
  3251. const nodeInternalPrefix = "__node_internal_";
  3252. /** @type {number} */
  3253. let userStackTraceLimit;
  3254. codes.ERR_INVALID_ARG_TYPE = createError(
  3255. "ERR_INVALID_ARG_TYPE",
  3256. /**
  3257. * @param {string} name
  3258. * @param {Array<string> | string} expected
  3259. * @param {unknown} actual
  3260. */
  3261. (name, expected, actual) => {
  3262. assert.ok(typeof name === "string", "'name' must be a string");
  3263. if (!Array.isArray(expected)) expected = [expected];
  3264. let message = "The ";
  3265. if (name.endsWith(" argument")) message += `${name} `;
  3266. else {
  3267. const type = name.includes(".") ? "property" : "argument";
  3268. message += `"${name}" ${type} `;
  3269. }
  3270. message += "must be ";
  3271. /** @type {Array<string>} */
  3272. const types = [];
  3273. /** @type {Array<string>} */
  3274. const instances = [];
  3275. /** @type {Array<string>} */
  3276. const other = [];
  3277. for (const value of expected) {
  3278. assert.ok(typeof value === "string", "All expected entries have to be of type string");
  3279. if (kTypes.has(value)) types.push(value.toLowerCase());
  3280. else if (classRegExp.exec(value) === null) {
  3281. assert.ok(value !== "object", "The value \"object\" should be written as \"Object\"");
  3282. other.push(value);
  3283. } else instances.push(value);
  3284. }
  3285. if (instances.length > 0) {
  3286. const pos = types.indexOf("object");
  3287. if (pos !== -1) {
  3288. types.slice(pos, 1);
  3289. instances.push("Object");
  3290. }
  3291. }
  3292. if (types.length > 0) {
  3293. message += `${types.length > 1 ? "one of type" : "of type"} ${formatList(types, "or")}`;
  3294. if (instances.length > 0 || other.length > 0) message += " or ";
  3295. }
  3296. if (instances.length > 0) {
  3297. message += `an instance of ${formatList(instances, "or")}`;
  3298. if (other.length > 0) message += " or ";
  3299. }
  3300. if (other.length > 0) if (other.length > 1) message += `one of ${formatList(other, "or")}`;
  3301. else {
  3302. if (other[0].toLowerCase() !== other[0]) message += "an ";
  3303. message += `${other[0]}`;
  3304. }
  3305. message += `. Received ${determineSpecificType(actual)}`;
  3306. return message;
  3307. },
  3308. TypeError
  3309. );
  3310. codes.ERR_INVALID_MODULE_SPECIFIER = createError(
  3311. "ERR_INVALID_MODULE_SPECIFIER",
  3312. /**
  3313. * @param {string} request
  3314. * @param {string} reason
  3315. * @param {string} [base]
  3316. */
  3317. (request, reason, base = void 0) => {
  3318. return `Invalid module "${request}" ${reason}${base ? ` imported from ${base}` : ""}`;
  3319. },
  3320. TypeError
  3321. );
  3322. codes.ERR_INVALID_PACKAGE_CONFIG = createError(
  3323. "ERR_INVALID_PACKAGE_CONFIG",
  3324. /**
  3325. * @param {string} path
  3326. * @param {string} [base]
  3327. * @param {string} [message]
  3328. */
  3329. (path, base, message) => {
  3330. return `Invalid package config ${path}${base ? ` while importing ${base}` : ""}${message ? `. ${message}` : ""}`;
  3331. },
  3332. Error
  3333. );
  3334. codes.ERR_INVALID_PACKAGE_TARGET = createError(
  3335. "ERR_INVALID_PACKAGE_TARGET",
  3336. /**
  3337. * @param {string} packagePath
  3338. * @param {string} key
  3339. * @param {unknown} target
  3340. * @param {boolean} [isImport=false]
  3341. * @param {string} [base]
  3342. */
  3343. (packagePath, key, target, isImport = false, base = void 0) => {
  3344. const relatedError = typeof target === "string" && !isImport && target.length > 0 && !target.startsWith("./");
  3345. if (key === ".") {
  3346. assert.ok(isImport === false);
  3347. 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 \"./\"" : ""}`;
  3348. }
  3349. 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 \"./\"" : ""}`;
  3350. },
  3351. Error
  3352. );
  3353. codes.ERR_MODULE_NOT_FOUND = createError(
  3354. "ERR_MODULE_NOT_FOUND",
  3355. /**
  3356. * @param {string} path
  3357. * @param {string} base
  3358. * @param {boolean} [exactUrl]
  3359. */
  3360. (path, base, exactUrl = false) => {
  3361. return `Cannot find ${exactUrl ? "module" : "package"} '${path}' imported from ${base}`;
  3362. },
  3363. Error
  3364. );
  3365. codes.ERR_NETWORK_IMPORT_DISALLOWED = createError("ERR_NETWORK_IMPORT_DISALLOWED", "import of '%s' by %s is not supported: %s", Error);
  3366. codes.ERR_PACKAGE_IMPORT_NOT_DEFINED = createError(
  3367. "ERR_PACKAGE_IMPORT_NOT_DEFINED",
  3368. /**
  3369. * @param {string} specifier
  3370. * @param {string} packagePath
  3371. * @param {string} base
  3372. */
  3373. (specifier, packagePath, base) => {
  3374. return `Package import specifier "${specifier}" is not defined${packagePath ? ` in package ${packagePath}package.json` : ""} imported from ${base}`;
  3375. },
  3376. TypeError
  3377. );
  3378. codes.ERR_PACKAGE_PATH_NOT_EXPORTED = createError(
  3379. "ERR_PACKAGE_PATH_NOT_EXPORTED",
  3380. /**
  3381. * @param {string} packagePath
  3382. * @param {string} subpath
  3383. * @param {string} [base]
  3384. */
  3385. (packagePath, subpath, base = void 0) => {
  3386. if (subpath === ".") return `No "exports" main defined in ${packagePath}package.json${base ? ` imported from ${base}` : ""}`;
  3387. return `Package subpath '${subpath}' is not defined by "exports" in ${packagePath}package.json${base ? ` imported from ${base}` : ""}`;
  3388. },
  3389. Error
  3390. );
  3391. codes.ERR_UNSUPPORTED_DIR_IMPORT = createError("ERR_UNSUPPORTED_DIR_IMPORT", "Directory import '%s' is not supported resolving ES modules imported from %s", Error);
  3392. 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);
  3393. codes.ERR_UNKNOWN_FILE_EXTENSION = createError(
  3394. "ERR_UNKNOWN_FILE_EXTENSION",
  3395. /**
  3396. * @param {string} extension
  3397. * @param {string} path
  3398. */
  3399. (extension, path) => {
  3400. return `Unknown file extension "${extension}" for ${path}`;
  3401. },
  3402. TypeError
  3403. );
  3404. codes.ERR_INVALID_ARG_VALUE = createError(
  3405. "ERR_INVALID_ARG_VALUE",
  3406. /**
  3407. * @param {string} name
  3408. * @param {unknown} value
  3409. * @param {string} [reason='is invalid']
  3410. */
  3411. (name, value, reason = "is invalid") => {
  3412. let inspected = inspect(value);
  3413. if (inspected.length > 128) inspected = `${inspected.slice(0, 128)}...`;
  3414. return `The ${name.includes(".") ? "property" : "argument"} '${name}' ${reason}. Received ${inspected}`;
  3415. },
  3416. TypeError
  3417. );
  3418. /**
  3419. * Utility function for registering the error codes. Only used here. Exported
  3420. * *only* to allow for testing.
  3421. * @param {string} sym
  3422. * @param {MessageFunction | string} value
  3423. * @param {ErrorConstructor} constructor
  3424. * @returns {new (...parameters: Array<any>) => Error}
  3425. */
  3426. function createError(sym, value, constructor) {
  3427. messages.set(sym, value);
  3428. return makeNodeErrorWithCode(constructor, sym);
  3429. }
  3430. /**
  3431. * @param {ErrorConstructor} Base
  3432. * @param {string} key
  3433. * @returns {ErrorConstructor}
  3434. */
  3435. function makeNodeErrorWithCode(Base, key) {
  3436. return NodeError;
  3437. /**
  3438. * @param {Array<unknown>} parameters
  3439. */
  3440. function NodeError(...parameters) {
  3441. const limit = Error.stackTraceLimit;
  3442. if (isErrorStackTraceLimitWritable()) Error.stackTraceLimit = 0;
  3443. const error = new Base();
  3444. if (isErrorStackTraceLimitWritable()) Error.stackTraceLimit = limit;
  3445. const message = getMessage(key, parameters, error);
  3446. Object.defineProperties(error, {
  3447. message: {
  3448. value: message,
  3449. enumerable: false,
  3450. writable: true,
  3451. configurable: true
  3452. },
  3453. toString: {
  3454. value() {
  3455. return `${this.name} [${key}]: ${this.message}`;
  3456. },
  3457. enumerable: false,
  3458. writable: true,
  3459. configurable: true
  3460. }
  3461. });
  3462. captureLargerStackTrace(error);
  3463. error.code = key;
  3464. return error;
  3465. }
  3466. }
  3467. /**
  3468. * @returns {boolean}
  3469. */
  3470. function isErrorStackTraceLimitWritable() {
  3471. try {
  3472. if (v8.startupSnapshot.isBuildingSnapshot()) return false;
  3473. } catch {}
  3474. const desc = Object.getOwnPropertyDescriptor(Error, "stackTraceLimit");
  3475. if (desc === void 0) return Object.isExtensible(Error);
  3476. return own$1.call(desc, "writable") && desc.writable !== void 0 ? desc.writable : desc.set !== void 0;
  3477. }
  3478. /**
  3479. * This function removes unnecessary frames from Node.js core errors.
  3480. * @template {(...parameters: unknown[]) => unknown} T
  3481. * @param {T} wrappedFunction
  3482. * @returns {T}
  3483. */
  3484. function hideStackFrames(wrappedFunction) {
  3485. const hidden = nodeInternalPrefix + wrappedFunction.name;
  3486. Object.defineProperty(wrappedFunction, "name", { value: hidden });
  3487. return wrappedFunction;
  3488. }
  3489. const captureLargerStackTrace = hideStackFrames(
  3490. /**
  3491. * @param {Error} error
  3492. * @returns {Error}
  3493. */
  3494. function(error) {
  3495. const stackTraceLimitIsWritable = isErrorStackTraceLimitWritable();
  3496. if (stackTraceLimitIsWritable) {
  3497. userStackTraceLimit = Error.stackTraceLimit;
  3498. Error.stackTraceLimit = Number.POSITIVE_INFINITY;
  3499. }
  3500. Error.captureStackTrace(error);
  3501. if (stackTraceLimitIsWritable) Error.stackTraceLimit = userStackTraceLimit;
  3502. return error;
  3503. }
  3504. );
  3505. /**
  3506. * @param {string} key
  3507. * @param {Array<unknown>} parameters
  3508. * @param {Error} self
  3509. * @returns {string}
  3510. */
  3511. function getMessage(key, parameters, self) {
  3512. const message = messages.get(key);
  3513. assert.ok(message !== void 0, "expected `message` to be found");
  3514. if (typeof message === "function") {
  3515. assert.ok(message.length <= parameters.length, `Code: ${key}; The provided arguments length (${parameters.length}) does not match the required ones (${message.length}).`);
  3516. return Reflect.apply(message, self, parameters);
  3517. }
  3518. const regex = /%[dfijoOs]/g;
  3519. let expectedLength = 0;
  3520. while (regex.exec(message) !== null) expectedLength++;
  3521. assert.ok(expectedLength === parameters.length, `Code: ${key}; The provided arguments length (${parameters.length}) does not match the required ones (${expectedLength}).`);
  3522. if (parameters.length === 0) return message;
  3523. parameters.unshift(message);
  3524. return Reflect.apply(format, null, parameters);
  3525. }
  3526. /**
  3527. * Determine the specific type of a value for type-mismatch errors.
  3528. * @param {unknown} value
  3529. * @returns {string}
  3530. */
  3531. function determineSpecificType(value) {
  3532. if (value === null || value === void 0) return String(value);
  3533. if (typeof value === "function" && value.name) return `function ${value.name}`;
  3534. if (typeof value === "object") {
  3535. if (value.constructor && value.constructor.name) return `an instance of ${value.constructor.name}`;
  3536. return `${inspect(value, { depth: -1 })}`;
  3537. }
  3538. let inspected = inspect(value, { colors: false });
  3539. if (inspected.length > 28) inspected = `${inspected.slice(0, 25)}...`;
  3540. return `type ${typeof value} (${inspected})`;
  3541. }
  3542. Object.freeze(["node", "import"]);
  3543. 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;
  3544. const TYPE_RE = /^\s*?type\s/;
  3545. function parseStaticImport(matched) {
  3546. const cleanedImports = clearImports(matched.imports);
  3547. const namedImports = {};
  3548. const _matches = cleanedImports.match(/{([^}]*)}/)?.[1]?.split(",") || [];
  3549. for (const namedImport of _matches) {
  3550. const _match = namedImport.match(/^\s*(\S*) as (\S*)\s*$/);
  3551. const source = _match?.[1] || namedImport.trim();
  3552. const importName = _match?.[2] || source;
  3553. if (source && !TYPE_RE.test(source)) namedImports[source] = importName;
  3554. }
  3555. const { namespacedImport, defaultImport } = getImportNames(cleanedImports);
  3556. return {
  3557. ...matched,
  3558. defaultImport,
  3559. namespacedImport,
  3560. namedImports
  3561. };
  3562. }
  3563. 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;
  3564. const COMMENT_RE = /\/\*.+?\*\/|\/\/.*(?=[nr])/g;
  3565. function hasESMSyntax(code, opts = {}) {
  3566. if (opts.stripComments) code = code.replace(COMMENT_RE, "");
  3567. return ESM_RE.test(code);
  3568. }
  3569. //#endregion
  3570. //#region ../../node_modules/.pnpm/es-module-lexer@1.7.0/node_modules/es-module-lexer/dist/lexer.js
  3571. var ImportType;
  3572. (function(A) {
  3573. 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";
  3574. })(ImportType || (ImportType = {}));
  3575. const A = 1 === new Uint8Array(new Uint16Array([1]).buffer)[0];
  3576. function parse$2(E, g = "@") {
  3577. if (!C) return init.then((() => parse$2(E)));
  3578. const I = E.length + 1, w = (C.__heap_base.value || C.__heap_base) + 4 * I - C.memory.buffer.byteLength;
  3579. w > 0 && C.memory.grow(Math.ceil(w / 65536));
  3580. const K = C.sa(I - 1);
  3581. 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() });
  3582. const o = [], D = [];
  3583. for (; C.ri();) {
  3584. const A = C.is(), Q = C.ie(), B = C.it(), g = C.ai(), I = C.id(), w = C.ss(), K = C.se();
  3585. let D;
  3586. C.ip() && (D = k(E.slice(-1 === I ? A - 1 : A, -1 === I ? Q + 1 : Q))), o.push({
  3587. n: D,
  3588. t: B,
  3589. s: A,
  3590. e: Q,
  3591. ss: w,
  3592. se: K,
  3593. d: I,
  3594. a: g
  3595. });
  3596. }
  3597. for (; C.re();) {
  3598. 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] : "";
  3599. D.push({
  3600. s: A,
  3601. e: Q,
  3602. ls: B,
  3603. le: g,
  3604. n: "\"" === w || "'" === w ? k(I) : I,
  3605. ln: "\"" === o || "'" === o ? k(K) : K
  3606. });
  3607. }
  3608. function k(A) {
  3609. try {
  3610. return (0, eval)(A);
  3611. } catch (A) {}
  3612. }
  3613. return [
  3614. o,
  3615. D,
  3616. !!C.f(),
  3617. !!C.ms()
  3618. ];
  3619. }
  3620. function Q(A, Q) {
  3621. const B = A.length;
  3622. let C = 0;
  3623. for (; C < B;) {
  3624. const B = A.charCodeAt(C);
  3625. Q[C++] = (255 & B) << 8 | B >>> 8;
  3626. }
  3627. }
  3628. function B(A, Q) {
  3629. const B = A.length;
  3630. let C = 0;
  3631. for (; C < B;) Q[C] = A.charCodeAt(C++);
  3632. }
  3633. let C;
  3634. const E = () => {
  3635. 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)));
  3636. var A;
  3637. };
  3638. const init = WebAssembly.compile(E()).then(WebAssembly.instantiate).then((({ exports: A }) => {
  3639. C = A;
  3640. }));
  3641. //#endregion
  3642. //#region src/node/plugins/oxc.ts
  3643. const IIFE_BEGIN_RE = /(?:(?:(?:const|var)\s+[^.\s]+|[^.\s]+\.[^.\s]+\.[^.\s]+)\s*=\s*|^|\n)\(?function\([^()]*\)\s*\{(?:\s*"use strict";)?/;
  3644. const UMD_BEGIN_RE = /\}\)\((?:this,\s*)?function\([^()]*\)\s*\{(?:\s*"use strict";)?/;
  3645. const jsxExtensionsRE = /\.(?:j|t)sx\b/;
  3646. const validExtensionRE = /\.\w+$/;
  3647. function getRollupJsxPresets(preset) {
  3648. switch (preset) {
  3649. case "react": return {
  3650. runtime: "classic",
  3651. pragma: "React.createElement",
  3652. pragmaFrag: "React.Fragment",
  3653. importSource: "react"
  3654. };
  3655. case "react-jsx": return {
  3656. runtime: "automatic",
  3657. pragma: "React.createElement",
  3658. importSource: "react"
  3659. };
  3660. }
  3661. }
  3662. function joinNewLine(s1, s2) {
  3663. return s1.replace(/\n+$/, "") + "\n" + s2.replace(/^\n+/, "");
  3664. }
  3665. function getErrorMessage(e) {
  3666. if (Object.hasOwn(e, "kind")) return e.message;
  3667. let s = "";
  3668. if (e.plugin) s += `[plugin ${e.plugin}]`;
  3669. const id = e.id ?? e.loc?.file;
  3670. if (id) {
  3671. s += " " + id;
  3672. if (e.loc) s += `:${e.loc.line}:${e.loc.column}`;
  3673. }
  3674. if (s) s += "\n";
  3675. const message = `${e.name ?? "Error"}: ${e.message}`;
  3676. s += message;
  3677. if (e.frame) s = joinNewLine(s, e.frame);
  3678. if (e.stack) s = joinNewLine(s, e.stack.replace(message, ""));
  3679. if (e.cause) {
  3680. s = joinNewLine(s, "Caused by:");
  3681. s = joinNewLine(s, getErrorMessage(e.cause).split("\n").map((line) => " " + line).join("\n"));
  3682. }
  3683. return s;
  3684. }
  3685. async function transformWithOxc(code, filename, options, inMap, config, watcher) {
  3686. let lang = options?.lang;
  3687. if (!lang) {
  3688. const ext = path.extname(validExtensionRE.test(filename) ? filename : cleanUrl(filename)).slice(1);
  3689. if (ext === "cjs" || ext === "mjs") lang = "js";
  3690. else if (ext === "cts" || ext === "mts") lang = "ts";
  3691. else lang = ext;
  3692. }
  3693. const result = transformSync(filename, code, {
  3694. sourcemap: true,
  3695. ...options,
  3696. inputMap: inMap,
  3697. lang
  3698. }, getTSConfigResolutionCache(config));
  3699. if (watcher && config && result.tsconfigFilePaths && result.tsconfigFilePaths.length > 0) for (const tsconfigFile of result.tsconfigFilePaths) ensureWatchedFile(watcher, normalizePath(tsconfigFile), config.root);
  3700. if (result.errors.length > 0) {
  3701. let summary = `Transform failed with ${result.errors.length} error${result.errors.length < 2 ? "" : "s"}:\n`;
  3702. for (let i = 0; i < result.errors.length; i++) {
  3703. summary += "\n";
  3704. if (i >= 5) {
  3705. summary += "...";
  3706. break;
  3707. }
  3708. summary += getErrorMessage(result.errors[i]);
  3709. }
  3710. const wrapper = new Error(summary);
  3711. Object.defineProperty(wrapper, "errors", {
  3712. configurable: true,
  3713. enumerable: true,
  3714. get: () => result.errors,
  3715. set: (value) => Object.defineProperty(wrapper, "errors", {
  3716. configurable: true,
  3717. enumerable: true,
  3718. value
  3719. })
  3720. });
  3721. throw wrapper;
  3722. }
  3723. return result;
  3724. }
  3725. const warnedMessages = /* @__PURE__ */ new Set();
  3726. function shouldSkipWarning(warning) {
  3727. if (warning.code === "UNSUPPORTED_TSCONFIG_OPTION") {
  3728. if (warnedMessages.has(warning.message)) return true;
  3729. warnedMessages.add(warning.message);
  3730. }
  3731. return false;
  3732. }
  3733. function oxcPlugin(config) {
  3734. if (config.isBundled) return perEnvironmentPlugin("native:transform", (environment) => {
  3735. const { jsxInject, include = /\.(m?ts|[jt]sx)$/, exclude = /\.js$/, jsxRefreshInclude, jsxRefreshExclude, ..._transformOptions } = config.oxc;
  3736. const transformOptions = _transformOptions;
  3737. transformOptions.sourcemap = environment.config.mode !== "build" || !!environment.config.build.sourcemap;
  3738. return viteTransformPlugin({
  3739. root: environment.config.root,
  3740. include,
  3741. exclude,
  3742. jsxRefreshInclude,
  3743. jsxRefreshExclude,
  3744. isServerConsumer: environment.config.consumer === "server",
  3745. jsxInject,
  3746. transformOptions
  3747. });
  3748. });
  3749. const { jsxInject, include, exclude, jsxRefreshInclude, jsxRefreshExclude, ...oxcTransformOptions } = config.oxc;
  3750. const filter = createFilter$1(include || /\.(m?ts|[jt]sx)$/, exclude || /\.js$/);
  3751. const jsxRefreshFilter = jsxRefreshInclude || jsxRefreshExclude ? createFilter$1(jsxRefreshInclude, jsxRefreshExclude) : void 0;
  3752. const jsxImportSource = typeof oxcTransformOptions.jsx === "object" && oxcTransformOptions.jsx.importSource || "react";
  3753. const jsxImportRuntime = `${jsxImportSource}/jsx-runtime`;
  3754. const jsxImportDevRuntime = `${jsxImportSource}/jsx-dev-runtime`;
  3755. const getModifiedOxcTransformOptions = (oxcTransformOptions, id, code, environment) => {
  3756. const result = {
  3757. ...oxcTransformOptions,
  3758. sourcemap: environment.mode !== "build" || !!environment.config.build.sourcemap
  3759. };
  3760. const jsxOptions = result.jsx;
  3761. const [filepath] = id.split("?");
  3762. const isJSX = filepath.endsWith("x");
  3763. if (typeof jsxOptions === "object" && jsxOptions.refresh && (environment.config.consumer === "server" || jsxRefreshFilter && !jsxRefreshFilter(id) || !(isJSX || code.includes(jsxImportRuntime) || code.includes(jsxImportDevRuntime)))) result.jsx = {
  3764. ...jsxOptions,
  3765. refresh: false
  3766. };
  3767. if (jsxRefreshFilter?.(id) && !JS_TYPES_RE.test(cleanUrl(id))) result.lang = "js";
  3768. return result;
  3769. };
  3770. const runtimeResolveBase = normalizePath(path.join(VITE_PACKAGE_DIR, "package.json"));
  3771. let server;
  3772. return {
  3773. name: "vite:oxc",
  3774. configureServer(_server) {
  3775. server = _server;
  3776. },
  3777. ...config.command === "serve" ? { resolveId: {
  3778. filter: { id: prefixRegex("@oxc-project/runtime/") },
  3779. async handler(id, _importer, opts) {
  3780. return await this.resolve(id, runtimeResolveBase, opts);
  3781. },
  3782. order: "pre"
  3783. } } : {},
  3784. async transform(code, id) {
  3785. if (filter(id) || filter(cleanUrl(id)) || jsxRefreshFilter?.(id)) {
  3786. const result = await transformWithOxc(code, id, getModifiedOxcTransformOptions(oxcTransformOptions, id, code, this.environment), void 0, config, server?.watcher);
  3787. if (jsxInject && jsxExtensionsRE.test(id)) result.code = jsxInject + ";" + result.code;
  3788. for (const warning of result.warnings) if (!shouldSkipWarning(warning)) this.warn(warning);
  3789. return {
  3790. code: result.code,
  3791. map: result.map,
  3792. moduleType: "js"
  3793. };
  3794. }
  3795. }
  3796. };
  3797. }
  3798. function convertEsbuildConfigToOxcConfig(esbuildConfig, logger) {
  3799. const { jsxInject, include, exclude, ...esbuildTransformOptions } = esbuildConfig;
  3800. const oxcOptions = {
  3801. jsxInject,
  3802. include,
  3803. exclude
  3804. };
  3805. if (esbuildTransformOptions.jsx === "preserve") oxcOptions.jsx = "preserve";
  3806. else {
  3807. const jsxOptions = {};
  3808. switch (esbuildTransformOptions.jsx) {
  3809. case "automatic":
  3810. jsxOptions.runtime = "automatic";
  3811. if (esbuildTransformOptions.jsxImportSource) jsxOptions.importSource = esbuildTransformOptions.jsxImportSource;
  3812. break;
  3813. case "transform":
  3814. jsxOptions.runtime = "classic";
  3815. if (esbuildTransformOptions.jsxFactory) jsxOptions.pragma = esbuildTransformOptions.jsxFactory;
  3816. if (esbuildTransformOptions.jsxFragment) jsxOptions.pragmaFrag = esbuildTransformOptions.jsxFragment;
  3817. break;
  3818. default: break;
  3819. }
  3820. if (esbuildTransformOptions.jsxDev !== void 0) jsxOptions.development = esbuildTransformOptions.jsxDev;
  3821. if (esbuildTransformOptions.jsxSideEffects !== void 0) jsxOptions.pure = esbuildTransformOptions.jsxSideEffects;
  3822. oxcOptions.jsx = jsxOptions;
  3823. }
  3824. if (esbuildTransformOptions.define) oxcOptions.define = esbuildTransformOptions.define;
  3825. if (esbuildTransformOptions.banner) warnDeprecatedShouldBeConvertedToPluginOptions(logger, "banner");
  3826. if (esbuildTransformOptions.footer) warnDeprecatedShouldBeConvertedToPluginOptions(logger, "footer");
  3827. return oxcOptions;
  3828. }
  3829. function warnDeprecatedShouldBeConvertedToPluginOptions(logger, name) {
  3830. 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.`));
  3831. }
  3832. //#endregion
  3833. //#region ../../node_modules/.pnpm/magic-string@0.30.21/node_modules/magic-string/dist/magic-string.es.mjs
  3834. var BitSet = class BitSet {
  3835. constructor(arg) {
  3836. this.bits = arg instanceof BitSet ? arg.bits.slice() : [];
  3837. }
  3838. add(n) {
  3839. this.bits[n >> 5] |= 1 << (n & 31);
  3840. }
  3841. has(n) {
  3842. return !!(this.bits[n >> 5] & 1 << (n & 31));
  3843. }
  3844. };
  3845. var Chunk = class Chunk {
  3846. constructor(start, end, content) {
  3847. this.start = start;
  3848. this.end = end;
  3849. this.original = content;
  3850. this.intro = "";
  3851. this.outro = "";
  3852. this.content = content;
  3853. this.storeName = false;
  3854. this.edited = false;
  3855. this.previous = null;
  3856. this.next = null;
  3857. }
  3858. appendLeft(content) {
  3859. this.outro += content;
  3860. }
  3861. appendRight(content) {
  3862. this.intro = this.intro + content;
  3863. }
  3864. clone() {
  3865. const chunk = new Chunk(this.start, this.end, this.original);
  3866. chunk.intro = this.intro;
  3867. chunk.outro = this.outro;
  3868. chunk.content = this.content;
  3869. chunk.storeName = this.storeName;
  3870. chunk.edited = this.edited;
  3871. return chunk;
  3872. }
  3873. contains(index) {
  3874. return this.start < index && index < this.end;
  3875. }
  3876. eachNext(fn) {
  3877. let chunk = this;
  3878. while (chunk) {
  3879. fn(chunk);
  3880. chunk = chunk.next;
  3881. }
  3882. }
  3883. eachPrevious(fn) {
  3884. let chunk = this;
  3885. while (chunk) {
  3886. fn(chunk);
  3887. chunk = chunk.previous;
  3888. }
  3889. }
  3890. edit(content, storeName, contentOnly) {
  3891. this.content = content;
  3892. if (!contentOnly) {
  3893. this.intro = "";
  3894. this.outro = "";
  3895. }
  3896. this.storeName = storeName;
  3897. this.edited = true;
  3898. return this;
  3899. }
  3900. prependLeft(content) {
  3901. this.outro = content + this.outro;
  3902. }
  3903. prependRight(content) {
  3904. this.intro = content + this.intro;
  3905. }
  3906. reset() {
  3907. this.intro = "";
  3908. this.outro = "";
  3909. if (this.edited) {
  3910. this.content = this.original;
  3911. this.storeName = false;
  3912. this.edited = false;
  3913. }
  3914. }
  3915. split(index) {
  3916. const sliceIndex = index - this.start;
  3917. const originalBefore = this.original.slice(0, sliceIndex);
  3918. const originalAfter = this.original.slice(sliceIndex);
  3919. this.original = originalBefore;
  3920. const newChunk = new Chunk(index, this.end, originalAfter);
  3921. newChunk.outro = this.outro;
  3922. this.outro = "";
  3923. this.end = index;
  3924. if (this.edited) {
  3925. newChunk.edit("", false);
  3926. this.content = "";
  3927. } else this.content = originalBefore;
  3928. newChunk.next = this.next;
  3929. if (newChunk.next) newChunk.next.previous = newChunk;
  3930. newChunk.previous = this;
  3931. this.next = newChunk;
  3932. return newChunk;
  3933. }
  3934. toString() {
  3935. return this.intro + this.content + this.outro;
  3936. }
  3937. trimEnd(rx) {
  3938. this.outro = this.outro.replace(rx, "");
  3939. if (this.outro.length) return true;
  3940. const trimmed = this.content.replace(rx, "");
  3941. if (trimmed.length) {
  3942. if (trimmed !== this.content) {
  3943. this.split(this.start + trimmed.length).edit("", void 0, true);
  3944. if (this.edited) this.edit(trimmed, this.storeName, true);
  3945. }
  3946. return true;
  3947. } else {
  3948. this.edit("", void 0, true);
  3949. this.intro = this.intro.replace(rx, "");
  3950. if (this.intro.length) return true;
  3951. }
  3952. }
  3953. trimStart(rx) {
  3954. this.intro = this.intro.replace(rx, "");
  3955. if (this.intro.length) return true;
  3956. const trimmed = this.content.replace(rx, "");
  3957. if (trimmed.length) {
  3958. if (trimmed !== this.content) {
  3959. const newChunk = this.split(this.end - trimmed.length);
  3960. if (this.edited) newChunk.edit(trimmed, this.storeName, true);
  3961. this.edit("", void 0, true);
  3962. }
  3963. return true;
  3964. } else {
  3965. this.edit("", void 0, true);
  3966. this.outro = this.outro.replace(rx, "");
  3967. if (this.outro.length) return true;
  3968. }
  3969. }
  3970. };
  3971. function getBtoa() {
  3972. if (typeof globalThis !== "undefined" && typeof globalThis.btoa === "function") return (str) => globalThis.btoa(unescape(encodeURIComponent(str)));
  3973. else if (typeof Buffer === "function") return (str) => Buffer.from(str, "utf-8").toString("base64");
  3974. else return () => {
  3975. throw new Error("Unsupported environment: `window.btoa` or `Buffer` should be supported.");
  3976. };
  3977. }
  3978. const btoa$1 = /* @__PURE__ */ getBtoa();
  3979. var SourceMap = class {
  3980. constructor(properties) {
  3981. this.version = 3;
  3982. this.file = properties.file;
  3983. this.sources = properties.sources;
  3984. this.sourcesContent = properties.sourcesContent;
  3985. this.names = properties.names;
  3986. this.mappings = encode$1(properties.mappings);
  3987. if (typeof properties.x_google_ignoreList !== "undefined") this.x_google_ignoreList = properties.x_google_ignoreList;
  3988. if (typeof properties.debugId !== "undefined") this.debugId = properties.debugId;
  3989. }
  3990. toString() {
  3991. return JSON.stringify(this);
  3992. }
  3993. toUrl() {
  3994. return "data:application/json;charset=utf-8;base64," + btoa$1(this.toString());
  3995. }
  3996. };
  3997. function guessIndent(code) {
  3998. const lines = code.split("\n");
  3999. const tabbed = lines.filter((line) => /^\t+/.test(line));
  4000. const spaced = lines.filter((line) => /^ {2,}/.test(line));
  4001. if (tabbed.length === 0 && spaced.length === 0) return null;
  4002. if (tabbed.length >= spaced.length) return " ";
  4003. const min = spaced.reduce((previous, current) => {
  4004. const numSpaces = /^ +/.exec(current)[0].length;
  4005. return Math.min(numSpaces, previous);
  4006. }, Infinity);
  4007. return new Array(min + 1).join(" ");
  4008. }
  4009. function getRelativePath(from, to) {
  4010. const fromParts = from.split(/[/\\]/);
  4011. const toParts = to.split(/[/\\]/);
  4012. fromParts.pop();
  4013. while (fromParts[0] === toParts[0]) {
  4014. fromParts.shift();
  4015. toParts.shift();
  4016. }
  4017. if (fromParts.length) {
  4018. let i = fromParts.length;
  4019. while (i--) fromParts[i] = "..";
  4020. }
  4021. return fromParts.concat(toParts).join("/");
  4022. }
  4023. const toString = Object.prototype.toString;
  4024. function isObject(thing) {
  4025. return toString.call(thing) === "[object Object]";
  4026. }
  4027. function getLocator(source) {
  4028. const originalLines = source.split("\n");
  4029. const lineOffsets = [];
  4030. for (let i = 0, pos = 0; i < originalLines.length; i++) {
  4031. lineOffsets.push(pos);
  4032. pos += originalLines[i].length + 1;
  4033. }
  4034. return function locate(index) {
  4035. let i = 0;
  4036. let j = lineOffsets.length;
  4037. while (i < j) {
  4038. const m = i + j >> 1;
  4039. if (index < lineOffsets[m]) j = m;
  4040. else i = m + 1;
  4041. }
  4042. const line = i - 1;
  4043. return {
  4044. line,
  4045. column: index - lineOffsets[line]
  4046. };
  4047. };
  4048. }
  4049. const wordRegex = /\w/;
  4050. var Mappings = class {
  4051. constructor(hires) {
  4052. this.hires = hires;
  4053. this.generatedCodeLine = 0;
  4054. this.generatedCodeColumn = 0;
  4055. this.raw = [];
  4056. this.rawSegments = this.raw[this.generatedCodeLine] = [];
  4057. this.pending = null;
  4058. }
  4059. addEdit(sourceIndex, content, loc, nameIndex) {
  4060. if (content.length) {
  4061. const contentLengthMinusOne = content.length - 1;
  4062. let contentLineEnd = content.indexOf("\n", 0);
  4063. let previousContentLineEnd = -1;
  4064. while (contentLineEnd >= 0 && contentLengthMinusOne > contentLineEnd) {
  4065. const segment = [
  4066. this.generatedCodeColumn,
  4067. sourceIndex,
  4068. loc.line,
  4069. loc.column
  4070. ];
  4071. if (nameIndex >= 0) segment.push(nameIndex);
  4072. this.rawSegments.push(segment);
  4073. this.generatedCodeLine += 1;
  4074. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  4075. this.generatedCodeColumn = 0;
  4076. previousContentLineEnd = contentLineEnd;
  4077. contentLineEnd = content.indexOf("\n", contentLineEnd + 1);
  4078. }
  4079. const segment = [
  4080. this.generatedCodeColumn,
  4081. sourceIndex,
  4082. loc.line,
  4083. loc.column
  4084. ];
  4085. if (nameIndex >= 0) segment.push(nameIndex);
  4086. this.rawSegments.push(segment);
  4087. this.advance(content.slice(previousContentLineEnd + 1));
  4088. } else if (this.pending) {
  4089. this.rawSegments.push(this.pending);
  4090. this.advance(content);
  4091. }
  4092. this.pending = null;
  4093. }
  4094. addUneditedChunk(sourceIndex, chunk, original, loc, sourcemapLocations) {
  4095. let originalCharIndex = chunk.start;
  4096. let first = true;
  4097. let charInHiresBoundary = false;
  4098. while (originalCharIndex < chunk.end) {
  4099. if (original[originalCharIndex] === "\n") {
  4100. loc.line += 1;
  4101. loc.column = 0;
  4102. this.generatedCodeLine += 1;
  4103. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  4104. this.generatedCodeColumn = 0;
  4105. first = true;
  4106. charInHiresBoundary = false;
  4107. } else {
  4108. if (this.hires || first || sourcemapLocations.has(originalCharIndex)) {
  4109. const segment = [
  4110. this.generatedCodeColumn,
  4111. sourceIndex,
  4112. loc.line,
  4113. loc.column
  4114. ];
  4115. if (this.hires === "boundary") if (wordRegex.test(original[originalCharIndex])) {
  4116. if (!charInHiresBoundary) {
  4117. this.rawSegments.push(segment);
  4118. charInHiresBoundary = true;
  4119. }
  4120. } else {
  4121. this.rawSegments.push(segment);
  4122. charInHiresBoundary = false;
  4123. }
  4124. else this.rawSegments.push(segment);
  4125. }
  4126. loc.column += 1;
  4127. this.generatedCodeColumn += 1;
  4128. first = false;
  4129. }
  4130. originalCharIndex += 1;
  4131. }
  4132. this.pending = null;
  4133. }
  4134. advance(str) {
  4135. if (!str) return;
  4136. const lines = str.split("\n");
  4137. if (lines.length > 1) {
  4138. for (let i = 0; i < lines.length - 1; i++) {
  4139. this.generatedCodeLine++;
  4140. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  4141. }
  4142. this.generatedCodeColumn = 0;
  4143. }
  4144. this.generatedCodeColumn += lines[lines.length - 1].length;
  4145. }
  4146. };
  4147. const n = "\n";
  4148. const warned = {
  4149. insertLeft: false,
  4150. insertRight: false,
  4151. storeName: false
  4152. };
  4153. var MagicString = class MagicString {
  4154. constructor(string, options = {}) {
  4155. const chunk = new Chunk(0, string.length, string);
  4156. Object.defineProperties(this, {
  4157. original: {
  4158. writable: true,
  4159. value: string
  4160. },
  4161. outro: {
  4162. writable: true,
  4163. value: ""
  4164. },
  4165. intro: {
  4166. writable: true,
  4167. value: ""
  4168. },
  4169. firstChunk: {
  4170. writable: true,
  4171. value: chunk
  4172. },
  4173. lastChunk: {
  4174. writable: true,
  4175. value: chunk
  4176. },
  4177. lastSearchedChunk: {
  4178. writable: true,
  4179. value: chunk
  4180. },
  4181. byStart: {
  4182. writable: true,
  4183. value: {}
  4184. },
  4185. byEnd: {
  4186. writable: true,
  4187. value: {}
  4188. },
  4189. filename: {
  4190. writable: true,
  4191. value: options.filename
  4192. },
  4193. indentExclusionRanges: {
  4194. writable: true,
  4195. value: options.indentExclusionRanges
  4196. },
  4197. sourcemapLocations: {
  4198. writable: true,
  4199. value: new BitSet()
  4200. },
  4201. storedNames: {
  4202. writable: true,
  4203. value: {}
  4204. },
  4205. indentStr: {
  4206. writable: true,
  4207. value: void 0
  4208. },
  4209. ignoreList: {
  4210. writable: true,
  4211. value: options.ignoreList
  4212. },
  4213. offset: {
  4214. writable: true,
  4215. value: options.offset || 0
  4216. }
  4217. });
  4218. this.byStart[0] = chunk;
  4219. this.byEnd[string.length] = chunk;
  4220. }
  4221. addSourcemapLocation(char) {
  4222. this.sourcemapLocations.add(char);
  4223. }
  4224. append(content) {
  4225. if (typeof content !== "string") throw new TypeError("outro content must be a string");
  4226. this.outro += content;
  4227. return this;
  4228. }
  4229. appendLeft(index, content) {
  4230. index = index + this.offset;
  4231. if (typeof content !== "string") throw new TypeError("inserted content must be a string");
  4232. this._split(index);
  4233. const chunk = this.byEnd[index];
  4234. if (chunk) chunk.appendLeft(content);
  4235. else this.intro += content;
  4236. return this;
  4237. }
  4238. appendRight(index, content) {
  4239. index = index + this.offset;
  4240. if (typeof content !== "string") throw new TypeError("inserted content must be a string");
  4241. this._split(index);
  4242. const chunk = this.byStart[index];
  4243. if (chunk) chunk.appendRight(content);
  4244. else this.outro += content;
  4245. return this;
  4246. }
  4247. clone() {
  4248. const cloned = new MagicString(this.original, {
  4249. filename: this.filename,
  4250. offset: this.offset
  4251. });
  4252. let originalChunk = this.firstChunk;
  4253. let clonedChunk = cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone();
  4254. while (originalChunk) {
  4255. cloned.byStart[clonedChunk.start] = clonedChunk;
  4256. cloned.byEnd[clonedChunk.end] = clonedChunk;
  4257. const nextOriginalChunk = originalChunk.next;
  4258. const nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone();
  4259. if (nextClonedChunk) {
  4260. clonedChunk.next = nextClonedChunk;
  4261. nextClonedChunk.previous = clonedChunk;
  4262. clonedChunk = nextClonedChunk;
  4263. }
  4264. originalChunk = nextOriginalChunk;
  4265. }
  4266. cloned.lastChunk = clonedChunk;
  4267. if (this.indentExclusionRanges) cloned.indentExclusionRanges = this.indentExclusionRanges.slice();
  4268. cloned.sourcemapLocations = new BitSet(this.sourcemapLocations);
  4269. cloned.intro = this.intro;
  4270. cloned.outro = this.outro;
  4271. return cloned;
  4272. }
  4273. generateDecodedMap(options) {
  4274. options = options || {};
  4275. const sourceIndex = 0;
  4276. const names = Object.keys(this.storedNames);
  4277. const mappings = new Mappings(options.hires);
  4278. const locate = getLocator(this.original);
  4279. if (this.intro) mappings.advance(this.intro);
  4280. this.firstChunk.eachNext((chunk) => {
  4281. const loc = locate(chunk.start);
  4282. if (chunk.intro.length) mappings.advance(chunk.intro);
  4283. if (chunk.edited) mappings.addEdit(sourceIndex, chunk.content, loc, chunk.storeName ? names.indexOf(chunk.original) : -1);
  4284. else mappings.addUneditedChunk(sourceIndex, chunk, this.original, loc, this.sourcemapLocations);
  4285. if (chunk.outro.length) mappings.advance(chunk.outro);
  4286. });
  4287. if (this.outro) mappings.advance(this.outro);
  4288. return {
  4289. file: options.file ? options.file.split(/[/\\]/).pop() : void 0,
  4290. sources: [options.source ? getRelativePath(options.file || "", options.source) : options.file || ""],
  4291. sourcesContent: options.includeContent ? [this.original] : void 0,
  4292. names,
  4293. mappings: mappings.raw,
  4294. x_google_ignoreList: this.ignoreList ? [sourceIndex] : void 0
  4295. };
  4296. }
  4297. generateMap(options) {
  4298. return new SourceMap(this.generateDecodedMap(options));
  4299. }
  4300. _ensureindentStr() {
  4301. if (this.indentStr === void 0) this.indentStr = guessIndent(this.original);
  4302. }
  4303. _getRawIndentString() {
  4304. this._ensureindentStr();
  4305. return this.indentStr;
  4306. }
  4307. getIndentString() {
  4308. this._ensureindentStr();
  4309. return this.indentStr === null ? " " : this.indentStr;
  4310. }
  4311. indent(indentStr, options) {
  4312. const pattern = /^[^\r\n]/gm;
  4313. if (isObject(indentStr)) {
  4314. options = indentStr;
  4315. indentStr = void 0;
  4316. }
  4317. if (indentStr === void 0) {
  4318. this._ensureindentStr();
  4319. indentStr = this.indentStr || " ";
  4320. }
  4321. if (indentStr === "") return this;
  4322. options = options || {};
  4323. const isExcluded = {};
  4324. if (options.exclude) (typeof options.exclude[0] === "number" ? [options.exclude] : options.exclude).forEach((exclusion) => {
  4325. for (let i = exclusion[0]; i < exclusion[1]; i += 1) isExcluded[i] = true;
  4326. });
  4327. let shouldIndentNextCharacter = options.indentStart !== false;
  4328. const replacer = (match) => {
  4329. if (shouldIndentNextCharacter) return `${indentStr}${match}`;
  4330. shouldIndentNextCharacter = true;
  4331. return match;
  4332. };
  4333. this.intro = this.intro.replace(pattern, replacer);
  4334. let charIndex = 0;
  4335. let chunk = this.firstChunk;
  4336. while (chunk) {
  4337. const end = chunk.end;
  4338. if (chunk.edited) {
  4339. if (!isExcluded[charIndex]) {
  4340. chunk.content = chunk.content.replace(pattern, replacer);
  4341. if (chunk.content.length) shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === "\n";
  4342. }
  4343. } else {
  4344. charIndex = chunk.start;
  4345. while (charIndex < end) {
  4346. if (!isExcluded[charIndex]) {
  4347. const char = this.original[charIndex];
  4348. if (char === "\n") shouldIndentNextCharacter = true;
  4349. else if (char !== "\r" && shouldIndentNextCharacter) {
  4350. shouldIndentNextCharacter = false;
  4351. if (charIndex === chunk.start) chunk.prependRight(indentStr);
  4352. else {
  4353. this._splitChunk(chunk, charIndex);
  4354. chunk = chunk.next;
  4355. chunk.prependRight(indentStr);
  4356. }
  4357. }
  4358. }
  4359. charIndex += 1;
  4360. }
  4361. }
  4362. charIndex = chunk.end;
  4363. chunk = chunk.next;
  4364. }
  4365. this.outro = this.outro.replace(pattern, replacer);
  4366. return this;
  4367. }
  4368. insert() {
  4369. throw new Error("magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)");
  4370. }
  4371. insertLeft(index, content) {
  4372. if (!warned.insertLeft) {
  4373. console.warn("magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead");
  4374. warned.insertLeft = true;
  4375. }
  4376. return this.appendLeft(index, content);
  4377. }
  4378. insertRight(index, content) {
  4379. if (!warned.insertRight) {
  4380. console.warn("magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead");
  4381. warned.insertRight = true;
  4382. }
  4383. return this.prependRight(index, content);
  4384. }
  4385. move(start, end, index) {
  4386. start = start + this.offset;
  4387. end = end + this.offset;
  4388. index = index + this.offset;
  4389. if (index >= start && index <= end) throw new Error("Cannot move a selection inside itself");
  4390. this._split(start);
  4391. this._split(end);
  4392. this._split(index);
  4393. const first = this.byStart[start];
  4394. const last = this.byEnd[end];
  4395. const oldLeft = first.previous;
  4396. const oldRight = last.next;
  4397. const newRight = this.byStart[index];
  4398. if (!newRight && last === this.lastChunk) return this;
  4399. const newLeft = newRight ? newRight.previous : this.lastChunk;
  4400. if (oldLeft) oldLeft.next = oldRight;
  4401. if (oldRight) oldRight.previous = oldLeft;
  4402. if (newLeft) newLeft.next = first;
  4403. if (newRight) newRight.previous = last;
  4404. if (!first.previous) this.firstChunk = last.next;
  4405. if (!last.next) {
  4406. this.lastChunk = first.previous;
  4407. this.lastChunk.next = null;
  4408. }
  4409. first.previous = newLeft;
  4410. last.next = newRight || null;
  4411. if (!newLeft) this.firstChunk = first;
  4412. if (!newRight) this.lastChunk = last;
  4413. return this;
  4414. }
  4415. overwrite(start, end, content, options) {
  4416. options = options || {};
  4417. return this.update(start, end, content, {
  4418. ...options,
  4419. overwrite: !options.contentOnly
  4420. });
  4421. }
  4422. update(start, end, content, options) {
  4423. start = start + this.offset;
  4424. end = end + this.offset;
  4425. if (typeof content !== "string") throw new TypeError("replacement content must be a string");
  4426. if (this.original.length !== 0) {
  4427. while (start < 0) start += this.original.length;
  4428. while (end < 0) end += this.original.length;
  4429. }
  4430. if (end > this.original.length) throw new Error("end is out of bounds");
  4431. if (start === end) throw new Error("Cannot overwrite a zero-length range – use appendLeft or prependRight instead");
  4432. this._split(start);
  4433. this._split(end);
  4434. if (options === true) {
  4435. if (!warned.storeName) {
  4436. console.warn("The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string");
  4437. warned.storeName = true;
  4438. }
  4439. options = { storeName: true };
  4440. }
  4441. const storeName = options !== void 0 ? options.storeName : false;
  4442. const overwrite = options !== void 0 ? options.overwrite : false;
  4443. if (storeName) {
  4444. const original = this.original.slice(start, end);
  4445. Object.defineProperty(this.storedNames, original, {
  4446. writable: true,
  4447. value: true,
  4448. enumerable: true
  4449. });
  4450. }
  4451. const first = this.byStart[start];
  4452. const last = this.byEnd[end];
  4453. if (first) {
  4454. let chunk = first;
  4455. while (chunk !== last) {
  4456. if (chunk.next !== this.byStart[chunk.end]) throw new Error("Cannot overwrite across a split point");
  4457. chunk = chunk.next;
  4458. chunk.edit("", false);
  4459. }
  4460. first.edit(content, storeName, !overwrite);
  4461. } else {
  4462. const newChunk = new Chunk(start, end, "").edit(content, storeName);
  4463. last.next = newChunk;
  4464. newChunk.previous = last;
  4465. }
  4466. return this;
  4467. }
  4468. prepend(content) {
  4469. if (typeof content !== "string") throw new TypeError("outro content must be a string");
  4470. this.intro = content + this.intro;
  4471. return this;
  4472. }
  4473. prependLeft(index, content) {
  4474. index = index + this.offset;
  4475. if (typeof content !== "string") throw new TypeError("inserted content must be a string");
  4476. this._split(index);
  4477. const chunk = this.byEnd[index];
  4478. if (chunk) chunk.prependLeft(content);
  4479. else this.intro = content + this.intro;
  4480. return this;
  4481. }
  4482. prependRight(index, content) {
  4483. index = index + this.offset;
  4484. if (typeof content !== "string") throw new TypeError("inserted content must be a string");
  4485. this._split(index);
  4486. const chunk = this.byStart[index];
  4487. if (chunk) chunk.prependRight(content);
  4488. else this.outro = content + this.outro;
  4489. return this;
  4490. }
  4491. remove(start, end) {
  4492. start = start + this.offset;
  4493. end = end + this.offset;
  4494. if (this.original.length !== 0) {
  4495. while (start < 0) start += this.original.length;
  4496. while (end < 0) end += this.original.length;
  4497. }
  4498. if (start === end) return this;
  4499. if (start < 0 || end > this.original.length) throw new Error("Character is out of bounds");
  4500. if (start > end) throw new Error("end must be greater than start");
  4501. this._split(start);
  4502. this._split(end);
  4503. let chunk = this.byStart[start];
  4504. while (chunk) {
  4505. chunk.intro = "";
  4506. chunk.outro = "";
  4507. chunk.edit("");
  4508. chunk = end > chunk.end ? this.byStart[chunk.end] : null;
  4509. }
  4510. return this;
  4511. }
  4512. reset(start, end) {
  4513. start = start + this.offset;
  4514. end = end + this.offset;
  4515. if (this.original.length !== 0) {
  4516. while (start < 0) start += this.original.length;
  4517. while (end < 0) end += this.original.length;
  4518. }
  4519. if (start === end) return this;
  4520. if (start < 0 || end > this.original.length) throw new Error("Character is out of bounds");
  4521. if (start > end) throw new Error("end must be greater than start");
  4522. this._split(start);
  4523. this._split(end);
  4524. let chunk = this.byStart[start];
  4525. while (chunk) {
  4526. chunk.reset();
  4527. chunk = end > chunk.end ? this.byStart[chunk.end] : null;
  4528. }
  4529. return this;
  4530. }
  4531. lastChar() {
  4532. if (this.outro.length) return this.outro[this.outro.length - 1];
  4533. let chunk = this.lastChunk;
  4534. do {
  4535. if (chunk.outro.length) return chunk.outro[chunk.outro.length - 1];
  4536. if (chunk.content.length) return chunk.content[chunk.content.length - 1];
  4537. if (chunk.intro.length) return chunk.intro[chunk.intro.length - 1];
  4538. } while (chunk = chunk.previous);
  4539. if (this.intro.length) return this.intro[this.intro.length - 1];
  4540. return "";
  4541. }
  4542. lastLine() {
  4543. let lineIndex = this.outro.lastIndexOf(n);
  4544. if (lineIndex !== -1) return this.outro.substr(lineIndex + 1);
  4545. let lineStr = this.outro;
  4546. let chunk = this.lastChunk;
  4547. do {
  4548. if (chunk.outro.length > 0) {
  4549. lineIndex = chunk.outro.lastIndexOf(n);
  4550. if (lineIndex !== -1) return chunk.outro.substr(lineIndex + 1) + lineStr;
  4551. lineStr = chunk.outro + lineStr;
  4552. }
  4553. if (chunk.content.length > 0) {
  4554. lineIndex = chunk.content.lastIndexOf(n);
  4555. if (lineIndex !== -1) return chunk.content.substr(lineIndex + 1) + lineStr;
  4556. lineStr = chunk.content + lineStr;
  4557. }
  4558. if (chunk.intro.length > 0) {
  4559. lineIndex = chunk.intro.lastIndexOf(n);
  4560. if (lineIndex !== -1) return chunk.intro.substr(lineIndex + 1) + lineStr;
  4561. lineStr = chunk.intro + lineStr;
  4562. }
  4563. } while (chunk = chunk.previous);
  4564. lineIndex = this.intro.lastIndexOf(n);
  4565. if (lineIndex !== -1) return this.intro.substr(lineIndex + 1) + lineStr;
  4566. return this.intro + lineStr;
  4567. }
  4568. slice(start = 0, end = this.original.length - this.offset) {
  4569. start = start + this.offset;
  4570. end = end + this.offset;
  4571. if (this.original.length !== 0) {
  4572. while (start < 0) start += this.original.length;
  4573. while (end < 0) end += this.original.length;
  4574. }
  4575. let result = "";
  4576. let chunk = this.firstChunk;
  4577. while (chunk && (chunk.start > start || chunk.end <= start)) {
  4578. if (chunk.start < end && chunk.end >= end) return result;
  4579. chunk = chunk.next;
  4580. }
  4581. if (chunk && chunk.edited && chunk.start !== start) throw new Error(`Cannot use replaced character ${start} as slice start anchor.`);
  4582. const startChunk = chunk;
  4583. while (chunk) {
  4584. if (chunk.intro && (startChunk !== chunk || chunk.start === start)) result += chunk.intro;
  4585. const containsEnd = chunk.start < end && chunk.end >= end;
  4586. if (containsEnd && chunk.edited && chunk.end !== end) throw new Error(`Cannot use replaced character ${end} as slice end anchor.`);
  4587. const sliceStart = startChunk === chunk ? start - chunk.start : 0;
  4588. const sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length;
  4589. result += chunk.content.slice(sliceStart, sliceEnd);
  4590. if (chunk.outro && (!containsEnd || chunk.end === end)) result += chunk.outro;
  4591. if (containsEnd) break;
  4592. chunk = chunk.next;
  4593. }
  4594. return result;
  4595. }
  4596. snip(start, end) {
  4597. const clone = this.clone();
  4598. clone.remove(0, start);
  4599. clone.remove(end, clone.original.length);
  4600. return clone;
  4601. }
  4602. _split(index) {
  4603. if (this.byStart[index] || this.byEnd[index]) return;
  4604. let chunk = this.lastSearchedChunk;
  4605. let previousChunk = chunk;
  4606. const searchForward = index > chunk.end;
  4607. while (chunk) {
  4608. if (chunk.contains(index)) return this._splitChunk(chunk, index);
  4609. chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start];
  4610. if (chunk === previousChunk) return;
  4611. previousChunk = chunk;
  4612. }
  4613. }
  4614. _splitChunk(chunk, index) {
  4615. if (chunk.edited && chunk.content.length) {
  4616. const loc = getLocator(this.original)(index);
  4617. throw new Error(`Cannot split a chunk that has already been edited (${loc.line}:${loc.column} – "${chunk.original}")`);
  4618. }
  4619. const newChunk = chunk.split(index);
  4620. this.byEnd[index] = chunk;
  4621. this.byStart[index] = newChunk;
  4622. this.byEnd[newChunk.end] = newChunk;
  4623. if (chunk === this.lastChunk) this.lastChunk = newChunk;
  4624. this.lastSearchedChunk = chunk;
  4625. return true;
  4626. }
  4627. toString() {
  4628. let str = this.intro;
  4629. let chunk = this.firstChunk;
  4630. while (chunk) {
  4631. str += chunk.toString();
  4632. chunk = chunk.next;
  4633. }
  4634. return str + this.outro;
  4635. }
  4636. isEmpty() {
  4637. let chunk = this.firstChunk;
  4638. do
  4639. if (chunk.intro.length && chunk.intro.trim() || chunk.content.length && chunk.content.trim() || chunk.outro.length && chunk.outro.trim()) return false;
  4640. while (chunk = chunk.next);
  4641. return true;
  4642. }
  4643. length() {
  4644. let chunk = this.firstChunk;
  4645. let length = 0;
  4646. do
  4647. length += chunk.intro.length + chunk.content.length + chunk.outro.length;
  4648. while (chunk = chunk.next);
  4649. return length;
  4650. }
  4651. trimLines() {
  4652. return this.trim("[\\r\\n]");
  4653. }
  4654. trim(charType) {
  4655. return this.trimStart(charType).trimEnd(charType);
  4656. }
  4657. trimEndAborted(charType) {
  4658. const rx = new RegExp((charType || "\\s") + "+$");
  4659. this.outro = this.outro.replace(rx, "");
  4660. if (this.outro.length) return true;
  4661. let chunk = this.lastChunk;
  4662. do {
  4663. const end = chunk.end;
  4664. const aborted = chunk.trimEnd(rx);
  4665. if (chunk.end !== end) {
  4666. if (this.lastChunk === chunk) this.lastChunk = chunk.next;
  4667. this.byEnd[chunk.end] = chunk;
  4668. this.byStart[chunk.next.start] = chunk.next;
  4669. this.byEnd[chunk.next.end] = chunk.next;
  4670. }
  4671. if (aborted) return true;
  4672. chunk = chunk.previous;
  4673. } while (chunk);
  4674. return false;
  4675. }
  4676. trimEnd(charType) {
  4677. this.trimEndAborted(charType);
  4678. return this;
  4679. }
  4680. trimStartAborted(charType) {
  4681. const rx = new RegExp("^" + (charType || "\\s") + "+");
  4682. this.intro = this.intro.replace(rx, "");
  4683. if (this.intro.length) return true;
  4684. let chunk = this.firstChunk;
  4685. do {
  4686. const end = chunk.end;
  4687. const aborted = chunk.trimStart(rx);
  4688. if (chunk.end !== end) {
  4689. if (chunk === this.lastChunk) this.lastChunk = chunk.next;
  4690. this.byEnd[chunk.end] = chunk;
  4691. this.byStart[chunk.next.start] = chunk.next;
  4692. this.byEnd[chunk.next.end] = chunk.next;
  4693. }
  4694. if (aborted) return true;
  4695. chunk = chunk.next;
  4696. } while (chunk);
  4697. return false;
  4698. }
  4699. trimStart(charType) {
  4700. this.trimStartAborted(charType);
  4701. return this;
  4702. }
  4703. hasChanged() {
  4704. return this.original !== this.toString();
  4705. }
  4706. _replaceRegexp(searchValue, replacement) {
  4707. function getReplacement(match, str) {
  4708. if (typeof replacement === "string") return replacement.replace(/\$(\$|&|\d+)/g, (_, i) => {
  4709. if (i === "$") return "$";
  4710. if (i === "&") return match[0];
  4711. if (+i < match.length) return match[+i];
  4712. return `$${i}`;
  4713. });
  4714. else return replacement(...match, match.index, str, match.groups);
  4715. }
  4716. function matchAll(re, str) {
  4717. let match;
  4718. const matches = [];
  4719. while (match = re.exec(str)) matches.push(match);
  4720. return matches;
  4721. }
  4722. if (searchValue.global) matchAll(searchValue, this.original).forEach((match) => {
  4723. if (match.index != null) {
  4724. const replacement = getReplacement(match, this.original);
  4725. if (replacement !== match[0]) this.overwrite(match.index, match.index + match[0].length, replacement);
  4726. }
  4727. });
  4728. else {
  4729. const match = this.original.match(searchValue);
  4730. if (match && match.index != null) {
  4731. const replacement = getReplacement(match, this.original);
  4732. if (replacement !== match[0]) this.overwrite(match.index, match.index + match[0].length, replacement);
  4733. }
  4734. }
  4735. return this;
  4736. }
  4737. _replaceString(string, replacement) {
  4738. const { original } = this;
  4739. const index = original.indexOf(string);
  4740. if (index !== -1) {
  4741. if (typeof replacement === "function") replacement = replacement(string, index, original);
  4742. if (string !== replacement) this.overwrite(index, index + string.length, replacement);
  4743. }
  4744. return this;
  4745. }
  4746. replace(searchValue, replacement) {
  4747. if (typeof searchValue === "string") return this._replaceString(searchValue, replacement);
  4748. return this._replaceRegexp(searchValue, replacement);
  4749. }
  4750. _replaceAllString(string, replacement) {
  4751. const { original } = this;
  4752. const stringLength = string.length;
  4753. for (let index = original.indexOf(string); index !== -1; index = original.indexOf(string, index + stringLength)) {
  4754. const previous = original.slice(index, index + stringLength);
  4755. let _replacement = replacement;
  4756. if (typeof replacement === "function") _replacement = replacement(previous, index, original);
  4757. if (previous !== _replacement) this.overwrite(index, index + stringLength, _replacement);
  4758. }
  4759. return this;
  4760. }
  4761. replaceAll(searchValue, replacement) {
  4762. if (typeof searchValue === "string") return this._replaceAllString(searchValue, replacement);
  4763. if (!searchValue.global) throw new TypeError("MagicString.prototype.replaceAll called with a non-global RegExp argument");
  4764. return this._replaceRegexp(searchValue, replacement);
  4765. }
  4766. };
  4767. //#endregion
  4768. //#region ../../node_modules/.pnpm/@rollup+plugin-alias@6.0.0_rollup@4.59.0/node_modules/@rollup/plugin-alias/dist/index.js
  4769. function matches$1(pattern, importee) {
  4770. if (pattern instanceof RegExp) return pattern.test(importee);
  4771. if (importee.length < pattern.length) return false;
  4772. if (importee === pattern) return true;
  4773. return importee.startsWith(pattern + "/");
  4774. }
  4775. function getEntries({ entries, customResolver }) {
  4776. if (!entries) return [];
  4777. const resolverFunctionFromOptions = resolveCustomResolver(customResolver);
  4778. if (Array.isArray(entries)) return entries.map((entry) => {
  4779. return {
  4780. find: entry.find,
  4781. replacement: entry.replacement,
  4782. resolverFunction: resolveCustomResolver(entry.customResolver) || resolverFunctionFromOptions
  4783. };
  4784. });
  4785. return Object.entries(entries).map(([key, value]) => {
  4786. return {
  4787. find: key,
  4788. replacement: value,
  4789. resolverFunction: resolverFunctionFromOptions
  4790. };
  4791. });
  4792. }
  4793. function getHookFunction(hook) {
  4794. if (typeof hook === "function") return hook;
  4795. if (hook && "handler" in hook && typeof hook.handler === "function") return hook.handler;
  4796. return null;
  4797. }
  4798. function resolveCustomResolver(customResolver) {
  4799. if (typeof customResolver === "function") return customResolver;
  4800. if (customResolver) return getHookFunction(customResolver.resolveId);
  4801. return null;
  4802. }
  4803. function alias$1(options = {}) {
  4804. const entries = getEntries(options);
  4805. if (entries.length === 0) return {
  4806. name: "alias",
  4807. resolveId: () => null
  4808. };
  4809. return {
  4810. name: "alias",
  4811. async buildStart(inputOptions) {
  4812. await Promise.all([...Array.isArray(options.entries) ? options.entries : [], options].map(({ customResolver }) => customResolver && getHookFunction(customResolver.buildStart)?.call(this, inputOptions)));
  4813. },
  4814. resolveId(importee, importer, resolveOptions) {
  4815. const matchedEntry = entries.find((entry) => matches$1(entry.find, importee));
  4816. if (!matchedEntry) return null;
  4817. const updatedId = importee.replace(matchedEntry.find, matchedEntry.replacement);
  4818. if (matchedEntry.resolverFunction) return matchedEntry.resolverFunction.call(this, updatedId, importer, resolveOptions);
  4819. return this.resolve(updatedId, importer, Object.assign({ skipSelf: true }, resolveOptions)).then((resolved) => {
  4820. if (resolved) return resolved;
  4821. 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.`);
  4822. return { id: updatedId };
  4823. });
  4824. }
  4825. };
  4826. }
  4827. //#endregion
  4828. //#region src/node/plugins/optimizedDeps.ts
  4829. const debug$13 = createDebugger("vite:optimize-deps");
  4830. function optimizedDepsPlugin() {
  4831. return {
  4832. name: "vite:optimized-deps",
  4833. applyToEnvironment(environment) {
  4834. return !isDepOptimizationDisabled(environment.config.optimizeDeps);
  4835. },
  4836. resolveId(id) {
  4837. if (this.environment.depsOptimizer?.isOptimizedDepFile(id)) return id;
  4838. },
  4839. async load(id) {
  4840. const environment = this.environment;
  4841. const depsOptimizer = environment.depsOptimizer;
  4842. if (depsOptimizer?.isOptimizedDepFile(id)) {
  4843. const metadata = depsOptimizer.metadata;
  4844. const file = cleanUrl(id);
  4845. const versionMatch = DEP_VERSION_RE.exec(id);
  4846. const browserHash = versionMatch ? versionMatch[1].split("=")[1] : void 0;
  4847. const info = optimizedDepInfoFromFile(metadata, file);
  4848. if (info) {
  4849. if (browserHash && info.browserHash !== browserHash && !environment.config.optimizeDeps.ignoreOutdatedRequests) throwOutdatedRequest(id);
  4850. try {
  4851. await info.processing;
  4852. } catch {
  4853. throwProcessingError(id);
  4854. }
  4855. const newMetadata = depsOptimizer.metadata;
  4856. if (metadata !== newMetadata) {
  4857. const currentInfo = optimizedDepInfoFromFile(newMetadata, file);
  4858. if (info.browserHash !== currentInfo?.browserHash && !environment.config.optimizeDeps.ignoreOutdatedRequests) throwOutdatedRequest(id);
  4859. }
  4860. }
  4861. debug$13?.(`load ${import_picocolors.default.cyan(file)}`);
  4862. try {
  4863. return await fsp.readFile(file, "utf-8");
  4864. } catch {
  4865. if (browserHash && !environment.config.optimizeDeps.ignoreOutdatedRequests) throwOutdatedRequest(id);
  4866. throwFileNotFoundInOptimizedDep(id);
  4867. }
  4868. }
  4869. }
  4870. };
  4871. }
  4872. function throwProcessingError(id) {
  4873. const err = /* @__PURE__ */ new Error(`Something unexpected happened while optimizing "${id}". The current page should have reloaded by now`);
  4874. err.code = ERR_OPTIMIZE_DEPS_PROCESSING_ERROR;
  4875. throw err;
  4876. }
  4877. function throwOutdatedRequest(id) {
  4878. 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.`);
  4879. err.code = ERR_OUTDATED_OPTIMIZED_DEP;
  4880. throw err;
  4881. }
  4882. function throwFileNotFoundInOptimizedDep(id) {
  4883. 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\`.`);
  4884. err.code = ERR_FILE_NOT_FOUND_IN_OPTIMIZED_DEP_DIR;
  4885. throw err;
  4886. }
  4887. //#endregion
  4888. //#region src/node/env.ts
  4889. var import_main = (/* @__PURE__ */ __commonJSMin(((exports, module) => {
  4890. function _resolveEscapeSequences(value) {
  4891. return value.replace(/\\\$/g, "$");
  4892. }
  4893. function expandValue(value, processEnv, runningParsed) {
  4894. const env = {
  4895. ...runningParsed,
  4896. ...processEnv
  4897. };
  4898. const regex = /(?<!\\)\${([^{}]+)}|(?<!\\)\$([A-Za-z_][A-Za-z0-9_]*)/g;
  4899. let result = value;
  4900. let match;
  4901. const seen = /* @__PURE__ */ new Set();
  4902. while ((match = regex.exec(result)) !== null) {
  4903. seen.add(result);
  4904. const [template, bracedExpression, unbracedExpression] = match;
  4905. const expression = bracedExpression || unbracedExpression;
  4906. const opMatch = expression.match(/(:\+|\+|:-|-)/);
  4907. const splitter = opMatch ? opMatch[0] : null;
  4908. const r = expression.split(splitter);
  4909. let defaultValue;
  4910. let value;
  4911. const key = r.shift();
  4912. if ([":+", "+"].includes(splitter)) {
  4913. defaultValue = env[key] ? r.join(splitter) : "";
  4914. value = null;
  4915. } else {
  4916. defaultValue = r.join(splitter);
  4917. value = env[key];
  4918. }
  4919. if (value) if (seen.has(value)) result = result.replace(template, defaultValue);
  4920. else result = result.replace(template, value);
  4921. else result = result.replace(template, defaultValue);
  4922. if (result === runningParsed[key]) break;
  4923. regex.lastIndex = 0;
  4924. }
  4925. return result;
  4926. }
  4927. function expand(options) {
  4928. let processEnv = process.env;
  4929. if (options && options.processEnv != null) processEnv = options.processEnv;
  4930. for (const key in options.parsed) {
  4931. let value = options.parsed[key];
  4932. if (processEnv[key] && processEnv[key] !== value) value = processEnv[key];
  4933. else value = expandValue(value, processEnv, options.parsed);
  4934. options.parsed[key] = _resolveEscapeSequences(value);
  4935. }
  4936. for (const processKey in options.parsed) processEnv[processKey] = options.parsed[processKey];
  4937. return options;
  4938. }
  4939. module.exports.expand = expand;
  4940. })))();
  4941. const debug$12 = createDebugger("vite:env");
  4942. function getEnvFilesForMode(mode, envDir) {
  4943. if (envDir !== false) return [
  4944. `.env`,
  4945. `.env.local`,
  4946. `.env.${mode}`,
  4947. `.env.${mode}.local`
  4948. ].map((file) => normalizePath(path.join(envDir, file)));
  4949. return [];
  4950. }
  4951. function loadEnv(mode, envDir, prefixes = "VITE_") {
  4952. const start = performance.now();
  4953. const getTime = () => `${(performance.now() - start).toFixed(2)}ms`;
  4954. if (mode === "local") throw new Error("\"local\" cannot be used as a mode name because it conflicts with the .local postfix for .env files.");
  4955. prefixes = arraify(prefixes);
  4956. const env = {};
  4957. const envFiles = getEnvFilesForMode(mode, envDir);
  4958. debug$12?.(`loading env files: %O`, envFiles);
  4959. const parsed = Object.fromEntries(envFiles.flatMap((filePath) => {
  4960. const stat = tryStatSync(filePath);
  4961. if (!stat || !stat.isFile() && !stat.isFIFO()) return [];
  4962. const parsedEnv = parseEnv(fs.readFileSync(filePath, "utf-8"));
  4963. return Object.entries(parsedEnv);
  4964. }));
  4965. debug$12?.(`env files loaded in ${getTime()}`);
  4966. if (parsed.NODE_ENV && process.env.VITE_USER_NODE_ENV === void 0) process.env.VITE_USER_NODE_ENV = parsed.NODE_ENV;
  4967. if (parsed.BROWSER && process.env.BROWSER === void 0) process.env.BROWSER = parsed.BROWSER;
  4968. if (parsed.BROWSER_ARGS && process.env.BROWSER_ARGS === void 0) process.env.BROWSER_ARGS = parsed.BROWSER_ARGS;
  4969. (0, import_main.expand)({
  4970. parsed,
  4971. processEnv: { ...process.env }
  4972. });
  4973. for (const [key, value] of Object.entries(parsed)) if (prefixes.some((prefix) => key.startsWith(prefix))) env[key] = value;
  4974. for (const key in process.env) if (prefixes.some((prefix) => key.startsWith(prefix))) env[key] = process.env[key];
  4975. debug$12?.(`using resolved env: %O`, env);
  4976. return env;
  4977. }
  4978. function resolveEnvPrefix({ envPrefix = "VITE_" }) {
  4979. envPrefix = arraify(envPrefix);
  4980. if (envPrefix.includes("")) throw new Error(`envPrefix option contains value '', which could lead unexpected exposure of sensitive information.`);
  4981. 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.`));
  4982. return envPrefix;
  4983. }
  4984. //#endregion
  4985. //#region src/node/deprecations.ts
  4986. const docsURL = "https://vite.dev";
  4987. const deprecationCode = {
  4988. removePluginHookSsrArgument: "this-environment-in-hooks",
  4989. removePluginHookHandleHotUpdate: "hotupdate-hook",
  4990. removeServerModuleGraph: "per-environment-apis",
  4991. removeServerReloadModule: "per-environment-apis",
  4992. removeServerPluginContainer: "per-environment-apis",
  4993. removeServerHot: "per-environment-apis",
  4994. removeServerTransformRequest: "per-environment-apis",
  4995. removeServerWarmupRequest: "per-environment-apis",
  4996. removeSsrLoadModule: "ssr-using-modulerunner"
  4997. };
  4998. const deprecationMessages = {
  4999. removePluginHookSsrArgument: "Plugin hook `options.ssr` is replaced with `this.environment.config.consumer === 'server'`.",
  5000. removePluginHookHandleHotUpdate: "Plugin hook `handleHotUpdate()` is replaced with `hotUpdate()`.",
  5001. removeServerModuleGraph: "The `server.moduleGraph` is replaced with `this.environment.moduleGraph`.",
  5002. removeServerReloadModule: "The `server.reloadModule` is replaced with `environment.reloadModule`.",
  5003. removeServerPluginContainer: "The `server.pluginContainer` is replaced with `this.environment.pluginContainer`.",
  5004. removeServerHot: "The `server.hot` is replaced with `this.environment.hot`.",
  5005. removeServerTransformRequest: "The `server.transformRequest` is replaced with `this.environment.transformRequest`.",
  5006. removeServerWarmupRequest: "The `server.warmupRequest` is replaced with `this.environment.warmupRequest`.",
  5007. removeSsrLoadModule: "The `server.ssrLoadModule` is replaced with Environment Runner."
  5008. };
  5009. let _ignoreDeprecationWarnings = false;
  5010. function isFutureDeprecationEnabled(config, type) {
  5011. return !!config.future?.[type];
  5012. }
  5013. /**
  5014. * Warn about future deprecations.
  5015. */
  5016. function warnFutureDeprecation(config, type, extraMessage, stacktrace = true) {
  5017. if (_ignoreDeprecationWarnings || !config.future || config.future[type] !== "warn") return;
  5018. let msg = `[vite future] ${deprecationMessages[type]}`;
  5019. if (extraMessage) msg += ` ${extraMessage}`;
  5020. msg = import_picocolors.default.yellow(msg);
  5021. const docs = `${docsURL}/changes/${deprecationCode[type].toLowerCase()}`;
  5022. msg += import_picocolors.default.gray(`\n ${stacktrace ? "├" : "└"}─── `) + import_picocolors.default.underline(docs) + "\n";
  5023. if (stacktrace) {
  5024. const stack = (/* @__PURE__ */ new Error()).stack;
  5025. if (stack) {
  5026. let stacks = stack.split("\n").slice(3).filter((i) => !i.includes("/node_modules/vite/dist/"));
  5027. if (stacks.length === 0) stacks.push("No stack trace found.");
  5028. stacks = stacks.map((i, idx) => ` ${idx === stacks.length - 1 ? "└" : "│"} ${i.trim()}`);
  5029. msg += import_picocolors.default.dim(stacks.join("\n")) + "\n";
  5030. }
  5031. }
  5032. config.logger.warnOnce(msg);
  5033. }
  5034. function ignoreDeprecationWarnings(fn) {
  5035. const before = _ignoreDeprecationWarnings;
  5036. _ignoreDeprecationWarnings = true;
  5037. const ret = fn();
  5038. _ignoreDeprecationWarnings = before;
  5039. return ret;
  5040. }
  5041. //#endregion
  5042. //#region src/node/server/middlewares/error.ts
  5043. function prepareError(err) {
  5044. return {
  5045. message: stripVTControlCharacters(err.message),
  5046. stack: stripVTControlCharacters(cleanStack(err.stack || "")),
  5047. id: err.id,
  5048. frame: stripVTControlCharacters(err.frame || ""),
  5049. plugin: err.plugin,
  5050. pluginCode: err.pluginCode?.toString(),
  5051. loc: err.loc
  5052. };
  5053. }
  5054. function buildErrorMessage(err, args = [], includeStack = true) {
  5055. if (err.plugin) args.push(` Plugin: ${import_picocolors.default.magenta(err.plugin)}`);
  5056. const loc = err.loc ? `:${err.loc.line}:${err.loc.column}` : "";
  5057. if (err.id) args.push(` File: ${import_picocolors.default.cyan(err.id)}${loc}`);
  5058. if (err.frame) args.push(import_picocolors.default.yellow(pad(err.frame)));
  5059. if (includeStack && err.stack) args.push(pad(cleanStack(err.stack)));
  5060. return args.join("\n");
  5061. }
  5062. function cleanStack(stack) {
  5063. return stack.split(/\n/).filter((l) => /^\s*at/.test(l)).join("\n");
  5064. }
  5065. function logError(server, err) {
  5066. const msg = buildErrorMessage(err, [import_picocolors.default.red(`Internal server error: ${err.message}`)]);
  5067. server.config.logger.error(msg, {
  5068. clear: true,
  5069. timestamp: true,
  5070. error: err
  5071. });
  5072. server.environments.client.hot.send({
  5073. type: "error",
  5074. err: prepareError(err)
  5075. });
  5076. }
  5077. function errorMiddleware(server, allowNext = false) {
  5078. return function viteErrorMiddleware(err, _req, res, next) {
  5079. logError(server, err);
  5080. if (allowNext) next();
  5081. else {
  5082. res.statusCode = 500;
  5083. res.end(`
  5084. <!DOCTYPE html>
  5085. <html lang="en">
  5086. <head>
  5087. <meta charset="UTF-8" />
  5088. <title>Error</title>
  5089. <script type="module">
  5090. const error = ${JSON.stringify(prepareError(err)).replace(/</g, "\\u003c")}
  5091. try {
  5092. const { ErrorOverlay } = await import(${JSON.stringify(path.posix.join(server.config.base, CLIENT_PUBLIC_PATH))})
  5093. document.body.appendChild(new ErrorOverlay(error))
  5094. } catch {
  5095. const h = (tag, text) => {
  5096. const el = document.createElement(tag)
  5097. el.textContent = text
  5098. return el
  5099. }
  5100. document.body.appendChild(h('h1', 'Internal Server Error'))
  5101. document.body.appendChild(h('h2', error.message))
  5102. document.body.appendChild(h('pre', error.stack))
  5103. document.body.appendChild(h('p', '(Error overlay failed to load)'))
  5104. }
  5105. <\/script>
  5106. </head>
  5107. <body>
  5108. </body>
  5109. </html>
  5110. `);
  5111. }
  5112. };
  5113. }
  5114. //#endregion
  5115. //#region ../../node_modules/.pnpm/encodeurl@1.0.2/node_modules/encodeurl/index.js
  5116. /*!
  5117. * encodeurl
  5118. * Copyright(c) 2016 Douglas Christopher Wilson
  5119. * MIT Licensed
  5120. */
  5121. var require_encodeurl = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  5122. /**
  5123. * Module exports.
  5124. * @public
  5125. */
  5126. module.exports = encodeUrl;
  5127. /**
  5128. * RegExp to match non-URL code points, *after* encoding (i.e. not including "%")
  5129. * and including invalid escape sequences.
  5130. * @private
  5131. */
  5132. 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;
  5133. /**
  5134. * RegExp to match unmatched surrogate pair.
  5135. * @private
  5136. */
  5137. var UNMATCHED_SURROGATE_PAIR_REGEXP = /(^|[^\uD800-\uDBFF])[\uDC00-\uDFFF]|[\uD800-\uDBFF]([^\uDC00-\uDFFF]|$)/g;
  5138. /**
  5139. * String to replace unmatched surrogate pair with.
  5140. * @private
  5141. */
  5142. var UNMATCHED_SURROGATE_PAIR_REPLACE = "$1�$2";
  5143. /**
  5144. * Encode a URL to a percent-encoded form, excluding already-encoded sequences.
  5145. *
  5146. * This function will take an already-encoded URL and encode all the non-URL
  5147. * code points. This function will not encode the "%" character unless it is
  5148. * not part of a valid sequence (`%20` will be left as-is, but `%foo` will
  5149. * be encoded as `%25foo`).
  5150. *
  5151. * This encode is meant to be "safe" and does not throw errors. It will try as
  5152. * hard as it can to properly encode the given URL, including replacing any raw,
  5153. * unpaired surrogate pairs with the Unicode replacement character prior to
  5154. * encoding.
  5155. *
  5156. * @param {string} url
  5157. * @return {string}
  5158. * @public
  5159. */
  5160. function encodeUrl(url) {
  5161. return String(url).replace(UNMATCHED_SURROGATE_PAIR_REGEXP, UNMATCHED_SURROGATE_PAIR_REPLACE).replace(ENCODE_CHARS_REGEXP, encodeURI);
  5162. }
  5163. }));
  5164. //#endregion
  5165. //#region ../../node_modules/.pnpm/escape-html@1.0.3/node_modules/escape-html/index.js
  5166. /*!
  5167. * escape-html
  5168. * Copyright(c) 2012-2013 TJ Holowaychuk
  5169. * Copyright(c) 2015 Andreas Lubbe
  5170. * Copyright(c) 2015 Tiancheng "Timothy" Gu
  5171. * MIT Licensed
  5172. */
  5173. var require_escape_html = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  5174. /**
  5175. * Module variables.
  5176. * @private
  5177. */
  5178. var matchHtmlRegExp = /["'&<>]/;
  5179. /**
  5180. * Module exports.
  5181. * @public
  5182. */
  5183. module.exports = escapeHtml;
  5184. /**
  5185. * Escape special characters in the given string of html.
  5186. *
  5187. * @param {string} string The string to escape for inserting into HTML
  5188. * @return {string}
  5189. * @public
  5190. */
  5191. function escapeHtml(string) {
  5192. var str = "" + string;
  5193. var match = matchHtmlRegExp.exec(str);
  5194. if (!match) return str;
  5195. var escape;
  5196. var html = "";
  5197. var index = 0;
  5198. var lastIndex = 0;
  5199. for (index = match.index; index < str.length; index++) {
  5200. switch (str.charCodeAt(index)) {
  5201. case 34:
  5202. escape = "&quot;";
  5203. break;
  5204. case 38:
  5205. escape = "&amp;";
  5206. break;
  5207. case 39:
  5208. escape = "&#39;";
  5209. break;
  5210. case 60:
  5211. escape = "&lt;";
  5212. break;
  5213. case 62:
  5214. escape = "&gt;";
  5215. break;
  5216. default: continue;
  5217. }
  5218. if (lastIndex !== index) html += str.substring(lastIndex, index);
  5219. lastIndex = index + 1;
  5220. html += escape;
  5221. }
  5222. return lastIndex !== index ? html + str.substring(lastIndex, index) : html;
  5223. }
  5224. }));
  5225. //#endregion
  5226. //#region ../../node_modules/.pnpm/ee-first@1.1.1/node_modules/ee-first/index.js
  5227. /*!
  5228. * ee-first
  5229. * Copyright(c) 2014 Jonathan Ong
  5230. * MIT Licensed
  5231. */
  5232. var require_ee_first = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  5233. /**
  5234. * Module exports.
  5235. * @public
  5236. */
  5237. module.exports = first;
  5238. /**
  5239. * Get the first event in a set of event emitters and event pairs.
  5240. *
  5241. * @param {array} stuff
  5242. * @param {function} done
  5243. * @public
  5244. */
  5245. function first(stuff, done) {
  5246. if (!Array.isArray(stuff)) throw new TypeError("arg must be an array of [ee, events...] arrays");
  5247. var cleanups = [];
  5248. for (var i = 0; i < stuff.length; i++) {
  5249. var arr = stuff[i];
  5250. if (!Array.isArray(arr) || arr.length < 2) throw new TypeError("each array member must be [ee, events...]");
  5251. var ee = arr[0];
  5252. for (var j = 1; j < arr.length; j++) {
  5253. var event = arr[j];
  5254. var fn = listener(event, callback);
  5255. ee.on(event, fn);
  5256. cleanups.push({
  5257. ee,
  5258. event,
  5259. fn
  5260. });
  5261. }
  5262. }
  5263. function callback() {
  5264. cleanup();
  5265. done.apply(null, arguments);
  5266. }
  5267. function cleanup() {
  5268. var x;
  5269. for (var i = 0; i < cleanups.length; i++) {
  5270. x = cleanups[i];
  5271. x.ee.removeListener(x.event, x.fn);
  5272. }
  5273. }
  5274. function thunk(fn) {
  5275. done = fn;
  5276. }
  5277. thunk.cancel = cleanup;
  5278. return thunk;
  5279. }
  5280. /**
  5281. * Create the event listener.
  5282. * @private
  5283. */
  5284. function listener(event, done) {
  5285. return function onevent(arg1) {
  5286. var args = new Array(arguments.length);
  5287. var ee = this;
  5288. var err = event === "error" ? arg1 : null;
  5289. for (var i = 0; i < args.length; i++) args[i] = arguments[i];
  5290. done(err, ee, event, args);
  5291. };
  5292. }
  5293. }));
  5294. //#endregion
  5295. //#region ../../node_modules/.pnpm/on-finished@2.3.0/node_modules/on-finished/index.js
  5296. /*!
  5297. * on-finished
  5298. * Copyright(c) 2013 Jonathan Ong
  5299. * Copyright(c) 2014 Douglas Christopher Wilson
  5300. * MIT Licensed
  5301. */
  5302. var require_on_finished = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  5303. /**
  5304. * Module exports.
  5305. * @public
  5306. */
  5307. module.exports = onFinished;
  5308. module.exports.isFinished = isFinished;
  5309. /**
  5310. * Module dependencies.
  5311. * @private
  5312. */
  5313. var first = require_ee_first();
  5314. /**
  5315. * Variables.
  5316. * @private
  5317. */
  5318. /* istanbul ignore next */
  5319. var defer = typeof setImmediate === "function" ? setImmediate : function(fn) {
  5320. process.nextTick(fn.bind.apply(fn, arguments));
  5321. };
  5322. /**
  5323. * Invoke callback when the response has finished, useful for
  5324. * cleaning up resources afterwards.
  5325. *
  5326. * @param {object} msg
  5327. * @param {function} listener
  5328. * @return {object}
  5329. * @public
  5330. */
  5331. function onFinished(msg, listener) {
  5332. if (isFinished(msg) !== false) {
  5333. defer(listener, null, msg);
  5334. return msg;
  5335. }
  5336. attachListener(msg, listener);
  5337. return msg;
  5338. }
  5339. /**
  5340. * Determine if message is already finished.
  5341. *
  5342. * @param {object} msg
  5343. * @return {boolean}
  5344. * @public
  5345. */
  5346. function isFinished(msg) {
  5347. var socket = msg.socket;
  5348. if (typeof msg.finished === "boolean") return Boolean(msg.finished || socket && !socket.writable);
  5349. if (typeof msg.complete === "boolean") return Boolean(msg.upgrade || !socket || !socket.readable || msg.complete && !msg.readable);
  5350. }
  5351. /**
  5352. * Attach a finished listener to the message.
  5353. *
  5354. * @param {object} msg
  5355. * @param {function} callback
  5356. * @private
  5357. */
  5358. function attachFinishedListener(msg, callback) {
  5359. var eeMsg;
  5360. var eeSocket;
  5361. var finished = false;
  5362. function onFinish(error) {
  5363. eeMsg.cancel();
  5364. eeSocket.cancel();
  5365. finished = true;
  5366. callback(error);
  5367. }
  5368. eeMsg = eeSocket = first([[
  5369. msg,
  5370. "end",
  5371. "finish"
  5372. ]], onFinish);
  5373. function onSocket(socket) {
  5374. msg.removeListener("socket", onSocket);
  5375. if (finished) return;
  5376. if (eeMsg !== eeSocket) return;
  5377. eeSocket = first([[
  5378. socket,
  5379. "error",
  5380. "close"
  5381. ]], onFinish);
  5382. }
  5383. if (msg.socket) {
  5384. onSocket(msg.socket);
  5385. return;
  5386. }
  5387. msg.on("socket", onSocket);
  5388. if (msg.socket === void 0) patchAssignSocket(msg, onSocket);
  5389. }
  5390. /**
  5391. * Attach the listener to the message.
  5392. *
  5393. * @param {object} msg
  5394. * @return {function}
  5395. * @private
  5396. */
  5397. function attachListener(msg, listener) {
  5398. var attached = msg.__onFinished;
  5399. if (!attached || !attached.queue) {
  5400. attached = msg.__onFinished = createListener(msg);
  5401. attachFinishedListener(msg, attached);
  5402. }
  5403. attached.queue.push(listener);
  5404. }
  5405. /**
  5406. * Create listener on message.
  5407. *
  5408. * @param {object} msg
  5409. * @return {function}
  5410. * @private
  5411. */
  5412. function createListener(msg) {
  5413. function listener(err) {
  5414. if (msg.__onFinished === listener) msg.__onFinished = null;
  5415. if (!listener.queue) return;
  5416. var queue = listener.queue;
  5417. listener.queue = null;
  5418. for (var i = 0; i < queue.length; i++) queue[i](err, msg);
  5419. }
  5420. listener.queue = [];
  5421. return listener;
  5422. }
  5423. /**
  5424. * Patch ServerResponse.prototype.assignSocket for node.js 0.8.
  5425. *
  5426. * @param {ServerResponse} res
  5427. * @param {function} callback
  5428. * @private
  5429. */
  5430. function patchAssignSocket(res, callback) {
  5431. var assignSocket = res.assignSocket;
  5432. if (typeof assignSocket !== "function") return;
  5433. res.assignSocket = function _assignSocket(socket) {
  5434. assignSocket.call(this, socket);
  5435. callback(socket);
  5436. };
  5437. }
  5438. }));
  5439. //#endregion
  5440. //#region ../../node_modules/.pnpm/parseurl@1.3.3/node_modules/parseurl/index.js
  5441. /*!
  5442. * parseurl
  5443. * Copyright(c) 2014 Jonathan Ong
  5444. * Copyright(c) 2014-2017 Douglas Christopher Wilson
  5445. * MIT Licensed
  5446. */
  5447. var require_parseurl = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  5448. /**
  5449. * Module dependencies.
  5450. * @private
  5451. */
  5452. var url$2 = __require("url");
  5453. var parse = url$2.parse;
  5454. var Url = url$2.Url;
  5455. /**
  5456. * Module exports.
  5457. * @public
  5458. */
  5459. module.exports = parseurl;
  5460. module.exports.original = originalurl;
  5461. /**
  5462. * Parse the `req` url with memoization.
  5463. *
  5464. * @param {ServerRequest} req
  5465. * @return {Object}
  5466. * @public
  5467. */
  5468. function parseurl(req) {
  5469. var url = req.url;
  5470. if (url === void 0) return;
  5471. var parsed = req._parsedUrl;
  5472. if (fresh(url, parsed)) return parsed;
  5473. parsed = fastparse(url);
  5474. parsed._raw = url;
  5475. return req._parsedUrl = parsed;
  5476. }
  5477. /**
  5478. * Parse the `req` original url with fallback and memoization.
  5479. *
  5480. * @param {ServerRequest} req
  5481. * @return {Object}
  5482. * @public
  5483. */
  5484. function originalurl(req) {
  5485. var url = req.originalUrl;
  5486. if (typeof url !== "string") return parseurl(req);
  5487. var parsed = req._parsedOriginalUrl;
  5488. if (fresh(url, parsed)) return parsed;
  5489. parsed = fastparse(url);
  5490. parsed._raw = url;
  5491. return req._parsedOriginalUrl = parsed;
  5492. }
  5493. /**
  5494. * Parse the `str` url with fast-path short-cut.
  5495. *
  5496. * @param {string} str
  5497. * @return {Object}
  5498. * @private
  5499. */
  5500. function fastparse(str) {
  5501. if (typeof str !== "string" || str.charCodeAt(0) !== 47) return parse(str);
  5502. var pathname = str;
  5503. var query = null;
  5504. var search = null;
  5505. for (var i = 1; i < str.length; i++) switch (str.charCodeAt(i)) {
  5506. case 63:
  5507. if (search === null) {
  5508. pathname = str.substring(0, i);
  5509. query = str.substring(i + 1);
  5510. search = str.substring(i);
  5511. }
  5512. break;
  5513. case 9:
  5514. case 10:
  5515. case 12:
  5516. case 13:
  5517. case 32:
  5518. case 35:
  5519. case 160:
  5520. case 65279: return parse(str);
  5521. }
  5522. var url = Url !== void 0 ? new Url() : {};
  5523. url.path = str;
  5524. url.href = str;
  5525. url.pathname = pathname;
  5526. if (search !== null) {
  5527. url.query = query;
  5528. url.search = search;
  5529. }
  5530. return url;
  5531. }
  5532. /**
  5533. * Determine if parsed is still fresh for url.
  5534. *
  5535. * @param {string} url
  5536. * @param {object} parsedUrl
  5537. * @return {boolean}
  5538. * @private
  5539. */
  5540. function fresh(url, parsedUrl) {
  5541. return typeof parsedUrl === "object" && parsedUrl !== null && (Url === void 0 || parsedUrl instanceof Url) && parsedUrl._raw === url;
  5542. }
  5543. }));
  5544. //#endregion
  5545. //#region ../../node_modules/.pnpm/statuses@1.5.0/node_modules/statuses/codes.json
  5546. var require_codes = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  5547. module.exports = {
  5548. "100": "Continue",
  5549. "101": "Switching Protocols",
  5550. "102": "Processing",
  5551. "103": "Early Hints",
  5552. "200": "OK",
  5553. "201": "Created",
  5554. "202": "Accepted",
  5555. "203": "Non-Authoritative Information",
  5556. "204": "No Content",
  5557. "205": "Reset Content",
  5558. "206": "Partial Content",
  5559. "207": "Multi-Status",
  5560. "208": "Already Reported",
  5561. "226": "IM Used",
  5562. "300": "Multiple Choices",
  5563. "301": "Moved Permanently",
  5564. "302": "Found",
  5565. "303": "See Other",
  5566. "304": "Not Modified",
  5567. "305": "Use Proxy",
  5568. "306": "(Unused)",
  5569. "307": "Temporary Redirect",
  5570. "308": "Permanent Redirect",
  5571. "400": "Bad Request",
  5572. "401": "Unauthorized",
  5573. "402": "Payment Required",
  5574. "403": "Forbidden",
  5575. "404": "Not Found",
  5576. "405": "Method Not Allowed",
  5577. "406": "Not Acceptable",
  5578. "407": "Proxy Authentication Required",
  5579. "408": "Request Timeout",
  5580. "409": "Conflict",
  5581. "410": "Gone",
  5582. "411": "Length Required",
  5583. "412": "Precondition Failed",
  5584. "413": "Payload Too Large",
  5585. "414": "URI Too Long",
  5586. "415": "Unsupported Media Type",
  5587. "416": "Range Not Satisfiable",
  5588. "417": "Expectation Failed",
  5589. "418": "I'm a teapot",
  5590. "421": "Misdirected Request",
  5591. "422": "Unprocessable Entity",
  5592. "423": "Locked",
  5593. "424": "Failed Dependency",
  5594. "425": "Unordered Collection",
  5595. "426": "Upgrade Required",
  5596. "428": "Precondition Required",
  5597. "429": "Too Many Requests",
  5598. "431": "Request Header Fields Too Large",
  5599. "451": "Unavailable For Legal Reasons",
  5600. "500": "Internal Server Error",
  5601. "501": "Not Implemented",
  5602. "502": "Bad Gateway",
  5603. "503": "Service Unavailable",
  5604. "504": "Gateway Timeout",
  5605. "505": "HTTP Version Not Supported",
  5606. "506": "Variant Also Negotiates",
  5607. "507": "Insufficient Storage",
  5608. "508": "Loop Detected",
  5609. "509": "Bandwidth Limit Exceeded",
  5610. "510": "Not Extended",
  5611. "511": "Network Authentication Required"
  5612. };
  5613. }));
  5614. //#endregion
  5615. //#region ../../node_modules/.pnpm/statuses@1.5.0/node_modules/statuses/index.js
  5616. /*!
  5617. * statuses
  5618. * Copyright(c) 2014 Jonathan Ong
  5619. * Copyright(c) 2016 Douglas Christopher Wilson
  5620. * MIT Licensed
  5621. */
  5622. var require_statuses = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  5623. /**
  5624. * Module dependencies.
  5625. * @private
  5626. */
  5627. var codes = require_codes();
  5628. /**
  5629. * Module exports.
  5630. * @public
  5631. */
  5632. module.exports = status;
  5633. status.STATUS_CODES = codes;
  5634. status.codes = populateStatusesMap(status, codes);
  5635. status.redirect = {
  5636. 300: true,
  5637. 301: true,
  5638. 302: true,
  5639. 303: true,
  5640. 305: true,
  5641. 307: true,
  5642. 308: true
  5643. };
  5644. status.empty = {
  5645. 204: true,
  5646. 205: true,
  5647. 304: true
  5648. };
  5649. status.retry = {
  5650. 502: true,
  5651. 503: true,
  5652. 504: true
  5653. };
  5654. /**
  5655. * Populate the statuses map for given codes.
  5656. * @private
  5657. */
  5658. function populateStatusesMap(statuses, codes) {
  5659. var arr = [];
  5660. Object.keys(codes).forEach(function forEachCode(code) {
  5661. var message = codes[code];
  5662. var status = Number(code);
  5663. statuses[status] = message;
  5664. statuses[message] = status;
  5665. statuses[message.toLowerCase()] = status;
  5666. arr.push(status);
  5667. });
  5668. return arr;
  5669. }
  5670. /**
  5671. * Get the status code.
  5672. *
  5673. * Given a number, this will throw if it is not a known status
  5674. * code, otherwise the code will be returned. Given a string,
  5675. * the string will be parsed for a number and return the code
  5676. * if valid, otherwise will lookup the code assuming this is
  5677. * the status message.
  5678. *
  5679. * @param {string|number} code
  5680. * @returns {number}
  5681. * @public
  5682. */
  5683. function status(code) {
  5684. if (typeof code === "number") {
  5685. if (!status[code]) throw new Error("invalid status code: " + code);
  5686. return code;
  5687. }
  5688. if (typeof code !== "string") throw new TypeError("code must be a number or string");
  5689. var n = parseInt(code, 10);
  5690. if (!isNaN(n)) {
  5691. if (!status[n]) throw new Error("invalid status code: " + n);
  5692. return n;
  5693. }
  5694. n = status[code.toLowerCase()];
  5695. if (!n) throw new Error("invalid status message: \"" + code + "\"");
  5696. return n;
  5697. }
  5698. }));
  5699. //#endregion
  5700. //#region ../../node_modules/.pnpm/unpipe@1.0.0/node_modules/unpipe/index.js
  5701. /*!
  5702. * unpipe
  5703. * Copyright(c) 2015 Douglas Christopher Wilson
  5704. * MIT Licensed
  5705. */
  5706. var require_unpipe = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  5707. /**
  5708. * Module exports.
  5709. * @public
  5710. */
  5711. module.exports = unpipe;
  5712. /**
  5713. * Determine if there are Node.js pipe-like data listeners.
  5714. * @private
  5715. */
  5716. function hasPipeDataListeners(stream) {
  5717. var listeners = stream.listeners("data");
  5718. for (var i = 0; i < listeners.length; i++) if (listeners[i].name === "ondata") return true;
  5719. return false;
  5720. }
  5721. /**
  5722. * Unpipe a stream from all destinations.
  5723. *
  5724. * @param {object} stream
  5725. * @public
  5726. */
  5727. function unpipe(stream) {
  5728. if (!stream) throw new TypeError("argument stream is required");
  5729. if (typeof stream.unpipe === "function") {
  5730. stream.unpipe();
  5731. return;
  5732. }
  5733. if (!hasPipeDataListeners(stream)) return;
  5734. var listener;
  5735. var listeners = stream.listeners("close");
  5736. for (var i = 0; i < listeners.length; i++) {
  5737. listener = listeners[i];
  5738. if (listener.name !== "cleanup" && listener.name !== "onclose") continue;
  5739. listener.call(stream);
  5740. }
  5741. }
  5742. }));
  5743. //#endregion
  5744. //#region ../../node_modules/.pnpm/finalhandler@1.1.2_ms@2.1.3/node_modules/finalhandler/index.js
  5745. /*!
  5746. * finalhandler
  5747. * Copyright(c) 2014-2017 Douglas Christopher Wilson
  5748. * MIT Licensed
  5749. */
  5750. var require_finalhandler = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  5751. /**
  5752. * Module dependencies.
  5753. * @private
  5754. */
  5755. var debug = (init_node(), __toCommonJS(node_exports))("finalhandler");
  5756. var encodeUrl = require_encodeurl();
  5757. var escapeHtml = require_escape_html();
  5758. var onFinished = require_on_finished();
  5759. var parseUrl = require_parseurl();
  5760. var statuses = require_statuses();
  5761. var unpipe = require_unpipe();
  5762. /**
  5763. * Module variables.
  5764. * @private
  5765. */
  5766. var DOUBLE_SPACE_REGEXP = /\x20{2}/g;
  5767. var NEWLINE_REGEXP = /\n/g;
  5768. /* istanbul ignore next */
  5769. var defer = typeof setImmediate === "function" ? setImmediate : function(fn) {
  5770. process.nextTick(fn.bind.apply(fn, arguments));
  5771. };
  5772. var isFinished = onFinished.isFinished;
  5773. /**
  5774. * Create a minimal HTML document.
  5775. *
  5776. * @param {string} message
  5777. * @private
  5778. */
  5779. function createHtmlDocument(message) {
  5780. 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";
  5781. }
  5782. /**
  5783. * Module exports.
  5784. * @public
  5785. */
  5786. module.exports = finalhandler;
  5787. /**
  5788. * Create a function to handle the final response.
  5789. *
  5790. * @param {Request} req
  5791. * @param {Response} res
  5792. * @param {Object} [options]
  5793. * @return {Function}
  5794. * @public
  5795. */
  5796. function finalhandler(req, res, options) {
  5797. var opts = options || {};
  5798. var env = opts.env || process.env.NODE_ENV || "development";
  5799. var onerror = opts.onerror;
  5800. return function(err) {
  5801. var headers;
  5802. var msg;
  5803. var status;
  5804. if (!err && headersSent(res)) {
  5805. debug("cannot 404 after headers sent");
  5806. return;
  5807. }
  5808. if (err) {
  5809. status = getErrorStatusCode(err);
  5810. if (status === void 0) status = getResponseStatusCode(res);
  5811. else headers = getErrorHeaders(err);
  5812. msg = getErrorMessage(err, status, env);
  5813. } else {
  5814. status = 404;
  5815. msg = "Cannot " + req.method + " " + encodeUrl(getResourceName(req));
  5816. }
  5817. debug("default %s", status);
  5818. if (err && onerror) defer(onerror, err, req, res);
  5819. if (headersSent(res)) {
  5820. debug("cannot %d after headers sent", status);
  5821. req.socket.destroy();
  5822. return;
  5823. }
  5824. send(req, res, status, headers, msg);
  5825. };
  5826. }
  5827. /**
  5828. * Get headers from Error object.
  5829. *
  5830. * @param {Error} err
  5831. * @return {object}
  5832. * @private
  5833. */
  5834. function getErrorHeaders(err) {
  5835. if (!err.headers || typeof err.headers !== "object") return;
  5836. var headers = Object.create(null);
  5837. var keys = Object.keys(err.headers);
  5838. for (var i = 0; i < keys.length; i++) {
  5839. var key = keys[i];
  5840. headers[key] = err.headers[key];
  5841. }
  5842. return headers;
  5843. }
  5844. /**
  5845. * Get message from Error object, fallback to status message.
  5846. *
  5847. * @param {Error} err
  5848. * @param {number} status
  5849. * @param {string} env
  5850. * @return {string}
  5851. * @private
  5852. */
  5853. function getErrorMessage(err, status, env) {
  5854. var msg;
  5855. if (env !== "production") {
  5856. msg = err.stack;
  5857. if (!msg && typeof err.toString === "function") msg = err.toString();
  5858. }
  5859. return msg || statuses[status];
  5860. }
  5861. /**
  5862. * Get status code from Error object.
  5863. *
  5864. * @param {Error} err
  5865. * @return {number}
  5866. * @private
  5867. */
  5868. function getErrorStatusCode(err) {
  5869. if (typeof err.status === "number" && err.status >= 400 && err.status < 600) return err.status;
  5870. if (typeof err.statusCode === "number" && err.statusCode >= 400 && err.statusCode < 600) return err.statusCode;
  5871. }
  5872. /**
  5873. * Get resource name for the request.
  5874. *
  5875. * This is typically just the original pathname of the request
  5876. * but will fallback to "resource" is that cannot be determined.
  5877. *
  5878. * @param {IncomingMessage} req
  5879. * @return {string}
  5880. * @private
  5881. */
  5882. function getResourceName(req) {
  5883. try {
  5884. return parseUrl.original(req).pathname;
  5885. } catch (e) {
  5886. return "resource";
  5887. }
  5888. }
  5889. /**
  5890. * Get status code from response.
  5891. *
  5892. * @param {OutgoingMessage} res
  5893. * @return {number}
  5894. * @private
  5895. */
  5896. function getResponseStatusCode(res) {
  5897. var status = res.statusCode;
  5898. if (typeof status !== "number" || status < 400 || status > 599) status = 500;
  5899. return status;
  5900. }
  5901. /**
  5902. * Determine if the response headers have been sent.
  5903. *
  5904. * @param {object} res
  5905. * @returns {boolean}
  5906. * @private
  5907. */
  5908. function headersSent(res) {
  5909. return typeof res.headersSent !== "boolean" ? Boolean(res._header) : res.headersSent;
  5910. }
  5911. /**
  5912. * Send response.
  5913. *
  5914. * @param {IncomingMessage} req
  5915. * @param {OutgoingMessage} res
  5916. * @param {number} status
  5917. * @param {object} headers
  5918. * @param {string} message
  5919. * @private
  5920. */
  5921. function send(req, res, status, headers, message) {
  5922. function write() {
  5923. var body = createHtmlDocument(message);
  5924. res.statusCode = status;
  5925. res.statusMessage = statuses[status];
  5926. setHeaders(res, headers);
  5927. res.setHeader("Content-Security-Policy", "default-src 'none'");
  5928. res.setHeader("X-Content-Type-Options", "nosniff");
  5929. res.setHeader("Content-Type", "text/html; charset=utf-8");
  5930. res.setHeader("Content-Length", Buffer.byteLength(body, "utf8"));
  5931. if (req.method === "HEAD") {
  5932. res.end();
  5933. return;
  5934. }
  5935. res.end(body, "utf8");
  5936. }
  5937. if (isFinished(req)) {
  5938. write();
  5939. return;
  5940. }
  5941. unpipe(req);
  5942. onFinished(req, write);
  5943. req.resume();
  5944. }
  5945. /**
  5946. * Set response headers from an object.
  5947. *
  5948. * @param {OutgoingMessage} res
  5949. * @param {object} headers
  5950. * @private
  5951. */
  5952. function setHeaders(res, headers) {
  5953. if (!headers) return;
  5954. var keys = Object.keys(headers);
  5955. for (var i = 0; i < keys.length; i++) {
  5956. var key = keys[i];
  5957. res.setHeader(key, headers[key]);
  5958. }
  5959. }
  5960. }));
  5961. //#endregion
  5962. //#region ../../node_modules/.pnpm/utils-merge@1.0.1/node_modules/utils-merge/index.js
  5963. var require_utils_merge = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  5964. /**
  5965. * Merge object b with object a.
  5966. *
  5967. * var a = { foo: 'bar' }
  5968. * , b = { bar: 'baz' };
  5969. *
  5970. * merge(a, b);
  5971. * // => { foo: 'bar', bar: 'baz' }
  5972. *
  5973. * @param {Object} a
  5974. * @param {Object} b
  5975. * @return {Object}
  5976. * @api public
  5977. */
  5978. exports = module.exports = function(a, b) {
  5979. if (a && b) for (var key in b) a[key] = b[key];
  5980. return a;
  5981. };
  5982. }));
  5983. //#endregion
  5984. //#region ../../node_modules/.pnpm/connect@3.7.0_ms@2.1.3/node_modules/connect/index.js
  5985. /*!
  5986. * connect
  5987. * Copyright(c) 2010 Sencha Inc.
  5988. * Copyright(c) 2011 TJ Holowaychuk
  5989. * Copyright(c) 2015 Douglas Christopher Wilson
  5990. * MIT Licensed
  5991. */
  5992. var require_connect = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  5993. /**
  5994. * Module dependencies.
  5995. * @private
  5996. */
  5997. var debug = (init_node(), __toCommonJS(node_exports))("connect:dispatcher");
  5998. var EventEmitter$4 = __require("events").EventEmitter;
  5999. var finalhandler = require_finalhandler();
  6000. var http$6 = __require("http");
  6001. var merge = require_utils_merge();
  6002. var parseUrl = require_parseurl();
  6003. /**
  6004. * Module exports.
  6005. * @public
  6006. */
  6007. module.exports = createServer;
  6008. /**
  6009. * Module variables.
  6010. * @private
  6011. */
  6012. var env = process.env.NODE_ENV || "development";
  6013. var proto = {};
  6014. /* istanbul ignore next */
  6015. var defer = typeof setImmediate === "function" ? setImmediate : function(fn) {
  6016. process.nextTick(fn.bind.apply(fn, arguments));
  6017. };
  6018. /**
  6019. * Create a new connect server.
  6020. *
  6021. * @return {function}
  6022. * @public
  6023. */
  6024. function createServer() {
  6025. function app(req, res, next) {
  6026. app.handle(req, res, next);
  6027. }
  6028. merge(app, proto);
  6029. merge(app, EventEmitter$4.prototype);
  6030. app.route = "/";
  6031. app.stack = [];
  6032. return app;
  6033. }
  6034. /**
  6035. * Utilize the given middleware `handle` to the given `route`,
  6036. * defaulting to _/_. This "route" is the mount-point for the
  6037. * middleware, when given a value other than _/_ the middleware
  6038. * is only effective when that segment is present in the request's
  6039. * pathname.
  6040. *
  6041. * For example if we were to mount a function at _/admin_, it would
  6042. * be invoked on _/admin_, and _/admin/settings_, however it would
  6043. * not be invoked for _/_, or _/posts_.
  6044. *
  6045. * @param {String|Function|Server} route, callback or server
  6046. * @param {Function|Server} callback or server
  6047. * @return {Server} for chaining
  6048. * @public
  6049. */
  6050. proto.use = function use(route, fn) {
  6051. var handle = fn;
  6052. var path = route;
  6053. if (typeof route !== "string") {
  6054. handle = route;
  6055. path = "/";
  6056. }
  6057. if (typeof handle.handle === "function") {
  6058. var server = handle;
  6059. server.route = path;
  6060. handle = function(req, res, next) {
  6061. server.handle(req, res, next);
  6062. };
  6063. }
  6064. if (handle instanceof http$6.Server) handle = handle.listeners("request")[0];
  6065. if (path[path.length - 1] === "/") path = path.slice(0, -1);
  6066. debug("use %s %s", path || "/", handle.name || "anonymous");
  6067. this.stack.push({
  6068. route: path,
  6069. handle
  6070. });
  6071. return this;
  6072. };
  6073. /**
  6074. * Handle server requests, punting them down
  6075. * the middleware stack.
  6076. *
  6077. * @private
  6078. */
  6079. proto.handle = function handle(req, res, out) {
  6080. var index = 0;
  6081. var protohost = getProtohost(req.url) || "";
  6082. var removed = "";
  6083. var slashAdded = false;
  6084. var stack = this.stack;
  6085. var done = out || finalhandler(req, res, {
  6086. env,
  6087. onerror: logerror
  6088. });
  6089. req.originalUrl = req.originalUrl || req.url;
  6090. function next(err) {
  6091. if (slashAdded) {
  6092. req.url = req.url.substr(1);
  6093. slashAdded = false;
  6094. }
  6095. if (removed.length !== 0) {
  6096. req.url = protohost + removed + req.url.substr(protohost.length);
  6097. removed = "";
  6098. }
  6099. var layer = stack[index++];
  6100. if (!layer) {
  6101. defer(done, err);
  6102. return;
  6103. }
  6104. var path = parseUrl(req).pathname || "/";
  6105. var route = layer.route;
  6106. if (path.toLowerCase().substr(0, route.length) !== route.toLowerCase()) return next(err);
  6107. var c = path.length > route.length && path[route.length];
  6108. if (c && c !== "/" && c !== ".") return next(err);
  6109. if (route.length !== 0 && route !== "/") {
  6110. removed = route;
  6111. req.url = protohost + req.url.substr(protohost.length + removed.length);
  6112. if (!protohost && req.url[0] !== "/") {
  6113. req.url = "/" + req.url;
  6114. slashAdded = true;
  6115. }
  6116. }
  6117. call(layer.handle, route, err, req, res, next);
  6118. }
  6119. next();
  6120. };
  6121. /**
  6122. * Listen for connections.
  6123. *
  6124. * This method takes the same arguments
  6125. * as node's `http.Server#listen()`.
  6126. *
  6127. * HTTP and HTTPS:
  6128. *
  6129. * If you run your application both as HTTP
  6130. * and HTTPS you may wrap them individually,
  6131. * since your Connect "server" is really just
  6132. * a JavaScript `Function`.
  6133. *
  6134. * var connect = require('connect')
  6135. * , http = require('http')
  6136. * , https = require('https');
  6137. *
  6138. * var app = connect();
  6139. *
  6140. * http.createServer(app).listen(80);
  6141. * https.createServer(options, app).listen(443);
  6142. *
  6143. * @return {http.Server}
  6144. * @api public
  6145. */
  6146. proto.listen = function listen() {
  6147. var server = http$6.createServer(this);
  6148. return server.listen.apply(server, arguments);
  6149. };
  6150. /**
  6151. * Invoke a route handle.
  6152. * @private
  6153. */
  6154. function call(handle, route, err, req, res, next) {
  6155. var arity = handle.length;
  6156. var error = err;
  6157. var hasError = Boolean(err);
  6158. debug("%s %s : %s", handle.name || "<anonymous>", route, req.originalUrl);
  6159. try {
  6160. if (hasError && arity === 4) {
  6161. handle(err, req, res, next);
  6162. return;
  6163. } else if (!hasError && arity < 4) {
  6164. handle(req, res, next);
  6165. return;
  6166. }
  6167. } catch (e) {
  6168. error = e;
  6169. }
  6170. next(error);
  6171. }
  6172. /**
  6173. * Log error using console.error.
  6174. *
  6175. * @param {Error} err
  6176. * @private
  6177. */
  6178. function logerror(err) {
  6179. if (env !== "test") console.error(err.stack || err.toString());
  6180. }
  6181. /**
  6182. * Get get protocol + host for a URL.
  6183. *
  6184. * @param {string} url
  6185. * @private
  6186. */
  6187. function getProtohost(url) {
  6188. if (url.length === 0 || url[0] === "/") return;
  6189. var fqdnIndex = url.indexOf("://");
  6190. return fqdnIndex !== -1 && url.lastIndexOf("?", fqdnIndex) === -1 ? url.substr(0, url.indexOf("/", 3 + fqdnIndex)) : void 0;
  6191. }
  6192. }));
  6193. //#endregion
  6194. //#region ../../node_modules/.pnpm/object-assign@4.1.1/node_modules/object-assign/index.js
  6195. /*
  6196. object-assign
  6197. (c) Sindre Sorhus
  6198. @license MIT
  6199. */
  6200. var require_object_assign = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  6201. var getOwnPropertySymbols = Object.getOwnPropertySymbols;
  6202. var hasOwnProperty = Object.prototype.hasOwnProperty;
  6203. var propIsEnumerable = Object.prototype.propertyIsEnumerable;
  6204. function toObject(val) {
  6205. if (val === null || val === void 0) throw new TypeError("Object.assign cannot be called with null or undefined");
  6206. return Object(val);
  6207. }
  6208. function shouldUseNative() {
  6209. try {
  6210. if (!Object.assign) return false;
  6211. var test1 = /* @__PURE__ */ new String("abc");
  6212. test1[5] = "de";
  6213. if (Object.getOwnPropertyNames(test1)[0] === "5") return false;
  6214. var test2 = {};
  6215. for (var i = 0; i < 10; i++) test2["_" + String.fromCharCode(i)] = i;
  6216. if (Object.getOwnPropertyNames(test2).map(function(n) {
  6217. return test2[n];
  6218. }).join("") !== "0123456789") return false;
  6219. var test3 = {};
  6220. "abcdefghijklmnopqrst".split("").forEach(function(letter) {
  6221. test3[letter] = letter;
  6222. });
  6223. if (Object.keys(Object.assign({}, test3)).join("") !== "abcdefghijklmnopqrst") return false;
  6224. return true;
  6225. } catch (err) {
  6226. return false;
  6227. }
  6228. }
  6229. module.exports = shouldUseNative() ? Object.assign : function(target, source) {
  6230. var from;
  6231. var to = toObject(target);
  6232. var symbols;
  6233. for (var s = 1; s < arguments.length; s++) {
  6234. from = Object(arguments[s]);
  6235. for (var key in from) if (hasOwnProperty.call(from, key)) to[key] = from[key];
  6236. if (getOwnPropertySymbols) {
  6237. symbols = getOwnPropertySymbols(from);
  6238. for (var i = 0; i < symbols.length; i++) if (propIsEnumerable.call(from, symbols[i])) to[symbols[i]] = from[symbols[i]];
  6239. }
  6240. }
  6241. return to;
  6242. };
  6243. }));
  6244. //#endregion
  6245. //#region ../../node_modules/.pnpm/vary@1.1.2/node_modules/vary/index.js
  6246. /*!
  6247. * vary
  6248. * Copyright(c) 2014-2017 Douglas Christopher Wilson
  6249. * MIT Licensed
  6250. */
  6251. var require_vary = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  6252. /**
  6253. * Module exports.
  6254. */
  6255. module.exports = vary;
  6256. module.exports.append = append;
  6257. /**
  6258. * RegExp to match field-name in RFC 7230 sec 3.2
  6259. *
  6260. * field-name = token
  6261. * token = 1*tchar
  6262. * tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*"
  6263. * / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~"
  6264. * / DIGIT / ALPHA
  6265. * ; any VCHAR, except delimiters
  6266. */
  6267. var FIELD_NAME_REGEXP = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
  6268. /**
  6269. * Append a field to a vary header.
  6270. *
  6271. * @param {String} header
  6272. * @param {String|Array} field
  6273. * @return {String}
  6274. * @public
  6275. */
  6276. function append(header, field) {
  6277. if (typeof header !== "string") throw new TypeError("header argument is required");
  6278. if (!field) throw new TypeError("field argument is required");
  6279. var fields = !Array.isArray(field) ? parse(String(field)) : field;
  6280. 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");
  6281. if (header === "*") return header;
  6282. var val = header;
  6283. var vals = parse(header.toLowerCase());
  6284. if (fields.indexOf("*") !== -1 || vals.indexOf("*") !== -1) return "*";
  6285. for (var i = 0; i < fields.length; i++) {
  6286. var fld = fields[i].toLowerCase();
  6287. if (vals.indexOf(fld) === -1) {
  6288. vals.push(fld);
  6289. val = val ? val + ", " + fields[i] : fields[i];
  6290. }
  6291. }
  6292. return val;
  6293. }
  6294. /**
  6295. * Parse a vary header into an array.
  6296. *
  6297. * @param {String} header
  6298. * @return {Array}
  6299. * @private
  6300. */
  6301. function parse(header) {
  6302. var end = 0;
  6303. var list = [];
  6304. var start = 0;
  6305. for (var i = 0, len = header.length; i < len; i++) switch (header.charCodeAt(i)) {
  6306. case 32:
  6307. if (start === end) start = end = i + 1;
  6308. break;
  6309. case 44:
  6310. list.push(header.substring(start, end));
  6311. start = end = i + 1;
  6312. break;
  6313. default:
  6314. end = i + 1;
  6315. break;
  6316. }
  6317. list.push(header.substring(start, end));
  6318. return list;
  6319. }
  6320. /**
  6321. * Mark that a request is varied on a header field.
  6322. *
  6323. * @param {Object} res
  6324. * @param {String|Array} field
  6325. * @public
  6326. */
  6327. function vary(res, field) {
  6328. if (!res || !res.getHeader || !res.setHeader) throw new TypeError("res argument is required");
  6329. var val = res.getHeader("Vary") || "";
  6330. if (val = append(Array.isArray(val) ? val.join(", ") : String(val), field)) res.setHeader("Vary", val);
  6331. }
  6332. }));
  6333. //#endregion
  6334. //#region ../../node_modules/.pnpm/cors@2.8.6/node_modules/cors/lib/index.js
  6335. var require_lib$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  6336. (function() {
  6337. "use strict";
  6338. var assign = require_object_assign();
  6339. var vary = require_vary();
  6340. var defaults = {
  6341. origin: "*",
  6342. methods: "GET,HEAD,PUT,PATCH,POST,DELETE",
  6343. preflightContinue: false,
  6344. optionsSuccessStatus: 204
  6345. };
  6346. function isString(s) {
  6347. return typeof s === "string" || s instanceof String;
  6348. }
  6349. function isOriginAllowed(origin, allowedOrigin) {
  6350. if (Array.isArray(allowedOrigin)) {
  6351. for (var i = 0; i < allowedOrigin.length; ++i) if (isOriginAllowed(origin, allowedOrigin[i])) return true;
  6352. return false;
  6353. } else if (isString(allowedOrigin)) return origin === allowedOrigin;
  6354. else if (allowedOrigin instanceof RegExp) return allowedOrigin.test(origin);
  6355. else return !!allowedOrigin;
  6356. }
  6357. function configureOrigin(options, req) {
  6358. var requestOrigin = req.headers.origin, headers = [], isAllowed;
  6359. if (!options.origin || options.origin === "*") headers.push([{
  6360. key: "Access-Control-Allow-Origin",
  6361. value: "*"
  6362. }]);
  6363. else if (isString(options.origin)) {
  6364. headers.push([{
  6365. key: "Access-Control-Allow-Origin",
  6366. value: options.origin
  6367. }]);
  6368. headers.push([{
  6369. key: "Vary",
  6370. value: "Origin"
  6371. }]);
  6372. } else {
  6373. isAllowed = isOriginAllowed(requestOrigin, options.origin);
  6374. headers.push([{
  6375. key: "Access-Control-Allow-Origin",
  6376. value: isAllowed ? requestOrigin : false
  6377. }]);
  6378. headers.push([{
  6379. key: "Vary",
  6380. value: "Origin"
  6381. }]);
  6382. }
  6383. return headers;
  6384. }
  6385. function configureMethods(options) {
  6386. var methods = options.methods;
  6387. if (methods.join) methods = options.methods.join(",");
  6388. return {
  6389. key: "Access-Control-Allow-Methods",
  6390. value: methods
  6391. };
  6392. }
  6393. function configureCredentials(options) {
  6394. if (options.credentials === true) return {
  6395. key: "Access-Control-Allow-Credentials",
  6396. value: "true"
  6397. };
  6398. return null;
  6399. }
  6400. function configureAllowedHeaders(options, req) {
  6401. var allowedHeaders = options.allowedHeaders || options.headers;
  6402. var headers = [];
  6403. if (!allowedHeaders) {
  6404. allowedHeaders = req.headers["access-control-request-headers"];
  6405. headers.push([{
  6406. key: "Vary",
  6407. value: "Access-Control-Request-Headers"
  6408. }]);
  6409. } else if (allowedHeaders.join) allowedHeaders = allowedHeaders.join(",");
  6410. if (allowedHeaders && allowedHeaders.length) headers.push([{
  6411. key: "Access-Control-Allow-Headers",
  6412. value: allowedHeaders
  6413. }]);
  6414. return headers;
  6415. }
  6416. function configureExposedHeaders(options) {
  6417. var headers = options.exposedHeaders;
  6418. if (!headers) return null;
  6419. else if (headers.join) headers = headers.join(",");
  6420. if (headers && headers.length) return {
  6421. key: "Access-Control-Expose-Headers",
  6422. value: headers
  6423. };
  6424. return null;
  6425. }
  6426. function configureMaxAge(options) {
  6427. var maxAge = (typeof options.maxAge === "number" || options.maxAge) && options.maxAge.toString();
  6428. if (maxAge && maxAge.length) return {
  6429. key: "Access-Control-Max-Age",
  6430. value: maxAge
  6431. };
  6432. return null;
  6433. }
  6434. function applyHeaders(headers, res) {
  6435. for (var i = 0, n = headers.length; i < n; i++) {
  6436. var header = headers[i];
  6437. if (header) {
  6438. if (Array.isArray(header)) applyHeaders(header, res);
  6439. else if (header.key === "Vary" && header.value) vary(res, header.value);
  6440. else if (header.value) res.setHeader(header.key, header.value);
  6441. }
  6442. }
  6443. }
  6444. function cors(options, req, res, next) {
  6445. var headers = [];
  6446. if ((req.method && req.method.toUpperCase && req.method.toUpperCase()) === "OPTIONS") {
  6447. headers.push(configureOrigin(options, req));
  6448. headers.push(configureCredentials(options));
  6449. headers.push(configureMethods(options));
  6450. headers.push(configureAllowedHeaders(options, req));
  6451. headers.push(configureMaxAge(options));
  6452. headers.push(configureExposedHeaders(options));
  6453. applyHeaders(headers, res);
  6454. if (options.preflightContinue) next();
  6455. else {
  6456. res.statusCode = options.optionsSuccessStatus;
  6457. res.setHeader("Content-Length", "0");
  6458. res.end();
  6459. }
  6460. } else {
  6461. headers.push(configureOrigin(options, req));
  6462. headers.push(configureCredentials(options));
  6463. headers.push(configureExposedHeaders(options));
  6464. applyHeaders(headers, res);
  6465. next();
  6466. }
  6467. }
  6468. function middlewareWrapper(o) {
  6469. var optionsCallback = null;
  6470. if (typeof o === "function") optionsCallback = o;
  6471. else optionsCallback = function(req, cb) {
  6472. cb(null, o);
  6473. };
  6474. return function corsMiddleware(req, res, next) {
  6475. optionsCallback(req, function(err, options) {
  6476. if (err) next(err);
  6477. else {
  6478. var corsOptions = assign({}, defaults, options);
  6479. var originCallback = null;
  6480. if (corsOptions.origin && typeof corsOptions.origin === "function") originCallback = corsOptions.origin;
  6481. else if (corsOptions.origin) originCallback = function(origin, cb) {
  6482. cb(null, corsOptions.origin);
  6483. };
  6484. if (originCallback) originCallback(req.headers.origin, function(err2, origin) {
  6485. if (err2 || !origin) next(err2);
  6486. else {
  6487. corsOptions.origin = origin;
  6488. cors(corsOptions, req, res, next);
  6489. }
  6490. });
  6491. else next();
  6492. }
  6493. });
  6494. };
  6495. }
  6496. module.exports = middlewareWrapper;
  6497. })();
  6498. }));
  6499. //#endregion
  6500. //#region ../../node_modules/.pnpm/readdirp@3.6.0/node_modules/readdirp/index.js
  6501. var require_readdirp = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  6502. const fs$10 = __require("fs");
  6503. const { Readable: Readable$1 } = __require("stream");
  6504. const sysPath$3 = __require("path");
  6505. const { promisify: promisify$4 } = __require("util");
  6506. const picomatch$2 = __require("picomatch");
  6507. const readdir = promisify$4(fs$10.readdir);
  6508. const stat = promisify$4(fs$10.stat);
  6509. const lstat = promisify$4(fs$10.lstat);
  6510. const realpath = promisify$4(fs$10.realpath);
  6511. /**
  6512. * @typedef {Object} EntryInfo
  6513. * @property {String} path
  6514. * @property {String} fullPath
  6515. * @property {fs.Stats=} stats
  6516. * @property {fs.Dirent=} dirent
  6517. * @property {String} basename
  6518. */
  6519. const BANG = "!";
  6520. const RECURSIVE_ERROR_CODE = "READDIRP_RECURSIVE_ERROR";
  6521. const NORMAL_FLOW_ERRORS = new Set([
  6522. "ENOENT",
  6523. "EPERM",
  6524. "EACCES",
  6525. "ELOOP",
  6526. RECURSIVE_ERROR_CODE
  6527. ]);
  6528. const FILE_TYPE = "files";
  6529. const DIR_TYPE = "directories";
  6530. const FILE_DIR_TYPE = "files_directories";
  6531. const EVERYTHING_TYPE = "all";
  6532. const ALL_TYPES = [
  6533. FILE_TYPE,
  6534. DIR_TYPE,
  6535. FILE_DIR_TYPE,
  6536. EVERYTHING_TYPE
  6537. ];
  6538. const isNormalFlowError = (error) => NORMAL_FLOW_ERRORS.has(error.code);
  6539. const [maj, min] = process.versions.node.split(".").slice(0, 2).map((n) => Number.parseInt(n, 10));
  6540. const wantBigintFsStats = process.platform === "win32" && (maj > 10 || maj === 10 && min >= 5);
  6541. const normalizeFilter = (filter) => {
  6542. if (filter === void 0) return;
  6543. if (typeof filter === "function") return filter;
  6544. if (typeof filter === "string") {
  6545. const glob = picomatch$2(filter.trim());
  6546. return (entry) => glob(entry.basename);
  6547. }
  6548. if (Array.isArray(filter)) {
  6549. const positive = [];
  6550. const negative = [];
  6551. for (const item of filter) {
  6552. const trimmed = item.trim();
  6553. if (trimmed.charAt(0) === BANG) negative.push(picomatch$2(trimmed.slice(1)));
  6554. else positive.push(picomatch$2(trimmed));
  6555. }
  6556. if (negative.length > 0) {
  6557. if (positive.length > 0) return (entry) => positive.some((f) => f(entry.basename)) && !negative.some((f) => f(entry.basename));
  6558. return (entry) => !negative.some((f) => f(entry.basename));
  6559. }
  6560. return (entry) => positive.some((f) => f(entry.basename));
  6561. }
  6562. };
  6563. var ReaddirpStream = class ReaddirpStream extends Readable$1 {
  6564. static get defaultOptions() {
  6565. return {
  6566. root: ".",
  6567. fileFilter: (path) => true,
  6568. directoryFilter: (path) => true,
  6569. type: FILE_TYPE,
  6570. lstat: false,
  6571. depth: 2147483648,
  6572. alwaysStat: false
  6573. };
  6574. }
  6575. constructor(options = {}) {
  6576. super({
  6577. objectMode: true,
  6578. autoDestroy: true,
  6579. highWaterMark: options.highWaterMark || 4096
  6580. });
  6581. const opts = {
  6582. ...ReaddirpStream.defaultOptions,
  6583. ...options
  6584. };
  6585. const { root, type } = opts;
  6586. this._fileFilter = normalizeFilter(opts.fileFilter);
  6587. this._directoryFilter = normalizeFilter(opts.directoryFilter);
  6588. const statMethod = opts.lstat ? lstat : stat;
  6589. if (wantBigintFsStats) this._stat = (path) => statMethod(path, { bigint: true });
  6590. else this._stat = statMethod;
  6591. this._maxDepth = opts.depth;
  6592. this._wantsDir = [
  6593. DIR_TYPE,
  6594. FILE_DIR_TYPE,
  6595. EVERYTHING_TYPE
  6596. ].includes(type);
  6597. this._wantsFile = [
  6598. FILE_TYPE,
  6599. FILE_DIR_TYPE,
  6600. EVERYTHING_TYPE
  6601. ].includes(type);
  6602. this._wantsEverything = type === EVERYTHING_TYPE;
  6603. this._root = sysPath$3.resolve(root);
  6604. this._isDirent = "Dirent" in fs$10 && !opts.alwaysStat;
  6605. this._statsProp = this._isDirent ? "dirent" : "stats";
  6606. this._rdOptions = {
  6607. encoding: "utf8",
  6608. withFileTypes: this._isDirent
  6609. };
  6610. this.parents = [this._exploreDir(root, 1)];
  6611. this.reading = false;
  6612. this.parent = void 0;
  6613. }
  6614. async _read(batch) {
  6615. if (this.reading) return;
  6616. this.reading = true;
  6617. try {
  6618. while (!this.destroyed && batch > 0) {
  6619. const { path, depth, files = [] } = this.parent || {};
  6620. if (files.length > 0) {
  6621. const slice = files.splice(0, batch).map((dirent) => this._formatEntry(dirent, path));
  6622. for (const entry of await Promise.all(slice)) {
  6623. if (this.destroyed) return;
  6624. const entryType = await this._getEntryType(entry);
  6625. if (entryType === "directory" && this._directoryFilter(entry)) {
  6626. if (depth <= this._maxDepth) this.parents.push(this._exploreDir(entry.fullPath, depth + 1));
  6627. if (this._wantsDir) {
  6628. this.push(entry);
  6629. batch--;
  6630. }
  6631. } else if ((entryType === "file" || this._includeAsFile(entry)) && this._fileFilter(entry)) {
  6632. if (this._wantsFile) {
  6633. this.push(entry);
  6634. batch--;
  6635. }
  6636. }
  6637. }
  6638. } else {
  6639. const parent = this.parents.pop();
  6640. if (!parent) {
  6641. this.push(null);
  6642. break;
  6643. }
  6644. this.parent = await parent;
  6645. if (this.destroyed) return;
  6646. }
  6647. }
  6648. } catch (error) {
  6649. this.destroy(error);
  6650. } finally {
  6651. this.reading = false;
  6652. }
  6653. }
  6654. async _exploreDir(path, depth) {
  6655. let files;
  6656. try {
  6657. files = await readdir(path, this._rdOptions);
  6658. } catch (error) {
  6659. this._onError(error);
  6660. }
  6661. return {
  6662. files,
  6663. depth,
  6664. path
  6665. };
  6666. }
  6667. async _formatEntry(dirent, path) {
  6668. let entry;
  6669. try {
  6670. const basename = this._isDirent ? dirent.name : dirent;
  6671. const fullPath = sysPath$3.resolve(sysPath$3.join(path, basename));
  6672. entry = {
  6673. path: sysPath$3.relative(this._root, fullPath),
  6674. fullPath,
  6675. basename
  6676. };
  6677. entry[this._statsProp] = this._isDirent ? dirent : await this._stat(fullPath);
  6678. } catch (err) {
  6679. this._onError(err);
  6680. }
  6681. return entry;
  6682. }
  6683. _onError(err) {
  6684. if (isNormalFlowError(err) && !this.destroyed) this.emit("warn", err);
  6685. else this.destroy(err);
  6686. }
  6687. async _getEntryType(entry) {
  6688. const stats = entry && entry[this._statsProp];
  6689. if (!stats) return;
  6690. if (stats.isFile()) return "file";
  6691. if (stats.isDirectory()) return "directory";
  6692. if (stats && stats.isSymbolicLink()) {
  6693. const full = entry.fullPath;
  6694. try {
  6695. const entryRealPath = await realpath(full);
  6696. const entryRealPathStats = await lstat(entryRealPath);
  6697. if (entryRealPathStats.isFile()) return "file";
  6698. if (entryRealPathStats.isDirectory()) {
  6699. const len = entryRealPath.length;
  6700. if (full.startsWith(entryRealPath) && full.substr(len, 1) === sysPath$3.sep) {
  6701. const recursiveError = /* @__PURE__ */ new Error(`Circular symlink detected: "${full}" points to "${entryRealPath}"`);
  6702. recursiveError.code = RECURSIVE_ERROR_CODE;
  6703. return this._onError(recursiveError);
  6704. }
  6705. return "directory";
  6706. }
  6707. } catch (error) {
  6708. this._onError(error);
  6709. }
  6710. }
  6711. }
  6712. _includeAsFile(entry) {
  6713. const stats = entry && entry[this._statsProp];
  6714. return stats && this._wantsEverything && !stats.isDirectory();
  6715. }
  6716. };
  6717. /**
  6718. * @typedef {Object} ReaddirpArguments
  6719. * @property {Function=} fileFilter
  6720. * @property {Function=} directoryFilter
  6721. * @property {String=} type
  6722. * @property {Number=} depth
  6723. * @property {String=} root
  6724. * @property {Boolean=} lstat
  6725. * @property {Boolean=} bigint
  6726. */
  6727. /**
  6728. * Main function which ends up calling readdirRec and reads all files and directories in given root recursively.
  6729. * @param {String} root Root directory
  6730. * @param {ReaddirpArguments=} options Options to specify root (start directory), filters and recursion depth
  6731. */
  6732. const readdirp = (root, options = {}) => {
  6733. let type = options.entryType || options.type;
  6734. if (type === "both") type = FILE_DIR_TYPE;
  6735. if (type) options.type = type;
  6736. if (!root) throw new Error("readdirp: root argument is required. Usage: readdirp(root, options)");
  6737. else if (typeof root !== "string") throw new TypeError("readdirp: root argument must be a string. Usage: readdirp(root, options)");
  6738. else if (type && !ALL_TYPES.includes(type)) throw new Error(`readdirp: Invalid type passed. Use one of ${ALL_TYPES.join(", ")}`);
  6739. options.root = root;
  6740. return new ReaddirpStream(options);
  6741. };
  6742. const readdirpPromise = (root, options = {}) => {
  6743. return new Promise((resolve, reject) => {
  6744. const files = [];
  6745. readdirp(root, options).on("data", (entry) => files.push(entry)).on("end", () => resolve(files)).on("error", (error) => reject(error));
  6746. });
  6747. };
  6748. readdirp.promise = readdirpPromise;
  6749. readdirp.ReaddirpStream = ReaddirpStream;
  6750. readdirp.default = readdirp;
  6751. module.exports = readdirp;
  6752. }));
  6753. //#endregion
  6754. //#region ../../node_modules/.pnpm/normalize-path@3.0.0/node_modules/normalize-path/index.js
  6755. var require_normalize_path = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  6756. /*!
  6757. * normalize-path <https://github.com/jonschlinkert/normalize-path>
  6758. *
  6759. * Copyright (c) 2014-2018, Jon Schlinkert.
  6760. * Released under the MIT License.
  6761. */
  6762. module.exports = function(path, stripTrailing) {
  6763. if (typeof path !== "string") throw new TypeError("expected path to be a string");
  6764. if (path === "\\" || path === "/") return "/";
  6765. var len = path.length;
  6766. if (len <= 1) return path;
  6767. var prefix = "";
  6768. if (len > 4 && path[3] === "\\") {
  6769. var ch = path[2];
  6770. if ((ch === "?" || ch === ".") && path.slice(0, 2) === "\\\\") {
  6771. path = path.slice(2);
  6772. prefix = "//";
  6773. }
  6774. }
  6775. var segs = path.split(/[/\\]+/);
  6776. if (stripTrailing !== false && segs[segs.length - 1] === "") segs.pop();
  6777. return prefix + segs.join("/");
  6778. };
  6779. }));
  6780. //#endregion
  6781. //#region ../../node_modules/.pnpm/anymatch@3.1.3/node_modules/anymatch/index.js
  6782. var require_anymatch = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  6783. Object.defineProperty(exports, "__esModule", { value: true });
  6784. const picomatch$1 = __require("picomatch");
  6785. const normalizePath = require_normalize_path();
  6786. /**
  6787. * @typedef {(testString: string) => boolean} AnymatchFn
  6788. * @typedef {string|RegExp|AnymatchFn} AnymatchPattern
  6789. * @typedef {AnymatchPattern|AnymatchPattern[]} AnymatchMatcher
  6790. */
  6791. const BANG = "!";
  6792. const DEFAULT_OPTIONS = { returnIndex: false };
  6793. const arrify = (item) => Array.isArray(item) ? item : [item];
  6794. /**
  6795. * @param {AnymatchPattern} matcher
  6796. * @param {object} options
  6797. * @returns {AnymatchFn}
  6798. */
  6799. const createPattern = (matcher, options) => {
  6800. if (typeof matcher === "function") return matcher;
  6801. if (typeof matcher === "string") {
  6802. const glob = picomatch$1(matcher, options);
  6803. return (string) => matcher === string || glob(string);
  6804. }
  6805. if (matcher instanceof RegExp) return (string) => matcher.test(string);
  6806. return (string) => false;
  6807. };
  6808. /**
  6809. * @param {Array<Function>} patterns
  6810. * @param {Array<Function>} negPatterns
  6811. * @param {String|Array} args
  6812. * @param {Boolean} returnIndex
  6813. * @returns {boolean|number}
  6814. */
  6815. const matchPatterns = (patterns, negPatterns, args, returnIndex) => {
  6816. const isList = Array.isArray(args);
  6817. const _path = isList ? args[0] : args;
  6818. if (!isList && typeof _path !== "string") throw new TypeError("anymatch: second argument must be a string: got " + Object.prototype.toString.call(_path));
  6819. const path = normalizePath(_path, false);
  6820. for (let index = 0; index < negPatterns.length; index++) {
  6821. const nglob = negPatterns[index];
  6822. if (nglob(path)) return returnIndex ? -1 : false;
  6823. }
  6824. const applied = isList && [path].concat(args.slice(1));
  6825. for (let index = 0; index < patterns.length; index++) {
  6826. const pattern = patterns[index];
  6827. if (isList ? pattern(...applied) : pattern(path)) return returnIndex ? index : true;
  6828. }
  6829. return returnIndex ? -1 : false;
  6830. };
  6831. /**
  6832. * @param {AnymatchMatcher} matchers
  6833. * @param {Array|string} testString
  6834. * @param {object} options
  6835. * @returns {boolean|number|Function}
  6836. */
  6837. const anymatch = (matchers, testString, options = DEFAULT_OPTIONS) => {
  6838. if (matchers == null) throw new TypeError("anymatch: specify first argument");
  6839. const opts = typeof options === "boolean" ? { returnIndex: options } : options;
  6840. const returnIndex = opts.returnIndex || false;
  6841. const mtchers = arrify(matchers);
  6842. const negatedGlobs = mtchers.filter((item) => typeof item === "string" && item.charAt(0) === BANG).map((item) => item.slice(1)).map((item) => picomatch$1(item, opts));
  6843. const patterns = mtchers.filter((item) => typeof item !== "string" || typeof item === "string" && item.charAt(0) !== BANG).map((matcher) => createPattern(matcher, opts));
  6844. if (testString == null) return (testString, ri = false) => {
  6845. return matchPatterns(patterns, negatedGlobs, testString, typeof ri === "boolean" ? ri : false);
  6846. };
  6847. return matchPatterns(patterns, negatedGlobs, testString, returnIndex);
  6848. };
  6849. anymatch.default = anymatch;
  6850. module.exports = anymatch;
  6851. }));
  6852. //#endregion
  6853. //#region ../../node_modules/.pnpm/is-extglob@2.1.1/node_modules/is-extglob/index.js
  6854. var require_is_extglob = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  6855. /*!
  6856. * is-extglob <https://github.com/jonschlinkert/is-extglob>
  6857. *
  6858. * Copyright (c) 2014-2016, Jon Schlinkert.
  6859. * Licensed under the MIT License.
  6860. */
  6861. module.exports = function isExtglob(str) {
  6862. if (typeof str !== "string" || str === "") return false;
  6863. var match;
  6864. while (match = /(\\).|([@?!+*]\(.*\))/g.exec(str)) {
  6865. if (match[2]) return true;
  6866. str = str.slice(match.index + match[0].length);
  6867. }
  6868. return false;
  6869. };
  6870. }));
  6871. //#endregion
  6872. //#region ../../node_modules/.pnpm/is-glob@4.0.3/node_modules/is-glob/index.js
  6873. var require_is_glob = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  6874. /*!
  6875. * is-glob <https://github.com/jonschlinkert/is-glob>
  6876. *
  6877. * Copyright (c) 2014-2017, Jon Schlinkert.
  6878. * Released under the MIT License.
  6879. */
  6880. var isExtglob = require_is_extglob();
  6881. var chars = {
  6882. "{": "}",
  6883. "(": ")",
  6884. "[": "]"
  6885. };
  6886. var strictCheck = function(str) {
  6887. if (str[0] === "!") return true;
  6888. var index = 0;
  6889. var pipeIndex = -2;
  6890. var closeSquareIndex = -2;
  6891. var closeCurlyIndex = -2;
  6892. var closeParenIndex = -2;
  6893. var backSlashIndex = -2;
  6894. while (index < str.length) {
  6895. if (str[index] === "*") return true;
  6896. if (str[index + 1] === "?" && /[\].+)]/.test(str[index])) return true;
  6897. if (closeSquareIndex !== -1 && str[index] === "[" && str[index + 1] !== "]") {
  6898. if (closeSquareIndex < index) closeSquareIndex = str.indexOf("]", index);
  6899. if (closeSquareIndex > index) {
  6900. if (backSlashIndex === -1 || backSlashIndex > closeSquareIndex) return true;
  6901. backSlashIndex = str.indexOf("\\", index);
  6902. if (backSlashIndex === -1 || backSlashIndex > closeSquareIndex) return true;
  6903. }
  6904. }
  6905. if (closeCurlyIndex !== -1 && str[index] === "{" && str[index + 1] !== "}") {
  6906. closeCurlyIndex = str.indexOf("}", index);
  6907. if (closeCurlyIndex > index) {
  6908. backSlashIndex = str.indexOf("\\", index);
  6909. if (backSlashIndex === -1 || backSlashIndex > closeCurlyIndex) return true;
  6910. }
  6911. }
  6912. if (closeParenIndex !== -1 && str[index] === "(" && str[index + 1] === "?" && /[:!=]/.test(str[index + 2]) && str[index + 3] !== ")") {
  6913. closeParenIndex = str.indexOf(")", index);
  6914. if (closeParenIndex > index) {
  6915. backSlashIndex = str.indexOf("\\", index);
  6916. if (backSlashIndex === -1 || backSlashIndex > closeParenIndex) return true;
  6917. }
  6918. }
  6919. if (pipeIndex !== -1 && str[index] === "(" && str[index + 1] !== "|") {
  6920. if (pipeIndex < index) pipeIndex = str.indexOf("|", index);
  6921. if (pipeIndex !== -1 && str[pipeIndex + 1] !== ")") {
  6922. closeParenIndex = str.indexOf(")", pipeIndex);
  6923. if (closeParenIndex > pipeIndex) {
  6924. backSlashIndex = str.indexOf("\\", pipeIndex);
  6925. if (backSlashIndex === -1 || backSlashIndex > closeParenIndex) return true;
  6926. }
  6927. }
  6928. }
  6929. if (str[index] === "\\") {
  6930. var open = str[index + 1];
  6931. index += 2;
  6932. var close = chars[open];
  6933. if (close) {
  6934. var n = str.indexOf(close, index);
  6935. if (n !== -1) index = n + 1;
  6936. }
  6937. if (str[index] === "!") return true;
  6938. } else index++;
  6939. }
  6940. return false;
  6941. };
  6942. var relaxedCheck = function(str) {
  6943. if (str[0] === "!") return true;
  6944. var index = 0;
  6945. while (index < str.length) {
  6946. if (/[*?{}()[\]]/.test(str[index])) return true;
  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. module.exports = function isGlob(str, options) {
  6961. if (typeof str !== "string" || str === "") return false;
  6962. if (isExtglob(str)) return true;
  6963. var check = strictCheck;
  6964. if (options && options.strict === false) check = relaxedCheck;
  6965. return check(str);
  6966. };
  6967. }));
  6968. //#endregion
  6969. //#region ../../node_modules/.pnpm/glob-parent@5.1.2/node_modules/glob-parent/index.js
  6970. var require_glob_parent = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  6971. var isGlob = require_is_glob();
  6972. var pathPosixDirname = __require("path").posix.dirname;
  6973. var isWin32 = __require("os").platform() === "win32";
  6974. var slash = "/";
  6975. var backslash = /\\/g;
  6976. var enclosure = /[\{\[].*[\}\]]$/;
  6977. var globby = /(^|[^\\])([\{\[]|\([^\)]+$)/;
  6978. var escaped = /\\([\!\*\?\|\[\]\(\)\{\}])/g;
  6979. /**
  6980. * @param {string} str
  6981. * @param {Object} opts
  6982. * @param {boolean} [opts.flipBackslashes=true]
  6983. * @returns {string}
  6984. */
  6985. module.exports = function globParent(str, opts) {
  6986. if (Object.assign({ flipBackslashes: true }, opts).flipBackslashes && isWin32 && str.indexOf(slash) < 0) str = str.replace(backslash, slash);
  6987. if (enclosure.test(str)) str += slash;
  6988. str += "a";
  6989. do
  6990. str = pathPosixDirname(str);
  6991. while (isGlob(str) || globby.test(str));
  6992. return str.replace(escaped, "$1");
  6993. };
  6994. }));
  6995. //#endregion
  6996. //#region ../../node_modules/.pnpm/braces@3.0.3/node_modules/braces/lib/utils.js
  6997. var require_utils = /* @__PURE__ */ __commonJSMin(((exports) => {
  6998. exports.isInteger = (num) => {
  6999. if (typeof num === "number") return Number.isInteger(num);
  7000. if (typeof num === "string" && num.trim() !== "") return Number.isInteger(Number(num));
  7001. return false;
  7002. };
  7003. /**
  7004. * Find a node of the given type
  7005. */
  7006. exports.find = (node, type) => node.nodes.find((node) => node.type === type);
  7007. /**
  7008. * Find a node of the given type
  7009. */
  7010. exports.exceedsLimit = (min, max, step = 1, limit) => {
  7011. if (limit === false) return false;
  7012. if (!exports.isInteger(min) || !exports.isInteger(max)) return false;
  7013. return (Number(max) - Number(min)) / Number(step) >= limit;
  7014. };
  7015. /**
  7016. * Escape the given node with '\\' before node.value
  7017. */
  7018. exports.escapeNode = (block, n = 0, type) => {
  7019. const node = block.nodes[n];
  7020. if (!node) return;
  7021. if (type && node.type === type || node.type === "open" || node.type === "close") {
  7022. if (node.escaped !== true) {
  7023. node.value = "\\" + node.value;
  7024. node.escaped = true;
  7025. }
  7026. }
  7027. };
  7028. /**
  7029. * Returns true if the given brace node should be enclosed in literal braces
  7030. */
  7031. exports.encloseBrace = (node) => {
  7032. if (node.type !== "brace") return false;
  7033. if (node.commas >> 0 + node.ranges >> 0 === 0) {
  7034. node.invalid = true;
  7035. return true;
  7036. }
  7037. return false;
  7038. };
  7039. /**
  7040. * Returns true if a brace node is invalid.
  7041. */
  7042. exports.isInvalidBrace = (block) => {
  7043. if (block.type !== "brace") return false;
  7044. if (block.invalid === true || block.dollar) return true;
  7045. if (block.commas >> 0 + block.ranges >> 0 === 0) {
  7046. block.invalid = true;
  7047. return true;
  7048. }
  7049. if (block.open !== true || block.close !== true) {
  7050. block.invalid = true;
  7051. return true;
  7052. }
  7053. return false;
  7054. };
  7055. /**
  7056. * Returns true if a node is an open or close node
  7057. */
  7058. exports.isOpenOrClose = (node) => {
  7059. if (node.type === "open" || node.type === "close") return true;
  7060. return node.open === true || node.close === true;
  7061. };
  7062. /**
  7063. * Reduce an array of text nodes.
  7064. */
  7065. exports.reduce = (nodes) => nodes.reduce((acc, node) => {
  7066. if (node.type === "text") acc.push(node.value);
  7067. if (node.type === "range") node.type = "text";
  7068. return acc;
  7069. }, []);
  7070. /**
  7071. * Flatten an array
  7072. */
  7073. exports.flatten = (...args) => {
  7074. const result = [];
  7075. const flat = (arr) => {
  7076. for (let i = 0; i < arr.length; i++) {
  7077. const ele = arr[i];
  7078. if (Array.isArray(ele)) {
  7079. flat(ele);
  7080. continue;
  7081. }
  7082. if (ele !== void 0) result.push(ele);
  7083. }
  7084. return result;
  7085. };
  7086. flat(args);
  7087. return result;
  7088. };
  7089. }));
  7090. //#endregion
  7091. //#region ../../node_modules/.pnpm/braces@3.0.3/node_modules/braces/lib/stringify.js
  7092. var require_stringify = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  7093. const utils = require_utils();
  7094. module.exports = (ast, options = {}) => {
  7095. const stringify = (node, parent = {}) => {
  7096. const invalidBlock = options.escapeInvalid && utils.isInvalidBrace(parent);
  7097. const invalidNode = node.invalid === true && options.escapeInvalid === true;
  7098. let output = "";
  7099. if (node.value) {
  7100. if ((invalidBlock || invalidNode) && utils.isOpenOrClose(node)) return "\\" + node.value;
  7101. return node.value;
  7102. }
  7103. if (node.value) return node.value;
  7104. if (node.nodes) for (const child of node.nodes) output += stringify(child);
  7105. return output;
  7106. };
  7107. return stringify(ast);
  7108. };
  7109. }));
  7110. //#endregion
  7111. //#region ../../node_modules/.pnpm/is-number@7.0.0/node_modules/is-number/index.js
  7112. /*!
  7113. * is-number <https://github.com/jonschlinkert/is-number>
  7114. *
  7115. * Copyright (c) 2014-present, Jon Schlinkert.
  7116. * Released under the MIT License.
  7117. */
  7118. var require_is_number = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  7119. module.exports = function(num) {
  7120. if (typeof num === "number") return num - num === 0;
  7121. if (typeof num === "string" && num.trim() !== "") return Number.isFinite ? Number.isFinite(+num) : isFinite(+num);
  7122. return false;
  7123. };
  7124. }));
  7125. //#endregion
  7126. //#region ../../node_modules/.pnpm/to-regex-range@5.0.1/node_modules/to-regex-range/index.js
  7127. /*!
  7128. * to-regex-range <https://github.com/micromatch/to-regex-range>
  7129. *
  7130. * Copyright (c) 2015-present, Jon Schlinkert.
  7131. * Released under the MIT License.
  7132. */
  7133. var require_to_regex_range = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  7134. const isNumber = require_is_number();
  7135. const toRegexRange = (min, max, options) => {
  7136. if (isNumber(min) === false) throw new TypeError("toRegexRange: expected the first argument to be a number");
  7137. if (max === void 0 || min === max) return String(min);
  7138. if (isNumber(max) === false) throw new TypeError("toRegexRange: expected the second argument to be a number.");
  7139. let opts = {
  7140. relaxZeros: true,
  7141. ...options
  7142. };
  7143. if (typeof opts.strictZeros === "boolean") opts.relaxZeros = opts.strictZeros === false;
  7144. let relax = String(opts.relaxZeros);
  7145. let shorthand = String(opts.shorthand);
  7146. let capture = String(opts.capture);
  7147. let wrap = String(opts.wrap);
  7148. let cacheKey = min + ":" + max + "=" + relax + shorthand + capture + wrap;
  7149. if (toRegexRange.cache.hasOwnProperty(cacheKey)) return toRegexRange.cache[cacheKey].result;
  7150. let a = Math.min(min, max);
  7151. let b = Math.max(min, max);
  7152. if (Math.abs(a - b) === 1) {
  7153. let result = min + "|" + max;
  7154. if (opts.capture) return `(${result})`;
  7155. if (opts.wrap === false) return result;
  7156. return `(?:${result})`;
  7157. }
  7158. let isPadded = hasPadding(min) || hasPadding(max);
  7159. let state = {
  7160. min,
  7161. max,
  7162. a,
  7163. b
  7164. };
  7165. let positives = [];
  7166. let negatives = [];
  7167. if (isPadded) {
  7168. state.isPadded = isPadded;
  7169. state.maxLen = String(state.max).length;
  7170. }
  7171. if (a < 0) {
  7172. negatives = splitToPatterns(b < 0 ? Math.abs(b) : 1, Math.abs(a), state, opts);
  7173. a = state.a = 0;
  7174. }
  7175. if (b >= 0) positives = splitToPatterns(a, b, state, opts);
  7176. state.negatives = negatives;
  7177. state.positives = positives;
  7178. state.result = collatePatterns(negatives, positives, opts);
  7179. if (opts.capture === true) state.result = `(${state.result})`;
  7180. else if (opts.wrap !== false && positives.length + negatives.length > 1) state.result = `(?:${state.result})`;
  7181. toRegexRange.cache[cacheKey] = state;
  7182. return state.result;
  7183. };
  7184. function collatePatterns(neg, pos, options) {
  7185. let onlyNegative = filterPatterns(neg, pos, "-", false, options) || [];
  7186. let onlyPositive = filterPatterns(pos, neg, "", false, options) || [];
  7187. let intersected = filterPatterns(neg, pos, "-?", true, options) || [];
  7188. return onlyNegative.concat(intersected).concat(onlyPositive).join("|");
  7189. }
  7190. function splitToRanges(min, max) {
  7191. let nines = 1;
  7192. let zeros = 1;
  7193. let stop = countNines(min, nines);
  7194. let stops = new Set([max]);
  7195. while (min <= stop && stop <= max) {
  7196. stops.add(stop);
  7197. nines += 1;
  7198. stop = countNines(min, nines);
  7199. }
  7200. stop = countZeros(max + 1, zeros) - 1;
  7201. while (min < stop && stop <= max) {
  7202. stops.add(stop);
  7203. zeros += 1;
  7204. stop = countZeros(max + 1, zeros) - 1;
  7205. }
  7206. stops = [...stops];
  7207. stops.sort(compare);
  7208. return stops;
  7209. }
  7210. /**
  7211. * Convert a range to a regex pattern
  7212. * @param {Number} `start`
  7213. * @param {Number} `stop`
  7214. * @return {String}
  7215. */
  7216. function rangeToPattern(start, stop, options) {
  7217. if (start === stop) return {
  7218. pattern: start,
  7219. count: [],
  7220. digits: 0
  7221. };
  7222. let zipped = zip(start, stop);
  7223. let digits = zipped.length;
  7224. let pattern = "";
  7225. let count = 0;
  7226. for (let i = 0; i < digits; i++) {
  7227. let [startDigit, stopDigit] = zipped[i];
  7228. if (startDigit === stopDigit) pattern += startDigit;
  7229. else if (startDigit !== "0" || stopDigit !== "9") pattern += toCharacterClass(startDigit, stopDigit, options);
  7230. else count++;
  7231. }
  7232. if (count) pattern += options.shorthand === true ? "\\d" : "[0-9]";
  7233. return {
  7234. pattern,
  7235. count: [count],
  7236. digits
  7237. };
  7238. }
  7239. function splitToPatterns(min, max, tok, options) {
  7240. let ranges = splitToRanges(min, max);
  7241. let tokens = [];
  7242. let start = min;
  7243. let prev;
  7244. for (let i = 0; i < ranges.length; i++) {
  7245. let max = ranges[i];
  7246. let obj = rangeToPattern(String(start), String(max), options);
  7247. let zeros = "";
  7248. if (!tok.isPadded && prev && prev.pattern === obj.pattern) {
  7249. if (prev.count.length > 1) prev.count.pop();
  7250. prev.count.push(obj.count[0]);
  7251. prev.string = prev.pattern + toQuantifier(prev.count);
  7252. start = max + 1;
  7253. continue;
  7254. }
  7255. if (tok.isPadded) zeros = padZeros(max, tok, options);
  7256. obj.string = zeros + obj.pattern + toQuantifier(obj.count);
  7257. tokens.push(obj);
  7258. start = max + 1;
  7259. prev = obj;
  7260. }
  7261. return tokens;
  7262. }
  7263. function filterPatterns(arr, comparison, prefix, intersection, options) {
  7264. let result = [];
  7265. for (let ele of arr) {
  7266. let { string } = ele;
  7267. if (!intersection && !contains(comparison, "string", string)) result.push(prefix + string);
  7268. if (intersection && contains(comparison, "string", string)) result.push(prefix + string);
  7269. }
  7270. return result;
  7271. }
  7272. /**
  7273. * Zip strings
  7274. */
  7275. function zip(a, b) {
  7276. let arr = [];
  7277. for (let i = 0; i < a.length; i++) arr.push([a[i], b[i]]);
  7278. return arr;
  7279. }
  7280. function compare(a, b) {
  7281. return a > b ? 1 : b > a ? -1 : 0;
  7282. }
  7283. function contains(arr, key, val) {
  7284. return arr.some((ele) => ele[key] === val);
  7285. }
  7286. function countNines(min, len) {
  7287. return Number(String(min).slice(0, -len) + "9".repeat(len));
  7288. }
  7289. function countZeros(integer, zeros) {
  7290. return integer - integer % Math.pow(10, zeros);
  7291. }
  7292. function toQuantifier(digits) {
  7293. let [start = 0, stop = ""] = digits;
  7294. if (stop || start > 1) return `{${start + (stop ? "," + stop : "")}}`;
  7295. return "";
  7296. }
  7297. function toCharacterClass(a, b, options) {
  7298. return `[${a}${b - a === 1 ? "" : "-"}${b}]`;
  7299. }
  7300. function hasPadding(str) {
  7301. return /^-?(0+)\d/.test(str);
  7302. }
  7303. function padZeros(value, tok, options) {
  7304. if (!tok.isPadded) return value;
  7305. let diff = Math.abs(tok.maxLen - String(value).length);
  7306. let relax = options.relaxZeros !== false;
  7307. switch (diff) {
  7308. case 0: return "";
  7309. case 1: return relax ? "0?" : "0";
  7310. case 2: return relax ? "0{0,2}" : "00";
  7311. default: return relax ? `0{0,${diff}}` : `0{${diff}}`;
  7312. }
  7313. }
  7314. /**
  7315. * Cache
  7316. */
  7317. toRegexRange.cache = {};
  7318. toRegexRange.clearCache = () => toRegexRange.cache = {};
  7319. /**
  7320. * Expose `toRegexRange`
  7321. */
  7322. module.exports = toRegexRange;
  7323. }));
  7324. //#endregion
  7325. //#region ../../node_modules/.pnpm/fill-range@7.1.1/node_modules/fill-range/index.js
  7326. /*!
  7327. * fill-range <https://github.com/jonschlinkert/fill-range>
  7328. *
  7329. * Copyright (c) 2014-present, Jon Schlinkert.
  7330. * Licensed under the MIT License.
  7331. */
  7332. var require_fill_range = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  7333. const util = __require("util");
  7334. const toRegexRange = require_to_regex_range();
  7335. const isObject = (val) => val !== null && typeof val === "object" && !Array.isArray(val);
  7336. const transform = (toNumber) => {
  7337. return (value) => toNumber === true ? Number(value) : String(value);
  7338. };
  7339. const isValidValue = (value) => {
  7340. return typeof value === "number" || typeof value === "string" && value !== "";
  7341. };
  7342. const isNumber = (num) => Number.isInteger(+num);
  7343. const zeros = (input) => {
  7344. let value = `${input}`;
  7345. let index = -1;
  7346. if (value[0] === "-") value = value.slice(1);
  7347. if (value === "0") return false;
  7348. while (value[++index] === "0");
  7349. return index > 0;
  7350. };
  7351. const stringify = (start, end, options) => {
  7352. if (typeof start === "string" || typeof end === "string") return true;
  7353. return options.stringify === true;
  7354. };
  7355. const pad = (input, maxLength, toNumber) => {
  7356. if (maxLength > 0) {
  7357. let dash = input[0] === "-" ? "-" : "";
  7358. if (dash) input = input.slice(1);
  7359. input = dash + input.padStart(dash ? maxLength - 1 : maxLength, "0");
  7360. }
  7361. if (toNumber === false) return String(input);
  7362. return input;
  7363. };
  7364. const toMaxLen = (input, maxLength) => {
  7365. let negative = input[0] === "-" ? "-" : "";
  7366. if (negative) {
  7367. input = input.slice(1);
  7368. maxLength--;
  7369. }
  7370. while (input.length < maxLength) input = "0" + input;
  7371. return negative ? "-" + input : input;
  7372. };
  7373. const toSequence = (parts, options, maxLen) => {
  7374. parts.negatives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
  7375. parts.positives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
  7376. let prefix = options.capture ? "" : "?:";
  7377. let positives = "";
  7378. let negatives = "";
  7379. let result;
  7380. if (parts.positives.length) positives = parts.positives.map((v) => toMaxLen(String(v), maxLen)).join("|");
  7381. if (parts.negatives.length) negatives = `-(${prefix}${parts.negatives.map((v) => toMaxLen(String(v), maxLen)).join("|")})`;
  7382. if (positives && negatives) result = `${positives}|${negatives}`;
  7383. else result = positives || negatives;
  7384. if (options.wrap) return `(${prefix}${result})`;
  7385. return result;
  7386. };
  7387. const toRange = (a, b, isNumbers, options) => {
  7388. if (isNumbers) return toRegexRange(a, b, {
  7389. wrap: false,
  7390. ...options
  7391. });
  7392. let start = String.fromCharCode(a);
  7393. if (a === b) return start;
  7394. return `[${start}-${String.fromCharCode(b)}]`;
  7395. };
  7396. const toRegex = (start, end, options) => {
  7397. if (Array.isArray(start)) return options.wrap === true ? `(${options.capture ? "" : "?:"}${start.join("|")})` : start.join("|");
  7398. return toRegexRange(start, end, options);
  7399. };
  7400. const rangeError = (...args) => {
  7401. return /* @__PURE__ */ new RangeError("Invalid range arguments: " + util.inspect(...args));
  7402. };
  7403. const invalidRange = (start, end, options) => {
  7404. if (options.strictRanges === true) throw rangeError([start, end]);
  7405. return [];
  7406. };
  7407. const invalidStep = (step, options) => {
  7408. if (options.strictRanges === true) throw new TypeError(`Expected step "${step}" to be a number`);
  7409. return [];
  7410. };
  7411. const fillNumbers = (start, end, step = 1, options = {}) => {
  7412. let a = Number(start);
  7413. let b = Number(end);
  7414. if (!Number.isInteger(a) || !Number.isInteger(b)) {
  7415. if (options.strictRanges === true) throw rangeError([start, end]);
  7416. return [];
  7417. }
  7418. if (a === 0) a = 0;
  7419. if (b === 0) b = 0;
  7420. let descending = a > b;
  7421. let startString = String(start);
  7422. let endString = String(end);
  7423. let stepString = String(step);
  7424. step = Math.max(Math.abs(step), 1);
  7425. let padded = zeros(startString) || zeros(endString) || zeros(stepString);
  7426. let maxLen = padded ? Math.max(startString.length, endString.length, stepString.length) : 0;
  7427. let toNumber = padded === false && stringify(start, end, options) === false;
  7428. let format = options.transform || transform(toNumber);
  7429. if (options.toRegex && step === 1) return toRange(toMaxLen(start, maxLen), toMaxLen(end, maxLen), true, options);
  7430. let parts = {
  7431. negatives: [],
  7432. positives: []
  7433. };
  7434. let push = (num) => parts[num < 0 ? "negatives" : "positives"].push(Math.abs(num));
  7435. let range = [];
  7436. let index = 0;
  7437. while (descending ? a >= b : a <= b) {
  7438. if (options.toRegex === true && step > 1) push(a);
  7439. else range.push(pad(format(a, index), maxLen, toNumber));
  7440. a = descending ? a - step : a + step;
  7441. index++;
  7442. }
  7443. if (options.toRegex === true) return step > 1 ? toSequence(parts, options, maxLen) : toRegex(range, null, {
  7444. wrap: false,
  7445. ...options
  7446. });
  7447. return range;
  7448. };
  7449. const fillLetters = (start, end, step = 1, options = {}) => {
  7450. if (!isNumber(start) && start.length > 1 || !isNumber(end) && end.length > 1) return invalidRange(start, end, options);
  7451. let format = options.transform || ((val) => String.fromCharCode(val));
  7452. let a = `${start}`.charCodeAt(0);
  7453. let b = `${end}`.charCodeAt(0);
  7454. let descending = a > b;
  7455. let min = Math.min(a, b);
  7456. let max = Math.max(a, b);
  7457. if (options.toRegex && step === 1) return toRange(min, max, false, options);
  7458. let range = [];
  7459. let index = 0;
  7460. while (descending ? a >= b : a <= b) {
  7461. range.push(format(a, index));
  7462. a = descending ? a - step : a + step;
  7463. index++;
  7464. }
  7465. if (options.toRegex === true) return toRegex(range, null, {
  7466. wrap: false,
  7467. options
  7468. });
  7469. return range;
  7470. };
  7471. const fill = (start, end, step, options = {}) => {
  7472. if (end == null && isValidValue(start)) return [start];
  7473. if (!isValidValue(start) || !isValidValue(end)) return invalidRange(start, end, options);
  7474. if (typeof step === "function") return fill(start, end, 1, { transform: step });
  7475. if (isObject(step)) return fill(start, end, 0, step);
  7476. let opts = { ...options };
  7477. if (opts.capture === true) opts.wrap = true;
  7478. step = step || opts.step || 1;
  7479. if (!isNumber(step)) {
  7480. if (step != null && !isObject(step)) return invalidStep(step, opts);
  7481. return fill(start, end, 1, step);
  7482. }
  7483. if (isNumber(start) && isNumber(end)) return fillNumbers(start, end, step, opts);
  7484. return fillLetters(start, end, Math.max(Math.abs(step), 1), opts);
  7485. };
  7486. module.exports = fill;
  7487. }));
  7488. //#endregion
  7489. //#region ../../node_modules/.pnpm/braces@3.0.3/node_modules/braces/lib/compile.js
  7490. var require_compile = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  7491. const fill = require_fill_range();
  7492. const utils = require_utils();
  7493. const compile = (ast, options = {}) => {
  7494. const walk = (node, parent = {}) => {
  7495. const invalid = utils.isInvalidBrace(parent) === true || (node.invalid === true && options.escapeInvalid === true) === true;
  7496. const prefix = options.escapeInvalid === true ? "\\" : "";
  7497. let output = "";
  7498. if (node.isOpen === true) return prefix + node.value;
  7499. if (node.isClose === true) {
  7500. console.log("node.isClose", prefix, node.value);
  7501. return prefix + node.value;
  7502. }
  7503. if (node.type === "open") return invalid ? prefix + node.value : "(";
  7504. if (node.type === "close") return invalid ? prefix + node.value : ")";
  7505. if (node.type === "comma") return node.prev.type === "comma" ? "" : invalid ? node.value : "|";
  7506. if (node.value) return node.value;
  7507. if (node.nodes && node.ranges > 0) {
  7508. const args = utils.reduce(node.nodes);
  7509. const range = fill(...args, {
  7510. ...options,
  7511. wrap: false,
  7512. toRegex: true,
  7513. strictZeros: true
  7514. });
  7515. if (range.length !== 0) return args.length > 1 && range.length > 1 ? `(${range})` : range;
  7516. }
  7517. if (node.nodes) for (const child of node.nodes) output += walk(child, node);
  7518. return output;
  7519. };
  7520. return walk(ast);
  7521. };
  7522. module.exports = compile;
  7523. }));
  7524. //#endregion
  7525. //#region ../../node_modules/.pnpm/braces@3.0.3/node_modules/braces/lib/expand.js
  7526. var require_expand = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  7527. const fill = require_fill_range();
  7528. const stringify = require_stringify();
  7529. const utils = require_utils();
  7530. const append = (queue = "", stash = "", enclose = false) => {
  7531. const result = [];
  7532. queue = [].concat(queue);
  7533. stash = [].concat(stash);
  7534. if (!stash.length) return queue;
  7535. if (!queue.length) return enclose ? utils.flatten(stash).map((ele) => `{${ele}}`) : stash;
  7536. for (const item of queue) if (Array.isArray(item)) for (const value of item) result.push(append(value, stash, enclose));
  7537. else for (let ele of stash) {
  7538. if (enclose === true && typeof ele === "string") ele = `{${ele}}`;
  7539. result.push(Array.isArray(ele) ? append(item, ele, enclose) : item + ele);
  7540. }
  7541. return utils.flatten(result);
  7542. };
  7543. const expand = (ast, options = {}) => {
  7544. const rangeLimit = options.rangeLimit === void 0 ? 1e3 : options.rangeLimit;
  7545. const walk = (node, parent = {}) => {
  7546. node.queue = [];
  7547. let p = parent;
  7548. let q = parent.queue;
  7549. while (p.type !== "brace" && p.type !== "root" && p.parent) {
  7550. p = p.parent;
  7551. q = p.queue;
  7552. }
  7553. if (node.invalid || node.dollar) {
  7554. q.push(append(q.pop(), stringify(node, options)));
  7555. return;
  7556. }
  7557. if (node.type === "brace" && node.invalid !== true && node.nodes.length === 2) {
  7558. q.push(append(q.pop(), ["{}"]));
  7559. return;
  7560. }
  7561. if (node.nodes && node.ranges > 0) {
  7562. const args = utils.reduce(node.nodes);
  7563. 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.");
  7564. let range = fill(...args, options);
  7565. if (range.length === 0) range = stringify(node, options);
  7566. q.push(append(q.pop(), range));
  7567. node.nodes = [];
  7568. return;
  7569. }
  7570. const enclose = utils.encloseBrace(node);
  7571. let queue = node.queue;
  7572. let block = node;
  7573. while (block.type !== "brace" && block.type !== "root" && block.parent) {
  7574. block = block.parent;
  7575. queue = block.queue;
  7576. }
  7577. for (let i = 0; i < node.nodes.length; i++) {
  7578. const child = node.nodes[i];
  7579. if (child.type === "comma" && node.type === "brace") {
  7580. if (i === 1) queue.push("");
  7581. queue.push("");
  7582. continue;
  7583. }
  7584. if (child.type === "close") {
  7585. q.push(append(q.pop(), queue, enclose));
  7586. continue;
  7587. }
  7588. if (child.value && child.type !== "open") {
  7589. queue.push(append(queue.pop(), child.value));
  7590. continue;
  7591. }
  7592. if (child.nodes) walk(child, node);
  7593. }
  7594. return queue;
  7595. };
  7596. return utils.flatten(walk(ast));
  7597. };
  7598. module.exports = expand;
  7599. }));
  7600. //#endregion
  7601. //#region ../../node_modules/.pnpm/braces@3.0.3/node_modules/braces/lib/constants.js
  7602. var require_constants$2 = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  7603. module.exports = {
  7604. MAX_LENGTH: 1e4,
  7605. CHAR_0: "0",
  7606. CHAR_9: "9",
  7607. CHAR_UPPERCASE_A: "A",
  7608. CHAR_LOWERCASE_A: "a",
  7609. CHAR_UPPERCASE_Z: "Z",
  7610. CHAR_LOWERCASE_Z: "z",
  7611. CHAR_LEFT_PARENTHESES: "(",
  7612. CHAR_RIGHT_PARENTHESES: ")",
  7613. CHAR_ASTERISK: "*",
  7614. CHAR_AMPERSAND: "&",
  7615. CHAR_AT: "@",
  7616. CHAR_BACKSLASH: "\\",
  7617. CHAR_BACKTICK: "`",
  7618. CHAR_CARRIAGE_RETURN: "\r",
  7619. CHAR_CIRCUMFLEX_ACCENT: "^",
  7620. CHAR_COLON: ":",
  7621. CHAR_COMMA: ",",
  7622. CHAR_DOLLAR: "$",
  7623. CHAR_DOT: ".",
  7624. CHAR_DOUBLE_QUOTE: "\"",
  7625. CHAR_EQUAL: "=",
  7626. CHAR_EXCLAMATION_MARK: "!",
  7627. CHAR_FORM_FEED: "\f",
  7628. CHAR_FORWARD_SLASH: "/",
  7629. CHAR_HASH: "#",
  7630. CHAR_HYPHEN_MINUS: "-",
  7631. CHAR_LEFT_ANGLE_BRACKET: "<",
  7632. CHAR_LEFT_CURLY_BRACE: "{",
  7633. CHAR_LEFT_SQUARE_BRACKET: "[",
  7634. CHAR_LINE_FEED: "\n",
  7635. CHAR_NO_BREAK_SPACE: "\xA0",
  7636. CHAR_PERCENT: "%",
  7637. CHAR_PLUS: "+",
  7638. CHAR_QUESTION_MARK: "?",
  7639. CHAR_RIGHT_ANGLE_BRACKET: ">",
  7640. CHAR_RIGHT_CURLY_BRACE: "}",
  7641. CHAR_RIGHT_SQUARE_BRACKET: "]",
  7642. CHAR_SEMICOLON: ";",
  7643. CHAR_SINGLE_QUOTE: "'",
  7644. CHAR_SPACE: " ",
  7645. CHAR_TAB: " ",
  7646. CHAR_UNDERSCORE: "_",
  7647. CHAR_VERTICAL_LINE: "|",
  7648. CHAR_ZERO_WIDTH_NOBREAK_SPACE: ""
  7649. };
  7650. }));
  7651. //#endregion
  7652. //#region ../../node_modules/.pnpm/braces@3.0.3/node_modules/braces/lib/parse.js
  7653. var require_parse$2 = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  7654. const stringify = require_stringify();
  7655. /**
  7656. * Constants
  7657. */
  7658. 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();
  7659. /**
  7660. * parse
  7661. */
  7662. const parse = (input, options = {}) => {
  7663. if (typeof input !== "string") throw new TypeError("Expected a string");
  7664. const opts = options || {};
  7665. const max = typeof opts.maxLength === "number" ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
  7666. if (input.length > max) throw new SyntaxError(`Input length (${input.length}), exceeds max characters (${max})`);
  7667. const ast = {
  7668. type: "root",
  7669. input,
  7670. nodes: []
  7671. };
  7672. const stack = [ast];
  7673. let block = ast;
  7674. let prev = ast;
  7675. let brackets = 0;
  7676. const length = input.length;
  7677. let index = 0;
  7678. let depth = 0;
  7679. let value;
  7680. /**
  7681. * Helpers
  7682. */
  7683. const advance = () => input[index++];
  7684. const push = (node) => {
  7685. if (node.type === "text" && prev.type === "dot") prev.type = "text";
  7686. if (prev && prev.type === "text" && node.type === "text") {
  7687. prev.value += node.value;
  7688. return;
  7689. }
  7690. block.nodes.push(node);
  7691. node.parent = block;
  7692. node.prev = prev;
  7693. prev = node;
  7694. return node;
  7695. };
  7696. push({ type: "bos" });
  7697. while (index < length) {
  7698. block = stack[stack.length - 1];
  7699. value = advance();
  7700. /**
  7701. * Invalid chars
  7702. */
  7703. if (value === CHAR_ZERO_WIDTH_NOBREAK_SPACE || value === CHAR_NO_BREAK_SPACE) continue;
  7704. /**
  7705. * Escaped chars
  7706. */
  7707. if (value === CHAR_BACKSLASH) {
  7708. push({
  7709. type: "text",
  7710. value: (options.keepEscaping ? value : "") + advance()
  7711. });
  7712. continue;
  7713. }
  7714. /**
  7715. * Right square bracket (literal): ']'
  7716. */
  7717. if (value === CHAR_RIGHT_SQUARE_BRACKET) {
  7718. push({
  7719. type: "text",
  7720. value: "\\" + value
  7721. });
  7722. continue;
  7723. }
  7724. /**
  7725. * Left square bracket: '['
  7726. */
  7727. if (value === CHAR_LEFT_SQUARE_BRACKET) {
  7728. brackets++;
  7729. let next;
  7730. while (index < length && (next = advance())) {
  7731. value += next;
  7732. if (next === CHAR_LEFT_SQUARE_BRACKET) {
  7733. brackets++;
  7734. continue;
  7735. }
  7736. if (next === CHAR_BACKSLASH) {
  7737. value += advance();
  7738. continue;
  7739. }
  7740. if (next === CHAR_RIGHT_SQUARE_BRACKET) {
  7741. brackets--;
  7742. if (brackets === 0) break;
  7743. }
  7744. }
  7745. push({
  7746. type: "text",
  7747. value
  7748. });
  7749. continue;
  7750. }
  7751. /**
  7752. * Parentheses
  7753. */
  7754. if (value === CHAR_LEFT_PARENTHESES) {
  7755. block = push({
  7756. type: "paren",
  7757. nodes: []
  7758. });
  7759. stack.push(block);
  7760. push({
  7761. type: "text",
  7762. value
  7763. });
  7764. continue;
  7765. }
  7766. if (value === CHAR_RIGHT_PARENTHESES) {
  7767. if (block.type !== "paren") {
  7768. push({
  7769. type: "text",
  7770. value
  7771. });
  7772. continue;
  7773. }
  7774. block = stack.pop();
  7775. push({
  7776. type: "text",
  7777. value
  7778. });
  7779. block = stack[stack.length - 1];
  7780. continue;
  7781. }
  7782. /**
  7783. * Quotes: '|"|`
  7784. */
  7785. if (value === CHAR_DOUBLE_QUOTE || value === CHAR_SINGLE_QUOTE || value === CHAR_BACKTICK) {
  7786. const open = value;
  7787. let next;
  7788. if (options.keepQuotes !== true) value = "";
  7789. while (index < length && (next = advance())) {
  7790. if (next === CHAR_BACKSLASH) {
  7791. value += next + advance();
  7792. continue;
  7793. }
  7794. if (next === open) {
  7795. if (options.keepQuotes === true) value += next;
  7796. break;
  7797. }
  7798. value += next;
  7799. }
  7800. push({
  7801. type: "text",
  7802. value
  7803. });
  7804. continue;
  7805. }
  7806. /**
  7807. * Left curly brace: '{'
  7808. */
  7809. if (value === CHAR_LEFT_CURLY_BRACE) {
  7810. depth++;
  7811. block = push({
  7812. type: "brace",
  7813. open: true,
  7814. close: false,
  7815. dollar: prev.value && prev.value.slice(-1) === "$" || block.dollar === true,
  7816. depth,
  7817. commas: 0,
  7818. ranges: 0,
  7819. nodes: []
  7820. });
  7821. stack.push(block);
  7822. push({
  7823. type: "open",
  7824. value
  7825. });
  7826. continue;
  7827. }
  7828. /**
  7829. * Right curly brace: '}'
  7830. */
  7831. if (value === CHAR_RIGHT_CURLY_BRACE) {
  7832. if (block.type !== "brace") {
  7833. push({
  7834. type: "text",
  7835. value
  7836. });
  7837. continue;
  7838. }
  7839. const type = "close";
  7840. block = stack.pop();
  7841. block.close = true;
  7842. push({
  7843. type,
  7844. value
  7845. });
  7846. depth--;
  7847. block = stack[stack.length - 1];
  7848. continue;
  7849. }
  7850. /**
  7851. * Comma: ','
  7852. */
  7853. if (value === CHAR_COMMA && depth > 0) {
  7854. if (block.ranges > 0) {
  7855. block.ranges = 0;
  7856. const open = block.nodes.shift();
  7857. block.nodes = [open, {
  7858. type: "text",
  7859. value: stringify(block)
  7860. }];
  7861. }
  7862. push({
  7863. type: "comma",
  7864. value
  7865. });
  7866. block.commas++;
  7867. continue;
  7868. }
  7869. /**
  7870. * Dot: '.'
  7871. */
  7872. if (value === CHAR_DOT && depth > 0 && block.commas === 0) {
  7873. const siblings = block.nodes;
  7874. if (depth === 0 || siblings.length === 0) {
  7875. push({
  7876. type: "text",
  7877. value
  7878. });
  7879. continue;
  7880. }
  7881. if (prev.type === "dot") {
  7882. block.range = [];
  7883. prev.value += value;
  7884. prev.type = "range";
  7885. if (block.nodes.length !== 3 && block.nodes.length !== 5) {
  7886. block.invalid = true;
  7887. block.ranges = 0;
  7888. prev.type = "text";
  7889. continue;
  7890. }
  7891. block.ranges++;
  7892. block.args = [];
  7893. continue;
  7894. }
  7895. if (prev.type === "range") {
  7896. siblings.pop();
  7897. const before = siblings[siblings.length - 1];
  7898. before.value += prev.value + value;
  7899. prev = before;
  7900. block.ranges--;
  7901. continue;
  7902. }
  7903. push({
  7904. type: "dot",
  7905. value
  7906. });
  7907. continue;
  7908. }
  7909. /**
  7910. * Text
  7911. */
  7912. push({
  7913. type: "text",
  7914. value
  7915. });
  7916. }
  7917. do {
  7918. block = stack.pop();
  7919. if (block.type !== "root") {
  7920. block.nodes.forEach((node) => {
  7921. if (!node.nodes) {
  7922. if (node.type === "open") node.isOpen = true;
  7923. if (node.type === "close") node.isClose = true;
  7924. if (!node.nodes) node.type = "text";
  7925. node.invalid = true;
  7926. }
  7927. });
  7928. const parent = stack[stack.length - 1];
  7929. const index = parent.nodes.indexOf(block);
  7930. parent.nodes.splice(index, 1, ...block.nodes);
  7931. }
  7932. } while (stack.length > 0);
  7933. push({ type: "eos" });
  7934. return ast;
  7935. };
  7936. module.exports = parse;
  7937. }));
  7938. //#endregion
  7939. //#region ../../node_modules/.pnpm/braces@3.0.3/node_modules/braces/index.js
  7940. var require_braces = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  7941. const stringify = require_stringify();
  7942. const compile = require_compile();
  7943. const expand = require_expand();
  7944. const parse = require_parse$2();
  7945. /**
  7946. * Expand the given pattern or create a regex-compatible string.
  7947. *
  7948. * ```js
  7949. * const braces = require('braces');
  7950. * console.log(braces('{a,b,c}', { compile: true })); //=> ['(a|b|c)']
  7951. * console.log(braces('{a,b,c}')); //=> ['a', 'b', 'c']
  7952. * ```
  7953. * @param {String} `str`
  7954. * @param {Object} `options`
  7955. * @return {String}
  7956. * @api public
  7957. */
  7958. const braces = (input, options = {}) => {
  7959. let output = [];
  7960. if (Array.isArray(input)) for (const pattern of input) {
  7961. const result = braces.create(pattern, options);
  7962. if (Array.isArray(result)) output.push(...result);
  7963. else output.push(result);
  7964. }
  7965. else output = [].concat(braces.create(input, options));
  7966. if (options && options.expand === true && options.nodupes === true) output = [...new Set(output)];
  7967. return output;
  7968. };
  7969. /**
  7970. * Parse the given `str` with the given `options`.
  7971. *
  7972. * ```js
  7973. * // braces.parse(pattern, [, options]);
  7974. * const ast = braces.parse('a/{b,c}/d');
  7975. * console.log(ast);
  7976. * ```
  7977. * @param {String} pattern Brace pattern to parse
  7978. * @param {Object} options
  7979. * @return {Object} Returns an AST
  7980. * @api public
  7981. */
  7982. braces.parse = (input, options = {}) => parse(input, options);
  7983. /**
  7984. * Creates a braces string from an AST, or an AST node.
  7985. *
  7986. * ```js
  7987. * const braces = require('braces');
  7988. * let ast = braces.parse('foo/{a,b}/bar');
  7989. * console.log(stringify(ast.nodes[2])); //=> '{a,b}'
  7990. * ```
  7991. * @param {String} `input` Brace pattern or AST.
  7992. * @param {Object} `options`
  7993. * @return {Array} Returns an array of expanded values.
  7994. * @api public
  7995. */
  7996. braces.stringify = (input, options = {}) => {
  7997. if (typeof input === "string") return stringify(braces.parse(input, options), options);
  7998. return stringify(input, options);
  7999. };
  8000. /**
  8001. * Compiles a brace pattern into a regex-compatible, optimized string.
  8002. * This method is called by the main [braces](#braces) function by default.
  8003. *
  8004. * ```js
  8005. * const braces = require('braces');
  8006. * console.log(braces.compile('a/{b,c}/d'));
  8007. * //=> ['a/(b|c)/d']
  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.compile = (input, options = {}) => {
  8015. if (typeof input === "string") input = braces.parse(input, options);
  8016. return compile(input, options);
  8017. };
  8018. /**
  8019. * Expands a brace pattern into an array. This method is called by the
  8020. * main [braces](#braces) function when `options.expand` is true. Before
  8021. * using this method it's recommended that you read the [performance notes](#performance))
  8022. * and advantages of using [.compile](#compile) instead.
  8023. *
  8024. * ```js
  8025. * const braces = require('braces');
  8026. * console.log(braces.expand('a/{b,c}/d'));
  8027. * //=> ['a/b/d', 'a/c/d'];
  8028. * ```
  8029. * @param {String} `pattern` Brace pattern
  8030. * @param {Object} `options`
  8031. * @return {Array} Returns an array of expanded values.
  8032. * @api public
  8033. */
  8034. braces.expand = (input, options = {}) => {
  8035. if (typeof input === "string") input = braces.parse(input, options);
  8036. let result = expand(input, options);
  8037. if (options.noempty === true) result = result.filter(Boolean);
  8038. if (options.nodupes === true) result = [...new Set(result)];
  8039. return result;
  8040. };
  8041. /**
  8042. * Processes a brace pattern and returns either an expanded array
  8043. * (if `options.expand` is true), a highly optimized regex-compatible string.
  8044. * This method is called by the main [braces](#braces) function.
  8045. *
  8046. * ```js
  8047. * const braces = require('braces');
  8048. * console.log(braces.create('user-{200..300}/project-{a,b,c}-{1..10}'))
  8049. * //=> 'user-(20[0-9]|2[1-9][0-9]|300)/project-(a|b|c)-([1-9]|10)'
  8050. * ```
  8051. * @param {String} `pattern` Brace pattern
  8052. * @param {Object} `options`
  8053. * @return {Array} Returns an array of expanded values.
  8054. * @api public
  8055. */
  8056. braces.create = (input, options = {}) => {
  8057. if (input === "" || input.length < 3) return [input];
  8058. return options.expand !== true ? braces.compile(input, options) : braces.expand(input, options);
  8059. };
  8060. /**
  8061. * Expose "braces"
  8062. */
  8063. module.exports = braces;
  8064. }));
  8065. //#endregion
  8066. //#region ../../node_modules/.pnpm/binary-extensions@2.3.0/node_modules/binary-extensions/binary-extensions.json
  8067. var require_binary_extensions$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  8068. module.exports = [
  8069. "3dm",
  8070. "3ds",
  8071. "3g2",
  8072. "3gp",
  8073. "7z",
  8074. "a",
  8075. "aac",
  8076. "adp",
  8077. "afdesign",
  8078. "afphoto",
  8079. "afpub",
  8080. "ai",
  8081. "aif",
  8082. "aiff",
  8083. "alz",
  8084. "ape",
  8085. "apk",
  8086. "appimage",
  8087. "ar",
  8088. "arj",
  8089. "asf",
  8090. "au",
  8091. "avi",
  8092. "bak",
  8093. "baml",
  8094. "bh",
  8095. "bin",
  8096. "bk",
  8097. "bmp",
  8098. "btif",
  8099. "bz2",
  8100. "bzip2",
  8101. "cab",
  8102. "caf",
  8103. "cgm",
  8104. "class",
  8105. "cmx",
  8106. "cpio",
  8107. "cr2",
  8108. "cur",
  8109. "dat",
  8110. "dcm",
  8111. "deb",
  8112. "dex",
  8113. "djvu",
  8114. "dll",
  8115. "dmg",
  8116. "dng",
  8117. "doc",
  8118. "docm",
  8119. "docx",
  8120. "dot",
  8121. "dotm",
  8122. "dra",
  8123. "DS_Store",
  8124. "dsk",
  8125. "dts",
  8126. "dtshd",
  8127. "dvb",
  8128. "dwg",
  8129. "dxf",
  8130. "ecelp4800",
  8131. "ecelp7470",
  8132. "ecelp9600",
  8133. "egg",
  8134. "eol",
  8135. "eot",
  8136. "epub",
  8137. "exe",
  8138. "f4v",
  8139. "fbs",
  8140. "fh",
  8141. "fla",
  8142. "flac",
  8143. "flatpak",
  8144. "fli",
  8145. "flv",
  8146. "fpx",
  8147. "fst",
  8148. "fvt",
  8149. "g3",
  8150. "gh",
  8151. "gif",
  8152. "graffle",
  8153. "gz",
  8154. "gzip",
  8155. "h261",
  8156. "h263",
  8157. "h264",
  8158. "icns",
  8159. "ico",
  8160. "ief",
  8161. "img",
  8162. "ipa",
  8163. "iso",
  8164. "jar",
  8165. "jpeg",
  8166. "jpg",
  8167. "jpgv",
  8168. "jpm",
  8169. "jxr",
  8170. "key",
  8171. "ktx",
  8172. "lha",
  8173. "lib",
  8174. "lvp",
  8175. "lz",
  8176. "lzh",
  8177. "lzma",
  8178. "lzo",
  8179. "m3u",
  8180. "m4a",
  8181. "m4v",
  8182. "mar",
  8183. "mdi",
  8184. "mht",
  8185. "mid",
  8186. "midi",
  8187. "mj2",
  8188. "mka",
  8189. "mkv",
  8190. "mmr",
  8191. "mng",
  8192. "mobi",
  8193. "mov",
  8194. "movie",
  8195. "mp3",
  8196. "mp4",
  8197. "mp4a",
  8198. "mpeg",
  8199. "mpg",
  8200. "mpga",
  8201. "mxu",
  8202. "nef",
  8203. "npx",
  8204. "numbers",
  8205. "nupkg",
  8206. "o",
  8207. "odp",
  8208. "ods",
  8209. "odt",
  8210. "oga",
  8211. "ogg",
  8212. "ogv",
  8213. "otf",
  8214. "ott",
  8215. "pages",
  8216. "pbm",
  8217. "pcx",
  8218. "pdb",
  8219. "pdf",
  8220. "pea",
  8221. "pgm",
  8222. "pic",
  8223. "png",
  8224. "pnm",
  8225. "pot",
  8226. "potm",
  8227. "potx",
  8228. "ppa",
  8229. "ppam",
  8230. "ppm",
  8231. "pps",
  8232. "ppsm",
  8233. "ppsx",
  8234. "ppt",
  8235. "pptm",
  8236. "pptx",
  8237. "psd",
  8238. "pya",
  8239. "pyc",
  8240. "pyo",
  8241. "pyv",
  8242. "qt",
  8243. "rar",
  8244. "ras",
  8245. "raw",
  8246. "resources",
  8247. "rgb",
  8248. "rip",
  8249. "rlc",
  8250. "rmf",
  8251. "rmvb",
  8252. "rpm",
  8253. "rtf",
  8254. "rz",
  8255. "s3m",
  8256. "s7z",
  8257. "scpt",
  8258. "sgi",
  8259. "shar",
  8260. "snap",
  8261. "sil",
  8262. "sketch",
  8263. "slk",
  8264. "smv",
  8265. "snk",
  8266. "so",
  8267. "stl",
  8268. "suo",
  8269. "sub",
  8270. "swf",
  8271. "tar",
  8272. "tbz",
  8273. "tbz2",
  8274. "tga",
  8275. "tgz",
  8276. "thmx",
  8277. "tif",
  8278. "tiff",
  8279. "tlz",
  8280. "ttc",
  8281. "ttf",
  8282. "txz",
  8283. "udf",
  8284. "uvh",
  8285. "uvi",
  8286. "uvm",
  8287. "uvp",
  8288. "uvs",
  8289. "uvu",
  8290. "viv",
  8291. "vob",
  8292. "war",
  8293. "wav",
  8294. "wax",
  8295. "wbmp",
  8296. "wdp",
  8297. "weba",
  8298. "webm",
  8299. "webp",
  8300. "whl",
  8301. "wim",
  8302. "wm",
  8303. "wma",
  8304. "wmv",
  8305. "wmx",
  8306. "woff",
  8307. "woff2",
  8308. "wrm",
  8309. "wvx",
  8310. "xbm",
  8311. "xif",
  8312. "xla",
  8313. "xlam",
  8314. "xls",
  8315. "xlsb",
  8316. "xlsm",
  8317. "xlsx",
  8318. "xlt",
  8319. "xltm",
  8320. "xltx",
  8321. "xm",
  8322. "xmind",
  8323. "xpi",
  8324. "xpm",
  8325. "xwd",
  8326. "xz",
  8327. "z",
  8328. "zip",
  8329. "zipx"
  8330. ];
  8331. }));
  8332. //#endregion
  8333. //#region ../../node_modules/.pnpm/binary-extensions@2.3.0/node_modules/binary-extensions/index.js
  8334. var require_binary_extensions = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  8335. module.exports = require_binary_extensions$1();
  8336. }));
  8337. //#endregion
  8338. //#region ../../node_modules/.pnpm/is-binary-path@2.1.0/node_modules/is-binary-path/index.js
  8339. var require_is_binary_path = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  8340. const path$10 = __require("path");
  8341. const binaryExtensions = require_binary_extensions();
  8342. const extensions = new Set(binaryExtensions);
  8343. module.exports = (filePath) => extensions.has(path$10.extname(filePath).slice(1).toLowerCase());
  8344. }));
  8345. //#endregion
  8346. //#region ../../node_modules/.pnpm/chokidar@3.6.0_patch_hash=8a4f9e2b397e6034b91a0508faae3cecb97f222313faa129d7cb0eb71e9d0e84/node_modules/chokidar/lib/constants.js
  8347. var require_constants$1 = /* @__PURE__ */ __commonJSMin(((exports) => {
  8348. const { sep: sep$1 } = __require("path");
  8349. const { platform } = process;
  8350. const os$3 = __require("os");
  8351. exports.EV_ALL = "all";
  8352. exports.EV_READY = "ready";
  8353. exports.EV_ADD = "add";
  8354. exports.EV_CHANGE = "change";
  8355. exports.EV_ADD_DIR = "addDir";
  8356. exports.EV_UNLINK = "unlink";
  8357. exports.EV_UNLINK_DIR = "unlinkDir";
  8358. exports.EV_RAW = "raw";
  8359. exports.EV_ERROR = "error";
  8360. exports.STR_DATA = "data";
  8361. exports.STR_END = "end";
  8362. exports.STR_CLOSE = "close";
  8363. exports.FSEVENT_CREATED = "created";
  8364. exports.FSEVENT_MODIFIED = "modified";
  8365. exports.FSEVENT_DELETED = "deleted";
  8366. exports.FSEVENT_MOVED = "moved";
  8367. exports.FSEVENT_CLONED = "cloned";
  8368. exports.FSEVENT_UNKNOWN = "unknown";
  8369. exports.FSEVENT_FLAG_MUST_SCAN_SUBDIRS = 1;
  8370. exports.FSEVENT_TYPE_FILE = "file";
  8371. exports.FSEVENT_TYPE_DIRECTORY = "directory";
  8372. exports.FSEVENT_TYPE_SYMLINK = "symlink";
  8373. exports.KEY_LISTENERS = "listeners";
  8374. exports.KEY_ERR = "errHandlers";
  8375. exports.KEY_RAW = "rawEmitters";
  8376. exports.HANDLER_KEYS = [
  8377. exports.KEY_LISTENERS,
  8378. exports.KEY_ERR,
  8379. exports.KEY_RAW
  8380. ];
  8381. exports.DOT_SLASH = `.${sep$1}`;
  8382. exports.BACK_SLASH_RE = /\\/g;
  8383. exports.DOUBLE_SLASH_RE = /\/\//;
  8384. exports.SLASH_OR_BACK_SLASH_RE = /[/\\]/;
  8385. exports.DOT_RE = /\..*\.(sw[px])$|~$|\.subl.*\.tmp/;
  8386. exports.REPLACER_RE = /^\.[/\\]/;
  8387. exports.SLASH = "/";
  8388. exports.SLASH_SLASH = "//";
  8389. exports.BRACE_START = "{";
  8390. exports.BANG = "!";
  8391. exports.ONE_DOT = ".";
  8392. exports.TWO_DOTS = "..";
  8393. exports.STAR = "*";
  8394. exports.GLOBSTAR = "**";
  8395. exports.ROOT_GLOBSTAR = "/**/*";
  8396. exports.SLASH_GLOBSTAR = "/**";
  8397. exports.DIR_SUFFIX = "Dir";
  8398. exports.ANYMATCH_OPTS = { dot: true };
  8399. exports.STRING_TYPE = "string";
  8400. exports.FUNCTION_TYPE = "function";
  8401. exports.EMPTY_STR = "";
  8402. exports.EMPTY_FN = () => {};
  8403. exports.IDENTITY_FN = (val) => val;
  8404. exports.isWindows = platform === "win32";
  8405. exports.isMacos = platform === "darwin";
  8406. exports.isLinux = platform === "linux";
  8407. exports.isIBMi = os$3.type() === "OS400";
  8408. }));
  8409. //#endregion
  8410. //#region ../../node_modules/.pnpm/chokidar@3.6.0_patch_hash=8a4f9e2b397e6034b91a0508faae3cecb97f222313faa129d7cb0eb71e9d0e84/node_modules/chokidar/lib/nodefs-handler.js
  8411. var require_nodefs_handler = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  8412. const fs$9 = __require("fs");
  8413. const sysPath$2 = __require("path");
  8414. const { promisify: promisify$3 } = __require("util");
  8415. const isBinaryPath = require_is_binary_path();
  8416. 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();
  8417. const THROTTLE_MODE_WATCH = "watch";
  8418. const open = promisify$3(fs$9.open);
  8419. const stat = promisify$3(fs$9.stat);
  8420. const lstat = promisify$3(fs$9.lstat);
  8421. const close = promisify$3(fs$9.close);
  8422. const fsrealpath = promisify$3(fs$9.realpath);
  8423. const statMethods = {
  8424. lstat,
  8425. stat
  8426. };
  8427. const foreach = (val, fn) => {
  8428. if (val instanceof Set) val.forEach(fn);
  8429. else fn(val);
  8430. };
  8431. const addAndConvert = (main, prop, item) => {
  8432. let container = main[prop];
  8433. if (!(container instanceof Set)) main[prop] = container = new Set([container]);
  8434. container.add(item);
  8435. };
  8436. const clearItem = (cont) => (key) => {
  8437. const set = cont[key];
  8438. if (set instanceof Set) set.clear();
  8439. else delete cont[key];
  8440. };
  8441. const delFromSet = (main, prop, item) => {
  8442. const container = main[prop];
  8443. if (container instanceof Set) container.delete(item);
  8444. else if (container === item) delete main[prop];
  8445. };
  8446. const isEmptySet = (val) => val instanceof Set ? val.size === 0 : !val;
  8447. /**
  8448. * @typedef {String} Path
  8449. */
  8450. /**
  8451. * @typedef {Object} FsWatchContainer
  8452. * @property {Set} listeners
  8453. * @property {Set} errHandlers
  8454. * @property {Set} rawEmitters
  8455. * @property {fs.FSWatcher=} watcher
  8456. * @property {Boolean=} watcherUnusable
  8457. */
  8458. /**
  8459. * @type {Map<String,FsWatchContainer>}
  8460. */
  8461. const FsWatchInstances = /* @__PURE__ */ new Map();
  8462. /**
  8463. * Instantiates the fs_watch interface
  8464. * @param {String} path to be watched
  8465. * @param {Object} options to be passed to fs_watch
  8466. * @param {Function} listener main event handler
  8467. * @param {Function} errHandler emits info about errors
  8468. * @param {Function} emitRaw emits raw event data
  8469. * @returns {fs.FSWatcher} new fsevents instance
  8470. */
  8471. function createFsWatchInstance(path, options, listener, errHandler, emitRaw) {
  8472. const handleEvent = (rawEvent, evPath) => {
  8473. listener(path);
  8474. emitRaw(rawEvent, evPath, { watchedPath: path });
  8475. if (evPath && path !== evPath) fsWatchBroadcast(sysPath$2.resolve(path, evPath), KEY_LISTENERS, sysPath$2.join(path, evPath));
  8476. };
  8477. try {
  8478. return fs$9.watch(path, options, handleEvent);
  8479. } catch (error) {
  8480. errHandler(error);
  8481. }
  8482. }
  8483. /**
  8484. * Helper for passing fs_watch event data to a collection of listeners
  8485. * @param {Path} fullPath absolute path bound to fs_watch instance
  8486. * @param {String} type listener type
  8487. * @param {*=} val1 arguments to be passed to listeners
  8488. * @param {*=} val2
  8489. * @param {*=} val3
  8490. */
  8491. const fsWatchBroadcast = (fullPath, type, val1, val2, val3) => {
  8492. const cont = FsWatchInstances.get(fullPath);
  8493. if (!cont) return;
  8494. foreach(cont[type], (listener) => {
  8495. listener(val1, val2, val3);
  8496. });
  8497. };
  8498. /**
  8499. * Instantiates the fs_watch interface or binds listeners
  8500. * to an existing one covering the same file system entry
  8501. * @param {String} path
  8502. * @param {String} fullPath absolute path
  8503. * @param {Object} options to be passed to fs_watch
  8504. * @param {Object} handlers container for event listener functions
  8505. */
  8506. const setFsWatchListener = (path, fullPath, options, handlers) => {
  8507. const { listener, errHandler, rawEmitter } = handlers;
  8508. let cont = FsWatchInstances.get(fullPath);
  8509. /** @type {fs.FSWatcher=} */
  8510. let watcher;
  8511. if (!options.persistent) {
  8512. watcher = createFsWatchInstance(path, options, listener, errHandler, rawEmitter);
  8513. return watcher.close.bind(watcher);
  8514. }
  8515. if (cont) {
  8516. addAndConvert(cont, KEY_LISTENERS, listener);
  8517. addAndConvert(cont, KEY_ERR, errHandler);
  8518. addAndConvert(cont, KEY_RAW, rawEmitter);
  8519. } else {
  8520. watcher = createFsWatchInstance(path, options, fsWatchBroadcast.bind(null, fullPath, KEY_LISTENERS), errHandler, fsWatchBroadcast.bind(null, fullPath, KEY_RAW));
  8521. if (!watcher) return;
  8522. watcher.on(EV_ERROR, async (error) => {
  8523. const broadcastErr = fsWatchBroadcast.bind(null, fullPath, KEY_ERR);
  8524. cont.watcherUnusable = true;
  8525. if (isWindows && error.code === "EPERM") try {
  8526. await close(await open(path, "r"));
  8527. broadcastErr(error);
  8528. } catch (err) {}
  8529. else broadcastErr(error);
  8530. });
  8531. cont = {
  8532. listeners: listener,
  8533. errHandlers: errHandler,
  8534. rawEmitters: rawEmitter,
  8535. watcher
  8536. };
  8537. FsWatchInstances.set(fullPath, cont);
  8538. }
  8539. return () => {
  8540. delFromSet(cont, KEY_LISTENERS, listener);
  8541. delFromSet(cont, KEY_ERR, errHandler);
  8542. delFromSet(cont, KEY_RAW, rawEmitter);
  8543. if (isEmptySet(cont.listeners)) {
  8544. cont.watcher.close();
  8545. FsWatchInstances.delete(fullPath);
  8546. HANDLER_KEYS.forEach(clearItem(cont));
  8547. cont.watcher = void 0;
  8548. Object.freeze(cont);
  8549. }
  8550. };
  8551. };
  8552. const FsWatchFileInstances = /* @__PURE__ */ new Map();
  8553. /**
  8554. * Instantiates the fs_watchFile interface or binds listeners
  8555. * to an existing one covering the same file system entry
  8556. * @param {String} path to be watched
  8557. * @param {String} fullPath absolute path
  8558. * @param {Object} options options to be passed to fs_watchFile
  8559. * @param {Object} handlers container for event listener functions
  8560. * @returns {Function} closer
  8561. */
  8562. const setFsWatchFileListener = (path, fullPath, options, handlers) => {
  8563. const { listener, rawEmitter } = handlers;
  8564. let cont = FsWatchFileInstances.get(fullPath);
  8565. const copts = cont && cont.options;
  8566. if (copts && (copts.persistent < options.persistent || copts.interval > options.interval)) {
  8567. fs$9.unwatchFile(fullPath);
  8568. cont = void 0;
  8569. }
  8570. if (cont) {
  8571. addAndConvert(cont, KEY_LISTENERS, listener);
  8572. addAndConvert(cont, KEY_RAW, rawEmitter);
  8573. } else {
  8574. cont = {
  8575. listeners: listener,
  8576. rawEmitters: rawEmitter,
  8577. options,
  8578. watcher: fs$9.watchFile(fullPath, options, (curr, prev) => {
  8579. foreach(cont.rawEmitters, (rawEmitter) => {
  8580. rawEmitter(EV_CHANGE, fullPath, {
  8581. curr,
  8582. prev
  8583. });
  8584. });
  8585. const currmtime = curr.mtimeMs;
  8586. if (curr.size !== prev.size || currmtime > prev.mtimeMs || currmtime === 0) foreach(cont.listeners, (listener) => listener(path, curr));
  8587. })
  8588. };
  8589. FsWatchFileInstances.set(fullPath, cont);
  8590. }
  8591. return () => {
  8592. delFromSet(cont, KEY_LISTENERS, listener);
  8593. delFromSet(cont, KEY_RAW, rawEmitter);
  8594. if (isEmptySet(cont.listeners)) {
  8595. FsWatchFileInstances.delete(fullPath);
  8596. fs$9.unwatchFile(fullPath);
  8597. cont.options = cont.watcher = void 0;
  8598. Object.freeze(cont);
  8599. }
  8600. };
  8601. };
  8602. /**
  8603. * @mixin
  8604. */
  8605. var NodeFsHandler = class {
  8606. /**
  8607. * @param {import("../index").FSWatcher} fsW
  8608. */
  8609. constructor(fsW) {
  8610. this.fsw = fsW;
  8611. this._boundHandleError = (error) => fsW._handleError(error);
  8612. }
  8613. /**
  8614. * Watch file for changes with fs_watchFile or fs_watch.
  8615. * @param {String} path to file or dir
  8616. * @param {Function} listener on fs change
  8617. * @returns {Function} closer for the watcher instance
  8618. */
  8619. _watchWithNodeFs(path, listener) {
  8620. const opts = this.fsw.options;
  8621. const directory = sysPath$2.dirname(path);
  8622. const basename = sysPath$2.basename(path);
  8623. this.fsw._getWatchedDir(directory).add(basename);
  8624. const absolutePath = sysPath$2.resolve(path);
  8625. const options = { persistent: opts.persistent };
  8626. if (!listener) listener = EMPTY_FN;
  8627. let closer;
  8628. if (opts.usePolling) {
  8629. options.interval = opts.enableBinaryInterval && isBinaryPath(basename) ? opts.binaryInterval : opts.interval;
  8630. closer = setFsWatchFileListener(path, absolutePath, options, {
  8631. listener,
  8632. rawEmitter: this.fsw._emitRaw
  8633. });
  8634. } else closer = setFsWatchListener(path, absolutePath, options, {
  8635. listener,
  8636. errHandler: this._boundHandleError,
  8637. rawEmitter: this.fsw._emitRaw
  8638. });
  8639. return closer;
  8640. }
  8641. /**
  8642. * Watch a file and emit add event if warranted.
  8643. * @param {Path} file Path
  8644. * @param {fs.Stats} stats result of fs_stat
  8645. * @param {Boolean} initialAdd was the file added at watch instantiation?
  8646. * @returns {Function} closer for the watcher instance
  8647. */
  8648. _handleFile(file, stats, initialAdd) {
  8649. if (this.fsw.closed) return;
  8650. const dirname = sysPath$2.dirname(file);
  8651. const basename = sysPath$2.basename(file);
  8652. const parent = this.fsw._getWatchedDir(dirname);
  8653. let prevStats = stats;
  8654. if (parent.has(basename)) return;
  8655. const listener = async (path, newStats) => {
  8656. if (!this.fsw._throttle(THROTTLE_MODE_WATCH, file, 5)) return;
  8657. if (!newStats || newStats.mtimeMs === 0) try {
  8658. const newStats = await stat(file);
  8659. if (this.fsw.closed) return;
  8660. const at = newStats.atimeMs;
  8661. const mt = newStats.mtimeMs;
  8662. if (!at || at <= mt || mt !== prevStats.mtimeMs) this.fsw._emit(EV_CHANGE, file, newStats);
  8663. if (isLinux && prevStats.ino !== newStats.ino) {
  8664. this.fsw._closeFile(path);
  8665. prevStats = newStats;
  8666. this.fsw._addPathCloser(path, this._watchWithNodeFs(file, listener));
  8667. } else prevStats = newStats;
  8668. } catch (error) {
  8669. this.fsw._remove(dirname, basename);
  8670. }
  8671. else if (parent.has(basename)) {
  8672. const at = newStats.atimeMs;
  8673. const mt = newStats.mtimeMs;
  8674. if (!at || at <= mt || mt !== prevStats.mtimeMs) this.fsw._emit(EV_CHANGE, file, newStats);
  8675. prevStats = newStats;
  8676. }
  8677. };
  8678. const closer = this._watchWithNodeFs(file, listener);
  8679. if (!(initialAdd && this.fsw.options.ignoreInitial) && this.fsw._isntIgnored(file)) {
  8680. if (!this.fsw._throttle(EV_ADD, file, 0)) return;
  8681. this.fsw._emit(EV_ADD, file, stats);
  8682. }
  8683. return closer;
  8684. }
  8685. /**
  8686. * Handle symlinks encountered while reading a dir.
  8687. * @param {Object} entry returned by readdirp
  8688. * @param {String} directory path of dir being read
  8689. * @param {String} path of this item
  8690. * @param {String} item basename of this item
  8691. * @returns {Promise<Boolean>} true if no more processing is needed for this entry.
  8692. */
  8693. async _handleSymlink(entry, directory, path, item) {
  8694. if (this.fsw.closed) return;
  8695. const full = entry.fullPath;
  8696. const dir = this.fsw._getWatchedDir(directory);
  8697. if (!this.fsw.options.followSymlinks) {
  8698. this.fsw._incrReadyCount();
  8699. let linkPath;
  8700. try {
  8701. linkPath = await fsrealpath(path);
  8702. } catch (e) {
  8703. this.fsw._emitReady();
  8704. return true;
  8705. }
  8706. if (this.fsw.closed) return;
  8707. if (dir.has(item)) {
  8708. if (this.fsw._symlinkPaths.get(full) !== linkPath) {
  8709. this.fsw._symlinkPaths.set(full, linkPath);
  8710. this.fsw._emit(EV_CHANGE, path, entry.stats);
  8711. }
  8712. } else {
  8713. dir.add(item);
  8714. this.fsw._symlinkPaths.set(full, linkPath);
  8715. this.fsw._emit(EV_ADD, path, entry.stats);
  8716. }
  8717. this.fsw._emitReady();
  8718. return true;
  8719. }
  8720. if (this.fsw._symlinkPaths.has(full)) return true;
  8721. this.fsw._symlinkPaths.set(full, true);
  8722. }
  8723. _handleRead(directory, initialAdd, wh, target, dir, depth, throttler) {
  8724. directory = sysPath$2.join(directory, EMPTY_STR);
  8725. if (!wh.hasGlob) {
  8726. throttler = this.fsw._throttle("readdir", directory, 1e3);
  8727. if (!throttler) return;
  8728. }
  8729. const previous = this.fsw._getWatchedDir(wh.path);
  8730. const current = /* @__PURE__ */ new Set();
  8731. let stream = this.fsw._readdirp(directory, {
  8732. fileFilter: (entry) => wh.filterPath(entry),
  8733. directoryFilter: (entry) => wh.filterDir(entry),
  8734. depth: 0
  8735. }).on(STR_DATA, async (entry) => {
  8736. if (this.fsw.closed) {
  8737. stream = void 0;
  8738. return;
  8739. }
  8740. const item = entry.path;
  8741. let path = sysPath$2.join(directory, item);
  8742. current.add(item);
  8743. if (entry.stats.isSymbolicLink() && await this._handleSymlink(entry, directory, path, item)) return;
  8744. if (this.fsw.closed) {
  8745. stream = void 0;
  8746. return;
  8747. }
  8748. if (item === target || !target && !previous.has(item)) {
  8749. this.fsw._incrReadyCount();
  8750. path = sysPath$2.join(dir, sysPath$2.relative(dir, path));
  8751. this._addToNodeFs(path, initialAdd, wh, depth + 1);
  8752. }
  8753. }).on(EV_ERROR, this._boundHandleError);
  8754. return new Promise((resolve) => stream.once(STR_END, () => {
  8755. if (this.fsw.closed) {
  8756. stream = void 0;
  8757. return;
  8758. }
  8759. const wasThrottled = throttler ? throttler.clear() : false;
  8760. resolve();
  8761. previous.getChildren().filter((item) => {
  8762. return item !== directory && !current.has(item) && (!wh.hasGlob || wh.filterPath({ fullPath: sysPath$2.resolve(directory, item) }));
  8763. }).forEach((item) => {
  8764. this.fsw._remove(directory, item);
  8765. });
  8766. stream = void 0;
  8767. if (wasThrottled) this._handleRead(directory, false, wh, target, dir, depth, throttler);
  8768. }));
  8769. }
  8770. /**
  8771. * Read directory to add / remove files from `@watched` list and re-read it on change.
  8772. * @param {String} dir fs path
  8773. * @param {fs.Stats} stats
  8774. * @param {Boolean} initialAdd
  8775. * @param {Number} depth relative to user-supplied path
  8776. * @param {String} target child path targeted for watch
  8777. * @param {Object} wh Common watch helpers for this path
  8778. * @param {String} realpath
  8779. * @returns {Promise<Function>} closer for the watcher instance.
  8780. */
  8781. async _handleDir(dir, stats, initialAdd, depth, target, wh, realpath) {
  8782. const parentDir = this.fsw._getWatchedDir(sysPath$2.dirname(dir));
  8783. const tracked = parentDir.has(sysPath$2.basename(dir));
  8784. if (!(initialAdd && this.fsw.options.ignoreInitial) && !target && !tracked) {
  8785. if (!wh.hasGlob || wh.globFilter(dir)) this.fsw._emit(EV_ADD_DIR, dir, stats);
  8786. }
  8787. parentDir.add(sysPath$2.basename(dir));
  8788. this.fsw._getWatchedDir(dir);
  8789. let throttler;
  8790. let closer;
  8791. const oDepth = this.fsw.options.depth;
  8792. if ((oDepth == null || depth <= oDepth) && !this.fsw._symlinkPaths.has(realpath)) {
  8793. if (!target) {
  8794. await this._handleRead(dir, initialAdd, wh, target, dir, depth, throttler);
  8795. if (this.fsw.closed) return;
  8796. }
  8797. closer = this._watchWithNodeFs(dir, (dirPath, stats) => {
  8798. if (stats && stats.mtimeMs === 0) return;
  8799. this._handleRead(dirPath, false, wh, target, dir, depth, throttler);
  8800. });
  8801. }
  8802. return closer;
  8803. }
  8804. /**
  8805. * Handle added file, directory, or glob pattern.
  8806. * Delegates call to _handleFile / _handleDir after checks.
  8807. * @param {String} path to file or ir
  8808. * @param {Boolean} initialAdd was the file added at watch instantiation?
  8809. * @param {Object} priorWh depth relative to user-supplied path
  8810. * @param {Number} depth Child path actually targeted for watch
  8811. * @param {String=} target Child path actually targeted for watch
  8812. * @returns {Promise}
  8813. */
  8814. async _addToNodeFs(path, initialAdd, priorWh, depth, target) {
  8815. const ready = this.fsw._emitReady;
  8816. if (this.fsw._isIgnored(path) || this.fsw.closed) {
  8817. ready();
  8818. return false;
  8819. }
  8820. const wh = this.fsw._getWatchHelpers(path, depth);
  8821. if (!wh.hasGlob && priorWh) {
  8822. wh.hasGlob = priorWh.hasGlob;
  8823. wh.globFilter = priorWh.globFilter;
  8824. wh.filterPath = (entry) => priorWh.filterPath(entry);
  8825. wh.filterDir = (entry) => priorWh.filterDir(entry);
  8826. }
  8827. try {
  8828. const stats = await statMethods[wh.statMethod](wh.watchPath);
  8829. if (this.fsw.closed) return;
  8830. if (this.fsw._isIgnored(wh.watchPath, stats)) {
  8831. ready();
  8832. return false;
  8833. }
  8834. const follow = this.fsw.options.followSymlinks && !path.includes(STAR) && !path.includes(BRACE_START);
  8835. let closer;
  8836. if (stats.isDirectory()) {
  8837. const absPath = sysPath$2.resolve(path);
  8838. const targetPath = follow ? await fsrealpath(path) : path;
  8839. if (this.fsw.closed) return;
  8840. closer = await this._handleDir(wh.watchPath, stats, initialAdd, depth, target, wh, targetPath);
  8841. if (this.fsw.closed) return;
  8842. if (absPath !== targetPath && targetPath !== void 0) this.fsw._symlinkPaths.set(absPath, targetPath);
  8843. } else if (stats.isSymbolicLink()) {
  8844. const targetPath = follow ? await fsrealpath(path) : path;
  8845. if (this.fsw.closed) return;
  8846. const parent = sysPath$2.dirname(wh.watchPath);
  8847. this.fsw._getWatchedDir(parent).add(wh.watchPath);
  8848. this.fsw._emit(EV_ADD, wh.watchPath, stats);
  8849. closer = await this._handleDir(parent, stats, initialAdd, depth, path, wh, targetPath);
  8850. if (this.fsw.closed) return;
  8851. if (targetPath !== void 0) this.fsw._symlinkPaths.set(sysPath$2.resolve(path), targetPath);
  8852. } else closer = this._handleFile(wh.watchPath, stats, initialAdd);
  8853. ready();
  8854. this.fsw._addPathCloser(path, closer);
  8855. return false;
  8856. } catch (error) {
  8857. if (this.fsw._handleError(error)) {
  8858. ready();
  8859. return path;
  8860. }
  8861. }
  8862. }
  8863. };
  8864. module.exports = NodeFsHandler;
  8865. }));
  8866. //#endregion
  8867. //#region ../../node_modules/.pnpm/chokidar@3.6.0_patch_hash=8a4f9e2b397e6034b91a0508faae3cecb97f222313faa129d7cb0eb71e9d0e84/node_modules/chokidar/lib/fsevents-handler.js
  8868. var require_fsevents_handler = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  8869. const fs$8 = __require("fs");
  8870. const sysPath$1 = __require("path");
  8871. const { promisify: promisify$2 } = __require("util");
  8872. let fsevents;
  8873. try {
  8874. fsevents = __require("fsevents");
  8875. } catch (error) {
  8876. if (process.env.CHOKIDAR_PRINT_FSEVENTS_REQUIRE_ERROR) console.error(error);
  8877. }
  8878. if (fsevents) {
  8879. const mtch = process.version.match(/v(\d+)\.(\d+)/);
  8880. if (mtch && mtch[1] && mtch[2]) {
  8881. if (Number.parseInt(mtch[1], 10) === 8 && Number.parseInt(mtch[2], 10) < 16) fsevents = void 0;
  8882. }
  8883. }
  8884. 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();
  8885. const Depth = (value) => isNaN(value) ? {} : { depth: value };
  8886. const stat = promisify$2(fs$8.stat);
  8887. const lstat = promisify$2(fs$8.lstat);
  8888. const realpath = promisify$2(fs$8.realpath);
  8889. const statMethods = {
  8890. stat,
  8891. lstat
  8892. };
  8893. /**
  8894. * @typedef {String} Path
  8895. */
  8896. /**
  8897. * @typedef {Object} FsEventsWatchContainer
  8898. * @property {Set<Function>} listeners
  8899. * @property {Function} rawEmitter
  8900. * @property {{stop: Function}} watcher
  8901. */
  8902. /**
  8903. * Object to hold per-process fsevents instances (may be shared across chokidar FSWatcher instances)
  8904. * @type {Map<Path,FsEventsWatchContainer>}
  8905. */
  8906. const FSEventsWatchers = /* @__PURE__ */ new Map();
  8907. const consolidateThreshhold = 10;
  8908. const wrongEventFlags = new Set([
  8909. 69888,
  8910. 70400,
  8911. 71424,
  8912. 72704,
  8913. 73472,
  8914. 131328,
  8915. 131840,
  8916. 262912
  8917. ]);
  8918. /**
  8919. * Instantiates the fsevents interface
  8920. * @param {Path} path path to be watched
  8921. * @param {Function} callback called when fsevents is bound and ready
  8922. * @returns {{stop: Function}} new fsevents instance
  8923. */
  8924. const createFSEventsInstance = (path, callback) => {
  8925. return { stop: fsevents.watch(path, callback) };
  8926. };
  8927. /**
  8928. * Instantiates the fsevents interface or binds listeners to an existing one covering
  8929. * the same file tree.
  8930. * @param {Path} path - to be watched
  8931. * @param {Path} realPath - real path for symlinks
  8932. * @param {Function} listener - called when fsevents emits events
  8933. * @param {Function} rawEmitter - passes data to listeners of the 'raw' event
  8934. * @returns {Function} closer
  8935. */
  8936. function setFSEventsListener(path, realPath, listener, rawEmitter) {
  8937. let watchPath = sysPath$1.extname(realPath) ? sysPath$1.dirname(realPath) : realPath;
  8938. const parentPath = sysPath$1.dirname(watchPath);
  8939. let cont = FSEventsWatchers.get(watchPath);
  8940. if (couldConsolidate(parentPath)) watchPath = parentPath;
  8941. const resolvedPath = sysPath$1.resolve(path);
  8942. const hasSymlink = resolvedPath !== realPath;
  8943. const filteredListener = (fullPath, flags, info) => {
  8944. if (hasSymlink) fullPath = fullPath.replace(realPath, resolvedPath);
  8945. if (fullPath === resolvedPath || !fullPath.indexOf(resolvedPath + sysPath$1.sep)) listener(fullPath, flags, info);
  8946. };
  8947. let watchedParent = false;
  8948. for (const watchedPath of FSEventsWatchers.keys()) if (realPath.indexOf(sysPath$1.resolve(watchedPath) + sysPath$1.sep) === 0) {
  8949. watchPath = watchedPath;
  8950. cont = FSEventsWatchers.get(watchPath);
  8951. watchedParent = true;
  8952. break;
  8953. }
  8954. if (cont || watchedParent) cont.listeners.add(filteredListener);
  8955. else {
  8956. cont = {
  8957. listeners: new Set([filteredListener]),
  8958. rawEmitter,
  8959. watcher: createFSEventsInstance(watchPath, (fullPath, flags) => {
  8960. if (!cont.listeners.size) return;
  8961. if (flags & FSEVENT_FLAG_MUST_SCAN_SUBDIRS) return;
  8962. const info = fsevents.getInfo(fullPath, flags);
  8963. cont.listeners.forEach((list) => {
  8964. list(fullPath, flags, info);
  8965. });
  8966. cont.rawEmitter(info.event, fullPath, info);
  8967. })
  8968. };
  8969. FSEventsWatchers.set(watchPath, cont);
  8970. }
  8971. return () => {
  8972. const lst = cont.listeners;
  8973. lst.delete(filteredListener);
  8974. if (!lst.size) {
  8975. FSEventsWatchers.delete(watchPath);
  8976. if (cont.watcher) return cont.watcher.stop().then(() => {
  8977. cont.rawEmitter = cont.watcher = void 0;
  8978. Object.freeze(cont);
  8979. });
  8980. }
  8981. };
  8982. }
  8983. const couldConsolidate = (path) => {
  8984. let count = 0;
  8985. for (const watchPath of FSEventsWatchers.keys()) if (watchPath.indexOf(path) === 0) {
  8986. count++;
  8987. if (count >= consolidateThreshhold) return true;
  8988. }
  8989. return false;
  8990. };
  8991. const canUse = () => fsevents && FSEventsWatchers.size < 128;
  8992. const calcDepth = (path, root) => {
  8993. let i = 0;
  8994. while (!path.indexOf(root) && (path = sysPath$1.dirname(path)) !== root) i++;
  8995. return i;
  8996. };
  8997. 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();
  8998. /**
  8999. * @mixin
  9000. */
  9001. var FsEventsHandler = class {
  9002. /**
  9003. * @param {import('../index').FSWatcher} fsw
  9004. */
  9005. constructor(fsw) {
  9006. this.fsw = fsw;
  9007. }
  9008. checkIgnored(path, stats) {
  9009. const ipaths = this.fsw._ignoredPaths;
  9010. if (this.fsw._isIgnored(path, stats)) {
  9011. ipaths.add(path);
  9012. if (stats && stats.isDirectory()) ipaths.add(path + ROOT_GLOBSTAR);
  9013. return true;
  9014. }
  9015. ipaths.delete(path);
  9016. ipaths.delete(path + ROOT_GLOBSTAR);
  9017. }
  9018. addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts) {
  9019. const event = watchedDir.has(item) ? EV_CHANGE : EV_ADD;
  9020. this.handleEvent(event, path, fullPath, realPath, parent, watchedDir, item, info, opts);
  9021. }
  9022. async checkExists(path, fullPath, realPath, parent, watchedDir, item, info, opts) {
  9023. try {
  9024. const stats = await stat(path);
  9025. if (this.fsw.closed) return;
  9026. if (sameTypes(info, stats)) this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts);
  9027. else this.handleEvent(EV_UNLINK, path, fullPath, realPath, parent, watchedDir, item, info, opts);
  9028. } catch (error) {
  9029. if (error.code === "EACCES") this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts);
  9030. else this.handleEvent(EV_UNLINK, path, fullPath, realPath, parent, watchedDir, item, info, opts);
  9031. }
  9032. }
  9033. handleEvent(event, path, fullPath, realPath, parent, watchedDir, item, info, opts) {
  9034. if (this.fsw.closed || this.checkIgnored(path)) return;
  9035. if (event === EV_UNLINK) {
  9036. const isDirectory = info.type === FSEVENT_TYPE_DIRECTORY;
  9037. if (isDirectory || watchedDir.has(item)) this.fsw._remove(parent, item, isDirectory);
  9038. } else {
  9039. if (event === EV_ADD) {
  9040. if (info.type === FSEVENT_TYPE_DIRECTORY) this.fsw._getWatchedDir(path);
  9041. if (info.type === FSEVENT_TYPE_SYMLINK && opts.followSymlinks) {
  9042. const curDepth = opts.depth === void 0 ? void 0 : calcDepth(fullPath, realPath) + 1;
  9043. return this._addToFsEvents(path, false, true, curDepth);
  9044. }
  9045. this.fsw._getWatchedDir(parent).add(item);
  9046. }
  9047. /**
  9048. * @type {'add'|'addDir'|'unlink'|'unlinkDir'}
  9049. */
  9050. const eventName = info.type === FSEVENT_TYPE_DIRECTORY ? event + DIR_SUFFIX : event;
  9051. this.fsw._emit(eventName, path);
  9052. if (eventName === EV_ADD_DIR) this._addToFsEvents(path, false, true);
  9053. }
  9054. }
  9055. /**
  9056. * Handle symlinks encountered during directory scan
  9057. * @param {String} watchPath - file/dir path to be watched with fsevents
  9058. * @param {String} realPath - real path (in case of symlinks)
  9059. * @param {Function} transform - path transformer
  9060. * @param {Function} globFilter - path filter in case a glob pattern was provided
  9061. * @returns {Function} closer for the watcher instance
  9062. */
  9063. _watchWithFsEvents(watchPath, realPath, transform, globFilter) {
  9064. if (this.fsw.closed || this.fsw._isIgnored(watchPath)) return;
  9065. const opts = this.fsw.options;
  9066. const watchCallback = async (fullPath, flags, info) => {
  9067. if (this.fsw.closed || this.fsw._isIgnored(fullPath)) return;
  9068. if (opts.depth !== void 0 && calcDepth(fullPath, realPath) > opts.depth) return;
  9069. const path = transform(sysPath$1.join(watchPath, sysPath$1.relative(watchPath, fullPath)));
  9070. if (globFilter && !globFilter(path)) return;
  9071. const parent = sysPath$1.dirname(path);
  9072. const item = sysPath$1.basename(path);
  9073. const watchedDir = this.fsw._getWatchedDir(info.type === FSEVENT_TYPE_DIRECTORY ? path : parent);
  9074. if (wrongEventFlags.has(flags) || info.event === FSEVENT_UNKNOWN) if (typeof opts.ignored === FUNCTION_TYPE) {
  9075. let stats;
  9076. try {
  9077. stats = await stat(path);
  9078. } catch (error) {}
  9079. if (this.fsw.closed) return;
  9080. if (this.checkIgnored(path, stats)) return;
  9081. if (sameTypes(info, stats)) this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts);
  9082. else this.handleEvent(EV_UNLINK, path, fullPath, realPath, parent, watchedDir, item, info, opts);
  9083. } else this.checkExists(path, fullPath, realPath, parent, watchedDir, item, info, opts);
  9084. else switch (info.event) {
  9085. case FSEVENT_CREATED:
  9086. case FSEVENT_MODIFIED: return this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts);
  9087. case FSEVENT_DELETED:
  9088. case FSEVENT_MOVED: return this.checkExists(path, fullPath, realPath, parent, watchedDir, item, info, opts);
  9089. }
  9090. };
  9091. const closer = setFSEventsListener(watchPath, realPath, watchCallback, this.fsw._emitRaw);
  9092. this.fsw._emitReady();
  9093. return closer;
  9094. }
  9095. /**
  9096. * Handle symlinks encountered during directory scan
  9097. * @param {String} linkPath path to symlink
  9098. * @param {String} fullPath absolute path to the symlink
  9099. * @param {Function} transform pre-existing path transformer
  9100. * @param {Number} curDepth level of subdirectories traversed to where symlink is
  9101. * @returns {Promise<void>}
  9102. */
  9103. async _handleFsEventsSymlink(linkPath, fullPath, transform, curDepth) {
  9104. if (this.fsw.closed || this.fsw._symlinkPaths.has(fullPath)) return;
  9105. this.fsw._symlinkPaths.set(fullPath, true);
  9106. this.fsw._incrReadyCount();
  9107. try {
  9108. const linkTarget = await realpath(linkPath);
  9109. if (this.fsw.closed) return;
  9110. if (this.fsw._isIgnored(linkTarget)) return this.fsw._emitReady();
  9111. this.fsw._incrReadyCount();
  9112. this._addToFsEvents(linkTarget || linkPath, (path) => {
  9113. let aliasedPath = linkPath;
  9114. if (linkTarget && linkTarget !== DOT_SLASH) aliasedPath = path.replace(linkTarget, linkPath);
  9115. else if (path !== DOT_SLASH) aliasedPath = sysPath$1.join(linkPath, path);
  9116. return transform(aliasedPath);
  9117. }, false, curDepth);
  9118. } catch (error) {
  9119. if (this.fsw._handleError(error)) return this.fsw._emitReady();
  9120. }
  9121. }
  9122. /**
  9123. *
  9124. * @param {Path} newPath
  9125. * @param {fs.Stats} stats
  9126. */
  9127. emitAdd(newPath, stats, processPath, opts, forceAdd) {
  9128. const pp = processPath(newPath);
  9129. const isDir = stats.isDirectory();
  9130. const dirObj = this.fsw._getWatchedDir(sysPath$1.dirname(pp));
  9131. const base = sysPath$1.basename(pp);
  9132. if (isDir) this.fsw._getWatchedDir(pp);
  9133. if (dirObj.has(base)) return;
  9134. dirObj.add(base);
  9135. if (!opts.ignoreInitial || forceAdd === true) this.fsw._emit(isDir ? EV_ADD_DIR : EV_ADD, pp, stats);
  9136. }
  9137. initWatch(realPath, path, wh, processPath) {
  9138. if (this.fsw.closed) return;
  9139. const closer = this._watchWithFsEvents(wh.watchPath, sysPath$1.resolve(realPath || wh.watchPath), processPath, wh.globFilter);
  9140. this.fsw._addPathCloser(path, closer);
  9141. }
  9142. /**
  9143. * Handle added path with fsevents
  9144. * @param {String} path file/dir path or glob pattern
  9145. * @param {Function|Boolean=} transform converts working path to what the user expects
  9146. * @param {Boolean=} forceAdd ensure add is emitted
  9147. * @param {Number=} priorDepth Level of subdirectories already traversed.
  9148. * @returns {Promise<void>}
  9149. */
  9150. async _addToFsEvents(path, transform, forceAdd, priorDepth) {
  9151. if (this.fsw.closed) return;
  9152. const opts = this.fsw.options;
  9153. const processPath = typeof transform === FUNCTION_TYPE ? transform : IDENTITY_FN;
  9154. const wh = this.fsw._getWatchHelpers(path);
  9155. try {
  9156. const stats = await statMethods[wh.statMethod](wh.watchPath);
  9157. if (this.fsw.closed) return;
  9158. if (this.fsw._isIgnored(wh.watchPath, stats)) throw null;
  9159. if (stats.isDirectory()) {
  9160. if (!wh.globFilter) this.emitAdd(processPath(path), stats, processPath, opts, forceAdd);
  9161. if (priorDepth && priorDepth > opts.depth) return;
  9162. this.fsw._readdirp(wh.watchPath, {
  9163. fileFilter: (entry) => wh.filterPath(entry),
  9164. directoryFilter: (entry) => wh.filterDir(entry),
  9165. ...Depth(opts.depth - (priorDepth || 0))
  9166. }).on(STR_DATA, (entry) => {
  9167. if (this.fsw.closed) return;
  9168. if (entry.stats.isDirectory() && !wh.filterPath(entry)) return;
  9169. const joinedPath = sysPath$1.join(wh.watchPath, entry.path);
  9170. const { fullPath } = entry;
  9171. if (wh.followSymlinks && entry.stats.isSymbolicLink()) {
  9172. const curDepth = opts.depth === void 0 ? void 0 : calcDepth(joinedPath, sysPath$1.resolve(wh.watchPath)) + 1;
  9173. this._handleFsEventsSymlink(joinedPath, fullPath, processPath, curDepth);
  9174. } else this.emitAdd(joinedPath, entry.stats, processPath, opts, forceAdd);
  9175. }).on(EV_ERROR, EMPTY_FN).on(STR_END, () => {
  9176. this.fsw._emitReady();
  9177. });
  9178. } else {
  9179. this.emitAdd(wh.watchPath, stats, processPath, opts, forceAdd);
  9180. this.fsw._emitReady();
  9181. }
  9182. } catch (error) {
  9183. if (!error || this.fsw._handleError(error)) {
  9184. this.fsw._emitReady();
  9185. this.fsw._emitReady();
  9186. }
  9187. }
  9188. if (opts.persistent && forceAdd !== true) if (typeof transform === FUNCTION_TYPE) this.initWatch(void 0, path, wh, processPath);
  9189. else {
  9190. let realPath;
  9191. try {
  9192. realPath = await realpath(wh.watchPath);
  9193. } catch (e) {}
  9194. this.initWatch(realPath, path, wh, processPath);
  9195. }
  9196. }
  9197. };
  9198. module.exports = FsEventsHandler;
  9199. module.exports.canUse = canUse;
  9200. }));
  9201. //#endregion
  9202. //#region ../../node_modules/.pnpm/chokidar@3.6.0_patch_hash=8a4f9e2b397e6034b91a0508faae3cecb97f222313faa129d7cb0eb71e9d0e84/node_modules/chokidar/index.js
  9203. var require_chokidar = /* @__PURE__ */ __commonJSMin(((exports) => {
  9204. const { EventEmitter: EventEmitter$3 } = __require("events");
  9205. const fs$7 = __require("fs");
  9206. const sysPath = __require("path");
  9207. const { promisify: promisify$1 } = __require("util");
  9208. const readdirp = require_readdirp();
  9209. const anymatch = require_anymatch().default;
  9210. const globParent = require_glob_parent();
  9211. const isGlob = require_is_glob();
  9212. const braces = require_braces();
  9213. const normalizePath = require_normalize_path();
  9214. const NodeFsHandler = require_nodefs_handler();
  9215. const FsEventsHandler = require_fsevents_handler();
  9216. 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();
  9217. const stat = promisify$1(fs$7.stat);
  9218. const readdir = promisify$1(fs$7.readdir);
  9219. /**
  9220. * @typedef {String} Path
  9221. * @typedef {'all'|'add'|'addDir'|'change'|'unlink'|'unlinkDir'|'raw'|'error'|'ready'} EventName
  9222. * @typedef {'readdir'|'watch'|'add'|'remove'|'change'} ThrottleType
  9223. */
  9224. /**
  9225. *
  9226. * @typedef {Object} WatchHelpers
  9227. * @property {Boolean} followSymlinks
  9228. * @property {'stat'|'lstat'} statMethod
  9229. * @property {Path} path
  9230. * @property {Path} watchPath
  9231. * @property {Function} entryPath
  9232. * @property {Boolean} hasGlob
  9233. * @property {Object} globFilter
  9234. * @property {Function} filterPath
  9235. * @property {Function} filterDir
  9236. */
  9237. const arrify = (value = []) => Array.isArray(value) ? value : [value];
  9238. const flatten = (list, result = []) => {
  9239. list.forEach((item) => {
  9240. if (Array.isArray(item)) flatten(item, result);
  9241. else result.push(item);
  9242. });
  9243. return result;
  9244. };
  9245. const unifyPaths = (paths_) => {
  9246. /**
  9247. * @type {Array<String>}
  9248. */
  9249. const paths = flatten(arrify(paths_));
  9250. if (!paths.every((p) => typeof p === STRING_TYPE)) throw new TypeError(`Non-string provided as watch path: ${paths}`);
  9251. return paths.map(normalizePathToUnix);
  9252. };
  9253. const toUnix = (string) => {
  9254. let str = string.replace(BACK_SLASH_RE, SLASH);
  9255. let prepend = false;
  9256. if (str.startsWith(SLASH_SLASH)) prepend = true;
  9257. while (str.match(DOUBLE_SLASH_RE)) str = str.replace(DOUBLE_SLASH_RE, SLASH);
  9258. if (prepend) str = SLASH + str;
  9259. return str;
  9260. };
  9261. const normalizePathToUnix = (path) => toUnix(sysPath.normalize(toUnix(path)));
  9262. const normalizeIgnored = (cwd = EMPTY_STR) => (path) => {
  9263. if (typeof path !== STRING_TYPE) return path;
  9264. return normalizePathToUnix(sysPath.isAbsolute(path) ? path : sysPath.join(cwd, path));
  9265. };
  9266. const getAbsolutePath = (path, cwd) => {
  9267. if (sysPath.isAbsolute(path)) return path;
  9268. if (path.startsWith(BANG)) return BANG + sysPath.join(cwd, path.slice(1));
  9269. return sysPath.join(cwd, path);
  9270. };
  9271. const undef = (opts, key) => opts[key] === void 0;
  9272. /**
  9273. * Directory entry.
  9274. * @property {Path} path
  9275. * @property {Set<Path>} items
  9276. */
  9277. var DirEntry = class {
  9278. /**
  9279. * @param {Path} dir
  9280. * @param {Function} removeWatcher
  9281. */
  9282. constructor(dir, removeWatcher) {
  9283. this.path = dir;
  9284. this._removeWatcher = removeWatcher;
  9285. /** @type {Set<Path>} */
  9286. this.items = /* @__PURE__ */ new Set();
  9287. }
  9288. add(item) {
  9289. const { items } = this;
  9290. if (!items) return;
  9291. if (item !== ONE_DOT && item !== TWO_DOTS) items.add(item);
  9292. }
  9293. async remove(item) {
  9294. const { items } = this;
  9295. if (!items) return;
  9296. items.delete(item);
  9297. if (items.size > 0) return;
  9298. const dir = this.path;
  9299. try {
  9300. await readdir(dir);
  9301. } catch (err) {
  9302. if (this._removeWatcher) this._removeWatcher(sysPath.dirname(dir), sysPath.basename(dir));
  9303. }
  9304. }
  9305. has(item) {
  9306. const { items } = this;
  9307. if (!items) return;
  9308. return items.has(item);
  9309. }
  9310. /**
  9311. * @returns {Array<String>}
  9312. */
  9313. getChildren() {
  9314. const { items } = this;
  9315. if (!items) return;
  9316. return [...items.values()];
  9317. }
  9318. dispose() {
  9319. this.items.clear();
  9320. delete this.path;
  9321. delete this._removeWatcher;
  9322. delete this.items;
  9323. Object.freeze(this);
  9324. }
  9325. };
  9326. const STAT_METHOD_F = "stat";
  9327. const STAT_METHOD_L = "lstat";
  9328. var WatchHelper = class {
  9329. constructor(path, watchPath, follow, fsw) {
  9330. this.fsw = fsw;
  9331. this.path = path = path.replace(REPLACER_RE, EMPTY_STR);
  9332. this.watchPath = watchPath;
  9333. this.fullWatchPath = sysPath.resolve(watchPath);
  9334. this.hasGlob = watchPath !== path;
  9335. /** @type {object|boolean} */
  9336. if (path === EMPTY_STR) this.hasGlob = false;
  9337. this.globSymlink = this.hasGlob && follow ? void 0 : false;
  9338. this.globFilter = this.hasGlob ? anymatch(path, void 0, ANYMATCH_OPTS) : false;
  9339. this.dirParts = this.getDirParts(path);
  9340. this.dirParts.forEach((parts) => {
  9341. if (parts.length > 1) parts.pop();
  9342. });
  9343. this.followSymlinks = follow;
  9344. this.statMethod = follow ? STAT_METHOD_F : STAT_METHOD_L;
  9345. }
  9346. checkGlobSymlink(entry) {
  9347. if (this.globSymlink === void 0) this.globSymlink = entry.fullParentDir === this.fullWatchPath ? false : {
  9348. realPath: entry.fullParentDir,
  9349. linkPath: this.fullWatchPath
  9350. };
  9351. if (this.globSymlink) return entry.fullPath.replace(this.globSymlink.realPath, this.globSymlink.linkPath);
  9352. return entry.fullPath;
  9353. }
  9354. entryPath(entry) {
  9355. return sysPath.join(this.watchPath, sysPath.relative(this.watchPath, this.checkGlobSymlink(entry)));
  9356. }
  9357. filterPath(entry) {
  9358. const { stats } = entry;
  9359. if (stats && stats.isSymbolicLink()) return this.filterDir(entry);
  9360. const resolvedPath = this.entryPath(entry);
  9361. return (this.hasGlob && typeof this.globFilter === FUNCTION_TYPE ? this.globFilter(resolvedPath) : true) && this.fsw._isntIgnored(resolvedPath, stats) && this.fsw._hasReadPermissions(stats);
  9362. }
  9363. getDirParts(path) {
  9364. if (!this.hasGlob) return [];
  9365. const parts = [];
  9366. (path.includes(BRACE_START) ? braces.expand(path) : [path]).forEach((path) => {
  9367. parts.push(sysPath.relative(this.watchPath, path).split(SLASH_OR_BACK_SLASH_RE));
  9368. });
  9369. return parts;
  9370. }
  9371. filterDir(entry) {
  9372. if (this.hasGlob) {
  9373. const entryParts = this.getDirParts(this.checkGlobSymlink(entry));
  9374. let globstar = false;
  9375. this.unmatchedGlob = !this.dirParts.some((parts) => {
  9376. return parts.every((part, i) => {
  9377. if (part === GLOBSTAR) globstar = true;
  9378. return globstar || !entryParts[0][i] || anymatch(part, entryParts[0][i], ANYMATCH_OPTS);
  9379. });
  9380. });
  9381. }
  9382. return !this.unmatchedGlob && this.fsw._isntIgnored(this.entryPath(entry), entry.stats);
  9383. }
  9384. };
  9385. /**
  9386. * Watches files & directories for changes. Emitted events:
  9387. * `add`, `addDir`, `change`, `unlink`, `unlinkDir`, `all`, `error`
  9388. *
  9389. * new FSWatcher()
  9390. * .add(directories)
  9391. * .on('add', path => log('File', path, 'was added'))
  9392. */
  9393. var FSWatcher = class extends EventEmitter$3 {
  9394. constructor(_opts) {
  9395. super();
  9396. const opts = {};
  9397. if (_opts) Object.assign(opts, _opts);
  9398. /** @type {Map<String, DirEntry>} */
  9399. this._watched = /* @__PURE__ */ new Map();
  9400. /** @type {Map<String, Array>} */
  9401. this._closers = /* @__PURE__ */ new Map();
  9402. /** @type {Set<String>} */
  9403. this._ignoredPaths = /* @__PURE__ */ new Set();
  9404. /** @type {Map<ThrottleType, Map>} */
  9405. this._throttled = /* @__PURE__ */ new Map();
  9406. /** @type {Map<Path, String|Boolean>} */
  9407. this._symlinkPaths = /* @__PURE__ */ new Map();
  9408. this._streams = /* @__PURE__ */ new Set();
  9409. this.closed = false;
  9410. if (undef(opts, "persistent")) opts.persistent = true;
  9411. if (undef(opts, "ignoreInitial")) opts.ignoreInitial = false;
  9412. if (undef(opts, "ignorePermissionErrors")) opts.ignorePermissionErrors = false;
  9413. if (undef(opts, "interval")) opts.interval = 100;
  9414. if (undef(opts, "binaryInterval")) opts.binaryInterval = 300;
  9415. if (undef(opts, "disableGlobbing")) opts.disableGlobbing = false;
  9416. opts.enableBinaryInterval = opts.binaryInterval !== opts.interval;
  9417. if (undef(opts, "useFsEvents")) opts.useFsEvents = !opts.usePolling;
  9418. if (!FsEventsHandler.canUse()) opts.useFsEvents = false;
  9419. if (undef(opts, "usePolling") && !opts.useFsEvents) opts.usePolling = isMacos;
  9420. if (isIBMi) opts.usePolling = true;
  9421. const envPoll = process.env.CHOKIDAR_USEPOLLING;
  9422. if (envPoll !== void 0) {
  9423. const envLower = envPoll.toLowerCase();
  9424. if (envLower === "false" || envLower === "0") opts.usePolling = false;
  9425. else if (envLower === "true" || envLower === "1") opts.usePolling = true;
  9426. else opts.usePolling = !!envLower;
  9427. }
  9428. const envInterval = process.env.CHOKIDAR_INTERVAL;
  9429. if (envInterval) opts.interval = Number.parseInt(envInterval, 10);
  9430. if (undef(opts, "atomic")) opts.atomic = !opts.usePolling && !opts.useFsEvents;
  9431. if (opts.atomic) this._pendingUnlinks = /* @__PURE__ */ new Map();
  9432. if (undef(opts, "followSymlinks")) opts.followSymlinks = true;
  9433. if (undef(opts, "awaitWriteFinish")) opts.awaitWriteFinish = false;
  9434. if (opts.awaitWriteFinish === true) opts.awaitWriteFinish = {};
  9435. const awf = opts.awaitWriteFinish;
  9436. if (awf) {
  9437. if (!awf.stabilityThreshold) awf.stabilityThreshold = 2e3;
  9438. if (!awf.pollInterval) awf.pollInterval = 100;
  9439. this._pendingWrites = /* @__PURE__ */ new Map();
  9440. }
  9441. if (opts.ignored) opts.ignored = arrify(opts.ignored);
  9442. let readyCalls = 0;
  9443. this._emitReady = () => {
  9444. readyCalls++;
  9445. if (readyCalls >= this._readyCount) {
  9446. this._emitReady = EMPTY_FN;
  9447. this._readyEmitted = true;
  9448. process.nextTick(() => this.emit(EV_READY));
  9449. }
  9450. };
  9451. this._emitRaw = (...args) => this.emit(EV_RAW, ...args);
  9452. this._readyEmitted = false;
  9453. this.options = opts;
  9454. if (opts.useFsEvents) this._fsEventsHandler = new FsEventsHandler(this);
  9455. else this._nodeFsHandler = new NodeFsHandler(this);
  9456. Object.freeze(opts);
  9457. }
  9458. /**
  9459. * Adds paths to be watched on an existing FSWatcher instance
  9460. * @param {Path|Array<Path>} paths_
  9461. * @param {String=} _origAdd private; for handling non-existent paths to be watched
  9462. * @param {Boolean=} _internal private; indicates a non-user add
  9463. * @returns {FSWatcher} for chaining
  9464. */
  9465. add(paths_, _origAdd, _internal) {
  9466. const { cwd, disableGlobbing } = this.options;
  9467. this.closed = false;
  9468. let paths = unifyPaths(paths_);
  9469. if (cwd) paths = paths.map((path) => {
  9470. const absPath = getAbsolutePath(path, cwd);
  9471. if (disableGlobbing || !isGlob(path)) return absPath;
  9472. return normalizePath(absPath);
  9473. });
  9474. paths = paths.filter((path) => {
  9475. if (path.startsWith(BANG)) {
  9476. this._ignoredPaths.add(path.slice(1));
  9477. return false;
  9478. }
  9479. this._ignoredPaths.delete(path);
  9480. this._ignoredPaths.delete(path + SLASH_GLOBSTAR);
  9481. this._userIgnored = void 0;
  9482. return true;
  9483. });
  9484. if (this.options.useFsEvents && this._fsEventsHandler) {
  9485. if (!this._readyCount) this._readyCount = paths.length;
  9486. if (this.options.persistent) this._readyCount += paths.length;
  9487. paths.forEach((path) => this._fsEventsHandler._addToFsEvents(path));
  9488. } else {
  9489. if (!this._readyCount) this._readyCount = 0;
  9490. this._readyCount += paths.length;
  9491. Promise.all(paths.map(async (path) => {
  9492. const res = await this._nodeFsHandler._addToNodeFs(path, !_internal, 0, 0, _origAdd);
  9493. if (res) this._emitReady();
  9494. return res;
  9495. })).then((results) => {
  9496. if (this.closed) return;
  9497. results.filter((item) => item).forEach((item) => {
  9498. this.add(sysPath.dirname(item), sysPath.basename(_origAdd || item));
  9499. });
  9500. });
  9501. }
  9502. return this;
  9503. }
  9504. /**
  9505. * Close watchers or start ignoring events from specified paths.
  9506. * @param {Path|Array<Path>} paths_ - string or array of strings, file/directory paths and/or globs
  9507. * @returns {FSWatcher} for chaining
  9508. */
  9509. unwatch(paths_) {
  9510. if (this.closed) return this;
  9511. const paths = unifyPaths(paths_);
  9512. const { cwd } = this.options;
  9513. paths.forEach((path) => {
  9514. if (!sysPath.isAbsolute(path) && !this._closers.has(path)) {
  9515. if (cwd) path = sysPath.join(cwd, path);
  9516. path = sysPath.resolve(path);
  9517. }
  9518. this._closePath(path);
  9519. this._ignoredPaths.add(path);
  9520. if (this._watched.has(path)) this._ignoredPaths.add(path + SLASH_GLOBSTAR);
  9521. this._userIgnored = void 0;
  9522. });
  9523. return this;
  9524. }
  9525. /**
  9526. * Close watchers and remove all listeners from watched paths.
  9527. * @returns {Promise<void>}.
  9528. */
  9529. close() {
  9530. if (this.closed) return this._closePromise;
  9531. this.closed = true;
  9532. this.removeAllListeners();
  9533. const closers = [];
  9534. this._closers.forEach((closerList) => closerList.forEach((closer) => {
  9535. const promise = closer();
  9536. if (promise instanceof Promise) closers.push(promise);
  9537. }));
  9538. this._streams.forEach((stream) => stream.destroy());
  9539. this._userIgnored = void 0;
  9540. this._readyCount = 0;
  9541. this._readyEmitted = false;
  9542. this._watched.forEach((dirent) => dirent.dispose());
  9543. [
  9544. "closers",
  9545. "watched",
  9546. "streams",
  9547. "symlinkPaths",
  9548. "throttled"
  9549. ].forEach((key) => {
  9550. this[`_${key}`].clear();
  9551. });
  9552. this._closePromise = closers.length ? Promise.all(closers).then(() => void 0) : Promise.resolve();
  9553. return this._closePromise;
  9554. }
  9555. /**
  9556. * Expose list of watched paths
  9557. * @returns {Object} for chaining
  9558. */
  9559. getWatched() {
  9560. const watchList = {};
  9561. this._watched.forEach((entry, dir) => {
  9562. const key = this.options.cwd ? sysPath.relative(this.options.cwd, dir) : dir;
  9563. watchList[key || ONE_DOT] = entry.getChildren().sort();
  9564. });
  9565. return watchList;
  9566. }
  9567. emitWithAll(event, args) {
  9568. this.emit(...args);
  9569. if (event !== EV_ERROR) this.emit(EV_ALL, ...args);
  9570. }
  9571. /**
  9572. * Normalize and emit events.
  9573. * Calling _emit DOES NOT MEAN emit() would be called!
  9574. * @param {EventName} event Type of event
  9575. * @param {Path} path File or directory path
  9576. * @param {*=} val1 arguments to be passed with event
  9577. * @param {*=} val2
  9578. * @param {*=} val3
  9579. * @returns the error if defined, otherwise the value of the FSWatcher instance's `closed` flag
  9580. */
  9581. async _emit(event, path, val1, val2, val3) {
  9582. if (this.closed) return;
  9583. const opts = this.options;
  9584. if (isWindows) path = sysPath.normalize(path);
  9585. if (opts.cwd) path = sysPath.relative(opts.cwd, path);
  9586. /** @type Array<any> */
  9587. const args = [event, path];
  9588. if (val3 !== void 0) args.push(val1, val2, val3);
  9589. else if (val2 !== void 0) args.push(val1, val2);
  9590. else if (val1 !== void 0) args.push(val1);
  9591. const awf = opts.awaitWriteFinish;
  9592. let pw;
  9593. if (awf && (pw = this._pendingWrites.get(path))) {
  9594. pw.lastChange = /* @__PURE__ */ new Date();
  9595. return this;
  9596. }
  9597. if (opts.atomic) {
  9598. if (event === EV_UNLINK) {
  9599. this._pendingUnlinks.set(path, args);
  9600. setTimeout(() => {
  9601. this._pendingUnlinks.forEach((entry, path) => {
  9602. this.emit(...entry);
  9603. this.emit(EV_ALL, ...entry);
  9604. this._pendingUnlinks.delete(path);
  9605. });
  9606. }, typeof opts.atomic === "number" ? opts.atomic : 100);
  9607. return this;
  9608. }
  9609. if (event === EV_ADD && this._pendingUnlinks.has(path)) {
  9610. event = args[0] = EV_CHANGE;
  9611. this._pendingUnlinks.delete(path);
  9612. }
  9613. }
  9614. if (awf && (event === EV_ADD || event === EV_CHANGE) && this._readyEmitted) {
  9615. const awfEmit = (err, stats) => {
  9616. if (err) {
  9617. event = args[0] = EV_ERROR;
  9618. args[1] = err;
  9619. this.emitWithAll(event, args);
  9620. } else if (stats) {
  9621. if (args.length > 2) args[2] = stats;
  9622. else args.push(stats);
  9623. this.emitWithAll(event, args);
  9624. }
  9625. };
  9626. this._awaitWriteFinish(path, awf.stabilityThreshold, event, awfEmit);
  9627. return this;
  9628. }
  9629. if (event === EV_CHANGE) {
  9630. if (!this._throttle(EV_CHANGE, path, 50)) return this;
  9631. }
  9632. if (opts.alwaysStat && val1 === void 0 && (event === EV_ADD || event === EV_ADD_DIR || event === EV_CHANGE)) {
  9633. const fullPath = opts.cwd ? sysPath.join(opts.cwd, path) : path;
  9634. let stats;
  9635. try {
  9636. stats = await stat(fullPath);
  9637. } catch (err) {}
  9638. if (!stats || this.closed) return;
  9639. args.push(stats);
  9640. }
  9641. this.emitWithAll(event, args);
  9642. return this;
  9643. }
  9644. /**
  9645. * Common handler for errors
  9646. * @param {Error} error
  9647. * @returns {Error|Boolean} The error if defined, otherwise the value of the FSWatcher instance's `closed` flag
  9648. */
  9649. _handleError(error) {
  9650. const code = error && error.code;
  9651. if (error && code !== "ENOENT" && code !== "ENOTDIR" && (!this.options.ignorePermissionErrors || code !== "EPERM" && code !== "EACCES")) this.emit(EV_ERROR, error);
  9652. return error || this.closed;
  9653. }
  9654. /**
  9655. * Helper utility for throttling
  9656. * @param {ThrottleType} actionType type being throttled
  9657. * @param {Path} path being acted upon
  9658. * @param {Number} timeout duration of time to suppress duplicate actions
  9659. * @returns {Object|false} tracking object or false if action should be suppressed
  9660. */
  9661. _throttle(actionType, path, timeout) {
  9662. if (!this._throttled.has(actionType)) this._throttled.set(actionType, /* @__PURE__ */ new Map());
  9663. /** @type {Map<Path, Object>} */
  9664. const action = this._throttled.get(actionType);
  9665. /** @type {Object} */
  9666. const actionPath = action.get(path);
  9667. if (actionPath) {
  9668. actionPath.count++;
  9669. return false;
  9670. }
  9671. let timeoutObject;
  9672. const clear = () => {
  9673. const item = action.get(path);
  9674. const count = item ? item.count : 0;
  9675. action.delete(path);
  9676. clearTimeout(timeoutObject);
  9677. if (item) clearTimeout(item.timeoutObject);
  9678. return count;
  9679. };
  9680. timeoutObject = setTimeout(clear, timeout);
  9681. const thr = {
  9682. timeoutObject,
  9683. clear,
  9684. count: 0
  9685. };
  9686. action.set(path, thr);
  9687. return thr;
  9688. }
  9689. _incrReadyCount() {
  9690. return this._readyCount++;
  9691. }
  9692. /**
  9693. * Awaits write operation to finish.
  9694. * Polls a newly created file for size variations. When files size does not change for 'threshold' milliseconds calls callback.
  9695. * @param {Path} path being acted upon
  9696. * @param {Number} threshold Time in milliseconds a file size must be fixed before acknowledging write OP is finished
  9697. * @param {EventName} event
  9698. * @param {Function} awfEmit Callback to be called when ready for event to be emitted.
  9699. */
  9700. _awaitWriteFinish(path, threshold, event, awfEmit) {
  9701. let timeoutHandler;
  9702. let fullPath = path;
  9703. if (this.options.cwd && !sysPath.isAbsolute(path)) fullPath = sysPath.join(this.options.cwd, path);
  9704. const now = /* @__PURE__ */ new Date();
  9705. const awaitWriteFinish = (prevStat) => {
  9706. fs$7.stat(fullPath, (err, curStat) => {
  9707. if (err || !this._pendingWrites.has(path)) {
  9708. if (err && err.code !== "ENOENT") awfEmit(err);
  9709. return;
  9710. }
  9711. const now = Number(/* @__PURE__ */ new Date());
  9712. if (prevStat && curStat.size !== prevStat.size) this._pendingWrites.get(path).lastChange = now;
  9713. if (now - this._pendingWrites.get(path).lastChange >= threshold) {
  9714. this._pendingWrites.delete(path);
  9715. awfEmit(void 0, curStat);
  9716. } else timeoutHandler = setTimeout(awaitWriteFinish, this.options.awaitWriteFinish.pollInterval, curStat);
  9717. });
  9718. };
  9719. if (!this._pendingWrites.has(path)) {
  9720. this._pendingWrites.set(path, {
  9721. lastChange: now,
  9722. cancelWait: () => {
  9723. this._pendingWrites.delete(path);
  9724. clearTimeout(timeoutHandler);
  9725. return event;
  9726. }
  9727. });
  9728. timeoutHandler = setTimeout(awaitWriteFinish, this.options.awaitWriteFinish.pollInterval);
  9729. }
  9730. }
  9731. _getGlobIgnored() {
  9732. return [...this._ignoredPaths.values()];
  9733. }
  9734. /**
  9735. * Determines whether user has asked to ignore this path.
  9736. * @param {Path} path filepath or dir
  9737. * @param {fs.Stats=} stats result of fs.stat
  9738. * @returns {Boolean}
  9739. */
  9740. _isIgnored(path, stats) {
  9741. if (this.options.atomic && DOT_RE.test(path)) return true;
  9742. if (!this._userIgnored) {
  9743. const { cwd } = this.options;
  9744. const ign = this.options.ignored;
  9745. const ignored = ign && ign.map(normalizeIgnored(cwd));
  9746. const paths = arrify(ignored).filter((path) => typeof path === STRING_TYPE && !isGlob(path)).map((path) => path + SLASH_GLOBSTAR);
  9747. this._userIgnored = anymatch(this._getGlobIgnored().map(normalizeIgnored(cwd)).concat(ignored, paths), void 0, ANYMATCH_OPTS);
  9748. }
  9749. return this._userIgnored([path, stats]);
  9750. }
  9751. _isntIgnored(path, stat) {
  9752. return !this._isIgnored(path, stat);
  9753. }
  9754. /**
  9755. * Provides a set of common helpers and properties relating to symlink and glob handling.
  9756. * @param {Path} path file, directory, or glob pattern being watched
  9757. * @param {Number=} depth at any depth > 0, this isn't a glob
  9758. * @returns {WatchHelper} object containing helpers for this path
  9759. */
  9760. _getWatchHelpers(path, depth) {
  9761. const watchPath = depth || this.options.disableGlobbing || !isGlob(path) ? path : globParent(path);
  9762. const follow = this.options.followSymlinks;
  9763. return new WatchHelper(path, watchPath, follow, this);
  9764. }
  9765. /**
  9766. * Provides directory tracking objects
  9767. * @param {String} directory path of the directory
  9768. * @returns {DirEntry} the directory's tracking object
  9769. */
  9770. _getWatchedDir(directory) {
  9771. if (!this._boundRemove) this._boundRemove = this._remove.bind(this);
  9772. const dir = sysPath.resolve(directory);
  9773. if (!this._watched.has(dir)) this._watched.set(dir, new DirEntry(dir, this._boundRemove));
  9774. return this._watched.get(dir);
  9775. }
  9776. /**
  9777. * Check for read permissions.
  9778. * Based on this answer on SO: https://stackoverflow.com/a/11781404/1358405
  9779. * @param {fs.Stats} stats - object, result of fs_stat
  9780. * @returns {Boolean} indicates whether the file can be read
  9781. */
  9782. _hasReadPermissions(stats) {
  9783. if (this.options.ignorePermissionErrors) return true;
  9784. const st = (stats && Number.parseInt(stats.mode, 10)) & 511;
  9785. const it = Number.parseInt(st.toString(8)[0], 10);
  9786. return Boolean(4 & it);
  9787. }
  9788. /**
  9789. * Handles emitting unlink events for
  9790. * files and directories, and via recursion, for
  9791. * files and directories within directories that are unlinked
  9792. * @param {String} directory within which the following item is located
  9793. * @param {String} item base path of item/directory
  9794. * @returns {void}
  9795. */
  9796. _remove(directory, item, isDirectory) {
  9797. const path = sysPath.join(directory, item);
  9798. const fullPath = sysPath.resolve(path);
  9799. isDirectory = isDirectory != null ? isDirectory : this._watched.has(path) || this._watched.has(fullPath);
  9800. if (!this._throttle("remove", path, 100)) return;
  9801. if (!isDirectory && !this.options.useFsEvents && this._watched.size === 1) this.add(directory, item, true);
  9802. this._getWatchedDir(path).getChildren().forEach((nested) => this._remove(path, nested));
  9803. const parent = this._getWatchedDir(directory);
  9804. const wasTracked = parent.has(item);
  9805. parent.remove(item);
  9806. if (this._symlinkPaths.has(fullPath)) this._symlinkPaths.delete(fullPath);
  9807. let relPath = path;
  9808. if (this.options.cwd) relPath = sysPath.relative(this.options.cwd, path);
  9809. if (this.options.awaitWriteFinish && this._pendingWrites.has(relPath)) {
  9810. if (this._pendingWrites.get(relPath).cancelWait() === EV_ADD) return;
  9811. }
  9812. this._watched.delete(path);
  9813. this._watched.delete(fullPath);
  9814. const eventName = isDirectory ? EV_UNLINK_DIR : EV_UNLINK;
  9815. if (wasTracked && !this._isIgnored(path)) this._emit(eventName, path);
  9816. if (!this.options.useFsEvents) this._closePath(path);
  9817. }
  9818. /**
  9819. * Closes all watchers for a path
  9820. * @param {Path} path
  9821. */
  9822. _closePath(path) {
  9823. this._closeFile(path);
  9824. const dir = sysPath.dirname(path);
  9825. this._getWatchedDir(dir).remove(sysPath.basename(path));
  9826. }
  9827. /**
  9828. * Closes only file-specific watchers
  9829. * @param {Path} path
  9830. */
  9831. _closeFile(path) {
  9832. const closers = this._closers.get(path);
  9833. if (!closers) return;
  9834. closers.forEach((closer) => closer());
  9835. this._closers.delete(path);
  9836. }
  9837. /**
  9838. *
  9839. * @param {Path} path
  9840. * @param {Function} closer
  9841. */
  9842. _addPathCloser(path, closer) {
  9843. if (!closer) return;
  9844. let list = this._closers.get(path);
  9845. if (!list) {
  9846. list = [];
  9847. this._closers.set(path, list);
  9848. }
  9849. list.push(closer);
  9850. }
  9851. _readdirp(root, opts) {
  9852. if (this.closed) return;
  9853. let stream = readdirp(root, {
  9854. type: EV_ALL,
  9855. alwaysStat: true,
  9856. lstat: true,
  9857. ...opts
  9858. });
  9859. this._streams.add(stream);
  9860. stream.once(STR_CLOSE, () => {
  9861. stream = void 0;
  9862. });
  9863. stream.once(STR_END, () => {
  9864. if (stream) {
  9865. this._streams.delete(stream);
  9866. stream = void 0;
  9867. }
  9868. });
  9869. return stream;
  9870. }
  9871. };
  9872. /**
  9873. * Instantiates watcher with paths to be tracked.
  9874. * @param {String|Array<String>} paths file/directory paths and/or globs
  9875. * @param {Object=} options chokidar opts
  9876. * @returns an instance of FSWatcher for chaining.
  9877. */
  9878. const watch = (paths, options) => {
  9879. const watcher = new FSWatcher(options);
  9880. watcher.add(paths);
  9881. return watcher;
  9882. };
  9883. exports.watch = watch;
  9884. }));
  9885. //#endregion
  9886. //#region ../../node_modules/.pnpm/shell-quote@1.8.3/node_modules/shell-quote/quote.js
  9887. var require_quote = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  9888. module.exports = function quote(xs) {
  9889. return xs.map(function(s) {
  9890. if (s === "") return "''";
  9891. if (s && typeof s === "object") return s.op.replace(/(.)/g, "\\$1");
  9892. if (/["\s\\]/.test(s) && !/'/.test(s)) return "'" + s.replace(/(['])/g, "\\$1") + "'";
  9893. if (/["'\s]/.test(s)) return "\"" + s.replace(/(["\\$`!])/g, "\\$1") + "\"";
  9894. return String(s).replace(/([A-Za-z]:)?([#!"$&'()*,:;<=>?@[\\\]^`{|}])/g, "$1\\$2");
  9895. }).join(" ");
  9896. };
  9897. }));
  9898. //#endregion
  9899. //#region ../../node_modules/.pnpm/shell-quote@1.8.3/node_modules/shell-quote/parse.js
  9900. var require_parse$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  9901. var CONTROL = "(?:" + [
  9902. "\\|\\|",
  9903. "\\&\\&",
  9904. ";;",
  9905. "\\|\\&",
  9906. "\\<\\(",
  9907. "\\<\\<\\<",
  9908. ">>",
  9909. ">\\&",
  9910. "<\\&",
  9911. "[&;()|<>]"
  9912. ].join("|") + ")";
  9913. var controlRE = new RegExp("^" + CONTROL + "$");
  9914. var META = "|&;()<> \\t";
  9915. var SINGLE_QUOTE = "\"((\\\\\"|[^\"])*?)\"";
  9916. var DOUBLE_QUOTE = "'((\\\\'|[^'])*?)'";
  9917. var hash = /^#$/;
  9918. var SQ = "'";
  9919. var DQ = "\"";
  9920. var DS = "$";
  9921. var TOKEN = "";
  9922. var mult = 4294967296;
  9923. for (var i = 0; i < 4; i++) TOKEN += (mult * Math.random()).toString(16);
  9924. var startsWithToken = new RegExp("^" + TOKEN);
  9925. function matchAll(s, r) {
  9926. var origIndex = r.lastIndex;
  9927. var matches = [];
  9928. var matchObj;
  9929. while (matchObj = r.exec(s)) {
  9930. matches.push(matchObj);
  9931. if (r.lastIndex === matchObj.index) r.lastIndex += 1;
  9932. }
  9933. r.lastIndex = origIndex;
  9934. return matches;
  9935. }
  9936. function getVar(env, pre, key) {
  9937. var r = typeof env === "function" ? env(key) : env[key];
  9938. if (typeof r === "undefined" && key != "") r = "";
  9939. else if (typeof r === "undefined") r = "$";
  9940. if (typeof r === "object") return pre + TOKEN + JSON.stringify(r) + TOKEN;
  9941. return pre + r;
  9942. }
  9943. function parseInternal(string, env, opts) {
  9944. if (!opts) opts = {};
  9945. var BS = opts.escape || "\\";
  9946. var BAREWORD = "(\\" + BS + "['\"" + META + "]|[^\\s'\"" + META + "])+";
  9947. var matches = matchAll(string, new RegExp(["(" + CONTROL + ")", "(" + BAREWORD + "|" + SINGLE_QUOTE + "|" + DOUBLE_QUOTE + ")+"].join("|"), "g"));
  9948. if (matches.length === 0) return [];
  9949. if (!env) env = {};
  9950. var commented = false;
  9951. return matches.map(function(match) {
  9952. var s = match[0];
  9953. if (!s || commented) return;
  9954. if (controlRE.test(s)) return { op: s };
  9955. var quote = false;
  9956. var esc = false;
  9957. var out = "";
  9958. var isGlob = false;
  9959. var i;
  9960. function parseEnvVar() {
  9961. i += 1;
  9962. var varend;
  9963. var varname;
  9964. var char = s.charAt(i);
  9965. if (char === "{") {
  9966. i += 1;
  9967. if (s.charAt(i) === "}") throw new Error("Bad substitution: " + s.slice(i - 2, i + 1));
  9968. varend = s.indexOf("}", i);
  9969. if (varend < 0) throw new Error("Bad substitution: " + s.slice(i));
  9970. varname = s.slice(i, varend);
  9971. i = varend;
  9972. } else if (/[*@#?$!_-]/.test(char)) {
  9973. varname = char;
  9974. i += 1;
  9975. } else {
  9976. var slicedFromI = s.slice(i);
  9977. varend = slicedFromI.match(/[^\w\d_]/);
  9978. if (!varend) {
  9979. varname = slicedFromI;
  9980. i = s.length;
  9981. } else {
  9982. varname = slicedFromI.slice(0, varend.index);
  9983. i += varend.index - 1;
  9984. }
  9985. }
  9986. return getVar(env, "", varname);
  9987. }
  9988. for (i = 0; i < s.length; i++) {
  9989. var c = s.charAt(i);
  9990. isGlob = isGlob || !quote && (c === "*" || c === "?");
  9991. if (esc) {
  9992. out += c;
  9993. esc = false;
  9994. } else if (quote) if (c === quote) quote = false;
  9995. else if (quote == SQ) out += c;
  9996. else if (c === BS) {
  9997. i += 1;
  9998. c = s.charAt(i);
  9999. if (c === DQ || c === BS || c === DS) out += c;
  10000. else out += BS + c;
  10001. } else if (c === DS) out += parseEnvVar();
  10002. else out += c;
  10003. else if (c === DQ || c === SQ) quote = c;
  10004. else if (controlRE.test(c)) return { op: s };
  10005. else if (hash.test(c)) {
  10006. commented = true;
  10007. var commentObj = { comment: string.slice(match.index + i + 1) };
  10008. if (out.length) return [out, commentObj];
  10009. return [commentObj];
  10010. } else if (c === BS) esc = true;
  10011. else if (c === DS) out += parseEnvVar();
  10012. else out += c;
  10013. }
  10014. if (isGlob) return {
  10015. op: "glob",
  10016. pattern: out
  10017. };
  10018. return out;
  10019. }).reduce(function(prev, arg) {
  10020. return typeof arg === "undefined" ? prev : prev.concat(arg);
  10021. }, []);
  10022. }
  10023. module.exports = function parse(s, env, opts) {
  10024. var mapped = parseInternal(s, env, opts);
  10025. if (typeof env !== "function") return mapped;
  10026. return mapped.reduce(function(acc, s) {
  10027. if (typeof s === "object") return acc.concat(s);
  10028. var xs = s.split(RegExp("(" + TOKEN + ".*?" + TOKEN + ")", "g"));
  10029. if (xs.length === 1) return acc.concat(xs[0]);
  10030. return acc.concat(xs.filter(Boolean).map(function(x) {
  10031. if (startsWithToken.test(x)) return JSON.parse(x.split(TOKEN)[1]);
  10032. return x;
  10033. }));
  10034. }, []);
  10035. };
  10036. }));
  10037. //#endregion
  10038. //#region ../../node_modules/.pnpm/shell-quote@1.8.3/node_modules/shell-quote/index.js
  10039. var require_shell_quote = /* @__PURE__ */ __commonJSMin(((exports) => {
  10040. exports.quote = require_quote();
  10041. exports.parse = require_parse$1();
  10042. }));
  10043. //#endregion
  10044. //#region ../../node_modules/.pnpm/launch-editor@2.13.1/node_modules/launch-editor/editor-info/macos.js
  10045. var require_macos = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  10046. module.exports = {
  10047. "/Applications/Atom.app/Contents/MacOS/Atom": "atom",
  10048. "/Applications/Atom Beta.app/Contents/MacOS/Atom Beta": "/Applications/Atom Beta.app/Contents/MacOS/Atom Beta",
  10049. "/Applications/Brackets.app/Contents/MacOS/Brackets": "brackets",
  10050. "/Applications/Sublime Text.app/Contents/MacOS/Sublime Text": "/Applications/Sublime Text.app/Contents/SharedSupport/bin/subl",
  10051. "/Applications/Sublime Text.app/Contents/MacOS/sublime_text": "/Applications/Sublime Text.app/Contents/SharedSupport/bin/subl",
  10052. "/Applications/Sublime Text 2.app/Contents/MacOS/Sublime Text 2": "/Applications/Sublime Text 2.app/Contents/SharedSupport/bin/subl",
  10053. "/Applications/Sublime Text Dev.app/Contents/MacOS/Sublime Text": "/Applications/Sublime Text Dev.app/Contents/SharedSupport/bin/subl",
  10054. "/Applications/Visual Studio Code.app/Contents/MacOS/Electron": "code",
  10055. "/Applications/Visual Studio Code - Insiders.app/Contents/MacOS/Code - Insiders": "code-insiders",
  10056. "/Applications/Visual Studio Code - Insiders.app/Contents/MacOS/Electron": "code-insiders",
  10057. "/Applications/VSCodium.app/Contents/MacOS/Electron": "codium",
  10058. "/Applications/Cursor.app/Contents/MacOS/Cursor": "cursor",
  10059. "/Applications/Trae.app/Contents/MacOS/Electron": "trae",
  10060. "/Applications/Antigravity.app/Contents/MacOS/Electron": "antigravity",
  10061. "/Applications/AppCode.app/Contents/MacOS/appcode": "/Applications/AppCode.app/Contents/MacOS/appcode",
  10062. "/Applications/CLion.app/Contents/MacOS/clion": "/Applications/CLion.app/Contents/MacOS/clion",
  10063. "/Applications/IntelliJ IDEA.app/Contents/MacOS/idea": "/Applications/IntelliJ IDEA.app/Contents/MacOS/idea",
  10064. "/Applications/IntelliJ IDEA Ultimate.app/Contents/MacOS/idea": "/Applications/IntelliJ IDEA Ultimate.app/Contents/MacOS/idea",
  10065. "/Applications/IntelliJ IDEA Community Edition.app/Contents/MacOS/idea": "/Applications/IntelliJ IDEA Community Edition.app/Contents/MacOS/idea",
  10066. "/Applications/PhpStorm.app/Contents/MacOS/phpstorm": "/Applications/PhpStorm.app/Contents/MacOS/phpstorm",
  10067. "/Applications/PyCharm.app/Contents/MacOS/pycharm": "/Applications/PyCharm.app/Contents/MacOS/pycharm",
  10068. "/Applications/PyCharm CE.app/Contents/MacOS/pycharm": "/Applications/PyCharm CE.app/Contents/MacOS/pycharm",
  10069. "/Applications/RubyMine.app/Contents/MacOS/rubymine": "/Applications/RubyMine.app/Contents/MacOS/rubymine",
  10070. "/Applications/WebStorm.app/Contents/MacOS/webstorm": "/Applications/WebStorm.app/Contents/MacOS/webstorm",
  10071. "/Applications/MacVim.app/Contents/MacOS/MacVim": "mvim",
  10072. "/Applications/GoLand.app/Contents/MacOS/goland": "/Applications/GoLand.app/Contents/MacOS/goland",
  10073. "/Applications/Rider.app/Contents/MacOS/rider": "/Applications/Rider.app/Contents/MacOS/rider",
  10074. "/Applications/Zed.app/Contents/MacOS/zed": "zed"
  10075. };
  10076. }));
  10077. //#endregion
  10078. //#region ../../node_modules/.pnpm/launch-editor@2.13.1/node_modules/launch-editor/editor-info/linux.js
  10079. var require_linux = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  10080. module.exports = {
  10081. atom: "atom",
  10082. Brackets: "brackets",
  10083. "code-insiders": "code-insiders",
  10084. code: "code",
  10085. vscodium: "vscodium",
  10086. codium: "codium",
  10087. cursor: "cursor",
  10088. trae: "trae",
  10089. antigravity: "antigravity",
  10090. emacs: "emacs",
  10091. gvim: "gvim",
  10092. idea: "idea",
  10093. "idea.sh": "idea",
  10094. phpstorm: "phpstorm",
  10095. "phpstorm.sh": "phpstorm",
  10096. pycharm: "pycharm",
  10097. "pycharm.sh": "pycharm",
  10098. rubymine: "rubymine",
  10099. "rubymine.sh": "rubymine",
  10100. sublime_text: "subl",
  10101. vim: "vim",
  10102. webstorm: "webstorm",
  10103. "webstorm.sh": "webstorm",
  10104. goland: "goland",
  10105. "goland.sh": "goland",
  10106. rider: "rider",
  10107. "rider.sh": "rider",
  10108. zed: "zed"
  10109. };
  10110. }));
  10111. //#endregion
  10112. //#region ../../node_modules/.pnpm/launch-editor@2.13.1/node_modules/launch-editor/editor-info/windows.js
  10113. var require_windows$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  10114. module.exports = [
  10115. "Brackets.exe",
  10116. "Code.exe",
  10117. "Code - Insiders.exe",
  10118. "VSCodium.exe",
  10119. "Cursor.exe",
  10120. "atom.exe",
  10121. "sublime_text.exe",
  10122. "notepad++.exe",
  10123. "clion.exe",
  10124. "clion64.exe",
  10125. "idea.exe",
  10126. "idea64.exe",
  10127. "phpstorm.exe",
  10128. "phpstorm64.exe",
  10129. "pycharm.exe",
  10130. "pycharm64.exe",
  10131. "rubymine.exe",
  10132. "rubymine64.exe",
  10133. "webstorm.exe",
  10134. "webstorm64.exe",
  10135. "goland.exe",
  10136. "goland64.exe",
  10137. "rider.exe",
  10138. "rider64.exe",
  10139. "trae.exe",
  10140. "zed.exe",
  10141. "Antigravity.exe"
  10142. ];
  10143. }));
  10144. //#endregion
  10145. //#region ../../node_modules/.pnpm/launch-editor@2.13.1/node_modules/launch-editor/guess.js
  10146. var require_guess = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  10147. const path$9 = __require("path");
  10148. const shellQuote = require_shell_quote();
  10149. const childProcess$2 = __require("child_process");
  10150. const COMMON_EDITORS_MACOS = require_macos();
  10151. const COMMON_EDITORS_LINUX = require_linux();
  10152. const COMMON_EDITORS_WIN = require_windows$1();
  10153. module.exports = function guessEditor(specifiedEditor) {
  10154. if (specifiedEditor) return shellQuote.parse(specifiedEditor);
  10155. if (process.env.LAUNCH_EDITOR) return [process.env.LAUNCH_EDITOR];
  10156. if (process.versions.webcontainer) return [process.env.EDITOR || "code"];
  10157. try {
  10158. if (process.platform === "darwin") {
  10159. const output = childProcess$2.execSync("ps x -o comm=", { stdio: [
  10160. "pipe",
  10161. "pipe",
  10162. "ignore"
  10163. ] }).toString();
  10164. const processNames = Object.keys(COMMON_EDITORS_MACOS);
  10165. const processList = output.split("\n");
  10166. for (let i = 0; i < processNames.length; i++) {
  10167. const processName = processNames[i];
  10168. if (processList.includes(processName)) return [COMMON_EDITORS_MACOS[processName]];
  10169. const processNameWithoutApplications = processName.replace("/Applications", "");
  10170. if (output.indexOf(processNameWithoutApplications) !== -1) {
  10171. if (processName !== COMMON_EDITORS_MACOS[processName]) return [COMMON_EDITORS_MACOS[processName]];
  10172. const runningProcess = processList.find((procName) => procName.endsWith(processNameWithoutApplications));
  10173. if (runningProcess !== void 0) return [runningProcess];
  10174. }
  10175. }
  10176. } else if (process.platform === "win32") {
  10177. 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: [
  10178. "pipe",
  10179. "pipe",
  10180. "ignore"
  10181. ] }).toString().split("\r\n");
  10182. for (let i = 0; i < runningProcesses.length; i++) {
  10183. const fullProcessPath = runningProcesses[i].trim();
  10184. const shortProcessName = path$9.basename(fullProcessPath);
  10185. if (COMMON_EDITORS_WIN.indexOf(shortProcessName) !== -1) return [fullProcessPath];
  10186. }
  10187. } else if (process.platform === "linux") {
  10188. const output = childProcess$2.execSync("ps x --no-heading -o comm --sort=comm", { stdio: [
  10189. "pipe",
  10190. "pipe",
  10191. "ignore"
  10192. ] }).toString();
  10193. const processNames = Object.keys(COMMON_EDITORS_LINUX);
  10194. for (let i = 0; i < processNames.length; i++) {
  10195. const processName = processNames[i];
  10196. if (output.indexOf(processName) !== -1) return [COMMON_EDITORS_LINUX[processName]];
  10197. }
  10198. }
  10199. } catch (ignoreError) {}
  10200. if (process.env.VISUAL) return [process.env.VISUAL];
  10201. else if (process.env.EDITOR) return [process.env.EDITOR];
  10202. return [null];
  10203. };
  10204. }));
  10205. //#endregion
  10206. //#region ../../node_modules/.pnpm/launch-editor@2.13.1/node_modules/launch-editor/get-args.js
  10207. var require_get_args = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  10208. const path$8 = __require("path");
  10209. module.exports = function getArgumentsForPosition(editor, fileName, lineNumber, columnNumber = 1) {
  10210. switch (path$8.basename(editor).replace(/\.(exe|cmd|bat)$/i, "")) {
  10211. case "atom":
  10212. case "Atom":
  10213. case "Atom Beta":
  10214. case "subl":
  10215. case "sublime":
  10216. case "sublime_text":
  10217. case "wstorm":
  10218. case "charm":
  10219. case "zed": return [`${fileName}:${lineNumber}:${columnNumber}`];
  10220. case "notepad++": return [
  10221. "-n" + lineNumber,
  10222. "-c" + columnNumber,
  10223. fileName
  10224. ];
  10225. case "vim":
  10226. case "mvim": return [`+call cursor(${lineNumber}, ${columnNumber})`, fileName];
  10227. case "joe":
  10228. case "gvim": return [`+${lineNumber}`, fileName];
  10229. case "emacs":
  10230. case "emacsclient": return [`+${lineNumber}:${columnNumber}`, fileName];
  10231. case "rmate":
  10232. case "mate":
  10233. case "mine": return [
  10234. "--line",
  10235. lineNumber,
  10236. fileName
  10237. ];
  10238. case "code":
  10239. case "Code":
  10240. case "code-insiders":
  10241. case "Code - Insiders":
  10242. case "codium":
  10243. case "trae":
  10244. case "antigravity":
  10245. case "cursor":
  10246. case "vscodium":
  10247. case "VSCodium": return [
  10248. "-r",
  10249. "-g",
  10250. `${fileName}:${lineNumber}:${columnNumber}`
  10251. ];
  10252. case "appcode":
  10253. case "clion":
  10254. case "clion64":
  10255. case "idea":
  10256. case "idea64":
  10257. case "phpstorm":
  10258. case "phpstorm64":
  10259. case "pycharm":
  10260. case "pycharm64":
  10261. case "rubymine":
  10262. case "rubymine64":
  10263. case "webstorm":
  10264. case "webstorm64":
  10265. case "goland":
  10266. case "goland64":
  10267. case "rider":
  10268. case "rider64": return [
  10269. "--line",
  10270. lineNumber,
  10271. "--column",
  10272. columnNumber,
  10273. fileName
  10274. ];
  10275. }
  10276. if (process.env.LAUNCH_EDITOR) return [
  10277. fileName,
  10278. lineNumber,
  10279. columnNumber
  10280. ];
  10281. return [fileName];
  10282. };
  10283. }));
  10284. //#endregion
  10285. //#region ../../node_modules/.pnpm/launch-editor@2.13.1/node_modules/launch-editor/index.js
  10286. var require_launch_editor = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  10287. /**
  10288. * Copyright (c) 2015-present, Facebook, Inc.
  10289. *
  10290. * This source code is licensed under the MIT license found in the
  10291. * LICENSE file at
  10292. * https://github.com/facebookincubator/create-react-app/blob/master/LICENSE
  10293. *
  10294. * Modified by Yuxi Evan You
  10295. */
  10296. const fs$6 = __require("fs");
  10297. const os$2 = __require("os");
  10298. const path$7 = __require("path");
  10299. const colors = require_picocolors();
  10300. const childProcess$1 = __require("child_process");
  10301. const guessEditor = require_guess();
  10302. const getArgumentsForPosition = require_get_args();
  10303. function wrapErrorCallback(cb) {
  10304. return (fileName, errorMessage) => {
  10305. console.log();
  10306. console.log(colors.red("Could not open " + path$7.basename(fileName) + " in the editor."));
  10307. if (errorMessage) {
  10308. if (errorMessage[errorMessage.length - 1] !== ".") errorMessage += ".";
  10309. console.log(colors.red("The editor process exited with an error: " + errorMessage));
  10310. }
  10311. console.log();
  10312. if (cb) cb(fileName, errorMessage);
  10313. };
  10314. }
  10315. function isTerminalEditor(editor) {
  10316. switch (editor) {
  10317. case "vim":
  10318. case "emacs":
  10319. case "nano": return true;
  10320. }
  10321. return false;
  10322. }
  10323. const positionRE = /:(\d+)(:(\d+))?$/;
  10324. function parseFile(file) {
  10325. if (file.startsWith("file://")) file = __require("url").fileURLToPath(file);
  10326. const fileName = file.replace(positionRE, "");
  10327. const match = file.match(positionRE);
  10328. return {
  10329. fileName,
  10330. lineNumber: match && match[1],
  10331. columnNumber: match && match[3]
  10332. };
  10333. }
  10334. let _childProcess = null;
  10335. function launchEditor(file, specifiedEditor, onErrorCallback) {
  10336. const parsed = parseFile(file);
  10337. let { fileName } = parsed;
  10338. const { lineNumber, columnNumber } = parsed;
  10339. if (!fs$6.existsSync(fileName)) return;
  10340. if (typeof specifiedEditor === "function") {
  10341. onErrorCallback = specifiedEditor;
  10342. specifiedEditor = void 0;
  10343. }
  10344. onErrorCallback = wrapErrorCallback(onErrorCallback);
  10345. const [editor, ...args] = guessEditor(specifiedEditor);
  10346. if (!editor) {
  10347. onErrorCallback(fileName, null);
  10348. return;
  10349. }
  10350. if (process.platform === "linux" && fileName.startsWith("/mnt/") && /Microsoft/i.test(os$2.release())) fileName = path$7.relative("", fileName);
  10351. if (lineNumber) {
  10352. const extraArgs = getArgumentsForPosition(editor, fileName, lineNumber, columnNumber);
  10353. args.push.apply(args, extraArgs);
  10354. } else args.push(fileName);
  10355. if (_childProcess && isTerminalEditor(editor)) _childProcess.kill("SIGKILL");
  10356. if (process.platform === "win32") {
  10357. function escapeCmdArgs(cmdArgs) {
  10358. return cmdArgs.replace(/([&|<>,;=^])/g, "^$1");
  10359. }
  10360. function doubleQuoteIfNeeded(str) {
  10361. if (str.includes("^")) return `^"${str}^"`;
  10362. else if (str.includes(" ")) return `"${str}"`;
  10363. return str;
  10364. }
  10365. const launchCommand = [editor, ...args.map(escapeCmdArgs)].map(doubleQuoteIfNeeded).join(" ");
  10366. _childProcess = childProcess$1.exec(launchCommand, {
  10367. stdio: "inherit",
  10368. shell: true
  10369. });
  10370. } else _childProcess = childProcess$1.spawn(editor, args, { stdio: "inherit" });
  10371. _childProcess.on("exit", function(errorCode) {
  10372. _childProcess = null;
  10373. if (errorCode) onErrorCallback(fileName, "(code " + errorCode + ")");
  10374. });
  10375. _childProcess.on("error", function(error) {
  10376. let { code, message } = error;
  10377. if ("ENOENT" === code) message = `${message} ('${editor}' command does not exist in 'PATH')`;
  10378. onErrorCallback(fileName, message);
  10379. });
  10380. }
  10381. module.exports = launchEditor;
  10382. }));
  10383. //#endregion
  10384. //#region ../../node_modules/.pnpm/launch-editor-middleware@2.13.1/node_modules/launch-editor-middleware/index.js
  10385. var require_launch_editor_middleware = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  10386. const path$6 = __require("path");
  10387. const launch = require_launch_editor();
  10388. module.exports = (specifiedEditor, srcRoot, onErrorCallback) => {
  10389. if (typeof specifiedEditor === "function") {
  10390. onErrorCallback = specifiedEditor;
  10391. specifiedEditor = void 0;
  10392. }
  10393. if (typeof srcRoot === "function") {
  10394. onErrorCallback = srcRoot;
  10395. srcRoot = void 0;
  10396. }
  10397. srcRoot = srcRoot || process.cwd();
  10398. return function launchEditorMiddleware(req, res) {
  10399. let url;
  10400. try {
  10401. const fullUrl = req.url.startsWith("http") ? req.url : `http://localhost${req.url}`;
  10402. url = new URL(fullUrl);
  10403. } catch (_err) {
  10404. res.statusCode = 500;
  10405. res.end(`launch-editor-middleware: invalid URL.`);
  10406. return;
  10407. }
  10408. const file = url.searchParams.get("file");
  10409. if (!file) {
  10410. res.statusCode = 500;
  10411. res.end(`launch-editor-middleware: required query param "file" is missing.`);
  10412. } else {
  10413. launch(file.startsWith("file://") ? file : path$6.resolve(srcRoot, file), specifiedEditor, onErrorCallback);
  10414. res.end();
  10415. }
  10416. };
  10417. };
  10418. }));
  10419. //#endregion
  10420. //#region ../../node_modules/.pnpm/@vercel+detect-agent@1.1.0/node_modules/@vercel/detect-agent/dist/index.js
  10421. var require_dist = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  10422. var __defProp = Object.defineProperty;
  10423. var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
  10424. var __getOwnPropNames = Object.getOwnPropertyNames;
  10425. var __hasOwnProp = Object.prototype.hasOwnProperty;
  10426. var __export = (target, all) => {
  10427. for (var name in all) __defProp(target, name, {
  10428. get: all[name],
  10429. enumerable: true
  10430. });
  10431. };
  10432. var __copyProps = (to, from, except, desc) => {
  10433. if (from && typeof from === "object" || typeof from === "function") {
  10434. for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
  10435. get: () => from[key],
  10436. enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
  10437. });
  10438. }
  10439. return to;
  10440. };
  10441. var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
  10442. var src_exports = {};
  10443. __export(src_exports, {
  10444. KNOWN_AGENTS: () => KNOWN_AGENTS,
  10445. determineAgent: () => determineAgent
  10446. });
  10447. module.exports = __toCommonJS(src_exports);
  10448. var import_promises = __require("node:fs/promises");
  10449. var import_node_fs = __require("node:fs");
  10450. const DEVIN_LOCAL_PATH = "/opt/.devin";
  10451. const CURSOR = "cursor";
  10452. const CURSOR_CLI = "cursor-cli";
  10453. const CLAUDE = "claude";
  10454. const DEVIN = "devin";
  10455. const REPLIT = "replit";
  10456. const GEMINI = "gemini";
  10457. const CODEX = "codex";
  10458. const AUGMENT_CLI = "augment-cli";
  10459. const OPENCODE = "opencode";
  10460. const KNOWN_AGENTS = {
  10461. CURSOR,
  10462. CURSOR_CLI,
  10463. CLAUDE,
  10464. DEVIN,
  10465. REPLIT,
  10466. GEMINI,
  10467. CODEX,
  10468. AUGMENT_CLI,
  10469. OPENCODE
  10470. };
  10471. async function determineAgent() {
  10472. if (process.env.AI_AGENT) {
  10473. const name = process.env.AI_AGENT.trim();
  10474. if (name) return {
  10475. isAgent: true,
  10476. agent: { name }
  10477. };
  10478. }
  10479. if (process.env.CURSOR_TRACE_ID) return {
  10480. isAgent: true,
  10481. agent: { name: CURSOR }
  10482. };
  10483. if (process.env.CURSOR_AGENT) return {
  10484. isAgent: true,
  10485. agent: { name: CURSOR_CLI }
  10486. };
  10487. if (process.env.GEMINI_CLI) return {
  10488. isAgent: true,
  10489. agent: { name: GEMINI }
  10490. };
  10491. if (process.env.CODEX_SANDBOX) return {
  10492. isAgent: true,
  10493. agent: { name: CODEX }
  10494. };
  10495. if (process.env.AUGMENT_AGENT) return {
  10496. isAgent: true,
  10497. agent: { name: AUGMENT_CLI }
  10498. };
  10499. if (process.env.OPENCODE_CLIENT) return {
  10500. isAgent: true,
  10501. agent: { name: OPENCODE }
  10502. };
  10503. if (process.env.CLAUDECODE || process.env.CLAUDE_CODE) return {
  10504. isAgent: true,
  10505. agent: { name: CLAUDE }
  10506. };
  10507. if (process.env.REPL_ID) return {
  10508. isAgent: true,
  10509. agent: { name: REPLIT }
  10510. };
  10511. try {
  10512. await (0, import_promises.access)(DEVIN_LOCAL_PATH, import_node_fs.constants.F_OK);
  10513. return {
  10514. isAgent: true,
  10515. agent: { name: DEVIN }
  10516. };
  10517. } catch (error) {}
  10518. return {
  10519. isAgent: false,
  10520. agent: void 0
  10521. };
  10522. }
  10523. }));
  10524. //#endregion
  10525. //#region src/node/http.ts
  10526. async function resolveHttpServer(app, httpsOptions) {
  10527. if (!httpsOptions) {
  10528. const { createServer } = await import("node:http");
  10529. return createServer(app);
  10530. }
  10531. const { createSecureServer } = await import("node:http2");
  10532. return createSecureServer({
  10533. maxSessionMemory: 1e3,
  10534. streamResetBurst: 1e5,
  10535. streamResetRate: 33,
  10536. ...httpsOptions,
  10537. allowHTTP1: true
  10538. }, app);
  10539. }
  10540. async function resolveHttpsConfig(https) {
  10541. if (!https) return void 0;
  10542. const [ca, cert, key, pfx] = await Promise.all([
  10543. readFileIfExists(https.ca),
  10544. readFileIfExists(https.cert),
  10545. readFileIfExists(https.key),
  10546. readFileIfExists(https.pfx)
  10547. ]);
  10548. return {
  10549. ...https,
  10550. ca,
  10551. cert,
  10552. key,
  10553. pfx
  10554. };
  10555. }
  10556. async function readFileIfExists(value) {
  10557. if (typeof value === "string") return fsp.readFile(path.resolve(value)).catch(() => value);
  10558. return value;
  10559. }
  10560. async function isPortAvailable(port) {
  10561. for (const host of wildcardHosts) if (!await tryListen(port, host).catch(() => true)) return false;
  10562. return true;
  10563. }
  10564. function tryListen(port, host) {
  10565. return new Promise((resolve) => {
  10566. const server = net.createServer();
  10567. server.once("error", (e) => {
  10568. server.close(() => resolve(e.code !== "EADDRINUSE"));
  10569. });
  10570. server.once("listening", () => {
  10571. server.close(() => resolve(true));
  10572. });
  10573. server.listen(port, host);
  10574. });
  10575. }
  10576. async function tryBindServer(httpServer, port, host) {
  10577. return new Promise((resolve) => {
  10578. const onError = (e) => {
  10579. httpServer.off("error", onError);
  10580. httpServer.off("listening", onListening);
  10581. resolve({
  10582. success: false,
  10583. error: e
  10584. });
  10585. };
  10586. const onListening = () => {
  10587. httpServer.off("error", onError);
  10588. httpServer.off("listening", onListening);
  10589. resolve({ success: true });
  10590. };
  10591. httpServer.on("error", onError);
  10592. httpServer.on("listening", onListening);
  10593. httpServer.listen(port, host);
  10594. });
  10595. }
  10596. const MAX_PORT = 65535;
  10597. async function httpServerStart(httpServer, serverOptions) {
  10598. const { port: startPort, strictPort, host, logger } = serverOptions;
  10599. for (let port = startPort; port <= MAX_PORT; port++) {
  10600. if (await isPortAvailable(port)) {
  10601. const result = await tryBindServer(httpServer, port, host);
  10602. if (result.success) return port;
  10603. if (result.error.code !== "EADDRINUSE") throw result.error;
  10604. }
  10605. if (strictPort) throw new Error(`Port ${port} is already in use`);
  10606. logger.info(`Port ${port} is in use, trying another one...`);
  10607. }
  10608. throw new Error(`No available ports found between ${startPort} and ${MAX_PORT}`);
  10609. }
  10610. function setClientErrorHandler(server, logger) {
  10611. server.on("clientError", (err, socket) => {
  10612. let msg = "400 Bad Request";
  10613. if (err.code === "HPE_HEADER_OVERFLOW") {
  10614. msg = "431 Request Header Fields Too Large";
  10615. 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."));
  10616. }
  10617. if (err.code === "ECONNRESET" || !socket.writable) return;
  10618. socket.end(`HTTP/1.1 ${msg}\r\n\r\n`);
  10619. });
  10620. }
  10621. //#endregion
  10622. //#region src/node/ssr/ssrStacktrace.ts
  10623. let offset;
  10624. function calculateOffsetOnce() {
  10625. if (offset !== void 0) return;
  10626. try {
  10627. new Function("throw new Error(1)")();
  10628. } catch (e) {
  10629. const match = /:(\d+):\d+\)$/.exec(e.stack.split("\n")[1]);
  10630. offset = match ? +match[1] - 1 : 0;
  10631. }
  10632. }
  10633. function ssrRewriteStacktrace(stack, moduleGraph) {
  10634. calculateOffsetOnce();
  10635. let alreadyRewritten = false;
  10636. return {
  10637. result: stack.split("\n").map((line) => {
  10638. return line.replace(/^ {4}at (?:(\S.*?)\s\()?(.+?):(\d+)(?::(\d+))?\)?/, (input, varName, id, originalLine, originalColumn) => {
  10639. if (!id) return input;
  10640. const rawSourceMap = moduleGraph.getModuleById(id)?.transformResult?.map;
  10641. if (!rawSourceMap) return input;
  10642. const traced = new TraceMap(rawSourceMap);
  10643. const line = Number(originalLine) - offset;
  10644. const column = Number(originalColumn) - 1;
  10645. if (line <= 0 || column < 0) {
  10646. alreadyRewritten = true;
  10647. return input;
  10648. }
  10649. const pos = originalPositionFor$2(traced, {
  10650. line,
  10651. column
  10652. });
  10653. if (!pos.source) return input;
  10654. const trimmedVarName = varName?.trim();
  10655. const source = `${path.resolve(path.dirname(id), pos.source)}:${pos.line}:${pos.column + 1}`;
  10656. if (!trimmedVarName || trimmedVarName === "eval") return ` at ${source}`;
  10657. else return ` at ${trimmedVarName} (${source})`;
  10658. });
  10659. }).join("\n"),
  10660. alreadyRewritten
  10661. };
  10662. }
  10663. function rebindErrorStacktrace(e, stacktrace) {
  10664. const { configurable, writable } = Object.getOwnPropertyDescriptor(e, "stack");
  10665. if (configurable) Object.defineProperty(e, "stack", {
  10666. value: stacktrace,
  10667. enumerable: true,
  10668. configurable: true,
  10669. writable: true
  10670. });
  10671. else if (writable) e.stack = stacktrace;
  10672. }
  10673. const rewroteStacktraces = /* @__PURE__ */ new WeakSet();
  10674. function ssrFixStacktrace(e, moduleGraph) {
  10675. if (!e.stack) return;
  10676. if (rewroteStacktraces.has(e)) return;
  10677. const { result: stacktrace, alreadyRewritten } = ssrRewriteStacktrace(e.stack, moduleGraph);
  10678. rebindErrorStacktrace(e, stacktrace);
  10679. 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.)";
  10680. rewroteStacktraces.add(e);
  10681. }
  10682. //#endregion
  10683. //#region src/node/ssr/runtime/serverModuleRunner.ts
  10684. function createHMROptions(environment, options) {
  10685. if (environment.config.server.hmr === false || options.hmr === false) return false;
  10686. if (!("api" in environment.hot)) return false;
  10687. return { logger: options.hmr?.logger };
  10688. }
  10689. const prepareStackTrace = { retrieveFile(id) {
  10690. if (existsSync(id)) return readFileSync(id, "utf-8");
  10691. } };
  10692. function resolveSourceMapOptions(options) {
  10693. if (options.sourcemapInterceptor != null) {
  10694. if (options.sourcemapInterceptor === "prepareStackTrace") return prepareStackTrace;
  10695. if (typeof options.sourcemapInterceptor === "object") return {
  10696. ...prepareStackTrace,
  10697. ...options.sourcemapInterceptor
  10698. };
  10699. return options.sourcemapInterceptor;
  10700. }
  10701. if (typeof process !== "undefined" && "setSourceMapsEnabled" in process) return "node";
  10702. return prepareStackTrace;
  10703. }
  10704. const createServerModuleRunnerTransport = (options) => {
  10705. const hmrClient = { send: (payload) => {
  10706. if (payload.type !== "custom") throw new Error("Cannot send non-custom events from the client to the server.");
  10707. options.channel.send(payload);
  10708. } };
  10709. let handler;
  10710. return {
  10711. connect({ onMessage }) {
  10712. options.channel.api.outsideEmitter.on("send", onMessage);
  10713. options.channel.api.innerEmitter.emit("vite:client:connect", void 0, hmrClient);
  10714. onMessage({ type: "connected" });
  10715. handler = onMessage;
  10716. },
  10717. disconnect() {
  10718. if (handler) options.channel.api.outsideEmitter.off("send", handler);
  10719. options.channel.api.innerEmitter.emit("vite:client:disconnect", void 0, hmrClient);
  10720. },
  10721. send(payload) {
  10722. if (payload.type !== "custom") throw new Error("Cannot send non-custom events from the server to the client.");
  10723. options.channel.api.innerEmitter.emit(payload.event, payload.data, hmrClient);
  10724. }
  10725. };
  10726. };
  10727. /**
  10728. * Create an instance of the Vite SSR runtime that support HMR.
  10729. * @experimental
  10730. */
  10731. function createServerModuleRunner(environment, options = {}) {
  10732. const hmr = createHMROptions(environment, options);
  10733. return new ModuleRunner({
  10734. ...options,
  10735. transport: createServerModuleRunnerTransport({ channel: environment.hot }),
  10736. hmr,
  10737. createImportMeta: createNodeImportMeta,
  10738. sourcemapInterceptor: resolveSourceMapOptions(options)
  10739. }, options.evaluator);
  10740. }
  10741. //#endregion
  10742. //#region src/node/ssr/ssrModuleLoader.ts
  10743. async function ssrLoadModule(url, server, fixStacktrace) {
  10744. const environment = server.environments.ssr;
  10745. if (!isRunnableDevEnvironment(environment)) throw new Error(`ssrLoadModule requires the 'ssr' environment to be a runnable environment.`);
  10746. server._ssrCompatModuleRunner ||= new SSRCompatModuleRunner(environment);
  10747. url = unwrapId(url);
  10748. return instantiateModule(url, server._ssrCompatModuleRunner, environment, fixStacktrace);
  10749. }
  10750. async function instantiateModule(url, runner, environment, fixStacktrace) {
  10751. const mod = await environment.moduleGraph.ensureEntryFromUrl(url);
  10752. if (mod.ssrError) throw mod.ssrError;
  10753. try {
  10754. return await runner.import(url);
  10755. } catch (e) {
  10756. if (e.stack && fixStacktrace) ssrFixStacktrace(e, environment.moduleGraph);
  10757. environment.logger.error(buildErrorMessage(e, [import_picocolors.default.red(`Error when evaluating SSR module ${url}: ${e.message}`)]), {
  10758. timestamp: true,
  10759. clear: environment.config.clearScreen,
  10760. error: e
  10761. });
  10762. throw e;
  10763. }
  10764. }
  10765. var SSRCompatModuleRunner = class extends ModuleRunner {
  10766. constructor(environment) {
  10767. super({
  10768. transport: createServerModuleRunnerTransport({ channel: environment.hot }),
  10769. createImportMeta: createNodeImportMeta,
  10770. sourcemapInterceptor: false,
  10771. hmr: false
  10772. }, new ESModulesEvaluator());
  10773. this.environment = environment;
  10774. }
  10775. async directRequest(url, mod, callstack) {
  10776. const id = mod.meta && "id" in mod.meta && mod.meta.id;
  10777. if (!id) return super.directRequest(url, mod, callstack);
  10778. const viteMod = this.environment.moduleGraph.getModuleById(id);
  10779. if (!viteMod) return super.directRequest(id, mod, callstack);
  10780. try {
  10781. const exports = await super.directRequest(id, mod, callstack);
  10782. viteMod.ssrModule = exports;
  10783. return exports;
  10784. } catch (err) {
  10785. viteMod.ssrError = err;
  10786. throw err;
  10787. }
  10788. }
  10789. };
  10790. //#endregion
  10791. //#region ../../node_modules/.pnpm/periscopic@4.0.2/node_modules/periscopic/src/index.js
  10792. /**
  10793. * @param {import('estree').Node} param
  10794. * @returns {string[]}
  10795. */
  10796. function extract_names(param) {
  10797. return extract_identifiers(param).map((node) => node.name);
  10798. }
  10799. /**
  10800. * @param {import('estree').Node} param
  10801. * @param {import('estree').Identifier[]} nodes
  10802. * @returns {import('estree').Identifier[]}
  10803. */
  10804. function extract_identifiers(param, nodes = []) {
  10805. switch (param.type) {
  10806. case "Identifier":
  10807. nodes.push(param);
  10808. break;
  10809. case "MemberExpression":
  10810. let object = param;
  10811. while (object.type === "MemberExpression") object = object.object;
  10812. nodes.push(object);
  10813. break;
  10814. case "ObjectPattern":
  10815. for (const prop of param.properties) if (prop.type === "RestElement") extract_identifiers(prop.argument, nodes);
  10816. else extract_identifiers(prop.value, nodes);
  10817. break;
  10818. case "ArrayPattern":
  10819. for (const element of param.elements) if (element) extract_identifiers(element, nodes);
  10820. break;
  10821. case "RestElement":
  10822. extract_identifiers(param.argument, nodes);
  10823. break;
  10824. case "AssignmentPattern":
  10825. extract_identifiers(param.left, nodes);
  10826. break;
  10827. }
  10828. return nodes;
  10829. }
  10830. //#endregion
  10831. //#region ../../node_modules/.pnpm/estree-walker@3.0.3/node_modules/estree-walker/src/walker.js
  10832. /**
  10833. * @typedef { import('estree').Node} Node
  10834. * @typedef {{
  10835. * skip: () => void;
  10836. * remove: () => void;
  10837. * replace: (node: Node) => void;
  10838. * }} WalkerContext
  10839. */
  10840. var WalkerBase = class {
  10841. constructor() {
  10842. /** @type {boolean} */
  10843. this.should_skip = false;
  10844. /** @type {boolean} */
  10845. this.should_remove = false;
  10846. /** @type {Node | null} */
  10847. this.replacement = null;
  10848. /** @type {WalkerContext} */
  10849. this.context = {
  10850. skip: () => this.should_skip = true,
  10851. remove: () => this.should_remove = true,
  10852. replace: (node) => this.replacement = node
  10853. };
  10854. }
  10855. /**
  10856. * @template {Node} Parent
  10857. * @param {Parent | null | undefined} parent
  10858. * @param {keyof Parent | null | undefined} prop
  10859. * @param {number | null | undefined} index
  10860. * @param {Node} node
  10861. */
  10862. replace(parent, prop, index, node) {
  10863. if (parent && prop) if (index != null)
  10864. /** @type {Array<Node>} */ parent[prop][index] = node;
  10865. else
  10866. /** @type {Node} */ parent[prop] = node;
  10867. }
  10868. /**
  10869. * @template {Node} Parent
  10870. * @param {Parent | null | undefined} parent
  10871. * @param {keyof Parent | null | undefined} prop
  10872. * @param {number | null | undefined} index
  10873. */
  10874. remove(parent, prop, index) {
  10875. if (parent && prop) if (index !== null && index !== void 0)
  10876. /** @type {Array<Node>} */ parent[prop].splice(index, 1);
  10877. else delete parent[prop];
  10878. }
  10879. };
  10880. //#endregion
  10881. //#region ../../node_modules/.pnpm/estree-walker@3.0.3/node_modules/estree-walker/src/sync.js
  10882. /**
  10883. * @typedef { import('estree').Node} Node
  10884. * @typedef { import('./walker.js').WalkerContext} WalkerContext
  10885. * @typedef {(
  10886. * this: WalkerContext,
  10887. * node: Node,
  10888. * parent: Node | null,
  10889. * key: string | number | symbol | null | undefined,
  10890. * index: number | null | undefined
  10891. * ) => void} SyncHandler
  10892. */
  10893. var SyncWalker = class extends WalkerBase {
  10894. /**
  10895. *
  10896. * @param {SyncHandler} [enter]
  10897. * @param {SyncHandler} [leave]
  10898. */
  10899. constructor(enter, leave) {
  10900. super();
  10901. /** @type {boolean} */
  10902. this.should_skip = false;
  10903. /** @type {boolean} */
  10904. this.should_remove = false;
  10905. /** @type {Node | null} */
  10906. this.replacement = null;
  10907. /** @type {WalkerContext} */
  10908. this.context = {
  10909. skip: () => this.should_skip = true,
  10910. remove: () => this.should_remove = true,
  10911. replace: (node) => this.replacement = node
  10912. };
  10913. /** @type {SyncHandler | undefined} */
  10914. this.enter = enter;
  10915. /** @type {SyncHandler | undefined} */
  10916. this.leave = leave;
  10917. }
  10918. /**
  10919. * @template {Node} Parent
  10920. * @param {Node} node
  10921. * @param {Parent | null} parent
  10922. * @param {keyof Parent} [prop]
  10923. * @param {number | null} [index]
  10924. * @returns {Node | null}
  10925. */
  10926. visit(node, parent, prop, index) {
  10927. if (node) {
  10928. if (this.enter) {
  10929. const _should_skip = this.should_skip;
  10930. const _should_remove = this.should_remove;
  10931. const _replacement = this.replacement;
  10932. this.should_skip = false;
  10933. this.should_remove = false;
  10934. this.replacement = null;
  10935. this.enter.call(this.context, node, parent, prop, index);
  10936. if (this.replacement) {
  10937. node = this.replacement;
  10938. this.replace(parent, prop, index, node);
  10939. }
  10940. if (this.should_remove) this.remove(parent, prop, index);
  10941. const skipped = this.should_skip;
  10942. const removed = this.should_remove;
  10943. this.should_skip = _should_skip;
  10944. this.should_remove = _should_remove;
  10945. this.replacement = _replacement;
  10946. if (skipped) return node;
  10947. if (removed) return null;
  10948. }
  10949. /** @type {keyof Node} */
  10950. let key;
  10951. for (key in node) {
  10952. /** @type {unknown} */
  10953. const value = node[key];
  10954. if (value && typeof value === "object") {
  10955. if (Array.isArray(value)) {
  10956. const nodes = value;
  10957. for (let i = 0; i < nodes.length; i += 1) {
  10958. const item = nodes[i];
  10959. if (isNode(item)) {
  10960. if (!this.visit(item, node, key, i)) i--;
  10961. }
  10962. }
  10963. } else if (isNode(value)) this.visit(value, node, key, null);
  10964. }
  10965. }
  10966. if (this.leave) {
  10967. const _replacement = this.replacement;
  10968. const _should_remove = this.should_remove;
  10969. this.replacement = null;
  10970. this.should_remove = false;
  10971. this.leave.call(this.context, node, parent, prop, index);
  10972. if (this.replacement) {
  10973. node = this.replacement;
  10974. this.replace(parent, prop, index, node);
  10975. }
  10976. if (this.should_remove) this.remove(parent, prop, index);
  10977. const removed = this.should_remove;
  10978. this.replacement = _replacement;
  10979. this.should_remove = _should_remove;
  10980. if (removed) return null;
  10981. }
  10982. }
  10983. return node;
  10984. }
  10985. };
  10986. /**
  10987. * Ducktype a node.
  10988. *
  10989. * @param {unknown} value
  10990. * @returns {value is Node}
  10991. */
  10992. function isNode(value) {
  10993. return value !== null && typeof value === "object" && "type" in value && typeof value.type === "string";
  10994. }
  10995. //#endregion
  10996. //#region ../../node_modules/.pnpm/estree-walker@3.0.3/node_modules/estree-walker/src/index.js
  10997. /**
  10998. * @typedef {import('estree').Node} Node
  10999. * @typedef {import('./sync.js').SyncHandler} SyncHandler
  11000. * @typedef {import('./async.js').AsyncHandler} AsyncHandler
  11001. */
  11002. /**
  11003. * @param {Node} ast
  11004. * @param {{
  11005. * enter?: SyncHandler
  11006. * leave?: SyncHandler
  11007. * }} walker
  11008. * @returns {Node | null}
  11009. */
  11010. function walk$1(ast, { enter, leave }) {
  11011. return new SyncWalker(enter, leave).visit(ast, null);
  11012. }
  11013. //#endregion
  11014. //#region src/node/plugins/json.ts
  11015. const jsonLangRE = new RegExp(`\\.(?:json|json5)(?:$|\\?)`);
  11016. const isJSONRequest = (request) => jsonLangRE.test(request);
  11017. //#endregion
  11018. //#region src/node/ssr/ssrTransform.ts
  11019. const ssrModuleExportsKey = `__vite_ssr_exports__`;
  11020. const ssrImportKey = `__vite_ssr_import__`;
  11021. const ssrDynamicImportKey = `__vite_ssr_dynamic_import__`;
  11022. const ssrExportAllKey = `__vite_ssr_exportAll__`;
  11023. const ssrExportNameKey = `__vite_ssr_exportName__`;
  11024. const ssrImportMetaKey = `__vite_ssr_import_meta__`;
  11025. const hashbangRE = /^#!.*\n/;
  11026. async function ssrTransform(code, inMap, url, originalCode, options) {
  11027. if (options?.json?.stringify && isJSONRequest(url)) return ssrTransformJSON(code, inMap);
  11028. return ssrTransformScript(code, inMap, url, originalCode);
  11029. }
  11030. async function ssrTransformJSON(code, inMap) {
  11031. return {
  11032. code: code.replace("export default", `${ssrModuleExportsKey}.default =`),
  11033. map: inMap,
  11034. deps: [],
  11035. dynamicDeps: [],
  11036. ssr: true
  11037. };
  11038. }
  11039. async function ssrTransformScript(code, inMap, url, originalCode) {
  11040. const s = new MagicString(code);
  11041. let ast;
  11042. try {
  11043. ast = await parseAstAsync(code);
  11044. } catch (err) {
  11045. if (err.code === "PARSE_ERROR") {
  11046. err.message = `Parse failure: ${err.message}\n`;
  11047. err.id = url;
  11048. if (typeof err.pos === "number") {
  11049. err.loc = numberToPos(code, err.pos);
  11050. err.loc.file = url;
  11051. err.frame = generateCodeFrame(code, err.pos);
  11052. err.message += `At file: ${url}:${err.loc.line}:${err.loc.column}`;
  11053. } else err.message += `At file: ${url}`;
  11054. }
  11055. throw err;
  11056. }
  11057. let uid = 0;
  11058. const deps = /* @__PURE__ */ new Set();
  11059. const dynamicDeps = /* @__PURE__ */ new Set();
  11060. const idToImportMap = /* @__PURE__ */ new Map();
  11061. const declaredConst = /* @__PURE__ */ new Set();
  11062. const fileStartIndex = hashbangRE.exec(code)?.[0].length ?? 0;
  11063. let hoistIndex = fileStartIndex;
  11064. function defineImport(index, importNode, metadata) {
  11065. const source = importNode.source.value;
  11066. deps.add(source);
  11067. const metadataArg = (metadata?.importedNames?.length ?? 0) > 0 ? `, ${JSON.stringify(metadata)}` : "";
  11068. const importId = `__vite_ssr_import_${uid++}__`;
  11069. const transformedImport = `const ${importId} = await ${ssrImportKey}(${JSON.stringify(source)}${metadataArg});\n`;
  11070. s.update(importNode.start, importNode.end, transformedImport);
  11071. if (importNode.start === index) hoistIndex = importNode.end;
  11072. else s.move(importNode.start, importNode.end, index);
  11073. return importId;
  11074. }
  11075. function defineExport(name, local = name) {
  11076. s.appendLeft(fileStartIndex, `${ssrExportNameKey}(${JSON.stringify(name)}, () => { try { return ${local} } catch {} });\n`);
  11077. }
  11078. const imports = [];
  11079. const exports = [];
  11080. const reExportImportIdMap = /* @__PURE__ */ new Map();
  11081. for (const node of ast.body) if (node.type === "ImportDeclaration") imports.push(node);
  11082. else if (node.type === "ExportDefaultDeclaration") exports.push(node);
  11083. else if (node.type === "ExportNamedDeclaration" || node.type === "ExportAllDeclaration") {
  11084. imports.push(node);
  11085. exports.push(node);
  11086. }
  11087. for (const node of imports) {
  11088. if (node.type === "ExportNamedDeclaration") {
  11089. if (node.source) {
  11090. const importId = defineImport(hoistIndex, node, { importedNames: node.specifiers.map((s) => getIdentifierNameOrLiteralValue$1(s.local)) });
  11091. reExportImportIdMap.set(node, importId);
  11092. }
  11093. continue;
  11094. }
  11095. if (node.type === "ExportAllDeclaration") {
  11096. if (node.source) {
  11097. const importId = defineImport(hoistIndex, node);
  11098. reExportImportIdMap.set(node, importId);
  11099. }
  11100. continue;
  11101. }
  11102. const importId = defineImport(hoistIndex, node, { importedNames: node.specifiers.map((s) => {
  11103. if (s.type === "ImportSpecifier") return getIdentifierNameOrLiteralValue$1(s.imported);
  11104. else if (s.type === "ImportDefaultSpecifier") return "default";
  11105. }).filter(isDefined) });
  11106. for (const spec of node.specifiers) if (spec.type === "ImportSpecifier") if (spec.imported.type === "Identifier") idToImportMap.set(spec.local.name, `${importId}.${spec.imported.name}`);
  11107. else idToImportMap.set(spec.local.name, `${importId}[${JSON.stringify(spec.imported.value)}]`);
  11108. else if (spec.type === "ImportDefaultSpecifier") idToImportMap.set(spec.local.name, `${importId}.default`);
  11109. else idToImportMap.set(spec.local.name, importId);
  11110. }
  11111. for (const node of exports) {
  11112. if (node.type === "ExportNamedDeclaration") if (node.declaration) {
  11113. if (node.declaration.type === "FunctionDeclaration" || node.declaration.type === "ClassDeclaration") defineExport(node.declaration.id.name);
  11114. else {
  11115. const declaration = node.declaration;
  11116. for (const decl of declaration.declarations) {
  11117. const names = extract_names(decl.id);
  11118. for (const name of names) defineExport(name);
  11119. }
  11120. }
  11121. s.remove(node.start, node.declaration.start);
  11122. } else if (node.source) {
  11123. const importId = reExportImportIdMap.get(node);
  11124. for (const spec of node.specifiers) {
  11125. const exportedAs = getIdentifierNameOrLiteralValue$1(spec.exported);
  11126. if (spec.local.type === "Identifier") defineExport(exportedAs, `${importId}.${spec.local.name}`);
  11127. else defineExport(exportedAs, `${importId}[${JSON.stringify(spec.local.value)}]`);
  11128. }
  11129. } else {
  11130. s.remove(node.start, node.end);
  11131. for (const spec of node.specifiers) {
  11132. const local = spec.local.name;
  11133. const binding = idToImportMap.get(local);
  11134. defineExport(getIdentifierNameOrLiteralValue$1(spec.exported), binding || local);
  11135. }
  11136. }
  11137. if (node.type === "ExportDefaultDeclaration") if ("id" in node.declaration && node.declaration.id && !["FunctionExpression", "ClassExpression"].includes(node.declaration.type)) {
  11138. const { name } = node.declaration.id;
  11139. s.remove(node.start, node.start + 15);
  11140. defineExport("default", name);
  11141. } else {
  11142. const name = `__vite_ssr_export_default__`;
  11143. s.update(node.start, node.start + 14, `const ${name} =`);
  11144. defineExport("default", name);
  11145. }
  11146. if (node.type === "ExportAllDeclaration") {
  11147. const importId = reExportImportIdMap.get(node);
  11148. if (node.exported) defineExport(getIdentifierNameOrLiteralValue$1(node.exported), `${importId}`);
  11149. else s.appendLeft(node.end, `${ssrExportAllKey}(${importId});\n`);
  11150. }
  11151. }
  11152. walk(ast, {
  11153. onStatements(statements) {
  11154. for (let i = 0; i < statements.length - 1; i++) {
  11155. const stmt = statements[i];
  11156. if (code[stmt.end - 1] !== ";" && stmt.type !== "FunctionDeclaration" && stmt.type !== "ClassDeclaration" && stmt.type !== "BlockStatement" && stmt.type !== "ImportDeclaration") s.appendLeft(stmt.end, ";");
  11157. }
  11158. },
  11159. onIdentifier(id, parent, parentStack) {
  11160. const grandparent = parentStack[1];
  11161. const binding = idToImportMap.get(id.name);
  11162. if (!binding) return;
  11163. if (isStaticProperty(parent) && parent.shorthand) {
  11164. if (!isNodeInPattern(parent) || isInDestructuringAssignment(parent, parentStack)) s.appendLeft(id.end, `: ${binding}`);
  11165. } else if (parent.type === "PropertyDefinition" && grandparent?.type === "ClassBody" || parent.type === "ClassDeclaration" && id === parent.superClass) {
  11166. if (!declaredConst.has(id.name)) {
  11167. declaredConst.add(id.name);
  11168. const topNode = parentStack[parentStack.length - 2];
  11169. s.prependRight(topNode.start, `const ${id.name} = ${binding};\n`);
  11170. }
  11171. } else if (parent.type === "CallExpression") {
  11172. s.update(id.start, id.end, binding);
  11173. s.prependRight(id.start, `(0,`);
  11174. s.appendLeft(id.end, `)`);
  11175. } else if (!(parent.type === "ClassExpression" && id === parent.id)) s.update(id.start, id.end, binding);
  11176. },
  11177. onImportMeta(node) {
  11178. s.update(node.start, node.end, ssrImportMetaKey);
  11179. },
  11180. onDynamicImport(node) {
  11181. s.update(node.start, node.start + 6, ssrDynamicImportKey);
  11182. if (node.type === "ImportExpression" && node.source.type === "Literal") dynamicDeps.add(node.source.value);
  11183. }
  11184. });
  11185. let map;
  11186. if (inMap?.mappings === "") map = inMap;
  11187. else {
  11188. map = s.generateMap({ hires: "boundary" });
  11189. map.sources = [path.basename(url)];
  11190. map.sourcesContent = [originalCode];
  11191. if (inMap && inMap.mappings && "sources" in inMap && inMap.sources.length > 0) map = combineSourcemaps(url, [map, inMap]);
  11192. }
  11193. return {
  11194. code: s.toString(),
  11195. map,
  11196. ssr: true,
  11197. deps: [...deps],
  11198. dynamicDeps: [...dynamicDeps]
  11199. };
  11200. }
  11201. function getIdentifierNameOrLiteralValue$1(node) {
  11202. return node.type === "Identifier" ? node.name : node.value;
  11203. }
  11204. const isNodeInPatternWeakSet = /* @__PURE__ */ new WeakSet();
  11205. const setIsNodeInPattern = (node) => isNodeInPatternWeakSet.add(node);
  11206. const isNodeInPattern = (node) => isNodeInPatternWeakSet.has(node);
  11207. /**
  11208. * Same logic from \@vue/compiler-core & \@vue/compiler-sfc
  11209. * Except this is using acorn AST
  11210. */
  11211. function walk(root, { onIdentifier, onImportMeta, onDynamicImport, onStatements }) {
  11212. const parentStack = [];
  11213. const varKindStack = [];
  11214. const scopeMap = /* @__PURE__ */ new WeakMap();
  11215. const identifiers = [];
  11216. const setScope = (node, name) => {
  11217. let scopeIds = scopeMap.get(node);
  11218. if (scopeIds && scopeIds.has(name)) return;
  11219. if (!scopeIds) {
  11220. scopeIds = /* @__PURE__ */ new Set();
  11221. scopeMap.set(node, scopeIds);
  11222. }
  11223. scopeIds.add(name);
  11224. };
  11225. function isInScope(name, parents) {
  11226. return parents.some((node) => scopeMap.get(node)?.has(name));
  11227. }
  11228. function handlePattern(p, parentScope) {
  11229. if (p.type === "Identifier") setScope(parentScope, p.name);
  11230. else if (p.type === "RestElement") handlePattern(p.argument, parentScope);
  11231. else if (p.type === "ObjectPattern") p.properties.forEach((property) => {
  11232. if (property.type === "RestElement") setScope(parentScope, property.argument.name);
  11233. else handlePattern(property.value, parentScope);
  11234. });
  11235. else if (p.type === "ArrayPattern") p.elements.forEach((element) => {
  11236. if (element) handlePattern(element, parentScope);
  11237. });
  11238. else if (p.type === "AssignmentPattern") handlePattern(p.left, parentScope);
  11239. else setScope(parentScope, p.name);
  11240. }
  11241. walk$1(root, {
  11242. enter(node, parent) {
  11243. if (node.type === "ImportDeclaration") return this.skip();
  11244. if (node.type === "Program" || node.type === "BlockStatement" || node.type === "StaticBlock") onStatements(node.body);
  11245. else if (node.type === "SwitchCase") onStatements(node.consequent);
  11246. if (parent && !(parent.type === "IfStatement" && node === parent.alternate)) parentStack.unshift(parent);
  11247. if (node.type === "VariableDeclaration") varKindStack.unshift(node.kind);
  11248. if (node.type === "MetaProperty" && node.meta.name === "import") onImportMeta(node);
  11249. else if (node.type === "ImportExpression") onDynamicImport(node);
  11250. if (node.type === "Identifier") {
  11251. if (!isInScope(node.name, parentStack) && isRefIdentifier(node, parent, parentStack)) identifiers.push([node, parentStack.slice(0)]);
  11252. } else if (isFunction(node)) {
  11253. if (node.type === "FunctionDeclaration") {
  11254. const parentScope = findParentScope(parentStack);
  11255. if (parentScope) setScope(parentScope, node.id.name);
  11256. }
  11257. if (node.type === "FunctionExpression" && node.id) setScope(node, node.id.name);
  11258. node.params.forEach((p) => {
  11259. if (p.type === "ObjectPattern" || p.type === "ArrayPattern") {
  11260. handlePattern(p, node);
  11261. return;
  11262. }
  11263. walk$1(p.type === "AssignmentPattern" ? p.left : p, { enter(child, parent) {
  11264. if (parent?.type === "AssignmentPattern" && parent.right === child) return this.skip();
  11265. if (child.type !== "Identifier") return;
  11266. if (isStaticPropertyKey(child, parent)) return;
  11267. if (parent?.type === "TemplateLiteral" && parent.expressions.includes(child) || parent?.type === "CallExpression" && parent.callee === child) return;
  11268. setScope(node, child.name);
  11269. } });
  11270. });
  11271. } else if (node.type === "ClassDeclaration") {
  11272. const parentScope = findParentScope(parentStack);
  11273. if (parentScope) setScope(parentScope, node.id.name);
  11274. } else if (node.type === "ClassExpression" && node.id) setScope(node, node.id.name);
  11275. else if (node.type === "Property" && parent.type === "ObjectPattern") setIsNodeInPattern(node);
  11276. else if (node.type === "VariableDeclarator") {
  11277. const parentFunction = findParentScope(parentStack, varKindStack[0] === "var");
  11278. if (parentFunction) handlePattern(node.id, parentFunction);
  11279. } else if (node.type === "CatchClause" && node.param) handlePattern(node.param, node);
  11280. },
  11281. leave(node, parent) {
  11282. if (parent && !(parent.type === "IfStatement" && node === parent.alternate)) parentStack.shift();
  11283. if (node.type === "VariableDeclaration") varKindStack.shift();
  11284. }
  11285. });
  11286. identifiers.forEach(([node, stack]) => {
  11287. if (!isInScope(node.name, stack)) onIdentifier(node, stack[0], stack);
  11288. });
  11289. }
  11290. function isRefIdentifier(id, parent, parentStack) {
  11291. if (parent.type === "CatchClause" || (parent.type === "VariableDeclarator" || parent.type === "ClassDeclaration") && parent.id === id) return false;
  11292. if (isFunction(parent)) {
  11293. if (parent.id === id) return false;
  11294. if (parent.params.includes(id)) return false;
  11295. }
  11296. if (parent.type === "MethodDefinition" && !parent.computed) return false;
  11297. if (isStaticPropertyKey(id, parent)) return false;
  11298. if (isNodeInPattern(parent) && parent.value === id) return false;
  11299. if (parent.type === "ArrayPattern" && !isInDestructuringAssignment(parent, parentStack)) return false;
  11300. if (parent.type === "MemberExpression" && parent.property === id && !parent.computed) return false;
  11301. if (parent.type === "ExportSpecifier" || parent.type === "ExportAllDeclaration") return false;
  11302. if (id.name === "arguments") return false;
  11303. return true;
  11304. }
  11305. const isStaticProperty = (node) => node.type === "Property" && !node.computed;
  11306. const isStaticPropertyKey = (node, parent) => parent && isStaticProperty(parent) && parent.key === node;
  11307. const functionNodeTypeRE = /Function(?:Expression|Declaration)$|Method$/;
  11308. function isFunction(node) {
  11309. return functionNodeTypeRE.test(node.type);
  11310. }
  11311. const blockNodeTypeRE = /^BlockStatement$|^For(?:In|Of)?Statement$/;
  11312. function isBlock(node) {
  11313. return blockNodeTypeRE.test(node.type);
  11314. }
  11315. function findParentScope(parentStack, isVar = false) {
  11316. return parentStack.find(isVar ? isFunction : isBlock);
  11317. }
  11318. function isInDestructuringAssignment(parent, parentStack) {
  11319. if (parent.type === "Property" || parent.type === "ArrayPattern") return parentStack.some((i) => i.type === "AssignmentExpression");
  11320. return false;
  11321. }
  11322. //#endregion
  11323. //#region ../../node_modules/.pnpm/is-docker@3.0.0/node_modules/is-docker/index.js
  11324. let isDockerCached;
  11325. function hasDockerEnv() {
  11326. try {
  11327. fs.statSync("/.dockerenv");
  11328. return true;
  11329. } catch {
  11330. return false;
  11331. }
  11332. }
  11333. function hasDockerCGroup() {
  11334. try {
  11335. return fs.readFileSync("/proc/self/cgroup", "utf8").includes("docker");
  11336. } catch {
  11337. return false;
  11338. }
  11339. }
  11340. function isDocker() {
  11341. if (isDockerCached === void 0) isDockerCached = hasDockerEnv() || hasDockerCGroup();
  11342. return isDockerCached;
  11343. }
  11344. //#endregion
  11345. //#region ../../node_modules/.pnpm/is-inside-container@1.0.0/node_modules/is-inside-container/index.js
  11346. let cachedResult;
  11347. const hasContainerEnv = () => {
  11348. try {
  11349. fs.statSync("/run/.containerenv");
  11350. return true;
  11351. } catch {
  11352. return false;
  11353. }
  11354. };
  11355. function isInsideContainer() {
  11356. if (cachedResult === void 0) cachedResult = hasContainerEnv() || isDocker();
  11357. return cachedResult;
  11358. }
  11359. //#endregion
  11360. //#region ../../node_modules/.pnpm/is-wsl@3.1.0/node_modules/is-wsl/index.js
  11361. const isWsl = () => {
  11362. if (process$1.platform !== "linux") return false;
  11363. if (os.release().toLowerCase().includes("microsoft")) {
  11364. if (isInsideContainer()) return false;
  11365. return true;
  11366. }
  11367. try {
  11368. return fs.readFileSync("/proc/version", "utf8").toLowerCase().includes("microsoft") ? !isInsideContainer() : false;
  11369. } catch {
  11370. return false;
  11371. }
  11372. };
  11373. var is_wsl_default = process$1.env.__IS_WSL_TEST__ ? isWsl : isWsl();
  11374. //#endregion
  11375. //#region ../../node_modules/.pnpm/wsl-utils@0.1.0/node_modules/wsl-utils/index.js
  11376. const wslDrivesMountPoint = (() => {
  11377. const defaultMountPoint = "/mnt/";
  11378. let mountPoint;
  11379. return async function() {
  11380. if (mountPoint) return mountPoint;
  11381. const configFilePath = "/etc/wsl.conf";
  11382. let isConfigFileExists = false;
  11383. try {
  11384. await fsp.access(configFilePath, constants.F_OK);
  11385. isConfigFileExists = true;
  11386. } catch {}
  11387. if (!isConfigFileExists) return defaultMountPoint;
  11388. const configContent = await fsp.readFile(configFilePath, { encoding: "utf8" });
  11389. const configMountPoint = /(?<!#.*)root\s*=\s*(?<mountPoint>.*)/g.exec(configContent);
  11390. if (!configMountPoint) return defaultMountPoint;
  11391. mountPoint = configMountPoint.groups.mountPoint.trim();
  11392. mountPoint = mountPoint.endsWith("/") ? mountPoint : `${mountPoint}/`;
  11393. return mountPoint;
  11394. };
  11395. })();
  11396. const powerShellPathFromWsl = async () => {
  11397. return `${await wslDrivesMountPoint()}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`;
  11398. };
  11399. const powerShellPath = async () => {
  11400. if (is_wsl_default) return powerShellPathFromWsl();
  11401. return `${process$1.env.SYSTEMROOT || process$1.env.windir || String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;
  11402. };
  11403. //#endregion
  11404. //#region ../../node_modules/.pnpm/define-lazy-prop@3.0.0/node_modules/define-lazy-prop/index.js
  11405. function defineLazyProperty(object, propertyName, valueGetter) {
  11406. const define = (value) => Object.defineProperty(object, propertyName, {
  11407. value,
  11408. enumerable: true,
  11409. writable: true
  11410. });
  11411. Object.defineProperty(object, propertyName, {
  11412. configurable: true,
  11413. enumerable: true,
  11414. get() {
  11415. const result = valueGetter();
  11416. define(result);
  11417. return result;
  11418. },
  11419. set(value) {
  11420. define(value);
  11421. }
  11422. });
  11423. return object;
  11424. }
  11425. //#endregion
  11426. //#region ../../node_modules/.pnpm/default-browser-id@5.0.1/node_modules/default-browser-id/index.js
  11427. const execFileAsync$3 = promisify(execFile);
  11428. async function defaultBrowserId() {
  11429. if (process$1.platform !== "darwin") throw new Error("macOS only");
  11430. const { stdout } = await execFileAsync$3("defaults", [
  11431. "read",
  11432. "com.apple.LaunchServices/com.apple.launchservices.secure",
  11433. "LSHandlers"
  11434. ]);
  11435. const browserId = /LSHandlerRoleAll = "(?!-)(?<id>[^"]+?)";\s+?LSHandlerURLScheme = (?:http|https);/.exec(stdout)?.groups.id ?? "com.apple.Safari";
  11436. if (browserId === "com.apple.safari") return "com.apple.Safari";
  11437. return browserId;
  11438. }
  11439. //#endregion
  11440. //#region ../../node_modules/.pnpm/run-applescript@7.1.0/node_modules/run-applescript/index.js
  11441. const execFileAsync$2 = promisify(execFile);
  11442. async function runAppleScript(script, { humanReadableOutput = true, signal } = {}) {
  11443. if (process$1.platform !== "darwin") throw new Error("macOS only");
  11444. const outputArguments = humanReadableOutput ? [] : ["-ss"];
  11445. const execOptions = {};
  11446. if (signal) execOptions.signal = signal;
  11447. const { stdout } = await execFileAsync$2("osascript", [
  11448. "-e",
  11449. script,
  11450. outputArguments
  11451. ], execOptions);
  11452. return stdout.trim();
  11453. }
  11454. //#endregion
  11455. //#region ../../node_modules/.pnpm/bundle-name@4.1.0/node_modules/bundle-name/index.js
  11456. async function bundleName(bundleId) {
  11457. 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")`);
  11458. }
  11459. //#endregion
  11460. //#region ../../node_modules/.pnpm/default-browser@5.5.0/node_modules/default-browser/windows.js
  11461. const execFileAsync$1 = promisify(execFile);
  11462. const windowsBrowserProgIds = {
  11463. MSEdgeHTM: {
  11464. name: "Edge",
  11465. id: "com.microsoft.edge"
  11466. },
  11467. MSEdgeBHTML: {
  11468. name: "Edge Beta",
  11469. id: "com.microsoft.edge.beta"
  11470. },
  11471. MSEdgeDHTML: {
  11472. name: "Edge Dev",
  11473. id: "com.microsoft.edge.dev"
  11474. },
  11475. AppXq0fevzme2pys62n3e0fbqa7peapykr8v: {
  11476. name: "Edge",
  11477. id: "com.microsoft.edge.old"
  11478. },
  11479. ChromeHTML: {
  11480. name: "Chrome",
  11481. id: "com.google.chrome"
  11482. },
  11483. ChromeBHTML: {
  11484. name: "Chrome Beta",
  11485. id: "com.google.chrome.beta"
  11486. },
  11487. ChromeDHTML: {
  11488. name: "Chrome Dev",
  11489. id: "com.google.chrome.dev"
  11490. },
  11491. ChromiumHTM: {
  11492. name: "Chromium",
  11493. id: "org.chromium.Chromium"
  11494. },
  11495. BraveHTML: {
  11496. name: "Brave",
  11497. id: "com.brave.Browser"
  11498. },
  11499. BraveBHTML: {
  11500. name: "Brave Beta",
  11501. id: "com.brave.Browser.beta"
  11502. },
  11503. BraveDHTML: {
  11504. name: "Brave Dev",
  11505. id: "com.brave.Browser.dev"
  11506. },
  11507. BraveSSHTM: {
  11508. name: "Brave Nightly",
  11509. id: "com.brave.Browser.nightly"
  11510. },
  11511. FirefoxURL: {
  11512. name: "Firefox",
  11513. id: "org.mozilla.firefox"
  11514. },
  11515. OperaStable: {
  11516. name: "Opera",
  11517. id: "com.operasoftware.Opera"
  11518. },
  11519. VivaldiHTM: {
  11520. name: "Vivaldi",
  11521. id: "com.vivaldi.Vivaldi"
  11522. },
  11523. "IE.HTTP": {
  11524. name: "Internet Explorer",
  11525. id: "com.microsoft.ie"
  11526. }
  11527. };
  11528. new Map(Object.entries(windowsBrowserProgIds));
  11529. var UnknownBrowserError = class extends Error {};
  11530. async function defaultBrowser$1(_execFileAsync = execFileAsync$1) {
  11531. const { stdout } = await _execFileAsync("reg", [
  11532. "QUERY",
  11533. " HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http\\UserChoice",
  11534. "/v",
  11535. "ProgId"
  11536. ]);
  11537. const match = /ProgId\s*REG_SZ\s*(?<id>\S+)/.exec(stdout);
  11538. if (!match) throw new UnknownBrowserError(`Cannot find Windows browser in stdout: ${JSON.stringify(stdout)}`);
  11539. const { id } = match.groups;
  11540. const dotIndex = id.lastIndexOf(".");
  11541. const hyphenIndex = id.lastIndexOf("-");
  11542. const baseIdByDot = dotIndex === -1 ? void 0 : id.slice(0, dotIndex);
  11543. const baseIdByHyphen = hyphenIndex === -1 ? void 0 : id.slice(0, hyphenIndex);
  11544. return windowsBrowserProgIds[id] ?? windowsBrowserProgIds[baseIdByDot] ?? windowsBrowserProgIds[baseIdByHyphen] ?? {
  11545. name: id,
  11546. id
  11547. };
  11548. }
  11549. //#endregion
  11550. //#region ../../node_modules/.pnpm/default-browser@5.5.0/node_modules/default-browser/index.js
  11551. const execFileAsync = promisify(execFile);
  11552. const titleize = (string) => string.toLowerCase().replaceAll(/(?:^|\s|-)\S/g, (x) => x.toUpperCase());
  11553. async function defaultBrowser() {
  11554. if (process$1.platform === "darwin") {
  11555. const id = await defaultBrowserId();
  11556. return {
  11557. name: await bundleName(id),
  11558. id
  11559. };
  11560. }
  11561. if (process$1.platform === "linux") {
  11562. const { stdout } = await execFileAsync("xdg-mime", [
  11563. "query",
  11564. "default",
  11565. "x-scheme-handler/http"
  11566. ]);
  11567. const id = stdout.trim();
  11568. return {
  11569. name: titleize(id.replace(/.desktop$/, "").replace("-", " ")),
  11570. id
  11571. };
  11572. }
  11573. if (process$1.platform === "win32") return defaultBrowser$1();
  11574. throw new Error("Only macOS, Linux, and Windows are supported");
  11575. }
  11576. //#endregion
  11577. //#region ../../node_modules/.pnpm/open@10.2.0/node_modules/open/index.js
  11578. const execFile$1 = promisify(childProcess.execFile);
  11579. const __dirname = path.dirname(fileURLToPath(import.meta.url));
  11580. const localXdgOpenPath = path.join(__dirname, "xdg-open");
  11581. const { platform, arch } = process$1;
  11582. /**
  11583. Get the default browser name in Windows from WSL.
  11584. @returns {Promise<string>} Browser name.
  11585. */
  11586. async function getWindowsDefaultBrowserFromWsl() {
  11587. const powershellPath = await powerShellPath();
  11588. const rawCommand = String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`;
  11589. const { stdout } = await execFile$1(powershellPath, [
  11590. "-NoProfile",
  11591. "-NonInteractive",
  11592. "-ExecutionPolicy",
  11593. "Bypass",
  11594. "-EncodedCommand",
  11595. Buffer$1.from(rawCommand, "utf16le").toString("base64")
  11596. ], { encoding: "utf8" });
  11597. const progId = stdout.trim();
  11598. const browserMap = {
  11599. ChromeHTML: "com.google.chrome",
  11600. BraveHTML: "com.brave.Browser",
  11601. MSEdgeHTM: "com.microsoft.edge",
  11602. FirefoxURL: "org.mozilla.firefox"
  11603. };
  11604. return browserMap[progId] ? { id: browserMap[progId] } : {};
  11605. }
  11606. const pTryEach = async (array, mapper) => {
  11607. let latestError;
  11608. for (const item of array) try {
  11609. return await mapper(item);
  11610. } catch (error) {
  11611. latestError = error;
  11612. }
  11613. throw latestError;
  11614. };
  11615. const baseOpen = async (options) => {
  11616. options = {
  11617. wait: false,
  11618. background: false,
  11619. newInstance: false,
  11620. allowNonzeroExitCode: false,
  11621. ...options
  11622. };
  11623. if (Array.isArray(options.app)) return pTryEach(options.app, (singleApp) => baseOpen({
  11624. ...options,
  11625. app: singleApp
  11626. }));
  11627. let { name: app, arguments: appArguments = [] } = options.app ?? {};
  11628. appArguments = [...appArguments];
  11629. if (Array.isArray(app)) return pTryEach(app, (appName) => baseOpen({
  11630. ...options,
  11631. app: {
  11632. name: appName,
  11633. arguments: appArguments
  11634. }
  11635. }));
  11636. if (app === "browser" || app === "browserPrivate") {
  11637. const ids = {
  11638. "com.google.chrome": "chrome",
  11639. "google-chrome.desktop": "chrome",
  11640. "com.brave.Browser": "brave",
  11641. "org.mozilla.firefox": "firefox",
  11642. "firefox.desktop": "firefox",
  11643. "com.microsoft.msedge": "edge",
  11644. "com.microsoft.edge": "edge",
  11645. "com.microsoft.edgemac": "edge",
  11646. "microsoft-edge.desktop": "edge"
  11647. };
  11648. const flags = {
  11649. chrome: "--incognito",
  11650. brave: "--incognito",
  11651. firefox: "--private-window",
  11652. edge: "--inPrivate"
  11653. };
  11654. const browser = is_wsl_default ? await getWindowsDefaultBrowserFromWsl() : await defaultBrowser();
  11655. if (browser.id in ids) {
  11656. const browserName = ids[browser.id];
  11657. if (app === "browserPrivate") appArguments.push(flags[browserName]);
  11658. return baseOpen({
  11659. ...options,
  11660. app: {
  11661. name: apps[browserName],
  11662. arguments: appArguments
  11663. }
  11664. });
  11665. }
  11666. throw new Error(`${browser.name} is not supported as a default browser`);
  11667. }
  11668. let command;
  11669. const cliArguments = [];
  11670. const childProcessOptions = {};
  11671. if (platform === "darwin") {
  11672. command = "open";
  11673. if (options.wait) cliArguments.push("--wait-apps");
  11674. if (options.background) cliArguments.push("--background");
  11675. if (options.newInstance) cliArguments.push("--new");
  11676. if (app) cliArguments.push("-a", app);
  11677. } else if (platform === "win32" || is_wsl_default && !isInsideContainer() && !app) {
  11678. command = await powerShellPath();
  11679. cliArguments.push("-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-EncodedCommand");
  11680. if (!is_wsl_default) childProcessOptions.windowsVerbatimArguments = true;
  11681. const encodedArguments = ["Start"];
  11682. if (options.wait) encodedArguments.push("-Wait");
  11683. if (app) {
  11684. encodedArguments.push(`"\`"${app}\`""`);
  11685. if (options.target) appArguments.push(options.target);
  11686. } else if (options.target) encodedArguments.push(`"${options.target}"`);
  11687. if (appArguments.length > 0) {
  11688. appArguments = appArguments.map((argument) => `"\`"${argument}\`""`);
  11689. encodedArguments.push("-ArgumentList", appArguments.join(","));
  11690. }
  11691. options.target = Buffer$1.from(encodedArguments.join(" "), "utf16le").toString("base64");
  11692. } else {
  11693. if (app) command = app;
  11694. else {
  11695. const isBundled = !__dirname || __dirname === "/";
  11696. let exeLocalXdgOpen = false;
  11697. try {
  11698. await fsp.access(localXdgOpenPath, constants.X_OK);
  11699. exeLocalXdgOpen = true;
  11700. } catch {}
  11701. command = process$1.versions.electron ?? (platform === "android" || isBundled || !exeLocalXdgOpen) ? "xdg-open" : localXdgOpenPath;
  11702. }
  11703. if (appArguments.length > 0) cliArguments.push(...appArguments);
  11704. if (!options.wait) {
  11705. childProcessOptions.stdio = "ignore";
  11706. childProcessOptions.detached = true;
  11707. }
  11708. }
  11709. if (platform === "darwin" && appArguments.length > 0) cliArguments.push("--args", ...appArguments);
  11710. if (options.target) cliArguments.push(options.target);
  11711. const subprocess = childProcess.spawn(command, cliArguments, childProcessOptions);
  11712. if (options.wait) return new Promise((resolve, reject) => {
  11713. subprocess.once("error", reject);
  11714. subprocess.once("close", (exitCode) => {
  11715. if (!options.allowNonzeroExitCode && exitCode > 0) {
  11716. reject(/* @__PURE__ */ new Error(`Exited with code ${exitCode}`));
  11717. return;
  11718. }
  11719. resolve(subprocess);
  11720. });
  11721. });
  11722. subprocess.unref();
  11723. return subprocess;
  11724. };
  11725. const open = (target, options) => {
  11726. if (typeof target !== "string") throw new TypeError("Expected a `target`");
  11727. return baseOpen({
  11728. ...options,
  11729. target
  11730. });
  11731. };
  11732. function detectArchBinary(binary) {
  11733. if (typeof binary === "string" || Array.isArray(binary)) return binary;
  11734. const { [arch]: archBinary } = binary;
  11735. if (!archBinary) throw new Error(`${arch} is not supported`);
  11736. return archBinary;
  11737. }
  11738. function detectPlatformBinary({ [platform]: platformBinary }, { wsl }) {
  11739. if (wsl && is_wsl_default) return detectArchBinary(wsl);
  11740. if (!platformBinary) throw new Error(`${platform} is not supported`);
  11741. return detectArchBinary(platformBinary);
  11742. }
  11743. const apps = {};
  11744. defineLazyProperty(apps, "chrome", () => detectPlatformBinary({
  11745. darwin: "google chrome",
  11746. win32: "chrome",
  11747. linux: [
  11748. "google-chrome",
  11749. "google-chrome-stable",
  11750. "chromium"
  11751. ]
  11752. }, { wsl: {
  11753. ia32: "/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe",
  11754. x64: ["/mnt/c/Program Files/Google/Chrome/Application/chrome.exe", "/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe"]
  11755. } }));
  11756. defineLazyProperty(apps, "brave", () => detectPlatformBinary({
  11757. darwin: "brave browser",
  11758. win32: "brave",
  11759. linux: ["brave-browser", "brave"]
  11760. }, { wsl: {
  11761. ia32: "/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe",
  11762. x64: ["/mnt/c/Program Files/BraveSoftware/Brave-Browser/Application/brave.exe", "/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe"]
  11763. } }));
  11764. defineLazyProperty(apps, "firefox", () => detectPlatformBinary({
  11765. darwin: "firefox",
  11766. win32: String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,
  11767. linux: "firefox"
  11768. }, { wsl: "/mnt/c/Program Files/Mozilla Firefox/firefox.exe" }));
  11769. defineLazyProperty(apps, "edge", () => detectPlatformBinary({
  11770. darwin: "microsoft edge",
  11771. win32: "msedge",
  11772. linux: ["microsoft-edge", "microsoft-edge-dev"]
  11773. }, { wsl: "/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe" }));
  11774. defineLazyProperty(apps, "browser", () => "browser");
  11775. defineLazyProperty(apps, "browserPrivate", () => "browserPrivate");
  11776. //#endregion
  11777. //#region ../../node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/windows.js
  11778. var require_windows = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  11779. module.exports = isexe;
  11780. isexe.sync = sync;
  11781. var fs$5 = __require("fs");
  11782. function checkPathExt(path, options) {
  11783. var pathext = options.pathExt !== void 0 ? options.pathExt : process.env.PATHEXT;
  11784. if (!pathext) return true;
  11785. pathext = pathext.split(";");
  11786. if (pathext.indexOf("") !== -1) return true;
  11787. for (var i = 0; i < pathext.length; i++) {
  11788. var p = pathext[i].toLowerCase();
  11789. if (p && path.substr(-p.length).toLowerCase() === p) return true;
  11790. }
  11791. return false;
  11792. }
  11793. function checkStat(stat, path, options) {
  11794. if (!stat.isSymbolicLink() && !stat.isFile()) return false;
  11795. return checkPathExt(path, options);
  11796. }
  11797. function isexe(path, options, cb) {
  11798. fs$5.stat(path, function(er, stat) {
  11799. cb(er, er ? false : checkStat(stat, path, options));
  11800. });
  11801. }
  11802. function sync(path, options) {
  11803. return checkStat(fs$5.statSync(path), path, options);
  11804. }
  11805. }));
  11806. //#endregion
  11807. //#region ../../node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/mode.js
  11808. var require_mode = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  11809. module.exports = isexe;
  11810. isexe.sync = sync;
  11811. var fs$4 = __require("fs");
  11812. function isexe(path, options, cb) {
  11813. fs$4.stat(path, function(er, stat) {
  11814. cb(er, er ? false : checkStat(stat, options));
  11815. });
  11816. }
  11817. function sync(path, options) {
  11818. return checkStat(fs$4.statSync(path), options);
  11819. }
  11820. function checkStat(stat, options) {
  11821. return stat.isFile() && checkMode(stat, options);
  11822. }
  11823. function checkMode(stat, options) {
  11824. var mod = stat.mode;
  11825. var uid = stat.uid;
  11826. var gid = stat.gid;
  11827. var myUid = options.uid !== void 0 ? options.uid : process.getuid && process.getuid();
  11828. var myGid = options.gid !== void 0 ? options.gid : process.getgid && process.getgid();
  11829. var u = parseInt("100", 8);
  11830. var g = parseInt("010", 8);
  11831. var o = parseInt("001", 8);
  11832. var ug = u | g;
  11833. return mod & o || mod & g && gid === myGid || mod & u && uid === myUid || mod & ug && myUid === 0;
  11834. }
  11835. }));
  11836. //#endregion
  11837. //#region ../../node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/index.js
  11838. var require_isexe = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  11839. __require("fs");
  11840. var core;
  11841. if (process.platform === "win32" || global.TESTING_WINDOWS) core = require_windows();
  11842. else core = require_mode();
  11843. module.exports = isexe;
  11844. isexe.sync = sync;
  11845. function isexe(path, options, cb) {
  11846. if (typeof options === "function") {
  11847. cb = options;
  11848. options = {};
  11849. }
  11850. if (!cb) {
  11851. if (typeof Promise !== "function") throw new TypeError("callback not provided");
  11852. return new Promise(function(resolve, reject) {
  11853. isexe(path, options || {}, function(er, is) {
  11854. if (er) reject(er);
  11855. else resolve(is);
  11856. });
  11857. });
  11858. }
  11859. core(path, options || {}, function(er, is) {
  11860. if (er) {
  11861. if (er.code === "EACCES" || options && options.ignoreErrors) {
  11862. er = null;
  11863. is = false;
  11864. }
  11865. }
  11866. cb(er, is);
  11867. });
  11868. }
  11869. function sync(path, options) {
  11870. try {
  11871. return core.sync(path, options || {});
  11872. } catch (er) {
  11873. if (options && options.ignoreErrors || er.code === "EACCES") return false;
  11874. else throw er;
  11875. }
  11876. }
  11877. }));
  11878. //#endregion
  11879. //#region ../../node_modules/.pnpm/which@2.0.2/node_modules/which/which.js
  11880. var require_which = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  11881. const isWindows = process.platform === "win32" || process.env.OSTYPE === "cygwin" || process.env.OSTYPE === "msys";
  11882. const path$5 = __require("path");
  11883. const COLON = isWindows ? ";" : ":";
  11884. const isexe = require_isexe();
  11885. const getNotFoundError = (cmd) => Object.assign(/* @__PURE__ */ new Error(`not found: ${cmd}`), { code: "ENOENT" });
  11886. const getPathInfo = (cmd, opt) => {
  11887. const colon = opt.colon || COLON;
  11888. const pathEnv = cmd.match(/\//) || isWindows && cmd.match(/\\/) ? [""] : [...isWindows ? [process.cwd()] : [], ...(opt.path || process.env.PATH || "").split(colon)];
  11889. const pathExtExe = isWindows ? opt.pathExt || process.env.PATHEXT || ".EXE;.CMD;.BAT;.COM" : "";
  11890. const pathExt = isWindows ? pathExtExe.split(colon) : [""];
  11891. if (isWindows) {
  11892. if (cmd.indexOf(".") !== -1 && pathExt[0] !== "") pathExt.unshift("");
  11893. }
  11894. return {
  11895. pathEnv,
  11896. pathExt,
  11897. pathExtExe
  11898. };
  11899. };
  11900. const which = (cmd, opt, cb) => {
  11901. if (typeof opt === "function") {
  11902. cb = opt;
  11903. opt = {};
  11904. }
  11905. if (!opt) opt = {};
  11906. const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt);
  11907. const found = [];
  11908. const step = (i) => new Promise((resolve, reject) => {
  11909. if (i === pathEnv.length) return opt.all && found.length ? resolve(found) : reject(getNotFoundError(cmd));
  11910. const ppRaw = pathEnv[i];
  11911. const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw;
  11912. const pCmd = path$5.join(pathPart, cmd);
  11913. resolve(subStep(!pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd, i, 0));
  11914. });
  11915. const subStep = (p, i, ii) => new Promise((resolve, reject) => {
  11916. if (ii === pathExt.length) return resolve(step(i + 1));
  11917. const ext = pathExt[ii];
  11918. isexe(p + ext, { pathExt: pathExtExe }, (er, is) => {
  11919. if (!er && is) if (opt.all) found.push(p + ext);
  11920. else return resolve(p + ext);
  11921. return resolve(subStep(p, i, ii + 1));
  11922. });
  11923. });
  11924. return cb ? step(0).then((res) => cb(null, res), cb) : step(0);
  11925. };
  11926. const whichSync = (cmd, opt) => {
  11927. opt = opt || {};
  11928. const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt);
  11929. const found = [];
  11930. for (let i = 0; i < pathEnv.length; i++) {
  11931. const ppRaw = pathEnv[i];
  11932. const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw;
  11933. const pCmd = path$5.join(pathPart, cmd);
  11934. const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd;
  11935. for (let j = 0; j < pathExt.length; j++) {
  11936. const cur = p + pathExt[j];
  11937. try {
  11938. if (isexe.sync(cur, { pathExt: pathExtExe })) if (opt.all) found.push(cur);
  11939. else return cur;
  11940. } catch (ex) {}
  11941. }
  11942. }
  11943. if (opt.all && found.length) return found;
  11944. if (opt.nothrow) return null;
  11945. throw getNotFoundError(cmd);
  11946. };
  11947. module.exports = which;
  11948. which.sync = whichSync;
  11949. }));
  11950. //#endregion
  11951. //#region ../../node_modules/.pnpm/path-key@3.1.1/node_modules/path-key/index.js
  11952. var require_path_key = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  11953. const pathKey = (options = {}) => {
  11954. const environment = options.env || process.env;
  11955. if ((options.platform || process.platform) !== "win32") return "PATH";
  11956. return Object.keys(environment).reverse().find((key) => key.toUpperCase() === "PATH") || "Path";
  11957. };
  11958. module.exports = pathKey;
  11959. module.exports.default = pathKey;
  11960. }));
  11961. //#endregion
  11962. //#region ../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/resolveCommand.js
  11963. var require_resolveCommand = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  11964. const path$4 = __require("path");
  11965. const which = require_which();
  11966. const getPathKey = require_path_key();
  11967. function resolveCommandAttempt(parsed, withoutPathExt) {
  11968. const env = parsed.options.env || process.env;
  11969. const cwd = process.cwd();
  11970. const hasCustomCwd = parsed.options.cwd != null;
  11971. const shouldSwitchCwd = hasCustomCwd && process.chdir !== void 0 && !process.chdir.disabled;
  11972. if (shouldSwitchCwd) try {
  11973. process.chdir(parsed.options.cwd);
  11974. } catch (err) {}
  11975. let resolved;
  11976. try {
  11977. resolved = which.sync(parsed.command, {
  11978. path: env[getPathKey({ env })],
  11979. pathExt: withoutPathExt ? path$4.delimiter : void 0
  11980. });
  11981. } catch (e) {} finally {
  11982. if (shouldSwitchCwd) process.chdir(cwd);
  11983. }
  11984. if (resolved) resolved = path$4.resolve(hasCustomCwd ? parsed.options.cwd : "", resolved);
  11985. return resolved;
  11986. }
  11987. function resolveCommand(parsed) {
  11988. return resolveCommandAttempt(parsed) || resolveCommandAttempt(parsed, true);
  11989. }
  11990. module.exports = resolveCommand;
  11991. }));
  11992. //#endregion
  11993. //#region ../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/escape.js
  11994. var require_escape = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  11995. const metaCharsRegExp = /([()\][%!^"`<>&|;, *?])/g;
  11996. function escapeCommand(arg) {
  11997. arg = arg.replace(metaCharsRegExp, "^$1");
  11998. return arg;
  11999. }
  12000. function escapeArgument(arg, doubleEscapeMetaChars) {
  12001. arg = `${arg}`;
  12002. arg = arg.replace(/(?=(\\+?)?)\1"/g, "$1$1\\\"");
  12003. arg = arg.replace(/(?=(\\+?)?)\1$/, "$1$1");
  12004. arg = `"${arg}"`;
  12005. arg = arg.replace(metaCharsRegExp, "^$1");
  12006. if (doubleEscapeMetaChars) arg = arg.replace(metaCharsRegExp, "^$1");
  12007. return arg;
  12008. }
  12009. module.exports.command = escapeCommand;
  12010. module.exports.argument = escapeArgument;
  12011. }));
  12012. //#endregion
  12013. //#region ../../node_modules/.pnpm/shebang-regex@3.0.0/node_modules/shebang-regex/index.js
  12014. var require_shebang_regex = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  12015. module.exports = /^#!(.*)/;
  12016. }));
  12017. //#endregion
  12018. //#region ../../node_modules/.pnpm/shebang-command@2.0.0/node_modules/shebang-command/index.js
  12019. var require_shebang_command = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  12020. const shebangRegex = require_shebang_regex();
  12021. module.exports = (string = "") => {
  12022. const match = string.match(shebangRegex);
  12023. if (!match) return null;
  12024. const [path, argument] = match[0].replace(/#! ?/, "").split(" ");
  12025. const binary = path.split("/").pop();
  12026. if (binary === "env") return argument;
  12027. return argument ? `${binary} ${argument}` : binary;
  12028. };
  12029. }));
  12030. //#endregion
  12031. //#region ../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/readShebang.js
  12032. var require_readShebang = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  12033. const fs$3 = __require("fs");
  12034. const shebangCommand = require_shebang_command();
  12035. function readShebang(command) {
  12036. const size = 150;
  12037. const buffer = Buffer.alloc(size);
  12038. let fd;
  12039. try {
  12040. fd = fs$3.openSync(command, "r");
  12041. fs$3.readSync(fd, buffer, 0, size, 0);
  12042. fs$3.closeSync(fd);
  12043. } catch (e) {}
  12044. return shebangCommand(buffer.toString());
  12045. }
  12046. module.exports = readShebang;
  12047. }));
  12048. //#endregion
  12049. //#region ../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/parse.js
  12050. var require_parse = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  12051. const path$3 = __require("path");
  12052. const resolveCommand = require_resolveCommand();
  12053. const escape = require_escape();
  12054. const readShebang = require_readShebang();
  12055. const isWin = process.platform === "win32";
  12056. const isExecutableRegExp = /\.(?:com|exe)$/i;
  12057. const isCmdShimRegExp = /node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;
  12058. function detectShebang(parsed) {
  12059. parsed.file = resolveCommand(parsed);
  12060. const shebang = parsed.file && readShebang(parsed.file);
  12061. if (shebang) {
  12062. parsed.args.unshift(parsed.file);
  12063. parsed.command = shebang;
  12064. return resolveCommand(parsed);
  12065. }
  12066. return parsed.file;
  12067. }
  12068. function parseNonShell(parsed) {
  12069. if (!isWin) return parsed;
  12070. const commandFile = detectShebang(parsed);
  12071. const needsShell = !isExecutableRegExp.test(commandFile);
  12072. if (parsed.options.forceShell || needsShell) {
  12073. const needsDoubleEscapeMetaChars = isCmdShimRegExp.test(commandFile);
  12074. parsed.command = path$3.normalize(parsed.command);
  12075. parsed.command = escape.command(parsed.command);
  12076. parsed.args = parsed.args.map((arg) => escape.argument(arg, needsDoubleEscapeMetaChars));
  12077. parsed.args = [
  12078. "/d",
  12079. "/s",
  12080. "/c",
  12081. `"${[parsed.command].concat(parsed.args).join(" ")}"`
  12082. ];
  12083. parsed.command = process.env.comspec || "cmd.exe";
  12084. parsed.options.windowsVerbatimArguments = true;
  12085. }
  12086. return parsed;
  12087. }
  12088. function parse(command, args, options) {
  12089. if (args && !Array.isArray(args)) {
  12090. options = args;
  12091. args = null;
  12092. }
  12093. args = args ? args.slice(0) : [];
  12094. options = Object.assign({}, options);
  12095. const parsed = {
  12096. command,
  12097. args,
  12098. options,
  12099. file: void 0,
  12100. original: {
  12101. command,
  12102. args
  12103. }
  12104. };
  12105. return options.shell ? parsed : parseNonShell(parsed);
  12106. }
  12107. module.exports = parse;
  12108. }));
  12109. //#endregion
  12110. //#region ../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/enoent.js
  12111. var require_enoent = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  12112. const isWin = process.platform === "win32";
  12113. function notFoundError(original, syscall) {
  12114. return Object.assign(/* @__PURE__ */ new Error(`${syscall} ${original.command} ENOENT`), {
  12115. code: "ENOENT",
  12116. errno: "ENOENT",
  12117. syscall: `${syscall} ${original.command}`,
  12118. path: original.command,
  12119. spawnargs: original.args
  12120. });
  12121. }
  12122. function hookChildProcess(cp, parsed) {
  12123. if (!isWin) return;
  12124. const originalEmit = cp.emit;
  12125. cp.emit = function(name, arg1) {
  12126. if (name === "exit") {
  12127. const err = verifyENOENT(arg1, parsed);
  12128. if (err) return originalEmit.call(cp, "error", err);
  12129. }
  12130. return originalEmit.apply(cp, arguments);
  12131. };
  12132. }
  12133. function verifyENOENT(status, parsed) {
  12134. if (isWin && status === 1 && !parsed.file) return notFoundError(parsed.original, "spawn");
  12135. return null;
  12136. }
  12137. function verifyENOENTSync(status, parsed) {
  12138. if (isWin && status === 1 && !parsed.file) return notFoundError(parsed.original, "spawnSync");
  12139. return null;
  12140. }
  12141. module.exports = {
  12142. hookChildProcess,
  12143. verifyENOENT,
  12144. verifyENOENTSync,
  12145. notFoundError
  12146. };
  12147. }));
  12148. //#endregion
  12149. //#region src/node/server/openBrowser.ts
  12150. /**
  12151. * The following is modified based on source found in
  12152. * https://github.com/facebook/create-react-app
  12153. *
  12154. * MIT Licensed
  12155. * Copyright (c) 2015-present, Facebook, Inc.
  12156. * https://github.com/facebook/create-react-app/blob/main/LICENSE
  12157. *
  12158. */
  12159. var import_cross_spawn = /* @__PURE__ */ __toESM((/* @__PURE__ */ __commonJSMin(((exports, module) => {
  12160. const cp = __require("child_process");
  12161. const parse = require_parse();
  12162. const enoent = require_enoent();
  12163. function spawn(command, args, options) {
  12164. const parsed = parse(command, args, options);
  12165. const spawned = cp.spawn(parsed.command, parsed.args, parsed.options);
  12166. enoent.hookChildProcess(spawned, parsed);
  12167. return spawned;
  12168. }
  12169. function spawnSync(command, args, options) {
  12170. const parsed = parse(command, args, options);
  12171. const result = cp.spawnSync(parsed.command, parsed.args, parsed.options);
  12172. result.error = result.error || enoent.verifyENOENTSync(result.status, parsed);
  12173. return result;
  12174. }
  12175. module.exports = spawn;
  12176. module.exports.spawn = spawn;
  12177. module.exports.sync = spawnSync;
  12178. module.exports._parse = parse;
  12179. module.exports._enoent = enoent;
  12180. })))(), 1);
  12181. /**
  12182. * Reads the BROWSER environment variable and decides what to do with it.
  12183. */
  12184. function openBrowser(url, opt, logger) {
  12185. const browser = typeof opt === "string" ? opt : process.env.BROWSER || "";
  12186. if (browser.toLowerCase().endsWith(".js")) executeNodeScript(browser, url, logger);
  12187. else if (browser.toLowerCase() !== "none") startBrowserProcess(browser, process.env.BROWSER_ARGS ? process.env.BROWSER_ARGS.split(" ") : [], url, logger);
  12188. }
  12189. function executeNodeScript(scriptPath, url, logger) {
  12190. const extraArgs = process.argv.slice(2);
  12191. (0, import_cross_spawn.default)(process.execPath, [
  12192. scriptPath,
  12193. ...extraArgs,
  12194. url
  12195. ], { stdio: "inherit" }).on("close", (code) => {
  12196. 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 });
  12197. });
  12198. }
  12199. const supportedChromiumBrowsers = [
  12200. "Google Chrome Canary",
  12201. "Google Chrome Dev",
  12202. "Google Chrome Beta",
  12203. "Google Chrome",
  12204. "Microsoft Edge",
  12205. "Brave Browser",
  12206. "Vivaldi",
  12207. "Chromium"
  12208. ];
  12209. async function startBrowserProcess(browser, browserArgs, url, logger) {
  12210. const preferredOSXBrowser = browser === "google chrome" ? "Google Chrome" : browser;
  12211. if (process.platform === "darwin" && (!preferredOSXBrowser || supportedChromiumBrowsers.includes(preferredOSXBrowser))) try {
  12212. const ps = await execAsync("ps cax");
  12213. const openedBrowser = preferredOSXBrowser && ps.includes(preferredOSXBrowser) ? preferredOSXBrowser : supportedChromiumBrowsers.find((b) => ps.includes(b));
  12214. if (openedBrowser) {
  12215. await execAsync(`osascript openChrome.js "${url}" "${openedBrowser}"`, { cwd: join(VITE_PACKAGE_DIR, "bin") });
  12216. return true;
  12217. }
  12218. } catch {}
  12219. if (process.platform === "darwin" && browser === "open") browser = void 0;
  12220. try {
  12221. const options = browser ? { app: {
  12222. name: browser,
  12223. arguments: browserArgs
  12224. } } : {};
  12225. new Promise((_, reject) => {
  12226. open(url, options).then((subprocess) => {
  12227. subprocess.on("error", reject);
  12228. }).catch(reject);
  12229. }).catch((err) => {
  12230. logger.error(err.stack || err.message);
  12231. });
  12232. return true;
  12233. } catch {
  12234. return false;
  12235. }
  12236. }
  12237. function execAsync(command, options) {
  12238. return new Promise((resolve, reject) => {
  12239. exec(command, options, (error, stdout) => {
  12240. if (error) reject(error);
  12241. else resolve(stdout.toString());
  12242. });
  12243. });
  12244. }
  12245. //#endregion
  12246. //#region src/node/shortcuts.ts
  12247. function bindCLIShortcuts(server, opts, enabled = process.stdin.isTTY && !process.env.CI) {
  12248. if (!server.httpServer || !enabled) return;
  12249. const isDev = isDevServer(server);
  12250. const previousShortcuts = server._shortcutsState?.options.customShortcuts ?? [];
  12251. const newShortcuts = opts?.customShortcuts ?? [];
  12252. const previousKeys = new Set(previousShortcuts.map((s) => s.key));
  12253. const customShortcuts = [...newShortcuts.filter((s) => !previousKeys.has(s.key)), ...previousShortcuts.map((s) => newShortcuts.find((n) => n.key === s.key) ?? s)];
  12254. const newOptions = {
  12255. ...opts,
  12256. customShortcuts
  12257. };
  12258. 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"));
  12259. const shortcuts = customShortcuts.concat(isDev ? BASE_DEV_SHORTCUTS : BASE_PREVIEW_SHORTCUTS);
  12260. let actionRunning = false;
  12261. const onInput = async (input) => {
  12262. if (actionRunning) return;
  12263. input = input.trim().toLocaleLowerCase();
  12264. if (input === "h") {
  12265. const loggedKeys = /* @__PURE__ */ new Set();
  12266. server.config.logger.info("\n Shortcuts");
  12267. for (const shortcut of shortcuts) {
  12268. if (loggedKeys.has(shortcut.key)) continue;
  12269. loggedKeys.add(shortcut.key);
  12270. if (shortcut.action == null) continue;
  12271. server.config.logger.info(import_picocolors.default.dim(" press ") + import_picocolors.default.bold(`${shortcut.key} + enter`) + import_picocolors.default.dim(` to ${shortcut.description}`));
  12272. }
  12273. return;
  12274. }
  12275. const shortcut = shortcuts.find((shortcut) => shortcut.key === input);
  12276. if (!shortcut || shortcut.action == null) return;
  12277. actionRunning = true;
  12278. await shortcut.action(server);
  12279. actionRunning = false;
  12280. };
  12281. if (!server._shortcutsState) {
  12282. server._shortcutsState = {
  12283. rl: readline.createInterface({ input: process.stdin }),
  12284. options: newOptions
  12285. };
  12286. server.httpServer.on("close", () => {
  12287. if (server._shortcutsState) server._shortcutsState.rl.close();
  12288. });
  12289. } else {
  12290. server._shortcutsState.rl.removeAllListeners("line");
  12291. server._shortcutsState.options = newOptions;
  12292. }
  12293. server._shortcutsState.rl.on("line", onInput);
  12294. }
  12295. const BASE_DEV_SHORTCUTS = [
  12296. {
  12297. key: "r",
  12298. description: "restart the server",
  12299. async action(server) {
  12300. await restartServerWithUrls(server);
  12301. }
  12302. },
  12303. {
  12304. key: "u",
  12305. description: "show server url",
  12306. action(server) {
  12307. server.config.logger.info("");
  12308. server.printUrls();
  12309. }
  12310. },
  12311. {
  12312. key: "o",
  12313. description: "open in browser",
  12314. action(server) {
  12315. server.openBrowser();
  12316. }
  12317. },
  12318. {
  12319. key: "c",
  12320. description: "clear console",
  12321. action(server) {
  12322. server.config.logger.clearScreen("error");
  12323. }
  12324. },
  12325. {
  12326. key: "q",
  12327. description: "quit",
  12328. async action(server) {
  12329. try {
  12330. await server.close();
  12331. } finally {
  12332. process.exit();
  12333. }
  12334. }
  12335. }
  12336. ];
  12337. const BASE_PREVIEW_SHORTCUTS = [{
  12338. key: "o",
  12339. description: "open in browser",
  12340. action(server) {
  12341. const url = server.resolvedUrls?.local[0] ?? server.resolvedUrls?.network[0];
  12342. if (url) openBrowser(url, true, server.config.logger);
  12343. else server.config.logger.warn("No URL available to open in browser");
  12344. }
  12345. }, {
  12346. key: "q",
  12347. description: "quit",
  12348. async action(server) {
  12349. try {
  12350. await server.close();
  12351. } finally {
  12352. process.exit();
  12353. }
  12354. }
  12355. }];
  12356. //#endregion
  12357. //#region src/node/watch.ts
  12358. function getResolvedOutDirs(root, outDir, outputOptions) {
  12359. const resolvedOutDir = path.resolve(root, outDir);
  12360. if (!outputOptions) return new Set([resolvedOutDir]);
  12361. return new Set(arraify(outputOptions).map(({ dir }) => dir ? path.resolve(root, dir) : resolvedOutDir));
  12362. }
  12363. function resolveEmptyOutDir(emptyOutDir, root, outDirs, logger) {
  12364. if (emptyOutDir != null) return emptyOutDir;
  12365. for (const outDir of outDirs) if (!normalizePath(outDir).startsWith(withTrailingSlash(root))) {
  12366. 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`));
  12367. return false;
  12368. }
  12369. return true;
  12370. }
  12371. function resolveChokidarOptions(options, resolvedOutDirs, emptyOutDir, cacheDir) {
  12372. const { ignored: ignoredList, ...otherOptions } = options ?? {};
  12373. const ignored = [
  12374. "**/.git/**",
  12375. "**/node_modules/**",
  12376. "**/test-results/**",
  12377. escapePath(cacheDir) + "/**",
  12378. ...arraify(ignoredList || [])
  12379. ];
  12380. if (emptyOutDir) ignored.push(...[...resolvedOutDirs].map((outDir) => escapePath(outDir) + "/**"));
  12381. return {
  12382. ignored,
  12383. ignoreInitial: true,
  12384. ignorePermissionErrors: true,
  12385. ...otherOptions
  12386. };
  12387. }
  12388. function convertToWatcherOptions(options) {
  12389. if (!options) return;
  12390. return {
  12391. usePolling: options.usePolling,
  12392. pollInterval: options.interval
  12393. };
  12394. }
  12395. var NoopWatcher = class extends EventEmitter {
  12396. constructor(options) {
  12397. super();
  12398. this.options = options;
  12399. }
  12400. add() {
  12401. return this;
  12402. }
  12403. unwatch() {
  12404. return this;
  12405. }
  12406. getWatched() {
  12407. return {};
  12408. }
  12409. ref() {
  12410. return this;
  12411. }
  12412. unref() {
  12413. return this;
  12414. }
  12415. async close() {}
  12416. };
  12417. function createNoopWatcher(options) {
  12418. return new NoopWatcher(options);
  12419. }
  12420. //#endregion
  12421. //#region src/node/publicDir.ts
  12422. const publicFilesMap = /* @__PURE__ */ new WeakMap();
  12423. async function initPublicFiles(config) {
  12424. let fileNames;
  12425. try {
  12426. fileNames = await recursiveReaddir(config.publicDir);
  12427. } catch (e) {
  12428. if (e.code === "ERR_SYMLINK_IN_RECURSIVE_READDIR") return;
  12429. throw e;
  12430. }
  12431. const publicFiles = new Set(fileNames.map((fileName) => fileName.slice(config.publicDir.length)));
  12432. publicFilesMap.set(config, publicFiles);
  12433. return publicFiles;
  12434. }
  12435. function getPublicFiles(config) {
  12436. return publicFilesMap.get(config);
  12437. }
  12438. function checkPublicFile(url, config) {
  12439. const { publicDir } = config;
  12440. if (!publicDir || url[0] !== "/") return;
  12441. const fileName = cleanUrl(url);
  12442. const publicFiles = getPublicFiles(config);
  12443. if (publicFiles) return publicFiles.has(fileName) ? normalizePath(path.join(publicDir, fileName)) : void 0;
  12444. const publicFile = normalizePath(path.join(publicDir, fileName));
  12445. if (!publicFile.startsWith(withTrailingSlash(publicDir))) return;
  12446. return tryStatSync(publicFile)?.isFile() ? publicFile : void 0;
  12447. }
  12448. //#endregion
  12449. //#region ../../node_modules/.pnpm/ws@8.19.0/node_modules/ws/lib/constants.js
  12450. var require_constants = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  12451. const BINARY_TYPES = [
  12452. "nodebuffer",
  12453. "arraybuffer",
  12454. "fragments"
  12455. ];
  12456. const hasBlob = typeof Blob !== "undefined";
  12457. if (hasBlob) BINARY_TYPES.push("blob");
  12458. module.exports = {
  12459. BINARY_TYPES,
  12460. CLOSE_TIMEOUT: 3e4,
  12461. EMPTY_BUFFER: Buffer.alloc(0),
  12462. GUID: "258EAFA5-E914-47DA-95CA-C5AB0DC85B11",
  12463. hasBlob,
  12464. kForOnEventAttribute: Symbol("kIsForOnEventAttribute"),
  12465. kListener: Symbol("kListener"),
  12466. kStatusCode: Symbol("status-code"),
  12467. kWebSocket: Symbol("websocket"),
  12468. NOOP: () => {}
  12469. };
  12470. }));
  12471. //#endregion
  12472. //#region ../../node_modules/.pnpm/ws@8.19.0/node_modules/ws/lib/buffer-util.js
  12473. var require_buffer_util = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  12474. const { EMPTY_BUFFER } = require_constants();
  12475. const FastBuffer = Buffer[Symbol.species];
  12476. /**
  12477. * Merges an array of buffers into a new buffer.
  12478. *
  12479. * @param {Buffer[]} list The array of buffers to concat
  12480. * @param {Number} totalLength The total length of buffers in the list
  12481. * @return {Buffer} The resulting buffer
  12482. * @public
  12483. */
  12484. function concat(list, totalLength) {
  12485. if (list.length === 0) return EMPTY_BUFFER;
  12486. if (list.length === 1) return list[0];
  12487. const target = Buffer.allocUnsafe(totalLength);
  12488. let offset = 0;
  12489. for (let i = 0; i < list.length; i++) {
  12490. const buf = list[i];
  12491. target.set(buf, offset);
  12492. offset += buf.length;
  12493. }
  12494. if (offset < totalLength) return new FastBuffer(target.buffer, target.byteOffset, offset);
  12495. return target;
  12496. }
  12497. /**
  12498. * Masks a buffer using the given mask.
  12499. *
  12500. * @param {Buffer} source The buffer to mask
  12501. * @param {Buffer} mask The mask to use
  12502. * @param {Buffer} output The buffer where to store the result
  12503. * @param {Number} offset The offset at which to start writing
  12504. * @param {Number} length The number of bytes to mask.
  12505. * @public
  12506. */
  12507. function _mask(source, mask, output, offset, length) {
  12508. for (let i = 0; i < length; i++) output[offset + i] = source[i] ^ mask[i & 3];
  12509. }
  12510. /**
  12511. * Unmasks a buffer using the given mask.
  12512. *
  12513. * @param {Buffer} buffer The buffer to unmask
  12514. * @param {Buffer} mask The mask to use
  12515. * @public
  12516. */
  12517. function _unmask(buffer, mask) {
  12518. for (let i = 0; i < buffer.length; i++) buffer[i] ^= mask[i & 3];
  12519. }
  12520. /**
  12521. * Converts a buffer to an `ArrayBuffer`.
  12522. *
  12523. * @param {Buffer} buf The buffer to convert
  12524. * @return {ArrayBuffer} Converted buffer
  12525. * @public
  12526. */
  12527. function toArrayBuffer(buf) {
  12528. if (buf.length === buf.buffer.byteLength) return buf.buffer;
  12529. return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.length);
  12530. }
  12531. /**
  12532. * Converts `data` to a `Buffer`.
  12533. *
  12534. * @param {*} data The data to convert
  12535. * @return {Buffer} The buffer
  12536. * @throws {TypeError}
  12537. * @public
  12538. */
  12539. function toBuffer(data) {
  12540. toBuffer.readOnly = true;
  12541. if (Buffer.isBuffer(data)) return data;
  12542. let buf;
  12543. if (data instanceof ArrayBuffer) buf = new FastBuffer(data);
  12544. else if (ArrayBuffer.isView(data)) buf = new FastBuffer(data.buffer, data.byteOffset, data.byteLength);
  12545. else {
  12546. buf = Buffer.from(data);
  12547. toBuffer.readOnly = false;
  12548. }
  12549. return buf;
  12550. }
  12551. module.exports = {
  12552. concat,
  12553. mask: _mask,
  12554. toArrayBuffer,
  12555. toBuffer,
  12556. unmask: _unmask
  12557. };
  12558. /* istanbul ignore else */
  12559. if (!process.env.WS_NO_BUFFER_UTIL) try {
  12560. const bufferUtil = __require("bufferutil");
  12561. module.exports.mask = function(source, mask, output, offset, length) {
  12562. if (length < 48) _mask(source, mask, output, offset, length);
  12563. else bufferUtil.mask(source, mask, output, offset, length);
  12564. };
  12565. module.exports.unmask = function(buffer, mask) {
  12566. if (buffer.length < 32) _unmask(buffer, mask);
  12567. else bufferUtil.unmask(buffer, mask);
  12568. };
  12569. } catch (e) {}
  12570. }));
  12571. //#endregion
  12572. //#region ../../node_modules/.pnpm/ws@8.19.0/node_modules/ws/lib/limiter.js
  12573. var require_limiter = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  12574. const kDone = Symbol("kDone");
  12575. const kRun = Symbol("kRun");
  12576. /**
  12577. * A very simple job queue with adjustable concurrency. Adapted from
  12578. * https://github.com/STRML/async-limiter
  12579. */
  12580. var Limiter = class {
  12581. /**
  12582. * Creates a new `Limiter`.
  12583. *
  12584. * @param {Number} [concurrency=Infinity] The maximum number of jobs allowed
  12585. * to run concurrently
  12586. */
  12587. constructor(concurrency) {
  12588. this[kDone] = () => {
  12589. this.pending--;
  12590. this[kRun]();
  12591. };
  12592. this.concurrency = concurrency || Infinity;
  12593. this.jobs = [];
  12594. this.pending = 0;
  12595. }
  12596. /**
  12597. * Adds a job to the queue.
  12598. *
  12599. * @param {Function} job The job to run
  12600. * @public
  12601. */
  12602. add(job) {
  12603. this.jobs.push(job);
  12604. this[kRun]();
  12605. }
  12606. /**
  12607. * Removes a job from the queue and runs it if possible.
  12608. *
  12609. * @private
  12610. */
  12611. [kRun]() {
  12612. if (this.pending === this.concurrency) return;
  12613. if (this.jobs.length) {
  12614. const job = this.jobs.shift();
  12615. this.pending++;
  12616. job(this[kDone]);
  12617. }
  12618. }
  12619. };
  12620. module.exports = Limiter;
  12621. }));
  12622. //#endregion
  12623. //#region ../../node_modules/.pnpm/ws@8.19.0/node_modules/ws/lib/permessage-deflate.js
  12624. var require_permessage_deflate = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  12625. const zlib$1 = __require("zlib");
  12626. const bufferUtil = require_buffer_util();
  12627. const Limiter = require_limiter();
  12628. const { kStatusCode } = require_constants();
  12629. const FastBuffer = Buffer[Symbol.species];
  12630. const TRAILER = Buffer.from([
  12631. 0,
  12632. 0,
  12633. 255,
  12634. 255
  12635. ]);
  12636. const kPerMessageDeflate = Symbol("permessage-deflate");
  12637. const kTotalLength = Symbol("total-length");
  12638. const kCallback = Symbol("callback");
  12639. const kBuffers = Symbol("buffers");
  12640. const kError = Symbol("error");
  12641. let zlibLimiter;
  12642. /**
  12643. * permessage-deflate implementation.
  12644. */
  12645. var PerMessageDeflate = class {
  12646. /**
  12647. * Creates a PerMessageDeflate instance.
  12648. *
  12649. * @param {Object} [options] Configuration options
  12650. * @param {(Boolean|Number)} [options.clientMaxWindowBits] Advertise support
  12651. * for, or request, a custom client window size
  12652. * @param {Boolean} [options.clientNoContextTakeover=false] Advertise/
  12653. * acknowledge disabling of client context takeover
  12654. * @param {Number} [options.concurrencyLimit=10] The number of concurrent
  12655. * calls to zlib
  12656. * @param {(Boolean|Number)} [options.serverMaxWindowBits] Request/confirm the
  12657. * use of a custom server window size
  12658. * @param {Boolean} [options.serverNoContextTakeover=false] Request/accept
  12659. * disabling of server context takeover
  12660. * @param {Number} [options.threshold=1024] Size (in bytes) below which
  12661. * messages should not be compressed if context takeover is disabled
  12662. * @param {Object} [options.zlibDeflateOptions] Options to pass to zlib on
  12663. * deflate
  12664. * @param {Object} [options.zlibInflateOptions] Options to pass to zlib on
  12665. * inflate
  12666. * @param {Boolean} [isServer=false] Create the instance in either server or
  12667. * client mode
  12668. * @param {Number} [maxPayload=0] The maximum allowed message length
  12669. */
  12670. constructor(options, isServer, maxPayload) {
  12671. this._maxPayload = maxPayload | 0;
  12672. this._options = options || {};
  12673. this._threshold = this._options.threshold !== void 0 ? this._options.threshold : 1024;
  12674. this._isServer = !!isServer;
  12675. this._deflate = null;
  12676. this._inflate = null;
  12677. this.params = null;
  12678. if (!zlibLimiter) zlibLimiter = new Limiter(this._options.concurrencyLimit !== void 0 ? this._options.concurrencyLimit : 10);
  12679. }
  12680. /**
  12681. * @type {String}
  12682. */
  12683. static get extensionName() {
  12684. return "permessage-deflate";
  12685. }
  12686. /**
  12687. * Create an extension negotiation offer.
  12688. *
  12689. * @return {Object} Extension parameters
  12690. * @public
  12691. */
  12692. offer() {
  12693. const params = {};
  12694. if (this._options.serverNoContextTakeover) params.server_no_context_takeover = true;
  12695. if (this._options.clientNoContextTakeover) params.client_no_context_takeover = true;
  12696. if (this._options.serverMaxWindowBits) params.server_max_window_bits = this._options.serverMaxWindowBits;
  12697. if (this._options.clientMaxWindowBits) params.client_max_window_bits = this._options.clientMaxWindowBits;
  12698. else if (this._options.clientMaxWindowBits == null) params.client_max_window_bits = true;
  12699. return params;
  12700. }
  12701. /**
  12702. * Accept an extension negotiation offer/response.
  12703. *
  12704. * @param {Array} configurations The extension negotiation offers/reponse
  12705. * @return {Object} Accepted configuration
  12706. * @public
  12707. */
  12708. accept(configurations) {
  12709. configurations = this.normalizeParams(configurations);
  12710. this.params = this._isServer ? this.acceptAsServer(configurations) : this.acceptAsClient(configurations);
  12711. return this.params;
  12712. }
  12713. /**
  12714. * Releases all resources used by the extension.
  12715. *
  12716. * @public
  12717. */
  12718. cleanup() {
  12719. if (this._inflate) {
  12720. this._inflate.close();
  12721. this._inflate = null;
  12722. }
  12723. if (this._deflate) {
  12724. const callback = this._deflate[kCallback];
  12725. this._deflate.close();
  12726. this._deflate = null;
  12727. if (callback) callback(/* @__PURE__ */ new Error("The deflate stream was closed while data was being processed"));
  12728. }
  12729. }
  12730. /**
  12731. * Accept an extension negotiation offer.
  12732. *
  12733. * @param {Array} offers The extension negotiation offers
  12734. * @return {Object} Accepted configuration
  12735. * @private
  12736. */
  12737. acceptAsServer(offers) {
  12738. const opts = this._options;
  12739. const accepted = offers.find((params) => {
  12740. 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;
  12741. return true;
  12742. });
  12743. if (!accepted) throw new Error("None of the extension offers can be accepted");
  12744. if (opts.serverNoContextTakeover) accepted.server_no_context_takeover = true;
  12745. if (opts.clientNoContextTakeover) accepted.client_no_context_takeover = true;
  12746. if (typeof opts.serverMaxWindowBits === "number") accepted.server_max_window_bits = opts.serverMaxWindowBits;
  12747. if (typeof opts.clientMaxWindowBits === "number") accepted.client_max_window_bits = opts.clientMaxWindowBits;
  12748. else if (accepted.client_max_window_bits === true || opts.clientMaxWindowBits === false) delete accepted.client_max_window_bits;
  12749. return accepted;
  12750. }
  12751. /**
  12752. * Accept the extension negotiation response.
  12753. *
  12754. * @param {Array} response The extension negotiation response
  12755. * @return {Object} Accepted configuration
  12756. * @private
  12757. */
  12758. acceptAsClient(response) {
  12759. const params = response[0];
  12760. if (this._options.clientNoContextTakeover === false && params.client_no_context_takeover) throw new Error("Unexpected parameter \"client_no_context_takeover\"");
  12761. if (!params.client_max_window_bits) {
  12762. if (typeof this._options.clientMaxWindowBits === "number") params.client_max_window_bits = this._options.clientMaxWindowBits;
  12763. } 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\"");
  12764. return params;
  12765. }
  12766. /**
  12767. * Normalize parameters.
  12768. *
  12769. * @param {Array} configurations The extension negotiation offers/reponse
  12770. * @return {Array} The offers/response with normalized parameters
  12771. * @private
  12772. */
  12773. normalizeParams(configurations) {
  12774. configurations.forEach((params) => {
  12775. Object.keys(params).forEach((key) => {
  12776. let value = params[key];
  12777. if (value.length > 1) throw new Error(`Parameter "${key}" must have only a single value`);
  12778. value = value[0];
  12779. if (key === "client_max_window_bits") {
  12780. if (value !== true) {
  12781. const num = +value;
  12782. if (!Number.isInteger(num) || num < 8 || num > 15) throw new TypeError(`Invalid value for parameter "${key}": ${value}`);
  12783. value = num;
  12784. } else if (!this._isServer) throw new TypeError(`Invalid value for parameter "${key}": ${value}`);
  12785. } else if (key === "server_max_window_bits") {
  12786. const num = +value;
  12787. if (!Number.isInteger(num) || num < 8 || num > 15) throw new TypeError(`Invalid value for parameter "${key}": ${value}`);
  12788. value = num;
  12789. } else if (key === "client_no_context_takeover" || key === "server_no_context_takeover") {
  12790. if (value !== true) throw new TypeError(`Invalid value for parameter "${key}": ${value}`);
  12791. } else throw new Error(`Unknown parameter "${key}"`);
  12792. params[key] = value;
  12793. });
  12794. });
  12795. return configurations;
  12796. }
  12797. /**
  12798. * Decompress data. Concurrency limited.
  12799. *
  12800. * @param {Buffer} data Compressed data
  12801. * @param {Boolean} fin Specifies whether or not this is the last fragment
  12802. * @param {Function} callback Callback
  12803. * @public
  12804. */
  12805. decompress(data, fin, callback) {
  12806. zlibLimiter.add((done) => {
  12807. this._decompress(data, fin, (err, result) => {
  12808. done();
  12809. callback(err, result);
  12810. });
  12811. });
  12812. }
  12813. /**
  12814. * Compress data. Concurrency limited.
  12815. *
  12816. * @param {(Buffer|String)} data Data to compress
  12817. * @param {Boolean} fin Specifies whether or not this is the last fragment
  12818. * @param {Function} callback Callback
  12819. * @public
  12820. */
  12821. compress(data, fin, callback) {
  12822. zlibLimiter.add((done) => {
  12823. this._compress(data, fin, (err, result) => {
  12824. done();
  12825. callback(err, result);
  12826. });
  12827. });
  12828. }
  12829. /**
  12830. * Decompress data.
  12831. *
  12832. * @param {Buffer} data Compressed data
  12833. * @param {Boolean} fin Specifies whether or not this is the last fragment
  12834. * @param {Function} callback Callback
  12835. * @private
  12836. */
  12837. _decompress(data, fin, callback) {
  12838. const endpoint = this._isServer ? "client" : "server";
  12839. if (!this._inflate) {
  12840. const key = `${endpoint}_max_window_bits`;
  12841. const windowBits = typeof this.params[key] !== "number" ? zlib$1.Z_DEFAULT_WINDOWBITS : this.params[key];
  12842. this._inflate = zlib$1.createInflateRaw({
  12843. ...this._options.zlibInflateOptions,
  12844. windowBits
  12845. });
  12846. this._inflate[kPerMessageDeflate] = this;
  12847. this._inflate[kTotalLength] = 0;
  12848. this._inflate[kBuffers] = [];
  12849. this._inflate.on("error", inflateOnError);
  12850. this._inflate.on("data", inflateOnData);
  12851. }
  12852. this._inflate[kCallback] = callback;
  12853. this._inflate.write(data);
  12854. if (fin) this._inflate.write(TRAILER);
  12855. this._inflate.flush(() => {
  12856. const err = this._inflate[kError];
  12857. if (err) {
  12858. this._inflate.close();
  12859. this._inflate = null;
  12860. callback(err);
  12861. return;
  12862. }
  12863. const data = bufferUtil.concat(this._inflate[kBuffers], this._inflate[kTotalLength]);
  12864. if (this._inflate._readableState.endEmitted) {
  12865. this._inflate.close();
  12866. this._inflate = null;
  12867. } else {
  12868. this._inflate[kTotalLength] = 0;
  12869. this._inflate[kBuffers] = [];
  12870. if (fin && this.params[`${endpoint}_no_context_takeover`]) this._inflate.reset();
  12871. }
  12872. callback(null, data);
  12873. });
  12874. }
  12875. /**
  12876. * Compress data.
  12877. *
  12878. * @param {(Buffer|String)} data Data to compress
  12879. * @param {Boolean} fin Specifies whether or not this is the last fragment
  12880. * @param {Function} callback Callback
  12881. * @private
  12882. */
  12883. _compress(data, fin, callback) {
  12884. const endpoint = this._isServer ? "server" : "client";
  12885. if (!this._deflate) {
  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._deflate = zlib$1.createDeflateRaw({
  12889. ...this._options.zlibDeflateOptions,
  12890. windowBits
  12891. });
  12892. this._deflate[kTotalLength] = 0;
  12893. this._deflate[kBuffers] = [];
  12894. this._deflate.on("data", deflateOnData);
  12895. }
  12896. this._deflate[kCallback] = callback;
  12897. this._deflate.write(data);
  12898. this._deflate.flush(zlib$1.Z_SYNC_FLUSH, () => {
  12899. if (!this._deflate) return;
  12900. let data = bufferUtil.concat(this._deflate[kBuffers], this._deflate[kTotalLength]);
  12901. if (fin) data = new FastBuffer(data.buffer, data.byteOffset, data.length - 4);
  12902. this._deflate[kCallback] = null;
  12903. this._deflate[kTotalLength] = 0;
  12904. this._deflate[kBuffers] = [];
  12905. if (fin && this.params[`${endpoint}_no_context_takeover`]) this._deflate.reset();
  12906. callback(null, data);
  12907. });
  12908. }
  12909. };
  12910. module.exports = PerMessageDeflate;
  12911. /**
  12912. * The listener of the `zlib.DeflateRaw` stream `'data'` event.
  12913. *
  12914. * @param {Buffer} chunk A chunk of data
  12915. * @private
  12916. */
  12917. function deflateOnData(chunk) {
  12918. this[kBuffers].push(chunk);
  12919. this[kTotalLength] += chunk.length;
  12920. }
  12921. /**
  12922. * The listener of the `zlib.InflateRaw` stream `'data'` event.
  12923. *
  12924. * @param {Buffer} chunk A chunk of data
  12925. * @private
  12926. */
  12927. function inflateOnData(chunk) {
  12928. this[kTotalLength] += chunk.length;
  12929. if (this[kPerMessageDeflate]._maxPayload < 1 || this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload) {
  12930. this[kBuffers].push(chunk);
  12931. return;
  12932. }
  12933. this[kError] = /* @__PURE__ */ new RangeError("Max payload size exceeded");
  12934. this[kError].code = "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH";
  12935. this[kError][kStatusCode] = 1009;
  12936. this.removeListener("data", inflateOnData);
  12937. this.reset();
  12938. }
  12939. /**
  12940. * The listener of the `zlib.InflateRaw` stream `'error'` event.
  12941. *
  12942. * @param {Error} err The emitted error
  12943. * @private
  12944. */
  12945. function inflateOnError(err) {
  12946. this[kPerMessageDeflate]._inflate = null;
  12947. if (this[kError]) {
  12948. this[kCallback](this[kError]);
  12949. return;
  12950. }
  12951. err[kStatusCode] = 1007;
  12952. this[kCallback](err);
  12953. }
  12954. }));
  12955. //#endregion
  12956. //#region ../../node_modules/.pnpm/ws@8.19.0/node_modules/ws/lib/validation.js
  12957. var require_validation = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  12958. const { isUtf8 } = __require("buffer");
  12959. const { hasBlob } = require_constants();
  12960. const tokenChars = [
  12961. 0,
  12962. 0,
  12963. 0,
  12964. 0,
  12965. 0,
  12966. 0,
  12967. 0,
  12968. 0,
  12969. 0,
  12970. 0,
  12971. 0,
  12972. 0,
  12973. 0,
  12974. 0,
  12975. 0,
  12976. 0,
  12977. 0,
  12978. 0,
  12979. 0,
  12980. 0,
  12981. 0,
  12982. 0,
  12983. 0,
  12984. 0,
  12985. 0,
  12986. 0,
  12987. 0,
  12988. 0,
  12989. 0,
  12990. 0,
  12991. 0,
  12992. 0,
  12993. 0,
  12994. 1,
  12995. 0,
  12996. 1,
  12997. 1,
  12998. 1,
  12999. 1,
  13000. 1,
  13001. 0,
  13002. 0,
  13003. 1,
  13004. 1,
  13005. 0,
  13006. 1,
  13007. 1,
  13008. 0,
  13009. 1,
  13010. 1,
  13011. 1,
  13012. 1,
  13013. 1,
  13014. 1,
  13015. 1,
  13016. 1,
  13017. 1,
  13018. 1,
  13019. 0,
  13020. 0,
  13021. 0,
  13022. 0,
  13023. 0,
  13024. 0,
  13025. 0,
  13026. 1,
  13027. 1,
  13028. 1,
  13029. 1,
  13030. 1,
  13031. 1,
  13032. 1,
  13033. 1,
  13034. 1,
  13035. 1,
  13036. 1,
  13037. 1,
  13038. 1,
  13039. 1,
  13040. 1,
  13041. 1,
  13042. 1,
  13043. 1,
  13044. 1,
  13045. 1,
  13046. 1,
  13047. 1,
  13048. 1,
  13049. 1,
  13050. 1,
  13051. 1,
  13052. 0,
  13053. 0,
  13054. 0,
  13055. 1,
  13056. 1,
  13057. 1,
  13058. 1,
  13059. 1,
  13060. 1,
  13061. 1,
  13062. 1,
  13063. 1,
  13064. 1,
  13065. 1,
  13066. 1,
  13067. 1,
  13068. 1,
  13069. 1,
  13070. 1,
  13071. 1,
  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. 0,
  13085. 1,
  13086. 0,
  13087. 1,
  13088. 0
  13089. ];
  13090. /**
  13091. * Checks if a status code is allowed in a close frame.
  13092. *
  13093. * @param {Number} code The status code
  13094. * @return {Boolean} `true` if the status code is valid, else `false`
  13095. * @public
  13096. */
  13097. function isValidStatusCode(code) {
  13098. return code >= 1e3 && code <= 1014 && code !== 1004 && code !== 1005 && code !== 1006 || code >= 3e3 && code <= 4999;
  13099. }
  13100. /**
  13101. * Checks if a given buffer contains only correct UTF-8.
  13102. * Ported from https://www.cl.cam.ac.uk/%7Emgk25/ucs/utf8_check.c by
  13103. * Markus Kuhn.
  13104. *
  13105. * @param {Buffer} buf The buffer to check
  13106. * @return {Boolean} `true` if `buf` contains only correct UTF-8, else `false`
  13107. * @public
  13108. */
  13109. function _isValidUTF8(buf) {
  13110. const len = buf.length;
  13111. let i = 0;
  13112. while (i < len) if ((buf[i] & 128) === 0) i++;
  13113. else if ((buf[i] & 224) === 192) {
  13114. if (i + 1 === len || (buf[i + 1] & 192) !== 128 || (buf[i] & 254) === 192) return false;
  13115. i += 2;
  13116. } else if ((buf[i] & 240) === 224) {
  13117. 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;
  13118. i += 3;
  13119. } else if ((buf[i] & 248) === 240) {
  13120. 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;
  13121. i += 4;
  13122. } else return false;
  13123. return true;
  13124. }
  13125. /**
  13126. * Determines whether a value is a `Blob`.
  13127. *
  13128. * @param {*} value The value to be tested
  13129. * @return {Boolean} `true` if `value` is a `Blob`, else `false`
  13130. * @private
  13131. */
  13132. function isBlob(value) {
  13133. 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");
  13134. }
  13135. module.exports = {
  13136. isBlob,
  13137. isValidStatusCode,
  13138. isValidUTF8: _isValidUTF8,
  13139. tokenChars
  13140. };
  13141. if (isUtf8) module.exports.isValidUTF8 = function(buf) {
  13142. return buf.length < 24 ? _isValidUTF8(buf) : isUtf8(buf);
  13143. };
  13144. else if (!process.env.WS_NO_UTF_8_VALIDATE) try {
  13145. const isValidUTF8 = __require("utf-8-validate");
  13146. module.exports.isValidUTF8 = function(buf) {
  13147. return buf.length < 32 ? _isValidUTF8(buf) : isValidUTF8(buf);
  13148. };
  13149. } catch (e) {}
  13150. }));
  13151. //#endregion
  13152. //#region ../../node_modules/.pnpm/ws@8.19.0/node_modules/ws/lib/receiver.js
  13153. var require_receiver = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  13154. const { Writable: Writable$1 } = __require("stream");
  13155. const PerMessageDeflate = require_permessage_deflate();
  13156. const { BINARY_TYPES, EMPTY_BUFFER, kStatusCode, kWebSocket } = require_constants();
  13157. const { concat, toArrayBuffer, unmask } = require_buffer_util();
  13158. const { isValidStatusCode, isValidUTF8 } = require_validation();
  13159. const FastBuffer = Buffer[Symbol.species];
  13160. const GET_INFO = 0;
  13161. const GET_PAYLOAD_LENGTH_16 = 1;
  13162. const GET_PAYLOAD_LENGTH_64 = 2;
  13163. const GET_MASK = 3;
  13164. const GET_DATA = 4;
  13165. const INFLATING = 5;
  13166. const DEFER_EVENT = 6;
  13167. /**
  13168. * HyBi Receiver implementation.
  13169. *
  13170. * @extends Writable
  13171. */
  13172. var Receiver = class extends Writable$1 {
  13173. /**
  13174. * Creates a Receiver instance.
  13175. *
  13176. * @param {Object} [options] Options object
  13177. * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether
  13178. * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
  13179. * multiple times in the same tick
  13180. * @param {String} [options.binaryType=nodebuffer] The type for binary data
  13181. * @param {Object} [options.extensions] An object containing the negotiated
  13182. * extensions
  13183. * @param {Boolean} [options.isServer=false] Specifies whether to operate in
  13184. * client or server mode
  13185. * @param {Number} [options.maxPayload=0] The maximum allowed message length
  13186. * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
  13187. * not to skip UTF-8 validation for text and close messages
  13188. */
  13189. constructor(options = {}) {
  13190. super();
  13191. this._allowSynchronousEvents = options.allowSynchronousEvents !== void 0 ? options.allowSynchronousEvents : true;
  13192. this._binaryType = options.binaryType || BINARY_TYPES[0];
  13193. this._extensions = options.extensions || {};
  13194. this._isServer = !!options.isServer;
  13195. this._maxPayload = options.maxPayload | 0;
  13196. this._skipUTF8Validation = !!options.skipUTF8Validation;
  13197. this[kWebSocket] = void 0;
  13198. this._bufferedBytes = 0;
  13199. this._buffers = [];
  13200. this._compressed = false;
  13201. this._payloadLength = 0;
  13202. this._mask = void 0;
  13203. this._fragmented = 0;
  13204. this._masked = false;
  13205. this._fin = false;
  13206. this._opcode = 0;
  13207. this._totalPayloadLength = 0;
  13208. this._messageLength = 0;
  13209. this._fragments = [];
  13210. this._errored = false;
  13211. this._loop = false;
  13212. this._state = GET_INFO;
  13213. }
  13214. /**
  13215. * Implements `Writable.prototype._write()`.
  13216. *
  13217. * @param {Buffer} chunk The chunk of data to write
  13218. * @param {String} encoding The character encoding of `chunk`
  13219. * @param {Function} cb Callback
  13220. * @private
  13221. */
  13222. _write(chunk, encoding, cb) {
  13223. if (this._opcode === 8 && this._state == GET_INFO) return cb();
  13224. this._bufferedBytes += chunk.length;
  13225. this._buffers.push(chunk);
  13226. this.startLoop(cb);
  13227. }
  13228. /**
  13229. * Consumes `n` bytes from the buffered data.
  13230. *
  13231. * @param {Number} n The number of bytes to consume
  13232. * @return {Buffer} The consumed bytes
  13233. * @private
  13234. */
  13235. consume(n) {
  13236. this._bufferedBytes -= n;
  13237. if (n === this._buffers[0].length) return this._buffers.shift();
  13238. if (n < this._buffers[0].length) {
  13239. const buf = this._buffers[0];
  13240. this._buffers[0] = new FastBuffer(buf.buffer, buf.byteOffset + n, buf.length - n);
  13241. return new FastBuffer(buf.buffer, buf.byteOffset, n);
  13242. }
  13243. const dst = Buffer.allocUnsafe(n);
  13244. do {
  13245. const buf = this._buffers[0];
  13246. const offset = dst.length - n;
  13247. if (n >= buf.length) dst.set(this._buffers.shift(), offset);
  13248. else {
  13249. dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n), offset);
  13250. this._buffers[0] = new FastBuffer(buf.buffer, buf.byteOffset + n, buf.length - n);
  13251. }
  13252. n -= buf.length;
  13253. } while (n > 0);
  13254. return dst;
  13255. }
  13256. /**
  13257. * Starts the parsing loop.
  13258. *
  13259. * @param {Function} cb Callback
  13260. * @private
  13261. */
  13262. startLoop(cb) {
  13263. this._loop = true;
  13264. do
  13265. switch (this._state) {
  13266. case GET_INFO:
  13267. this.getInfo(cb);
  13268. break;
  13269. case GET_PAYLOAD_LENGTH_16:
  13270. this.getPayloadLength16(cb);
  13271. break;
  13272. case GET_PAYLOAD_LENGTH_64:
  13273. this.getPayloadLength64(cb);
  13274. break;
  13275. case GET_MASK:
  13276. this.getMask();
  13277. break;
  13278. case GET_DATA:
  13279. this.getData(cb);
  13280. break;
  13281. case INFLATING:
  13282. case DEFER_EVENT:
  13283. this._loop = false;
  13284. return;
  13285. }
  13286. while (this._loop);
  13287. if (!this._errored) cb();
  13288. }
  13289. /**
  13290. * Reads the first two bytes of a frame.
  13291. *
  13292. * @param {Function} cb Callback
  13293. * @private
  13294. */
  13295. getInfo(cb) {
  13296. if (this._bufferedBytes < 2) {
  13297. this._loop = false;
  13298. return;
  13299. }
  13300. const buf = this.consume(2);
  13301. if ((buf[0] & 48) !== 0) {
  13302. cb(this.createError(RangeError, "RSV2 and RSV3 must be clear", true, 1002, "WS_ERR_UNEXPECTED_RSV_2_3"));
  13303. return;
  13304. }
  13305. const compressed = (buf[0] & 64) === 64;
  13306. if (compressed && !this._extensions[PerMessageDeflate.extensionName]) {
  13307. cb(this.createError(RangeError, "RSV1 must be clear", true, 1002, "WS_ERR_UNEXPECTED_RSV_1"));
  13308. return;
  13309. }
  13310. this._fin = (buf[0] & 128) === 128;
  13311. this._opcode = buf[0] & 15;
  13312. this._payloadLength = buf[1] & 127;
  13313. if (this._opcode === 0) {
  13314. if (compressed) {
  13315. cb(this.createError(RangeError, "RSV1 must be clear", true, 1002, "WS_ERR_UNEXPECTED_RSV_1"));
  13316. return;
  13317. }
  13318. if (!this._fragmented) {
  13319. cb(this.createError(RangeError, "invalid opcode 0", true, 1002, "WS_ERR_INVALID_OPCODE"));
  13320. return;
  13321. }
  13322. this._opcode = this._fragmented;
  13323. } else if (this._opcode === 1 || this._opcode === 2) {
  13324. if (this._fragmented) {
  13325. cb(this.createError(RangeError, `invalid opcode ${this._opcode}`, true, 1002, "WS_ERR_INVALID_OPCODE"));
  13326. return;
  13327. }
  13328. this._compressed = compressed;
  13329. } else if (this._opcode > 7 && this._opcode < 11) {
  13330. if (!this._fin) {
  13331. cb(this.createError(RangeError, "FIN must be set", true, 1002, "WS_ERR_EXPECTED_FIN"));
  13332. return;
  13333. }
  13334. if (compressed) {
  13335. cb(this.createError(RangeError, "RSV1 must be clear", true, 1002, "WS_ERR_UNEXPECTED_RSV_1"));
  13336. return;
  13337. }
  13338. if (this._payloadLength > 125 || this._opcode === 8 && this._payloadLength === 1) {
  13339. cb(this.createError(RangeError, `invalid payload length ${this._payloadLength}`, true, 1002, "WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH"));
  13340. return;
  13341. }
  13342. } else {
  13343. cb(this.createError(RangeError, `invalid opcode ${this._opcode}`, true, 1002, "WS_ERR_INVALID_OPCODE"));
  13344. return;
  13345. }
  13346. if (!this._fin && !this._fragmented) this._fragmented = this._opcode;
  13347. this._masked = (buf[1] & 128) === 128;
  13348. if (this._isServer) {
  13349. if (!this._masked) {
  13350. cb(this.createError(RangeError, "MASK must be set", true, 1002, "WS_ERR_EXPECTED_MASK"));
  13351. return;
  13352. }
  13353. } else if (this._masked) {
  13354. cb(this.createError(RangeError, "MASK must be clear", true, 1002, "WS_ERR_UNEXPECTED_MASK"));
  13355. return;
  13356. }
  13357. if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16;
  13358. else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64;
  13359. else this.haveLength(cb);
  13360. }
  13361. /**
  13362. * Gets extended payload length (7+16).
  13363. *
  13364. * @param {Function} cb Callback
  13365. * @private
  13366. */
  13367. getPayloadLength16(cb) {
  13368. if (this._bufferedBytes < 2) {
  13369. this._loop = false;
  13370. return;
  13371. }
  13372. this._payloadLength = this.consume(2).readUInt16BE(0);
  13373. this.haveLength(cb);
  13374. }
  13375. /**
  13376. * Gets extended payload length (7+64).
  13377. *
  13378. * @param {Function} cb Callback
  13379. * @private
  13380. */
  13381. getPayloadLength64(cb) {
  13382. if (this._bufferedBytes < 8) {
  13383. this._loop = false;
  13384. return;
  13385. }
  13386. const buf = this.consume(8);
  13387. const num = buf.readUInt32BE(0);
  13388. if (num > Math.pow(2, 21) - 1) {
  13389. cb(this.createError(RangeError, "Unsupported WebSocket frame: payload length > 2^53 - 1", false, 1009, "WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH"));
  13390. return;
  13391. }
  13392. this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4);
  13393. this.haveLength(cb);
  13394. }
  13395. /**
  13396. * Payload length has been read.
  13397. *
  13398. * @param {Function} cb Callback
  13399. * @private
  13400. */
  13401. haveLength(cb) {
  13402. if (this._payloadLength && this._opcode < 8) {
  13403. this._totalPayloadLength += this._payloadLength;
  13404. if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) {
  13405. cb(this.createError(RangeError, "Max payload size exceeded", false, 1009, "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"));
  13406. return;
  13407. }
  13408. }
  13409. if (this._masked) this._state = GET_MASK;
  13410. else this._state = GET_DATA;
  13411. }
  13412. /**
  13413. * Reads mask bytes.
  13414. *
  13415. * @private
  13416. */
  13417. getMask() {
  13418. if (this._bufferedBytes < 4) {
  13419. this._loop = false;
  13420. return;
  13421. }
  13422. this._mask = this.consume(4);
  13423. this._state = GET_DATA;
  13424. }
  13425. /**
  13426. * Reads data bytes.
  13427. *
  13428. * @param {Function} cb Callback
  13429. * @private
  13430. */
  13431. getData(cb) {
  13432. let data = EMPTY_BUFFER;
  13433. if (this._payloadLength) {
  13434. if (this._bufferedBytes < this._payloadLength) {
  13435. this._loop = false;
  13436. return;
  13437. }
  13438. data = this.consume(this._payloadLength);
  13439. if (this._masked && (this._mask[0] | this._mask[1] | this._mask[2] | this._mask[3]) !== 0) unmask(data, this._mask);
  13440. }
  13441. if (this._opcode > 7) {
  13442. this.controlMessage(data, cb);
  13443. return;
  13444. }
  13445. if (this._compressed) {
  13446. this._state = INFLATING;
  13447. this.decompress(data, cb);
  13448. return;
  13449. }
  13450. if (data.length) {
  13451. this._messageLength = this._totalPayloadLength;
  13452. this._fragments.push(data);
  13453. }
  13454. this.dataMessage(cb);
  13455. }
  13456. /**
  13457. * Decompresses data.
  13458. *
  13459. * @param {Buffer} data Compressed data
  13460. * @param {Function} cb Callback
  13461. * @private
  13462. */
  13463. decompress(data, cb) {
  13464. this._extensions[PerMessageDeflate.extensionName].decompress(data, this._fin, (err, buf) => {
  13465. if (err) return cb(err);
  13466. if (buf.length) {
  13467. this._messageLength += buf.length;
  13468. if (this._messageLength > this._maxPayload && this._maxPayload > 0) {
  13469. cb(this.createError(RangeError, "Max payload size exceeded", false, 1009, "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"));
  13470. return;
  13471. }
  13472. this._fragments.push(buf);
  13473. }
  13474. this.dataMessage(cb);
  13475. if (this._state === GET_INFO) this.startLoop(cb);
  13476. });
  13477. }
  13478. /**
  13479. * Handles a data message.
  13480. *
  13481. * @param {Function} cb Callback
  13482. * @private
  13483. */
  13484. dataMessage(cb) {
  13485. if (!this._fin) {
  13486. this._state = GET_INFO;
  13487. return;
  13488. }
  13489. const messageLength = this._messageLength;
  13490. const fragments = this._fragments;
  13491. this._totalPayloadLength = 0;
  13492. this._messageLength = 0;
  13493. this._fragmented = 0;
  13494. this._fragments = [];
  13495. if (this._opcode === 2) {
  13496. let data;
  13497. if (this._binaryType === "nodebuffer") data = concat(fragments, messageLength);
  13498. else if (this._binaryType === "arraybuffer") data = toArrayBuffer(concat(fragments, messageLength));
  13499. else if (this._binaryType === "blob") data = new Blob(fragments);
  13500. else data = fragments;
  13501. if (this._allowSynchronousEvents) {
  13502. this.emit("message", data, true);
  13503. this._state = GET_INFO;
  13504. } else {
  13505. this._state = DEFER_EVENT;
  13506. setImmediate(() => {
  13507. this.emit("message", data, true);
  13508. this._state = GET_INFO;
  13509. this.startLoop(cb);
  13510. });
  13511. }
  13512. } else {
  13513. const buf = concat(fragments, messageLength);
  13514. if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
  13515. cb(this.createError(Error, "invalid UTF-8 sequence", true, 1007, "WS_ERR_INVALID_UTF8"));
  13516. return;
  13517. }
  13518. if (this._state === INFLATING || this._allowSynchronousEvents) {
  13519. this.emit("message", buf, false);
  13520. this._state = GET_INFO;
  13521. } else {
  13522. this._state = DEFER_EVENT;
  13523. setImmediate(() => {
  13524. this.emit("message", buf, false);
  13525. this._state = GET_INFO;
  13526. this.startLoop(cb);
  13527. });
  13528. }
  13529. }
  13530. }
  13531. /**
  13532. * Handles a control message.
  13533. *
  13534. * @param {Buffer} data Data to handle
  13535. * @return {(Error|RangeError|undefined)} A possible error
  13536. * @private
  13537. */
  13538. controlMessage(data, cb) {
  13539. if (this._opcode === 8) {
  13540. if (data.length === 0) {
  13541. this._loop = false;
  13542. this.emit("conclude", 1005, EMPTY_BUFFER);
  13543. this.end();
  13544. } else {
  13545. const code = data.readUInt16BE(0);
  13546. if (!isValidStatusCode(code)) {
  13547. cb(this.createError(RangeError, `invalid status code ${code}`, true, 1002, "WS_ERR_INVALID_CLOSE_CODE"));
  13548. return;
  13549. }
  13550. const buf = new FastBuffer(data.buffer, data.byteOffset + 2, data.length - 2);
  13551. if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
  13552. cb(this.createError(Error, "invalid UTF-8 sequence", true, 1007, "WS_ERR_INVALID_UTF8"));
  13553. return;
  13554. }
  13555. this._loop = false;
  13556. this.emit("conclude", code, buf);
  13557. this.end();
  13558. }
  13559. this._state = GET_INFO;
  13560. return;
  13561. }
  13562. if (this._allowSynchronousEvents) {
  13563. this.emit(this._opcode === 9 ? "ping" : "pong", data);
  13564. this._state = GET_INFO;
  13565. } else {
  13566. this._state = DEFER_EVENT;
  13567. setImmediate(() => {
  13568. this.emit(this._opcode === 9 ? "ping" : "pong", data);
  13569. this._state = GET_INFO;
  13570. this.startLoop(cb);
  13571. });
  13572. }
  13573. }
  13574. /**
  13575. * Builds an error object.
  13576. *
  13577. * @param {function(new:Error|RangeError)} ErrorCtor The error constructor
  13578. * @param {String} message The error message
  13579. * @param {Boolean} prefix Specifies whether or not to add a default prefix to
  13580. * `message`
  13581. * @param {Number} statusCode The status code
  13582. * @param {String} errorCode The exposed error code
  13583. * @return {(Error|RangeError)} The error
  13584. * @private
  13585. */
  13586. createError(ErrorCtor, message, prefix, statusCode, errorCode) {
  13587. this._loop = false;
  13588. this._errored = true;
  13589. const err = new ErrorCtor(prefix ? `Invalid WebSocket frame: ${message}` : message);
  13590. Error.captureStackTrace(err, this.createError);
  13591. err.code = errorCode;
  13592. err[kStatusCode] = statusCode;
  13593. return err;
  13594. }
  13595. };
  13596. module.exports = Receiver;
  13597. }));
  13598. //#endregion
  13599. //#region ../../node_modules/.pnpm/ws@8.19.0/node_modules/ws/lib/sender.js
  13600. var require_sender = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  13601. const { Duplex: Duplex$3 } = __require("stream");
  13602. const { randomFillSync } = __require("crypto");
  13603. const PerMessageDeflate = require_permessage_deflate();
  13604. const { EMPTY_BUFFER, kWebSocket, NOOP } = require_constants();
  13605. const { isBlob, isValidStatusCode } = require_validation();
  13606. const { mask: applyMask, toBuffer } = require_buffer_util();
  13607. const kByteLength = Symbol("kByteLength");
  13608. const maskBuffer = Buffer.alloc(4);
  13609. const RANDOM_POOL_SIZE = 8 * 1024;
  13610. let randomPool;
  13611. let randomPoolPointer = RANDOM_POOL_SIZE;
  13612. const DEFAULT = 0;
  13613. const DEFLATING = 1;
  13614. const GET_BLOB_DATA = 2;
  13615. module.exports = class Sender {
  13616. /**
  13617. * Creates a Sender instance.
  13618. *
  13619. * @param {Duplex} socket The connection socket
  13620. * @param {Object} [extensions] An object containing the negotiated extensions
  13621. * @param {Function} [generateMask] The function used to generate the masking
  13622. * key
  13623. */
  13624. constructor(socket, extensions, generateMask) {
  13625. this._extensions = extensions || {};
  13626. if (generateMask) {
  13627. this._generateMask = generateMask;
  13628. this._maskBuffer = Buffer.alloc(4);
  13629. }
  13630. this._socket = socket;
  13631. this._firstFragment = true;
  13632. this._compress = false;
  13633. this._bufferedBytes = 0;
  13634. this._queue = [];
  13635. this._state = DEFAULT;
  13636. this.onerror = NOOP;
  13637. this[kWebSocket] = void 0;
  13638. }
  13639. /**
  13640. * Frames a piece of data according to the HyBi WebSocket protocol.
  13641. *
  13642. * @param {(Buffer|String)} data The data to frame
  13643. * @param {Object} options Options object
  13644. * @param {Boolean} [options.fin=false] Specifies whether or not to set the
  13645. * FIN bit
  13646. * @param {Function} [options.generateMask] The function used to generate the
  13647. * masking key
  13648. * @param {Boolean} [options.mask=false] Specifies whether or not to mask
  13649. * `data`
  13650. * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
  13651. * key
  13652. * @param {Number} options.opcode The opcode
  13653. * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
  13654. * modified
  13655. * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
  13656. * RSV1 bit
  13657. * @return {(Buffer|String)[]} The framed data
  13658. * @public
  13659. */
  13660. static frame(data, options) {
  13661. let mask;
  13662. let merge = false;
  13663. let offset = 2;
  13664. let skipMasking = false;
  13665. if (options.mask) {
  13666. mask = options.maskBuffer || maskBuffer;
  13667. if (options.generateMask) options.generateMask(mask);
  13668. else {
  13669. if (randomPoolPointer === RANDOM_POOL_SIZE) {
  13670. /* istanbul ignore else */
  13671. if (randomPool === void 0) randomPool = Buffer.alloc(RANDOM_POOL_SIZE);
  13672. randomFillSync(randomPool, 0, RANDOM_POOL_SIZE);
  13673. randomPoolPointer = 0;
  13674. }
  13675. mask[0] = randomPool[randomPoolPointer++];
  13676. mask[1] = randomPool[randomPoolPointer++];
  13677. mask[2] = randomPool[randomPoolPointer++];
  13678. mask[3] = randomPool[randomPoolPointer++];
  13679. }
  13680. skipMasking = (mask[0] | mask[1] | mask[2] | mask[3]) === 0;
  13681. offset = 6;
  13682. }
  13683. let dataLength;
  13684. if (typeof data === "string") if ((!options.mask || skipMasking) && options[kByteLength] !== void 0) dataLength = options[kByteLength];
  13685. else {
  13686. data = Buffer.from(data);
  13687. dataLength = data.length;
  13688. }
  13689. else {
  13690. dataLength = data.length;
  13691. merge = options.mask && options.readOnly && !skipMasking;
  13692. }
  13693. let payloadLength = dataLength;
  13694. if (dataLength >= 65536) {
  13695. offset += 8;
  13696. payloadLength = 127;
  13697. } else if (dataLength > 125) {
  13698. offset += 2;
  13699. payloadLength = 126;
  13700. }
  13701. const target = Buffer.allocUnsafe(merge ? dataLength + offset : offset);
  13702. target[0] = options.fin ? options.opcode | 128 : options.opcode;
  13703. if (options.rsv1) target[0] |= 64;
  13704. target[1] = payloadLength;
  13705. if (payloadLength === 126) target.writeUInt16BE(dataLength, 2);
  13706. else if (payloadLength === 127) {
  13707. target[2] = target[3] = 0;
  13708. target.writeUIntBE(dataLength, 4, 6);
  13709. }
  13710. if (!options.mask) return [target, data];
  13711. target[1] |= 128;
  13712. target[offset - 4] = mask[0];
  13713. target[offset - 3] = mask[1];
  13714. target[offset - 2] = mask[2];
  13715. target[offset - 1] = mask[3];
  13716. if (skipMasking) return [target, data];
  13717. if (merge) {
  13718. applyMask(data, mask, target, offset, dataLength);
  13719. return [target];
  13720. }
  13721. applyMask(data, mask, data, 0, dataLength);
  13722. return [target, data];
  13723. }
  13724. /**
  13725. * Sends a close message to the other peer.
  13726. *
  13727. * @param {Number} [code] The status code component of the body
  13728. * @param {(String|Buffer)} [data] The message component of the body
  13729. * @param {Boolean} [mask=false] Specifies whether or not to mask the message
  13730. * @param {Function} [cb] Callback
  13731. * @public
  13732. */
  13733. close(code, data, mask, cb) {
  13734. let buf;
  13735. if (code === void 0) buf = EMPTY_BUFFER;
  13736. else if (typeof code !== "number" || !isValidStatusCode(code)) throw new TypeError("First argument must be a valid error code number");
  13737. else if (data === void 0 || !data.length) {
  13738. buf = Buffer.allocUnsafe(2);
  13739. buf.writeUInt16BE(code, 0);
  13740. } else {
  13741. const length = Buffer.byteLength(data);
  13742. if (length > 123) throw new RangeError("The message must not be greater than 123 bytes");
  13743. buf = Buffer.allocUnsafe(2 + length);
  13744. buf.writeUInt16BE(code, 0);
  13745. if (typeof data === "string") buf.write(data, 2);
  13746. else buf.set(data, 2);
  13747. }
  13748. const options = {
  13749. [kByteLength]: buf.length,
  13750. fin: true,
  13751. generateMask: this._generateMask,
  13752. mask,
  13753. maskBuffer: this._maskBuffer,
  13754. opcode: 8,
  13755. readOnly: false,
  13756. rsv1: false
  13757. };
  13758. if (this._state !== DEFAULT) this.enqueue([
  13759. this.dispatch,
  13760. buf,
  13761. false,
  13762. options,
  13763. cb
  13764. ]);
  13765. else this.sendFrame(Sender.frame(buf, options), cb);
  13766. }
  13767. /**
  13768. * Sends a ping message to the other peer.
  13769. *
  13770. * @param {*} data The message to send
  13771. * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
  13772. * @param {Function} [cb] Callback
  13773. * @public
  13774. */
  13775. ping(data, mask, cb) {
  13776. let byteLength;
  13777. let readOnly;
  13778. if (typeof data === "string") {
  13779. byteLength = Buffer.byteLength(data);
  13780. readOnly = false;
  13781. } else if (isBlob(data)) {
  13782. byteLength = data.size;
  13783. readOnly = false;
  13784. } else {
  13785. data = toBuffer(data);
  13786. byteLength = data.length;
  13787. readOnly = toBuffer.readOnly;
  13788. }
  13789. if (byteLength > 125) throw new RangeError("The data size must not be greater than 125 bytes");
  13790. const options = {
  13791. [kByteLength]: byteLength,
  13792. fin: true,
  13793. generateMask: this._generateMask,
  13794. mask,
  13795. maskBuffer: this._maskBuffer,
  13796. opcode: 9,
  13797. readOnly,
  13798. rsv1: false
  13799. };
  13800. if (isBlob(data)) if (this._state !== DEFAULT) this.enqueue([
  13801. this.getBlobData,
  13802. data,
  13803. false,
  13804. options,
  13805. cb
  13806. ]);
  13807. else this.getBlobData(data, false, options, cb);
  13808. else if (this._state !== DEFAULT) this.enqueue([
  13809. this.dispatch,
  13810. data,
  13811. false,
  13812. options,
  13813. cb
  13814. ]);
  13815. else this.sendFrame(Sender.frame(data, options), cb);
  13816. }
  13817. /**
  13818. * Sends a pong message to the other peer.
  13819. *
  13820. * @param {*} data The message to send
  13821. * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
  13822. * @param {Function} [cb] Callback
  13823. * @public
  13824. */
  13825. pong(data, mask, cb) {
  13826. let byteLength;
  13827. let readOnly;
  13828. if (typeof data === "string") {
  13829. byteLength = Buffer.byteLength(data);
  13830. readOnly = false;
  13831. } else if (isBlob(data)) {
  13832. byteLength = data.size;
  13833. readOnly = false;
  13834. } else {
  13835. data = toBuffer(data);
  13836. byteLength = data.length;
  13837. readOnly = toBuffer.readOnly;
  13838. }
  13839. if (byteLength > 125) throw new RangeError("The data size must not be greater than 125 bytes");
  13840. const options = {
  13841. [kByteLength]: byteLength,
  13842. fin: true,
  13843. generateMask: this._generateMask,
  13844. mask,
  13845. maskBuffer: this._maskBuffer,
  13846. opcode: 10,
  13847. readOnly,
  13848. rsv1: false
  13849. };
  13850. if (isBlob(data)) if (this._state !== DEFAULT) this.enqueue([
  13851. this.getBlobData,
  13852. data,
  13853. false,
  13854. options,
  13855. cb
  13856. ]);
  13857. else this.getBlobData(data, false, options, cb);
  13858. else if (this._state !== DEFAULT) this.enqueue([
  13859. this.dispatch,
  13860. data,
  13861. false,
  13862. options,
  13863. cb
  13864. ]);
  13865. else this.sendFrame(Sender.frame(data, options), cb);
  13866. }
  13867. /**
  13868. * Sends a data message to the other peer.
  13869. *
  13870. * @param {*} data The message to send
  13871. * @param {Object} options Options object
  13872. * @param {Boolean} [options.binary=false] Specifies whether `data` is binary
  13873. * or text
  13874. * @param {Boolean} [options.compress=false] Specifies whether or not to
  13875. * compress `data`
  13876. * @param {Boolean} [options.fin=false] Specifies whether the fragment is the
  13877. * last one
  13878. * @param {Boolean} [options.mask=false] Specifies whether or not to mask
  13879. * `data`
  13880. * @param {Function} [cb] Callback
  13881. * @public
  13882. */
  13883. send(data, options, cb) {
  13884. const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
  13885. let opcode = options.binary ? 2 : 1;
  13886. let rsv1 = options.compress;
  13887. let byteLength;
  13888. let readOnly;
  13889. if (typeof data === "string") {
  13890. byteLength = Buffer.byteLength(data);
  13891. readOnly = false;
  13892. } else if (isBlob(data)) {
  13893. byteLength = data.size;
  13894. readOnly = false;
  13895. } else {
  13896. data = toBuffer(data);
  13897. byteLength = data.length;
  13898. readOnly = toBuffer.readOnly;
  13899. }
  13900. if (this._firstFragment) {
  13901. this._firstFragment = false;
  13902. if (rsv1 && perMessageDeflate && perMessageDeflate.params[perMessageDeflate._isServer ? "server_no_context_takeover" : "client_no_context_takeover"]) rsv1 = byteLength >= perMessageDeflate._threshold;
  13903. this._compress = rsv1;
  13904. } else {
  13905. rsv1 = false;
  13906. opcode = 0;
  13907. }
  13908. if (options.fin) this._firstFragment = true;
  13909. const opts = {
  13910. [kByteLength]: byteLength,
  13911. fin: options.fin,
  13912. generateMask: this._generateMask,
  13913. mask: options.mask,
  13914. maskBuffer: this._maskBuffer,
  13915. opcode,
  13916. readOnly,
  13917. rsv1
  13918. };
  13919. if (isBlob(data)) if (this._state !== DEFAULT) this.enqueue([
  13920. this.getBlobData,
  13921. data,
  13922. this._compress,
  13923. opts,
  13924. cb
  13925. ]);
  13926. else this.getBlobData(data, this._compress, opts, cb);
  13927. else if (this._state !== DEFAULT) this.enqueue([
  13928. this.dispatch,
  13929. data,
  13930. this._compress,
  13931. opts,
  13932. cb
  13933. ]);
  13934. else this.dispatch(data, this._compress, opts, cb);
  13935. }
  13936. /**
  13937. * Gets the contents of a blob as binary data.
  13938. *
  13939. * @param {Blob} blob The blob
  13940. * @param {Boolean} [compress=false] Specifies whether or not to compress
  13941. * the data
  13942. * @param {Object} options Options object
  13943. * @param {Boolean} [options.fin=false] Specifies whether or not to set the
  13944. * FIN bit
  13945. * @param {Function} [options.generateMask] The function used to generate the
  13946. * masking key
  13947. * @param {Boolean} [options.mask=false] Specifies whether or not to mask
  13948. * `data`
  13949. * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
  13950. * key
  13951. * @param {Number} options.opcode The opcode
  13952. * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
  13953. * modified
  13954. * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
  13955. * RSV1 bit
  13956. * @param {Function} [cb] Callback
  13957. * @private
  13958. */
  13959. getBlobData(blob, compress, options, cb) {
  13960. this._bufferedBytes += options[kByteLength];
  13961. this._state = GET_BLOB_DATA;
  13962. blob.arrayBuffer().then((arrayBuffer) => {
  13963. if (this._socket.destroyed) {
  13964. const err = /* @__PURE__ */ new Error("The socket was closed while the blob was being read");
  13965. process.nextTick(callCallbacks, this, err, cb);
  13966. return;
  13967. }
  13968. this._bufferedBytes -= options[kByteLength];
  13969. const data = toBuffer(arrayBuffer);
  13970. if (!compress) {
  13971. this._state = DEFAULT;
  13972. this.sendFrame(Sender.frame(data, options), cb);
  13973. this.dequeue();
  13974. } else this.dispatch(data, compress, options, cb);
  13975. }).catch((err) => {
  13976. process.nextTick(onError, this, err, cb);
  13977. });
  13978. }
  13979. /**
  13980. * Dispatches a message.
  13981. *
  13982. * @param {(Buffer|String)} data The message to send
  13983. * @param {Boolean} [compress=false] Specifies whether or not to compress
  13984. * `data`
  13985. * @param {Object} options Options object
  13986. * @param {Boolean} [options.fin=false] Specifies whether or not to set the
  13987. * FIN bit
  13988. * @param {Function} [options.generateMask] The function used to generate the
  13989. * masking key
  13990. * @param {Boolean} [options.mask=false] Specifies whether or not to mask
  13991. * `data`
  13992. * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
  13993. * key
  13994. * @param {Number} options.opcode The opcode
  13995. * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
  13996. * modified
  13997. * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
  13998. * RSV1 bit
  13999. * @param {Function} [cb] Callback
  14000. * @private
  14001. */
  14002. dispatch(data, compress, options, cb) {
  14003. if (!compress) {
  14004. this.sendFrame(Sender.frame(data, options), cb);
  14005. return;
  14006. }
  14007. const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
  14008. this._bufferedBytes += options[kByteLength];
  14009. this._state = DEFLATING;
  14010. perMessageDeflate.compress(data, options.fin, (_, buf) => {
  14011. if (this._socket.destroyed) {
  14012. callCallbacks(this, /* @__PURE__ */ new Error("The socket was closed while data was being compressed"), cb);
  14013. return;
  14014. }
  14015. this._bufferedBytes -= options[kByteLength];
  14016. this._state = DEFAULT;
  14017. options.readOnly = false;
  14018. this.sendFrame(Sender.frame(buf, options), cb);
  14019. this.dequeue();
  14020. });
  14021. }
  14022. /**
  14023. * Executes queued send operations.
  14024. *
  14025. * @private
  14026. */
  14027. dequeue() {
  14028. while (this._state === DEFAULT && this._queue.length) {
  14029. const params = this._queue.shift();
  14030. this._bufferedBytes -= params[3][kByteLength];
  14031. Reflect.apply(params[0], this, params.slice(1));
  14032. }
  14033. }
  14034. /**
  14035. * Enqueues a send operation.
  14036. *
  14037. * @param {Array} params Send operation parameters.
  14038. * @private
  14039. */
  14040. enqueue(params) {
  14041. this._bufferedBytes += params[3][kByteLength];
  14042. this._queue.push(params);
  14043. }
  14044. /**
  14045. * Sends a frame.
  14046. *
  14047. * @param {(Buffer | String)[]} list The frame to send
  14048. * @param {Function} [cb] Callback
  14049. * @private
  14050. */
  14051. sendFrame(list, cb) {
  14052. if (list.length === 2) {
  14053. this._socket.cork();
  14054. this._socket.write(list[0]);
  14055. this._socket.write(list[1], cb);
  14056. this._socket.uncork();
  14057. } else this._socket.write(list[0], cb);
  14058. }
  14059. };
  14060. /**
  14061. * Calls queued callbacks with an error.
  14062. *
  14063. * @param {Sender} sender The `Sender` instance
  14064. * @param {Error} err The error to call the callbacks with
  14065. * @param {Function} [cb] The first callback
  14066. * @private
  14067. */
  14068. function callCallbacks(sender, err, cb) {
  14069. if (typeof cb === "function") cb(err);
  14070. for (let i = 0; i < sender._queue.length; i++) {
  14071. const params = sender._queue[i];
  14072. const callback = params[params.length - 1];
  14073. if (typeof callback === "function") callback(err);
  14074. }
  14075. }
  14076. /**
  14077. * Handles a `Sender` error.
  14078. *
  14079. * @param {Sender} sender The `Sender` instance
  14080. * @param {Error} err The error
  14081. * @param {Function} [cb] The first pending callback
  14082. * @private
  14083. */
  14084. function onError(sender, err, cb) {
  14085. callCallbacks(sender, err, cb);
  14086. sender.onerror(err);
  14087. }
  14088. }));
  14089. //#endregion
  14090. //#region ../../node_modules/.pnpm/ws@8.19.0/node_modules/ws/lib/event-target.js
  14091. var require_event_target = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  14092. const { kForOnEventAttribute, kListener } = require_constants();
  14093. const kCode = Symbol("kCode");
  14094. const kData = Symbol("kData");
  14095. const kError = Symbol("kError");
  14096. const kMessage = Symbol("kMessage");
  14097. const kReason = Symbol("kReason");
  14098. const kTarget = Symbol("kTarget");
  14099. const kType = Symbol("kType");
  14100. const kWasClean = Symbol("kWasClean");
  14101. /**
  14102. * Class representing an event.
  14103. */
  14104. var Event = class {
  14105. /**
  14106. * Create a new `Event`.
  14107. *
  14108. * @param {String} type The name of the event
  14109. * @throws {TypeError} If the `type` argument is not specified
  14110. */
  14111. constructor(type) {
  14112. this[kTarget] = null;
  14113. this[kType] = type;
  14114. }
  14115. /**
  14116. * @type {*}
  14117. */
  14118. get target() {
  14119. return this[kTarget];
  14120. }
  14121. /**
  14122. * @type {String}
  14123. */
  14124. get type() {
  14125. return this[kType];
  14126. }
  14127. };
  14128. Object.defineProperty(Event.prototype, "target", { enumerable: true });
  14129. Object.defineProperty(Event.prototype, "type", { enumerable: true });
  14130. /**
  14131. * Class representing a close event.
  14132. *
  14133. * @extends Event
  14134. */
  14135. var CloseEvent = class extends Event {
  14136. /**
  14137. * Create a new `CloseEvent`.
  14138. *
  14139. * @param {String} type The name of the event
  14140. * @param {Object} [options] A dictionary object that allows for setting
  14141. * attributes via object members of the same name
  14142. * @param {Number} [options.code=0] The status code explaining why the
  14143. * connection was closed
  14144. * @param {String} [options.reason=''] A human-readable string explaining why
  14145. * the connection was closed
  14146. * @param {Boolean} [options.wasClean=false] Indicates whether or not the
  14147. * connection was cleanly closed
  14148. */
  14149. constructor(type, options = {}) {
  14150. super(type);
  14151. this[kCode] = options.code === void 0 ? 0 : options.code;
  14152. this[kReason] = options.reason === void 0 ? "" : options.reason;
  14153. this[kWasClean] = options.wasClean === void 0 ? false : options.wasClean;
  14154. }
  14155. /**
  14156. * @type {Number}
  14157. */
  14158. get code() {
  14159. return this[kCode];
  14160. }
  14161. /**
  14162. * @type {String}
  14163. */
  14164. get reason() {
  14165. return this[kReason];
  14166. }
  14167. /**
  14168. * @type {Boolean}
  14169. */
  14170. get wasClean() {
  14171. return this[kWasClean];
  14172. }
  14173. };
  14174. Object.defineProperty(CloseEvent.prototype, "code", { enumerable: true });
  14175. Object.defineProperty(CloseEvent.prototype, "reason", { enumerable: true });
  14176. Object.defineProperty(CloseEvent.prototype, "wasClean", { enumerable: true });
  14177. /**
  14178. * Class representing an error event.
  14179. *
  14180. * @extends Event
  14181. */
  14182. var ErrorEvent = class extends Event {
  14183. /**
  14184. * Create a new `ErrorEvent`.
  14185. *
  14186. * @param {String} type The name of the event
  14187. * @param {Object} [options] A dictionary object that allows for setting
  14188. * attributes via object members of the same name
  14189. * @param {*} [options.error=null] The error that generated this event
  14190. * @param {String} [options.message=''] The error message
  14191. */
  14192. constructor(type, options = {}) {
  14193. super(type);
  14194. this[kError] = options.error === void 0 ? null : options.error;
  14195. this[kMessage] = options.message === void 0 ? "" : options.message;
  14196. }
  14197. /**
  14198. * @type {*}
  14199. */
  14200. get error() {
  14201. return this[kError];
  14202. }
  14203. /**
  14204. * @type {String}
  14205. */
  14206. get message() {
  14207. return this[kMessage];
  14208. }
  14209. };
  14210. Object.defineProperty(ErrorEvent.prototype, "error", { enumerable: true });
  14211. Object.defineProperty(ErrorEvent.prototype, "message", { enumerable: true });
  14212. /**
  14213. * Class representing a message event.
  14214. *
  14215. * @extends Event
  14216. */
  14217. var MessageEvent = class extends Event {
  14218. /**
  14219. * Create a new `MessageEvent`.
  14220. *
  14221. * @param {String} type The name of the event
  14222. * @param {Object} [options] A dictionary object that allows for setting
  14223. * attributes via object members of the same name
  14224. * @param {*} [options.data=null] The message content
  14225. */
  14226. constructor(type, options = {}) {
  14227. super(type);
  14228. this[kData] = options.data === void 0 ? null : options.data;
  14229. }
  14230. /**
  14231. * @type {*}
  14232. */
  14233. get data() {
  14234. return this[kData];
  14235. }
  14236. };
  14237. Object.defineProperty(MessageEvent.prototype, "data", { enumerable: true });
  14238. module.exports = {
  14239. CloseEvent,
  14240. ErrorEvent,
  14241. Event,
  14242. EventTarget: {
  14243. addEventListener(type, handler, options = {}) {
  14244. for (const listener of this.listeners(type)) if (!options[kForOnEventAttribute] && listener[kListener] === handler && !listener[kForOnEventAttribute]) return;
  14245. let wrapper;
  14246. if (type === "message") wrapper = function onMessage(data, isBinary) {
  14247. const event = new MessageEvent("message", { data: isBinary ? data : data.toString() });
  14248. event[kTarget] = this;
  14249. callListener(handler, this, event);
  14250. };
  14251. else if (type === "close") wrapper = function onClose(code, message) {
  14252. const event = new CloseEvent("close", {
  14253. code,
  14254. reason: message.toString(),
  14255. wasClean: this._closeFrameReceived && this._closeFrameSent
  14256. });
  14257. event[kTarget] = this;
  14258. callListener(handler, this, event);
  14259. };
  14260. else if (type === "error") wrapper = function onError(error) {
  14261. const event = new ErrorEvent("error", {
  14262. error,
  14263. message: error.message
  14264. });
  14265. event[kTarget] = this;
  14266. callListener(handler, this, event);
  14267. };
  14268. else if (type === "open") wrapper = function onOpen() {
  14269. const event = new Event("open");
  14270. event[kTarget] = this;
  14271. callListener(handler, this, event);
  14272. };
  14273. else return;
  14274. wrapper[kForOnEventAttribute] = !!options[kForOnEventAttribute];
  14275. wrapper[kListener] = handler;
  14276. if (options.once) this.once(type, wrapper);
  14277. else this.on(type, wrapper);
  14278. },
  14279. removeEventListener(type, handler) {
  14280. for (const listener of this.listeners(type)) if (listener[kListener] === handler && !listener[kForOnEventAttribute]) {
  14281. this.removeListener(type, listener);
  14282. break;
  14283. }
  14284. }
  14285. },
  14286. MessageEvent
  14287. };
  14288. /**
  14289. * Call an event listener
  14290. *
  14291. * @param {(Function|Object)} listener The listener to call
  14292. * @param {*} thisArg The value to use as `this`` when calling the listener
  14293. * @param {Event} event The event to pass to the listener
  14294. * @private
  14295. */
  14296. function callListener(listener, thisArg, event) {
  14297. if (typeof listener === "object" && listener.handleEvent) listener.handleEvent.call(listener, event);
  14298. else listener.call(thisArg, event);
  14299. }
  14300. }));
  14301. //#endregion
  14302. //#region ../../node_modules/.pnpm/ws@8.19.0/node_modules/ws/lib/extension.js
  14303. var require_extension = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  14304. const { tokenChars } = require_validation();
  14305. /**
  14306. * Adds an offer to the map of extension offers or a parameter to the map of
  14307. * parameters.
  14308. *
  14309. * @param {Object} dest The map of extension offers or parameters
  14310. * @param {String} name The extension or parameter name
  14311. * @param {(Object|Boolean|String)} elem The extension parameters or the
  14312. * parameter value
  14313. * @private
  14314. */
  14315. function push(dest, name, elem) {
  14316. if (dest[name] === void 0) dest[name] = [elem];
  14317. else dest[name].push(elem);
  14318. }
  14319. /**
  14320. * Parses the `Sec-WebSocket-Extensions` header into an object.
  14321. *
  14322. * @param {String} header The field value of the header
  14323. * @return {Object} The parsed object
  14324. * @public
  14325. */
  14326. function parse(header) {
  14327. const offers = Object.create(null);
  14328. let params = Object.create(null);
  14329. let mustUnescape = false;
  14330. let isEscaping = false;
  14331. let inQuotes = false;
  14332. let extensionName;
  14333. let paramName;
  14334. let start = -1;
  14335. let code = -1;
  14336. let end = -1;
  14337. let i = 0;
  14338. for (; i < header.length; i++) {
  14339. code = header.charCodeAt(i);
  14340. if (extensionName === void 0) if (end === -1 && tokenChars[code] === 1) {
  14341. if (start === -1) start = i;
  14342. } else if (i !== 0 && (code === 32 || code === 9)) {
  14343. if (end === -1 && start !== -1) end = i;
  14344. } else if (code === 59 || code === 44) {
  14345. if (start === -1) throw new SyntaxError(`Unexpected character at index ${i}`);
  14346. if (end === -1) end = i;
  14347. const name = header.slice(start, end);
  14348. if (code === 44) {
  14349. push(offers, name, params);
  14350. params = Object.create(null);
  14351. } else extensionName = name;
  14352. start = end = -1;
  14353. } else throw new SyntaxError(`Unexpected character at index ${i}`);
  14354. else if (paramName === void 0) if (end === -1 && tokenChars[code] === 1) {
  14355. if (start === -1) start = i;
  14356. } else if (code === 32 || code === 9) {
  14357. if (end === -1 && start !== -1) end = i;
  14358. } else if (code === 59 || code === 44) {
  14359. if (start === -1) throw new SyntaxError(`Unexpected character at index ${i}`);
  14360. if (end === -1) end = i;
  14361. push(params, header.slice(start, end), true);
  14362. if (code === 44) {
  14363. push(offers, extensionName, params);
  14364. params = Object.create(null);
  14365. extensionName = void 0;
  14366. }
  14367. start = end = -1;
  14368. } else if (code === 61 && start !== -1 && end === -1) {
  14369. paramName = header.slice(start, i);
  14370. start = end = -1;
  14371. } else throw new SyntaxError(`Unexpected character at index ${i}`);
  14372. else if (isEscaping) {
  14373. if (tokenChars[code] !== 1) throw new SyntaxError(`Unexpected character at index ${i}`);
  14374. if (start === -1) start = i;
  14375. else if (!mustUnescape) mustUnescape = true;
  14376. isEscaping = false;
  14377. } else if (inQuotes) if (tokenChars[code] === 1) {
  14378. if (start === -1) start = i;
  14379. } else if (code === 34 && start !== -1) {
  14380. inQuotes = false;
  14381. end = i;
  14382. } else if (code === 92) isEscaping = true;
  14383. else throw new SyntaxError(`Unexpected character at index ${i}`);
  14384. else if (code === 34 && header.charCodeAt(i - 1) === 61) inQuotes = true;
  14385. else if (end === -1 && tokenChars[code] === 1) {
  14386. if (start === -1) start = i;
  14387. } else if (start !== -1 && (code === 32 || code === 9)) {
  14388. if (end === -1) end = i;
  14389. } else if (code === 59 || code === 44) {
  14390. if (start === -1) throw new SyntaxError(`Unexpected character at index ${i}`);
  14391. if (end === -1) end = i;
  14392. let value = header.slice(start, end);
  14393. if (mustUnescape) {
  14394. value = value.replace(/\\/g, "");
  14395. mustUnescape = false;
  14396. }
  14397. push(params, paramName, value);
  14398. if (code === 44) {
  14399. push(offers, extensionName, params);
  14400. params = Object.create(null);
  14401. extensionName = void 0;
  14402. }
  14403. paramName = void 0;
  14404. start = end = -1;
  14405. } else throw new SyntaxError(`Unexpected character at index ${i}`);
  14406. }
  14407. if (start === -1 || inQuotes || code === 32 || code === 9) throw new SyntaxError("Unexpected end of input");
  14408. if (end === -1) end = i;
  14409. const token = header.slice(start, end);
  14410. if (extensionName === void 0) push(offers, token, params);
  14411. else {
  14412. if (paramName === void 0) push(params, token, true);
  14413. else if (mustUnescape) push(params, paramName, token.replace(/\\/g, ""));
  14414. else push(params, paramName, token);
  14415. push(offers, extensionName, params);
  14416. }
  14417. return offers;
  14418. }
  14419. /**
  14420. * Builds the `Sec-WebSocket-Extensions` header field value.
  14421. *
  14422. * @param {Object} extensions The map of extensions and parameters to format
  14423. * @return {String} A string representing the given object
  14424. * @public
  14425. */
  14426. function format(extensions) {
  14427. return Object.keys(extensions).map((extension) => {
  14428. let configurations = extensions[extension];
  14429. if (!Array.isArray(configurations)) configurations = [configurations];
  14430. return configurations.map((params) => {
  14431. return [extension].concat(Object.keys(params).map((k) => {
  14432. let values = params[k];
  14433. if (!Array.isArray(values)) values = [values];
  14434. return values.map((v) => v === true ? k : `${k}=${v}`).join("; ");
  14435. })).join("; ");
  14436. }).join(", ");
  14437. }).join(", ");
  14438. }
  14439. module.exports = {
  14440. format,
  14441. parse
  14442. };
  14443. }));
  14444. //#endregion
  14445. //#region ../../node_modules/.pnpm/ws@8.19.0/node_modules/ws/lib/websocket.js
  14446. var require_websocket = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  14447. const EventEmitter$2 = __require("events");
  14448. const https$3 = __require("https");
  14449. const http$5 = __require("http");
  14450. const net$1 = __require("net");
  14451. const tls = __require("tls");
  14452. const { randomBytes, createHash: createHash$1 } = __require("crypto");
  14453. const { Duplex: Duplex$2, Readable } = __require("stream");
  14454. const { URL: URL$2 } = __require("url");
  14455. const PerMessageDeflate = require_permessage_deflate();
  14456. const Receiver = require_receiver();
  14457. const Sender = require_sender();
  14458. const { isBlob } = require_validation();
  14459. const { BINARY_TYPES, CLOSE_TIMEOUT, EMPTY_BUFFER, GUID, kForOnEventAttribute, kListener, kStatusCode, kWebSocket, NOOP } = require_constants();
  14460. const { EventTarget: { addEventListener, removeEventListener } } = require_event_target();
  14461. const { format, parse } = require_extension();
  14462. const { toBuffer } = require_buffer_util();
  14463. const kAborted = Symbol("kAborted");
  14464. const protocolVersions = [8, 13];
  14465. const readyStates = [
  14466. "CONNECTING",
  14467. "OPEN",
  14468. "CLOSING",
  14469. "CLOSED"
  14470. ];
  14471. const subprotocolRegex = /^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;
  14472. /**
  14473. * Class representing a WebSocket.
  14474. *
  14475. * @extends EventEmitter
  14476. */
  14477. var WebSocket = class WebSocket extends EventEmitter$2 {
  14478. /**
  14479. * Create a new `WebSocket`.
  14480. *
  14481. * @param {(String|URL)} address The URL to which to connect
  14482. * @param {(String|String[])} [protocols] The subprotocols
  14483. * @param {Object} [options] Connection options
  14484. */
  14485. constructor(address, protocols, options) {
  14486. super();
  14487. this._binaryType = BINARY_TYPES[0];
  14488. this._closeCode = 1006;
  14489. this._closeFrameReceived = false;
  14490. this._closeFrameSent = false;
  14491. this._closeMessage = EMPTY_BUFFER;
  14492. this._closeTimer = null;
  14493. this._errorEmitted = false;
  14494. this._extensions = {};
  14495. this._paused = false;
  14496. this._protocol = "";
  14497. this._readyState = WebSocket.CONNECTING;
  14498. this._receiver = null;
  14499. this._sender = null;
  14500. this._socket = null;
  14501. if (address !== null) {
  14502. this._bufferedAmount = 0;
  14503. this._isServer = false;
  14504. this._redirects = 0;
  14505. if (protocols === void 0) protocols = [];
  14506. else if (!Array.isArray(protocols)) if (typeof protocols === "object" && protocols !== null) {
  14507. options = protocols;
  14508. protocols = [];
  14509. } else protocols = [protocols];
  14510. initAsClient(this, address, protocols, options);
  14511. } else {
  14512. this._autoPong = options.autoPong;
  14513. this._closeTimeout = options.closeTimeout;
  14514. this._isServer = true;
  14515. }
  14516. }
  14517. /**
  14518. * For historical reasons, the custom "nodebuffer" type is used by the default
  14519. * instead of "blob".
  14520. *
  14521. * @type {String}
  14522. */
  14523. get binaryType() {
  14524. return this._binaryType;
  14525. }
  14526. set binaryType(type) {
  14527. if (!BINARY_TYPES.includes(type)) return;
  14528. this._binaryType = type;
  14529. if (this._receiver) this._receiver._binaryType = type;
  14530. }
  14531. /**
  14532. * @type {Number}
  14533. */
  14534. get bufferedAmount() {
  14535. if (!this._socket) return this._bufferedAmount;
  14536. return this._socket._writableState.length + this._sender._bufferedBytes;
  14537. }
  14538. /**
  14539. * @type {String}
  14540. */
  14541. get extensions() {
  14542. return Object.keys(this._extensions).join();
  14543. }
  14544. /**
  14545. * @type {Boolean}
  14546. */
  14547. get isPaused() {
  14548. return this._paused;
  14549. }
  14550. /**
  14551. * @type {Function}
  14552. */
  14553. /* istanbul ignore next */
  14554. get onclose() {
  14555. return null;
  14556. }
  14557. /**
  14558. * @type {Function}
  14559. */
  14560. /* istanbul ignore next */
  14561. get onerror() {
  14562. return null;
  14563. }
  14564. /**
  14565. * @type {Function}
  14566. */
  14567. /* istanbul ignore next */
  14568. get onopen() {
  14569. return null;
  14570. }
  14571. /**
  14572. * @type {Function}
  14573. */
  14574. /* istanbul ignore next */
  14575. get onmessage() {
  14576. return null;
  14577. }
  14578. /**
  14579. * @type {String}
  14580. */
  14581. get protocol() {
  14582. return this._protocol;
  14583. }
  14584. /**
  14585. * @type {Number}
  14586. */
  14587. get readyState() {
  14588. return this._readyState;
  14589. }
  14590. /**
  14591. * @type {String}
  14592. */
  14593. get url() {
  14594. return this._url;
  14595. }
  14596. /**
  14597. * Set up the socket and the internal resources.
  14598. *
  14599. * @param {Duplex} socket The network socket between the server and client
  14600. * @param {Buffer} head The first packet of the upgraded stream
  14601. * @param {Object} options Options object
  14602. * @param {Boolean} [options.allowSynchronousEvents=false] Specifies whether
  14603. * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
  14604. * multiple times in the same tick
  14605. * @param {Function} [options.generateMask] The function used to generate the
  14606. * masking key
  14607. * @param {Number} [options.maxPayload=0] The maximum allowed message size
  14608. * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
  14609. * not to skip UTF-8 validation for text and close messages
  14610. * @private
  14611. */
  14612. setSocket(socket, head, options) {
  14613. const receiver = new Receiver({
  14614. allowSynchronousEvents: options.allowSynchronousEvents,
  14615. binaryType: this.binaryType,
  14616. extensions: this._extensions,
  14617. isServer: this._isServer,
  14618. maxPayload: options.maxPayload,
  14619. skipUTF8Validation: options.skipUTF8Validation
  14620. });
  14621. const sender = new Sender(socket, this._extensions, options.generateMask);
  14622. this._receiver = receiver;
  14623. this._sender = sender;
  14624. this._socket = socket;
  14625. receiver[kWebSocket] = this;
  14626. sender[kWebSocket] = this;
  14627. socket[kWebSocket] = this;
  14628. receiver.on("conclude", receiverOnConclude);
  14629. receiver.on("drain", receiverOnDrain);
  14630. receiver.on("error", receiverOnError);
  14631. receiver.on("message", receiverOnMessage);
  14632. receiver.on("ping", receiverOnPing);
  14633. receiver.on("pong", receiverOnPong);
  14634. sender.onerror = senderOnError;
  14635. if (socket.setTimeout) socket.setTimeout(0);
  14636. if (socket.setNoDelay) socket.setNoDelay();
  14637. if (head.length > 0) socket.unshift(head);
  14638. socket.on("close", socketOnClose);
  14639. socket.on("data", socketOnData);
  14640. socket.on("end", socketOnEnd);
  14641. socket.on("error", socketOnError);
  14642. this._readyState = WebSocket.OPEN;
  14643. this.emit("open");
  14644. }
  14645. /**
  14646. * Emit the `'close'` event.
  14647. *
  14648. * @private
  14649. */
  14650. emitClose() {
  14651. if (!this._socket) {
  14652. this._readyState = WebSocket.CLOSED;
  14653. this.emit("close", this._closeCode, this._closeMessage);
  14654. return;
  14655. }
  14656. if (this._extensions[PerMessageDeflate.extensionName]) this._extensions[PerMessageDeflate.extensionName].cleanup();
  14657. this._receiver.removeAllListeners();
  14658. this._readyState = WebSocket.CLOSED;
  14659. this.emit("close", this._closeCode, this._closeMessage);
  14660. }
  14661. /**
  14662. * Start a closing handshake.
  14663. *
  14664. * +----------+ +-----------+ +----------+
  14665. * - - -|ws.close()|-->|close frame|-->|ws.close()|- - -
  14666. * | +----------+ +-----------+ +----------+ |
  14667. * +----------+ +-----------+ |
  14668. * CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING
  14669. * +----------+ +-----------+ |
  14670. * | | | +---+ |
  14671. * +------------------------+-->|fin| - - - -
  14672. * | +---+ | +---+
  14673. * - - - - -|fin|<---------------------+
  14674. * +---+
  14675. *
  14676. * @param {Number} [code] Status code explaining why the connection is closing
  14677. * @param {(String|Buffer)} [data] The reason why the connection is
  14678. * closing
  14679. * @public
  14680. */
  14681. close(code, data) {
  14682. if (this.readyState === WebSocket.CLOSED) return;
  14683. if (this.readyState === WebSocket.CONNECTING) {
  14684. abortHandshake(this, this._req, "WebSocket was closed before the connection was established");
  14685. return;
  14686. }
  14687. if (this.readyState === WebSocket.CLOSING) {
  14688. if (this._closeFrameSent && (this._closeFrameReceived || this._receiver._writableState.errorEmitted)) this._socket.end();
  14689. return;
  14690. }
  14691. this._readyState = WebSocket.CLOSING;
  14692. this._sender.close(code, data, !this._isServer, (err) => {
  14693. if (err) return;
  14694. this._closeFrameSent = true;
  14695. if (this._closeFrameReceived || this._receiver._writableState.errorEmitted) this._socket.end();
  14696. });
  14697. setCloseTimer(this);
  14698. }
  14699. /**
  14700. * Pause the socket.
  14701. *
  14702. * @public
  14703. */
  14704. pause() {
  14705. if (this.readyState === WebSocket.CONNECTING || this.readyState === WebSocket.CLOSED) return;
  14706. this._paused = true;
  14707. this._socket.pause();
  14708. }
  14709. /**
  14710. * Send a ping.
  14711. *
  14712. * @param {*} [data] The data to send
  14713. * @param {Boolean} [mask] Indicates whether or not to mask `data`
  14714. * @param {Function} [cb] Callback which is executed when the ping is sent
  14715. * @public
  14716. */
  14717. ping(data, mask, cb) {
  14718. if (this.readyState === WebSocket.CONNECTING) throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
  14719. if (typeof data === "function") {
  14720. cb = data;
  14721. data = mask = void 0;
  14722. } else if (typeof mask === "function") {
  14723. cb = mask;
  14724. mask = void 0;
  14725. }
  14726. if (typeof data === "number") data = data.toString();
  14727. if (this.readyState !== WebSocket.OPEN) {
  14728. sendAfterClose(this, data, cb);
  14729. return;
  14730. }
  14731. if (mask === void 0) mask = !this._isServer;
  14732. this._sender.ping(data || EMPTY_BUFFER, mask, cb);
  14733. }
  14734. /**
  14735. * Send a pong.
  14736. *
  14737. * @param {*} [data] The data to send
  14738. * @param {Boolean} [mask] Indicates whether or not to mask `data`
  14739. * @param {Function} [cb] Callback which is executed when the pong is sent
  14740. * @public
  14741. */
  14742. pong(data, mask, cb) {
  14743. if (this.readyState === WebSocket.CONNECTING) throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
  14744. if (typeof data === "function") {
  14745. cb = data;
  14746. data = mask = void 0;
  14747. } else if (typeof mask === "function") {
  14748. cb = mask;
  14749. mask = void 0;
  14750. }
  14751. if (typeof data === "number") data = data.toString();
  14752. if (this.readyState !== WebSocket.OPEN) {
  14753. sendAfterClose(this, data, cb);
  14754. return;
  14755. }
  14756. if (mask === void 0) mask = !this._isServer;
  14757. this._sender.pong(data || EMPTY_BUFFER, mask, cb);
  14758. }
  14759. /**
  14760. * Resume the socket.
  14761. *
  14762. * @public
  14763. */
  14764. resume() {
  14765. if (this.readyState === WebSocket.CONNECTING || this.readyState === WebSocket.CLOSED) return;
  14766. this._paused = false;
  14767. if (!this._receiver._writableState.needDrain) this._socket.resume();
  14768. }
  14769. /**
  14770. * Send a data message.
  14771. *
  14772. * @param {*} data The message to send
  14773. * @param {Object} [options] Options object
  14774. * @param {Boolean} [options.binary] Specifies whether `data` is binary or
  14775. * text
  14776. * @param {Boolean} [options.compress] Specifies whether or not to compress
  14777. * `data`
  14778. * @param {Boolean} [options.fin=true] Specifies whether the fragment is the
  14779. * last one
  14780. * @param {Boolean} [options.mask] Specifies whether or not to mask `data`
  14781. * @param {Function} [cb] Callback which is executed when data is written out
  14782. * @public
  14783. */
  14784. send(data, options, cb) {
  14785. if (this.readyState === WebSocket.CONNECTING) throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
  14786. if (typeof options === "function") {
  14787. cb = options;
  14788. options = {};
  14789. }
  14790. if (typeof data === "number") data = data.toString();
  14791. if (this.readyState !== WebSocket.OPEN) {
  14792. sendAfterClose(this, data, cb);
  14793. return;
  14794. }
  14795. const opts = {
  14796. binary: typeof data !== "string",
  14797. mask: !this._isServer,
  14798. compress: true,
  14799. fin: true,
  14800. ...options
  14801. };
  14802. if (!this._extensions[PerMessageDeflate.extensionName]) opts.compress = false;
  14803. this._sender.send(data || EMPTY_BUFFER, opts, cb);
  14804. }
  14805. /**
  14806. * Forcibly close the connection.
  14807. *
  14808. * @public
  14809. */
  14810. terminate() {
  14811. if (this.readyState === WebSocket.CLOSED) return;
  14812. if (this.readyState === WebSocket.CONNECTING) {
  14813. abortHandshake(this, this._req, "WebSocket was closed before the connection was established");
  14814. return;
  14815. }
  14816. if (this._socket) {
  14817. this._readyState = WebSocket.CLOSING;
  14818. this._socket.destroy();
  14819. }
  14820. }
  14821. };
  14822. /**
  14823. * @constant {Number} CONNECTING
  14824. * @memberof WebSocket
  14825. */
  14826. Object.defineProperty(WebSocket, "CONNECTING", {
  14827. enumerable: true,
  14828. value: readyStates.indexOf("CONNECTING")
  14829. });
  14830. /**
  14831. * @constant {Number} CONNECTING
  14832. * @memberof WebSocket.prototype
  14833. */
  14834. Object.defineProperty(WebSocket.prototype, "CONNECTING", {
  14835. enumerable: true,
  14836. value: readyStates.indexOf("CONNECTING")
  14837. });
  14838. /**
  14839. * @constant {Number} OPEN
  14840. * @memberof WebSocket
  14841. */
  14842. Object.defineProperty(WebSocket, "OPEN", {
  14843. enumerable: true,
  14844. value: readyStates.indexOf("OPEN")
  14845. });
  14846. /**
  14847. * @constant {Number} OPEN
  14848. * @memberof WebSocket.prototype
  14849. */
  14850. Object.defineProperty(WebSocket.prototype, "OPEN", {
  14851. enumerable: true,
  14852. value: readyStates.indexOf("OPEN")
  14853. });
  14854. /**
  14855. * @constant {Number} CLOSING
  14856. * @memberof WebSocket
  14857. */
  14858. Object.defineProperty(WebSocket, "CLOSING", {
  14859. enumerable: true,
  14860. value: readyStates.indexOf("CLOSING")
  14861. });
  14862. /**
  14863. * @constant {Number} CLOSING
  14864. * @memberof WebSocket.prototype
  14865. */
  14866. Object.defineProperty(WebSocket.prototype, "CLOSING", {
  14867. enumerable: true,
  14868. value: readyStates.indexOf("CLOSING")
  14869. });
  14870. /**
  14871. * @constant {Number} CLOSED
  14872. * @memberof WebSocket
  14873. */
  14874. Object.defineProperty(WebSocket, "CLOSED", {
  14875. enumerable: true,
  14876. value: readyStates.indexOf("CLOSED")
  14877. });
  14878. /**
  14879. * @constant {Number} CLOSED
  14880. * @memberof WebSocket.prototype
  14881. */
  14882. Object.defineProperty(WebSocket.prototype, "CLOSED", {
  14883. enumerable: true,
  14884. value: readyStates.indexOf("CLOSED")
  14885. });
  14886. [
  14887. "binaryType",
  14888. "bufferedAmount",
  14889. "extensions",
  14890. "isPaused",
  14891. "protocol",
  14892. "readyState",
  14893. "url"
  14894. ].forEach((property) => {
  14895. Object.defineProperty(WebSocket.prototype, property, { enumerable: true });
  14896. });
  14897. [
  14898. "open",
  14899. "error",
  14900. "close",
  14901. "message"
  14902. ].forEach((method) => {
  14903. Object.defineProperty(WebSocket.prototype, `on${method}`, {
  14904. enumerable: true,
  14905. get() {
  14906. for (const listener of this.listeners(method)) if (listener[kForOnEventAttribute]) return listener[kListener];
  14907. return null;
  14908. },
  14909. set(handler) {
  14910. for (const listener of this.listeners(method)) if (listener[kForOnEventAttribute]) {
  14911. this.removeListener(method, listener);
  14912. break;
  14913. }
  14914. if (typeof handler !== "function") return;
  14915. this.addEventListener(method, handler, { [kForOnEventAttribute]: true });
  14916. }
  14917. });
  14918. });
  14919. WebSocket.prototype.addEventListener = addEventListener;
  14920. WebSocket.prototype.removeEventListener = removeEventListener;
  14921. module.exports = WebSocket;
  14922. /**
  14923. * Initialize a WebSocket client.
  14924. *
  14925. * @param {WebSocket} websocket The client to initialize
  14926. * @param {(String|URL)} address The URL to which to connect
  14927. * @param {Array} protocols The subprotocols
  14928. * @param {Object} [options] Connection options
  14929. * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether any
  14930. * of the `'message'`, `'ping'`, and `'pong'` events can be emitted multiple
  14931. * times in the same tick
  14932. * @param {Boolean} [options.autoPong=true] Specifies whether or not to
  14933. * automatically send a pong in response to a ping
  14934. * @param {Number} [options.closeTimeout=30000] Duration in milliseconds to wait
  14935. * for the closing handshake to finish after `websocket.close()` is called
  14936. * @param {Function} [options.finishRequest] A function which can be used to
  14937. * customize the headers of each http request before it is sent
  14938. * @param {Boolean} [options.followRedirects=false] Whether or not to follow
  14939. * redirects
  14940. * @param {Function} [options.generateMask] The function used to generate the
  14941. * masking key
  14942. * @param {Number} [options.handshakeTimeout] Timeout in milliseconds for the
  14943. * handshake request
  14944. * @param {Number} [options.maxPayload=104857600] The maximum allowed message
  14945. * size
  14946. * @param {Number} [options.maxRedirects=10] The maximum number of redirects
  14947. * allowed
  14948. * @param {String} [options.origin] Value of the `Origin` or
  14949. * `Sec-WebSocket-Origin` header
  14950. * @param {(Boolean|Object)} [options.perMessageDeflate=true] Enable/disable
  14951. * permessage-deflate
  14952. * @param {Number} [options.protocolVersion=13] Value of the
  14953. * `Sec-WebSocket-Version` header
  14954. * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
  14955. * not to skip UTF-8 validation for text and close messages
  14956. * @private
  14957. */
  14958. function initAsClient(websocket, address, protocols, options) {
  14959. const opts = {
  14960. allowSynchronousEvents: true,
  14961. autoPong: true,
  14962. closeTimeout: CLOSE_TIMEOUT,
  14963. protocolVersion: protocolVersions[1],
  14964. maxPayload: 100 * 1024 * 1024,
  14965. skipUTF8Validation: false,
  14966. perMessageDeflate: true,
  14967. followRedirects: false,
  14968. maxRedirects: 10,
  14969. ...options,
  14970. socketPath: void 0,
  14971. hostname: void 0,
  14972. protocol: void 0,
  14973. timeout: void 0,
  14974. method: "GET",
  14975. host: void 0,
  14976. path: void 0,
  14977. port: void 0
  14978. };
  14979. websocket._autoPong = opts.autoPong;
  14980. websocket._closeTimeout = opts.closeTimeout;
  14981. if (!protocolVersions.includes(opts.protocolVersion)) throw new RangeError(`Unsupported protocol version: ${opts.protocolVersion} (supported versions: ${protocolVersions.join(", ")})`);
  14982. let parsedUrl;
  14983. if (address instanceof URL$2) parsedUrl = address;
  14984. else try {
  14985. parsedUrl = new URL$2(address);
  14986. } catch (e) {
  14987. throw new SyntaxError(`Invalid URL: ${address}`);
  14988. }
  14989. if (parsedUrl.protocol === "http:") parsedUrl.protocol = "ws:";
  14990. else if (parsedUrl.protocol === "https:") parsedUrl.protocol = "wss:";
  14991. websocket._url = parsedUrl.href;
  14992. const isSecure = parsedUrl.protocol === "wss:";
  14993. const isIpcUrl = parsedUrl.protocol === "ws+unix:";
  14994. let invalidUrlMessage;
  14995. if (parsedUrl.protocol !== "ws:" && !isSecure && !isIpcUrl) invalidUrlMessage = "The URL's protocol must be one of \"ws:\", \"wss:\", \"http:\", \"https:\", or \"ws+unix:\"";
  14996. else if (isIpcUrl && !parsedUrl.pathname) invalidUrlMessage = "The URL's pathname is empty";
  14997. else if (parsedUrl.hash) invalidUrlMessage = "The URL contains a fragment identifier";
  14998. if (invalidUrlMessage) {
  14999. const err = new SyntaxError(invalidUrlMessage);
  15000. if (websocket._redirects === 0) throw err;
  15001. else {
  15002. emitErrorAndClose(websocket, err);
  15003. return;
  15004. }
  15005. }
  15006. const defaultPort = isSecure ? 443 : 80;
  15007. const key = randomBytes(16).toString("base64");
  15008. const request = isSecure ? https$3.request : http$5.request;
  15009. const protocolSet = /* @__PURE__ */ new Set();
  15010. let perMessageDeflate;
  15011. opts.createConnection = opts.createConnection || (isSecure ? tlsConnect : netConnect);
  15012. opts.defaultPort = opts.defaultPort || defaultPort;
  15013. opts.port = parsedUrl.port || defaultPort;
  15014. opts.host = parsedUrl.hostname.startsWith("[") ? parsedUrl.hostname.slice(1, -1) : parsedUrl.hostname;
  15015. opts.headers = {
  15016. ...opts.headers,
  15017. "Sec-WebSocket-Version": opts.protocolVersion,
  15018. "Sec-WebSocket-Key": key,
  15019. Connection: "Upgrade",
  15020. Upgrade: "websocket"
  15021. };
  15022. opts.path = parsedUrl.pathname + parsedUrl.search;
  15023. opts.timeout = opts.handshakeTimeout;
  15024. if (opts.perMessageDeflate) {
  15025. perMessageDeflate = new PerMessageDeflate(opts.perMessageDeflate !== true ? opts.perMessageDeflate : {}, false, opts.maxPayload);
  15026. opts.headers["Sec-WebSocket-Extensions"] = format({ [PerMessageDeflate.extensionName]: perMessageDeflate.offer() });
  15027. }
  15028. if (protocols.length) {
  15029. for (const protocol of protocols) {
  15030. if (typeof protocol !== "string" || !subprotocolRegex.test(protocol) || protocolSet.has(protocol)) throw new SyntaxError("An invalid or duplicated subprotocol was specified");
  15031. protocolSet.add(protocol);
  15032. }
  15033. opts.headers["Sec-WebSocket-Protocol"] = protocols.join(",");
  15034. }
  15035. if (opts.origin) if (opts.protocolVersion < 13) opts.headers["Sec-WebSocket-Origin"] = opts.origin;
  15036. else opts.headers.Origin = opts.origin;
  15037. if (parsedUrl.username || parsedUrl.password) opts.auth = `${parsedUrl.username}:${parsedUrl.password}`;
  15038. if (isIpcUrl) {
  15039. const parts = opts.path.split(":");
  15040. opts.socketPath = parts[0];
  15041. opts.path = parts[1];
  15042. }
  15043. let req;
  15044. if (opts.followRedirects) {
  15045. if (websocket._redirects === 0) {
  15046. websocket._originalIpc = isIpcUrl;
  15047. websocket._originalSecure = isSecure;
  15048. websocket._originalHostOrSocketPath = isIpcUrl ? opts.socketPath : parsedUrl.host;
  15049. const headers = options && options.headers;
  15050. options = {
  15051. ...options,
  15052. headers: {}
  15053. };
  15054. if (headers) for (const [key, value] of Object.entries(headers)) options.headers[key.toLowerCase()] = value;
  15055. } else if (websocket.listenerCount("redirect") === 0) {
  15056. const isSameHost = isIpcUrl ? websocket._originalIpc ? opts.socketPath === websocket._originalHostOrSocketPath : false : websocket._originalIpc ? false : parsedUrl.host === websocket._originalHostOrSocketPath;
  15057. if (!isSameHost || websocket._originalSecure && !isSecure) {
  15058. delete opts.headers.authorization;
  15059. delete opts.headers.cookie;
  15060. if (!isSameHost) delete opts.headers.host;
  15061. opts.auth = void 0;
  15062. }
  15063. }
  15064. if (opts.auth && !options.headers.authorization) options.headers.authorization = "Basic " + Buffer.from(opts.auth).toString("base64");
  15065. req = websocket._req = request(opts);
  15066. if (websocket._redirects) websocket.emit("redirect", websocket.url, req);
  15067. } else req = websocket._req = request(opts);
  15068. if (opts.timeout) req.on("timeout", () => {
  15069. abortHandshake(websocket, req, "Opening handshake has timed out");
  15070. });
  15071. req.on("error", (err) => {
  15072. if (req === null || req[kAborted]) return;
  15073. req = websocket._req = null;
  15074. emitErrorAndClose(websocket, err);
  15075. });
  15076. req.on("response", (res) => {
  15077. const location = res.headers.location;
  15078. const statusCode = res.statusCode;
  15079. if (location && opts.followRedirects && statusCode >= 300 && statusCode < 400) {
  15080. if (++websocket._redirects > opts.maxRedirects) {
  15081. abortHandshake(websocket, req, "Maximum redirects exceeded");
  15082. return;
  15083. }
  15084. req.abort();
  15085. let addr;
  15086. try {
  15087. addr = new URL$2(location, address);
  15088. } catch (e) {
  15089. emitErrorAndClose(websocket, /* @__PURE__ */ new SyntaxError(`Invalid URL: ${location}`));
  15090. return;
  15091. }
  15092. initAsClient(websocket, addr, protocols, options);
  15093. } else if (!websocket.emit("unexpected-response", req, res)) abortHandshake(websocket, req, `Unexpected server response: ${res.statusCode}`);
  15094. });
  15095. req.on("upgrade", (res, socket, head) => {
  15096. websocket.emit("upgrade", res);
  15097. if (websocket.readyState !== WebSocket.CONNECTING) return;
  15098. req = websocket._req = null;
  15099. const upgrade = res.headers.upgrade;
  15100. if (upgrade === void 0 || upgrade.toLowerCase() !== "websocket") {
  15101. abortHandshake(websocket, socket, "Invalid Upgrade header");
  15102. return;
  15103. }
  15104. const digest = createHash$1("sha1").update(key + GUID).digest("base64");
  15105. if (res.headers["sec-websocket-accept"] !== digest) {
  15106. abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header");
  15107. return;
  15108. }
  15109. const serverProt = res.headers["sec-websocket-protocol"];
  15110. let protError;
  15111. if (serverProt !== void 0) {
  15112. if (!protocolSet.size) protError = "Server sent a subprotocol but none was requested";
  15113. else if (!protocolSet.has(serverProt)) protError = "Server sent an invalid subprotocol";
  15114. } else if (protocolSet.size) protError = "Server sent no subprotocol";
  15115. if (protError) {
  15116. abortHandshake(websocket, socket, protError);
  15117. return;
  15118. }
  15119. if (serverProt) websocket._protocol = serverProt;
  15120. const secWebSocketExtensions = res.headers["sec-websocket-extensions"];
  15121. if (secWebSocketExtensions !== void 0) {
  15122. if (!perMessageDeflate) {
  15123. abortHandshake(websocket, socket, "Server sent a Sec-WebSocket-Extensions header but no extension was requested");
  15124. return;
  15125. }
  15126. let extensions;
  15127. try {
  15128. extensions = parse(secWebSocketExtensions);
  15129. } catch (err) {
  15130. abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Extensions header");
  15131. return;
  15132. }
  15133. const extensionNames = Object.keys(extensions);
  15134. if (extensionNames.length !== 1 || extensionNames[0] !== PerMessageDeflate.extensionName) {
  15135. abortHandshake(websocket, socket, "Server indicated an extension that was not requested");
  15136. return;
  15137. }
  15138. try {
  15139. perMessageDeflate.accept(extensions[PerMessageDeflate.extensionName]);
  15140. } catch (err) {
  15141. abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Extensions header");
  15142. return;
  15143. }
  15144. websocket._extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
  15145. }
  15146. websocket.setSocket(socket, head, {
  15147. allowSynchronousEvents: opts.allowSynchronousEvents,
  15148. generateMask: opts.generateMask,
  15149. maxPayload: opts.maxPayload,
  15150. skipUTF8Validation: opts.skipUTF8Validation
  15151. });
  15152. });
  15153. if (opts.finishRequest) opts.finishRequest(req, websocket);
  15154. else req.end();
  15155. }
  15156. /**
  15157. * Emit the `'error'` and `'close'` events.
  15158. *
  15159. * @param {WebSocket} websocket The WebSocket instance
  15160. * @param {Error} The error to emit
  15161. * @private
  15162. */
  15163. function emitErrorAndClose(websocket, err) {
  15164. websocket._readyState = WebSocket.CLOSING;
  15165. websocket._errorEmitted = true;
  15166. websocket.emit("error", err);
  15167. websocket.emitClose();
  15168. }
  15169. /**
  15170. * Create a `net.Socket` and initiate a connection.
  15171. *
  15172. * @param {Object} options Connection options
  15173. * @return {net.Socket} The newly created socket used to start the connection
  15174. * @private
  15175. */
  15176. function netConnect(options) {
  15177. options.path = options.socketPath;
  15178. return net$1.connect(options);
  15179. }
  15180. /**
  15181. * Create a `tls.TLSSocket` and initiate a connection.
  15182. *
  15183. * @param {Object} options Connection options
  15184. * @return {tls.TLSSocket} The newly created socket used to start the connection
  15185. * @private
  15186. */
  15187. function tlsConnect(options) {
  15188. options.path = void 0;
  15189. if (!options.servername && options.servername !== "") options.servername = net$1.isIP(options.host) ? "" : options.host;
  15190. return tls.connect(options);
  15191. }
  15192. /**
  15193. * Abort the handshake and emit an error.
  15194. *
  15195. * @param {WebSocket} websocket The WebSocket instance
  15196. * @param {(http.ClientRequest|net.Socket|tls.Socket)} stream The request to
  15197. * abort or the socket to destroy
  15198. * @param {String} message The error message
  15199. * @private
  15200. */
  15201. function abortHandshake(websocket, stream, message) {
  15202. websocket._readyState = WebSocket.CLOSING;
  15203. const err = new Error(message);
  15204. Error.captureStackTrace(err, abortHandshake);
  15205. if (stream.setHeader) {
  15206. stream[kAborted] = true;
  15207. stream.abort();
  15208. if (stream.socket && !stream.socket.destroyed) stream.socket.destroy();
  15209. process.nextTick(emitErrorAndClose, websocket, err);
  15210. } else {
  15211. stream.destroy(err);
  15212. stream.once("error", websocket.emit.bind(websocket, "error"));
  15213. stream.once("close", websocket.emitClose.bind(websocket));
  15214. }
  15215. }
  15216. /**
  15217. * Handle cases where the `ping()`, `pong()`, or `send()` methods are called
  15218. * when the `readyState` attribute is `CLOSING` or `CLOSED`.
  15219. *
  15220. * @param {WebSocket} websocket The WebSocket instance
  15221. * @param {*} [data] The data to send
  15222. * @param {Function} [cb] Callback
  15223. * @private
  15224. */
  15225. function sendAfterClose(websocket, data, cb) {
  15226. if (data) {
  15227. const length = isBlob(data) ? data.size : toBuffer(data).length;
  15228. if (websocket._socket) websocket._sender._bufferedBytes += length;
  15229. else websocket._bufferedAmount += length;
  15230. }
  15231. if (cb) {
  15232. const err = /* @__PURE__ */ new Error(`WebSocket is not open: readyState ${websocket.readyState} (${readyStates[websocket.readyState]})`);
  15233. process.nextTick(cb, err);
  15234. }
  15235. }
  15236. /**
  15237. * The listener of the `Receiver` `'conclude'` event.
  15238. *
  15239. * @param {Number} code The status code
  15240. * @param {Buffer} reason The reason for closing
  15241. * @private
  15242. */
  15243. function receiverOnConclude(code, reason) {
  15244. const websocket = this[kWebSocket];
  15245. websocket._closeFrameReceived = true;
  15246. websocket._closeMessage = reason;
  15247. websocket._closeCode = code;
  15248. if (websocket._socket[kWebSocket] === void 0) return;
  15249. websocket._socket.removeListener("data", socketOnData);
  15250. process.nextTick(resume, websocket._socket);
  15251. if (code === 1005) websocket.close();
  15252. else websocket.close(code, reason);
  15253. }
  15254. /**
  15255. * The listener of the `Receiver` `'drain'` event.
  15256. *
  15257. * @private
  15258. */
  15259. function receiverOnDrain() {
  15260. const websocket = this[kWebSocket];
  15261. if (!websocket.isPaused) websocket._socket.resume();
  15262. }
  15263. /**
  15264. * The listener of the `Receiver` `'error'` event.
  15265. *
  15266. * @param {(RangeError|Error)} err The emitted error
  15267. * @private
  15268. */
  15269. function receiverOnError(err) {
  15270. const websocket = this[kWebSocket];
  15271. if (websocket._socket[kWebSocket] !== void 0) {
  15272. websocket._socket.removeListener("data", socketOnData);
  15273. process.nextTick(resume, websocket._socket);
  15274. websocket.close(err[kStatusCode]);
  15275. }
  15276. if (!websocket._errorEmitted) {
  15277. websocket._errorEmitted = true;
  15278. websocket.emit("error", err);
  15279. }
  15280. }
  15281. /**
  15282. * The listener of the `Receiver` `'finish'` event.
  15283. *
  15284. * @private
  15285. */
  15286. function receiverOnFinish() {
  15287. this[kWebSocket].emitClose();
  15288. }
  15289. /**
  15290. * The listener of the `Receiver` `'message'` event.
  15291. *
  15292. * @param {Buffer|ArrayBuffer|Buffer[])} data The message
  15293. * @param {Boolean} isBinary Specifies whether the message is binary or not
  15294. * @private
  15295. */
  15296. function receiverOnMessage(data, isBinary) {
  15297. this[kWebSocket].emit("message", data, isBinary);
  15298. }
  15299. /**
  15300. * The listener of the `Receiver` `'ping'` event.
  15301. *
  15302. * @param {Buffer} data The data included in the ping frame
  15303. * @private
  15304. */
  15305. function receiverOnPing(data) {
  15306. const websocket = this[kWebSocket];
  15307. if (websocket._autoPong) websocket.pong(data, !this._isServer, NOOP);
  15308. websocket.emit("ping", data);
  15309. }
  15310. /**
  15311. * The listener of the `Receiver` `'pong'` event.
  15312. *
  15313. * @param {Buffer} data The data included in the pong frame
  15314. * @private
  15315. */
  15316. function receiverOnPong(data) {
  15317. this[kWebSocket].emit("pong", data);
  15318. }
  15319. /**
  15320. * Resume a readable stream
  15321. *
  15322. * @param {Readable} stream The readable stream
  15323. * @private
  15324. */
  15325. function resume(stream) {
  15326. stream.resume();
  15327. }
  15328. /**
  15329. * The `Sender` error event handler.
  15330. *
  15331. * @param {Error} The error
  15332. * @private
  15333. */
  15334. function senderOnError(err) {
  15335. const websocket = this[kWebSocket];
  15336. if (websocket.readyState === WebSocket.CLOSED) return;
  15337. if (websocket.readyState === WebSocket.OPEN) {
  15338. websocket._readyState = WebSocket.CLOSING;
  15339. setCloseTimer(websocket);
  15340. }
  15341. this._socket.end();
  15342. if (!websocket._errorEmitted) {
  15343. websocket._errorEmitted = true;
  15344. websocket.emit("error", err);
  15345. }
  15346. }
  15347. /**
  15348. * Set a timer to destroy the underlying raw socket of a WebSocket.
  15349. *
  15350. * @param {WebSocket} websocket The WebSocket instance
  15351. * @private
  15352. */
  15353. function setCloseTimer(websocket) {
  15354. websocket._closeTimer = setTimeout(websocket._socket.destroy.bind(websocket._socket), websocket._closeTimeout);
  15355. }
  15356. /**
  15357. * The listener of the socket `'close'` event.
  15358. *
  15359. * @private
  15360. */
  15361. function socketOnClose() {
  15362. const websocket = this[kWebSocket];
  15363. this.removeListener("close", socketOnClose);
  15364. this.removeListener("data", socketOnData);
  15365. this.removeListener("end", socketOnEnd);
  15366. websocket._readyState = WebSocket.CLOSING;
  15367. if (!this._readableState.endEmitted && !websocket._closeFrameReceived && !websocket._receiver._writableState.errorEmitted && this._readableState.length !== 0) {
  15368. const chunk = this.read(this._readableState.length);
  15369. websocket._receiver.write(chunk);
  15370. }
  15371. websocket._receiver.end();
  15372. this[kWebSocket] = void 0;
  15373. clearTimeout(websocket._closeTimer);
  15374. if (websocket._receiver._writableState.finished || websocket._receiver._writableState.errorEmitted) websocket.emitClose();
  15375. else {
  15376. websocket._receiver.on("error", receiverOnFinish);
  15377. websocket._receiver.on("finish", receiverOnFinish);
  15378. }
  15379. }
  15380. /**
  15381. * The listener of the socket `'data'` event.
  15382. *
  15383. * @param {Buffer} chunk A chunk of data
  15384. * @private
  15385. */
  15386. function socketOnData(chunk) {
  15387. if (!this[kWebSocket]._receiver.write(chunk)) this.pause();
  15388. }
  15389. /**
  15390. * The listener of the socket `'end'` event.
  15391. *
  15392. * @private
  15393. */
  15394. function socketOnEnd() {
  15395. const websocket = this[kWebSocket];
  15396. websocket._readyState = WebSocket.CLOSING;
  15397. websocket._receiver.end();
  15398. this.end();
  15399. }
  15400. /**
  15401. * The listener of the socket `'error'` event.
  15402. *
  15403. * @private
  15404. */
  15405. function socketOnError() {
  15406. const websocket = this[kWebSocket];
  15407. this.removeListener("error", socketOnError);
  15408. this.on("error", NOOP);
  15409. if (websocket) {
  15410. websocket._readyState = WebSocket.CLOSING;
  15411. this.destroy();
  15412. }
  15413. }
  15414. }));
  15415. //#endregion
  15416. //#region ../../node_modules/.pnpm/ws@8.19.0/node_modules/ws/lib/stream.js
  15417. var require_stream = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  15418. require_websocket();
  15419. const { Duplex: Duplex$1 } = __require("stream");
  15420. /**
  15421. * Emits the `'close'` event on a stream.
  15422. *
  15423. * @param {Duplex} stream The stream.
  15424. * @private
  15425. */
  15426. function emitClose(stream) {
  15427. stream.emit("close");
  15428. }
  15429. /**
  15430. * The listener of the `'end'` event.
  15431. *
  15432. * @private
  15433. */
  15434. function duplexOnEnd() {
  15435. if (!this.destroyed && this._writableState.finished) this.destroy();
  15436. }
  15437. /**
  15438. * The listener of the `'error'` event.
  15439. *
  15440. * @param {Error} err The error
  15441. * @private
  15442. */
  15443. function duplexOnError(err) {
  15444. this.removeListener("error", duplexOnError);
  15445. this.destroy();
  15446. if (this.listenerCount("error") === 0) this.emit("error", err);
  15447. }
  15448. /**
  15449. * Wraps a `WebSocket` in a duplex stream.
  15450. *
  15451. * @param {WebSocket} ws The `WebSocket` to wrap
  15452. * @param {Object} [options] The options for the `Duplex` constructor
  15453. * @return {Duplex} The duplex stream
  15454. * @public
  15455. */
  15456. function createWebSocketStream(ws, options) {
  15457. let terminateOnDestroy = true;
  15458. const duplex = new Duplex$1({
  15459. ...options,
  15460. autoDestroy: false,
  15461. emitClose: false,
  15462. objectMode: false,
  15463. writableObjectMode: false
  15464. });
  15465. ws.on("message", function message(msg, isBinary) {
  15466. const data = !isBinary && duplex._readableState.objectMode ? msg.toString() : msg;
  15467. if (!duplex.push(data)) ws.pause();
  15468. });
  15469. ws.once("error", function error(err) {
  15470. if (duplex.destroyed) return;
  15471. terminateOnDestroy = false;
  15472. duplex.destroy(err);
  15473. });
  15474. ws.once("close", function close() {
  15475. if (duplex.destroyed) return;
  15476. duplex.push(null);
  15477. });
  15478. duplex._destroy = function(err, callback) {
  15479. if (ws.readyState === ws.CLOSED) {
  15480. callback(err);
  15481. process.nextTick(emitClose, duplex);
  15482. return;
  15483. }
  15484. let called = false;
  15485. ws.once("error", function error(err) {
  15486. called = true;
  15487. callback(err);
  15488. });
  15489. ws.once("close", function close() {
  15490. if (!called) callback(err);
  15491. process.nextTick(emitClose, duplex);
  15492. });
  15493. if (terminateOnDestroy) ws.terminate();
  15494. };
  15495. duplex._final = function(callback) {
  15496. if (ws.readyState === ws.CONNECTING) {
  15497. ws.once("open", function open() {
  15498. duplex._final(callback);
  15499. });
  15500. return;
  15501. }
  15502. if (ws._socket === null) return;
  15503. if (ws._socket._writableState.finished) {
  15504. callback();
  15505. if (duplex._readableState.endEmitted) duplex.destroy();
  15506. } else {
  15507. ws._socket.once("finish", function finish() {
  15508. callback();
  15509. });
  15510. ws.close();
  15511. }
  15512. };
  15513. duplex._read = function() {
  15514. if (ws.isPaused) ws.resume();
  15515. };
  15516. duplex._write = function(chunk, encoding, callback) {
  15517. if (ws.readyState === ws.CONNECTING) {
  15518. ws.once("open", function open() {
  15519. duplex._write(chunk, encoding, callback);
  15520. });
  15521. return;
  15522. }
  15523. ws.send(chunk, callback);
  15524. };
  15525. duplex.on("end", duplexOnEnd);
  15526. duplex.on("error", duplexOnError);
  15527. return duplex;
  15528. }
  15529. module.exports = createWebSocketStream;
  15530. }));
  15531. //#endregion
  15532. //#region ../../node_modules/.pnpm/ws@8.19.0/node_modules/ws/lib/subprotocol.js
  15533. var require_subprotocol = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  15534. const { tokenChars } = require_validation();
  15535. /**
  15536. * Parses the `Sec-WebSocket-Protocol` header into a set of subprotocol names.
  15537. *
  15538. * @param {String} header The field value of the header
  15539. * @return {Set} The subprotocol names
  15540. * @public
  15541. */
  15542. function parse(header) {
  15543. const protocols = /* @__PURE__ */ new Set();
  15544. let start = -1;
  15545. let end = -1;
  15546. let i = 0;
  15547. for (; i < header.length; i++) {
  15548. const code = header.charCodeAt(i);
  15549. if (end === -1 && tokenChars[code] === 1) {
  15550. if (start === -1) start = i;
  15551. } else if (i !== 0 && (code === 32 || code === 9)) {
  15552. if (end === -1 && start !== -1) end = i;
  15553. } else if (code === 44) {
  15554. if (start === -1) throw new SyntaxError(`Unexpected character at index ${i}`);
  15555. if (end === -1) end = i;
  15556. const protocol = header.slice(start, end);
  15557. if (protocols.has(protocol)) throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`);
  15558. protocols.add(protocol);
  15559. start = end = -1;
  15560. } else throw new SyntaxError(`Unexpected character at index ${i}`);
  15561. }
  15562. if (start === -1 || end !== -1) throw new SyntaxError("Unexpected end of input");
  15563. const protocol = header.slice(start, i);
  15564. if (protocols.has(protocol)) throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`);
  15565. protocols.add(protocol);
  15566. return protocols;
  15567. }
  15568. module.exports = { parse };
  15569. }));
  15570. //#endregion
  15571. //#region ../../node_modules/.pnpm/ws@8.19.0/node_modules/ws/lib/websocket-server.js
  15572. var require_websocket_server = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  15573. const EventEmitter$1 = __require("events");
  15574. const http$4 = __require("http");
  15575. const { Duplex } = __require("stream");
  15576. const { createHash } = __require("crypto");
  15577. const extension = require_extension();
  15578. const PerMessageDeflate = require_permessage_deflate();
  15579. const subprotocol = require_subprotocol();
  15580. const WebSocket = require_websocket();
  15581. const { CLOSE_TIMEOUT, GUID, kWebSocket } = require_constants();
  15582. const keyRegex = /^[+/0-9A-Za-z]{22}==$/;
  15583. const RUNNING = 0;
  15584. const CLOSING = 1;
  15585. const CLOSED = 2;
  15586. /**
  15587. * Class representing a WebSocket server.
  15588. *
  15589. * @extends EventEmitter
  15590. */
  15591. var WebSocketServer = class extends EventEmitter$1 {
  15592. /**
  15593. * Create a `WebSocketServer` instance.
  15594. *
  15595. * @param {Object} options Configuration options
  15596. * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether
  15597. * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
  15598. * multiple times in the same tick
  15599. * @param {Boolean} [options.autoPong=true] Specifies whether or not to
  15600. * automatically send a pong in response to a ping
  15601. * @param {Number} [options.backlog=511] The maximum length of the queue of
  15602. * pending connections
  15603. * @param {Boolean} [options.clientTracking=true] Specifies whether or not to
  15604. * track clients
  15605. * @param {Number} [options.closeTimeout=30000] Duration in milliseconds to
  15606. * wait for the closing handshake to finish after `websocket.close()` is
  15607. * called
  15608. * @param {Function} [options.handleProtocols] A hook to handle protocols
  15609. * @param {String} [options.host] The hostname where to bind the server
  15610. * @param {Number} [options.maxPayload=104857600] The maximum allowed message
  15611. * size
  15612. * @param {Boolean} [options.noServer=false] Enable no server mode
  15613. * @param {String} [options.path] Accept only connections matching this path
  15614. * @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable
  15615. * permessage-deflate
  15616. * @param {Number} [options.port] The port where to bind the server
  15617. * @param {(http.Server|https.Server)} [options.server] A pre-created HTTP/S
  15618. * server to use
  15619. * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
  15620. * not to skip UTF-8 validation for text and close messages
  15621. * @param {Function} [options.verifyClient] A hook to reject connections
  15622. * @param {Function} [options.WebSocket=WebSocket] Specifies the `WebSocket`
  15623. * class to use. It must be the `WebSocket` class or class that extends it
  15624. * @param {Function} [callback] A listener for the `listening` event
  15625. */
  15626. constructor(options, callback) {
  15627. super();
  15628. options = {
  15629. allowSynchronousEvents: true,
  15630. autoPong: true,
  15631. maxPayload: 100 * 1024 * 1024,
  15632. skipUTF8Validation: false,
  15633. perMessageDeflate: false,
  15634. handleProtocols: null,
  15635. clientTracking: true,
  15636. closeTimeout: CLOSE_TIMEOUT,
  15637. verifyClient: null,
  15638. noServer: false,
  15639. backlog: null,
  15640. server: null,
  15641. host: null,
  15642. path: null,
  15643. port: null,
  15644. WebSocket,
  15645. ...options
  15646. };
  15647. 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");
  15648. if (options.port != null) {
  15649. this._server = http$4.createServer((req, res) => {
  15650. const body = http$4.STATUS_CODES[426];
  15651. res.writeHead(426, {
  15652. "Content-Length": body.length,
  15653. "Content-Type": "text/plain"
  15654. });
  15655. res.end(body);
  15656. });
  15657. this._server.listen(options.port, options.host, options.backlog, callback);
  15658. } else if (options.server) this._server = options.server;
  15659. if (this._server) {
  15660. const emitConnection = this.emit.bind(this, "connection");
  15661. this._removeListeners = addListeners(this._server, {
  15662. listening: this.emit.bind(this, "listening"),
  15663. error: this.emit.bind(this, "error"),
  15664. upgrade: (req, socket, head) => {
  15665. this.handleUpgrade(req, socket, head, emitConnection);
  15666. }
  15667. });
  15668. }
  15669. if (options.perMessageDeflate === true) options.perMessageDeflate = {};
  15670. if (options.clientTracking) {
  15671. this.clients = /* @__PURE__ */ new Set();
  15672. this._shouldEmitClose = false;
  15673. }
  15674. this.options = options;
  15675. this._state = RUNNING;
  15676. }
  15677. /**
  15678. * Returns the bound address, the address family name, and port of the server
  15679. * as reported by the operating system if listening on an IP socket.
  15680. * If the server is listening on a pipe or UNIX domain socket, the name is
  15681. * returned as a string.
  15682. *
  15683. * @return {(Object|String|null)} The address of the server
  15684. * @public
  15685. */
  15686. address() {
  15687. if (this.options.noServer) throw new Error("The server is operating in \"noServer\" mode");
  15688. if (!this._server) return null;
  15689. return this._server.address();
  15690. }
  15691. /**
  15692. * Stop the server from accepting new connections and emit the `'close'` event
  15693. * when all existing connections are closed.
  15694. *
  15695. * @param {Function} [cb] A one-time listener for the `'close'` event
  15696. * @public
  15697. */
  15698. close(cb) {
  15699. if (this._state === CLOSED) {
  15700. if (cb) this.once("close", () => {
  15701. cb(/* @__PURE__ */ new Error("The server is not running"));
  15702. });
  15703. process.nextTick(emitClose, this);
  15704. return;
  15705. }
  15706. if (cb) this.once("close", cb);
  15707. if (this._state === CLOSING) return;
  15708. this._state = CLOSING;
  15709. if (this.options.noServer || this.options.server) {
  15710. if (this._server) {
  15711. this._removeListeners();
  15712. this._removeListeners = this._server = null;
  15713. }
  15714. if (this.clients) if (!this.clients.size) process.nextTick(emitClose, this);
  15715. else this._shouldEmitClose = true;
  15716. else process.nextTick(emitClose, this);
  15717. } else {
  15718. const server = this._server;
  15719. this._removeListeners();
  15720. this._removeListeners = this._server = null;
  15721. server.close(() => {
  15722. emitClose(this);
  15723. });
  15724. }
  15725. }
  15726. /**
  15727. * See if a given request should be handled by this server instance.
  15728. *
  15729. * @param {http.IncomingMessage} req Request object to inspect
  15730. * @return {Boolean} `true` if the request is valid, else `false`
  15731. * @public
  15732. */
  15733. shouldHandle(req) {
  15734. if (this.options.path) {
  15735. const index = req.url.indexOf("?");
  15736. if ((index !== -1 ? req.url.slice(0, index) : req.url) !== this.options.path) return false;
  15737. }
  15738. return true;
  15739. }
  15740. /**
  15741. * Handle a HTTP Upgrade request.
  15742. *
  15743. * @param {http.IncomingMessage} req The request object
  15744. * @param {Duplex} socket The network socket between the server and client
  15745. * @param {Buffer} head The first packet of the upgraded stream
  15746. * @param {Function} cb Callback
  15747. * @public
  15748. */
  15749. handleUpgrade(req, socket, head, cb) {
  15750. socket.on("error", socketOnError);
  15751. const key = req.headers["sec-websocket-key"];
  15752. const upgrade = req.headers.upgrade;
  15753. const version = +req.headers["sec-websocket-version"];
  15754. if (req.method !== "GET") {
  15755. abortHandshakeOrEmitwsClientError(this, req, socket, 405, "Invalid HTTP method");
  15756. return;
  15757. }
  15758. if (upgrade === void 0 || upgrade.toLowerCase() !== "websocket") {
  15759. abortHandshakeOrEmitwsClientError(this, req, socket, 400, "Invalid Upgrade header");
  15760. return;
  15761. }
  15762. if (key === void 0 || !keyRegex.test(key)) {
  15763. abortHandshakeOrEmitwsClientError(this, req, socket, 400, "Missing or invalid Sec-WebSocket-Key header");
  15764. return;
  15765. }
  15766. if (version !== 13 && version !== 8) {
  15767. abortHandshakeOrEmitwsClientError(this, req, socket, 400, "Missing or invalid Sec-WebSocket-Version header", { "Sec-WebSocket-Version": "13, 8" });
  15768. return;
  15769. }
  15770. if (!this.shouldHandle(req)) {
  15771. abortHandshake(socket, 400);
  15772. return;
  15773. }
  15774. const secWebSocketProtocol = req.headers["sec-websocket-protocol"];
  15775. let protocols = /* @__PURE__ */ new Set();
  15776. if (secWebSocketProtocol !== void 0) try {
  15777. protocols = subprotocol.parse(secWebSocketProtocol);
  15778. } catch (err) {
  15779. abortHandshakeOrEmitwsClientError(this, req, socket, 400, "Invalid Sec-WebSocket-Protocol header");
  15780. return;
  15781. }
  15782. const secWebSocketExtensions = req.headers["sec-websocket-extensions"];
  15783. const extensions = {};
  15784. if (this.options.perMessageDeflate && secWebSocketExtensions !== void 0) {
  15785. const perMessageDeflate = new PerMessageDeflate(this.options.perMessageDeflate, true, this.options.maxPayload);
  15786. try {
  15787. const offers = extension.parse(secWebSocketExtensions);
  15788. if (offers[PerMessageDeflate.extensionName]) {
  15789. perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]);
  15790. extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
  15791. }
  15792. } catch (err) {
  15793. abortHandshakeOrEmitwsClientError(this, req, socket, 400, "Invalid or unacceptable Sec-WebSocket-Extensions header");
  15794. return;
  15795. }
  15796. }
  15797. if (this.options.verifyClient) {
  15798. const info = {
  15799. origin: req.headers[`${version === 8 ? "sec-websocket-origin" : "origin"}`],
  15800. secure: !!(req.socket.authorized || req.socket.encrypted),
  15801. req
  15802. };
  15803. if (this.options.verifyClient.length === 2) {
  15804. this.options.verifyClient(info, (verified, code, message, headers) => {
  15805. if (!verified) return abortHandshake(socket, code || 401, message, headers);
  15806. this.completeUpgrade(extensions, key, protocols, req, socket, head, cb);
  15807. });
  15808. return;
  15809. }
  15810. if (!this.options.verifyClient(info)) return abortHandshake(socket, 401);
  15811. }
  15812. this.completeUpgrade(extensions, key, protocols, req, socket, head, cb);
  15813. }
  15814. /**
  15815. * Upgrade the connection to WebSocket.
  15816. *
  15817. * @param {Object} extensions The accepted extensions
  15818. * @param {String} key The value of the `Sec-WebSocket-Key` header
  15819. * @param {Set} protocols The subprotocols
  15820. * @param {http.IncomingMessage} req The request object
  15821. * @param {Duplex} socket The network socket between the server and client
  15822. * @param {Buffer} head The first packet of the upgraded stream
  15823. * @param {Function} cb Callback
  15824. * @throws {Error} If called more than once with the same socket
  15825. * @private
  15826. */
  15827. completeUpgrade(extensions, key, protocols, req, socket, head, cb) {
  15828. if (!socket.readable || !socket.writable) return socket.destroy();
  15829. if (socket[kWebSocket]) throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");
  15830. if (this._state > RUNNING) return abortHandshake(socket, 503);
  15831. const headers = [
  15832. "HTTP/1.1 101 Switching Protocols",
  15833. "Upgrade: websocket",
  15834. "Connection: Upgrade",
  15835. `Sec-WebSocket-Accept: ${createHash("sha1").update(key + GUID).digest("base64")}`
  15836. ];
  15837. const ws = new this.options.WebSocket(null, void 0, this.options);
  15838. if (protocols.size) {
  15839. const protocol = this.options.handleProtocols ? this.options.handleProtocols(protocols, req) : protocols.values().next().value;
  15840. if (protocol) {
  15841. headers.push(`Sec-WebSocket-Protocol: ${protocol}`);
  15842. ws._protocol = protocol;
  15843. }
  15844. }
  15845. if (extensions[PerMessageDeflate.extensionName]) {
  15846. const params = extensions[PerMessageDeflate.extensionName].params;
  15847. const value = extension.format({ [PerMessageDeflate.extensionName]: [params] });
  15848. headers.push(`Sec-WebSocket-Extensions: ${value}`);
  15849. ws._extensions = extensions;
  15850. }
  15851. this.emit("headers", headers, req);
  15852. socket.write(headers.concat("\r\n").join("\r\n"));
  15853. socket.removeListener("error", socketOnError);
  15854. ws.setSocket(socket, head, {
  15855. allowSynchronousEvents: this.options.allowSynchronousEvents,
  15856. maxPayload: this.options.maxPayload,
  15857. skipUTF8Validation: this.options.skipUTF8Validation
  15858. });
  15859. if (this.clients) {
  15860. this.clients.add(ws);
  15861. ws.on("close", () => {
  15862. this.clients.delete(ws);
  15863. if (this._shouldEmitClose && !this.clients.size) process.nextTick(emitClose, this);
  15864. });
  15865. }
  15866. cb(ws, req);
  15867. }
  15868. };
  15869. module.exports = WebSocketServer;
  15870. /**
  15871. * Add event listeners on an `EventEmitter` using a map of <event, listener>
  15872. * pairs.
  15873. *
  15874. * @param {EventEmitter} server The event emitter
  15875. * @param {Object.<String, Function>} map The listeners to add
  15876. * @return {Function} A function that will remove the added listeners when
  15877. * called
  15878. * @private
  15879. */
  15880. function addListeners(server, map) {
  15881. for (const event of Object.keys(map)) server.on(event, map[event]);
  15882. return function removeListeners() {
  15883. for (const event of Object.keys(map)) server.removeListener(event, map[event]);
  15884. };
  15885. }
  15886. /**
  15887. * Emit a `'close'` event on an `EventEmitter`.
  15888. *
  15889. * @param {EventEmitter} server The event emitter
  15890. * @private
  15891. */
  15892. function emitClose(server) {
  15893. server._state = CLOSED;
  15894. server.emit("close");
  15895. }
  15896. /**
  15897. * Handle socket errors.
  15898. *
  15899. * @private
  15900. */
  15901. function socketOnError() {
  15902. this.destroy();
  15903. }
  15904. /**
  15905. * Close the connection when preconditions are not fulfilled.
  15906. *
  15907. * @param {Duplex} socket The socket of the upgrade request
  15908. * @param {Number} code The HTTP response status code
  15909. * @param {String} [message] The HTTP response body
  15910. * @param {Object} [headers] Additional HTTP response headers
  15911. * @private
  15912. */
  15913. function abortHandshake(socket, code, message, headers) {
  15914. message = message || http$4.STATUS_CODES[code];
  15915. headers = {
  15916. Connection: "close",
  15917. "Content-Type": "text/html",
  15918. "Content-Length": Buffer.byteLength(message),
  15919. ...headers
  15920. };
  15921. socket.once("finish", socket.destroy);
  15922. 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);
  15923. }
  15924. /**
  15925. * Emit a `'wsClientError'` event on a `WebSocketServer` if there is at least
  15926. * one listener for it, otherwise call `abortHandshake()`.
  15927. *
  15928. * @param {WebSocketServer} server The WebSocket server
  15929. * @param {http.IncomingMessage} req The request object
  15930. * @param {Duplex} socket The socket of the upgrade request
  15931. * @param {Number} code The HTTP response status code
  15932. * @param {String} message The HTTP response body
  15933. * @param {Object} [headers] The HTTP response headers
  15934. * @private
  15935. */
  15936. function abortHandshakeOrEmitwsClientError(server, req, socket, code, message, headers) {
  15937. if (server.listenerCount("wsClientError")) {
  15938. const err = new Error(message);
  15939. Error.captureStackTrace(err, abortHandshakeOrEmitwsClientError);
  15940. server.emit("wsClientError", err, socket, req);
  15941. } else abortHandshake(socket, code, message, headers);
  15942. }
  15943. }));
  15944. require_stream();
  15945. require_receiver();
  15946. require_sender();
  15947. require_websocket();
  15948. var import_websocket_server = /* @__PURE__ */ __toESM(require_websocket_server(), 1);
  15949. //#endregion
  15950. //#region ../../node_modules/.pnpm/host-validation-middleware@0.1.2/node_modules/host-validation-middleware/dist/index.js
  15951. /**
  15952. * This function assumes that the input is not malformed.
  15953. * This is because we only care about browser requests.
  15954. * Non-browser clients can send any value they want anyway.
  15955. */
  15956. function extractHostNameFromHostHeader(hostHeader) {
  15957. const trimmedHost = hostHeader.trim();
  15958. if (trimmedHost[0] === "[") {
  15959. const endIpv6 = trimmedHost.indexOf("]");
  15960. if (endIpv6 < 0) return { type: "invalid" };
  15961. return net.isIP(trimmedHost.slice(1, endIpv6)) === 6 ? { type: "ipv6" } : { type: "invalid" };
  15962. }
  15963. const colonPos = trimmedHost.indexOf(":");
  15964. const hostname = colonPos === -1 ? trimmedHost : trimmedHost.slice(0, colonPos);
  15965. if (net.isIP(hostname) === 4) return { type: "ipv4" };
  15966. return {
  15967. type: "hostname",
  15968. value: hostname
  15969. };
  15970. }
  15971. const isFileOrExtensionProtocolRE = /^(?:file|.+-extension):/i;
  15972. function isHostAllowedInternal(hostHeader, allowedHosts) {
  15973. if (isFileOrExtensionProtocolRE.test(hostHeader)) return true;
  15974. const extracted = extractHostNameFromHostHeader(hostHeader);
  15975. if (extracted.type === "invalid") return false;
  15976. if (extracted.type === "ipv4" || extracted.type === "ipv6") return true;
  15977. const hostname = extracted.value;
  15978. if (hostname === "localhost" || hostname.endsWith(".localhost")) return true;
  15979. for (const allowedHost of allowedHosts) {
  15980. if (allowedHost === hostname) return true;
  15981. if (allowedHost[0] === "." && (allowedHost.slice(1) === hostname || hostname.endsWith(allowedHost))) return true;
  15982. }
  15983. return false;
  15984. }
  15985. const cache = /* @__PURE__ */ new WeakMap();
  15986. /**
  15987. * Check if the host contained in the host header is allowed.
  15988. *
  15989. * This function will cache the result if the `allowedHosts` array is frozen.
  15990. *
  15991. * @param hostHeader - The value of host header. See [RFC 9110 7.2](https://datatracker.ietf.org/doc/html/rfc9110#name-host-and-authority).
  15992. * @param allowedHosts - The allowed host patterns. See the README for more details.
  15993. */
  15994. function isHostAllowed(hostHeader, allowedHosts) {
  15995. if (hostHeader === void 0) return true;
  15996. let cachedAllowedHosts;
  15997. if (Object.isFrozen(allowedHosts)) {
  15998. if (!cache.has(allowedHosts)) cache.set(allowedHosts, /* @__PURE__ */ new Set());
  15999. cachedAllowedHosts = cache.get(allowedHosts);
  16000. if (cachedAllowedHosts.has(hostHeader)) return true;
  16001. }
  16002. const result = isHostAllowedInternal(hostHeader, allowedHosts);
  16003. if (cachedAllowedHosts && result) cachedAllowedHosts.add(hostHeader);
  16004. return result;
  16005. }
  16006. /**
  16007. * Middleware to validate the host header of incoming requests.
  16008. *
  16009. * If the host header is not in the allowed hosts list, a 403 Forbidden response
  16010. * is sent.
  16011. */
  16012. function hostValidationMiddleware$2(options) {
  16013. return async function hostValidationMiddleware$1(req, res, next) {
  16014. const hostHeader = req.headers.host;
  16015. if (!isHostAllowed(hostHeader, options.allowedHosts)) {
  16016. const hostname = hostHeader?.replace(/:\d+$/, "") ?? "";
  16017. const errorMessage = options.generateErrorMessage?.(hostname) ?? generateDefaultErrorMessage(hostname);
  16018. res.writeHead(403, { "Content-Type": options.errorResponseContentType ?? "text/plain" });
  16019. res.end(errorMessage);
  16020. return;
  16021. }
  16022. next();
  16023. };
  16024. }
  16025. function generateDefaultErrorMessage(hostname) {
  16026. return `Blocked request. This host (${JSON.stringify(hostname)}) is not allowed.`;
  16027. }
  16028. //#endregion
  16029. //#region src/node/server/ws.ts
  16030. const WebSocketServerRaw = process.versions.bun ? import.meta.require("ws").WebSocketServer : import_websocket_server.default;
  16031. const isWebSocketServer = Symbol("isWebSocketServer");
  16032. const wsServerEvents = [
  16033. "connection",
  16034. "error",
  16035. "headers",
  16036. "listening",
  16037. "message"
  16038. ];
  16039. function noop$1() {}
  16040. function hasValidToken(config, url) {
  16041. const token = url.searchParams.get("token");
  16042. if (!token) return false;
  16043. try {
  16044. return crypto.timingSafeEqual(Buffer.from(token), Buffer.from(config.webSocketToken));
  16045. } catch {}
  16046. return false;
  16047. }
  16048. function createWebSocketServer(server, config, httpsOptions) {
  16049. if (config.server.ws === false) return {
  16050. [isWebSocketServer]: true,
  16051. get clients() {
  16052. return /* @__PURE__ */ new Set();
  16053. },
  16054. async close() {},
  16055. on: noop$1,
  16056. off: noop$1,
  16057. setInvokeHandler: noop$1,
  16058. handleInvoke: async () => ({ error: {
  16059. name: "TransportError",
  16060. message: "handleInvoke not implemented",
  16061. stack: (/* @__PURE__ */ new Error()).stack
  16062. } }),
  16063. listen: noop$1,
  16064. send: noop$1
  16065. };
  16066. let wsHttpServer = void 0;
  16067. const hmr = isObject$1(config.server.hmr) && config.server.hmr;
  16068. const hmrServer = hmr && hmr.server;
  16069. const hmrPort = hmr && hmr.port;
  16070. const wsServer = hmrServer || (!hmrPort || hmrPort === config.server.port) && server;
  16071. let hmrServerWsListener;
  16072. const customListeners = /* @__PURE__ */ new Map();
  16073. const clientsMap = /* @__PURE__ */ new WeakMap();
  16074. const port = hmrPort || 24678;
  16075. const host = hmr && hmr.host || void 0;
  16076. const allowedHosts = config.server.allowedHosts === true ? config.server.allowedHosts : Object.freeze([...config.server.allowedHosts]);
  16077. const shouldHandle = (req) => {
  16078. if (req.headers["sec-websocket-protocol"] === "vite-ping") return true;
  16079. if (allowedHosts !== true && !isHostAllowed(req.headers.host, allowedHosts)) return false;
  16080. if (config.legacy?.skipWebSocketTokenCheck) return true;
  16081. if (req.headers.origin) return hasValidToken(config, new URL(`http://example.com${req.url}`));
  16082. return true;
  16083. };
  16084. const handleUpgrade = (req, socket, head, isPing) => {
  16085. wss.handleUpgrade(req, socket, head, (ws) => {
  16086. if (isPing) {
  16087. ws.close(1e3);
  16088. return;
  16089. }
  16090. wss.emit("connection", ws, req);
  16091. });
  16092. };
  16093. const wss = new WebSocketServerRaw({ noServer: true });
  16094. wss.shouldHandle = shouldHandle;
  16095. if (wsServer) {
  16096. let hmrBase = config.base;
  16097. const hmrPath = hmr ? hmr.path : void 0;
  16098. if (hmrPath) hmrBase = path.posix.join(hmrBase, hmrPath);
  16099. hmrServerWsListener = (req, socket, head) => {
  16100. const protocol = req.headers["sec-websocket-protocol"];
  16101. const parsedUrl = new URL(`http://example.com${req.url}`);
  16102. if (["vite-hmr", "vite-ping"].includes(protocol) && parsedUrl.pathname === hmrBase) handleUpgrade(req, socket, head, protocol === "vite-ping");
  16103. };
  16104. wsServer.on("upgrade", hmrServerWsListener);
  16105. } else {
  16106. const route = ((_, res) => {
  16107. const statusCode = 426;
  16108. const body = STATUS_CODES[statusCode];
  16109. if (!body) throw new Error(`No body text found for the ${statusCode} status code`);
  16110. res.writeHead(statusCode, {
  16111. "Content-Length": body.length,
  16112. "Content-Type": "text/plain"
  16113. });
  16114. res.end(body);
  16115. });
  16116. if (httpsOptions) wsHttpServer = createServer$1(httpsOptions, route);
  16117. else wsHttpServer = createServer(route);
  16118. wsHttpServer.on("upgrade", (req, socket, head) => {
  16119. const protocol = req.headers["sec-websocket-protocol"];
  16120. if (protocol === "vite-ping" && server && !server.listening) {
  16121. req.destroy();
  16122. return;
  16123. }
  16124. handleUpgrade(req, socket, head, protocol === "vite-ping");
  16125. });
  16126. wsHttpServer.on("error", (e) => {
  16127. if (e.code === "EADDRINUSE") config.logger.error(import_picocolors.default.red(`WebSocket server error: Port ${e.port} is already in use`), { error: e });
  16128. else config.logger.error(import_picocolors.default.red(`WebSocket server error:\n${e.stack || e.message}`), { error: e });
  16129. });
  16130. }
  16131. const emitCustomEvent = (event, data, socket) => {
  16132. const listeners = customListeners.get(event);
  16133. if (!listeners?.size) return;
  16134. const client = getSocketClient(socket);
  16135. for (const listener of listeners) listener(data, client);
  16136. };
  16137. wss.on("connection", (socket) => {
  16138. socket.on("message", (raw) => {
  16139. if (!customListeners.size) return;
  16140. let parsed;
  16141. try {
  16142. parsed = JSON.parse(String(raw));
  16143. } catch {}
  16144. if (!parsed || parsed.type !== "custom" || !parsed.event) return;
  16145. emitCustomEvent(parsed.event, parsed.data, socket);
  16146. });
  16147. socket.on("error", (err) => {
  16148. config.logger.error(`${import_picocolors.default.red(`ws error:`)}\n${err.stack}`, {
  16149. timestamp: true,
  16150. error: err
  16151. });
  16152. });
  16153. socket.on("close", () => {
  16154. emitCustomEvent("vite:client:disconnect", void 0, socket);
  16155. });
  16156. emitCustomEvent("vite:client:connect", void 0, socket);
  16157. socket.send(JSON.stringify({ type: "connected" }));
  16158. if (bufferedMessage) {
  16159. socket.send(JSON.stringify(bufferedMessage));
  16160. bufferedMessage = null;
  16161. }
  16162. });
  16163. wss.on("error", (e) => {
  16164. if (e.code === "EADDRINUSE") config.logger.error(import_picocolors.default.red(`WebSocket server error: Port ${e.port} is already in use`), { error: e });
  16165. else config.logger.error(import_picocolors.default.red(`WebSocket server error:\n${e.stack || e.message}`), { error: e });
  16166. });
  16167. function getSocketClient(socket) {
  16168. if (!clientsMap.has(socket)) clientsMap.set(socket, {
  16169. send: (...args) => {
  16170. let payload;
  16171. if (typeof args[0] === "string") payload = {
  16172. type: "custom",
  16173. event: args[0],
  16174. data: args[1]
  16175. };
  16176. else payload = args[0];
  16177. socket.send(JSON.stringify(payload));
  16178. },
  16179. socket
  16180. });
  16181. return clientsMap.get(socket);
  16182. }
  16183. let bufferedMessage = null;
  16184. const normalizedHotChannel = normalizeHotChannel({
  16185. send(payload) {
  16186. if ((payload.type === "error" || payload.type === "full-reload") && !wss.clients.size) {
  16187. bufferedMessage = payload;
  16188. return;
  16189. }
  16190. const stringified = JSON.stringify(payload);
  16191. wss.clients.forEach((client) => {
  16192. if (client.readyState === 1) client.send(stringified);
  16193. });
  16194. },
  16195. on(event, fn) {
  16196. if (!customListeners.has(event)) customListeners.set(event, /* @__PURE__ */ new Set());
  16197. customListeners.get(event).add(fn);
  16198. },
  16199. off(event, fn) {
  16200. customListeners.get(event)?.delete(fn);
  16201. },
  16202. listen() {
  16203. wsHttpServer?.listen(port, host);
  16204. },
  16205. close() {
  16206. if (hmrServerWsListener && wsServer) wsServer.off("upgrade", hmrServerWsListener);
  16207. return new Promise((resolve, reject) => {
  16208. wss.clients.forEach((client) => {
  16209. client.terminate();
  16210. });
  16211. wss.close((err) => {
  16212. if (err) reject(err);
  16213. else if (wsHttpServer) wsHttpServer.close((err) => {
  16214. if (err) reject(err);
  16215. else resolve();
  16216. });
  16217. else resolve();
  16218. });
  16219. });
  16220. }
  16221. }, config.server.hmr !== false, false);
  16222. return {
  16223. ...normalizedHotChannel,
  16224. on: ((event, fn) => {
  16225. if (wsServerEvents.includes(event)) {
  16226. wss.on(event, fn);
  16227. return;
  16228. }
  16229. normalizedHotChannel.on(event, fn);
  16230. }),
  16231. off: ((event, fn) => {
  16232. if (wsServerEvents.includes(event)) {
  16233. wss.off(event, fn);
  16234. return;
  16235. }
  16236. normalizedHotChannel.off(event, fn);
  16237. }),
  16238. async close() {
  16239. await normalizedHotChannel.close();
  16240. },
  16241. [isWebSocketServer]: true,
  16242. get clients() {
  16243. return new Set(Array.from(wss.clients).map(getSocketClient));
  16244. }
  16245. };
  16246. }
  16247. //#endregion
  16248. //#region src/node/server/middlewares/base.ts
  16249. function baseMiddleware(rawBase, middlewareMode) {
  16250. return function viteBaseMiddleware(req, res, next) {
  16251. const url = req.url;
  16252. const pathname = cleanUrl(url);
  16253. const base = rawBase;
  16254. if (pathname.startsWith(base)) {
  16255. req.url = stripBase(url, base);
  16256. return next();
  16257. }
  16258. if (middlewareMode) return next();
  16259. if (pathname === "/" || pathname === "/index.html") {
  16260. res.writeHead(302, { Location: base + url.slice(pathname.length) });
  16261. res.end();
  16262. return;
  16263. }
  16264. const redirectPath = withTrailingSlash(url) !== base ? joinUrlSegments(base, url) : base;
  16265. if (req.headers.accept?.includes("text/html")) {
  16266. res.writeHead(404, { "Content-Type": "text/html" });
  16267. res.end(`The server is configured with a public base URL of ${base} - did you mean to visit <a href="${redirectPath}">${redirectPath}</a> instead?`);
  16268. return;
  16269. } else {
  16270. res.writeHead(404, { "Content-Type": "text/plain" });
  16271. res.end(`The server is configured with a public base URL of ${base} - did you mean to visit ${redirectPath} instead?`);
  16272. return;
  16273. }
  16274. };
  16275. }
  16276. //#endregion
  16277. //#region ../../node_modules/.pnpm/follow-redirects@1.15.11_obug@1.0.2_ms@2.1.3_/node_modules/follow-redirects/debug.js
  16278. var require_debug = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  16279. var debug;
  16280. module.exports = function() {
  16281. if (!debug) {
  16282. try {
  16283. debug = (init_node(), __toCommonJS(node_exports))("follow-redirects");
  16284. } catch (error) {}
  16285. if (typeof debug !== "function") debug = function() {};
  16286. }
  16287. debug.apply(null, arguments);
  16288. };
  16289. }));
  16290. //#endregion
  16291. //#region ../../node_modules/.pnpm/follow-redirects@1.15.11_obug@1.0.2_ms@2.1.3_/node_modules/follow-redirects/index.js
  16292. var require_follow_redirects = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  16293. var url$1 = __require("url");
  16294. var URL = url$1.URL;
  16295. var http$3 = __require("http");
  16296. var https$2 = __require("https");
  16297. var Writable = __require("stream").Writable;
  16298. var assert$1 = __require("assert");
  16299. var debug = require_debug();
  16300. // istanbul ignore next
  16301. (function detectUnsupportedEnvironment() {
  16302. var looksLikeNode = typeof process !== "undefined";
  16303. var looksLikeBrowser = typeof window !== "undefined" && typeof document !== "undefined";
  16304. var looksLikeV8 = isFunction(Error.captureStackTrace);
  16305. if (!looksLikeNode && (looksLikeBrowser || !looksLikeV8)) console.warn("The follow-redirects package should be excluded from browser builds.");
  16306. })();
  16307. var useNativeURL = false;
  16308. try {
  16309. assert$1(new URL(""));
  16310. } catch (error) {
  16311. useNativeURL = error.code === "ERR_INVALID_URL";
  16312. }
  16313. var preservedUrlFields = [
  16314. "auth",
  16315. "host",
  16316. "hostname",
  16317. "href",
  16318. "path",
  16319. "pathname",
  16320. "port",
  16321. "protocol",
  16322. "query",
  16323. "search",
  16324. "hash"
  16325. ];
  16326. var events = [
  16327. "abort",
  16328. "aborted",
  16329. "connect",
  16330. "error",
  16331. "socket",
  16332. "timeout"
  16333. ];
  16334. var eventHandlers = Object.create(null);
  16335. events.forEach(function(event) {
  16336. eventHandlers[event] = function(arg1, arg2, arg3) {
  16337. this._redirectable.emit(event, arg1, arg2, arg3);
  16338. };
  16339. });
  16340. var InvalidUrlError = createErrorType("ERR_INVALID_URL", "Invalid URL", TypeError);
  16341. var RedirectionError = createErrorType("ERR_FR_REDIRECTION_FAILURE", "Redirected request failed");
  16342. var TooManyRedirectsError = createErrorType("ERR_FR_TOO_MANY_REDIRECTS", "Maximum number of redirects exceeded", RedirectionError);
  16343. var MaxBodyLengthExceededError = createErrorType("ERR_FR_MAX_BODY_LENGTH_EXCEEDED", "Request body larger than maxBodyLength limit");
  16344. var WriteAfterEndError = createErrorType("ERR_STREAM_WRITE_AFTER_END", "write after end");
  16345. // istanbul ignore next
  16346. var destroy = Writable.prototype.destroy || noop;
  16347. function RedirectableRequest(options, responseCallback) {
  16348. Writable.call(this);
  16349. this._sanitizeOptions(options);
  16350. this._options = options;
  16351. this._ended = false;
  16352. this._ending = false;
  16353. this._redirectCount = 0;
  16354. this._redirects = [];
  16355. this._requestBodyLength = 0;
  16356. this._requestBodyBuffers = [];
  16357. if (responseCallback) this.on("response", responseCallback);
  16358. var self = this;
  16359. this._onNativeResponse = function(response) {
  16360. try {
  16361. self._processResponse(response);
  16362. } catch (cause) {
  16363. self.emit("error", cause instanceof RedirectionError ? cause : new RedirectionError({ cause }));
  16364. }
  16365. };
  16366. this._performRequest();
  16367. }
  16368. RedirectableRequest.prototype = Object.create(Writable.prototype);
  16369. RedirectableRequest.prototype.abort = function() {
  16370. destroyRequest(this._currentRequest);
  16371. this._currentRequest.abort();
  16372. this.emit("abort");
  16373. };
  16374. RedirectableRequest.prototype.destroy = function(error) {
  16375. destroyRequest(this._currentRequest, error);
  16376. destroy.call(this, error);
  16377. return this;
  16378. };
  16379. RedirectableRequest.prototype.write = function(data, encoding, callback) {
  16380. if (this._ending) throw new WriteAfterEndError();
  16381. if (!isString(data) && !isBuffer(data)) throw new TypeError("data should be a string, Buffer or Uint8Array");
  16382. if (isFunction(encoding)) {
  16383. callback = encoding;
  16384. encoding = null;
  16385. }
  16386. if (data.length === 0) {
  16387. if (callback) callback();
  16388. return;
  16389. }
  16390. if (this._requestBodyLength + data.length <= this._options.maxBodyLength) {
  16391. this._requestBodyLength += data.length;
  16392. this._requestBodyBuffers.push({
  16393. data,
  16394. encoding
  16395. });
  16396. this._currentRequest.write(data, encoding, callback);
  16397. } else {
  16398. this.emit("error", new MaxBodyLengthExceededError());
  16399. this.abort();
  16400. }
  16401. };
  16402. RedirectableRequest.prototype.end = function(data, encoding, callback) {
  16403. if (isFunction(data)) {
  16404. callback = data;
  16405. data = encoding = null;
  16406. } else if (isFunction(encoding)) {
  16407. callback = encoding;
  16408. encoding = null;
  16409. }
  16410. if (!data) {
  16411. this._ended = this._ending = true;
  16412. this._currentRequest.end(null, null, callback);
  16413. } else {
  16414. var self = this;
  16415. var currentRequest = this._currentRequest;
  16416. this.write(data, encoding, function() {
  16417. self._ended = true;
  16418. currentRequest.end(null, null, callback);
  16419. });
  16420. this._ending = true;
  16421. }
  16422. };
  16423. RedirectableRequest.prototype.setHeader = function(name, value) {
  16424. this._options.headers[name] = value;
  16425. this._currentRequest.setHeader(name, value);
  16426. };
  16427. RedirectableRequest.prototype.removeHeader = function(name) {
  16428. delete this._options.headers[name];
  16429. this._currentRequest.removeHeader(name);
  16430. };
  16431. RedirectableRequest.prototype.setTimeout = function(msecs, callback) {
  16432. var self = this;
  16433. function destroyOnTimeout(socket) {
  16434. socket.setTimeout(msecs);
  16435. socket.removeListener("timeout", socket.destroy);
  16436. socket.addListener("timeout", socket.destroy);
  16437. }
  16438. function startTimer(socket) {
  16439. if (self._timeout) clearTimeout(self._timeout);
  16440. self._timeout = setTimeout(function() {
  16441. self.emit("timeout");
  16442. clearTimer();
  16443. }, msecs);
  16444. destroyOnTimeout(socket);
  16445. }
  16446. function clearTimer() {
  16447. if (self._timeout) {
  16448. clearTimeout(self._timeout);
  16449. self._timeout = null;
  16450. }
  16451. self.removeListener("abort", clearTimer);
  16452. self.removeListener("error", clearTimer);
  16453. self.removeListener("response", clearTimer);
  16454. self.removeListener("close", clearTimer);
  16455. if (callback) self.removeListener("timeout", callback);
  16456. if (!self.socket) self._currentRequest.removeListener("socket", startTimer);
  16457. }
  16458. if (callback) this.on("timeout", callback);
  16459. if (this.socket) startTimer(this.socket);
  16460. else this._currentRequest.once("socket", startTimer);
  16461. this.on("socket", destroyOnTimeout);
  16462. this.on("abort", clearTimer);
  16463. this.on("error", clearTimer);
  16464. this.on("response", clearTimer);
  16465. this.on("close", clearTimer);
  16466. return this;
  16467. };
  16468. [
  16469. "flushHeaders",
  16470. "getHeader",
  16471. "setNoDelay",
  16472. "setSocketKeepAlive"
  16473. ].forEach(function(method) {
  16474. RedirectableRequest.prototype[method] = function(a, b) {
  16475. return this._currentRequest[method](a, b);
  16476. };
  16477. });
  16478. [
  16479. "aborted",
  16480. "connection",
  16481. "socket"
  16482. ].forEach(function(property) {
  16483. Object.defineProperty(RedirectableRequest.prototype, property, { get: function() {
  16484. return this._currentRequest[property];
  16485. } });
  16486. });
  16487. RedirectableRequest.prototype._sanitizeOptions = function(options) {
  16488. if (!options.headers) options.headers = {};
  16489. if (options.host) {
  16490. if (!options.hostname) options.hostname = options.host;
  16491. delete options.host;
  16492. }
  16493. if (!options.pathname && options.path) {
  16494. var searchPos = options.path.indexOf("?");
  16495. if (searchPos < 0) options.pathname = options.path;
  16496. else {
  16497. options.pathname = options.path.substring(0, searchPos);
  16498. options.search = options.path.substring(searchPos);
  16499. }
  16500. }
  16501. };
  16502. RedirectableRequest.prototype._performRequest = function() {
  16503. var protocol = this._options.protocol;
  16504. var nativeProtocol = this._options.nativeProtocols[protocol];
  16505. if (!nativeProtocol) throw new TypeError("Unsupported protocol " + protocol);
  16506. if (this._options.agents) {
  16507. var scheme = protocol.slice(0, -1);
  16508. this._options.agent = this._options.agents[scheme];
  16509. }
  16510. var request = this._currentRequest = nativeProtocol.request(this._options, this._onNativeResponse);
  16511. request._redirectable = this;
  16512. for (var event of events) request.on(event, eventHandlers[event]);
  16513. this._currentUrl = /^\//.test(this._options.path) ? url$1.format(this._options) : this._options.path;
  16514. if (this._isRedirect) {
  16515. var i = 0;
  16516. var self = this;
  16517. var buffers = this._requestBodyBuffers;
  16518. (function writeNext(error) {
  16519. // istanbul ignore else
  16520. if (request === self._currentRequest) {
  16521. // istanbul ignore if
  16522. if (error) self.emit("error", error);
  16523. else if (i < buffers.length) {
  16524. var buffer = buffers[i++];
  16525. // istanbul ignore else
  16526. if (!request.finished) request.write(buffer.data, buffer.encoding, writeNext);
  16527. } else if (self._ended) request.end();
  16528. }
  16529. })();
  16530. }
  16531. };
  16532. RedirectableRequest.prototype._processResponse = function(response) {
  16533. var statusCode = response.statusCode;
  16534. if (this._options.trackRedirects) this._redirects.push({
  16535. url: this._currentUrl,
  16536. headers: response.headers,
  16537. statusCode
  16538. });
  16539. var location = response.headers.location;
  16540. if (!location || this._options.followRedirects === false || statusCode < 300 || statusCode >= 400) {
  16541. response.responseUrl = this._currentUrl;
  16542. response.redirects = this._redirects;
  16543. this.emit("response", response);
  16544. this._requestBodyBuffers = [];
  16545. return;
  16546. }
  16547. destroyRequest(this._currentRequest);
  16548. response.destroy();
  16549. if (++this._redirectCount > this._options.maxRedirects) throw new TooManyRedirectsError();
  16550. var requestHeaders;
  16551. var beforeRedirect = this._options.beforeRedirect;
  16552. if (beforeRedirect) requestHeaders = Object.assign({ Host: response.req.getHeader("host") }, this._options.headers);
  16553. var method = this._options.method;
  16554. if ((statusCode === 301 || statusCode === 302) && this._options.method === "POST" || statusCode === 303 && !/^(?:GET|HEAD)$/.test(this._options.method)) {
  16555. this._options.method = "GET";
  16556. this._requestBodyBuffers = [];
  16557. removeMatchingHeaders(/^content-/i, this._options.headers);
  16558. }
  16559. var currentHostHeader = removeMatchingHeaders(/^host$/i, this._options.headers);
  16560. var currentUrlParts = parseUrl(this._currentUrl);
  16561. var currentHost = currentHostHeader || currentUrlParts.host;
  16562. var currentUrl = /^\w+:/.test(location) ? this._currentUrl : url$1.format(Object.assign(currentUrlParts, { host: currentHost }));
  16563. var redirectUrl = resolveUrl(location, currentUrl);
  16564. debug("redirecting to", redirectUrl.href);
  16565. this._isRedirect = true;
  16566. spreadUrlObject(redirectUrl, this._options);
  16567. if (redirectUrl.protocol !== currentUrlParts.protocol && redirectUrl.protocol !== "https:" || redirectUrl.host !== currentHost && !isSubdomain(redirectUrl.host, currentHost)) removeMatchingHeaders(/^(?:(?:proxy-)?authorization|cookie)$/i, this._options.headers);
  16568. if (isFunction(beforeRedirect)) {
  16569. beforeRedirect(this._options, {
  16570. headers: response.headers,
  16571. statusCode
  16572. }, {
  16573. url: currentUrl,
  16574. method,
  16575. headers: requestHeaders
  16576. });
  16577. this._sanitizeOptions(this._options);
  16578. }
  16579. this._performRequest();
  16580. };
  16581. function wrap(protocols) {
  16582. var exports$1 = {
  16583. maxRedirects: 21,
  16584. maxBodyLength: 10 * 1024 * 1024
  16585. };
  16586. var nativeProtocols = {};
  16587. Object.keys(protocols).forEach(function(scheme) {
  16588. var protocol = scheme + ":";
  16589. var nativeProtocol = nativeProtocols[protocol] = protocols[scheme];
  16590. var wrappedProtocol = exports$1[scheme] = Object.create(nativeProtocol);
  16591. function request(input, options, callback) {
  16592. if (isURL(input)) input = spreadUrlObject(input);
  16593. else if (isString(input)) input = spreadUrlObject(parseUrl(input));
  16594. else {
  16595. callback = options;
  16596. options = validateUrl(input);
  16597. input = { protocol };
  16598. }
  16599. if (isFunction(options)) {
  16600. callback = options;
  16601. options = null;
  16602. }
  16603. options = Object.assign({
  16604. maxRedirects: exports$1.maxRedirects,
  16605. maxBodyLength: exports$1.maxBodyLength
  16606. }, input, options);
  16607. options.nativeProtocols = nativeProtocols;
  16608. if (!isString(options.host) && !isString(options.hostname)) options.hostname = "::1";
  16609. assert$1.equal(options.protocol, protocol, "protocol mismatch");
  16610. debug("options", options);
  16611. return new RedirectableRequest(options, callback);
  16612. }
  16613. function get(input, options, callback) {
  16614. var wrappedRequest = wrappedProtocol.request(input, options, callback);
  16615. wrappedRequest.end();
  16616. return wrappedRequest;
  16617. }
  16618. Object.defineProperties(wrappedProtocol, {
  16619. request: {
  16620. value: request,
  16621. configurable: true,
  16622. enumerable: true,
  16623. writable: true
  16624. },
  16625. get: {
  16626. value: get,
  16627. configurable: true,
  16628. enumerable: true,
  16629. writable: true
  16630. }
  16631. });
  16632. });
  16633. return exports$1;
  16634. }
  16635. function noop() {}
  16636. function parseUrl(input) {
  16637. var parsed;
  16638. // istanbul ignore else
  16639. if (useNativeURL) parsed = new URL(input);
  16640. else {
  16641. parsed = validateUrl(url$1.parse(input));
  16642. if (!isString(parsed.protocol)) throw new InvalidUrlError({ input });
  16643. }
  16644. return parsed;
  16645. }
  16646. function resolveUrl(relative, base) {
  16647. // istanbul ignore next
  16648. return useNativeURL ? new URL(relative, base) : parseUrl(url$1.resolve(base, relative));
  16649. }
  16650. function validateUrl(input) {
  16651. if (/^\[/.test(input.hostname) && !/^\[[:0-9a-f]+\]$/i.test(input.hostname)) throw new InvalidUrlError({ input: input.href || input });
  16652. if (/^\[/.test(input.host) && !/^\[[:0-9a-f]+\](:\d+)?$/i.test(input.host)) throw new InvalidUrlError({ input: input.href || input });
  16653. return input;
  16654. }
  16655. function spreadUrlObject(urlObject, target) {
  16656. var spread = target || {};
  16657. for (var key of preservedUrlFields) spread[key] = urlObject[key];
  16658. if (spread.hostname.startsWith("[")) spread.hostname = spread.hostname.slice(1, -1);
  16659. if (spread.port !== "") spread.port = Number(spread.port);
  16660. spread.path = spread.search ? spread.pathname + spread.search : spread.pathname;
  16661. return spread;
  16662. }
  16663. function removeMatchingHeaders(regex, headers) {
  16664. var lastValue;
  16665. for (var header in headers) if (regex.test(header)) {
  16666. lastValue = headers[header];
  16667. delete headers[header];
  16668. }
  16669. return lastValue === null || typeof lastValue === "undefined" ? void 0 : String(lastValue).trim();
  16670. }
  16671. function createErrorType(code, message, baseClass) {
  16672. function CustomError(properties) {
  16673. // istanbul ignore else
  16674. if (isFunction(Error.captureStackTrace)) Error.captureStackTrace(this, this.constructor);
  16675. Object.assign(this, properties || {});
  16676. this.code = code;
  16677. this.message = this.cause ? message + ": " + this.cause.message : message;
  16678. }
  16679. CustomError.prototype = new (baseClass || Error)();
  16680. Object.defineProperties(CustomError.prototype, {
  16681. constructor: {
  16682. value: CustomError,
  16683. enumerable: false
  16684. },
  16685. name: {
  16686. value: "Error [" + code + "]",
  16687. enumerable: false
  16688. }
  16689. });
  16690. return CustomError;
  16691. }
  16692. function destroyRequest(request, error) {
  16693. for (var event of events) request.removeListener(event, eventHandlers[event]);
  16694. request.on("error", noop);
  16695. request.destroy(error);
  16696. }
  16697. function isSubdomain(subdomain, domain) {
  16698. assert$1(isString(subdomain) && isString(domain));
  16699. var dot = subdomain.length - domain.length - 1;
  16700. return dot > 0 && subdomain[dot] === "." && subdomain.endsWith(domain);
  16701. }
  16702. function isString(value) {
  16703. return typeof value === "string" || value instanceof String;
  16704. }
  16705. function isFunction(value) {
  16706. return typeof value === "function";
  16707. }
  16708. function isBuffer(value) {
  16709. return typeof value === "object" && "length" in value;
  16710. }
  16711. function isURL(value) {
  16712. return URL && value instanceof URL;
  16713. }
  16714. module.exports = wrap({
  16715. http: http$3,
  16716. https: https$2
  16717. });
  16718. module.exports.wrap = wrap;
  16719. }));
  16720. //#endregion
  16721. //#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
  16722. var require_common = /* @__PURE__ */ __commonJSMin(((exports) => {
  16723. Object.defineProperty(exports, "__esModule", { value: true });
  16724. exports.isSSL = void 0;
  16725. exports.setupOutgoing = setupOutgoing;
  16726. exports.setupSocket = setupSocket;
  16727. exports.getPort = getPort;
  16728. exports.hasEncryptedConnection = hasEncryptedConnection;
  16729. exports.urlJoin = urlJoin;
  16730. exports.rewriteCookieProperty = rewriteCookieProperty;
  16731. exports.toURL = toURL;
  16732. const node_tls_1 = __require("node:tls");
  16733. const upgradeHeader = /(^|,)\s*upgrade\s*($|,)/i;
  16734. exports.isSSL = /^https|wss/;
  16735. const HEADER_BLACKLIST = "trailer";
  16736. const HTTP2_HEADER_BLACKLIST = [
  16737. ":method",
  16738. ":path",
  16739. ":scheme",
  16740. ":authority",
  16741. "connection",
  16742. "keep-alive"
  16743. ];
  16744. function setupOutgoing(outgoing, options, req, forward) {
  16745. const target = options[forward || "target"];
  16746. outgoing.port = +(target.port ?? (target.protocol !== void 0 && exports.isSSL.test(target.protocol) ? 443 : 80));
  16747. for (const e of [
  16748. "host",
  16749. "hostname",
  16750. "socketPath",
  16751. "pfx",
  16752. "key",
  16753. "passphrase",
  16754. "cert",
  16755. "ca",
  16756. "ciphers",
  16757. "secureProtocol"
  16758. ]) outgoing[e] = target[e];
  16759. outgoing.method = options.method || req.method;
  16760. outgoing.headers = { ...req.headers };
  16761. if (req.headers?.[":authority"]) outgoing.headers.host = req.headers[":authority"];
  16762. if (options.headers) outgoing.headers = {
  16763. ...outgoing.headers,
  16764. ...options.headers
  16765. };
  16766. for (const header in outgoing.headers) if (HEADER_BLACKLIST == header.toLowerCase()) {
  16767. delete outgoing.headers[header];
  16768. break;
  16769. }
  16770. if (req.httpVersionMajor > 1) for (const header of HTTP2_HEADER_BLACKLIST) delete outgoing.headers[header];
  16771. if (options.auth) {
  16772. delete outgoing.headers.authorization;
  16773. outgoing.auth = options.auth;
  16774. }
  16775. if (options.ca) outgoing.ca = options.ca;
  16776. if (target.protocol !== void 0 && exports.isSSL.test(target.protocol)) outgoing.rejectUnauthorized = typeof options.secure === "undefined" ? true : options.secure;
  16777. outgoing.agent = options.agent || false;
  16778. outgoing.localAddress = options.localAddress;
  16779. if (!outgoing.agent) {
  16780. outgoing.headers = outgoing.headers || {};
  16781. if (typeof outgoing.headers.connection !== "string" || !upgradeHeader.test(outgoing.headers.connection)) outgoing.headers.connection = "close";
  16782. }
  16783. const targetPath = target && options.prependPath !== false && "pathname" in target ? getPath(`${target.pathname}${target.search ?? ""}`) : "/";
  16784. let outgoingPath = options.toProxy ? req.url : getPath(req.url);
  16785. outgoingPath = !options.ignorePath ? outgoingPath : "";
  16786. outgoing.path = urlJoin(targetPath, outgoingPath ?? "");
  16787. if (options.changeOrigin) outgoing.headers.host = target.protocol !== void 0 && required(outgoing.port, target.protocol) && !hasPort(outgoing.host) ? outgoing.host + ":" + outgoing.port : outgoing.host;
  16788. outgoing.url = "href" in target && target.href || (target.protocol === "https" ? "https" : "http") + "://" + outgoing.host + (outgoing.port ? ":" + outgoing.port : "");
  16789. if (req.httpVersionMajor > 1) for (const header of HTTP2_HEADER_BLACKLIST) delete outgoing.headers[header];
  16790. return outgoing;
  16791. }
  16792. function setupSocket(socket) {
  16793. socket.setTimeout(0);
  16794. socket.setNoDelay(true);
  16795. socket.setKeepAlive(true, 0);
  16796. return socket;
  16797. }
  16798. function getPort(req) {
  16799. const hostHeader = req.headers[":authority"] || req.headers.host;
  16800. const res = hostHeader ? hostHeader.match(/:(\d+)/) : "";
  16801. return res ? res[1] : hasEncryptedConnection(req) ? "443" : "80";
  16802. }
  16803. function hasEncryptedConnection(req) {
  16804. const conn = req.connection;
  16805. return conn instanceof node_tls_1.TLSSocket && conn.encrypted || Boolean(conn.pair);
  16806. }
  16807. function urlJoin(...args) {
  16808. const queryParams = [];
  16809. let queryParamRaw = "";
  16810. args.forEach((url, index) => {
  16811. const qpStart = url.indexOf("?");
  16812. if (qpStart !== -1) {
  16813. queryParams.push(url.substring(qpStart + 1));
  16814. args[index] = url.substring(0, qpStart);
  16815. }
  16816. });
  16817. queryParamRaw = queryParams.filter(Boolean).join("&");
  16818. let retSegs = "";
  16819. for (const seg of args) {
  16820. if (!seg) continue;
  16821. if (retSegs.endsWith("/")) if (seg.startsWith("/")) retSegs += seg.slice(1);
  16822. else retSegs += seg;
  16823. else if (seg.startsWith("/")) retSegs += seg;
  16824. else retSegs += "/" + seg;
  16825. }
  16826. return queryParamRaw ? retSegs + "?" + queryParamRaw : retSegs;
  16827. }
  16828. function rewriteCookieProperty(header, config, property) {
  16829. if (Array.isArray(header)) return header.map((headerElement) => {
  16830. return rewriteCookieProperty(headerElement, config, property);
  16831. });
  16832. return header.replace(new RegExp("(;\\s*" + property + "=)([^;]+)", "i"), (match, prefix, previousValue) => {
  16833. let newValue;
  16834. if (previousValue in config) newValue = config[previousValue];
  16835. else if ("*" in config) newValue = config["*"];
  16836. else return match;
  16837. if (newValue) return prefix + newValue;
  16838. else return "";
  16839. });
  16840. }
  16841. function hasPort(host) {
  16842. return !!~host.indexOf(":");
  16843. }
  16844. function getPath(url) {
  16845. if (url === "" || url?.startsWith("?")) return url;
  16846. const u = toURL(url);
  16847. return `${u.pathname ?? ""}${u.search ?? ""}`;
  16848. }
  16849. function toURL(url) {
  16850. if (url instanceof URL) return url;
  16851. else if (typeof url === "object" && "href" in url && typeof url.href === "string") url = url.href;
  16852. if (!url) url = "";
  16853. if (typeof url != "string") url = `${url}`;
  16854. if (url.startsWith("//")) url = `http://base.invalid${url}`;
  16855. return new URL(url, "http://base.invalid");
  16856. }
  16857. function required(port, protocol) {
  16858. protocol = protocol.split(":")[0];
  16859. port = +port;
  16860. if (!port) return false;
  16861. switch (protocol) {
  16862. case "http":
  16863. case "ws": return port !== 80;
  16864. case "https":
  16865. case "wss": return port !== 443;
  16866. }
  16867. return port !== 0;
  16868. }
  16869. }));
  16870. //#endregion
  16871. //#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
  16872. var require_web_outgoing = /* @__PURE__ */ __commonJSMin(((exports) => {
  16873. var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o, m, k, k2) {
  16874. if (k2 === void 0) k2 = k;
  16875. var desc = Object.getOwnPropertyDescriptor(m, k);
  16876. if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) desc = {
  16877. enumerable: true,
  16878. get: function() {
  16879. return m[k];
  16880. }
  16881. };
  16882. Object.defineProperty(o, k2, desc);
  16883. }) : (function(o, m, k, k2) {
  16884. if (k2 === void 0) k2 = k;
  16885. o[k2] = m[k];
  16886. }));
  16887. var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o, v) {
  16888. Object.defineProperty(o, "default", {
  16889. enumerable: true,
  16890. value: v
  16891. });
  16892. }) : function(o, v) {
  16893. o["default"] = v;
  16894. });
  16895. var __importStar = exports && exports.__importStar || (function() {
  16896. var ownKeys = function(o) {
  16897. ownKeys = Object.getOwnPropertyNames || function(o) {
  16898. var ar = [];
  16899. for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
  16900. return ar;
  16901. };
  16902. return ownKeys(o);
  16903. };
  16904. return function(mod) {
  16905. if (mod && mod.__esModule) return mod;
  16906. var result = {};
  16907. if (mod != null) {
  16908. for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
  16909. }
  16910. __setModuleDefault(result, mod);
  16911. return result;
  16912. };
  16913. })();
  16914. Object.defineProperty(exports, "__esModule", { value: true });
  16915. exports.OUTGOING_PASSES = void 0;
  16916. exports.removeChunked = removeChunked;
  16917. exports.setConnection = setConnection;
  16918. exports.setRedirectHostRewrite = setRedirectHostRewrite;
  16919. exports.writeHeaders = writeHeaders;
  16920. exports.writeStatusCode = writeStatusCode;
  16921. const common = __importStar(require_common());
  16922. const redirectRegex = /^201|30(1|2|7|8)$/;
  16923. function removeChunked(_req, _res, proxyRes) {
  16924. delete proxyRes.headers["transfer-encoding"];
  16925. }
  16926. function setConnection(req, _res, proxyRes) {
  16927. if (req.httpVersion === "1.0") proxyRes.headers["connection"] = req.headers["connection"] || "close";
  16928. else if (req.httpVersion !== "2.0" && !proxyRes.headers["connection"]) proxyRes.headers["connection"] = req.headers["connection"] || "keep-alive";
  16929. }
  16930. function setRedirectHostRewrite(req, _res, proxyRes, options) {
  16931. if ((options.hostRewrite || options.autoRewrite || options.protocolRewrite) && proxyRes.headers["location"] && redirectRegex.test(`${proxyRes.statusCode}`)) {
  16932. const target = common.toURL(options.target);
  16933. const location = proxyRes.headers["location"];
  16934. if (typeof location != "string") return;
  16935. const u = common.toURL(location);
  16936. if (target.host != u.host) return;
  16937. if (options.hostRewrite) u.host = options.hostRewrite;
  16938. else if (options.autoRewrite) u.host = req.headers[":authority"] ?? req.headers["host"] ?? "";
  16939. if (options.protocolRewrite) u.protocol = options.protocolRewrite;
  16940. proxyRes.headers["location"] = u.toString();
  16941. }
  16942. }
  16943. function writeHeaders(_req, res, proxyRes, options) {
  16944. const rewriteCookieDomainConfig = typeof options.cookieDomainRewrite === "string" ? { "*": options.cookieDomainRewrite } : options.cookieDomainRewrite;
  16945. const rewriteCookiePathConfig = typeof options.cookiePathRewrite === "string" ? { "*": options.cookiePathRewrite } : options.cookiePathRewrite;
  16946. const preserveHeaderKeyCase = options.preserveHeaderKeyCase;
  16947. const setHeader = (key, header) => {
  16948. if (header == void 0) return;
  16949. if (rewriteCookieDomainConfig && key.toLowerCase() === "set-cookie") header = common.rewriteCookieProperty(header, rewriteCookieDomainConfig, "domain");
  16950. if (rewriteCookiePathConfig && key.toLowerCase() === "set-cookie") header = common.rewriteCookieProperty(header, rewriteCookiePathConfig, "path");
  16951. res.setHeader(String(key).trim(), header);
  16952. };
  16953. let rawHeaderKeyMap;
  16954. if (preserveHeaderKeyCase && proxyRes.rawHeaders != void 0) {
  16955. rawHeaderKeyMap = {};
  16956. for (let i = 0; i < proxyRes.rawHeaders.length; i += 2) {
  16957. const key = proxyRes.rawHeaders[i];
  16958. rawHeaderKeyMap[key.toLowerCase()] = key;
  16959. }
  16960. }
  16961. for (const key0 in proxyRes.headers) {
  16962. let key = key0;
  16963. if (_req.httpVersionMajor > 1 && (key === "connection" || key === "keep-alive")) continue;
  16964. const header = proxyRes.headers[key];
  16965. if (preserveHeaderKeyCase && rawHeaderKeyMap) key = rawHeaderKeyMap[key] ?? key;
  16966. setHeader(key, header);
  16967. }
  16968. }
  16969. function writeStatusCode(_req, res, proxyRes) {
  16970. res.statusCode = proxyRes.statusCode;
  16971. if (proxyRes.statusMessage && _req.httpVersionMajor === 1) res.statusMessage = proxyRes.statusMessage;
  16972. }
  16973. exports.OUTGOING_PASSES = {
  16974. removeChunked,
  16975. setConnection,
  16976. setRedirectHostRewrite,
  16977. writeHeaders,
  16978. writeStatusCode
  16979. };
  16980. }));
  16981. //#endregion
  16982. //#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
  16983. var require_web_incoming = /* @__PURE__ */ __commonJSMin(((exports) => {
  16984. var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o, m, k, k2) {
  16985. if (k2 === void 0) k2 = k;
  16986. var desc = Object.getOwnPropertyDescriptor(m, k);
  16987. if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) desc = {
  16988. enumerable: true,
  16989. get: function() {
  16990. return m[k];
  16991. }
  16992. };
  16993. Object.defineProperty(o, k2, desc);
  16994. }) : (function(o, m, k, k2) {
  16995. if (k2 === void 0) k2 = k;
  16996. o[k2] = m[k];
  16997. }));
  16998. var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o, v) {
  16999. Object.defineProperty(o, "default", {
  17000. enumerable: true,
  17001. value: v
  17002. });
  17003. }) : function(o, v) {
  17004. o["default"] = v;
  17005. });
  17006. var __importStar = exports && exports.__importStar || (function() {
  17007. var ownKeys = function(o) {
  17008. ownKeys = Object.getOwnPropertyNames || function(o) {
  17009. var ar = [];
  17010. for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
  17011. return ar;
  17012. };
  17013. return ownKeys(o);
  17014. };
  17015. return function(mod) {
  17016. if (mod && mod.__esModule) return mod;
  17017. var result = {};
  17018. if (mod != null) {
  17019. for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
  17020. }
  17021. __setModuleDefault(result, mod);
  17022. return result;
  17023. };
  17024. })();
  17025. Object.defineProperty(exports, "__esModule", { value: true });
  17026. exports.WEB_PASSES = void 0;
  17027. exports.deleteLength = deleteLength;
  17028. exports.timeout = timeout;
  17029. exports.XHeaders = XHeaders;
  17030. exports.stream = stream;
  17031. const http$2 = __importStar(__require("node:http"));
  17032. const https$1 = __importStar(__require("node:https"));
  17033. const followRedirects = __importStar(require_follow_redirects());
  17034. const common = __importStar(require_common());
  17035. const web_outgoing_1 = require_web_outgoing();
  17036. const node_stream_1 = __require("node:stream");
  17037. const web_o = Object.values(web_outgoing_1.OUTGOING_PASSES);
  17038. const nativeAgents = {
  17039. http: http$2,
  17040. https: https$1
  17041. };
  17042. function deleteLength(req) {
  17043. if ((req.method === "DELETE" || req.method === "OPTIONS") && !req.headers["content-length"]) {
  17044. req.headers["content-length"] = "0";
  17045. delete req.headers["transfer-encoding"];
  17046. }
  17047. }
  17048. function timeout(req, _res, options) {
  17049. if (options.timeout) req.socket.setTimeout(options.timeout);
  17050. }
  17051. function XHeaders(req, _res, options) {
  17052. if (!options.xfwd) return;
  17053. const encrypted = common.hasEncryptedConnection(req);
  17054. const values = {
  17055. for: req.connection.remoteAddress || req.socket.remoteAddress,
  17056. port: common.getPort(req),
  17057. proto: encrypted ? "https" : "http"
  17058. };
  17059. for (const header of [
  17060. "for",
  17061. "port",
  17062. "proto"
  17063. ]) req.headers["x-forwarded-" + header] = (req.headers["x-forwarded-" + header] || "") + (req.headers["x-forwarded-" + header] ? "," : "") + values[header];
  17064. req.headers["x-forwarded-host"] = req.headers["x-forwarded-host"] || req.headers[":authority"] || req.headers["host"] || "";
  17065. }
  17066. function stream(req, res, options, _, server, cb) {
  17067. server.emit("start", req, res, options.target || options.forward);
  17068. if (options.fetch || options.fetchOptions || process.env.FORCE_FETCH_PATH === "true") return stream2(req, res, options, _, server, cb);
  17069. const agents = options.followRedirects ? followRedirects : nativeAgents;
  17070. const http = agents.http;
  17071. const https = agents.https;
  17072. if (options.forward) {
  17073. const proto = options.forward.protocol === "https:" ? https : http;
  17074. const outgoingOptions = common.setupOutgoing(options.ssl || {}, options, req, "forward");
  17075. const forwardReq = proto.request(outgoingOptions);
  17076. const forwardError = createErrorHandler(forwardReq, options.forward);
  17077. req.on("error", forwardError);
  17078. forwardReq.on("error", forwardError);
  17079. (options.buffer || req).pipe(forwardReq);
  17080. if (!options.target) return res.end();
  17081. }
  17082. const proto = options.target.protocol === "https:" ? https : http;
  17083. const outgoingOptions = common.setupOutgoing(options.ssl || {}, options, req);
  17084. const proxyReq = proto.request(outgoingOptions);
  17085. proxyReq.on("socket", (socket) => {
  17086. if (server && !proxyReq.getHeader("expect")) server.emit("proxyReq", proxyReq, req, res, options, socket);
  17087. });
  17088. if (options.proxyTimeout) proxyReq.setTimeout(options.proxyTimeout, () => {
  17089. proxyReq.destroy();
  17090. });
  17091. res.on("close", () => {
  17092. if (!res.writableFinished) proxyReq.destroy();
  17093. });
  17094. const proxyError = createErrorHandler(proxyReq, options.target);
  17095. req.on("error", proxyError);
  17096. proxyReq.on("error", proxyError);
  17097. function createErrorHandler(proxyReq, url) {
  17098. return (err) => {
  17099. if (req.socket.destroyed && err.code === "ECONNRESET") {
  17100. server.emit("econnreset", err, req, res, url);
  17101. proxyReq.destroy();
  17102. return;
  17103. }
  17104. if (cb) cb(err, req, res, url);
  17105. else server.emit("error", err, req, res, url);
  17106. };
  17107. }
  17108. (options.buffer || req).pipe(proxyReq);
  17109. proxyReq.on("response", (proxyRes) => {
  17110. server?.emit("proxyRes", proxyRes, req, res);
  17111. if (!res.headersSent && !options.selfHandleResponse) for (const pass of web_o) pass(req, res, proxyRes, options);
  17112. if (!res.finished) {
  17113. proxyRes.on("end", () => {
  17114. server?.emit("end", req, res, proxyRes);
  17115. });
  17116. if (!options.selfHandleResponse) proxyRes.pipe(res);
  17117. } else server?.emit("end", req, res, proxyRes);
  17118. });
  17119. }
  17120. async function stream2(req, res, options, _, server, cb) {
  17121. const handleError = (err, target) => {
  17122. const e = err;
  17123. if (e.code === void 0 && e.cause?.code) e.code = e.cause.code;
  17124. if (cb) cb(err, req, res, target);
  17125. else server.emit("error", err, req, res, target);
  17126. };
  17127. req.on("error", (err) => {
  17128. if (req.socket.destroyed && err.code === "ECONNRESET") {
  17129. const target = options.target || options.forward;
  17130. if (target) server.emit("econnreset", err, req, res, target);
  17131. return;
  17132. }
  17133. handleError(err);
  17134. });
  17135. const customFetch = options.fetch || fetch;
  17136. const fetchOptions = options.fetchOptions ?? {};
  17137. const prepareRequest = (outgoing) => {
  17138. const requestOptions = {
  17139. method: outgoing.method,
  17140. ...fetchOptions.requestOptions
  17141. };
  17142. const headers = new Headers(fetchOptions.requestOptions?.headers);
  17143. if (!fetchOptions.requestOptions?.headers && outgoing.headers) {
  17144. for (const [key, value] of Object.entries(outgoing.headers)) if (typeof key === "string") {
  17145. if (Array.isArray(value)) for (const v of value) headers.append(key, v);
  17146. else if (value != null) headers.append(key, value);
  17147. }
  17148. }
  17149. if (options.auth) headers.set("authorization", `Basic ${Buffer.from(options.auth).toString("base64")}`);
  17150. if (options.proxyTimeout) requestOptions.signal = AbortSignal.timeout(options.proxyTimeout);
  17151. requestOptions.headers = headers;
  17152. if (options.buffer) requestOptions.body = options.buffer;
  17153. else if (req.method !== "GET" && req.method !== "HEAD") {
  17154. requestOptions.body = req;
  17155. requestOptions.duplex = "half";
  17156. }
  17157. return requestOptions;
  17158. };
  17159. if (options.forward) {
  17160. const outgoingOptions = common.setupOutgoing(options.ssl || {}, options, req, "forward");
  17161. const requestOptions = prepareRequest(outgoingOptions);
  17162. let targetUrl = new URL(outgoingOptions.url).origin + outgoingOptions.path;
  17163. if (targetUrl.startsWith("ws")) targetUrl = targetUrl.replace("ws", "http");
  17164. if (fetchOptions.onBeforeRequest) try {
  17165. await fetchOptions.onBeforeRequest(requestOptions, req, res, options);
  17166. } catch (err) {
  17167. handleError(err, options.forward);
  17168. return;
  17169. }
  17170. try {
  17171. const result = await customFetch(targetUrl, requestOptions);
  17172. if (fetchOptions.onAfterResponse) try {
  17173. await fetchOptions.onAfterResponse(result, req, res, options);
  17174. } catch (err) {
  17175. handleError(err, options.forward);
  17176. return;
  17177. }
  17178. } catch (err) {
  17179. handleError(err, options.forward);
  17180. }
  17181. if (!options.target) return res.end();
  17182. }
  17183. const outgoingOptions = common.setupOutgoing(options.ssl || {}, options, req);
  17184. const requestOptions = prepareRequest(outgoingOptions);
  17185. let targetUrl = new URL(outgoingOptions.url).origin + outgoingOptions.path;
  17186. if (targetUrl.startsWith("ws")) targetUrl = targetUrl.replace("ws", "http");
  17187. if (fetchOptions.onBeforeRequest) try {
  17188. await fetchOptions.onBeforeRequest(requestOptions, req, res, options);
  17189. } catch (err) {
  17190. handleError(err, options.target);
  17191. return;
  17192. }
  17193. try {
  17194. const response = await customFetch(targetUrl, requestOptions);
  17195. if (fetchOptions.onAfterResponse) try {
  17196. await fetchOptions.onAfterResponse(response, req, res, options);
  17197. } catch (err) {
  17198. handleError(err, options.target);
  17199. return;
  17200. }
  17201. const fakeProxyRes = {
  17202. statusCode: response.status,
  17203. statusMessage: response.statusText,
  17204. headers: Object.fromEntries(response.headers.entries()),
  17205. rawHeaders: Object.entries(response.headers).flatMap(([key, value]) => {
  17206. if (Array.isArray(value)) return value.flatMap((v) => v != null ? [key, v] : []);
  17207. return value != null ? [key, value] : [];
  17208. })
  17209. };
  17210. server?.emit("proxyRes", fakeProxyRes, req, res);
  17211. if (!res.headersSent && !options.selfHandleResponse) for (const pass of web_o) pass(req, res, fakeProxyRes, options);
  17212. if (!res.writableEnded) {
  17213. const nodeStream = response.body ? node_stream_1.Readable.from(response.body) : null;
  17214. if (nodeStream) {
  17215. nodeStream.on("error", (err) => {
  17216. handleError(err, options.target);
  17217. });
  17218. nodeStream.on("end", () => {
  17219. server?.emit("end", req, res, fakeProxyRes);
  17220. });
  17221. if (!options.selfHandleResponse) nodeStream.pipe(res, { end: true });
  17222. else nodeStream.resume();
  17223. } else server?.emit("end", req, res, fakeProxyRes);
  17224. } else server?.emit("end", req, res, fakeProxyRes);
  17225. } catch (err) {
  17226. handleError(err, options.target);
  17227. }
  17228. }
  17229. exports.WEB_PASSES = {
  17230. deleteLength,
  17231. timeout,
  17232. XHeaders,
  17233. stream
  17234. };
  17235. }));
  17236. //#endregion
  17237. //#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
  17238. var require_ws_incoming = /* @__PURE__ */ __commonJSMin(((exports) => {
  17239. var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o, m, k, k2) {
  17240. if (k2 === void 0) k2 = k;
  17241. var desc = Object.getOwnPropertyDescriptor(m, k);
  17242. if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) desc = {
  17243. enumerable: true,
  17244. get: function() {
  17245. return m[k];
  17246. }
  17247. };
  17248. Object.defineProperty(o, k2, desc);
  17249. }) : (function(o, m, k, k2) {
  17250. if (k2 === void 0) k2 = k;
  17251. o[k2] = m[k];
  17252. }));
  17253. var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o, v) {
  17254. Object.defineProperty(o, "default", {
  17255. enumerable: true,
  17256. value: v
  17257. });
  17258. }) : function(o, v) {
  17259. o["default"] = v;
  17260. });
  17261. var __importStar = exports && exports.__importStar || (function() {
  17262. var ownKeys = function(o) {
  17263. ownKeys = Object.getOwnPropertyNames || function(o) {
  17264. var ar = [];
  17265. for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
  17266. return ar;
  17267. };
  17268. return ownKeys(o);
  17269. };
  17270. return function(mod) {
  17271. if (mod && mod.__esModule) return mod;
  17272. var result = {};
  17273. if (mod != null) {
  17274. for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
  17275. }
  17276. __setModuleDefault(result, mod);
  17277. return result;
  17278. };
  17279. })();
  17280. var __importDefault = exports && exports.__importDefault || function(mod) {
  17281. return mod && mod.__esModule ? mod : { "default": mod };
  17282. };
  17283. Object.defineProperty(exports, "__esModule", { value: true });
  17284. exports.WS_PASSES = void 0;
  17285. exports.numOpenSockets = numOpenSockets;
  17286. exports.checkMethodAndHeader = checkMethodAndHeader;
  17287. exports.XHeaders = XHeaders;
  17288. exports.stream = stream;
  17289. const http$1 = __importStar(__require("node:http"));
  17290. const https = __importStar(__require("node:https"));
  17291. const common = __importStar(require_common());
  17292. const web_outgoing_1 = require_web_outgoing();
  17293. const log = (0, __importDefault((init_node(), __toCommonJS(node_exports))).default)("http-proxy-3:ws-incoming");
  17294. const web_o = Object.values(web_outgoing_1.OUTGOING_PASSES);
  17295. function createSocketCounter(name) {
  17296. let sockets = /* @__PURE__ */ new Set();
  17297. return ({ add, rm } = {}) => {
  17298. if (add) {
  17299. if (!add.id) add.id = Math.random();
  17300. if (!sockets.has(add.id)) sockets.add(add.id);
  17301. }
  17302. if (rm) {
  17303. if (!rm.id) rm.id = Math.random();
  17304. if (sockets.has(rm.id)) sockets.delete(rm.id);
  17305. }
  17306. log("socket counter:", { [name]: sockets.size }, add ? "add" : rm ? "rm" : "");
  17307. return sockets.size;
  17308. };
  17309. }
  17310. const socketCounter = createSocketCounter("socket");
  17311. const proxySocketCounter = createSocketCounter("proxySocket");
  17312. var MockResponse = class {
  17313. constructor() {
  17314. this.headers = {};
  17315. this.statusCode = 200;
  17316. this.statusMessage = "";
  17317. }
  17318. setHeader(key, value) {
  17319. this.headers[key] = value;
  17320. return this;
  17321. }
  17322. };
  17323. function numOpenSockets() {
  17324. return socketCounter() + proxySocketCounter();
  17325. }
  17326. function checkMethodAndHeader(req, socket) {
  17327. log("websocket: checkMethodAndHeader");
  17328. if (req.method !== "GET" || !req.headers.upgrade) {
  17329. socket.destroy();
  17330. return true;
  17331. }
  17332. if (req.headers.upgrade.toLowerCase() !== "websocket") {
  17333. socket.destroy();
  17334. return true;
  17335. }
  17336. }
  17337. function XHeaders(req, _socket, options) {
  17338. if (!options.xfwd) return;
  17339. log("websocket: XHeaders");
  17340. const values = {
  17341. for: req.connection.remoteAddress || req.socket.remoteAddress,
  17342. port: common.getPort(req),
  17343. proto: common.hasEncryptedConnection(req) ? "wss" : "ws"
  17344. };
  17345. for (const header of [
  17346. "for",
  17347. "port",
  17348. "proto"
  17349. ]) req.headers["x-forwarded-" + header] = (req.headers["x-forwarded-" + header] || "") + (req.headers["x-forwarded-" + header] ? "," : "") + values[header];
  17350. }
  17351. function stream(req, socket, options, head, server, cb) {
  17352. log("websocket: new stream");
  17353. const proxySockets = [];
  17354. socketCounter({ add: socket });
  17355. const cleanUpProxySockets = () => {
  17356. for (const p of proxySockets) p.end();
  17357. };
  17358. socket.on("close", () => {
  17359. socketCounter({ rm: socket });
  17360. cleanUpProxySockets();
  17361. });
  17362. socket.on("error", cleanUpProxySockets);
  17363. const createHttpHeader = (line, headers) => {
  17364. return Object.keys(headers).reduce((head, key) => {
  17365. const value = headers[key];
  17366. if (!Array.isArray(value)) {
  17367. head.push(key + ": " + value);
  17368. return head;
  17369. }
  17370. for (let i = 0; i < value.length; i++) head.push(key + ": " + value[i]);
  17371. return head;
  17372. }, [line]).join("\r\n") + "\r\n\r\n";
  17373. };
  17374. common.setupSocket(socket);
  17375. if (head && head.length) socket.unshift(head);
  17376. const proto = common.isSSL.test(options.target.protocol) ? https : http$1;
  17377. const outgoingOptions = common.setupOutgoing(options.ssl || {}, options, req);
  17378. const proxyReq = proto.request(outgoingOptions);
  17379. if (server) server.emit("proxyReqWs", proxyReq, req, socket, options, head);
  17380. proxyReq.on("error", onOutgoingError);
  17381. proxyReq.on("upgrade", (proxyRes, proxySocket, proxyHead) => {
  17382. log("upgrade");
  17383. proxySocketCounter({ add: proxySocket });
  17384. proxySockets.push(proxySocket);
  17385. proxySocket.on("close", () => {
  17386. proxySocketCounter({ rm: proxySocket });
  17387. });
  17388. proxySocket.on("error", onOutgoingError);
  17389. proxySocket.on("end", () => {
  17390. server.emit("close", proxyRes, proxySocket, proxyHead);
  17391. });
  17392. proxySocket.on("close", () => {
  17393. socket.end();
  17394. });
  17395. common.setupSocket(proxySocket);
  17396. if (proxyHead && proxyHead.length) proxySocket.unshift(proxyHead);
  17397. socket.write(createHttpHeader("HTTP/1.1 101 Switching Protocols", proxyRes.headers));
  17398. proxySocket.pipe(socket).pipe(proxySocket);
  17399. server.emit("open", proxySocket);
  17400. });
  17401. function onOutgoingError(err) {
  17402. if (cb) cb(err, req, socket);
  17403. else server.emit("error", err, req, socket);
  17404. socket.destroySoon();
  17405. }
  17406. proxyReq.on("response", (proxyRes) => {
  17407. log("got non-ws HTTP response", {
  17408. statusCode: proxyRes.statusCode,
  17409. statusMessage: proxyRes.statusMessage
  17410. });
  17411. const res = new MockResponse();
  17412. for (const pass of web_o) pass(req, res, proxyRes, options);
  17413. let writeChunk = (chunk) => {
  17414. socket.write(chunk);
  17415. };
  17416. if (req.httpVersion === "1.1" && proxyRes.headers["content-length"] === void 0) {
  17417. res.headers["transfer-encoding"] = "chunked";
  17418. writeChunk = (chunk) => {
  17419. socket.write(chunk.length.toString(16));
  17420. socket.write("\r\n");
  17421. socket.write(chunk);
  17422. socket.write("\r\n");
  17423. };
  17424. }
  17425. const proxyHead = createHttpHeader(`HTTP/${req.httpVersion} ${proxyRes.statusCode} ${proxyRes.statusMessage}`, res.headers);
  17426. if (!socket.destroyed) {
  17427. socket.write(proxyHead);
  17428. proxyRes.on("data", (chunk) => {
  17429. writeChunk(chunk);
  17430. });
  17431. proxyRes.on("end", () => {
  17432. writeChunk("");
  17433. socket.destroySoon();
  17434. });
  17435. } else proxyRes.resume();
  17436. });
  17437. proxyReq.end();
  17438. }
  17439. exports.WS_PASSES = {
  17440. checkMethodAndHeader,
  17441. XHeaders,
  17442. stream
  17443. };
  17444. }));
  17445. //#endregion
  17446. //#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
  17447. var require_http_proxy = /* @__PURE__ */ __commonJSMin(((exports) => {
  17448. var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o, m, k, k2) {
  17449. if (k2 === void 0) k2 = k;
  17450. var desc = Object.getOwnPropertyDescriptor(m, k);
  17451. if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) desc = {
  17452. enumerable: true,
  17453. get: function() {
  17454. return m[k];
  17455. }
  17456. };
  17457. Object.defineProperty(o, k2, desc);
  17458. }) : (function(o, m, k, k2) {
  17459. if (k2 === void 0) k2 = k;
  17460. o[k2] = m[k];
  17461. }));
  17462. var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o, v) {
  17463. Object.defineProperty(o, "default", {
  17464. enumerable: true,
  17465. value: v
  17466. });
  17467. }) : function(o, v) {
  17468. o["default"] = v;
  17469. });
  17470. var __importStar = exports && exports.__importStar || (function() {
  17471. var ownKeys = function(o) {
  17472. ownKeys = Object.getOwnPropertyNames || function(o) {
  17473. var ar = [];
  17474. for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
  17475. return ar;
  17476. };
  17477. return ownKeys(o);
  17478. };
  17479. return function(mod) {
  17480. if (mod && mod.__esModule) return mod;
  17481. var result = {};
  17482. if (mod != null) {
  17483. for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
  17484. }
  17485. __setModuleDefault(result, mod);
  17486. return result;
  17487. };
  17488. })();
  17489. var __importDefault = exports && exports.__importDefault || function(mod) {
  17490. return mod && mod.__esModule ? mod : { "default": mod };
  17491. };
  17492. Object.defineProperty(exports, "__esModule", { value: true });
  17493. exports.ProxyServer = void 0;
  17494. const http = __importStar(__require("node:http"));
  17495. const http2 = __importStar(__require("node:http2"));
  17496. const web_incoming_1 = require_web_incoming();
  17497. const ws_incoming_1 = require_ws_incoming();
  17498. const node_events_1 = __require("node:events");
  17499. const debug_1 = __importDefault((init_node(), __toCommonJS(node_exports)));
  17500. const common_1 = require_common();
  17501. const log = (0, debug_1.default)("http-proxy-3");
  17502. exports.ProxyServer = class ProxyServer extends node_events_1.EventEmitter {
  17503. /**
  17504. * Creates the proxy server with specified options.
  17505. * @param options - Config object passed to the proxy
  17506. */
  17507. constructor(options = {}) {
  17508. super();
  17509. this.createRightProxy = (type) => {
  17510. log("createRightProxy", { type });
  17511. return (options) => {
  17512. return (...args) => {
  17513. const req = args[0];
  17514. log("proxy: ", {
  17515. type,
  17516. path: req.url
  17517. });
  17518. const res = args[1];
  17519. const passes = type === "ws" ? this.wsPasses : this.webPasses;
  17520. if (type == "ws") res.on("error", (err) => {
  17521. this.emit("error", err, req, res);
  17522. });
  17523. let counter = args.length - 1;
  17524. let head;
  17525. let cb;
  17526. if (typeof args[counter] === "function") {
  17527. cb = args[counter];
  17528. counter--;
  17529. }
  17530. let requestOptions;
  17531. if (!(args[counter] instanceof Buffer) && args[counter] !== res) {
  17532. requestOptions = {
  17533. ...options,
  17534. ...args[counter]
  17535. };
  17536. counter--;
  17537. } else requestOptions = { ...options };
  17538. if (args[counter] instanceof Buffer) head = args[counter];
  17539. for (const e of ["target", "forward"]) if (typeof requestOptions[e] === "string") requestOptions[e] = (0, common_1.toURL)(requestOptions[e]);
  17540. if (!requestOptions.target && !requestOptions.forward) {
  17541. this.emit("error", /* @__PURE__ */ new Error("Must set target or forward"), req, res);
  17542. return;
  17543. }
  17544. for (const pass of passes)
  17545. /**
  17546. * Call of passes functions
  17547. * pass(req, res, options, head)
  17548. *
  17549. * In WebSockets case, the `res` variable
  17550. * refer to the connection socket
  17551. * pass(req, socket, options, head)
  17552. */
  17553. if (pass(req, res, requestOptions, head, this, cb)) break;
  17554. };
  17555. };
  17556. };
  17557. this.onError = (err) => {
  17558. if (this.listeners("error").length === 1) throw err;
  17559. };
  17560. /**
  17561. * A function that wraps the object in a webserver, for your convenience
  17562. * @param port - Port to listen on
  17563. * @param hostname - The hostname to listen on
  17564. */
  17565. this.listen = (port, hostname) => {
  17566. log("listen", {
  17567. port,
  17568. hostname
  17569. });
  17570. const requestListener = (req, res) => {
  17571. this.web(req, res);
  17572. };
  17573. this._server = this.options.ssl ? http2.createSecureServer({
  17574. ...this.options.ssl,
  17575. allowHTTP1: true
  17576. }, requestListener) : http.createServer(requestListener);
  17577. if (this.options.ws) this._server.on("upgrade", (req, socket, head) => {
  17578. this.ws(req, socket, head);
  17579. });
  17580. this._server.listen(port, hostname);
  17581. return this;
  17582. };
  17583. this.address = () => {
  17584. return this._server?.address();
  17585. };
  17586. /**
  17587. * A function that closes the inner webserver and stops listening on given port
  17588. */
  17589. this.close = (cb) => {
  17590. if (this._server == null) {
  17591. cb?.();
  17592. return;
  17593. }
  17594. this._server.close((err) => {
  17595. this._server = null;
  17596. cb?.(err);
  17597. });
  17598. };
  17599. this.before = (type, passName, cb) => {
  17600. if (type !== "ws" && type !== "web") throw new Error("type must be `web` or `ws`");
  17601. const passes = type === "ws" ? this.wsPasses : this.webPasses;
  17602. let i = false;
  17603. passes.forEach((v, idx) => {
  17604. if (v.name === passName) i = idx;
  17605. });
  17606. if (i === false) throw new Error("No such pass");
  17607. passes.splice(i, 0, cb);
  17608. };
  17609. this.after = (type, passName, cb) => {
  17610. if (type !== "ws" && type !== "web") throw new Error("type must be `web` or `ws`");
  17611. const passes = type === "ws" ? this.wsPasses : this.webPasses;
  17612. let i = false;
  17613. passes.forEach((v, idx) => {
  17614. if (v.name === passName) i = idx;
  17615. });
  17616. if (i === false) throw new Error("No such pass");
  17617. passes.splice(i++, 0, cb);
  17618. };
  17619. log("creating a ProxyServer", options);
  17620. options.prependPath = options.prependPath !== false;
  17621. this.options = options;
  17622. this.web = this.createRightProxy("web")(options);
  17623. this.ws = this.createRightProxy("ws")(options);
  17624. this.webPasses = Object.values(web_incoming_1.WEB_PASSES);
  17625. this.wsPasses = Object.values(ws_incoming_1.WS_PASSES);
  17626. this.on("error", this.onError);
  17627. }
  17628. /**
  17629. * Creates the proxy server with specified options.
  17630. * @param options Config object passed to the proxy
  17631. * @returns Proxy object with handlers for `ws` and `web` requests
  17632. */
  17633. static createProxyServer(options) {
  17634. return new ProxyServer(options);
  17635. }
  17636. /**
  17637. * Creates the proxy server with specified options.
  17638. * @param options Config object passed to the proxy
  17639. * @returns Proxy object with handlers for `ws` and `web` requests
  17640. */
  17641. static createServer(options) {
  17642. return new ProxyServer(options);
  17643. }
  17644. /**
  17645. * Creates the proxy server with specified options.
  17646. * @param options Config object passed to the proxy
  17647. * @returns Proxy object with handlers for `ws` and `web` requests
  17648. */
  17649. static createProxy(options) {
  17650. return new ProxyServer(options);
  17651. }
  17652. };
  17653. }));
  17654. //#endregion
  17655. //#region src/node/server/middlewares/proxy.ts
  17656. var import_lib$1 = /* @__PURE__ */ __toESM((/* @__PURE__ */ __commonJSMin(((exports) => {
  17657. Object.defineProperty(exports, "__esModule", { value: true });
  17658. exports.numOpenSockets = exports.ProxyServer = void 0;
  17659. exports.createProxyServer = createProxyServer;
  17660. const index_1 = require_http_proxy();
  17661. Object.defineProperty(exports, "ProxyServer", {
  17662. enumerable: true,
  17663. get: function() {
  17664. return index_1.ProxyServer;
  17665. }
  17666. });
  17667. var ws_incoming_1 = require_ws_incoming();
  17668. Object.defineProperty(exports, "numOpenSockets", {
  17669. enumerable: true,
  17670. get: function() {
  17671. return ws_incoming_1.numOpenSockets;
  17672. }
  17673. });
  17674. /**
  17675. * Creates the proxy server.
  17676. *
  17677. * Examples:
  17678. *
  17679. * httpProxy.createProxyServer({ .. }, 8000)
  17680. * // => '{ web: [Function], ws: [Function] ... }'
  17681. *
  17682. * @param {Object} Options Config object passed to the proxy
  17683. *
  17684. * @return {Object} Proxy Proxy object with handlers for `ws` and `web` requests
  17685. *
  17686. * @api public
  17687. */
  17688. function createProxyServer(options = {}) {
  17689. return new index_1.ProxyServer(options);
  17690. }
  17691. })))(), 1);
  17692. const debug$11 = createDebugger("vite:proxy");
  17693. const rewriteOriginHeader = (proxyReq, options, config) => {
  17694. if (options.rewriteWsOrigin) {
  17695. const { target } = options;
  17696. if (proxyReq.headersSent) {
  17697. config.logger.warn(import_picocolors.default.yellow(`Unable to rewrite Origin header as headers are already sent.`));
  17698. return;
  17699. }
  17700. if (proxyReq.getHeader("origin") && target) {
  17701. const changedOrigin = typeof target === "object" ? `${target.protocol ?? "http:"}//${target.host}` : target;
  17702. proxyReq.setHeader("origin", changedOrigin);
  17703. }
  17704. }
  17705. };
  17706. function proxyMiddleware(httpServer, options, config) {
  17707. const proxies = {};
  17708. Object.keys(options).forEach((context) => {
  17709. let opts = options[context];
  17710. if (!opts) return;
  17711. if (typeof opts === "string") opts = {
  17712. target: opts,
  17713. changeOrigin: true
  17714. };
  17715. const proxy = import_lib$1.createProxyServer(opts);
  17716. if (opts.configure) opts.configure(proxy, opts);
  17717. proxy.on("error", (err, _req, res) => {
  17718. if ("req" in res) {
  17719. config.logger.error(`${import_picocolors.default.red(`http proxy error: ${res.req.url}`)}\n${err.stack}`, {
  17720. timestamp: true,
  17721. error: err
  17722. });
  17723. if (!res.headersSent && !res.writableEnded) res.writeHead(502, { "Content-Type": "text/plain" }).end();
  17724. } else {
  17725. config.logger.error(`${import_picocolors.default.red(`ws proxy error:`)}\n${err.stack}`, {
  17726. timestamp: true,
  17727. error: err
  17728. });
  17729. res.end();
  17730. }
  17731. });
  17732. proxy.on("proxyReqWs", (proxyReq, _req, socket, options) => {
  17733. rewriteOriginHeader(proxyReq, options, config);
  17734. socket.on("error", (err) => {
  17735. config.logger.error(`${import_picocolors.default.red(`ws proxy socket error:`)}\n${err.stack}`, {
  17736. timestamp: true,
  17737. error: err
  17738. });
  17739. });
  17740. });
  17741. proxies[context] = [proxy, { ...opts }];
  17742. });
  17743. if (httpServer) httpServer.on("upgrade", async (req, socket, head) => {
  17744. const url = req.url;
  17745. for (const context in proxies) if (doesProxyContextMatchUrl(context, url)) {
  17746. const [proxy, opts] = proxies[context];
  17747. if (opts.ws || opts.target?.toString().startsWith("ws:") || opts.target?.toString().startsWith("wss:")) {
  17748. if (opts.bypass) try {
  17749. const bypassResult = await opts.bypass(req, void 0, opts);
  17750. if (typeof bypassResult === "string") {
  17751. debug$11?.(`bypass: ${req.url} -> ${bypassResult}`);
  17752. req.url = bypassResult;
  17753. return;
  17754. }
  17755. if (bypassResult === false) {
  17756. debug$11?.(`bypass: ${req.url} -> 404`);
  17757. socket.end("HTTP/1.1 404 Not Found\r\n\r\n", "");
  17758. return;
  17759. }
  17760. } catch (err) {
  17761. config.logger.error(`${import_picocolors.default.red(`ws proxy bypass error:`)}\n${err.stack}`, {
  17762. timestamp: true,
  17763. error: err
  17764. });
  17765. return;
  17766. }
  17767. if (opts.rewrite) req.url = opts.rewrite(url);
  17768. debug$11?.(`${req.url} -> ws ${opts.target}`);
  17769. proxy.ws(req, socket, head);
  17770. return;
  17771. }
  17772. }
  17773. });
  17774. return async function viteProxyMiddleware(req, res, next) {
  17775. const url = req.url;
  17776. for (const context in proxies) if (doesProxyContextMatchUrl(context, url)) {
  17777. const [proxy, opts] = proxies[context];
  17778. const options = {};
  17779. if (opts.bypass) try {
  17780. const bypassResult = await opts.bypass(req, res, opts);
  17781. if (typeof bypassResult === "string") {
  17782. debug$11?.(`bypass: ${req.url} -> ${bypassResult}`);
  17783. req.url = bypassResult;
  17784. if (res.writableEnded) return;
  17785. return next();
  17786. }
  17787. if (bypassResult === false) {
  17788. debug$11?.(`bypass: ${req.url} -> 404`);
  17789. res.statusCode = 404;
  17790. return res.end();
  17791. }
  17792. } catch (e) {
  17793. debug$11?.(`bypass: ${req.url} -> ${e}`);
  17794. return next(e);
  17795. }
  17796. debug$11?.(`${req.url} -> ${opts.target || opts.forward}`);
  17797. if (opts.rewrite) req.url = opts.rewrite(req.url);
  17798. proxy.web(req, res, options);
  17799. return;
  17800. }
  17801. next();
  17802. };
  17803. }
  17804. function doesProxyContextMatchUrl(context, url) {
  17805. return context[0] === "^" && new RegExp(context).test(url) || url.startsWith(context);
  17806. }
  17807. //#endregion
  17808. //#region ../../node_modules/.pnpm/etag@1.8.1/node_modules/etag/index.js
  17809. /*!
  17810. * etag
  17811. * Copyright(c) 2014-2016 Douglas Christopher Wilson
  17812. * MIT Licensed
  17813. */
  17814. var require_etag = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  17815. /**
  17816. * Module exports.
  17817. * @public
  17818. */
  17819. module.exports = etag;
  17820. /**
  17821. * Module dependencies.
  17822. * @private
  17823. */
  17824. var crypto$1 = __require("crypto");
  17825. var Stats = __require("fs").Stats;
  17826. /**
  17827. * Module variables.
  17828. * @private
  17829. */
  17830. var toString = Object.prototype.toString;
  17831. /**
  17832. * Generate an entity tag.
  17833. *
  17834. * @param {Buffer|string} entity
  17835. * @return {string}
  17836. * @private
  17837. */
  17838. function entitytag(entity) {
  17839. if (entity.length === 0) return "\"0-2jmj7l5rSw0yVb/vlWAYkK/YBwk\"";
  17840. var hash = crypto$1.createHash("sha1").update(entity, "utf8").digest("base64").substring(0, 27);
  17841. return "\"" + (typeof entity === "string" ? Buffer.byteLength(entity, "utf8") : entity.length).toString(16) + "-" + hash + "\"";
  17842. }
  17843. /**
  17844. * Create a simple ETag.
  17845. *
  17846. * @param {string|Buffer|Stats} entity
  17847. * @param {object} [options]
  17848. * @param {boolean} [options.weak]
  17849. * @return {String}
  17850. * @public
  17851. */
  17852. function etag(entity, options) {
  17853. if (entity == null) throw new TypeError("argument entity is required");
  17854. var isStats = isstats(entity);
  17855. var weak = options && typeof options.weak === "boolean" ? options.weak : isStats;
  17856. if (!isStats && typeof entity !== "string" && !Buffer.isBuffer(entity)) throw new TypeError("argument entity must be string, Buffer, or fs.Stats");
  17857. var tag = isStats ? stattag(entity) : entitytag(entity);
  17858. return weak ? "W/" + tag : tag;
  17859. }
  17860. /**
  17861. * Determine if object is a Stats object.
  17862. *
  17863. * @param {object} obj
  17864. * @return {boolean}
  17865. * @api private
  17866. */
  17867. function isstats(obj) {
  17868. if (typeof Stats === "function" && obj instanceof Stats) return true;
  17869. 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";
  17870. }
  17871. /**
  17872. * Generate a tag for a stat.
  17873. *
  17874. * @param {object} stat
  17875. * @return {string}
  17876. * @private
  17877. */
  17878. function stattag(stat) {
  17879. var mtime = stat.mtime.getTime().toString(16);
  17880. return "\"" + stat.size.toString(16) + "-" + mtime + "\"";
  17881. }
  17882. }));
  17883. //#endregion
  17884. //#region src/node/environment.ts
  17885. /**
  17886. * Creates a function that hides the complexities of a WeakMap with an initial value
  17887. * to implement object metadata. Used by plugins to implement cross hooks per
  17888. * environment metadata
  17889. *
  17890. * @experimental
  17891. */
  17892. function perEnvironmentState(initial) {
  17893. const stateMap = /* @__PURE__ */ new WeakMap();
  17894. return function(context) {
  17895. const { environment } = context;
  17896. let state = stateMap.get(environment);
  17897. if (!state) {
  17898. state = initial(environment);
  17899. stateMap.set(environment, state);
  17900. }
  17901. return state;
  17902. };
  17903. }
  17904. //#endregion
  17905. //#region ../../node_modules/.pnpm/strip-literal@3.1.0/node_modules/strip-literal/dist/index.mjs
  17906. var import_js_tokens = /* @__PURE__ */ __toESM((/* @__PURE__ */ __commonJSMin(((exports, module) => {
  17907. 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;
  17908. Punctuator = /--|\+\+|=>|\.{3}|\??\.(?!\d)|(?:&&|\|\||\?\?|[+\-%&|^]|\*{1,2}|<{1,2}|>{1,3}|!=?|={1,2}|\/(?![\/*]))=?|[?~,:;[\](){}]/y;
  17909. Identifier = /(\x23?)(?=[$_\p{ID_Start}\\])(?:[$_\u200C\u200D\p{ID_Continue}]+|\\u[\da-fA-F]{4}|\\u\{[\da-fA-F]+\})+/uy;
  17910. StringLiteral = /(['"])(?:[^'"\\\n\r]+|(?!\1)['"]|\\(?:\r\n|[^]))*(\1)?/y;
  17911. 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;
  17912. Template = /[`}](?:[^`\\$]+|\\[^]|\$(?!\{))*(`|\$\{)?/y;
  17913. WhiteSpace = /[\t\v\f\ufeff\p{Zs}]+/uy;
  17914. LineTerminatorSequence = /\r?\n|[\r\u2028\u2029]/y;
  17915. MultiLineComment = /\/\*(?:[^*]+|\*(?!\/))*(\*\/)?/y;
  17916. SingleLineComment = /\/\/.*/y;
  17917. HashbangComment = /^#!.*/;
  17918. JSXPunctuator = /[<>.:={}]|\/(?![\/*])/y;
  17919. JSXIdentifier = /[$_\p{ID_Start}][$_\u200C\u200D\p{ID_Continue}-]*/uy;
  17920. JSXString = /(['"])(?:[^'"]+|(?!\1)['"])*(\1)?/y;
  17921. JSXText = /[^<>{}]+/y;
  17922. TokensPrecedingExpression = /^(?:[\/+-]|\.{3}|\?(?:InterpolationIn(?:JSX|Template)|NoLineTerminatorHere|NonExpressionParenEnd|UnaryIncDec))?$|[{}([,;<>=*%&|^!~?:]$/;
  17923. TokensNotPrecedingObjectLiteral = /^(?:=>|[;\]){}]|else|\?(?:NoLineTerminatorHere|NonExpressionParenEnd))?$/;
  17924. KeywordsWithExpressionAfter = /^(?:await|case|default|delete|do|else|instanceof|new|return|throw|typeof|void|yield)$/;
  17925. KeywordsWithNoLineTerminatorAfter = /^(?:return|throw|yield)$/;
  17926. Newline = RegExp(LineTerminatorSequence.source);
  17927. module.exports = function* (input, { jsx = false } = {}) {
  17928. var braces, firstCodePoint, isExpression, lastIndex, lastSignificantToken, length, match, mode, nextLastIndex, nextLastSignificantToken, parenNesting, postfixIncDec, punctuator, stack;
  17929. ({length} = input);
  17930. lastIndex = 0;
  17931. lastSignificantToken = "";
  17932. stack = [{ tag: "JS" }];
  17933. braces = [];
  17934. parenNesting = 0;
  17935. postfixIncDec = false;
  17936. if (match = HashbangComment.exec(input)) {
  17937. yield {
  17938. type: "HashbangComment",
  17939. value: match[0]
  17940. };
  17941. lastIndex = match[0].length;
  17942. }
  17943. while (lastIndex < length) {
  17944. mode = stack[stack.length - 1];
  17945. switch (mode.tag) {
  17946. case "JS":
  17947. case "JSNonExpressionParen":
  17948. case "InterpolationInTemplate":
  17949. case "InterpolationInJSX":
  17950. if (input[lastIndex] === "/" && (TokensPrecedingExpression.test(lastSignificantToken) || KeywordsWithExpressionAfter.test(lastSignificantToken))) {
  17951. RegularExpressionLiteral.lastIndex = lastIndex;
  17952. if (match = RegularExpressionLiteral.exec(input)) {
  17953. lastIndex = RegularExpressionLiteral.lastIndex;
  17954. lastSignificantToken = match[0];
  17955. postfixIncDec = true;
  17956. yield {
  17957. type: "RegularExpressionLiteral",
  17958. value: match[0],
  17959. closed: match[1] !== void 0 && match[1] !== "\\"
  17960. };
  17961. continue;
  17962. }
  17963. }
  17964. Punctuator.lastIndex = lastIndex;
  17965. if (match = Punctuator.exec(input)) {
  17966. punctuator = match[0];
  17967. nextLastIndex = Punctuator.lastIndex;
  17968. nextLastSignificantToken = punctuator;
  17969. switch (punctuator) {
  17970. case "(":
  17971. if (lastSignificantToken === "?NonExpressionParenKeyword") stack.push({
  17972. tag: "JSNonExpressionParen",
  17973. nesting: parenNesting
  17974. });
  17975. parenNesting++;
  17976. postfixIncDec = false;
  17977. break;
  17978. case ")":
  17979. parenNesting--;
  17980. postfixIncDec = true;
  17981. if (mode.tag === "JSNonExpressionParen" && parenNesting === mode.nesting) {
  17982. stack.pop();
  17983. nextLastSignificantToken = "?NonExpressionParenEnd";
  17984. postfixIncDec = false;
  17985. }
  17986. break;
  17987. case "{":
  17988. Punctuator.lastIndex = 0;
  17989. isExpression = !TokensNotPrecedingObjectLiteral.test(lastSignificantToken) && (TokensPrecedingExpression.test(lastSignificantToken) || KeywordsWithExpressionAfter.test(lastSignificantToken));
  17990. braces.push(isExpression);
  17991. postfixIncDec = false;
  17992. break;
  17993. case "}":
  17994. switch (mode.tag) {
  17995. case "InterpolationInTemplate":
  17996. if (braces.length === mode.nesting) {
  17997. Template.lastIndex = lastIndex;
  17998. match = Template.exec(input);
  17999. lastIndex = Template.lastIndex;
  18000. lastSignificantToken = match[0];
  18001. if (match[1] === "${") {
  18002. lastSignificantToken = "?InterpolationInTemplate";
  18003. postfixIncDec = false;
  18004. yield {
  18005. type: "TemplateMiddle",
  18006. value: match[0]
  18007. };
  18008. } else {
  18009. stack.pop();
  18010. postfixIncDec = true;
  18011. yield {
  18012. type: "TemplateTail",
  18013. value: match[0],
  18014. closed: match[1] === "`"
  18015. };
  18016. }
  18017. continue;
  18018. }
  18019. break;
  18020. case "InterpolationInJSX": if (braces.length === mode.nesting) {
  18021. stack.pop();
  18022. lastIndex += 1;
  18023. lastSignificantToken = "}";
  18024. yield {
  18025. type: "JSXPunctuator",
  18026. value: "}"
  18027. };
  18028. continue;
  18029. }
  18030. }
  18031. postfixIncDec = braces.pop();
  18032. nextLastSignificantToken = postfixIncDec ? "?ExpressionBraceEnd" : "}";
  18033. break;
  18034. case "]":
  18035. postfixIncDec = true;
  18036. break;
  18037. case "++":
  18038. case "--":
  18039. nextLastSignificantToken = postfixIncDec ? "?PostfixIncDec" : "?UnaryIncDec";
  18040. break;
  18041. case "<":
  18042. if (jsx && (TokensPrecedingExpression.test(lastSignificantToken) || KeywordsWithExpressionAfter.test(lastSignificantToken))) {
  18043. stack.push({ tag: "JSXTag" });
  18044. lastIndex += 1;
  18045. lastSignificantToken = "<";
  18046. yield {
  18047. type: "JSXPunctuator",
  18048. value: punctuator
  18049. };
  18050. continue;
  18051. }
  18052. postfixIncDec = false;
  18053. break;
  18054. default: postfixIncDec = false;
  18055. }
  18056. lastIndex = nextLastIndex;
  18057. lastSignificantToken = nextLastSignificantToken;
  18058. yield {
  18059. type: "Punctuator",
  18060. value: punctuator
  18061. };
  18062. continue;
  18063. }
  18064. Identifier.lastIndex = lastIndex;
  18065. if (match = Identifier.exec(input)) {
  18066. lastIndex = Identifier.lastIndex;
  18067. nextLastSignificantToken = match[0];
  18068. switch (match[0]) {
  18069. case "for":
  18070. case "if":
  18071. case "while":
  18072. case "with": if (lastSignificantToken !== "." && lastSignificantToken !== "?.") nextLastSignificantToken = "?NonExpressionParenKeyword";
  18073. }
  18074. lastSignificantToken = nextLastSignificantToken;
  18075. postfixIncDec = !KeywordsWithExpressionAfter.test(match[0]);
  18076. yield {
  18077. type: match[1] === "#" ? "PrivateIdentifier" : "IdentifierName",
  18078. value: match[0]
  18079. };
  18080. continue;
  18081. }
  18082. StringLiteral.lastIndex = lastIndex;
  18083. if (match = StringLiteral.exec(input)) {
  18084. lastIndex = StringLiteral.lastIndex;
  18085. lastSignificantToken = match[0];
  18086. postfixIncDec = true;
  18087. yield {
  18088. type: "StringLiteral",
  18089. value: match[0],
  18090. closed: match[2] !== void 0
  18091. };
  18092. continue;
  18093. }
  18094. NumericLiteral.lastIndex = lastIndex;
  18095. if (match = NumericLiteral.exec(input)) {
  18096. lastIndex = NumericLiteral.lastIndex;
  18097. lastSignificantToken = match[0];
  18098. postfixIncDec = true;
  18099. yield {
  18100. type: "NumericLiteral",
  18101. value: match[0]
  18102. };
  18103. continue;
  18104. }
  18105. Template.lastIndex = lastIndex;
  18106. if (match = Template.exec(input)) {
  18107. lastIndex = Template.lastIndex;
  18108. lastSignificantToken = match[0];
  18109. if (match[1] === "${") {
  18110. lastSignificantToken = "?InterpolationInTemplate";
  18111. stack.push({
  18112. tag: "InterpolationInTemplate",
  18113. nesting: braces.length
  18114. });
  18115. postfixIncDec = false;
  18116. yield {
  18117. type: "TemplateHead",
  18118. value: match[0]
  18119. };
  18120. } else {
  18121. postfixIncDec = true;
  18122. yield {
  18123. type: "NoSubstitutionTemplate",
  18124. value: match[0],
  18125. closed: match[1] === "`"
  18126. };
  18127. }
  18128. continue;
  18129. }
  18130. break;
  18131. case "JSXTag":
  18132. case "JSXTagEnd":
  18133. JSXPunctuator.lastIndex = lastIndex;
  18134. if (match = JSXPunctuator.exec(input)) {
  18135. lastIndex = JSXPunctuator.lastIndex;
  18136. nextLastSignificantToken = match[0];
  18137. switch (match[0]) {
  18138. case "<":
  18139. stack.push({ tag: "JSXTag" });
  18140. break;
  18141. case ">":
  18142. stack.pop();
  18143. if (lastSignificantToken === "/" || mode.tag === "JSXTagEnd") {
  18144. nextLastSignificantToken = "?JSX";
  18145. postfixIncDec = true;
  18146. } else stack.push({ tag: "JSXChildren" });
  18147. break;
  18148. case "{":
  18149. stack.push({
  18150. tag: "InterpolationInJSX",
  18151. nesting: braces.length
  18152. });
  18153. nextLastSignificantToken = "?InterpolationInJSX";
  18154. postfixIncDec = false;
  18155. break;
  18156. case "/": if (lastSignificantToken === "<") {
  18157. stack.pop();
  18158. if (stack[stack.length - 1].tag === "JSXChildren") stack.pop();
  18159. stack.push({ tag: "JSXTagEnd" });
  18160. }
  18161. }
  18162. lastSignificantToken = nextLastSignificantToken;
  18163. yield {
  18164. type: "JSXPunctuator",
  18165. value: match[0]
  18166. };
  18167. continue;
  18168. }
  18169. JSXIdentifier.lastIndex = lastIndex;
  18170. if (match = JSXIdentifier.exec(input)) {
  18171. lastIndex = JSXIdentifier.lastIndex;
  18172. lastSignificantToken = match[0];
  18173. yield {
  18174. type: "JSXIdentifier",
  18175. value: match[0]
  18176. };
  18177. continue;
  18178. }
  18179. JSXString.lastIndex = lastIndex;
  18180. if (match = JSXString.exec(input)) {
  18181. lastIndex = JSXString.lastIndex;
  18182. lastSignificantToken = match[0];
  18183. yield {
  18184. type: "JSXString",
  18185. value: match[0],
  18186. closed: match[2] !== void 0
  18187. };
  18188. continue;
  18189. }
  18190. break;
  18191. case "JSXChildren":
  18192. JSXText.lastIndex = lastIndex;
  18193. if (match = JSXText.exec(input)) {
  18194. lastIndex = JSXText.lastIndex;
  18195. lastSignificantToken = match[0];
  18196. yield {
  18197. type: "JSXText",
  18198. value: match[0]
  18199. };
  18200. continue;
  18201. }
  18202. switch (input[lastIndex]) {
  18203. case "<":
  18204. stack.push({ tag: "JSXTag" });
  18205. lastIndex++;
  18206. lastSignificantToken = "<";
  18207. yield {
  18208. type: "JSXPunctuator",
  18209. value: "<"
  18210. };
  18211. continue;
  18212. case "{":
  18213. stack.push({
  18214. tag: "InterpolationInJSX",
  18215. nesting: braces.length
  18216. });
  18217. lastIndex++;
  18218. lastSignificantToken = "?InterpolationInJSX";
  18219. postfixIncDec = false;
  18220. yield {
  18221. type: "JSXPunctuator",
  18222. value: "{"
  18223. };
  18224. continue;
  18225. }
  18226. }
  18227. WhiteSpace.lastIndex = lastIndex;
  18228. if (match = WhiteSpace.exec(input)) {
  18229. lastIndex = WhiteSpace.lastIndex;
  18230. yield {
  18231. type: "WhiteSpace",
  18232. value: match[0]
  18233. };
  18234. continue;
  18235. }
  18236. LineTerminatorSequence.lastIndex = lastIndex;
  18237. if (match = LineTerminatorSequence.exec(input)) {
  18238. lastIndex = LineTerminatorSequence.lastIndex;
  18239. postfixIncDec = false;
  18240. if (KeywordsWithNoLineTerminatorAfter.test(lastSignificantToken)) lastSignificantToken = "?NoLineTerminatorHere";
  18241. yield {
  18242. type: "LineTerminatorSequence",
  18243. value: match[0]
  18244. };
  18245. continue;
  18246. }
  18247. MultiLineComment.lastIndex = lastIndex;
  18248. if (match = MultiLineComment.exec(input)) {
  18249. lastIndex = MultiLineComment.lastIndex;
  18250. if (Newline.test(match[0])) {
  18251. postfixIncDec = false;
  18252. if (KeywordsWithNoLineTerminatorAfter.test(lastSignificantToken)) lastSignificantToken = "?NoLineTerminatorHere";
  18253. }
  18254. yield {
  18255. type: "MultiLineComment",
  18256. value: match[0],
  18257. closed: match[1] !== void 0
  18258. };
  18259. continue;
  18260. }
  18261. SingleLineComment.lastIndex = lastIndex;
  18262. if (match = SingleLineComment.exec(input)) {
  18263. lastIndex = SingleLineComment.lastIndex;
  18264. postfixIncDec = false;
  18265. yield {
  18266. type: "SingleLineComment",
  18267. value: match[0]
  18268. };
  18269. continue;
  18270. }
  18271. firstCodePoint = String.fromCodePoint(input.codePointAt(lastIndex));
  18272. lastIndex += firstCodePoint.length;
  18273. lastSignificantToken = firstCodePoint;
  18274. postfixIncDec = false;
  18275. yield {
  18276. type: mode.tag.startsWith("JSX") ? "JSXInvalid" : "Invalid",
  18277. value: firstCodePoint
  18278. };
  18279. }
  18280. };
  18281. })))(), 1);
  18282. const FILL_COMMENT = " ";
  18283. function stripLiteralFromToken(token, fillChar, filter) {
  18284. if (token.type === "SingleLineComment") return FILL_COMMENT.repeat(token.value.length);
  18285. if (token.type === "MultiLineComment") return token.value.replace(/[^\n]/g, FILL_COMMENT);
  18286. if (token.type === "StringLiteral") {
  18287. if (!token.closed) return token.value;
  18288. const body = token.value.slice(1, -1);
  18289. if (filter(body)) return token.value[0] + fillChar.repeat(body.length) + token.value[token.value.length - 1];
  18290. }
  18291. if (token.type === "NoSubstitutionTemplate") {
  18292. const body = token.value.slice(1, -1);
  18293. if (filter(body)) return `\`${body.replace(/[^\n]/g, fillChar)}\``;
  18294. }
  18295. if (token.type === "RegularExpressionLiteral") {
  18296. const body = token.value;
  18297. if (filter(body)) return body.replace(/\/(.*)\/(\w?)$/g, (_, $1, $2) => `/${fillChar.repeat($1.length)}/${$2}`);
  18298. }
  18299. if (token.type === "TemplateHead") {
  18300. const body = token.value.slice(1, -2);
  18301. if (filter(body)) return `\`${body.replace(/[^\n]/g, fillChar)}\${`;
  18302. }
  18303. if (token.type === "TemplateTail") {
  18304. const body = token.value.slice(0, -2);
  18305. if (filter(body)) return `}${body.replace(/[^\n]/g, fillChar)}\``;
  18306. }
  18307. if (token.type === "TemplateMiddle") {
  18308. const body = token.value.slice(1, -2);
  18309. if (filter(body)) return `}${body.replace(/[^\n]/g, fillChar)}\${`;
  18310. }
  18311. return token.value;
  18312. }
  18313. function optionsWithDefaults(options) {
  18314. return {
  18315. fillChar: options?.fillChar ?? " ",
  18316. filter: options?.filter ?? (() => true)
  18317. };
  18318. }
  18319. function stripLiteral(code, options) {
  18320. let result = "";
  18321. const _options = optionsWithDefaults(options);
  18322. for (const token of (0, import_js_tokens.default)(code, { jsx: false })) result += stripLiteralFromToken(token, _options.fillChar, _options.filter);
  18323. return result;
  18324. }
  18325. //#endregion
  18326. //#region src/node/assetSource.ts
  18327. const ALLOWED_META_NAME = [
  18328. "msapplication-tileimage",
  18329. "msapplication-square70x70logo",
  18330. "msapplication-square150x150logo",
  18331. "msapplication-wide310x150logo",
  18332. "msapplication-square310x310logo",
  18333. "msapplication-config",
  18334. "twitter:image"
  18335. ];
  18336. const ALLOWED_META_PROPERTY = [
  18337. "og:image",
  18338. "og:image:url",
  18339. "og:image:secure_url",
  18340. "og:audio",
  18341. "og:audio:secure_url",
  18342. "og:video",
  18343. "og:video:secure_url"
  18344. ];
  18345. const DEFAULT_HTML_ASSET_SOURCES = {
  18346. audio: { srcAttributes: ["src"] },
  18347. embed: { srcAttributes: ["src"] },
  18348. img: {
  18349. srcAttributes: ["src"],
  18350. srcsetAttributes: ["srcset"]
  18351. },
  18352. image: { srcAttributes: ["href", "xlink:href"] },
  18353. input: { srcAttributes: ["src"] },
  18354. link: {
  18355. srcAttributes: ["href"],
  18356. srcsetAttributes: ["imagesrcset"]
  18357. },
  18358. object: { srcAttributes: ["data"] },
  18359. source: {
  18360. srcAttributes: ["src"],
  18361. srcsetAttributes: ["srcset"]
  18362. },
  18363. track: { srcAttributes: ["src"] },
  18364. use: { srcAttributes: ["href", "xlink:href"] },
  18365. video: { srcAttributes: ["src", "poster"] },
  18366. meta: {
  18367. srcAttributes: ["content"],
  18368. filter({ attributes }) {
  18369. if (attributes.name && ALLOWED_META_NAME.includes(attributes.name.trim().toLowerCase())) return true;
  18370. if (attributes.property && ALLOWED_META_PROPERTY.includes(attributes.property.trim().toLowerCase())) return true;
  18371. return false;
  18372. }
  18373. }
  18374. };
  18375. /**
  18376. * Given a HTML node, find all attributes that references an asset to be processed
  18377. */
  18378. function getNodeAssetAttributes(node) {
  18379. const matched = DEFAULT_HTML_ASSET_SOURCES[node.nodeName];
  18380. if (!matched) return [];
  18381. const attributes = {};
  18382. for (const attr of node.attrs) attributes[getAttrKey(attr)] = attr.value;
  18383. if ("vite-ignore" in attributes) return [{
  18384. type: "remove",
  18385. key: "vite-ignore",
  18386. value: "",
  18387. attributes,
  18388. location: node.sourceCodeLocation.attrs["vite-ignore"]
  18389. }];
  18390. const actions = [];
  18391. function handleAttributeKey(key, type) {
  18392. const value = attributes[key];
  18393. if (!value) return;
  18394. if (matched.filter && !matched.filter({
  18395. key,
  18396. value,
  18397. attributes
  18398. })) return;
  18399. const location = node.sourceCodeLocation.attrs[key];
  18400. actions.push({
  18401. type,
  18402. key,
  18403. value,
  18404. attributes,
  18405. location
  18406. });
  18407. }
  18408. matched.srcAttributes?.forEach((key) => handleAttributeKey(key, "src"));
  18409. matched.srcsetAttributes?.forEach((key) => handleAttributeKey(key, "srcset"));
  18410. return actions;
  18411. }
  18412. function getAttrKey(attr) {
  18413. return attr.prefix === void 0 ? attr.name : `${attr.prefix}:${attr.name}`;
  18414. }
  18415. //#endregion
  18416. //#region ../../node_modules/.pnpm/mrmime@2.0.1/node_modules/mrmime/index.mjs
  18417. const mimes = {
  18418. "3g2": "video/3gpp2",
  18419. "3gp": "video/3gpp",
  18420. "3gpp": "video/3gpp",
  18421. "3mf": "model/3mf",
  18422. "aac": "audio/aac",
  18423. "ac": "application/pkix-attr-cert",
  18424. "adp": "audio/adpcm",
  18425. "adts": "audio/aac",
  18426. "ai": "application/postscript",
  18427. "aml": "application/automationml-aml+xml",
  18428. "amlx": "application/automationml-amlx+zip",
  18429. "amr": "audio/amr",
  18430. "apng": "image/apng",
  18431. "appcache": "text/cache-manifest",
  18432. "appinstaller": "application/appinstaller",
  18433. "appx": "application/appx",
  18434. "appxbundle": "application/appxbundle",
  18435. "asc": "application/pgp-keys",
  18436. "atom": "application/atom+xml",
  18437. "atomcat": "application/atomcat+xml",
  18438. "atomdeleted": "application/atomdeleted+xml",
  18439. "atomsvc": "application/atomsvc+xml",
  18440. "au": "audio/basic",
  18441. "avci": "image/avci",
  18442. "avcs": "image/avcs",
  18443. "avif": "image/avif",
  18444. "aw": "application/applixware",
  18445. "bdoc": "application/bdoc",
  18446. "bin": "application/octet-stream",
  18447. "bmp": "image/bmp",
  18448. "bpk": "application/octet-stream",
  18449. "btf": "image/prs.btif",
  18450. "btif": "image/prs.btif",
  18451. "buffer": "application/octet-stream",
  18452. "ccxml": "application/ccxml+xml",
  18453. "cdfx": "application/cdfx+xml",
  18454. "cdmia": "application/cdmi-capability",
  18455. "cdmic": "application/cdmi-container",
  18456. "cdmid": "application/cdmi-domain",
  18457. "cdmio": "application/cdmi-object",
  18458. "cdmiq": "application/cdmi-queue",
  18459. "cer": "application/pkix-cert",
  18460. "cgm": "image/cgm",
  18461. "cjs": "application/node",
  18462. "class": "application/java-vm",
  18463. "coffee": "text/coffeescript",
  18464. "conf": "text/plain",
  18465. "cpl": "application/cpl+xml",
  18466. "cpt": "application/mac-compactpro",
  18467. "crl": "application/pkix-crl",
  18468. "css": "text/css",
  18469. "csv": "text/csv",
  18470. "cu": "application/cu-seeme",
  18471. "cwl": "application/cwl",
  18472. "cww": "application/prs.cww",
  18473. "davmount": "application/davmount+xml",
  18474. "dbk": "application/docbook+xml",
  18475. "deb": "application/octet-stream",
  18476. "def": "text/plain",
  18477. "deploy": "application/octet-stream",
  18478. "dib": "image/bmp",
  18479. "disposition-notification": "message/disposition-notification",
  18480. "dist": "application/octet-stream",
  18481. "distz": "application/octet-stream",
  18482. "dll": "application/octet-stream",
  18483. "dmg": "application/octet-stream",
  18484. "dms": "application/octet-stream",
  18485. "doc": "application/msword",
  18486. "dot": "application/msword",
  18487. "dpx": "image/dpx",
  18488. "drle": "image/dicom-rle",
  18489. "dsc": "text/prs.lines.tag",
  18490. "dssc": "application/dssc+der",
  18491. "dtd": "application/xml-dtd",
  18492. "dump": "application/octet-stream",
  18493. "dwd": "application/atsc-dwd+xml",
  18494. "ear": "application/java-archive",
  18495. "ecma": "application/ecmascript",
  18496. "elc": "application/octet-stream",
  18497. "emf": "image/emf",
  18498. "eml": "message/rfc822",
  18499. "emma": "application/emma+xml",
  18500. "emotionml": "application/emotionml+xml",
  18501. "eps": "application/postscript",
  18502. "epub": "application/epub+zip",
  18503. "exe": "application/octet-stream",
  18504. "exi": "application/exi",
  18505. "exp": "application/express",
  18506. "exr": "image/aces",
  18507. "ez": "application/andrew-inset",
  18508. "fdf": "application/fdf",
  18509. "fdt": "application/fdt+xml",
  18510. "fits": "image/fits",
  18511. "g3": "image/g3fax",
  18512. "gbr": "application/rpki-ghostbusters",
  18513. "geojson": "application/geo+json",
  18514. "gif": "image/gif",
  18515. "glb": "model/gltf-binary",
  18516. "gltf": "model/gltf+json",
  18517. "gml": "application/gml+xml",
  18518. "gpx": "application/gpx+xml",
  18519. "gram": "application/srgs",
  18520. "grxml": "application/srgs+xml",
  18521. "gxf": "application/gxf",
  18522. "gz": "application/gzip",
  18523. "h261": "video/h261",
  18524. "h263": "video/h263",
  18525. "h264": "video/h264",
  18526. "heic": "image/heic",
  18527. "heics": "image/heic-sequence",
  18528. "heif": "image/heif",
  18529. "heifs": "image/heif-sequence",
  18530. "hej2": "image/hej2k",
  18531. "held": "application/atsc-held+xml",
  18532. "hjson": "application/hjson",
  18533. "hlp": "application/winhlp",
  18534. "hqx": "application/mac-binhex40",
  18535. "hsj2": "image/hsj2",
  18536. "htm": "text/html",
  18537. "html": "text/html",
  18538. "ics": "text/calendar",
  18539. "ief": "image/ief",
  18540. "ifb": "text/calendar",
  18541. "iges": "model/iges",
  18542. "igs": "model/iges",
  18543. "img": "application/octet-stream",
  18544. "in": "text/plain",
  18545. "ini": "text/plain",
  18546. "ink": "application/inkml+xml",
  18547. "inkml": "application/inkml+xml",
  18548. "ipfix": "application/ipfix",
  18549. "iso": "application/octet-stream",
  18550. "its": "application/its+xml",
  18551. "jade": "text/jade",
  18552. "jar": "application/java-archive",
  18553. "jhc": "image/jphc",
  18554. "jls": "image/jls",
  18555. "jp2": "image/jp2",
  18556. "jpe": "image/jpeg",
  18557. "jpeg": "image/jpeg",
  18558. "jpf": "image/jpx",
  18559. "jpg": "image/jpeg",
  18560. "jpg2": "image/jp2",
  18561. "jpgm": "image/jpm",
  18562. "jpgv": "video/jpeg",
  18563. "jph": "image/jph",
  18564. "jpm": "image/jpm",
  18565. "jpx": "image/jpx",
  18566. "js": "text/javascript",
  18567. "json": "application/json",
  18568. "json5": "application/json5",
  18569. "jsonld": "application/ld+json",
  18570. "jsonml": "application/jsonml+json",
  18571. "jsx": "text/jsx",
  18572. "jt": "model/jt",
  18573. "jxl": "image/jxl",
  18574. "jxr": "image/jxr",
  18575. "jxra": "image/jxra",
  18576. "jxrs": "image/jxrs",
  18577. "jxs": "image/jxs",
  18578. "jxsc": "image/jxsc",
  18579. "jxsi": "image/jxsi",
  18580. "jxss": "image/jxss",
  18581. "kar": "audio/midi",
  18582. "ktx": "image/ktx",
  18583. "ktx2": "image/ktx2",
  18584. "less": "text/less",
  18585. "lgr": "application/lgr+xml",
  18586. "list": "text/plain",
  18587. "litcoffee": "text/coffeescript",
  18588. "log": "text/plain",
  18589. "lostxml": "application/lost+xml",
  18590. "lrf": "application/octet-stream",
  18591. "m1v": "video/mpeg",
  18592. "m21": "application/mp21",
  18593. "m2a": "audio/mpeg",
  18594. "m2t": "video/mp2t",
  18595. "m2ts": "video/mp2t",
  18596. "m2v": "video/mpeg",
  18597. "m3a": "audio/mpeg",
  18598. "m4a": "audio/mp4",
  18599. "m4p": "application/mp4",
  18600. "m4s": "video/iso.segment",
  18601. "ma": "application/mathematica",
  18602. "mads": "application/mads+xml",
  18603. "maei": "application/mmt-aei+xml",
  18604. "man": "text/troff",
  18605. "manifest": "text/cache-manifest",
  18606. "map": "application/json",
  18607. "mar": "application/octet-stream",
  18608. "markdown": "text/markdown",
  18609. "mathml": "application/mathml+xml",
  18610. "mb": "application/mathematica",
  18611. "mbox": "application/mbox",
  18612. "md": "text/markdown",
  18613. "mdx": "text/mdx",
  18614. "me": "text/troff",
  18615. "mesh": "model/mesh",
  18616. "meta4": "application/metalink4+xml",
  18617. "metalink": "application/metalink+xml",
  18618. "mets": "application/mets+xml",
  18619. "mft": "application/rpki-manifest",
  18620. "mid": "audio/midi",
  18621. "midi": "audio/midi",
  18622. "mime": "message/rfc822",
  18623. "mj2": "video/mj2",
  18624. "mjp2": "video/mj2",
  18625. "mjs": "text/javascript",
  18626. "mml": "text/mathml",
  18627. "mods": "application/mods+xml",
  18628. "mov": "video/quicktime",
  18629. "mp2": "audio/mpeg",
  18630. "mp21": "application/mp21",
  18631. "mp2a": "audio/mpeg",
  18632. "mp3": "audio/mpeg",
  18633. "mp4": "video/mp4",
  18634. "mp4a": "audio/mp4",
  18635. "mp4s": "application/mp4",
  18636. "mp4v": "video/mp4",
  18637. "mpd": "application/dash+xml",
  18638. "mpe": "video/mpeg",
  18639. "mpeg": "video/mpeg",
  18640. "mpf": "application/media-policy-dataset+xml",
  18641. "mpg": "video/mpeg",
  18642. "mpg4": "video/mp4",
  18643. "mpga": "audio/mpeg",
  18644. "mpp": "application/dash-patch+xml",
  18645. "mrc": "application/marc",
  18646. "mrcx": "application/marcxml+xml",
  18647. "ms": "text/troff",
  18648. "mscml": "application/mediaservercontrol+xml",
  18649. "msh": "model/mesh",
  18650. "msi": "application/octet-stream",
  18651. "msix": "application/msix",
  18652. "msixbundle": "application/msixbundle",
  18653. "msm": "application/octet-stream",
  18654. "msp": "application/octet-stream",
  18655. "mtl": "model/mtl",
  18656. "mts": "video/mp2t",
  18657. "musd": "application/mmt-usd+xml",
  18658. "mxf": "application/mxf",
  18659. "mxmf": "audio/mobile-xmf",
  18660. "mxml": "application/xv+xml",
  18661. "n3": "text/n3",
  18662. "nb": "application/mathematica",
  18663. "nq": "application/n-quads",
  18664. "nt": "application/n-triples",
  18665. "obj": "model/obj",
  18666. "oda": "application/oda",
  18667. "oga": "audio/ogg",
  18668. "ogg": "audio/ogg",
  18669. "ogv": "video/ogg",
  18670. "ogx": "application/ogg",
  18671. "omdoc": "application/omdoc+xml",
  18672. "onepkg": "application/onenote",
  18673. "onetmp": "application/onenote",
  18674. "onetoc": "application/onenote",
  18675. "onetoc2": "application/onenote",
  18676. "opf": "application/oebps-package+xml",
  18677. "opus": "audio/ogg",
  18678. "otf": "font/otf",
  18679. "owl": "application/rdf+xml",
  18680. "oxps": "application/oxps",
  18681. "p10": "application/pkcs10",
  18682. "p7c": "application/pkcs7-mime",
  18683. "p7m": "application/pkcs7-mime",
  18684. "p7s": "application/pkcs7-signature",
  18685. "p8": "application/pkcs8",
  18686. "pdf": "application/pdf",
  18687. "pfr": "application/font-tdpfr",
  18688. "pgp": "application/pgp-encrypted",
  18689. "pkg": "application/octet-stream",
  18690. "pki": "application/pkixcmp",
  18691. "pkipath": "application/pkix-pkipath",
  18692. "pls": "application/pls+xml",
  18693. "png": "image/png",
  18694. "prc": "model/prc",
  18695. "prf": "application/pics-rules",
  18696. "provx": "application/provenance+xml",
  18697. "ps": "application/postscript",
  18698. "pskcxml": "application/pskc+xml",
  18699. "pti": "image/prs.pti",
  18700. "qt": "video/quicktime",
  18701. "raml": "application/raml+yaml",
  18702. "rapd": "application/route-apd+xml",
  18703. "rdf": "application/rdf+xml",
  18704. "relo": "application/p2p-overlay+xml",
  18705. "rif": "application/reginfo+xml",
  18706. "rl": "application/resource-lists+xml",
  18707. "rld": "application/resource-lists-diff+xml",
  18708. "rmi": "audio/midi",
  18709. "rnc": "application/relax-ng-compact-syntax",
  18710. "rng": "application/xml",
  18711. "roa": "application/rpki-roa",
  18712. "roff": "text/troff",
  18713. "rq": "application/sparql-query",
  18714. "rs": "application/rls-services+xml",
  18715. "rsat": "application/atsc-rsat+xml",
  18716. "rsd": "application/rsd+xml",
  18717. "rsheet": "application/urc-ressheet+xml",
  18718. "rss": "application/rss+xml",
  18719. "rtf": "text/rtf",
  18720. "rtx": "text/richtext",
  18721. "rusd": "application/route-usd+xml",
  18722. "s3m": "audio/s3m",
  18723. "sbml": "application/sbml+xml",
  18724. "scq": "application/scvp-cv-request",
  18725. "scs": "application/scvp-cv-response",
  18726. "sdp": "application/sdp",
  18727. "senmlx": "application/senml+xml",
  18728. "sensmlx": "application/sensml+xml",
  18729. "ser": "application/java-serialized-object",
  18730. "setpay": "application/set-payment-initiation",
  18731. "setreg": "application/set-registration-initiation",
  18732. "sgi": "image/sgi",
  18733. "sgm": "text/sgml",
  18734. "sgml": "text/sgml",
  18735. "shex": "text/shex",
  18736. "shf": "application/shf+xml",
  18737. "shtml": "text/html",
  18738. "sieve": "application/sieve",
  18739. "sig": "application/pgp-signature",
  18740. "sil": "audio/silk",
  18741. "silo": "model/mesh",
  18742. "siv": "application/sieve",
  18743. "slim": "text/slim",
  18744. "slm": "text/slim",
  18745. "sls": "application/route-s-tsid+xml",
  18746. "smi": "application/smil+xml",
  18747. "smil": "application/smil+xml",
  18748. "snd": "audio/basic",
  18749. "so": "application/octet-stream",
  18750. "spdx": "text/spdx",
  18751. "spp": "application/scvp-vp-response",
  18752. "spq": "application/scvp-vp-request",
  18753. "spx": "audio/ogg",
  18754. "sql": "application/sql",
  18755. "sru": "application/sru+xml",
  18756. "srx": "application/sparql-results+xml",
  18757. "ssdl": "application/ssdl+xml",
  18758. "ssml": "application/ssml+xml",
  18759. "stk": "application/hyperstudio",
  18760. "stl": "model/stl",
  18761. "stpx": "model/step+xml",
  18762. "stpxz": "model/step-xml+zip",
  18763. "stpz": "model/step+zip",
  18764. "styl": "text/stylus",
  18765. "stylus": "text/stylus",
  18766. "svg": "image/svg+xml",
  18767. "svgz": "image/svg+xml",
  18768. "swidtag": "application/swid+xml",
  18769. "t": "text/troff",
  18770. "t38": "image/t38",
  18771. "td": "application/urc-targetdesc+xml",
  18772. "tei": "application/tei+xml",
  18773. "teicorpus": "application/tei+xml",
  18774. "text": "text/plain",
  18775. "tfi": "application/thraud+xml",
  18776. "tfx": "image/tiff-fx",
  18777. "tif": "image/tiff",
  18778. "tiff": "image/tiff",
  18779. "toml": "application/toml",
  18780. "tr": "text/troff",
  18781. "trig": "application/trig",
  18782. "ts": "video/mp2t",
  18783. "tsd": "application/timestamped-data",
  18784. "tsv": "text/tab-separated-values",
  18785. "ttc": "font/collection",
  18786. "ttf": "font/ttf",
  18787. "ttl": "text/turtle",
  18788. "ttml": "application/ttml+xml",
  18789. "txt": "text/plain",
  18790. "u3d": "model/u3d",
  18791. "u8dsn": "message/global-delivery-status",
  18792. "u8hdr": "message/global-headers",
  18793. "u8mdn": "message/global-disposition-notification",
  18794. "u8msg": "message/global",
  18795. "ubj": "application/ubjson",
  18796. "uri": "text/uri-list",
  18797. "uris": "text/uri-list",
  18798. "urls": "text/uri-list",
  18799. "vcard": "text/vcard",
  18800. "vrml": "model/vrml",
  18801. "vtt": "text/vtt",
  18802. "vxml": "application/voicexml+xml",
  18803. "war": "application/java-archive",
  18804. "wasm": "application/wasm",
  18805. "wav": "audio/wav",
  18806. "weba": "audio/webm",
  18807. "webm": "video/webm",
  18808. "webmanifest": "application/manifest+json",
  18809. "webp": "image/webp",
  18810. "wgsl": "text/wgsl",
  18811. "wgt": "application/widget",
  18812. "wif": "application/watcherinfo+xml",
  18813. "wmf": "image/wmf",
  18814. "woff": "font/woff",
  18815. "woff2": "font/woff2",
  18816. "wrl": "model/vrml",
  18817. "wsdl": "application/wsdl+xml",
  18818. "wspolicy": "application/wspolicy+xml",
  18819. "x3d": "model/x3d+xml",
  18820. "x3db": "model/x3d+fastinfoset",
  18821. "x3dbz": "model/x3d+binary",
  18822. "x3dv": "model/x3d-vrml",
  18823. "x3dvz": "model/x3d+vrml",
  18824. "x3dz": "model/x3d+xml",
  18825. "xaml": "application/xaml+xml",
  18826. "xav": "application/xcap-att+xml",
  18827. "xca": "application/xcap-caps+xml",
  18828. "xcs": "application/calendar+xml",
  18829. "xdf": "application/xcap-diff+xml",
  18830. "xdssc": "application/dssc+xml",
  18831. "xel": "application/xcap-el+xml",
  18832. "xenc": "application/xenc+xml",
  18833. "xer": "application/patch-ops-error+xml",
  18834. "xfdf": "application/xfdf",
  18835. "xht": "application/xhtml+xml",
  18836. "xhtml": "application/xhtml+xml",
  18837. "xhvml": "application/xv+xml",
  18838. "xlf": "application/xliff+xml",
  18839. "xm": "audio/xm",
  18840. "xml": "text/xml",
  18841. "xns": "application/xcap-ns+xml",
  18842. "xop": "application/xop+xml",
  18843. "xpl": "application/xproc+xml",
  18844. "xsd": "application/xml",
  18845. "xsf": "application/prs.xsf+xml",
  18846. "xsl": "application/xml",
  18847. "xslt": "application/xml",
  18848. "xspf": "application/xspf+xml",
  18849. "xvm": "application/xv+xml",
  18850. "xvml": "application/xv+xml",
  18851. "yaml": "text/yaml",
  18852. "yang": "application/yang",
  18853. "yin": "application/yin+xml",
  18854. "yml": "text/yaml",
  18855. "zip": "application/zip"
  18856. };
  18857. function lookup(extn) {
  18858. let tmp = ("" + extn).trim().toLowerCase();
  18859. let idx = tmp.lastIndexOf(".");
  18860. return mimes[!~idx ? tmp : tmp.substring(++idx)];
  18861. }
  18862. //#endregion
  18863. //#region src/node/plugins/asset.ts
  18864. const assetUrlRE = /__VITE_ASSET__([\w$]+)__(?:\$_(.*?)__)?/g;
  18865. const jsSourceMapRE = /\.[cm]?js\.map$/;
  18866. const noInlineRE = /[?&]no-inline\b/;
  18867. const inlineRE$3 = /[?&]inline\b/;
  18868. const assetCache = /* @__PURE__ */ new WeakMap();
  18869. /** a set of referenceId for entry CSS assets for each environment */
  18870. const cssEntriesMap = /* @__PURE__ */ new WeakMap();
  18871. function registerCustomMime() {
  18872. mimes.ico = "image/x-icon";
  18873. mimes.cur = "image/x-icon";
  18874. mimes.flac = "audio/flac";
  18875. mimes.eot = "application/vnd.ms-fontobject";
  18876. }
  18877. function renderAssetUrlInJS(pluginContext, chunk, opts, code) {
  18878. const { environment } = pluginContext;
  18879. const toRelativeRuntime = createToImportMetaURLBasedRelativeRuntime(opts.format, environment.config.isWorker);
  18880. let match;
  18881. let s;
  18882. assetUrlRE.lastIndex = 0;
  18883. while (match = assetUrlRE.exec(code)) {
  18884. s ||= new MagicString(code);
  18885. const [full, referenceId, postfix = ""] = match;
  18886. const file = pluginContext.getFileName(referenceId);
  18887. chunk.viteMetadata.importedAssets.add(cleanUrl(file));
  18888. const replacement = toOutputFilePathInJS(environment, file + postfix, "asset", chunk.fileName, "js", toRelativeRuntime);
  18889. const replacementString = typeof replacement === "string" ? JSON.stringify(encodeURIPath(replacement)).slice(1, -1) : `"+${replacement.runtime}+"`;
  18890. s.update(match.index, match.index + full.length, replacementString);
  18891. }
  18892. const publicAssetUrlMap = publicAssetUrlCache.get(environment.getTopLevelConfig());
  18893. publicAssetUrlRE.lastIndex = 0;
  18894. while (match = publicAssetUrlRE.exec(code)) {
  18895. s ||= new MagicString(code);
  18896. const [full, hash] = match;
  18897. const replacement = toOutputFilePathInJS(environment, publicAssetUrlMap.get(hash).slice(1), "public", chunk.fileName, "js", toRelativeRuntime);
  18898. const replacementString = typeof replacement === "string" ? JSON.stringify(encodeURIPath(replacement)).slice(1, -1) : `"+${replacement.runtime}+"`;
  18899. s.update(match.index, match.index + full.length, replacementString);
  18900. }
  18901. return s;
  18902. }
  18903. /**
  18904. * Also supports loading plain strings with import text from './foo.txt?raw'
  18905. */
  18906. function assetPlugin(config) {
  18907. registerCustomMime();
  18908. return {
  18909. name: "vite:asset",
  18910. perEnvironmentStartEndDuringDev: true,
  18911. buildStart() {
  18912. assetCache.set(this.environment, /* @__PURE__ */ new Map());
  18913. cssEntriesMap.set(this.environment, /* @__PURE__ */ new Map());
  18914. },
  18915. resolveId: {
  18916. filter: { id: [
  18917. urlRE$1,
  18918. DEFAULT_ASSETS_RE,
  18919. ...makeIdFiltersToMatchWithQuery(config.rawAssetsInclude).map((v) => typeof v === "string" ? picomatch.makeRe(v, { dot: true }) : v)
  18920. ] },
  18921. handler(id) {
  18922. if (!config.assetsInclude(cleanUrl(id)) && !urlRE$1.test(id)) return;
  18923. if (checkPublicFile(id, config)) return id;
  18924. }
  18925. },
  18926. load: {
  18927. filter: { id: {
  18928. include: [
  18929. rawRE$1,
  18930. urlRE$1,
  18931. DEFAULT_ASSETS_RE,
  18932. ...makeIdFiltersToMatchWithQuery(config.rawAssetsInclude)
  18933. ],
  18934. exclude: /^\0/
  18935. } },
  18936. async handler(id) {
  18937. if (rawRE$1.test(id)) {
  18938. const file = checkPublicFile(id, config) || cleanUrl(id);
  18939. this.addWatchFile(file);
  18940. return {
  18941. code: `export default ${JSON.stringify(await fsp.readFile(file, "utf-8"))}`,
  18942. moduleType: "js"
  18943. };
  18944. }
  18945. if (!urlRE$1.test(id) && !config.assetsInclude(cleanUrl(id))) return;
  18946. id = removeUrlQuery(id);
  18947. let url = await fileToUrl$1(this, id);
  18948. if (!url.startsWith("data:") && this.environment.mode === "dev") {
  18949. const mod = this.environment.moduleGraph.getModuleById(id);
  18950. if (mod && mod.lastHMRTimestamp > 0) url = injectQuery(url, `t=${mod.lastHMRTimestamp}`);
  18951. }
  18952. return {
  18953. code: `export default ${JSON.stringify(encodeURIPath(url))}`,
  18954. moduleSideEffects: config.command === "build" && this.getModuleInfo(id)?.isEntry ? "no-treeshake" : false,
  18955. meta: config.command === "build" ? { "vite:asset": true } : void 0,
  18956. moduleType: "js"
  18957. };
  18958. }
  18959. },
  18960. ...config.command === "build" ? { renderChunk(code, chunk, opts) {
  18961. const s = renderAssetUrlInJS(this, chunk, opts, code);
  18962. if (s) return {
  18963. code: s.toString(),
  18964. map: this.environment.config.build.sourcemap ? s.generateMap({ hires: "boundary" }) : null
  18965. };
  18966. else return null;
  18967. } } : {},
  18968. generateBundle(_, bundle) {
  18969. let importedFiles;
  18970. for (const file in bundle) {
  18971. const chunk = bundle[file];
  18972. if (chunk.type === "chunk" && chunk.isEntry && chunk.moduleIds.length === 1 && config.assetsInclude(chunk.moduleIds[0]) && this.getModuleInfo(chunk.moduleIds[0])?.meta["vite:asset"]) {
  18973. if (!importedFiles) {
  18974. importedFiles = /* @__PURE__ */ new Set();
  18975. for (const file in bundle) {
  18976. const chunk = bundle[file];
  18977. if (chunk.type === "chunk") {
  18978. for (const importedFile of chunk.imports) importedFiles.add(importedFile);
  18979. for (const importedFile of chunk.dynamicImports) importedFiles.add(importedFile);
  18980. }
  18981. }
  18982. }
  18983. if (!importedFiles.has(file)) delete bundle[file];
  18984. }
  18985. }
  18986. if (config.command === "build" && !this.environment.config.build.emitAssets) {
  18987. for (const file in bundle) if (bundle[file].type === "asset" && !file.endsWith("ssr-manifest.json") && !jsSourceMapRE.test(file)) delete bundle[file];
  18988. }
  18989. },
  18990. watchChange(id) {
  18991. assetCache.get(this.environment)?.delete(normalizePath(id));
  18992. }
  18993. };
  18994. }
  18995. async function fileToUrl$1(pluginContext, id, asFileUrl = false) {
  18996. const { environment } = pluginContext;
  18997. if (!environment.config.isBundled) return fileToDevUrl(environment, id, asFileUrl);
  18998. else return fileToBuiltUrl(pluginContext, id);
  18999. }
  19000. async function fileToDevUrl(environment, id, asFileUrl = false) {
  19001. const config = environment.getTopLevelConfig();
  19002. const publicFile = checkPublicFile(id, config);
  19003. if (inlineRE$3.test(id)) {
  19004. const file = publicFile || cleanUrl(id);
  19005. return assetToDataURL(environment, file, await fsp.readFile(file));
  19006. }
  19007. const cleanedId = cleanUrl(id);
  19008. if (cleanedId.endsWith(".svg")) {
  19009. const file = publicFile || cleanedId;
  19010. const content = await fsp.readFile(file);
  19011. if (shouldInline(environment, file, id, content, void 0, void 0)) return assetToDataURL(environment, file, content);
  19012. }
  19013. if (asFileUrl) return pathToFileURL(cleanedId).href;
  19014. let rtn;
  19015. if (publicFile) rtn = id;
  19016. else if (id.startsWith(withTrailingSlash(config.root))) rtn = "/" + path.posix.relative(config.root, id);
  19017. else rtn = path.posix.join(FS_PREFIX, id);
  19018. return joinUrlSegments(joinUrlSegments(config.server.origin ?? "", config.decodedBase), removeLeadingSlash(rtn));
  19019. }
  19020. function getPublicAssetFilename(hash, config) {
  19021. return publicAssetUrlCache.get(config)?.get(hash);
  19022. }
  19023. const publicAssetUrlCache = /* @__PURE__ */ new WeakMap();
  19024. const publicAssetUrlRE = /__VITE_PUBLIC_ASSET__([a-z\d]{8})__/g;
  19025. function publicFileToBuiltUrl(url, config) {
  19026. if (config.command !== "build") return joinUrlSegments(config.decodedBase, url);
  19027. const hash = getHash(url);
  19028. let cache = publicAssetUrlCache.get(config);
  19029. if (!cache) {
  19030. cache = /* @__PURE__ */ new Map();
  19031. publicAssetUrlCache.set(config, cache);
  19032. }
  19033. if (!cache.get(hash)) cache.set(hash, url);
  19034. return `__VITE_PUBLIC_ASSET__${hash}__`;
  19035. }
  19036. const GIT_LFS_PREFIX = Buffer$1.from("version https://git-lfs.github.com");
  19037. function isGitLfsPlaceholder(content) {
  19038. if (content.length < GIT_LFS_PREFIX.length) return false;
  19039. return GIT_LFS_PREFIX.compare(content, 0, GIT_LFS_PREFIX.length) === 0;
  19040. }
  19041. /**
  19042. * Register an asset to be emitted as part of the bundle (if necessary)
  19043. * and returns the resolved public URL
  19044. */
  19045. async function fileToBuiltUrl(pluginContext, id, skipPublicCheck = false, forceInline) {
  19046. const environment = pluginContext.environment;
  19047. const topLevelConfig = environment.getTopLevelConfig();
  19048. if (!skipPublicCheck) {
  19049. const publicFile = checkPublicFile(id, topLevelConfig);
  19050. if (publicFile) if (inlineRE$3.test(id)) id = publicFile;
  19051. else return publicFileToBuiltUrl(id, topLevelConfig);
  19052. }
  19053. const cache = assetCache.get(environment);
  19054. const cached = cache.get(id);
  19055. if (cached) return cached;
  19056. let { file, postfix } = splitFileAndPostfix(id);
  19057. const content = await fsp.readFile(file);
  19058. let url;
  19059. if (shouldInline(environment, file, id, content, pluginContext, forceInline)) url = assetToDataURL(environment, file, content);
  19060. else {
  19061. const originalFileName = normalizePath(path.relative(environment.config.root, file));
  19062. const referenceId = pluginContext.emitFile({
  19063. type: "asset",
  19064. name: path.basename(file),
  19065. originalFileName,
  19066. source: content
  19067. });
  19068. if (environment.config.command === "build" && noInlineRE.test(postfix)) postfix = postfix.replace(noInlineRE, "").replace(/^&/, "?");
  19069. if (environment.config.command === "serve" && environment.config.experimental.bundledDev) url = toOutputFilePathInJSForBundledDev(environment, pluginContext.getFileName(referenceId));
  19070. else url = `__VITE_ASSET__${referenceId}__${postfix ? `$_${postfix}__` : ``}`;
  19071. }
  19072. cache.set(id, url);
  19073. return url;
  19074. }
  19075. function toOutputFilePathInJSForBundledDev(environment, filename) {
  19076. const outputUrl = toOutputFilePathInJS(environment, filename, "asset", "assets/dummy.js", "js", () => {
  19077. throw new Error("unreachable");
  19078. });
  19079. if (typeof outputUrl === "object") throw new Error("unreachable");
  19080. return outputUrl;
  19081. }
  19082. async function urlToBuiltUrl(pluginContext, url, importer, forceInline) {
  19083. const topLevelConfig = pluginContext.environment.getTopLevelConfig();
  19084. if (checkPublicFile(url, topLevelConfig)) return publicFileToBuiltUrl(url, topLevelConfig);
  19085. return fileToBuiltUrl(pluginContext, normalizePath(url[0] === "/" ? path.join(topLevelConfig.root, url) : path.join(path.dirname(importer), url)), true, forceInline);
  19086. }
  19087. function shouldInline(environment, file, id, content, buildPluginContext, forceInline) {
  19088. if (noInlineRE.test(id)) return false;
  19089. if (inlineRE$3.test(id)) return true;
  19090. if (buildPluginContext) {
  19091. if (environment.config.build.lib) return true;
  19092. if (buildPluginContext.getModuleInfo(id)?.isEntry) return false;
  19093. }
  19094. if (forceInline !== void 0) return forceInline;
  19095. if (file.endsWith(".html")) return false;
  19096. if (file.endsWith(".svg") && id.includes("#")) return false;
  19097. let limit;
  19098. const { assetsInlineLimit } = environment.config.build;
  19099. if (typeof assetsInlineLimit === "function") {
  19100. const userShouldInline = assetsInlineLimit(file, content);
  19101. if (userShouldInline != null) return userShouldInline;
  19102. limit = DEFAULT_ASSETS_INLINE_LIMIT;
  19103. } else limit = Number(assetsInlineLimit);
  19104. return content.length < limit && !isGitLfsPlaceholder(content);
  19105. }
  19106. function assetToDataURL(environment, file, content) {
  19107. if (environment.config.build.lib && isGitLfsPlaceholder(content)) environment.logger.warn(import_picocolors.default.yellow(`Inlined file ${file} was not downloaded via Git LFS`));
  19108. if (file.endsWith(".svg")) return svgToDataURL(content);
  19109. else return `data:${lookup(file) ?? "application/octet-stream"};base64,${content.toString("base64")}`;
  19110. }
  19111. const nestedQuotesRE = /"[^"']*'[^"]*"|'[^'"]*"[^']*'/;
  19112. function svgToDataURL(content) {
  19113. const stringContent = content.toString();
  19114. if (stringContent.includes("<text") || stringContent.includes("<foreignObject") || nestedQuotesRE.test(stringContent)) return `data:image/svg+xml;base64,${content.toString("base64")}`;
  19115. else return "data:image/svg+xml," + stringContent.trim().replaceAll(/>\s+</g, "><").replaceAll("\"", "'").replaceAll("%", "%25").replaceAll("#", "%23").replaceAll("<", "%3c").replaceAll(">", "%3e").replaceAll(/\s+/g, "%20");
  19116. }
  19117. //#endregion
  19118. //#region ../../node_modules/.pnpm/lilconfig@3.1.3/node_modules/lilconfig/src/index.js
  19119. var require_src$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  19120. const path$2 = __require("path");
  19121. const fs$2 = __require("fs");
  19122. const os$1 = __require("os");
  19123. const url = __require("url");
  19124. const fsReadFileAsync = fs$2.promises.readFile;
  19125. /** @type {(name: string, sync: boolean) => string[]} */
  19126. function getDefaultSearchPlaces(name, sync) {
  19127. return [
  19128. "package.json",
  19129. `.${name}rc.json`,
  19130. `.${name}rc.js`,
  19131. `.${name}rc.cjs`,
  19132. ...sync ? [] : [`.${name}rc.mjs`],
  19133. `.config/${name}rc`,
  19134. `.config/${name}rc.json`,
  19135. `.config/${name}rc.js`,
  19136. `.config/${name}rc.cjs`,
  19137. ...sync ? [] : [`.config/${name}rc.mjs`],
  19138. `${name}.config.js`,
  19139. `${name}.config.cjs`,
  19140. ...sync ? [] : [`${name}.config.mjs`]
  19141. ];
  19142. }
  19143. /**
  19144. * @type {(p: string) => string}
  19145. *
  19146. * see #17
  19147. * On *nix, if cwd is not under homedir,
  19148. * the last path will be '', ('/build' -> '')
  19149. * but it should be '/' actually.
  19150. * And on Windows, this will never happen. ('C:\build' -> 'C:')
  19151. */
  19152. function parentDir(p) {
  19153. return path$2.dirname(p) || path$2.sep;
  19154. }
  19155. /** @type {import('./index').LoaderSync} */
  19156. const jsonLoader = (_, content) => JSON.parse(content);
  19157. const requireFunc = typeof __webpack_require__ === "function" ? __non_webpack_require__ : __require;
  19158. /** @type {import('./index').LoadersSync} */
  19159. const defaultLoadersSync = Object.freeze({
  19160. ".js": requireFunc,
  19161. ".json": requireFunc,
  19162. ".cjs": requireFunc,
  19163. noExt: jsonLoader
  19164. });
  19165. module.exports.defaultLoadersSync = defaultLoadersSync;
  19166. /** @type {import('./index').Loader} */
  19167. const dynamicImport = async (id) => {
  19168. try {
  19169. return (await import(url.pathToFileURL(id).href)).default;
  19170. } catch (e) {
  19171. try {
  19172. return requireFunc(id);
  19173. } catch (requireE) {
  19174. if (requireE.code === "ERR_REQUIRE_ESM" || requireE instanceof SyntaxError && requireE.toString().includes("Cannot use import statement outside a module")) throw e;
  19175. throw requireE;
  19176. }
  19177. }
  19178. };
  19179. /** @type {import('./index').Loaders} */
  19180. const defaultLoaders = Object.freeze({
  19181. ".js": dynamicImport,
  19182. ".mjs": dynamicImport,
  19183. ".cjs": dynamicImport,
  19184. ".json": jsonLoader,
  19185. noExt: jsonLoader
  19186. });
  19187. module.exports.defaultLoaders = defaultLoaders;
  19188. /**
  19189. * @param {string} name
  19190. * @param {import('./index').Options | import('./index').OptionsSync} options
  19191. * @param {boolean} sync
  19192. * @returns {Required<import('./index').Options | import('./index').OptionsSync>}
  19193. */
  19194. function getOptions(name, options, sync) {
  19195. /** @type {Required<import('./index').Options>} */
  19196. const conf = {
  19197. stopDir: os$1.homedir(),
  19198. searchPlaces: getDefaultSearchPlaces(name, sync),
  19199. ignoreEmptySearchPlaces: true,
  19200. cache: true,
  19201. transform: (x) => x,
  19202. packageProp: [name],
  19203. ...options,
  19204. loaders: {
  19205. ...sync ? defaultLoadersSync : defaultLoaders,
  19206. ...options.loaders
  19207. }
  19208. };
  19209. conf.searchPlaces.forEach((place) => {
  19210. const key = path$2.extname(place) || "noExt";
  19211. const loader = conf.loaders[key];
  19212. if (!loader) throw new Error(`Missing loader for extension "${place}"`);
  19213. if (typeof loader !== "function") throw new Error(`Loader for extension "${place}" is not a function: Received ${typeof loader}.`);
  19214. });
  19215. return conf;
  19216. }
  19217. /** @type {(props: string | string[], obj: Record<string, any>) => unknown} */
  19218. function getPackageProp(props, obj) {
  19219. if (typeof props === "string" && props in obj) return obj[props];
  19220. return (Array.isArray(props) ? props : props.split(".")).reduce((acc, prop) => acc === void 0 ? acc : acc[prop], obj) || null;
  19221. }
  19222. /** @param {string} filepath */
  19223. function validateFilePath(filepath) {
  19224. if (!filepath) throw new Error("load must pass a non-empty string");
  19225. }
  19226. /** @type {(loader: import('./index').Loader, ext: string) => void} */
  19227. function validateLoader(loader, ext) {
  19228. if (!loader) throw new Error(`No loader specified for extension "${ext}"`);
  19229. if (typeof loader !== "function") throw new Error("loader is not a function");
  19230. }
  19231. /** @type {(enableCache: boolean) => <T>(c: Map<string, T>, filepath: string, res: T) => T} */
  19232. const makeEmplace = (enableCache) => (c, filepath, res) => {
  19233. if (enableCache) c.set(filepath, res);
  19234. return res;
  19235. };
  19236. /** @type {import('./index').lilconfig} */
  19237. module.exports.lilconfig = function lilconfig(name, options) {
  19238. const { ignoreEmptySearchPlaces, loaders, packageProp, searchPlaces, stopDir, transform, cache } = getOptions(name, options ?? {}, false);
  19239. const searchCache = /* @__PURE__ */ new Map();
  19240. const loadCache = /* @__PURE__ */ new Map();
  19241. const emplace = makeEmplace(cache);
  19242. return {
  19243. async search(searchFrom = process.cwd()) {
  19244. /** @type {import('./index').LilconfigResult} */
  19245. const result = {
  19246. config: null,
  19247. filepath: ""
  19248. };
  19249. /** @type {Set<string>} */
  19250. const visited = /* @__PURE__ */ new Set();
  19251. let dir = searchFrom;
  19252. dirLoop: while (true) {
  19253. if (cache) {
  19254. const r = searchCache.get(dir);
  19255. if (r !== void 0) {
  19256. for (const p of visited) searchCache.set(p, r);
  19257. return r;
  19258. }
  19259. visited.add(dir);
  19260. }
  19261. for (const searchPlace of searchPlaces) {
  19262. const filepath = path$2.join(dir, searchPlace);
  19263. try {
  19264. await fs$2.promises.access(filepath);
  19265. } catch {
  19266. continue;
  19267. }
  19268. const content = String(await fsReadFileAsync(filepath));
  19269. const loaderKey = path$2.extname(searchPlace) || "noExt";
  19270. const loader = loaders[loaderKey];
  19271. if (searchPlace === "package.json") {
  19272. const maybeConfig = getPackageProp(packageProp, await loader(filepath, content));
  19273. if (maybeConfig != null) {
  19274. result.config = maybeConfig;
  19275. result.filepath = filepath;
  19276. break dirLoop;
  19277. }
  19278. continue;
  19279. }
  19280. const isEmpty = content.trim() === "";
  19281. if (isEmpty && ignoreEmptySearchPlaces) continue;
  19282. if (isEmpty) {
  19283. result.isEmpty = true;
  19284. result.config = void 0;
  19285. } else {
  19286. validateLoader(loader, loaderKey);
  19287. result.config = await loader(filepath, content);
  19288. }
  19289. result.filepath = filepath;
  19290. break dirLoop;
  19291. }
  19292. if (dir === stopDir || dir === parentDir(dir)) break dirLoop;
  19293. dir = parentDir(dir);
  19294. }
  19295. const transformed = result.filepath === "" && result.config === null ? transform(null) : transform(result);
  19296. if (cache) for (const p of visited) searchCache.set(p, transformed);
  19297. return transformed;
  19298. },
  19299. async load(filepath) {
  19300. validateFilePath(filepath);
  19301. const absPath = path$2.resolve(process.cwd(), filepath);
  19302. if (cache && loadCache.has(absPath)) return loadCache.get(absPath);
  19303. const { base, ext } = path$2.parse(absPath);
  19304. const loaderKey = ext || "noExt";
  19305. const loader = loaders[loaderKey];
  19306. validateLoader(loader, loaderKey);
  19307. const content = String(await fsReadFileAsync(absPath));
  19308. if (base === "package.json") return emplace(loadCache, absPath, transform({
  19309. config: getPackageProp(packageProp, await loader(absPath, content)),
  19310. filepath: absPath
  19311. }));
  19312. /** @type {import('./index').LilconfigResult} */
  19313. const result = {
  19314. config: null,
  19315. filepath: absPath
  19316. };
  19317. const isEmpty = content.trim() === "";
  19318. if (isEmpty && ignoreEmptySearchPlaces) return emplace(loadCache, absPath, transform({
  19319. config: void 0,
  19320. filepath: absPath,
  19321. isEmpty: true
  19322. }));
  19323. result.config = isEmpty ? void 0 : await loader(absPath, content);
  19324. return emplace(loadCache, absPath, transform(isEmpty ? {
  19325. ...result,
  19326. isEmpty,
  19327. config: void 0
  19328. } : result));
  19329. },
  19330. clearLoadCache() {
  19331. if (cache) loadCache.clear();
  19332. },
  19333. clearSearchCache() {
  19334. if (cache) searchCache.clear();
  19335. },
  19336. clearCaches() {
  19337. if (cache) {
  19338. loadCache.clear();
  19339. searchCache.clear();
  19340. }
  19341. }
  19342. };
  19343. };
  19344. /** @type {import('./index').lilconfigSync} */
  19345. module.exports.lilconfigSync = function lilconfigSync(name, options) {
  19346. const { ignoreEmptySearchPlaces, loaders, packageProp, searchPlaces, stopDir, transform, cache } = getOptions(name, options ?? {}, true);
  19347. const searchCache = /* @__PURE__ */ new Map();
  19348. const loadCache = /* @__PURE__ */ new Map();
  19349. const emplace = makeEmplace(cache);
  19350. return {
  19351. search(searchFrom = process.cwd()) {
  19352. /** @type {import('./index').LilconfigResult} */
  19353. const result = {
  19354. config: null,
  19355. filepath: ""
  19356. };
  19357. /** @type {Set<string>} */
  19358. const visited = /* @__PURE__ */ new Set();
  19359. let dir = searchFrom;
  19360. dirLoop: while (true) {
  19361. if (cache) {
  19362. const r = searchCache.get(dir);
  19363. if (r !== void 0) {
  19364. for (const p of visited) searchCache.set(p, r);
  19365. return r;
  19366. }
  19367. visited.add(dir);
  19368. }
  19369. for (const searchPlace of searchPlaces) {
  19370. const filepath = path$2.join(dir, searchPlace);
  19371. try {
  19372. fs$2.accessSync(filepath);
  19373. } catch {
  19374. continue;
  19375. }
  19376. const loaderKey = path$2.extname(searchPlace) || "noExt";
  19377. const loader = loaders[loaderKey];
  19378. const content = String(fs$2.readFileSync(filepath));
  19379. if (searchPlace === "package.json") {
  19380. const maybeConfig = getPackageProp(packageProp, loader(filepath, content));
  19381. if (maybeConfig != null) {
  19382. result.config = maybeConfig;
  19383. result.filepath = filepath;
  19384. break dirLoop;
  19385. }
  19386. continue;
  19387. }
  19388. const isEmpty = content.trim() === "";
  19389. if (isEmpty && ignoreEmptySearchPlaces) continue;
  19390. if (isEmpty) {
  19391. result.isEmpty = true;
  19392. result.config = void 0;
  19393. } else {
  19394. validateLoader(loader, loaderKey);
  19395. result.config = loader(filepath, content);
  19396. }
  19397. result.filepath = filepath;
  19398. break dirLoop;
  19399. }
  19400. if (dir === stopDir || dir === parentDir(dir)) break dirLoop;
  19401. dir = parentDir(dir);
  19402. }
  19403. const transformed = result.filepath === "" && result.config === null ? transform(null) : transform(result);
  19404. if (cache) for (const p of visited) searchCache.set(p, transformed);
  19405. return transformed;
  19406. },
  19407. load(filepath) {
  19408. validateFilePath(filepath);
  19409. const absPath = path$2.resolve(process.cwd(), filepath);
  19410. if (cache && loadCache.has(absPath)) return loadCache.get(absPath);
  19411. const { base, ext } = path$2.parse(absPath);
  19412. const loaderKey = ext || "noExt";
  19413. const loader = loaders[loaderKey];
  19414. validateLoader(loader, loaderKey);
  19415. const content = String(fs$2.readFileSync(absPath));
  19416. if (base === "package.json") return transform({
  19417. config: getPackageProp(packageProp, loader(absPath, content)),
  19418. filepath: absPath
  19419. });
  19420. const result = {
  19421. config: null,
  19422. filepath: absPath
  19423. };
  19424. const isEmpty = content.trim() === "";
  19425. if (isEmpty && ignoreEmptySearchPlaces) return emplace(loadCache, absPath, transform({
  19426. filepath: absPath,
  19427. config: void 0,
  19428. isEmpty: true
  19429. }));
  19430. result.config = isEmpty ? void 0 : loader(absPath, content);
  19431. return emplace(loadCache, absPath, transform(isEmpty ? {
  19432. ...result,
  19433. isEmpty,
  19434. config: void 0
  19435. } : result));
  19436. },
  19437. clearLoadCache() {
  19438. if (cache) loadCache.clear();
  19439. },
  19440. clearSearchCache() {
  19441. if (cache) searchCache.clear();
  19442. },
  19443. clearCaches() {
  19444. if (cache) {
  19445. loadCache.clear();
  19446. searchCache.clear();
  19447. }
  19448. }
  19449. };
  19450. };
  19451. }));
  19452. //#endregion
  19453. //#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
  19454. var require_req = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  19455. const { createRequire: createRequire$1 } = __require("node:module");
  19456. const { fileURLToPath: fileURLToPath$1, pathToFileURL: pathToFileURL$1 } = __require("node:url");
  19457. const TS_EXT_RE = /\.[mc]?ts$/;
  19458. let tsx;
  19459. let jiti;
  19460. let importError = [];
  19461. /**
  19462. * @param {string} name
  19463. * @param {string} rootFile
  19464. * @returns {Promise<any>}
  19465. */
  19466. async function req(name, rootFile = fileURLToPath$1(import.meta.url)) {
  19467. let url = createRequire$1(rootFile).resolve(name);
  19468. try {
  19469. return (await import(`${pathToFileURL$1(url)}?t=${Date.now()}`)).default;
  19470. } catch (err) {
  19471. if (!TS_EXT_RE.test(url))
  19472. /* c8 ignore start */
  19473. throw err;
  19474. }
  19475. if (tsx === void 0) try {
  19476. tsx = await import("tsx/cjs/api");
  19477. } catch (error) {
  19478. importError.push(error);
  19479. }
  19480. if (tsx) {
  19481. let loaded = tsx.require(name, rootFile);
  19482. return loaded && "__esModule" in loaded ? loaded.default : loaded;
  19483. }
  19484. if (jiti === void 0) try {
  19485. jiti = (await import("jiti")).default;
  19486. } catch (error) {
  19487. importError.push(error);
  19488. }
  19489. if (jiti) return jiti(rootFile, { interopDefault: true })(name);
  19490. 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")}`);
  19491. }
  19492. module.exports = req;
  19493. }));
  19494. //#endregion
  19495. //#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
  19496. var require_options = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  19497. const req = require_req();
  19498. /**
  19499. * Load Options
  19500. *
  19501. * @private
  19502. * @method options
  19503. *
  19504. * @param {Object} config PostCSS Config
  19505. *
  19506. * @return {Promise<Object>} options PostCSS Options
  19507. */
  19508. async function options(config, file) {
  19509. if (config.parser && typeof config.parser === "string") try {
  19510. config.parser = await req(config.parser, file);
  19511. } catch (err) {
  19512. throw new Error(`Loading PostCSS Parser failed: ${err.message}\n\n(@${file})`);
  19513. }
  19514. if (config.syntax && typeof config.syntax === "string") try {
  19515. config.syntax = await req(config.syntax, file);
  19516. } catch (err) {
  19517. throw new Error(`Loading PostCSS Syntax failed: ${err.message}\n\n(@${file})`);
  19518. }
  19519. if (config.stringifier && typeof config.stringifier === "string") try {
  19520. config.stringifier = await req(config.stringifier, file);
  19521. } catch (err) {
  19522. throw new Error(`Loading PostCSS Stringifier failed: ${err.message}\n\n(@${file})`);
  19523. }
  19524. return config;
  19525. }
  19526. module.exports = options;
  19527. }));
  19528. //#endregion
  19529. //#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
  19530. var require_plugins = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  19531. const req = require_req();
  19532. /**
  19533. * Plugin Loader
  19534. *
  19535. * @private
  19536. * @method load
  19537. *
  19538. * @param {String} plugin PostCSS Plugin Name
  19539. * @param {Object} options PostCSS Plugin Options
  19540. *
  19541. * @return {Promise<Function>} PostCSS Plugin
  19542. */
  19543. async function load(plugin, options, file) {
  19544. try {
  19545. if (options === null || options === void 0 || Object.keys(options).length === 0) return await req(plugin, file);
  19546. else return (await req(plugin, file))(options);
  19547. } catch (err) {
  19548. throw new Error(`Loading PostCSS Plugin failed: ${err.message}\n\n(@${file})`);
  19549. }
  19550. }
  19551. /**
  19552. * Load Plugins
  19553. *
  19554. * @private
  19555. * @method plugins
  19556. *
  19557. * @param {Object} config PostCSS Config Plugins
  19558. *
  19559. * @return {Promise<Array>} plugins PostCSS Plugins
  19560. */
  19561. async function plugins(config, file) {
  19562. let list = [];
  19563. if (Array.isArray(config.plugins)) list = config.plugins.filter(Boolean);
  19564. else {
  19565. list = Object.entries(config.plugins).filter(([, options]) => {
  19566. return options !== false;
  19567. }).map(([plugin, options]) => {
  19568. return load(plugin, options, file);
  19569. });
  19570. list = await Promise.all(list);
  19571. }
  19572. if (list.length && list.length > 0) list.forEach((plugin, i) => {
  19573. if (plugin.default) plugin = plugin.default;
  19574. if (plugin.postcss === true) plugin = plugin();
  19575. else if (plugin.postcss) plugin = plugin.postcss;
  19576. 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})`);
  19577. });
  19578. return list;
  19579. }
  19580. module.exports = plugins;
  19581. }));
  19582. //#endregion
  19583. //#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
  19584. var require_src = /* @__PURE__ */ __commonJSMin(((exports, module) => {
  19585. const { resolve: resolve$3 } = __require("node:path");
  19586. const config = require_src$1();
  19587. const loadOptions = require_options();
  19588. const loadPlugins = require_plugins();
  19589. const req = require_req();
  19590. const interopRequireDefault = (obj) => obj && obj.__esModule ? obj : { default: obj };
  19591. /**
  19592. * Process the result from cosmiconfig
  19593. *
  19594. * @param {Object} ctx Config Context
  19595. * @param {Object} result Cosmiconfig result
  19596. *
  19597. * @return {Promise<Object>} PostCSS Config
  19598. */
  19599. async function processResult(ctx, result) {
  19600. let file = result.filepath || "";
  19601. let projectConfig = interopRequireDefault(result.config).default || {};
  19602. if (typeof projectConfig === "function") projectConfig = projectConfig(ctx);
  19603. else projectConfig = Object.assign({}, projectConfig, ctx);
  19604. if (!projectConfig.plugins) projectConfig.plugins = [];
  19605. let res = {
  19606. file,
  19607. options: await loadOptions(projectConfig, file),
  19608. plugins: await loadPlugins(projectConfig, file)
  19609. };
  19610. delete projectConfig.plugins;
  19611. return res;
  19612. }
  19613. /**
  19614. * Builds the Config Context
  19615. *
  19616. * @param {Object} ctx Config Context
  19617. *
  19618. * @return {Object} Config Context
  19619. */
  19620. function createContext(ctx) {
  19621. /**
  19622. * @type {Object}
  19623. *
  19624. * @prop {String} cwd=process.cwd() Config search start location
  19625. * @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`
  19626. */
  19627. ctx = Object.assign({
  19628. cwd: process.cwd(),
  19629. env: process.env.NODE_ENV
  19630. }, ctx);
  19631. if (!ctx.env) process.env.NODE_ENV = "development";
  19632. return ctx;
  19633. }
  19634. async function loader(filepath) {
  19635. return req(filepath);
  19636. }
  19637. let yaml;
  19638. async function yamlLoader(_, content) {
  19639. if (!yaml) try {
  19640. yaml = await import("yaml");
  19641. } catch (e) {
  19642. /* c8 ignore start */
  19643. throw new Error(`'yaml' is required for the YAML configuration files. Make sure it is installed\nError: ${e.message}`);
  19644. }
  19645. return yaml.parse(content);
  19646. }
  19647. /** @return {import('lilconfig').Options} */
  19648. const withLoaders = (options = {}) => {
  19649. let moduleName = "postcss";
  19650. return {
  19651. ...options,
  19652. loaders: {
  19653. ...options.loaders,
  19654. ".cjs": loader,
  19655. ".cts": loader,
  19656. ".js": loader,
  19657. ".mjs": loader,
  19658. ".mts": loader,
  19659. ".ts": loader,
  19660. ".yaml": yamlLoader,
  19661. ".yml": yamlLoader
  19662. },
  19663. searchPlaces: [
  19664. ...options.searchPlaces || [],
  19665. "package.json",
  19666. `.${moduleName}rc`,
  19667. `.${moduleName}rc.json`,
  19668. `.${moduleName}rc.yaml`,
  19669. `.${moduleName}rc.yml`,
  19670. `.${moduleName}rc.ts`,
  19671. `.${moduleName}rc.cts`,
  19672. `.${moduleName}rc.mts`,
  19673. `.${moduleName}rc.js`,
  19674. `.${moduleName}rc.cjs`,
  19675. `.${moduleName}rc.mjs`,
  19676. `${moduleName}.config.ts`,
  19677. `${moduleName}.config.cts`,
  19678. `${moduleName}.config.mts`,
  19679. `${moduleName}.config.js`,
  19680. `${moduleName}.config.cjs`,
  19681. `${moduleName}.config.mjs`
  19682. ]
  19683. };
  19684. };
  19685. /**
  19686. * Load Config
  19687. *
  19688. * @method rc
  19689. *
  19690. * @param {Object} ctx Config Context
  19691. * @param {String} path Config Path
  19692. * @param {Object} options Config Options
  19693. *
  19694. * @return {Promise} config PostCSS Config
  19695. */
  19696. function rc(ctx, path, options) {
  19697. /**
  19698. * @type {Object} The full Config Context
  19699. */
  19700. ctx = createContext(ctx);
  19701. /**
  19702. * @type {String} `process.cwd()`
  19703. */
  19704. path = path ? resolve$3(path) : process.cwd();
  19705. return config.lilconfig("postcss", withLoaders(options)).search(path).then((result) => {
  19706. if (!result) throw new Error(`No PostCSS Config found in: ${path}`);
  19707. return processResult(ctx, result);
  19708. });
  19709. }
  19710. /**
  19711. * Autoload Config for PostCSS
  19712. *
  19713. * @author Michael Ciniawsky @michael-ciniawsky <michael.ciniawsky@gmail.com>
  19714. * @license MIT
  19715. *
  19716. * @module postcss-load-config
  19717. * @version 2.1.0
  19718. *
  19719. * @requires comsiconfig
  19720. * @requires ./options
  19721. * @requires ./plugins
  19722. */
  19723. module.exports = rc;
  19724. }));
  19725. //#endregion
  19726. //#region src/node/server/sourcemap.ts
  19727. var import_convert_source_map = /* @__PURE__ */ __toESM((/* @__PURE__ */ __commonJSMin(((exports) => {
  19728. Object.defineProperty(exports, "commentRegex", { get: function getCommentRegex() {
  19729. return /^\s*?\/[\/\*][@#]\s+?sourceMappingURL=data:(((?:application|text)\/json)(?:;charset=([^;,]+?)?)?)?(?:;(base64))?,(.*?)$/gm;
  19730. } });
  19731. Object.defineProperty(exports, "mapFileCommentRegex", { get: function getMapFileCommentRegex() {
  19732. return /(?:\/\/[@#][ \t]+?sourceMappingURL=([^\s'"`]+?)[ \t]*?$)|(?:\/\*[@#][ \t]+sourceMappingURL=([^*]+?)[ \t]*?(?:\*\/){1}[ \t]*?$)/gm;
  19733. } });
  19734. var decodeBase64;
  19735. if (typeof Buffer !== "undefined") if (typeof Buffer.from === "function") decodeBase64 = decodeBase64WithBufferFrom;
  19736. else decodeBase64 = decodeBase64WithNewBuffer;
  19737. else decodeBase64 = decodeBase64WithAtob;
  19738. function decodeBase64WithBufferFrom(base64) {
  19739. return Buffer.from(base64, "base64").toString();
  19740. }
  19741. function decodeBase64WithNewBuffer(base64) {
  19742. if (typeof value === "number") throw new TypeError("The value to decode must not be of type number.");
  19743. return new Buffer(base64, "base64").toString();
  19744. }
  19745. function decodeBase64WithAtob(base64) {
  19746. return decodeURIComponent(escape(atob(base64)));
  19747. }
  19748. function stripComment(sm) {
  19749. return sm.split(",").pop();
  19750. }
  19751. function readFromFileMap(sm, read) {
  19752. var r = exports.mapFileCommentRegex.exec(sm);
  19753. var filename = r[1] || r[2];
  19754. try {
  19755. var sm = read(filename);
  19756. if (sm != null && typeof sm.catch === "function") return sm.catch(throwError);
  19757. else return sm;
  19758. } catch (e) {
  19759. throwError(e);
  19760. }
  19761. function throwError(e) {
  19762. throw new Error("An error occurred while trying to read the map file at " + filename + "\n" + e.stack);
  19763. }
  19764. }
  19765. function Converter(sm, opts) {
  19766. opts = opts || {};
  19767. if (opts.hasComment) sm = stripComment(sm);
  19768. if (opts.encoding === "base64") sm = decodeBase64(sm);
  19769. else if (opts.encoding === "uri") sm = decodeURIComponent(sm);
  19770. if (opts.isJSON || opts.encoding) sm = JSON.parse(sm);
  19771. this.sourcemap = sm;
  19772. }
  19773. Converter.prototype.toJSON = function(space) {
  19774. return JSON.stringify(this.sourcemap, null, space);
  19775. };
  19776. if (typeof Buffer !== "undefined") if (typeof Buffer.from === "function") Converter.prototype.toBase64 = encodeBase64WithBufferFrom;
  19777. else Converter.prototype.toBase64 = encodeBase64WithNewBuffer;
  19778. else Converter.prototype.toBase64 = encodeBase64WithBtoa;
  19779. function encodeBase64WithBufferFrom() {
  19780. var json = this.toJSON();
  19781. return Buffer.from(json, "utf8").toString("base64");
  19782. }
  19783. function encodeBase64WithNewBuffer() {
  19784. var json = this.toJSON();
  19785. if (typeof json === "number") throw new TypeError("The json to encode must not be of type number.");
  19786. return new Buffer(json, "utf8").toString("base64");
  19787. }
  19788. function encodeBase64WithBtoa() {
  19789. var json = this.toJSON();
  19790. return btoa(unescape(encodeURIComponent(json)));
  19791. }
  19792. Converter.prototype.toURI = function() {
  19793. var json = this.toJSON();
  19794. return encodeURIComponent(json);
  19795. };
  19796. Converter.prototype.toComment = function(options) {
  19797. var encoding, content, data;
  19798. if (options != null && options.encoding === "uri") {
  19799. encoding = "";
  19800. content = this.toURI();
  19801. } else {
  19802. encoding = ";base64";
  19803. content = this.toBase64();
  19804. }
  19805. data = "sourceMappingURL=data:application/json;charset=utf-8" + encoding + "," + content;
  19806. return options != null && options.multiline ? "/*# " + data + " */" : "//# " + data;
  19807. };
  19808. Converter.prototype.toObject = function() {
  19809. return JSON.parse(this.toJSON());
  19810. };
  19811. Converter.prototype.addProperty = function(key, value) {
  19812. if (this.sourcemap.hasOwnProperty(key)) throw new Error("property \"" + key + "\" already exists on the sourcemap, use set property instead");
  19813. return this.setProperty(key, value);
  19814. };
  19815. Converter.prototype.setProperty = function(key, value) {
  19816. this.sourcemap[key] = value;
  19817. return this;
  19818. };
  19819. Converter.prototype.getProperty = function(key) {
  19820. return this.sourcemap[key];
  19821. };
  19822. exports.fromObject = function(obj) {
  19823. return new Converter(obj);
  19824. };
  19825. exports.fromJSON = function(json) {
  19826. return new Converter(json, { isJSON: true });
  19827. };
  19828. exports.fromURI = function(uri) {
  19829. return new Converter(uri, { encoding: "uri" });
  19830. };
  19831. exports.fromBase64 = function(base64) {
  19832. return new Converter(base64, { encoding: "base64" });
  19833. };
  19834. exports.fromComment = function(comment) {
  19835. var m, encoding;
  19836. comment = comment.replace(/^\/\*/g, "//").replace(/\*\/$/g, "");
  19837. m = exports.commentRegex.exec(comment);
  19838. encoding = m && m[4] || "uri";
  19839. return new Converter(comment, {
  19840. encoding,
  19841. hasComment: true
  19842. });
  19843. };
  19844. function makeConverter(sm) {
  19845. return new Converter(sm, { isJSON: true });
  19846. }
  19847. exports.fromMapFileComment = function(comment, read) {
  19848. 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");
  19849. var sm = readFromFileMap(comment, read);
  19850. if (sm != null && typeof sm.then === "function") return sm.then(makeConverter);
  19851. else return makeConverter(sm);
  19852. };
  19853. exports.fromSource = function(content) {
  19854. var m = content.match(exports.commentRegex);
  19855. return m ? exports.fromComment(m.pop()) : null;
  19856. };
  19857. exports.fromMapFileSource = function(content, read) {
  19858. 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");
  19859. var m = content.match(exports.mapFileCommentRegex);
  19860. return m ? exports.fromMapFileComment(m.pop(), read) : null;
  19861. };
  19862. exports.removeComments = function(src) {
  19863. return src.replace(exports.commentRegex, "");
  19864. };
  19865. exports.removeMapFileComments = function(src) {
  19866. return src.replace(exports.mapFileCommentRegex, "");
  19867. };
  19868. exports.generateMapFileComment = function(file, options) {
  19869. var data = "sourceMappingURL=" + file;
  19870. return options && options.multiline ? "/*# " + data + " */" : "//# " + data;
  19871. };
  19872. })))(), 1);
  19873. const debug$10 = createDebugger("vite:sourcemap", { onlyWhenFocused: true });
  19874. const virtualSourceRE = /^(?:dep:|browser-external:|virtual:)|\0/;
  19875. async function computeSourceRoute(map, file) {
  19876. let sourceRoot;
  19877. try {
  19878. sourceRoot = await fsp.realpath(path.resolve(path.dirname(file), map.sourceRoot || ""));
  19879. } catch {}
  19880. return sourceRoot;
  19881. }
  19882. async function injectSourcesContent(map, file, logger) {
  19883. let sourceRootPromise;
  19884. const missingSources = [];
  19885. const sourcesContent = map.sourcesContent || [];
  19886. const sourcesContentPromises = [];
  19887. for (let index = 0; index < map.sources.length; index++) {
  19888. const sourcePath = map.sources[index];
  19889. if (sourcesContent[index] == null && sourcePath && !virtualSourceRE.test(sourcePath)) sourcesContentPromises.push((async () => {
  19890. sourceRootPromise ??= computeSourceRoute(map, file);
  19891. const sourceRoot = await sourceRootPromise;
  19892. let resolvedSourcePath = cleanUrl(decodeURI(sourcePath));
  19893. if (sourceRoot) resolvedSourcePath = path.resolve(sourceRoot, resolvedSourcePath);
  19894. sourcesContent[index] = await fsp.readFile(resolvedSourcePath, "utf-8").catch(() => {
  19895. missingSources.push(resolvedSourcePath);
  19896. return null;
  19897. });
  19898. })());
  19899. }
  19900. await Promise.all(sourcesContentPromises);
  19901. map.sourcesContent = sourcesContent;
  19902. if (missingSources.length) {
  19903. logger.warnOnce(`Sourcemap for "${file}" points to missing source files`);
  19904. debug$10?.(`Missing sources:\n ` + missingSources.join(`\n `));
  19905. }
  19906. }
  19907. function genSourceMapUrl(map) {
  19908. if (typeof map !== "string") map = JSON.stringify(map);
  19909. return `data:application/json;base64,${Buffer.from(map).toString("base64")}`;
  19910. }
  19911. function getCodeWithSourcemap(type, code, map) {
  19912. if (debug$10) code += `\n/*${JSON.stringify(map, null, 2).replace(/\*\//g, "*\\/")}*/\n`;
  19913. if (type === "js") code += `\n//# sourceMappingURL=${genSourceMapUrl(map)}`;
  19914. else if (type === "css") code += `\n/*# sourceMappingURL=${genSourceMapUrl(map)} */`;
  19915. return code;
  19916. }
  19917. function applySourcemapIgnoreList(map, sourcemapPath, sourcemapIgnoreList, logger) {
  19918. let { x_google_ignoreList } = map;
  19919. if (x_google_ignoreList === void 0) x_google_ignoreList = [];
  19920. if (map.sources) {
  19921. for (let sourcesIndex = 0; sourcesIndex < map.sources.length; ++sourcesIndex) {
  19922. const sourcePath = map.sources[sourcesIndex];
  19923. if (!sourcePath) continue;
  19924. const ignoreList = sourcemapIgnoreList(path.isAbsolute(sourcePath) ? sourcePath : path.resolve(path.dirname(sourcemapPath), sourcePath), sourcemapPath);
  19925. if (logger && typeof ignoreList !== "boolean") logger.warn("sourcemapIgnoreList function must return a boolean.");
  19926. if (ignoreList && !x_google_ignoreList.includes(sourcesIndex)) x_google_ignoreList.push(sourcesIndex);
  19927. }
  19928. if (x_google_ignoreList.length > 0) {
  19929. if (!map.x_google_ignoreList) map.x_google_ignoreList = x_google_ignoreList;
  19930. }
  19931. }
  19932. }
  19933. function extractSourcemapFromFile(code, filePath) {
  19934. const map = (import_convert_source_map.fromSource(code) || import_convert_source_map.fromMapFileSource(code, createConvertSourceMapReadMap(filePath)))?.toObject();
  19935. if (map) return {
  19936. code: code.replace(import_convert_source_map.default.mapFileCommentRegex, blankReplacer),
  19937. map
  19938. };
  19939. }
  19940. function createConvertSourceMapReadMap(originalFileName) {
  19941. return (filename) => {
  19942. return fs.readFileSync(path.resolve(path.dirname(originalFileName), filename), "utf-8");
  19943. };
  19944. }
  19945. //#endregion
  19946. //#region src/node/idResolver.ts
  19947. /**
  19948. * Some projects like Astro were overriding config.createResolver to add a custom
  19949. * alias plugin. For the client and ssr environments, we root through it to avoid
  19950. * breaking changes for now.
  19951. */
  19952. function createBackCompatIdResolver(config, options) {
  19953. const compatResolve = config.createResolver(options);
  19954. let resolve;
  19955. return async (environment, id, importer, aliasOnly) => {
  19956. if (environment.name === "client" || environment.name === "ssr") return compatResolve(id, importer, aliasOnly, environment.name === "ssr");
  19957. resolve ??= createIdResolver(config, options);
  19958. return resolve(environment, id, importer, aliasOnly);
  19959. };
  19960. }
  19961. /**
  19962. * Create an internal resolver to be used in special scenarios, e.g.
  19963. * optimizer and handling css @imports
  19964. */
  19965. function createIdResolver(config, options) {
  19966. const scan = options?.scan;
  19967. const pluginContainerMap = /* @__PURE__ */ new Map();
  19968. async function resolve(environment, id, importer) {
  19969. let pluginContainer = pluginContainerMap.get(environment);
  19970. if (!pluginContainer) {
  19971. pluginContainer = await createEnvironmentPluginContainer(environment, [alias$1({ entries: environment.config.resolve.alias }), ...oxcResolvePlugin({
  19972. root: config.root,
  19973. isProduction: config.isProduction,
  19974. isBuild: config.command === "build",
  19975. asSrc: true,
  19976. preferRelative: false,
  19977. tryIndex: true,
  19978. ...options,
  19979. idOnly: true
  19980. }, environment.config)], void 0, false);
  19981. pluginContainerMap.set(environment, pluginContainer);
  19982. }
  19983. return await pluginContainer.resolveId(id, importer, { scan });
  19984. }
  19985. const aliasOnlyPluginContainerMap = /* @__PURE__ */ new Map();
  19986. async function resolveAlias(environment, id, importer) {
  19987. let pluginContainer = aliasOnlyPluginContainerMap.get(environment);
  19988. if (!pluginContainer) {
  19989. pluginContainer = await createEnvironmentPluginContainer(environment, [alias$1({ entries: environment.config.resolve.alias })], void 0, false);
  19990. aliasOnlyPluginContainerMap.set(environment, pluginContainer);
  19991. }
  19992. return await pluginContainer.resolveId(id, importer, { scan });
  19993. }
  19994. return async (environment, id, importer, aliasOnly) => {
  19995. return (await (aliasOnly ? resolveAlias : resolve)(environment, id, importer))?.id;
  19996. };
  19997. }
  19998. //#endregion
  19999. //#region src/node/baseEnvironment.ts
  20000. const environmentColors = [
  20001. import_picocolors.default.blue,
  20002. import_picocolors.default.magenta,
  20003. import_picocolors.default.green,
  20004. import_picocolors.default.gray
  20005. ];
  20006. var PartialEnvironment = class {
  20007. name;
  20008. getTopLevelConfig() {
  20009. return this._topLevelConfig;
  20010. }
  20011. config;
  20012. logger;
  20013. /**
  20014. * @internal
  20015. */
  20016. _options;
  20017. /**
  20018. * @internal
  20019. */
  20020. _topLevelConfig;
  20021. constructor(name, topLevelConfig, options = topLevelConfig.environments[name]) {
  20022. if (!/^[\w$]+$/.test(name)) throw new Error(`Invalid environment name "${name}". Environment names must only contain alphanumeric characters and "$", "_".`);
  20023. this.name = name;
  20024. this._topLevelConfig = topLevelConfig;
  20025. this._options = options;
  20026. this.config = new Proxy(options, { get: (target, prop) => {
  20027. if (prop === "logger") return this.logger;
  20028. if (prop in target) return this._options[prop];
  20029. return this._topLevelConfig[prop];
  20030. } });
  20031. const environment = import_picocolors.default.dim(`(${this.name})`);
  20032. const infoColor = environmentColors[[...this.name].reduce((acc, c) => acc + c.charCodeAt(0), 0) % environmentColors.length || 0];
  20033. this.logger = {
  20034. get hasWarned() {
  20035. return topLevelConfig.logger.hasWarned;
  20036. },
  20037. info(msg, opts) {
  20038. return topLevelConfig.logger.info(msg, {
  20039. ...opts,
  20040. environment: infoColor(environment)
  20041. });
  20042. },
  20043. warn(msg, opts) {
  20044. return topLevelConfig.logger.warn(msg, {
  20045. ...opts,
  20046. environment: import_picocolors.default.yellow(environment)
  20047. });
  20048. },
  20049. warnOnce(msg, opts) {
  20050. return topLevelConfig.logger.warnOnce(msg, {
  20051. ...opts,
  20052. environment: import_picocolors.default.yellow(environment)
  20053. });
  20054. },
  20055. error(msg, opts) {
  20056. return topLevelConfig.logger.error(msg, {
  20057. ...opts,
  20058. environment: import_picocolors.default.red(environment)
  20059. });
  20060. },
  20061. clearScreen(type) {
  20062. return topLevelConfig.logger.clearScreen(type);
  20063. },
  20064. hasErrorLogged(error) {
  20065. return topLevelConfig.logger.hasErrorLogged(error);
  20066. }
  20067. };
  20068. }
  20069. };
  20070. var BaseEnvironment = class extends PartialEnvironment {
  20071. get plugins() {
  20072. return this.config.plugins;
  20073. }
  20074. /**
  20075. * @internal
  20076. */
  20077. _initiated = false;
  20078. constructor(name, config, options = config.environments[name]) {
  20079. super(name, config, options);
  20080. }
  20081. };
  20082. //#endregion
  20083. //#region src/node/server/searchRoot.ts
  20084. const ROOT_FILES = ["pnpm-workspace.yaml", "lerna.json"];
  20085. function hasWorkspacePackageJSON(root) {
  20086. const path = join(root, "package.json");
  20087. if (!isFileReadable(path)) return false;
  20088. try {
  20089. return !!(JSON.parse(fs.readFileSync(path, "utf-8")) || {}).workspaces;
  20090. } catch {
  20091. return false;
  20092. }
  20093. }
  20094. function hasRootFile(root) {
  20095. return ROOT_FILES.some((file) => fs.existsSync(join(root, file)));
  20096. }
  20097. function hasPackageJSON(root) {
  20098. const path = join(root, "package.json");
  20099. return fs.existsSync(path);
  20100. }
  20101. /**
  20102. * Search up for the nearest `package.json`
  20103. */
  20104. function searchForPackageRoot(current, root = current) {
  20105. if (hasPackageJSON(current)) return current;
  20106. const dir = dirname(current);
  20107. if (!dir || dir === current) return root;
  20108. return searchForPackageRoot(dir, root);
  20109. }
  20110. /**
  20111. * Search up for the nearest workspace root
  20112. */
  20113. function searchForWorkspaceRoot(current, root = searchForPackageRoot(current)) {
  20114. if (hasRootFile(current)) return current;
  20115. if (hasWorkspacePackageJSON(current)) return current;
  20116. const dir = dirname(current);
  20117. if (!dir || dir === current) return root;
  20118. return searchForWorkspaceRoot(dir, root);
  20119. }
  20120. //#endregion
  20121. //#region src/node/plugins/manifest.ts
  20122. const endsWithJSRE = /\.[cm]?js$/;
  20123. function manifestPlugin() {
  20124. const getState = perEnvironmentState(() => {
  20125. return {
  20126. manifest: {},
  20127. outputCount: 0,
  20128. reset() {
  20129. this.manifest = {};
  20130. this.outputCount = 0;
  20131. }
  20132. };
  20133. });
  20134. return perEnvironmentPlugin("native:manifest", (environment) => {
  20135. if (!environment.config.build.manifest) return false;
  20136. const root = environment.config.root;
  20137. const outPath = environment.config.build.manifest === true ? ".vite/manifest.json" : environment.config.build.manifest;
  20138. const envs = {};
  20139. function getChunkName(chunk) {
  20140. return getChunkOriginalFileName(chunk, root, false) ?? `_${path.basename(chunk.fileName)}`;
  20141. }
  20142. return [
  20143. {
  20144. name: "native:manifest-envs",
  20145. buildStart() {
  20146. envs[environment.name] = this.environment;
  20147. }
  20148. },
  20149. viteManifestPlugin({
  20150. root,
  20151. outPath,
  20152. isOutputOptionsForLegacyChunks: environment.config.isOutputOptionsForLegacyChunks,
  20153. cssEntries() {
  20154. return Object.fromEntries(cssEntriesMap.get(envs[environment.name]).entries());
  20155. }
  20156. }),
  20157. {
  20158. name: "native:manifest-compatible",
  20159. generateBundle(_, bundle) {
  20160. const asset = bundle[outPath];
  20161. if (asset.type === "asset") {
  20162. let manifest;
  20163. for (const output of Object.values(bundle)) {
  20164. const importedCss = output.viteMetadata?.importedCss;
  20165. const importedAssets = output.viteMetadata?.importedAssets;
  20166. if (!importedCss?.size && !importedAssets?.size) continue;
  20167. manifest ??= JSON.parse(asset.source.toString());
  20168. if (output.type === "chunk") {
  20169. const item = manifest[getChunkName(output)];
  20170. if (!item) continue;
  20171. if (importedCss?.size) item.css = [...importedCss];
  20172. if (importedAssets?.size) item.assets = [...importedAssets];
  20173. } else if (output.type === "asset" && output.names.length > 0) {
  20174. const keys = output.originalFileNames.length > 0 ? output.originalFileNames : [`_${path.basename(output.fileName)}`];
  20175. for (const key of keys) {
  20176. const item = manifest[key];
  20177. if (!item) continue;
  20178. if (!(item.file && endsWithJSRE.test(item.file))) {
  20179. if (importedCss?.size) item.css = [...importedCss];
  20180. if (importedAssets?.size) item.assets = [...importedAssets];
  20181. }
  20182. }
  20183. }
  20184. }
  20185. const output = this.environment.config.build.rolldownOptions.output;
  20186. const outputLength = Array.isArray(output) ? output.length : 1;
  20187. if (manifest && outputLength === 1) {
  20188. asset.source = JSON.stringify(manifest, void 0, 2);
  20189. return;
  20190. }
  20191. const state = getState(this);
  20192. state.outputCount++;
  20193. state.manifest = Object.assign(state.manifest, manifest ?? JSON.parse(asset.source.toString()));
  20194. if (state.outputCount >= outputLength) {
  20195. asset.source = JSON.stringify(state.manifest, void 0, 2);
  20196. state.reset();
  20197. } else delete bundle[outPath];
  20198. }
  20199. }
  20200. }
  20201. ];
  20202. });
  20203. }
  20204. function getChunkOriginalFileName(chunk, root, isLegacy) {
  20205. if (chunk.facadeModuleId) {
  20206. let name = normalizePath(path.relative(root, chunk.facadeModuleId));
  20207. if (isLegacy && !chunk.name.includes("-legacy")) {
  20208. const ext = path.extname(name);
  20209. const endPos = ext.length !== 0 ? -ext.length : void 0;
  20210. name = `${name.slice(0, endPos)}-legacy${ext}`;
  20211. }
  20212. return name.replace(/\0/g, "");
  20213. }
  20214. }
  20215. //#endregion
  20216. //#region src/node/plugins/css.ts
  20217. var import_src = /* @__PURE__ */ __toESM(require_src(), 1);
  20218. const decoder = new TextDecoder();
  20219. const _cssConfigDefaults = Object.freeze({
  20220. transformer: "postcss",
  20221. preprocessorMaxWorkers: true,
  20222. devSourcemap: false
  20223. });
  20224. const cssConfigDefaults = _cssConfigDefaults;
  20225. function resolveCSSOptions(options) {
  20226. const resolved = mergeWithDefaults(_cssConfigDefaults, options ?? {});
  20227. if (resolved.transformer === "lightningcss") {
  20228. resolved.lightningcss ??= {};
  20229. resolved.lightningcss.targets ??= convertTargets(ESBUILD_BASELINE_WIDELY_AVAILABLE_TARGET);
  20230. }
  20231. return resolved;
  20232. }
  20233. const cssModuleRE = new RegExp(`\\.module${CSS_LANGS_RE.source}`);
  20234. const directRequestRE = /[?&]direct\b/;
  20235. const htmlProxyRE$1 = /[?&]html-proxy\b/;
  20236. const htmlProxyIndexRE = /&index=(\d+)/;
  20237. const commonjsProxyRE = /[?&]commonjs-proxy/;
  20238. const inlineRE$2 = /[?&]inline\b/;
  20239. const inlineCSSRE$1 = /[?&]inline-css\b/;
  20240. const styleAttrRE = /[?&]style-attr\b/;
  20241. const functionCallRE = /^[A-Z_][.\w-]*\(/i;
  20242. const transformOnlyRE = /[?&]transform-only\b/;
  20243. const nonEscapedDoubleQuoteRe = /(?<!\\)"/g;
  20244. const defaultCssBundleName = "style.css";
  20245. var PreprocessLang = /* @__PURE__ */ function(PreprocessLang) {
  20246. PreprocessLang["less"] = "less";
  20247. PreprocessLang["sass"] = "sass";
  20248. PreprocessLang["scss"] = "scss";
  20249. PreprocessLang["styl"] = "styl";
  20250. PreprocessLang["stylus"] = "stylus";
  20251. return PreprocessLang;
  20252. }(PreprocessLang || {});
  20253. var PostCssDialectLang = /* @__PURE__ */ function(PostCssDialectLang) {
  20254. PostCssDialectLang["sss"] = "sugarss";
  20255. return PostCssDialectLang;
  20256. }(PostCssDialectLang || {});
  20257. const isModuleCSSRequest = (request) => cssModuleRE.test(request);
  20258. const isDirectCSSRequest = (request) => CSS_LANGS_RE.test(request) && directRequestRE.test(request);
  20259. const isDirectRequest = (request) => directRequestRE.test(request);
  20260. const cssModulesCache = /* @__PURE__ */ new WeakMap();
  20261. const removedPureCssFilesCache = /* @__PURE__ */ new WeakMap();
  20262. const cssBundleNameCache = /* @__PURE__ */ new WeakMap();
  20263. const postcssConfigCache = /* @__PURE__ */ new WeakMap();
  20264. function encodePublicUrlsInCSS(config) {
  20265. return config.command === "build";
  20266. }
  20267. const cssUrlAssetRE = /__VITE_CSS_URL__([\da-f]+)__/g;
  20268. /**
  20269. * Plugin applied before user plugins
  20270. */
  20271. function cssPlugin(config) {
  20272. const isBuild = config.command === "build";
  20273. let moduleCache;
  20274. const idResolver = createBackCompatIdResolver(config, {
  20275. preferRelative: true,
  20276. tryIndex: false,
  20277. extensions: []
  20278. });
  20279. let preprocessorWorkerController;
  20280. if (config.css.transformer !== "lightningcss") resolvePostcssConfig(config).catch(() => {});
  20281. return {
  20282. name: "vite:css",
  20283. buildStart() {
  20284. moduleCache = /* @__PURE__ */ new Map();
  20285. cssModulesCache.set(config, moduleCache);
  20286. removedPureCssFilesCache.set(config, /* @__PURE__ */ new Map());
  20287. preprocessorWorkerController = createPreprocessorWorkerController(normalizeMaxWorkers(config.css.preprocessorMaxWorkers));
  20288. preprocessorWorkerControllerCache.set(config, preprocessorWorkerController);
  20289. },
  20290. buildEnd() {
  20291. preprocessorWorkerController?.close();
  20292. },
  20293. load: {
  20294. filter: { id: CSS_LANGS_RE },
  20295. async handler(id) {
  20296. if (urlRE$1.test(id)) {
  20297. if (isModuleCSSRequest(id)) throw new Error(`?url is not supported with CSS modules. (tried to import ${JSON.stringify(id)})`);
  20298. if (isBuild) {
  20299. id = injectQuery(removeUrlQuery(id), "transform-only");
  20300. return `import ${JSON.stringify(id)};export default "__VITE_CSS_URL__${Buffer.from(id).toString("hex")}__"`;
  20301. }
  20302. }
  20303. }
  20304. },
  20305. transform: {
  20306. filter: { id: {
  20307. include: CSS_LANGS_RE,
  20308. exclude: [commonjsProxyRE, SPECIAL_QUERY_RE]
  20309. } },
  20310. async handler(raw, id) {
  20311. const { environment } = this;
  20312. const resolveUrl = (url, importer) => idResolver(environment, url, importer);
  20313. const urlResolver = async (url, importer) => {
  20314. const decodedUrl = decodeURI(url);
  20315. if (checkPublicFile(decodedUrl, config)) if (encodePublicUrlsInCSS(config)) return [publicFileToBuiltUrl(decodedUrl, config), void 0];
  20316. else return [joinUrlSegments(joinUrlSegments(config.server.origin ?? "", config.base), decodedUrl), void 0];
  20317. const [id, fragment] = decodedUrl.split("#");
  20318. let resolved = await resolveUrl(id, importer);
  20319. if (resolved) {
  20320. if (fragment) resolved += "#" + fragment;
  20321. let url = await fileToUrl$1(this, resolved);
  20322. if (!url.startsWith("data:") && this.environment.mode === "dev") {
  20323. const mod = [...this.environment.moduleGraph.getModulesByFile(resolved) ?? []].find((mod) => mod.type === "asset");
  20324. if (mod?.lastHMRTimestamp) url = injectQuery(url, `t=${mod.lastHMRTimestamp}`);
  20325. }
  20326. return [url, cleanUrl(resolved)];
  20327. }
  20328. if (config.command === "build") {
  20329. 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`);
  20330. }
  20331. return [url, void 0];
  20332. };
  20333. const { code: css, modules, deps, map } = await compileCSS(environment, id, raw, preprocessorWorkerController, urlResolver);
  20334. if (modules) moduleCache.set(id, modules);
  20335. if (deps) for (const file of deps) this.addWatchFile(file);
  20336. return {
  20337. code: css,
  20338. map
  20339. };
  20340. }
  20341. }
  20342. };
  20343. }
  20344. /**
  20345. * Plugin applied after user plugins
  20346. */
  20347. function cssPostPlugin(config) {
  20348. const styles = /* @__PURE__ */ new Map();
  20349. let codeSplitEmitQueue = createSerialPromiseQueue();
  20350. const urlEmitQueue = createSerialPromiseQueue();
  20351. let pureCssChunks;
  20352. let hasEmitted = false;
  20353. let chunkCSSMap;
  20354. const rollupOptionsOutput = config.build.rollupOptions.output;
  20355. const assetFileNames = (Array.isArray(rollupOptionsOutput) ? rollupOptionsOutput[0] : rollupOptionsOutput)?.assetFileNames;
  20356. const getCssAssetDirname = (cssAssetName, originalFileName) => {
  20357. const cssAssetNameDir = path.dirname(cssAssetName);
  20358. if (!assetFileNames) return path.join(config.build.assetsDir, cssAssetNameDir);
  20359. else if (typeof assetFileNames === "string") return path.join(path.dirname(assetFileNames), cssAssetNameDir);
  20360. else return path.dirname(assetFileNames({
  20361. type: "asset",
  20362. names: [cssAssetName],
  20363. originalFileNames: originalFileName ? [originalFileName] : [],
  20364. source: "/* vite internal call, ignore */"
  20365. }));
  20366. };
  20367. function getCssBundleName() {
  20368. const cached = cssBundleNameCache.get(config);
  20369. if (cached) return cached;
  20370. const cssBundleName = config.build.lib ? resolveLibCssFilename(config.build.lib, config.root, config.packageCache) : defaultCssBundleName;
  20371. cssBundleNameCache.set(config, cssBundleName);
  20372. return cssBundleName;
  20373. }
  20374. return {
  20375. name: "vite:css-post",
  20376. renderStart() {
  20377. pureCssChunks = /* @__PURE__ */ new Set();
  20378. hasEmitted = false;
  20379. chunkCSSMap = /* @__PURE__ */ new Map();
  20380. codeSplitEmitQueue = createSerialPromiseQueue();
  20381. },
  20382. transform: {
  20383. filter: { id: {
  20384. include: CSS_LANGS_RE,
  20385. exclude: [commonjsProxyRE, SPECIAL_QUERY_RE]
  20386. } },
  20387. async handler(css, id) {
  20388. css = stripBomTag(css);
  20389. const inlineCSS = inlineCSSRE$1.test(id);
  20390. const isHTMLProxy = htmlProxyRE$1.test(id);
  20391. if (inlineCSS && isHTMLProxy) {
  20392. if (styleAttrRE.test(id)) css = css.replace(/"/g, "&quot;");
  20393. const index = htmlProxyIndexRE.exec(id)?.[1];
  20394. if (index == null) throw new Error(`HTML proxy index in "${id}" not found`);
  20395. addToHTMLProxyTransformResult(`${getHash(cleanUrl(id))}_${Number.parseInt(index)}`, css);
  20396. return `export default ''`;
  20397. }
  20398. const inlined = inlineRE$2.test(id);
  20399. const modules = cssModulesCache.get(config).get(id);
  20400. const modulesCode = modules && !inlined && dataToEsm(modules, {
  20401. namedExports: true,
  20402. preferConst: true
  20403. });
  20404. if (config.command === "serve") {
  20405. const getContentWithSourcemap = async (content) => {
  20406. if (config.css.devSourcemap) {
  20407. const sourcemap = this.getCombinedSourcemap();
  20408. if (sourcemap.mappings) await injectSourcesContent(sourcemap, cleanUrl(id), config.logger);
  20409. return getCodeWithSourcemap("css", content, sourcemap);
  20410. }
  20411. return content;
  20412. };
  20413. if (isDirectCSSRequest(id)) return null;
  20414. if (inlined) return `export default ${JSON.stringify(css)}`;
  20415. if (this.environment.config.consumer === "server") return modulesCode || "export {}";
  20416. const cssContent = await getContentWithSourcemap(css);
  20417. return {
  20418. code: [
  20419. 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))}`,
  20420. `const __vite__id = ${JSON.stringify(id)}`,
  20421. `const __vite__css = ${JSON.stringify(cssContent)}`,
  20422. `__vite__updateStyle(__vite__id, __vite__css)`,
  20423. `${modulesCode || "import.meta.hot.accept()"}`,
  20424. `import.meta.hot.prune(() => __vite__removeStyle(__vite__id))`
  20425. ].join("\n"),
  20426. map: { mappings: "" },
  20427. moduleType: "js"
  20428. };
  20429. }
  20430. if (!inlined) styles.set(id, css);
  20431. let code;
  20432. if (modulesCode) code = modulesCode;
  20433. else if (inlined) {
  20434. let content = css;
  20435. if (config.build.cssMinify) content = await minifyCSS(content, config, true);
  20436. code = `export default ${JSON.stringify(content)}`;
  20437. } else code = "";
  20438. return {
  20439. code,
  20440. map: { mappings: "" },
  20441. moduleSideEffects: modulesCode || inlined ? false : "no-treeshake",
  20442. moduleType: "js"
  20443. };
  20444. }
  20445. },
  20446. ...config.command === "build" ? {
  20447. async renderChunk(code, chunk, opts, meta) {
  20448. let chunkCSS;
  20449. const renderedModules = new Proxy({}, { get(_target, p) {
  20450. for (const name in meta.chunks) {
  20451. const module = meta.chunks[name].modules[p];
  20452. if (module) return module;
  20453. }
  20454. } });
  20455. const isJsChunkEmpty = code === "" && !chunk.isEntry;
  20456. let isPureCssChunk = chunk.exports.length === 0;
  20457. const ids = Object.keys(chunk.modules);
  20458. for (const id of ids) if (styles.has(id)) {
  20459. if (transformOnlyRE.test(id)) continue;
  20460. const cssScopeTo = this.getModuleInfo(id)?.meta?.vite?.cssScopeTo;
  20461. if (cssScopeTo && !isCssScopeToRendered(cssScopeTo, renderedModules)) continue;
  20462. if (cssModuleRE.test(id)) isPureCssChunk = false;
  20463. chunkCSS = (chunkCSS || "") + styles.get(id);
  20464. } else if (!isJsChunkEmpty) isPureCssChunk = false;
  20465. const publicAssetUrlMap = publicAssetUrlCache.get(config);
  20466. const resolveAssetUrlsInCss = (chunkCSS, cssAssetName, originalFileName) => {
  20467. const encodedPublicUrls = encodePublicUrlsInCSS(config);
  20468. const cssAssetDirname = encodedPublicUrls || config.base === "./" || config.base === "" ? slash(getCssAssetDirname(cssAssetName, originalFileName)) : void 0;
  20469. const toRelative = (filename) => {
  20470. const relativePath = normalizePath(path.relative(cssAssetDirname, filename));
  20471. return relativePath[0] === "." ? relativePath : "./" + relativePath;
  20472. };
  20473. chunkCSS = chunkCSS.replace(assetUrlRE, (_, fileHash, postfix = "") => {
  20474. const filename = this.getFileName(fileHash) + postfix;
  20475. chunk.viteMetadata.importedAssets.add(cleanUrl(filename));
  20476. return encodeURIPath(toOutputFilePathInCss(filename, "asset", cssAssetName, "css", config, toRelative));
  20477. });
  20478. if (encodedPublicUrls) {
  20479. const relativePathToPublicFromCSS = normalizePath(path.relative(cssAssetDirname, ""));
  20480. chunkCSS = chunkCSS.replace(publicAssetUrlRE, (_, hash) => {
  20481. const publicUrl = publicAssetUrlMap.get(hash).slice(1);
  20482. return encodeURIPath(toOutputFilePathInCss(publicUrl, "public", cssAssetName, "css", config, () => `${relativePathToPublicFromCSS}/${publicUrl}`));
  20483. });
  20484. }
  20485. return chunkCSS;
  20486. };
  20487. function ensureFileExt(name, ext) {
  20488. return normalizePath(path.format({
  20489. ...path.parse(name),
  20490. base: void 0,
  20491. ext
  20492. }));
  20493. }
  20494. let s;
  20495. const urlEmitTasks = [];
  20496. if (code.includes("__VITE_CSS_URL__")) {
  20497. let match;
  20498. cssUrlAssetRE.lastIndex = 0;
  20499. while (match = cssUrlAssetRE.exec(code)) {
  20500. const [full, idHex] = match;
  20501. const id = Buffer.from(idHex, "hex").toString();
  20502. const originalFileName = cleanUrl(id);
  20503. const cssAssetName = ensureFileExt(path.basename(originalFileName), ".css");
  20504. if (!styles.has(id)) throw new Error(`css content for ${JSON.stringify(id)} was not found`);
  20505. let cssContent = styles.get(id);
  20506. cssContent = resolveAssetUrlsInCss(cssContent, cssAssetName, originalFileName);
  20507. urlEmitTasks.push({
  20508. cssAssetName,
  20509. originalFileName,
  20510. content: cssContent,
  20511. start: match.index,
  20512. end: match.index + full.length
  20513. });
  20514. }
  20515. }
  20516. await urlEmitQueue.run(async () => Promise.all(urlEmitTasks.map(async (info) => {
  20517. info.content = await finalizeCss(info.content, config);
  20518. })));
  20519. if (urlEmitTasks.length > 0) {
  20520. const toRelativeRuntime = createToImportMetaURLBasedRelativeRuntime(opts.format, config.isWorker);
  20521. s ||= new MagicString(code);
  20522. for (const { cssAssetName, originalFileName, content, start, end } of urlEmitTasks) {
  20523. const referenceId = this.emitFile({
  20524. type: "asset",
  20525. name: cssAssetName,
  20526. originalFileName,
  20527. source: content
  20528. });
  20529. const filename = this.getFileName(referenceId);
  20530. chunk.viteMetadata.importedAssets.add(cleanUrl(filename));
  20531. const replacement = toOutputFilePathInJS(this.environment, filename, "asset", chunk.fileName, "js", toRelativeRuntime);
  20532. const replacementString = typeof replacement === "string" ? JSON.stringify(encodeURIPath(replacement)).slice(1, -1) : `"+${replacement.runtime}+"`;
  20533. s.update(start, end, replacementString);
  20534. }
  20535. }
  20536. if (chunkCSS !== void 0) {
  20537. if (isPureCssChunk && (opts.format === "es" || opts.format === "cjs")) pureCssChunks.add(chunk);
  20538. if (this.environment.config.build.cssCodeSplit) {
  20539. if ((opts.format === "es" || opts.format === "cjs") && !chunk.fileName.includes("-legacy")) {
  20540. const isEntry = chunk.isEntry && isPureCssChunk;
  20541. const cssFullAssetName = ensureFileExt(chunk.name, ".css");
  20542. const cssAssetName = chunk.isEntry && (!chunk.facadeModuleId || !isCSSRequest(chunk.facadeModuleId)) ? path.basename(cssFullAssetName) : cssFullAssetName;
  20543. const originalFileName = getChunkOriginalFileName(chunk, config.root, this.environment.config.isOutputOptionsForLegacyChunks?.(opts) ?? false);
  20544. chunkCSS = resolveAssetUrlsInCss(chunkCSS, cssAssetName, originalFileName);
  20545. chunkCSS = await codeSplitEmitQueue.run(async () => {
  20546. return finalizeCss(chunkCSS, config);
  20547. });
  20548. const referenceId = this.emitFile({
  20549. type: "asset",
  20550. name: cssAssetName,
  20551. originalFileName,
  20552. source: chunkCSS
  20553. });
  20554. if (isEntry) cssEntriesMap.get(this.environment).set(chunk.name, referenceId);
  20555. chunk.viteMetadata.importedCss.add(this.getFileName(referenceId));
  20556. } else if (this.environment.config.consumer === "client") {
  20557. chunkCSS = await finalizeCss(chunkCSS, config);
  20558. let cssString = JSON.stringify(chunkCSS);
  20559. cssString = renderAssetUrlInJS(this, chunk, opts, cssString)?.toString() || cssString;
  20560. const style = `__vite_style__`;
  20561. const injectCode = `var ${style} = document.createElement('style');${style}.textContent = ${cssString};document.head.appendChild(${style});`;
  20562. s ||= new MagicString(code);
  20563. injectInlinedCSS(s, this, code, opts.format, injectCode);
  20564. }
  20565. } else {
  20566. chunkCSS = resolveAssetUrlsInCss(chunkCSS, getCssBundleName(), defaultCssBundleName);
  20567. chunkCSSMap.set(chunk.fileName, chunkCSS);
  20568. }
  20569. }
  20570. if (s) if (config.build.sourcemap) return {
  20571. code: s.toString(),
  20572. map: s.generateMap({ hires: "boundary" })
  20573. };
  20574. else return { code: s.toString() };
  20575. return null;
  20576. },
  20577. augmentChunkHash(chunk) {
  20578. if (chunk.viteMetadata?.importedCss.size) {
  20579. let hash = "";
  20580. for (const id of chunk.viteMetadata.importedCss) hash += id;
  20581. return hash;
  20582. }
  20583. }
  20584. } : {},
  20585. async generateBundle(opts, bundle) {
  20586. if (this.environment.config.isOutputOptionsForLegacyChunks?.(opts)) return;
  20587. if ((config.command !== "build" || this.environment.config.build.emitAssets) && !this.environment.config.build.cssCodeSplit && !hasEmitted) {
  20588. let extractedCss = "";
  20589. const collected = /* @__PURE__ */ new Set();
  20590. const dynamicImports = /* @__PURE__ */ new Set();
  20591. function collect(chunk) {
  20592. if (!chunk || chunk.type !== "chunk" || collected.has(chunk)) return;
  20593. collected.add(chunk);
  20594. chunk.imports.forEach((importName) => collect(bundle[importName]));
  20595. chunk.dynamicImports.forEach((importName) => dynamicImports.add(importName));
  20596. extractedCss += chunkCSSMap.get(chunk.preliminaryFileName) ?? "";
  20597. }
  20598. for (const chunk of Object.values(bundle)) if (chunk.type === "chunk" && chunk.isEntry) collect(chunk);
  20599. for (const chunkName of dynamicImports) collect(bundle[chunkName]);
  20600. if (extractedCss) {
  20601. hasEmitted = true;
  20602. extractedCss = await finalizeCss(extractedCss, config);
  20603. this.emitFile({
  20604. name: getCssBundleName(),
  20605. type: "asset",
  20606. source: extractedCss,
  20607. originalFileName: defaultCssBundleName
  20608. });
  20609. }
  20610. }
  20611. if (pureCssChunks.size) {
  20612. const prelimaryNameToChunkMap = Object.fromEntries(Object.values(bundle).filter((chunk) => chunk.type === "chunk").map((chunk) => [chunk.preliminaryFileName, chunk.fileName]));
  20613. const pureCssChunkNames = [...pureCssChunks].map((pureCssChunk) => prelimaryNameToChunkMap[pureCssChunk.fileName]).filter(Boolean);
  20614. const replaceEmptyChunk = getEmptyChunkReplacer(pureCssChunkNames, opts.format);
  20615. for (const file in bundle) {
  20616. const chunk = bundle[file];
  20617. if (chunk.type === "chunk") {
  20618. let chunkImportsPureCssChunk = false;
  20619. chunk.imports = chunk.imports.filter((file) => {
  20620. if (pureCssChunkNames.includes(file)) {
  20621. const { importedCss, importedAssets } = bundle[file].viteMetadata;
  20622. importedCss.forEach((file) => chunk.viteMetadata.importedCss.add(file));
  20623. importedAssets.forEach((file) => chunk.viteMetadata.importedAssets.add(file));
  20624. chunkImportsPureCssChunk = true;
  20625. return false;
  20626. }
  20627. return true;
  20628. });
  20629. if (chunkImportsPureCssChunk) chunk.code = replaceEmptyChunk(chunk.code);
  20630. }
  20631. }
  20632. const removedPureCssFiles = removedPureCssFilesCache.get(config);
  20633. pureCssChunkNames.forEach((fileName) => {
  20634. const emptyJsPlaceholder = bundle[fileName];
  20635. if (emptyJsPlaceholder.isEntry) {
  20636. const { importedAssets, importedCss } = emptyJsPlaceholder.viteMetadata;
  20637. const cssReferenceId = cssEntriesMap.get(this.environment).get(emptyJsPlaceholder.name);
  20638. const realCssEntryName = this.getFileName(cssReferenceId);
  20639. const realCssEntry = bundle[realCssEntryName];
  20640. importedCss.delete(realCssEntryName);
  20641. if (importedAssets.size) realCssEntry.viteMetadata.importedAssets = importedAssets;
  20642. if (importedCss.size) realCssEntry.viteMetadata.importedCss = importedCss;
  20643. }
  20644. removedPureCssFiles.set(fileName, emptyJsPlaceholder);
  20645. delete bundle[fileName];
  20646. delete bundle[`${fileName}.map`];
  20647. });
  20648. }
  20649. const cssAssets = Object.values(bundle).filter((asset) => asset.type === "asset" && asset.fileName.endsWith(".css"));
  20650. for (const cssAsset of cssAssets) if (typeof cssAsset.source === "string") cssAsset.source = cssAsset.source.replace(viteHashUpdateMarkerRE, "");
  20651. }
  20652. };
  20653. }
  20654. function injectInlinedCSS(s, ctx, code, format, injectCode) {
  20655. let injectionPoint;
  20656. if (format === "iife" || format === "umd") {
  20657. const m = (format === "iife" ? IIFE_BEGIN_RE : UMD_BEGIN_RE).exec(code);
  20658. if (!m) ctx.error("Injection point for inlined CSS not found");
  20659. injectionPoint = m.index + m[0].length;
  20660. } else if (format === "es") if (code.startsWith("#!")) {
  20661. let secondLinePos = code.indexOf("\n");
  20662. if (secondLinePos === -1) secondLinePos = 0;
  20663. injectionPoint = secondLinePos;
  20664. } else injectionPoint = 0;
  20665. else ctx.error("Non supported format");
  20666. s.appendRight(injectionPoint, injectCode);
  20667. }
  20668. function cssAnalysisPlugin(config) {
  20669. return {
  20670. name: "vite:css-analysis",
  20671. transform: {
  20672. filter: { id: {
  20673. include: CSS_LANGS_RE,
  20674. exclude: [commonjsProxyRE, SPECIAL_QUERY_RE]
  20675. } },
  20676. async handler(_, id) {
  20677. const { moduleGraph } = this.environment;
  20678. const thisModule = moduleGraph.getModuleById(id);
  20679. if (thisModule) {
  20680. const isSelfAccepting = !cssModulesCache.get(config)?.get(id) && !inlineRE$2.test(id) && !htmlProxyRE$1.test(id);
  20681. const pluginImports = this._addedImports;
  20682. if (pluginImports) {
  20683. const depModules = /* @__PURE__ */ new Set();
  20684. for (const file of pluginImports) depModules.add(moduleGraph.createFileOnlyEntry(file));
  20685. moduleGraph.updateModuleInfo(thisModule, depModules, null, /* @__PURE__ */ new Set(), null, isSelfAccepting);
  20686. } else thisModule.isSelfAccepting = isSelfAccepting;
  20687. }
  20688. }
  20689. }
  20690. };
  20691. }
  20692. function isCssScopeToRendered(cssScopeTo, renderedModules) {
  20693. const [importerId, exp] = cssScopeTo;
  20694. const importer = renderedModules[importerId];
  20695. return importer && (exp === void 0 || importer.renderedExports.includes(exp));
  20696. }
  20697. /**
  20698. * Create a replacer function that takes code and replaces given pure CSS chunk imports
  20699. * @param pureCssChunkNames The chunks that only contain pure CSS and should be replaced
  20700. * @param outputFormat The module output format to decide whether to replace `import` or `require`
  20701. */
  20702. function getEmptyChunkReplacer(pureCssChunkNames, outputFormat) {
  20703. const emptyChunkFiles = pureCssChunkNames.map((file) => escapeRegex(path.basename(file))).join("|");
  20704. const emptyChunkRE = new RegExp(outputFormat === "es" ? `\\bimport\\s*["'][^"']*(?:${emptyChunkFiles})["'];` : `(\\b|,\\s*)require\\(\\s*["'\`][^"'\`]*(?:${emptyChunkFiles})["'\`]\\)(;|,)`, "g");
  20705. return (code) => code.replace(emptyChunkRE, (m, p1, p2) => {
  20706. if (outputFormat === "es") return `/* empty css ${"".padEnd(m.length - 15)}*/`;
  20707. if (p2 === ";") return `${p2}/* empty css ${"".padEnd(m.length - 16)}*/`;
  20708. return `${p1}/* empty css ${"".padEnd(m.length - 15 - p1.length)}*/`;
  20709. });
  20710. }
  20711. const fileURLWithWindowsDriveRE = /^file:\/\/\/[a-zA-Z]:\//;
  20712. function createCSSResolvers(config) {
  20713. let cssResolve;
  20714. let sassResolve;
  20715. let lessResolve;
  20716. return {
  20717. get css() {
  20718. return cssResolve ??= createBackCompatIdResolver(config, {
  20719. extensions: [".css"],
  20720. mainFields: ["style"],
  20721. conditions: ["style", DEV_PROD_CONDITION],
  20722. tryIndex: false,
  20723. preferRelative: true
  20724. });
  20725. },
  20726. get sass() {
  20727. if (!sassResolve) {
  20728. const resolver = createBackCompatIdResolver(config, {
  20729. extensions: [
  20730. ".scss",
  20731. ".sass",
  20732. ".css"
  20733. ],
  20734. mainFields: ["sass", "style"],
  20735. conditions: [
  20736. "sass",
  20737. "style",
  20738. DEV_PROD_CONDITION
  20739. ],
  20740. tryIndex: true,
  20741. tryPrefix: "_",
  20742. preferRelative: true,
  20743. skipMainField: true
  20744. });
  20745. sassResolve = async (...args) => {
  20746. if (args[1].startsWith("file://")) args[1] = fileURLToPath(args[1], { windows: isWindows && !fileURLWithWindowsDriveRE.test(args[1]) ? false : void 0 });
  20747. return resolver(...args);
  20748. };
  20749. }
  20750. return sassResolve;
  20751. },
  20752. get less() {
  20753. return lessResolve ??= createBackCompatIdResolver(config, {
  20754. extensions: [".less", ".css"],
  20755. mainFields: ["less", "style"],
  20756. conditions: [
  20757. "less",
  20758. "style",
  20759. DEV_PROD_CONDITION
  20760. ],
  20761. tryIndex: false,
  20762. preferRelative: true
  20763. });
  20764. }
  20765. };
  20766. }
  20767. function getCssResolversKeys(resolvers) {
  20768. return Object.keys(resolvers);
  20769. }
  20770. async function compileCSSPreprocessors(environment, id, lang, code, workerController) {
  20771. const { config } = environment;
  20772. const { preprocessorOptions, devSourcemap } = config.css;
  20773. const atImportResolvers = getAtImportResolvers(environment.getTopLevelConfig());
  20774. const opts = {
  20775. ...preprocessorOptions && preprocessorOptions[lang] || {},
  20776. filename: cleanUrl(id),
  20777. enableSourcemap: devSourcemap ?? false
  20778. };
  20779. const preProcessor = workerController[lang];
  20780. const preprocessResult = await preProcessor(environment, code, config.root, opts, atImportResolvers);
  20781. if (preprocessResult.error) throw preprocessResult.error;
  20782. let deps;
  20783. if (preprocessResult.deps.length > 0) {
  20784. const normalizedFilename = normalizePath(opts.filename);
  20785. deps = new Set([...preprocessResult.deps].filter((dep) => normalizePath(dep) !== normalizedFilename));
  20786. }
  20787. return {
  20788. code: preprocessResult.code,
  20789. map: combineSourcemapsIfExists(opts.filename, preprocessResult.map, preprocessResult.additionalMap),
  20790. deps
  20791. };
  20792. }
  20793. const configToAtImportResolvers = /* @__PURE__ */ new WeakMap();
  20794. function getAtImportResolvers(config) {
  20795. let atImportResolvers = configToAtImportResolvers.get(config);
  20796. if (!atImportResolvers) {
  20797. atImportResolvers = createCSSResolvers(config);
  20798. configToAtImportResolvers.set(config, atImportResolvers);
  20799. }
  20800. return atImportResolvers;
  20801. }
  20802. async function compileCSS(environment, id, code, workerController, urlResolver) {
  20803. const { config } = environment;
  20804. const lang = CSS_LANGS_RE.exec(id)?.[1];
  20805. const deps = /* @__PURE__ */ new Set();
  20806. let preprocessorMap;
  20807. if (isPreProcessor(lang)) {
  20808. const preprocessorResult = await compileCSSPreprocessors(environment, id, lang, code, workerController);
  20809. code = preprocessorResult.code;
  20810. preprocessorMap = preprocessorResult.map;
  20811. preprocessorResult.deps?.forEach((dep) => deps.add(dep));
  20812. } else if (lang === "sss" && config.css.transformer === "lightningcss") {
  20813. const sssResult = await transformSugarSS(environment, id, code);
  20814. code = sssResult.code;
  20815. preprocessorMap = sssResult.map;
  20816. }
  20817. const transformResult = await (config.css.transformer === "lightningcss" ? compileLightningCSS(environment, id, code, deps, workerController, urlResolver) : compilePostCSS(environment, id, code, deps, lang, workerController, urlResolver));
  20818. if (!transformResult) return {
  20819. code,
  20820. map: config.css.devSourcemap ? preprocessorMap : { mappings: "" },
  20821. deps
  20822. };
  20823. return {
  20824. ...transformResult,
  20825. map: config.css.devSourcemap ? combineSourcemapsIfExists(cleanUrl(id), typeof transformResult.map === "string" ? JSON.parse(transformResult.map) : transformResult.map, preprocessorMap) : { mappings: "" },
  20826. deps
  20827. };
  20828. }
  20829. async function compilePostCSS(environment, id, code, deps, lang, workerController, urlResolver) {
  20830. const { config } = environment;
  20831. const { modules: modulesOptions, devSourcemap } = config.css;
  20832. const isModule = modulesOptions !== false && cssModuleRE.test(id);
  20833. const needInlineImport = code.includes("@import");
  20834. const hasUrl = cssUrlRE.test(code) || cssImageSetRE.test(code);
  20835. const postcssConfig = await resolvePostcssConfig(environment.getTopLevelConfig());
  20836. if (lang !== "sss" && !postcssConfig && !isModule && !needInlineImport && !hasUrl) return;
  20837. const atImportResolvers = getAtImportResolvers(environment.getTopLevelConfig());
  20838. const postcssPlugins = postcssConfig?.plugins.slice() ?? [];
  20839. if (needInlineImport) postcssPlugins.unshift((await importPostcssImport()).default({
  20840. async resolve(id, basedir) {
  20841. const publicFile = checkPublicFile(id, environment.getTopLevelConfig());
  20842. if (publicFile) return publicFile;
  20843. const resolved = await atImportResolvers.css(environment, id, path.join(basedir, "*"));
  20844. if (resolved) return path.resolve(resolved);
  20845. if (!path.isAbsolute(id)) environment.logger.error(import_picocolors.default.red(`Unable to resolve \`@import "${id}"\` from ${basedir}`));
  20846. return id;
  20847. },
  20848. async load(id) {
  20849. const code = await fs.promises.readFile(id, "utf-8");
  20850. const lang = CSS_LANGS_RE.exec(id)?.[1];
  20851. if (isPreProcessor(lang)) {
  20852. const result = await compileCSSPreprocessors(environment, id, lang, code, workerController);
  20853. result.deps?.forEach((dep) => deps.add(dep));
  20854. return result.code;
  20855. }
  20856. return code;
  20857. },
  20858. nameLayer(index) {
  20859. return `vite--anon-layer-${getHash(id)}-${index}`;
  20860. }
  20861. }));
  20862. if (urlResolver && (postcssPlugins.length > 0 || isModule || hasUrl)) postcssPlugins.push(UrlRewritePostcssPlugin({
  20863. resolver: urlResolver,
  20864. deps,
  20865. logger: environment.logger
  20866. }));
  20867. let modules;
  20868. if (isModule) postcssPlugins.unshift((await importPostcssModules()).default({
  20869. ...modulesOptions,
  20870. localsConvention: modulesOptions?.localsConvention,
  20871. getJSON(cssFileName, _modules, outputFileName) {
  20872. modules = _modules;
  20873. if (modulesOptions && typeof modulesOptions.getJSON === "function") modulesOptions.getJSON(cssFileName, _modules, outputFileName);
  20874. },
  20875. async resolve(id, importer) {
  20876. for (const key of getCssResolversKeys(atImportResolvers)) {
  20877. const resolved = await atImportResolvers[key](environment, id, importer);
  20878. if (resolved) return path.resolve(resolved);
  20879. }
  20880. return id;
  20881. }
  20882. }));
  20883. const postcssOptions = postcssConfig?.options ?? {};
  20884. const postcssParser = lang === "sss" ? await loadSss(config.root) : postcssOptions.parser;
  20885. if (!postcssPlugins.length && !postcssParser) return;
  20886. return {
  20887. ...await runPostCSS(id, code, postcssPlugins, {
  20888. ...postcssOptions,
  20889. parser: postcssParser
  20890. }, deps, environment.logger, devSourcemap),
  20891. modules
  20892. };
  20893. }
  20894. async function transformSugarSS(environment, id, code) {
  20895. const { config } = environment;
  20896. const { devSourcemap } = config.css;
  20897. return await runPostCSS(id, code, [], { parser: await loadSss(config.root) }, void 0, environment.logger, devSourcemap);
  20898. }
  20899. async function runPostCSS(id, code, plugins, options, deps, logger, enableSourcemap) {
  20900. let postcssResult;
  20901. try {
  20902. const source = removeDirectQuery(id);
  20903. postcssResult = await (await importPostcss()).default(plugins).process(code, {
  20904. ...options,
  20905. to: source,
  20906. from: source,
  20907. ...enableSourcemap ? { map: {
  20908. inline: false,
  20909. annotation: false,
  20910. sourcesContent: true
  20911. } } : {}
  20912. });
  20913. for (const message of postcssResult.messages) if (message.type === "dependency") deps?.add(normalizePath(message.file));
  20914. else if (message.type === "dir-dependency") {
  20915. const { dir, glob: globPattern = "**" } = message;
  20916. const files = globSync(globPattern, {
  20917. absolute: true,
  20918. cwd: path.resolve(path.dirname(id), dir),
  20919. expandDirectories: false,
  20920. ignore: ["**/node_modules/**"]
  20921. });
  20922. for (let i = 0; i < files.length; i++) deps?.add(files[i]);
  20923. } else if (message.type === "warning") {
  20924. const warning = message;
  20925. let msg = `[vite:css][postcss] ${warning.text}`;
  20926. msg += `\n${generateCodeFrame(code, {
  20927. line: warning.line,
  20928. column: warning.column - 1
  20929. }, warning.endLine !== void 0 && warning.endColumn !== void 0 ? {
  20930. line: warning.endLine,
  20931. column: warning.endColumn - 1
  20932. } : void 0)}`;
  20933. logger.warn(import_picocolors.default.yellow(msg));
  20934. }
  20935. } catch (e) {
  20936. e.message = `[postcss] ${e.message}`;
  20937. e.code = code;
  20938. e.loc = {
  20939. file: e.file,
  20940. line: e.line,
  20941. column: e.column - 1
  20942. };
  20943. throw e;
  20944. }
  20945. if (!enableSourcemap) return {
  20946. code: postcssResult.css,
  20947. map: { mappings: "" }
  20948. };
  20949. const postcssMap = await formatPostcssSourceMap(postcssResult.map.toJSON(), cleanUrl(id));
  20950. return {
  20951. code: postcssResult.css,
  20952. map: postcssMap
  20953. };
  20954. }
  20955. function createCachedImport(imp) {
  20956. let cached;
  20957. return () => {
  20958. if (!cached) cached = imp().then((module) => {
  20959. cached = module;
  20960. return module;
  20961. });
  20962. return cached;
  20963. };
  20964. }
  20965. const importPostcssImport = createCachedImport(() => import("./postcss-import.js").then((m) => /* @__PURE__ */ __toESM(m.default, 1)));
  20966. const importPostcssModules = createCachedImport(() => import("./build2.js").then((m) => /* @__PURE__ */ __toESM(m.default, 1)));
  20967. const importPostcss = createCachedImport(() => import("postcss"));
  20968. const preprocessorWorkerControllerCache = /* @__PURE__ */ new WeakMap();
  20969. let alwaysFakeWorkerWorkerControllerCache;
  20970. /**
  20971. * @experimental
  20972. */
  20973. async function preprocessCSS(code, filename, config) {
  20974. let workerController = preprocessorWorkerControllerCache.get(config);
  20975. if (!workerController) {
  20976. alwaysFakeWorkerWorkerControllerCache ||= createPreprocessorWorkerController(0);
  20977. workerController = alwaysFakeWorkerWorkerControllerCache;
  20978. }
  20979. return await compileCSS(new PartialEnvironment("client", config), filename, code, workerController);
  20980. }
  20981. async function formatPostcssSourceMap(rawMap, file) {
  20982. const inputFileDir = path.dirname(file);
  20983. const sources = rawMap.sources.map((source) => {
  20984. const cleanSource = cleanUrl(decodeURIComponent(source));
  20985. if (cleanSource[0] === "<" && cleanSource.endsWith(">")) return `\0${cleanSource}`;
  20986. return normalizePath(path.resolve(inputFileDir, cleanSource));
  20987. });
  20988. return {
  20989. file,
  20990. mappings: rawMap.mappings,
  20991. names: rawMap.names,
  20992. sources,
  20993. sourcesContent: rawMap.sourcesContent,
  20994. version: rawMap.version
  20995. };
  20996. }
  20997. function combineSourcemapsIfExists(filename, map1, map2) {
  20998. if (!map1 || !map2) return map1;
  20999. if (map1.mappings === "" || map2.mappings === "") return { mappings: "" };
  21000. return combineSourcemaps(filename, [map1, map2]);
  21001. }
  21002. const viteHashUpdateMarker = "/*$vite$:1*/";
  21003. const viteHashUpdateMarkerRE = /\/\*\$vite\$:\d+\*\//;
  21004. async function finalizeCss(css, config) {
  21005. if (css.includes("@import") || css.includes("@charset")) css = await hoistAtRules(css);
  21006. if (config.build.cssMinify) css = await minifyCSS(css, config, false);
  21007. css += viteHashUpdateMarker;
  21008. return css;
  21009. }
  21010. async function resolvePostcssConfig(config) {
  21011. let result = postcssConfigCache.get(config);
  21012. if (result !== void 0) return await result;
  21013. const inlineOptions = config.css.postcss;
  21014. if (isObject$1(inlineOptions)) {
  21015. const options = { ...inlineOptions };
  21016. delete options.plugins;
  21017. result = {
  21018. options,
  21019. plugins: inlineOptions.plugins || []
  21020. };
  21021. } else {
  21022. const searchPath = typeof inlineOptions === "string" ? inlineOptions : config.root;
  21023. result = (0, import_src.default)({}, searchPath, { stopDir: searchForWorkspaceRoot(config.root) }).catch((e) => {
  21024. if (!e.message.includes("No PostCSS Config found")) if (e instanceof Error) {
  21025. const { name, message, stack } = e;
  21026. e.name = "Failed to load PostCSS config";
  21027. e.message = `Failed to load PostCSS config (searchPath: ${searchPath}): [${name}] ${message}\n${stack}`;
  21028. e.stack = "";
  21029. throw e;
  21030. } else throw new Error(`Failed to load PostCSS config: ${e}`);
  21031. return null;
  21032. });
  21033. result.then((resolved) => {
  21034. postcssConfigCache.set(config, resolved);
  21035. }, () => {});
  21036. }
  21037. postcssConfigCache.set(config, result);
  21038. return result;
  21039. }
  21040. const cssUrlRE = /(?<!@import\s+)(?<=^|[^\w\-\u0080-\uffff])url\((\s*('[^']+'|"[^"]+")\s*|(?:\\.|[^'")\\])+)\)/;
  21041. const cssDataUriRE = /(?<=^|[^\w\-\u0080-\uffff])data-uri\((\s*('[^']+'|"[^"]+")\s*|[^'")]+)\)/;
  21042. const importCssRE = /@import\s+(?:url\()?('[^']+\.css'|"[^"]+\.css"|[^'"\s)]+\.css)/;
  21043. const cssImageSetRE = /(?<=image-set\()((?:[\w-]{1,256}\([^)]*\)|[^)])*)(?=\))/;
  21044. const UrlRewritePostcssPlugin = (opts) => {
  21045. if (!opts) throw new Error("base or replace is required");
  21046. return {
  21047. postcssPlugin: "vite-url-rewrite",
  21048. Once(root) {
  21049. const promises = [];
  21050. root.walkDecls((declaration) => {
  21051. const importer = declaration.source?.input.file;
  21052. 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.");
  21053. const isCssUrl = cssUrlRE.test(declaration.value);
  21054. const isCssImageSet = cssImageSetRE.test(declaration.value);
  21055. if (isCssUrl || isCssImageSet) {
  21056. const replacerForDeclaration = async (rawUrl) => {
  21057. const [newUrl, resolvedId] = await opts.resolver(rawUrl, importer);
  21058. if (resolvedId) opts.deps.add(resolvedId);
  21059. return newUrl;
  21060. };
  21061. if (isCssUrl && isCssImageSet) promises.push(rewriteCssUrls(declaration.value, replacerForDeclaration).then((url) => rewriteCssImageSet(url, replacerForDeclaration)).then((url) => {
  21062. declaration.value = url;
  21063. }));
  21064. else promises.push((isCssImageSet ? rewriteCssImageSet : rewriteCssUrls)(declaration.value, replacerForDeclaration).then((url) => {
  21065. declaration.value = url;
  21066. }));
  21067. }
  21068. });
  21069. if (promises.length) return Promise.all(promises);
  21070. }
  21071. };
  21072. };
  21073. UrlRewritePostcssPlugin.postcss = true;
  21074. function rewriteCssUrls(css, replacer) {
  21075. return asyncReplace(css, cssUrlRE, async (match) => {
  21076. const [matched, rawUrl] = match;
  21077. return await doUrlReplace(rawUrl.trim(), matched, replacer);
  21078. });
  21079. }
  21080. function rewriteCssDataUris(css, replacer) {
  21081. return asyncReplace(css, cssDataUriRE, async (match) => {
  21082. const [matched, rawUrl] = match;
  21083. return await doUrlReplace(rawUrl.trim(), matched, replacer, "data-uri");
  21084. });
  21085. }
  21086. function rewriteImportCss(css, replacer) {
  21087. return asyncReplace(css, importCssRE, async (match) => {
  21088. const [matched, rawUrl] = match;
  21089. return await doImportCSSReplace(rawUrl, matched, replacer);
  21090. });
  21091. }
  21092. const cssNotProcessedRE = /(?:gradient|element|cross-fade|image)\(/;
  21093. async function rewriteCssImageSet(css, replacer) {
  21094. return await asyncReplace(css, cssImageSetRE, async (match) => {
  21095. const [, rawUrl] = match;
  21096. return await processSrcSet(rawUrl, async ({ url }) => {
  21097. if (cssUrlRE.test(url)) return await rewriteCssUrls(url, replacer);
  21098. if (!cssNotProcessedRE.test(url)) return await doUrlReplace(url, url, replacer);
  21099. return url;
  21100. });
  21101. });
  21102. }
  21103. function skipUrlReplacer(unquotedUrl) {
  21104. return isExternalUrl(unquotedUrl) || isDataUrl(unquotedUrl) || unquotedUrl[0] === "#" || functionCallRE.test(unquotedUrl) || unquotedUrl.startsWith("__VITE_ASSET__") || unquotedUrl.startsWith("__VITE_PUBLIC_ASSET__");
  21105. }
  21106. async function doUrlReplace(rawUrl, matched, replacer, funcName = "url") {
  21107. let wrap = "";
  21108. const first = rawUrl[0];
  21109. let unquotedUrl = rawUrl;
  21110. if (first === `"` || first === `'`) {
  21111. wrap = first;
  21112. unquotedUrl = rawUrl.slice(1, -1);
  21113. }
  21114. if (skipUrlReplacer(unquotedUrl)) return matched;
  21115. unquotedUrl = unquotedUrl.replace(/\\(\W)/g, "$1");
  21116. let newUrl = await replacer(unquotedUrl, rawUrl);
  21117. if (newUrl === false) return matched;
  21118. if (wrap === "" && (newUrl !== encodeURI(newUrl) || newUrl.includes(")"))) wrap = "\"";
  21119. if (wrap === "'" && newUrl.includes("'")) wrap = "\"";
  21120. if (wrap === "\"" && newUrl.includes("\"")) newUrl = newUrl.replace(nonEscapedDoubleQuoteRe, "\\\"");
  21121. return `${funcName}(${wrap}${newUrl}${wrap})`;
  21122. }
  21123. async function doImportCSSReplace(rawUrl, matched, replacer) {
  21124. let wrap = "";
  21125. const first = rawUrl[0];
  21126. let unquotedUrl = rawUrl;
  21127. if (first === `"` || first === `'`) {
  21128. wrap = first;
  21129. unquotedUrl = rawUrl.slice(1, -1);
  21130. }
  21131. if (skipUrlReplacer(unquotedUrl)) return matched;
  21132. const newUrl = await replacer(unquotedUrl, rawUrl);
  21133. if (newUrl === false) return matched;
  21134. return `@import ${matched.includes("url(") ? "url(" : ""}${wrap}${newUrl}${wrap}`;
  21135. }
  21136. async function minifyCSS(css, config, inlined) {
  21137. if (config.build.cssMinify === "esbuild") {
  21138. const { transform, formatMessages } = await importEsbuild();
  21139. try {
  21140. const { code, warnings } = await transform(css, {
  21141. loader: "css",
  21142. target: config.build.cssTarget || void 0,
  21143. ...resolveMinifyCssEsbuildOptions(config.esbuild || {})
  21144. });
  21145. if (warnings.length) {
  21146. const msgs = await formatMessages(warnings, { kind: "warning" });
  21147. config.logger.warn(import_picocolors.default.yellow(`[esbuild css minify]\n${msgs.join("\n")}`));
  21148. }
  21149. return inlined ? code.trimEnd() : code;
  21150. } catch (e) {
  21151. if (e.errors) {
  21152. e.message = "[esbuild css minify] " + e.message;
  21153. e.frame = "\n" + (await formatMessages(e.errors, { kind: "error" })).join("\n");
  21154. e.loc = e.errors[0].location;
  21155. }
  21156. throw e;
  21157. }
  21158. }
  21159. try {
  21160. const { code, warnings } = (await importLightningCSS()).transform({
  21161. ...config.css.lightningcss,
  21162. targets: convertTargets(config.build.cssTarget),
  21163. cssModules: void 0,
  21164. filename: defaultCssBundleName,
  21165. code: Buffer.from(css),
  21166. minify: true
  21167. });
  21168. for (const warning of warnings) {
  21169. let msg = `[lightningcss minify] ${warning.message}`;
  21170. msg += `\n${generateCodeFrame(css, {
  21171. line: warning.loc.line,
  21172. column: warning.loc.column - 1
  21173. })}`;
  21174. config.logger.warn(import_picocolors.default.yellow(msg));
  21175. }
  21176. return decoder.decode(code) + (inlined ? "" : "\n");
  21177. } catch (e) {
  21178. e.message = `[lightningcss minify] ${e.message}`;
  21179. const friendlyMessage = getLightningCssErrorMessageForIeSyntaxes(css);
  21180. if (friendlyMessage) e.message += friendlyMessage;
  21181. if (e.loc) {
  21182. e.loc = {
  21183. line: e.loc.line,
  21184. column: e.loc.column - 1
  21185. };
  21186. e.frame = generateCodeFrame(css, e.loc);
  21187. }
  21188. throw e;
  21189. }
  21190. }
  21191. function resolveMinifyCssEsbuildOptions(options) {
  21192. const base = {
  21193. charset: options.charset,
  21194. logLevel: options.logLevel,
  21195. logLimit: options.logLimit,
  21196. logOverride: options.logOverride,
  21197. legalComments: options.legalComments
  21198. };
  21199. if (options.minifyIdentifiers != null || options.minifySyntax != null || options.minifyWhitespace != null) return {
  21200. ...base,
  21201. minifyIdentifiers: options.minifyIdentifiers ?? true,
  21202. minifySyntax: options.minifySyntax ?? true,
  21203. minifyWhitespace: options.minifyWhitespace ?? true
  21204. };
  21205. else return {
  21206. ...base,
  21207. minify: true
  21208. };
  21209. }
  21210. const atImportRE = /@import(?:\s*(?:url\([^)]*\)|"(?:[^"]|(?<=\\)")*"|'(?:[^']|(?<=\\)')*').*?|[^;]*);/g;
  21211. const atCharsetRE = /@charset(?:\s*(?:"(?:[^"]|(?<=\\)")*"|'(?:[^']|(?<=\\)')*').*?|[^;]*);/g;
  21212. async function hoistAtRules(css) {
  21213. const s = new MagicString(css);
  21214. const cleanCss = emptyCssComments(css);
  21215. let match;
  21216. atImportRE.lastIndex = 0;
  21217. while (match = atImportRE.exec(cleanCss)) {
  21218. s.remove(match.index, match.index + match[0].length);
  21219. s.appendLeft(0, match[0]);
  21220. }
  21221. atCharsetRE.lastIndex = 0;
  21222. let foundCharset = false;
  21223. while (match = atCharsetRE.exec(cleanCss)) {
  21224. s.remove(match.index, match.index + match[0].length);
  21225. if (!foundCharset) {
  21226. s.prepend(match[0]);
  21227. foundCharset = true;
  21228. }
  21229. }
  21230. return s.toString();
  21231. }
  21232. const loadedPreprocessorPath = {};
  21233. function loadPreprocessorPath(lang, root) {
  21234. const cached = loadedPreprocessorPath[lang];
  21235. if (cached) return cached;
  21236. const resolved = nodeResolveWithVite(lang, void 0, { root }) ?? nodeResolveWithVite(lang, _dirname, { root });
  21237. if (resolved) return loadedPreprocessorPath[lang] = resolved;
  21238. const installCommand = getPackageManagerCommand("install");
  21239. throw new Error(`Preprocessor dependency "${lang}" not found. Did you install it? Try \`${installCommand} -D ${lang}\`.`);
  21240. }
  21241. function loadSassPackage(root, skipEmbedded = false) {
  21242. if (!skipEmbedded) try {
  21243. return {
  21244. name: "sass-embedded",
  21245. path: loadPreprocessorPath("sass-embedded", root)
  21246. };
  21247. } catch (e1) {
  21248. try {
  21249. return {
  21250. name: "sass",
  21251. path: loadPreprocessorPath(PreprocessLang.sass, root)
  21252. };
  21253. } catch {
  21254. throw e1;
  21255. }
  21256. }
  21257. return {
  21258. name: "sass",
  21259. path: loadPreprocessorPath(PreprocessLang.sass, root)
  21260. };
  21261. }
  21262. let cachedSss;
  21263. async function loadSss(root) {
  21264. if (!cachedSss) cachedSss = (async () => {
  21265. return cachedSss = (await import(pathToFileURL(loadPreprocessorPath(PostCssDialectLang.sss, root)).href)).default;
  21266. })();
  21267. return cachedSss;
  21268. }
  21269. function cleanScssBugUrl(url) {
  21270. if (typeof window !== "undefined" && typeof location !== "undefined" && typeof location.href === "string") {
  21271. const prefix = location.href.replace(/\/$/, "");
  21272. return url.replace(prefix, "");
  21273. } else return url;
  21274. }
  21275. const makeScssWorker = (environment, resolvers, _maxWorkers) => {
  21276. let compilerPromise;
  21277. return {
  21278. async run(sassPath, data, options) {
  21279. const sass = await import(sassPath);
  21280. compilerPromise ??= sass.initAsyncCompiler();
  21281. const compiler = await compilerPromise;
  21282. const sassOptions = { ...options };
  21283. sassOptions.url = pathToFileURL(options.filename);
  21284. sassOptions.sourceMap = options.enableSourcemap;
  21285. const skipRebaseUrls = (unquotedUrl, rawUrl) => {
  21286. if (!(rawUrl[0] === "\"" || rawUrl[0] === "'") && unquotedUrl[0] === "$") return true;
  21287. return unquotedUrl.startsWith("#{");
  21288. };
  21289. const internalImporter = {
  21290. async canonicalize(url, context) {
  21291. const importer = context.containingUrl ? fileURLToPath(context.containingUrl) : options.filename;
  21292. const resolved = await resolvers.sass(environment, url, cleanScssBugUrl(importer));
  21293. if (resolved && (resolved.endsWith(".css") || resolved.endsWith(".scss") || resolved.endsWith(".sass"))) return pathToFileURL(resolved);
  21294. return null;
  21295. },
  21296. async load(canonicalUrl) {
  21297. const ext = path.extname(canonicalUrl.pathname);
  21298. let syntax = "scss";
  21299. if (ext === ".sass") syntax = "indented";
  21300. else if (ext === ".css") syntax = "css";
  21301. const result = await rebaseUrls(environment, fileURLToPath(canonicalUrl), options.filename, resolvers.sass, skipRebaseUrls);
  21302. return {
  21303. contents: result.contents ?? await fsp.readFile(result.file, "utf-8"),
  21304. syntax,
  21305. sourceMapUrl: canonicalUrl
  21306. };
  21307. }
  21308. };
  21309. sassOptions.importers = [...sassOptions.importers ?? [], internalImporter];
  21310. sassOptions.importer ??= internalImporter;
  21311. const result = await compiler.compileStringAsync(data, sassOptions);
  21312. return {
  21313. css: result.css,
  21314. map: result.sourceMap ? JSON.stringify(result.sourceMap) : void 0,
  21315. stats: { includedFiles: result.loadedUrls.filter((url) => url.protocol === "file:").map((url) => fileURLToPath(url)) }
  21316. };
  21317. },
  21318. async stop() {
  21319. await (await compilerPromise)?.dispose();
  21320. compilerPromise = void 0;
  21321. }
  21322. };
  21323. };
  21324. const scssProcessor = (maxWorkers) => {
  21325. let worker;
  21326. let failedSassEmbedded;
  21327. return {
  21328. close() {
  21329. worker?.stop();
  21330. },
  21331. async process(environment, source, root, options, resolvers) {
  21332. let sassPackage = loadSassPackage(root, failedSassEmbedded ?? false);
  21333. if (failedSassEmbedded === void 0) {
  21334. failedSassEmbedded = false;
  21335. try {
  21336. await import(sassPackage.path);
  21337. } catch (e) {
  21338. if (/sass-embedded-[a-z0-9]+-[a-z0-9]+/i.test(e.message)) {
  21339. failedSassEmbedded = true;
  21340. sassPackage = loadSassPackage(root, failedSassEmbedded);
  21341. }
  21342. }
  21343. }
  21344. worker ??= makeScssWorker(environment, resolvers, maxWorkers);
  21345. const { content: data, map: additionalMap } = await getSource(source, options.filename, options.additionalData, options.enableSourcemap);
  21346. const optionsWithoutAdditionalData = {
  21347. ...options,
  21348. additionalData: void 0
  21349. };
  21350. try {
  21351. const result = await worker.run(pathToFileURL(sassPackage.path).href, data, optionsWithoutAdditionalData);
  21352. const deps = result.stats.includedFiles.map((f) => cleanScssBugUrl(f));
  21353. const map = result.map ? JSON.parse(result.map.toString()) : void 0;
  21354. if (map) map.sources = map.sources.map((url) => url.startsWith("file://") ? normalizePath(fileURLToPath(url)) : url);
  21355. return {
  21356. code: result.css.toString(),
  21357. map,
  21358. additionalMap,
  21359. deps
  21360. };
  21361. } catch (e) {
  21362. e.message = `[sass] ${e.message}`;
  21363. e.id = e.file;
  21364. e.frame = e.formatted;
  21365. if (e.span?.start) {
  21366. e.line = e.span.start.line + 1;
  21367. e.column = e.span.start.column + 1;
  21368. e.frame = e.message;
  21369. }
  21370. return {
  21371. code: "",
  21372. error: e,
  21373. deps: []
  21374. };
  21375. }
  21376. }
  21377. };
  21378. };
  21379. /**
  21380. * relative url() inside \@imported sass and less files must be rebased to use
  21381. * root file as base.
  21382. */
  21383. async function rebaseUrls(environment, file, rootFile, resolver, ignoreUrl) {
  21384. file = path.resolve(file);
  21385. const fileDir = path.dirname(file);
  21386. const rootDir = path.dirname(rootFile);
  21387. if (fileDir === rootDir) return { file };
  21388. const content = await fsp.readFile(file, "utf-8");
  21389. const hasUrls = cssUrlRE.test(content);
  21390. const hasDataUris = cssDataUriRE.test(content);
  21391. const hasImportCss = importCssRE.test(content);
  21392. if (!hasUrls && !hasDataUris && !hasImportCss) return { file };
  21393. let rebased;
  21394. const rebaseFn = async (unquotedUrl, rawUrl) => {
  21395. if (ignoreUrl?.(unquotedUrl, rawUrl)) return false;
  21396. if (unquotedUrl[0] === "/") return unquotedUrl;
  21397. const absolute = await resolver(environment, unquotedUrl, file) || path.resolve(fileDir, unquotedUrl);
  21398. return normalizePath(path.relative(rootDir, absolute));
  21399. };
  21400. if (hasImportCss) rebased = await rewriteImportCss(content, rebaseFn);
  21401. if (hasUrls) rebased = await rewriteCssUrls(rebased || content, rebaseFn);
  21402. if (hasDataUris) rebased = await rewriteCssDataUris(rebased || content, rebaseFn);
  21403. return {
  21404. file,
  21405. contents: rebased
  21406. };
  21407. }
  21408. const makeLessWorker = (environment, resolvers, maxWorkers) => {
  21409. const skipRebaseUrls = (unquotedUrl, _rawUrl) => {
  21410. return unquotedUrl[0] === "@";
  21411. };
  21412. const viteLessResolve = async (filename, dir, rootFile, mime) => {
  21413. const resolved = await resolvers.less(environment, filename, path.join(dir, "*"));
  21414. if (!resolved) return void 0;
  21415. if (mime === "application/javascript") return { resolved: path.resolve(resolved) };
  21416. const result = await rebaseUrls(environment, resolved, rootFile, resolvers.less, skipRebaseUrls);
  21417. return {
  21418. resolved,
  21419. contents: "contents" in result ? result.contents : void 0
  21420. };
  21421. };
  21422. return new WorkerWithFallback(async () => {
  21423. const [fsp, path] = await Promise.all([import("node:fs/promises"), import("node:path")]);
  21424. let ViteLessManager;
  21425. const createViteLessPlugin = (less, rootFile) => {
  21426. const { FileManager } = less;
  21427. ViteLessManager ??= class ViteManager extends FileManager {
  21428. rootFile;
  21429. constructor(rootFile) {
  21430. super();
  21431. this.rootFile = rootFile;
  21432. }
  21433. supports(filename) {
  21434. return !/^(?:https?:)?\/\//.test(filename);
  21435. }
  21436. supportsSync() {
  21437. return false;
  21438. }
  21439. async loadFile(filename, dir, opts, env) {
  21440. const result = await viteLessResolve(filename, dir, this.rootFile, opts.mime);
  21441. if (result) return {
  21442. filename: path.resolve(result.resolved),
  21443. contents: result.contents ?? await fsp.readFile(result.resolved, "utf-8")
  21444. };
  21445. else return super.loadFile(filename, dir, opts, env);
  21446. }
  21447. };
  21448. return {
  21449. install(_, pluginManager) {
  21450. pluginManager.addFileManager(new ViteLessManager(rootFile));
  21451. },
  21452. minVersion: [
  21453. 3,
  21454. 0,
  21455. 0
  21456. ]
  21457. };
  21458. };
  21459. return async (lessPath, content, options) => {
  21460. const nodeLess = (await import(lessPath)).default;
  21461. const viteResolverPlugin = createViteLessPlugin(nodeLess, options.filename);
  21462. return await nodeLess.render(content, {
  21463. paths: ["node_modules"],
  21464. ...options,
  21465. plugins: [viteResolverPlugin, ...options.plugins || []],
  21466. ...options.enableSourcemap ? { sourceMap: {
  21467. outputSourceFiles: true,
  21468. disableSourcemapAnnotation: true,
  21469. sourceMapFileInline: false
  21470. } } : {}
  21471. });
  21472. };
  21473. }, {
  21474. parentFunctions: { viteLessResolve },
  21475. shouldUseFake(_lessPath, _content, options) {
  21476. return !!options.plugins && options.plugins.length > 0;
  21477. },
  21478. max: maxWorkers
  21479. });
  21480. };
  21481. const lessProcessor = (maxWorkers) => {
  21482. let worker;
  21483. return {
  21484. close() {
  21485. worker?.stop();
  21486. },
  21487. async process(environment, source, root, options, resolvers) {
  21488. const lessPath = loadPreprocessorPath(PreprocessLang.less, root);
  21489. worker ??= makeLessWorker(environment, resolvers, maxWorkers);
  21490. const { content, map: additionalMap } = await getSource(source, options.filename, options.additionalData, options.enableSourcemap);
  21491. let result;
  21492. const optionsWithoutAdditionalData = {
  21493. ...options,
  21494. additionalData: void 0
  21495. };
  21496. try {
  21497. result = await worker.run(pathToFileURL(lessPath).href, content, optionsWithoutAdditionalData);
  21498. } catch (e) {
  21499. const error = e;
  21500. const normalizedError = /* @__PURE__ */ new Error(`[less] ${error.message || error.type}`);
  21501. normalizedError.loc = {
  21502. file: error.filename || options.filename,
  21503. line: error.line,
  21504. column: error.column
  21505. };
  21506. return {
  21507. code: "",
  21508. error: normalizedError,
  21509. deps: []
  21510. };
  21511. }
  21512. const map = result.map && JSON.parse(result.map);
  21513. if (map) delete map.sourcesContent;
  21514. return {
  21515. code: result.css.toString(),
  21516. map,
  21517. additionalMap,
  21518. deps: result.imports
  21519. };
  21520. }
  21521. };
  21522. };
  21523. const makeStylWorker = (maxWorkers) => {
  21524. return new WorkerWithFallback(() => {
  21525. return async (stylusPath, content, root, options) => {
  21526. const stylus = (await import(stylusPath)).default;
  21527. const ref = stylus(content, {
  21528. paths: ["node_modules"],
  21529. ...options
  21530. });
  21531. if (options.define) for (const key in options.define) ref.define(key, options.define[key]);
  21532. if (options.enableSourcemap) ref.set("sourcemap", {
  21533. comment: false,
  21534. inline: false,
  21535. basePath: root
  21536. });
  21537. return {
  21538. code: ref.render(),
  21539. map: ref.sourcemap,
  21540. deps: ref.deps()
  21541. };
  21542. };
  21543. }, {
  21544. shouldUseFake(_stylusPath, _content, _root, options) {
  21545. return !!(options.define && Object.values(options.define).some((d) => typeof d === "function") || options.Evaluator);
  21546. },
  21547. max: maxWorkers
  21548. });
  21549. };
  21550. const stylProcessor = (maxWorkers) => {
  21551. let worker;
  21552. return {
  21553. close() {
  21554. worker?.stop();
  21555. },
  21556. async process(_environment, source, root, options, _resolvers) {
  21557. const stylusPath = loadPreprocessorPath(PreprocessLang.stylus, root);
  21558. worker ??= makeStylWorker(maxWorkers);
  21559. const { content, map: additionalMap } = await getSource(source, options.filename, options.additionalData, options.enableSourcemap, "\n");
  21560. const importsDeps = (options.imports ?? []).map((dep) => path.resolve(dep));
  21561. const optionsWithoutAdditionalData = {
  21562. ...options,
  21563. additionalData: void 0
  21564. };
  21565. try {
  21566. const { code, map, deps } = await worker.run(pathToFileURL(stylusPath).href, content, root, optionsWithoutAdditionalData);
  21567. return {
  21568. code,
  21569. map: formatStylusSourceMap(map, root),
  21570. additionalMap,
  21571. deps: [...deps, ...importsDeps]
  21572. };
  21573. } catch (e) {
  21574. const wrapped = /* @__PURE__ */ new Error(`[stylus] ${e.message}`);
  21575. wrapped.name = e.name;
  21576. wrapped.stack = e.stack;
  21577. return {
  21578. code: "",
  21579. error: wrapped,
  21580. deps: []
  21581. };
  21582. }
  21583. }
  21584. };
  21585. };
  21586. function formatStylusSourceMap(mapBefore, root) {
  21587. if (!mapBefore) return void 0;
  21588. const map = { ...mapBefore };
  21589. const resolveFromRoot = (p) => normalizePath(path.resolve(root, p));
  21590. if (map.file) map.file = resolveFromRoot(map.file);
  21591. map.sources = map.sources.map(resolveFromRoot);
  21592. return map;
  21593. }
  21594. async function getSource(source, filename, additionalData, enableSourcemap, sep = "") {
  21595. if (!additionalData) return { content: source };
  21596. if (typeof additionalData === "function") {
  21597. const newContent = await additionalData(source, filename);
  21598. if (typeof newContent === "string") return { content: newContent };
  21599. return newContent;
  21600. }
  21601. if (!enableSourcemap) return { content: additionalData + sep + source };
  21602. const ms = new MagicString(source);
  21603. ms.appendLeft(0, sep);
  21604. ms.appendLeft(0, additionalData);
  21605. const map = ms.generateMap({ hires: "boundary" });
  21606. map.file = filename;
  21607. map.sources = [filename];
  21608. return {
  21609. content: ms.toString(),
  21610. map
  21611. };
  21612. }
  21613. const createPreprocessorWorkerController = (maxWorkers) => {
  21614. const scss = scssProcessor(maxWorkers);
  21615. const less = lessProcessor(maxWorkers);
  21616. const styl = stylProcessor(maxWorkers);
  21617. const sassProcess = (environment, source, root, options, resolvers) => {
  21618. const opts = { ...options };
  21619. opts.syntax = "indented";
  21620. return scss.process(environment, source, root, opts, resolvers);
  21621. };
  21622. const close = () => {
  21623. less.close();
  21624. scss.close();
  21625. styl.close();
  21626. };
  21627. return {
  21628. [PreprocessLang.less]: less.process,
  21629. [PreprocessLang.scss]: scss.process,
  21630. [PreprocessLang.sass]: sassProcess,
  21631. [PreprocessLang.styl]: styl.process,
  21632. [PreprocessLang.stylus]: styl.process,
  21633. close
  21634. };
  21635. };
  21636. const normalizeMaxWorkers = (maxWorker) => {
  21637. if (maxWorker === void 0) return 0;
  21638. if (maxWorker === true) return void 0;
  21639. return maxWorker;
  21640. };
  21641. const preprocessorSet = new Set([
  21642. PreprocessLang.less,
  21643. PreprocessLang.sass,
  21644. PreprocessLang.scss,
  21645. PreprocessLang.styl,
  21646. PreprocessLang.stylus
  21647. ]);
  21648. function isPreProcessor(lang) {
  21649. return lang && preprocessorSet.has(lang);
  21650. }
  21651. const importEsbuild = createCachedImport(() => import("esbuild"));
  21652. const importLightningCSS = createCachedImport(() => import("lightningcss"));
  21653. async function compileLightningCSS(environment, id, src, deps, workerController, urlResolver) {
  21654. const { config } = environment;
  21655. const filename = removeDirectQuery(id).replace("\0", NULL_BYTE_PLACEHOLDER);
  21656. let res;
  21657. try {
  21658. res = styleAttrRE.test(id) ? (await importLightningCSS()).transformStyleAttribute({
  21659. filename,
  21660. code: Buffer.from(src),
  21661. targets: config.css.lightningcss?.targets,
  21662. minify: config.isProduction && !!config.build.cssMinify,
  21663. analyzeDependencies: true
  21664. }) : await (await importLightningCSS()).bundleAsync({
  21665. ...config.css.lightningcss,
  21666. filename,
  21667. projectRoot: config.root,
  21668. resolver: {
  21669. async read(filePath) {
  21670. if (filePath === filename) return src;
  21671. const code = fs.readFileSync(filePath, "utf-8");
  21672. const lang = CSS_LANGS_RE.exec(filePath)?.[1];
  21673. if (isPreProcessor(lang)) {
  21674. const result = await compileCSSPreprocessors(environment, id, lang, code, workerController);
  21675. result.deps?.forEach((dep) => deps.add(dep));
  21676. return result.code;
  21677. } else if (lang === "sss") return (await transformSugarSS(environment, id, code)).code;
  21678. return code;
  21679. },
  21680. async resolve(id, from) {
  21681. const publicFile = checkPublicFile(id, environment.getTopLevelConfig());
  21682. if (publicFile) return publicFile;
  21683. const atImportResolvers = getAtImportResolvers(environment.getTopLevelConfig());
  21684. const lang = CSS_LANGS_RE.exec(from)?.[1];
  21685. let resolver;
  21686. switch (lang) {
  21687. case "css":
  21688. case "sss":
  21689. case "styl":
  21690. case "stylus":
  21691. case void 0:
  21692. resolver = atImportResolvers.css;
  21693. break;
  21694. case "sass":
  21695. case "scss":
  21696. resolver = atImportResolvers.sass;
  21697. break;
  21698. case "less":
  21699. resolver = atImportResolvers.less;
  21700. break;
  21701. default: throw new Error(`Unknown lang: ${lang}`);
  21702. }
  21703. const resolved = await resolver(environment, id, from);
  21704. if (resolved) {
  21705. deps.add(resolved);
  21706. return resolved;
  21707. }
  21708. return id;
  21709. }
  21710. },
  21711. minify: config.isProduction && !!config.build.cssMinify,
  21712. sourceMap: config.command === "build" ? !!config.build.sourcemap : config.css.devSourcemap,
  21713. analyzeDependencies: true,
  21714. cssModules: cssModuleRE.test(id) ? config.css.lightningcss?.cssModules ?? true : void 0
  21715. });
  21716. } catch (e) {
  21717. e.message = `[lightningcss] ${e.message}`;
  21718. if (e.loc) {
  21719. e.loc = {
  21720. file: e.fileName.replace(NULL_BYTE_PLACEHOLDER, "\0"),
  21721. line: e.loc.line,
  21722. column: e.loc.column - 1
  21723. };
  21724. try {
  21725. const friendlyMessage = getLightningCssErrorMessageForIeSyntaxes(fs.readFileSync(e.fileName, "utf-8"));
  21726. if (friendlyMessage) e.message += friendlyMessage;
  21727. } catch {}
  21728. }
  21729. throw e;
  21730. }
  21731. for (const warning of res.warnings) {
  21732. let msg = `[vite:css][lightningcss] ${warning.message}`;
  21733. msg += `\n${generateCodeFrame(src, {
  21734. line: warning.loc.line,
  21735. column: warning.loc.column - 1
  21736. })}`;
  21737. environment.logger.warn(import_picocolors.default.yellow(msg));
  21738. }
  21739. let css = decoder.decode(res.code);
  21740. for (const dep of res.dependencies) switch (dep.type) {
  21741. case "url": {
  21742. let replaceUrl;
  21743. if (skipUrlReplacer(dep.url)) replaceUrl = dep.url;
  21744. else if (urlResolver) {
  21745. const [newUrl, resolvedId] = await urlResolver(dep.url, dep.loc.filePath.replace(NULL_BYTE_PLACEHOLDER, "\0"));
  21746. if (resolvedId) deps.add(resolvedId);
  21747. replaceUrl = newUrl;
  21748. } else replaceUrl = dep.url;
  21749. css = css.replace(dep.placeholder, () => replaceUrl.replaceAll("\"", "\\\""));
  21750. break;
  21751. }
  21752. default: throw new Error(`Unsupported dependency type: ${dep.type}`);
  21753. }
  21754. let modules;
  21755. if ("exports" in res && res.exports) {
  21756. modules = {};
  21757. const sortedEntries = Object.entries(res.exports).sort((a, b) => a[0].localeCompare(b[0]));
  21758. for (const [key, value] of sortedEntries) {
  21759. modules[key] = value.name;
  21760. for (const c of value.composes) modules[key] += " " + c.name;
  21761. }
  21762. }
  21763. return {
  21764. code: css,
  21765. map: "map" in res ? res.map?.toString() : void 0,
  21766. modules
  21767. };
  21768. }
  21769. function getLightningCssErrorMessageForIeSyntaxes(code) {
  21770. 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.";
  21771. if (/[\s;{]\*[a-zA-Z-][\w-]+\s*:/.test(code)) return ".\nThis file contains star property hack (e.g. `*zoom`)" + commonIeMessage;
  21772. if (/min-width:\s*0\\0/.test(code)) return ".\nThis file contains @media zero hack (e.g. `@media (min-width: 0\\0)`)" + commonIeMessage;
  21773. }
  21774. const map = {
  21775. chrome: "chrome",
  21776. edge: "edge",
  21777. firefox: "firefox",
  21778. hermes: false,
  21779. ie: "ie",
  21780. ios: "ios_saf",
  21781. node: false,
  21782. opera: "opera",
  21783. rhino: false,
  21784. safari: "safari"
  21785. };
  21786. const esMap = {
  21787. 2015: [
  21788. "chrome49",
  21789. "edge13",
  21790. "safari10",
  21791. "ios10",
  21792. "firefox44",
  21793. "opera36"
  21794. ],
  21795. 2016: [
  21796. "chrome50",
  21797. "edge13",
  21798. "safari10",
  21799. "ios10",
  21800. "firefox43",
  21801. "opera37"
  21802. ],
  21803. 2017: [
  21804. "chrome58",
  21805. "edge15",
  21806. "safari11",
  21807. "ios11",
  21808. "firefox52",
  21809. "opera45"
  21810. ],
  21811. 2018: [
  21812. "chrome63",
  21813. "edge79",
  21814. "safari12",
  21815. "ios12",
  21816. "firefox58",
  21817. "opera50"
  21818. ],
  21819. 2019: [
  21820. "chrome73",
  21821. "edge79",
  21822. "safari12.1",
  21823. "ios12.1",
  21824. "firefox64",
  21825. "opera60"
  21826. ],
  21827. 2020: [
  21828. "chrome80",
  21829. "edge80",
  21830. "safari14.1",
  21831. "ios14.5",
  21832. "firefox80",
  21833. "opera67"
  21834. ],
  21835. 2021: [
  21836. "chrome85",
  21837. "edge85",
  21838. "safari14.1",
  21839. "ios14.5",
  21840. "firefox80",
  21841. "opera71"
  21842. ],
  21843. 2022: [
  21844. "chrome94",
  21845. "edge94",
  21846. "safari16.4",
  21847. "ios16.4",
  21848. "firefox93",
  21849. "opera80"
  21850. ],
  21851. 2023: [
  21852. "chrome110",
  21853. "edge110",
  21854. "safari16.4",
  21855. "ios16.4",
  21856. "firefox146",
  21857. "opera96"
  21858. ],
  21859. 2024: [
  21860. "chrome119",
  21861. "edge119",
  21862. "safari17.4",
  21863. "ios17.4",
  21864. "firefox145",
  21865. "opera105"
  21866. ],
  21867. 2025: [
  21868. "chrome136",
  21869. "edge136",
  21870. "safari26.0",
  21871. "ios26.0",
  21872. "firefox138",
  21873. "opera121"
  21874. ]
  21875. };
  21876. const esRE = /es(\d{4})/;
  21877. const versionRE = /\d/;
  21878. const convertTargetsCache = /* @__PURE__ */ new Map();
  21879. const convertTargets = (esbuildTarget) => {
  21880. if (!esbuildTarget) return {};
  21881. const cached = convertTargetsCache.get(esbuildTarget);
  21882. if (cached) return cached;
  21883. const targets = {};
  21884. const entriesWithoutES = arraify(esbuildTarget).flatMap((e) => {
  21885. const match = esRE.exec(e);
  21886. if (!match) return e;
  21887. const year = Number(match[1]);
  21888. if (!esMap[year]) throw new Error(`Unsupported target "${e}"`);
  21889. return esMap[year];
  21890. });
  21891. for (const entry of entriesWithoutES) {
  21892. if (entry === "esnext") continue;
  21893. const index = entry.search(versionRE);
  21894. if (index >= 0) {
  21895. const browser = map[entry.slice(0, index)];
  21896. if (browser === false) continue;
  21897. if (browser) {
  21898. const [major, minor = 0] = entry.slice(index).split(".").map((v) => parseInt(v, 10));
  21899. if (!isNaN(major) && !isNaN(minor)) {
  21900. const version = major << 16 | minor << 8;
  21901. if (!targets[browser] || version < targets[browser]) targets[browser] = version;
  21902. continue;
  21903. }
  21904. }
  21905. }
  21906. throw new Error(`Unsupported target "${entry}"`);
  21907. }
  21908. convertTargetsCache.set(esbuildTarget, targets);
  21909. return targets;
  21910. };
  21911. function resolveLibCssFilename(libOptions, root, packageCache) {
  21912. if (typeof libOptions.cssFileName === "string") return `${libOptions.cssFileName}.css`;
  21913. else if (typeof libOptions.fileName === "string") return `${libOptions.fileName}.css`;
  21914. const packageJson = findNearestMainPackageData(root, packageCache)?.data;
  21915. const name = packageJson ? getPkgName(packageJson.name) : void 0;
  21916. if (!name) throw new Error("Name in package.json is required if option \"build.lib.cssFileName\" is not provided.");
  21917. return `${name}.css`;
  21918. }
  21919. //#endregion
  21920. //#region src/node/plugins/modulePreloadPolyfill.ts
  21921. const modulePreloadPolyfillId = "vite/modulepreload-polyfill";
  21922. const resolvedModulePreloadPolyfillId = "\0" + modulePreloadPolyfillId + ".js";
  21923. function modulePreloadPolyfillPlugin(config) {
  21924. if (config.isBundled) return perEnvironmentPlugin("native:modulepreload-polyfill", (environment) => {
  21925. return viteModulePreloadPolyfillPlugin({ isServer: environment.config.consumer !== "client" });
  21926. });
  21927. return {
  21928. name: "vite:modulepreload-polyfill",
  21929. resolveId: {
  21930. filter: { id: exactRegex(modulePreloadPolyfillId) },
  21931. handler(_id) {
  21932. return resolvedModulePreloadPolyfillId;
  21933. }
  21934. },
  21935. load: {
  21936. filter: { id: exactRegex(resolvedModulePreloadPolyfillId) },
  21937. handler(_id) {
  21938. return "";
  21939. }
  21940. }
  21941. };
  21942. }
  21943. //#endregion
  21944. //#region src/node/plugins/html.ts
  21945. var import_escape_html = /* @__PURE__ */ __toESM(require_escape_html(), 1);
  21946. const htmlProxyRE = /[?&]html-proxy=?(?:&inline-css)?(?:&style-attr)?&index=(\d+)\.(?:js|css)$/;
  21947. const isHtmlProxyRE = /[?&]html-proxy\b/;
  21948. const inlineCSSRE = /__VITE_INLINE_CSS__([a-z\d]{8}_\d+)__/g;
  21949. const inlineImportRE = /(?<!(?<!\.\.)\.)\bimport\s*\(("(?:[^"]|(?<=\\)")*"|'(?:[^']|(?<=\\)')*')\)/dg;
  21950. const htmlLangRE = /\.(?:html|htm)$/;
  21951. const spaceRe = /[\t\n\f\r ]/;
  21952. const importMapRE = /[ \t]*<script[^>]*type\s*=\s*(?:"importmap"|'importmap'|importmap)[^>]*>.*?<\/script>/is;
  21953. 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");
  21954. const isHTMLProxy = (id) => isHtmlProxyRE.test(id);
  21955. const isHTMLRequest = (request) => htmlLangRE.test(request);
  21956. const htmlProxyMap = /* @__PURE__ */ new WeakMap();
  21957. const htmlProxyResult = /* @__PURE__ */ new Map();
  21958. function htmlInlineProxyPlugin(config) {
  21959. htmlProxyMap.set(config, /* @__PURE__ */ new Map());
  21960. return {
  21961. name: "vite:html-inline-proxy",
  21962. resolveId: {
  21963. filter: { id: isHtmlProxyRE },
  21964. handler(id) {
  21965. return id;
  21966. }
  21967. },
  21968. load: {
  21969. filter: { id: isHtmlProxyRE },
  21970. handler(id) {
  21971. const proxyMatch = htmlProxyRE.exec(id);
  21972. if (proxyMatch) {
  21973. const index = Number(proxyMatch[1]);
  21974. const url = cleanUrl(id).replace(normalizePath(config.root), "");
  21975. const result = htmlProxyMap.get(config).get(url)?.[index];
  21976. if (result) return {
  21977. ...result,
  21978. moduleSideEffects: true
  21979. };
  21980. else throw new Error(`No matching HTML proxy module found from ${id}`);
  21981. }
  21982. }
  21983. }
  21984. };
  21985. }
  21986. function addToHTMLProxyCache(config, filePath, index, result) {
  21987. if (!htmlProxyMap.get(config)) htmlProxyMap.set(config, /* @__PURE__ */ new Map());
  21988. if (!htmlProxyMap.get(config).get(filePath)) htmlProxyMap.get(config).set(filePath, []);
  21989. htmlProxyMap.get(config).get(filePath)[index] = result;
  21990. }
  21991. function addToHTMLProxyTransformResult(hash, code) {
  21992. htmlProxyResult.set(hash, code);
  21993. }
  21994. const noInlineLinkRels = new Set([
  21995. "icon",
  21996. "apple-touch-icon",
  21997. "apple-touch-startup-image",
  21998. "manifest"
  21999. ]);
  22000. const isAsyncScriptMap = /* @__PURE__ */ new WeakMap();
  22001. function nodeIsElement(node) {
  22002. return node.nodeName[0] !== "#";
  22003. }
  22004. function traverseNodes(node, visitor) {
  22005. if (node.nodeName === "template") node = node.content;
  22006. visitor(node);
  22007. if (nodeIsElement(node) || node.nodeName === "#document" || node.nodeName === "#document-fragment") node.childNodes.forEach((childNode) => traverseNodes(childNode, visitor));
  22008. }
  22009. async function traverseHtml(html, filePath, warn, visitor) {
  22010. const { parse } = await import("./dist.js");
  22011. const warnings = {};
  22012. traverseNodes(parse(html, {
  22013. scriptingEnabled: false,
  22014. sourceCodeLocationInfo: true,
  22015. onParseError: (e) => {
  22016. handleParseError(e, html, filePath, warnings);
  22017. }
  22018. }), visitor);
  22019. for (const message of Object.values(warnings)) warn(import_picocolors.default.yellow(`\n${message}`));
  22020. }
  22021. function getScriptInfo(node) {
  22022. let src;
  22023. let srcSourceCodeLocation;
  22024. let isModule = false;
  22025. let isAsync = false;
  22026. let isIgnored = false;
  22027. for (const p of node.attrs) {
  22028. if (p.prefix !== void 0) continue;
  22029. if (p.name === "src") {
  22030. if (!src) {
  22031. src = p;
  22032. srcSourceCodeLocation = node.sourceCodeLocation?.attrs["src"];
  22033. }
  22034. } else if (p.name === "type" && p.value === "module") isModule = true;
  22035. else if (p.name === "async") isAsync = true;
  22036. else if (p.name === "vite-ignore") isIgnored = true;
  22037. }
  22038. return {
  22039. src,
  22040. srcSourceCodeLocation,
  22041. isModule,
  22042. isAsync,
  22043. isIgnored
  22044. };
  22045. }
  22046. const attrValueStartRE = /=\s*(.)/;
  22047. function overwriteAttrValue(s, sourceCodeLocation, newValue) {
  22048. const srcString = s.slice(sourceCodeLocation.startOffset, sourceCodeLocation.endOffset);
  22049. const valueStart = attrValueStartRE.exec(srcString);
  22050. if (!valueStart) throw new Error(`[vite:html] internal error, failed to overwrite attribute value`);
  22051. const wrapOffset = valueStart[1] === "\"" || valueStart[1] === "'" ? 1 : 0;
  22052. const valueOffset = valueStart.index + valueStart[0].length - 1;
  22053. s.update(sourceCodeLocation.startOffset + valueOffset + wrapOffset, sourceCodeLocation.endOffset - wrapOffset, newValue);
  22054. return s;
  22055. }
  22056. function removeViteIgnoreAttr(s, sourceCodeLocation) {
  22057. const loc = sourceCodeLocation.attrs?.["vite-ignore"];
  22058. if (loc) s.remove(loc.startOffset, loc.endOffset);
  22059. return s;
  22060. }
  22061. /**
  22062. * Format parse5 @type {ParserError} to @type {RollupError}
  22063. */
  22064. function formatParseError(parserError, id, html) {
  22065. return {
  22066. code: parserError.code,
  22067. message: `parse5 error code ${parserError.code}`,
  22068. frame: generateCodeFrame(html, parserError.startOffset, parserError.endOffset),
  22069. loc: {
  22070. file: id,
  22071. line: parserError.startLine,
  22072. column: parserError.startCol
  22073. }
  22074. };
  22075. }
  22076. function handleParseError(parserError, html, filePath, warnings) {
  22077. switch (parserError.code) {
  22078. case "missing-doctype": return;
  22079. case "abandoned-head-element-child": return;
  22080. case "duplicate-attribute": return;
  22081. case "non-void-html-element-start-tag-with-trailing-solidus": return;
  22082. case "unexpected-question-mark-instead-of-tag-name": return;
  22083. }
  22084. const parseError = formatParseError(parserError, filePath, html);
  22085. warnings[parseError.code] ??= `Unable to parse HTML; ${parseError.message}\n at ${parseError.loc.file}:${parseError.loc.line}:${parseError.loc.column}\n` + parseError.frame;
  22086. }
  22087. /**
  22088. * Compiles index.html into an entry js module
  22089. */
  22090. function buildHtmlPlugin(config) {
  22091. const [preHooks, normalHooks, postHooks] = resolveHtmlTransforms(config.plugins);
  22092. preHooks.unshift(injectCspNonceMetaTagHook(config));
  22093. preHooks.unshift(preImportMapHook(config));
  22094. preHooks.push(htmlEnvHook(config));
  22095. postHooks.push(injectNonceAttributeTagHook(config));
  22096. postHooks.push(postImportMapHook());
  22097. const processedHtml = perEnvironmentState(() => /* @__PURE__ */ new Map());
  22098. const isExcludedUrl = (url) => url[0] === "#" || isExternalUrl(url) || isDataUrl(url);
  22099. isAsyncScriptMap.set(config, /* @__PURE__ */ new Map());
  22100. return {
  22101. name: "vite:build-html",
  22102. transform: {
  22103. filter: { id: /\.html$/ },
  22104. async handler(html, id) {
  22105. id = normalizePath(id);
  22106. const relativeUrlPath = normalizePath(path.relative(config.root, id));
  22107. const publicPath = `/${relativeUrlPath}`;
  22108. const publicBase = getBaseInHTML(relativeUrlPath, config);
  22109. const publicToRelative = (filename) => publicBase + filename;
  22110. const toOutputPublicFilePath = (url) => toOutputFilePathInHtml(url.slice(1), "public", relativeUrlPath, "html", config, publicToRelative);
  22111. const nodeStartWithLeadingWhitespace = (node) => {
  22112. const startOffset = node.sourceCodeLocation.startOffset;
  22113. if (startOffset === 0) return 0;
  22114. const lineStartOffset = startOffset - node.sourceCodeLocation.startCol;
  22115. let isLineEmpty = false;
  22116. try {
  22117. isLineEmpty = !s.slice(Math.max(0, lineStartOffset), startOffset).trim();
  22118. } catch {}
  22119. return isLineEmpty ? lineStartOffset : startOffset;
  22120. };
  22121. html = await applyHtmlTransforms(html, preHooks, this, {
  22122. path: publicPath,
  22123. filename: id
  22124. });
  22125. let js = "";
  22126. const s = new MagicString(html);
  22127. const scriptUrls = [];
  22128. const styleUrls = [];
  22129. let inlineModuleIndex = -1;
  22130. let everyScriptIsAsync = true;
  22131. let someScriptsAreAsync = false;
  22132. let someScriptsAreDefer = false;
  22133. const assetUrlsPromises = [];
  22134. const namedOutput = Object.keys(config.build.rollupOptions.input || {});
  22135. const processAssetUrl = async (url, shouldInline) => {
  22136. if (url !== "" && !namedOutput.includes(url) && !namedOutput.includes(removeLeadingSlash(url))) try {
  22137. return await urlToBuiltUrl(this, url, id, shouldInline);
  22138. } catch (e) {
  22139. if (e.code !== "ENOENT") throw e;
  22140. }
  22141. return url;
  22142. };
  22143. const setModuleSideEffectPromises = [];
  22144. await traverseHtml(html, id, config.logger.warn, (node) => {
  22145. if (!nodeIsElement(node)) return;
  22146. let shouldRemove = false;
  22147. if (node.nodeName === "script") {
  22148. const { src, srcSourceCodeLocation, isModule, isAsync, isIgnored } = getScriptInfo(node);
  22149. if (isIgnored) removeViteIgnoreAttr(s, node.sourceCodeLocation);
  22150. else {
  22151. const url = src && src.value;
  22152. const isPublicFile = !!(url && checkPublicFile(url, config));
  22153. if (isPublicFile) overwriteAttrValue(s, srcSourceCodeLocation, partialEncodeURIPath(toOutputPublicFilePath(url)));
  22154. if (isModule) {
  22155. inlineModuleIndex++;
  22156. if (url && !isExcludedUrl(url) && !isPublicFile) {
  22157. setModuleSideEffectPromises.push(this.resolve(url, id).then((resolved) => {
  22158. if (!resolved) return Promise.reject(/* @__PURE__ */ new Error(`Failed to resolve ${url} from ${id}`));
  22159. const moduleInfo = this.getModuleInfo(resolved.id);
  22160. if (moduleInfo) moduleInfo.moduleSideEffects = true;
  22161. else if (!resolved.external) return this.load({
  22162. ...resolved,
  22163. moduleSideEffects: true
  22164. }).then(() => {});
  22165. }));
  22166. js += `\nimport ${JSON.stringify(url)}`;
  22167. shouldRemove = true;
  22168. } else if (node.childNodes.length) {
  22169. const contents = node.childNodes.pop().value;
  22170. addToHTMLProxyCache(config, id.replace(normalizePath(config.root), ""), inlineModuleIndex, { code: contents });
  22171. js += `\nimport "${id}?html-proxy&index=${inlineModuleIndex}.js"`;
  22172. shouldRemove = true;
  22173. }
  22174. everyScriptIsAsync &&= isAsync;
  22175. someScriptsAreAsync ||= isAsync;
  22176. someScriptsAreDefer ||= !isAsync;
  22177. } else if (url && !isPublicFile) {
  22178. if (!isExcludedUrl(url)) config.logger.warn(`<script src="${url}"> in "${publicPath}" can't be bundled without type="module" attribute`);
  22179. } else if (node.childNodes.length) {
  22180. const scriptNode = node.childNodes.pop();
  22181. scriptUrls.push(...extractImportExpressionFromClassicScript(scriptNode));
  22182. }
  22183. }
  22184. }
  22185. const assetAttributes = getNodeAssetAttributes(node);
  22186. for (const attr of assetAttributes) if (attr.type === "remove") {
  22187. s.remove(attr.location.startOffset, attr.location.endOffset);
  22188. continue;
  22189. } else if (attr.type === "srcset") assetUrlsPromises.push((async () => {
  22190. const processedEncodedUrl = await processSrcSet(attr.value, async ({ url }) => {
  22191. const decodedUrl = decodeURIIfPossible(url);
  22192. if (decodedUrl !== void 0 && !isExcludedUrl(decodedUrl)) {
  22193. const result = await processAssetUrl(url);
  22194. return result !== decodedUrl ? encodeURIPath(result) : url;
  22195. }
  22196. return url;
  22197. });
  22198. if (processedEncodedUrl !== attr.value) overwriteAttrValue(s, attr.location, processedEncodedUrl);
  22199. })());
  22200. else if (attr.type === "src") {
  22201. const url = decodeURIIfPossible(attr.value);
  22202. if (url === void 0) {} else if (checkPublicFile(url, config)) overwriteAttrValue(s, attr.location, partialEncodeURIPath(toOutputPublicFilePath(url)));
  22203. else if (!isExcludedUrl(url)) if (node.nodeName === "link" && isCSSRequest(url) && !("media" in attr.attributes || "disabled" in attr.attributes)) {
  22204. const importExpression = `\nimport ${JSON.stringify(url)}`;
  22205. styleUrls.push({
  22206. url,
  22207. start: nodeStartWithLeadingWhitespace(node),
  22208. end: node.sourceCodeLocation.endOffset
  22209. });
  22210. js += importExpression;
  22211. } else {
  22212. const shouldInline = node.nodeName === "link" && attr.attributes.rel && parseRelAttr(attr.attributes.rel).some((v) => noInlineLinkRels.has(v)) ? false : void 0;
  22213. assetUrlsPromises.push((async () => {
  22214. const processedUrl = await processAssetUrl(url, shouldInline);
  22215. if (processedUrl !== url) overwriteAttrValue(s, attr.location, partialEncodeURIPath(processedUrl));
  22216. })());
  22217. }
  22218. }
  22219. const inlineStyle = findNeedTransformStyleAttribute(node);
  22220. if (inlineStyle) {
  22221. inlineModuleIndex++;
  22222. const code = inlineStyle.attr.value;
  22223. addToHTMLProxyCache(config, id.replace(normalizePath(config.root), ""), inlineModuleIndex, { code });
  22224. js += `\nimport "${id}?html-proxy&inline-css&style-attr&index=${inlineModuleIndex}.css"`;
  22225. const hash = getHash(cleanUrl(id));
  22226. overwriteAttrValue(s, inlineStyle.location, `__VITE_INLINE_CSS__${hash}_${inlineModuleIndex}__`);
  22227. }
  22228. if (node.nodeName === "style" && node.childNodes.length) {
  22229. const styleNode = node.childNodes.pop();
  22230. const filePath = id.replace(normalizePath(config.root), "");
  22231. inlineModuleIndex++;
  22232. addToHTMLProxyCache(config, filePath, inlineModuleIndex, { code: styleNode.value });
  22233. js += `\nimport "${id}?html-proxy&inline-css&index=${inlineModuleIndex}.css"`;
  22234. const hash = getHash(cleanUrl(id));
  22235. s.update(styleNode.sourceCodeLocation.startOffset, styleNode.sourceCodeLocation.endOffset, `__VITE_INLINE_CSS__${hash}_${inlineModuleIndex}__`);
  22236. }
  22237. if (shouldRemove) s.remove(nodeStartWithLeadingWhitespace(node), node.sourceCodeLocation.endOffset);
  22238. });
  22239. isAsyncScriptMap.get(config).set(id, everyScriptIsAsync);
  22240. 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.`);
  22241. await Promise.all(assetUrlsPromises);
  22242. for (const { start, end, url } of scriptUrls) if (checkPublicFile(url, config)) s.update(start, end, partialEncodeURIPath(toOutputPublicFilePath(url)));
  22243. else if (!isExcludedUrl(url)) s.update(start, end, partialEncodeURIPath(await urlToBuiltUrl(this, url, id)));
  22244. const resolvedStyleUrls = await Promise.all(styleUrls.map(async (styleUrl) => ({
  22245. ...styleUrl,
  22246. resolved: await this.resolve(styleUrl.url, id)
  22247. })));
  22248. for (const { start, end, url, resolved } of resolvedStyleUrls) if (resolved == null) {
  22249. config.logger.warnOnce(`\n${url} doesn't exist at build time, it will remain unchanged to be resolved at runtime`);
  22250. const importExpression = `\nimport ${JSON.stringify(url)}`;
  22251. js = js.replace(importExpression, "");
  22252. } else s.remove(start, end);
  22253. processedHtml(this).set(id, s.toString());
  22254. const { modulePreload } = this.environment.config.build;
  22255. if (modulePreload !== false && modulePreload.polyfill && (someScriptsAreAsync || someScriptsAreDefer)) js = `import "${modulePreloadPolyfillId}";\n${js}`;
  22256. await Promise.all(setModuleSideEffectPromises);
  22257. return {
  22258. code: js,
  22259. moduleSideEffects: "no-treeshake"
  22260. };
  22261. }
  22262. },
  22263. async generateBundle(options, bundle) {
  22264. const analyzedImportedCssFiles = /* @__PURE__ */ new Map();
  22265. const inlineEntryChunk = /* @__PURE__ */ new Set();
  22266. const getImportedChunks = (chunk, seen = /* @__PURE__ */ new Set()) => {
  22267. const chunks = [];
  22268. chunk.imports.forEach((file) => {
  22269. const importee = bundle[file];
  22270. if (importee) {
  22271. if (importee.type === "chunk" && !seen.has(file)) {
  22272. seen.add(file);
  22273. chunks.push(...getImportedChunks(importee, seen));
  22274. chunks.push(importee);
  22275. }
  22276. } else chunks.push(file);
  22277. });
  22278. return chunks;
  22279. };
  22280. const toScriptTag = (chunkOrUrl, toOutputPath, isAsync) => ({
  22281. tag: "script",
  22282. attrs: {
  22283. ...isAsync ? { async: true } : {},
  22284. type: "module",
  22285. crossorigin: true,
  22286. src: typeof chunkOrUrl === "string" ? chunkOrUrl : toOutputPath(chunkOrUrl.fileName)
  22287. }
  22288. });
  22289. const toPreloadTag = (filename, toOutputPath) => ({
  22290. tag: "link",
  22291. attrs: {
  22292. rel: "modulepreload",
  22293. crossorigin: true,
  22294. href: toOutputPath(filename)
  22295. }
  22296. });
  22297. const toStyleSheetLinkTag = (file, toOutputPath) => ({
  22298. tag: "link",
  22299. attrs: {
  22300. rel: "stylesheet",
  22301. crossorigin: true,
  22302. href: toOutputPath(file)
  22303. }
  22304. });
  22305. const getCssFilesForChunk = (chunk, seenChunks = /* @__PURE__ */ new Set(), seenCss = /* @__PURE__ */ new Set()) => {
  22306. if (seenChunks.has(chunk.fileName)) return [];
  22307. seenChunks.add(chunk.fileName);
  22308. if (analyzedImportedCssFiles.has(chunk)) {
  22309. const additionals = analyzedImportedCssFiles.get(chunk).filter((file) => !seenCss.has(file));
  22310. additionals.forEach((file) => seenCss.add(file));
  22311. return additionals;
  22312. }
  22313. const files = [];
  22314. chunk.imports.forEach((file) => {
  22315. const importee = bundle[file];
  22316. if (importee?.type === "chunk") files.push(...getCssFilesForChunk(importee, seenChunks, seenCss));
  22317. });
  22318. analyzedImportedCssFiles.set(chunk, files);
  22319. chunk.viteMetadata.importedCss.forEach((file) => {
  22320. if (!seenCss.has(file)) {
  22321. seenCss.add(file);
  22322. files.push(file);
  22323. }
  22324. });
  22325. return files;
  22326. };
  22327. const getCssTagsForChunk = (chunk, toOutputPath) => getCssFilesForChunk(chunk).map((file) => toStyleSheetLinkTag(file, toOutputPath));
  22328. for (const [normalizedId, html] of processedHtml(this)) {
  22329. const relativeUrlPath = normalizePath(path.relative(config.root, normalizedId));
  22330. const assetsBase = getBaseInHTML(relativeUrlPath, config);
  22331. const toOutputFilePath = (filename, type) => {
  22332. if (isExternalUrl(filename)) return filename;
  22333. else return toOutputFilePathInHtml(filename, type, relativeUrlPath, "html", config, (filename) => assetsBase + filename);
  22334. };
  22335. const toOutputAssetFilePath = (filename) => toOutputFilePath(filename, "asset");
  22336. const toOutputPublicAssetFilePath = (filename) => toOutputFilePath(filename, "public");
  22337. const isAsync = isAsyncScriptMap.get(config).get(normalizedId);
  22338. let result = html;
  22339. const chunk = Object.values(bundle).find((chunk) => chunk.type === "chunk" && chunk.isEntry && chunk.facadeModuleId && normalizePath(chunk.facadeModuleId) === normalizedId);
  22340. let canInlineEntry = false;
  22341. if (chunk) {
  22342. if (options.format === "es" && isEntirelyImport(chunk.code)) canInlineEntry = true;
  22343. const imports = getImportedChunks(chunk);
  22344. let assetTags;
  22345. if (canInlineEntry) assetTags = imports.map((chunk) => toScriptTag(chunk, toOutputAssetFilePath, isAsync));
  22346. else {
  22347. const { modulePreload } = this.environment.config.build;
  22348. assetTags = [toScriptTag(chunk, toOutputAssetFilePath, isAsync)];
  22349. if (modulePreload !== false) {
  22350. const resolveDependencies = typeof modulePreload === "object" && modulePreload.resolveDependencies;
  22351. const importsFileNames = imports.filter((chunkOrUrl) => typeof chunkOrUrl !== "string").map((chunk) => chunk.fileName);
  22352. const resolvedDeps = resolveDependencies ? resolveDependencies(chunk.fileName, importsFileNames, {
  22353. hostId: relativeUrlPath,
  22354. hostType: "html"
  22355. }) : importsFileNames;
  22356. assetTags.push(...resolvedDeps.map((i) => toPreloadTag(i, toOutputAssetFilePath)));
  22357. }
  22358. }
  22359. assetTags.push(...getCssTagsForChunk(chunk, toOutputAssetFilePath));
  22360. result = injectToHead(result, assetTags);
  22361. }
  22362. if (!this.environment.config.build.cssCodeSplit) {
  22363. const cssBundleName = cssBundleNameCache.get(config);
  22364. const cssChunk = cssBundleName && Object.values(bundle).find((chunk) => chunk.type === "asset" && chunk.names.includes(cssBundleName));
  22365. if (cssChunk) result = injectToHead(result, [{
  22366. tag: "link",
  22367. attrs: {
  22368. rel: "stylesheet",
  22369. crossorigin: true,
  22370. href: toOutputAssetFilePath(cssChunk.fileName)
  22371. }
  22372. }]);
  22373. }
  22374. let match;
  22375. let s;
  22376. inlineCSSRE.lastIndex = 0;
  22377. while (match = inlineCSSRE.exec(result)) {
  22378. s ||= new MagicString(result);
  22379. const { 0: full, 1: scopedName } = match;
  22380. const cssTransformedCode = htmlProxyResult.get(scopedName);
  22381. s.update(match.index, match.index + full.length, cssTransformedCode);
  22382. }
  22383. if (s) result = s.toString();
  22384. result = await applyHtmlTransforms(result, [...normalHooks, ...postHooks], this, {
  22385. path: "/" + relativeUrlPath,
  22386. filename: normalizedId,
  22387. bundle,
  22388. chunk
  22389. });
  22390. result = result.replace(assetUrlRE, (_, fileHash, postfix = "") => {
  22391. const file = this.getFileName(fileHash);
  22392. if (chunk) chunk.viteMetadata.importedAssets.add(cleanUrl(file));
  22393. return encodeURIPath(toOutputAssetFilePath(file)) + postfix;
  22394. });
  22395. result = result.replace(publicAssetUrlRE, (_, fileHash) => {
  22396. const publicAssetPath = toOutputPublicAssetFilePath(getPublicAssetFilename(fileHash, config));
  22397. return encodeURIPath(URL$1.canParse(publicAssetPath) ? publicAssetPath : normalizePath(publicAssetPath));
  22398. });
  22399. if (chunk && canInlineEntry) inlineEntryChunk.add(chunk.fileName);
  22400. const shortEmitName = normalizePath(path.relative(config.root, normalizedId));
  22401. this.emitFile({
  22402. type: "asset",
  22403. originalFileName: normalizedId,
  22404. fileName: shortEmitName,
  22405. source: result
  22406. });
  22407. }
  22408. for (const fileName of inlineEntryChunk) delete bundle[fileName];
  22409. }
  22410. };
  22411. }
  22412. function parseRelAttr(attr) {
  22413. return attr.split(spaceRe).map((v) => v.toLowerCase());
  22414. }
  22415. function findNeedTransformStyleAttribute(node) {
  22416. const attr = node.attrs.find((prop) => prop.prefix === void 0 && prop.name === "style" && (prop.value.includes("url(") || prop.value.includes("image-set(")));
  22417. if (!attr) return void 0;
  22418. return {
  22419. attr,
  22420. location: node.sourceCodeLocation?.attrs?.["style"]
  22421. };
  22422. }
  22423. function extractImportExpressionFromClassicScript(scriptTextNode) {
  22424. const startOffset = scriptTextNode.sourceCodeLocation.startOffset;
  22425. const cleanCode = stripLiteral(scriptTextNode.value);
  22426. const scriptUrls = [];
  22427. let match;
  22428. inlineImportRE.lastIndex = 0;
  22429. while (match = inlineImportRE.exec(cleanCode)) {
  22430. const [, [urlStart, urlEnd]] = match.indices;
  22431. const start = urlStart + 1;
  22432. const end = urlEnd - 1;
  22433. scriptUrls.push({
  22434. start: start + startOffset,
  22435. end: end + startOffset,
  22436. url: scriptTextNode.value.slice(start, end)
  22437. });
  22438. }
  22439. return scriptUrls;
  22440. }
  22441. function preImportMapHook(config) {
  22442. return (html, ctx) => {
  22443. const importMapIndex = html.search(importMapRE);
  22444. if (importMapIndex < 0) return;
  22445. const importMapAppendIndex = html.search(importMapAppendRE);
  22446. if (importMapAppendIndex < 0) return;
  22447. if (importMapAppendIndex < importMapIndex) {
  22448. const relativeHtml = normalizePath(path.relative(config.root, ctx.filename));
  22449. 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}`)));
  22450. }
  22451. };
  22452. }
  22453. /**
  22454. * Move importmap before the first module script and modulepreload link
  22455. */
  22456. function postImportMapHook() {
  22457. return (html) => {
  22458. if (!importMapAppendRE.test(html)) return;
  22459. let importMap;
  22460. html = html.replace(importMapRE, (match) => {
  22461. importMap = match;
  22462. return "";
  22463. });
  22464. if (importMap) html = html.replace(importMapAppendRE, (match) => `${importMap}\n${match}`);
  22465. return html;
  22466. };
  22467. }
  22468. function injectCspNonceMetaTagHook(config) {
  22469. return () => {
  22470. if (!config.html?.cspNonce) return;
  22471. return [{
  22472. tag: "meta",
  22473. injectTo: "head",
  22474. attrs: {
  22475. property: "csp-nonce",
  22476. nonce: config.html.cspNonce
  22477. }
  22478. }];
  22479. };
  22480. }
  22481. /**
  22482. * Support `%ENV_NAME%` syntax in html files
  22483. */
  22484. function htmlEnvHook(config) {
  22485. const pattern = /%(\S+?)%/g;
  22486. const envPrefix = resolveEnvPrefix({ envPrefix: config.envPrefix });
  22487. const env = { ...config.env };
  22488. for (const key in config.define) if (key.startsWith(`import.meta.env.`)) {
  22489. const val = config.define[key];
  22490. if (typeof val === "string") try {
  22491. const parsed = JSON.parse(val);
  22492. env[key.slice(16)] = typeof parsed === "string" ? parsed : val;
  22493. } catch {
  22494. env[key.slice(16)] = val;
  22495. }
  22496. else env[key.slice(16)] = JSON.stringify(val);
  22497. }
  22498. return (html, ctx) => {
  22499. return html.replace(pattern, (text, key) => {
  22500. if (key in env) return env[key];
  22501. else {
  22502. if (envPrefix.some((prefix) => key.startsWith(prefix))) {
  22503. const relativeHtml = normalizePath(path.relative(config.root, ctx.filename));
  22504. 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?`)));
  22505. }
  22506. return text;
  22507. }
  22508. });
  22509. };
  22510. }
  22511. function injectNonceAttributeTagHook(config) {
  22512. const processRelType = new Set([
  22513. "stylesheet",
  22514. "modulepreload",
  22515. "preload"
  22516. ]);
  22517. return async (html, { filename }) => {
  22518. const nonce = config.html?.cspNonce;
  22519. if (!nonce) return;
  22520. const s = new MagicString(html);
  22521. await traverseHtml(html, filename, config.logger.warn, (node) => {
  22522. if (!nodeIsElement(node)) return;
  22523. const { nodeName, attrs, sourceCodeLocation } = node;
  22524. if (nodeName === "script" || nodeName === "style" || nodeName === "link" && attrs.some((attr) => attr.name === "rel" && parseRelAttr(attr.value).some((a) => processRelType.has(a)))) {
  22525. if (attrs.some(({ name }) => name === "nonce")) return;
  22526. const startTagEndOffset = sourceCodeLocation.startTag.endOffset;
  22527. const appendOffset = html[startTagEndOffset - 2] === "/" ? 2 : 1;
  22528. s.appendRight(startTagEndOffset - appendOffset, ` nonce="${nonce}"`);
  22529. }
  22530. });
  22531. return s.toString();
  22532. };
  22533. }
  22534. function resolveHtmlTransforms(plugins) {
  22535. const preHooks = [];
  22536. const normalHooks = [];
  22537. const postHooks = [];
  22538. for (const plugin of plugins) {
  22539. const hook = plugin.transformIndexHtml;
  22540. if (!hook) continue;
  22541. if (typeof hook === "function") normalHooks.push(hook);
  22542. else {
  22543. const handler = hook.handler;
  22544. if (hook.order === "pre") preHooks.push(handler);
  22545. else if (hook.order === "post") postHooks.push(handler);
  22546. else normalHooks.push(handler);
  22547. }
  22548. }
  22549. return [
  22550. preHooks,
  22551. normalHooks,
  22552. postHooks
  22553. ];
  22554. }
  22555. const elementsAllowedInHead = new Set([
  22556. "title",
  22557. "base",
  22558. "link",
  22559. "style",
  22560. "meta",
  22561. "script",
  22562. "noscript",
  22563. "template"
  22564. ]);
  22565. function headTagInsertCheck(tags, ctx) {
  22566. if (!tags.length) return;
  22567. const { logger } = ctx.server?.config || {};
  22568. const disallowedTags = tags.filter((tagDescriptor) => !elementsAllowedInHead.has(tagDescriptor.tag));
  22569. if (disallowedTags.length) {
  22570. const dedupedTags = unique(disallowedTags.map((tagDescriptor) => `<${tagDescriptor.tag}>`));
  22571. 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`)));
  22572. }
  22573. }
  22574. async function applyHtmlTransforms(html, hooks, pluginContext, ctx) {
  22575. for (const hook of hooks) {
  22576. const res = await hook.call(pluginContext, html, ctx);
  22577. if (!res) continue;
  22578. if (typeof res === "string") html = res;
  22579. else {
  22580. let tags;
  22581. if (Array.isArray(res)) tags = res;
  22582. else {
  22583. html = res.html || html;
  22584. tags = res.tags;
  22585. }
  22586. let headTags;
  22587. let headPrependTags;
  22588. let bodyTags;
  22589. let bodyPrependTags;
  22590. for (const tag of tags) switch (tag.injectTo) {
  22591. case "body":
  22592. (bodyTags ??= []).push(tag);
  22593. break;
  22594. case "body-prepend":
  22595. (bodyPrependTags ??= []).push(tag);
  22596. break;
  22597. case "head":
  22598. (headTags ??= []).push(tag);
  22599. break;
  22600. default: (headPrependTags ??= []).push(tag);
  22601. }
  22602. headTagInsertCheck([...headTags || [], ...headPrependTags || []], ctx);
  22603. if (headPrependTags) html = injectToHead(html, headPrependTags, true);
  22604. if (headTags) html = injectToHead(html, headTags);
  22605. if (bodyPrependTags) html = injectToBody(html, bodyPrependTags, true);
  22606. if (bodyTags) html = injectToBody(html, bodyTags);
  22607. }
  22608. }
  22609. return html;
  22610. }
  22611. const entirelyImportRE = /^(?:import\s*(?:"[^"\n]*[^\\\n]"|'[^'\n]*[^\\\n]');*|\/\*[\s\S]*?\*\/|\/\/.*[$\n])*$/;
  22612. function isEntirelyImport(code) {
  22613. return entirelyImportRE.test(code.trim());
  22614. }
  22615. function getBaseInHTML(urlRelativePath, config) {
  22616. return config.base === "./" || config.base === "" ? path.posix.join(path.posix.relative(urlRelativePath, "").slice(0, -2), "./") : config.base;
  22617. }
  22618. const headInjectRE = /([ \t]*)<\/head>/i;
  22619. const headPrependInjectRE = /([ \t]*)<head[^>]*>/i;
  22620. const htmlInjectRE = /<\/html>/i;
  22621. const htmlPrependInjectRE = /([ \t]*)<html[^>]*>/i;
  22622. const bodyInjectRE = /([ \t]*)<\/body>/i;
  22623. const bodyPrependInjectRE = /([ \t]*)<body[^>]*>/i;
  22624. const doctypePrependInjectRE = /<!doctype html>/i;
  22625. function injectToHead(html, tags, prepend = false) {
  22626. if (tags.length === 0) return html;
  22627. if (prepend) {
  22628. if (headPrependInjectRE.test(html)) return html.replace(headPrependInjectRE, (match, p1) => `${match}\n${serializeTags(tags, incrementIndent(p1))}`);
  22629. } else {
  22630. if (headInjectRE.test(html)) return html.replace(headInjectRE, (match, p1) => `${serializeTags(tags, incrementIndent(p1))}${match}`);
  22631. if (bodyPrependInjectRE.test(html)) return html.replace(bodyPrependInjectRE, (match, p1) => `${serializeTags(tags, p1)}\n${match}`);
  22632. }
  22633. return prependInjectFallback(html, tags);
  22634. }
  22635. function injectToBody(html, tags, prepend = false) {
  22636. if (tags.length === 0) return html;
  22637. if (prepend) {
  22638. if (bodyPrependInjectRE.test(html)) return html.replace(bodyPrependInjectRE, (match, p1) => `${match}\n${serializeTags(tags, incrementIndent(p1))}`);
  22639. if (headInjectRE.test(html)) return html.replace(headInjectRE, (match, p1) => `${match}\n${serializeTags(tags, p1)}`);
  22640. return prependInjectFallback(html, tags);
  22641. } else {
  22642. if (bodyInjectRE.test(html)) return html.replace(bodyInjectRE, (match, p1) => `${serializeTags(tags, incrementIndent(p1))}${match}`);
  22643. if (htmlInjectRE.test(html)) return html.replace(htmlInjectRE, `${serializeTags(tags)}\n$&`);
  22644. return html + `\n` + serializeTags(tags);
  22645. }
  22646. }
  22647. function prependInjectFallback(html, tags) {
  22648. if (htmlPrependInjectRE.test(html)) return html.replace(htmlPrependInjectRE, `$&\n${serializeTags(tags)}`);
  22649. if (doctypePrependInjectRE.test(html)) return html.replace(doctypePrependInjectRE, `$&\n${serializeTags(tags)}`);
  22650. return serializeTags(tags) + html;
  22651. }
  22652. const unaryTags = new Set([
  22653. "link",
  22654. "meta",
  22655. "base"
  22656. ]);
  22657. function serializeTag({ tag, attrs, children }, indent = "") {
  22658. if (unaryTags.has(tag)) return `<${tag}${serializeAttrs(attrs)}>`;
  22659. else return `<${tag}${serializeAttrs(attrs)}>${serializeTags(children, incrementIndent(indent))}</${tag}>`;
  22660. }
  22661. function serializeTags(tags, indent = "") {
  22662. if (typeof tags === "string") return tags;
  22663. else if (tags && tags.length) return tags.map((tag) => `${indent}${serializeTag(tag, indent)}\n`).join("");
  22664. return "";
  22665. }
  22666. function serializeAttrs(attrs) {
  22667. let res = "";
  22668. for (const key in attrs) if (typeof attrs[key] === "boolean") res += attrs[key] ? ` ${key}` : ``;
  22669. else res += ` ${key}="${(0, import_escape_html.default)(attrs[key])}"`;
  22670. return res;
  22671. }
  22672. function incrementIndent(indent = "") {
  22673. return `${indent}${indent[0] === " " ? " " : " "}`;
  22674. }
  22675. //#endregion
  22676. //#region src/node/plugins/define.ts
  22677. const nonJsRe = /\.json(?:$|\?)/;
  22678. const isNonJsRequest = (request) => nonJsRe.test(request);
  22679. const escapedDotRE = /(?<!\\)\\./g;
  22680. function definePlugin(config) {
  22681. const isBundled = config.isBundled;
  22682. const isBuild = config.command === "build";
  22683. const isBuildLib = isBuild && config.build.lib;
  22684. const processEnv = {};
  22685. if (!isBuildLib) {
  22686. const nodeEnv = process.env.NODE_ENV || config.mode;
  22687. Object.assign(processEnv, {
  22688. "process.env": `{}`,
  22689. "global.process.env": `{}`,
  22690. "globalThis.process.env": `{}`,
  22691. "process.env.NODE_ENV": JSON.stringify(nodeEnv),
  22692. "global.process.env.NODE_ENV": JSON.stringify(nodeEnv),
  22693. "globalThis.process.env.NODE_ENV": JSON.stringify(nodeEnv)
  22694. });
  22695. }
  22696. const importMetaKeys = {};
  22697. const importMetaEnvKeys = {};
  22698. const importMetaFallbackKeys = {};
  22699. if (isBuild) importMetaKeys["import.meta.hot"] = `undefined`;
  22700. if (isBundled) {
  22701. for (const key in config.env) {
  22702. const val = JSON.stringify(config.env[key]);
  22703. importMetaKeys[`import.meta.env.${key}`] = val;
  22704. importMetaEnvKeys[key] = val;
  22705. }
  22706. importMetaKeys["import.meta.env.SSR"] = `undefined`;
  22707. importMetaFallbackKeys["import.meta.env"] = `undefined`;
  22708. }
  22709. function generatePattern(environment) {
  22710. const keepProcessEnv = environment.config.keepProcessEnv;
  22711. const userDefine = {};
  22712. const userDefineEnv = {};
  22713. for (const key in environment.config.define) {
  22714. userDefine[key] = handleDefineValue(environment.config.define[key]);
  22715. if (isBuild && key.startsWith("import.meta.env.")) userDefineEnv[key.slice(16)] = environment.config.define[key];
  22716. }
  22717. const define = {
  22718. ...keepProcessEnv ? {} : processEnv,
  22719. ...importMetaKeys,
  22720. ...userDefine,
  22721. ...importMetaFallbackKeys
  22722. };
  22723. const ssr = environment.config.consumer === "server";
  22724. if ("import.meta.env.SSR" in define) define["import.meta.env.SSR"] = ssr + "";
  22725. const importMetaEnvVal = serializeDefine({
  22726. ...importMetaEnvKeys,
  22727. SSR: ssr + "",
  22728. ...userDefineEnv
  22729. });
  22730. const patternKeys = Object.keys(userDefine);
  22731. if (!keepProcessEnv && Object.keys(processEnv).length) patternKeys.push("process.env");
  22732. if (Object.keys(importMetaKeys).length) patternKeys.push("import.meta.env", "import.meta.hot");
  22733. return [
  22734. define,
  22735. patternKeys.length ? new RegExp(patternKeys.map((key) => escapeRegex(key).replaceAll(escapedDotRE, "\\??\\.")).join("|")) : null,
  22736. importMetaEnvVal
  22737. ];
  22738. }
  22739. const patternsCache = /* @__PURE__ */ new WeakMap();
  22740. function getPattern(environment) {
  22741. let pattern = patternsCache.get(environment);
  22742. if (!pattern) {
  22743. pattern = generatePattern(environment);
  22744. patternsCache.set(environment, pattern);
  22745. }
  22746. return pattern;
  22747. }
  22748. if (isBundled) return {
  22749. name: "vite:define",
  22750. options(option) {
  22751. const [define, _pattern, importMetaEnvVal] = getPattern(this.environment);
  22752. define["import.meta.env"] = importMetaEnvVal;
  22753. define["import.meta.env.*"] = "undefined";
  22754. option.transform ??= {};
  22755. option.transform.define = {
  22756. ...option.transform.define,
  22757. ...define
  22758. };
  22759. }
  22760. };
  22761. return {
  22762. name: "vite:define",
  22763. transform: { async handler(code, id) {
  22764. if (this.environment.config.consumer === "client") return;
  22765. if (isHTMLRequest(id) || isCSSRequest(id) || isNonJsRequest(id) || config.assetsInclude(id)) return;
  22766. const [define, pattern] = getPattern(this.environment);
  22767. if (!pattern) return;
  22768. pattern.lastIndex = 0;
  22769. if (!pattern.test(code)) return;
  22770. return await replaceDefine(this.environment, code, id, define);
  22771. } }
  22772. };
  22773. }
  22774. async function replaceDefine(environment, code, id, define) {
  22775. const result = transformSync(id, code, {
  22776. lang: "js",
  22777. sourceType: "module",
  22778. define,
  22779. sourcemap: environment.config.command === "build" ? !!environment.config.build.sourcemap : true,
  22780. tsconfig: false
  22781. });
  22782. if (result.errors.length > 0) throw new AggregateError(result.errors, "oxc transform error");
  22783. return {
  22784. code: result.code,
  22785. map: result.map || null
  22786. };
  22787. }
  22788. /**
  22789. * Like `JSON.stringify` but keeps raw string values as a literal
  22790. * in the generated code. For example: `"window"` would refer to
  22791. * the global `window` object directly.
  22792. */
  22793. function serializeDefine(define) {
  22794. let res = `{`;
  22795. const keys = Object.keys(define).sort();
  22796. for (let i = 0; i < keys.length; i++) {
  22797. const key = keys[i];
  22798. const val = define[key];
  22799. res += `${JSON.stringify(key)}: ${handleDefineValue(val)}`;
  22800. if (i !== keys.length - 1) res += `, `;
  22801. }
  22802. return res + `}`;
  22803. }
  22804. function handleDefineValue(value) {
  22805. if (typeof value === "undefined") return "undefined";
  22806. if (typeof value === "string") return value;
  22807. return JSON.stringify(value);
  22808. }
  22809. //#endregion
  22810. //#region src/node/plugins/clientInjections.ts
  22811. const normalizedClientEntry$1 = normalizePath(CLIENT_ENTRY);
  22812. const normalizedEnvEntry$1 = normalizePath(ENV_ENTRY);
  22813. /**
  22814. * some values used by the client needs to be dynamically injected by the server
  22815. * @server-only
  22816. */
  22817. function clientInjectionsPlugin(config) {
  22818. let injectConfigValues;
  22819. const getDefineReplacer = perEnvironmentState((environment) => {
  22820. const userDefine = {};
  22821. for (const key in environment.config.define) if (!key.startsWith("import.meta.env.")) userDefine[key] = environment.config.define[key];
  22822. const serializedDefines = serializeDefine(userDefine);
  22823. const definesReplacement = () => serializedDefines;
  22824. return (code) => code.replace(`__DEFINES__`, definesReplacement);
  22825. });
  22826. return {
  22827. name: "vite:client-inject",
  22828. async buildStart() {
  22829. injectConfigValues = await createClientConfigValueReplacer(config);
  22830. },
  22831. async transform(code, id) {
  22832. const ssr = this.environment.config.consumer === "server";
  22833. const cleanId = cleanUrl(id);
  22834. if (cleanId === normalizedClientEntry$1 || cleanId === normalizedEnvEntry$1) return getDefineReplacer(this)(injectConfigValues(code));
  22835. else if (!ssr && code.includes("process.env.NODE_ENV")) {
  22836. const nodeEnv = this.environment.config.define?.["process.env.NODE_ENV"] || JSON.stringify(process.env.NODE_ENV || config.mode);
  22837. return await replaceDefine(this.environment, code, id, {
  22838. "process.env.NODE_ENV": nodeEnv,
  22839. "global.process.env.NODE_ENV": nodeEnv,
  22840. "globalThis.process.env.NODE_ENV": nodeEnv
  22841. });
  22842. }
  22843. }
  22844. };
  22845. }
  22846. function escapeReplacement(value) {
  22847. const jsonValue = JSON.stringify(value);
  22848. return () => jsonValue;
  22849. }
  22850. async function createClientConfigValueReplacer(config) {
  22851. const resolvedServerHostname = (await resolveHostname(config.server.host)).name;
  22852. const resolvedServerPort = config.server.port;
  22853. const devBase = config.base;
  22854. const serverHost = `${resolvedServerHostname}:${resolvedServerPort}${devBase}`;
  22855. let hmrConfig = config.server.hmr;
  22856. hmrConfig = isObject$1(hmrConfig) ? hmrConfig : void 0;
  22857. const host = hmrConfig?.host || null;
  22858. const protocol = hmrConfig?.protocol || null;
  22859. const timeout = hmrConfig?.timeout || 3e4;
  22860. const overlay = hmrConfig?.overlay !== false;
  22861. const isHmrServerSpecified = !!hmrConfig?.server;
  22862. const hmrConfigName = path.basename(config.configFile || "vite.config.js");
  22863. let port = hmrConfig?.clientPort || hmrConfig?.port || null;
  22864. if (config.server.middlewareMode && !isHmrServerSpecified) port ||= 24678;
  22865. let directTarget = hmrConfig?.host || resolvedServerHostname;
  22866. directTarget += `:${hmrConfig?.port || resolvedServerPort}`;
  22867. directTarget += devBase;
  22868. let hmrBase = devBase;
  22869. if (hmrConfig?.path) hmrBase = path.posix.join(hmrBase, hmrConfig.path);
  22870. const modeReplacement = escapeReplacement(config.mode);
  22871. const baseReplacement = escapeReplacement(devBase);
  22872. const serverHostReplacement = escapeReplacement(serverHost);
  22873. const hmrProtocolReplacement = escapeReplacement(protocol);
  22874. const hmrHostnameReplacement = escapeReplacement(host);
  22875. const hmrPortReplacement = escapeReplacement(port);
  22876. const hmrDirectTargetReplacement = escapeReplacement(directTarget);
  22877. const hmrBaseReplacement = escapeReplacement(hmrBase);
  22878. const hmrTimeoutReplacement = escapeReplacement(timeout);
  22879. const hmrEnableOverlayReplacement = escapeReplacement(overlay);
  22880. const hmrConfigNameReplacement = escapeReplacement(hmrConfigName);
  22881. const wsTokenReplacement = escapeReplacement(config.webSocketToken);
  22882. const serverForwardConsoleReplacement = escapeReplacement(config.server.forwardConsole);
  22883. const bundleDevReplacement = escapeReplacement(config.experimental.bundledDev || false);
  22884. 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);
  22885. }
  22886. async function getHmrImplementation(config) {
  22887. const content = fs.readFileSync(normalizedClientEntry$1, "utf-8");
  22888. return (await createClientConfigValueReplacer(config))(content).replace(/import\s*['"]@vite\/env['"]/, "");
  22889. }
  22890. //#endregion
  22891. //#region src/node/ssr/fetchModule.ts
  22892. /**
  22893. * Fetch module information for Vite runner.
  22894. * @experimental
  22895. */
  22896. async function fetchModule(environment, url, importer, options = {}) {
  22897. if (url.startsWith("data:") || isBuiltin(environment.config.resolve.builtins, url)) return {
  22898. externalize: url,
  22899. type: "builtin"
  22900. };
  22901. const isFileUrl = url.startsWith("file://");
  22902. if (isExternalUrl(url) && !isFileUrl) return {
  22903. externalize: url,
  22904. type: "network"
  22905. };
  22906. if (!isFileUrl && importer && url[0] !== "." && url[0] !== "/") {
  22907. const { isProduction, root } = environment.config;
  22908. const { externalConditions, dedupe, preserveSymlinks } = environment.config.resolve;
  22909. const resolved = tryNodeResolve(url, importer, {
  22910. mainFields: ["main"],
  22911. conditions: externalConditions,
  22912. externalConditions,
  22913. external: [],
  22914. noExternal: [],
  22915. extensions: [
  22916. ".js",
  22917. ".cjs",
  22918. ".json"
  22919. ],
  22920. dedupe,
  22921. preserveSymlinks,
  22922. tsconfigPaths: false,
  22923. isBuild: false,
  22924. isProduction,
  22925. root,
  22926. packageCache: environment.config.packageCache,
  22927. builtins: environment.config.resolve.builtins
  22928. });
  22929. if (!resolved) {
  22930. const err = /* @__PURE__ */ new Error(`Cannot find module '${url}' imported from '${importer}'`);
  22931. err.code = "ERR_MODULE_NOT_FOUND";
  22932. throw err;
  22933. }
  22934. return {
  22935. externalize: pathToFileURL(resolved.id).toString(),
  22936. type: isFilePathESM(resolved.id, environment.config.packageCache) ? "module" : "commonjs"
  22937. };
  22938. }
  22939. url = unwrapId(url);
  22940. const mod = await environment.moduleGraph.ensureEntryFromUrl(url);
  22941. const cached = !!mod.transformResult;
  22942. if (options.cached && cached) return { cache: true };
  22943. let result = await environment.transformRequest(url);
  22944. if (!result) throw new Error(`[vite] transform failed for module '${url}'${importer ? ` imported from '${importer}'` : ""}.`);
  22945. if (options.inlineSourceMap !== false) result = inlineSourceMap(mod, result, options.startOffset);
  22946. if (result.code[0] === "#") result.code = result.code.replace(/^#!.*/, (s) => " ".repeat(s.length));
  22947. return {
  22948. code: result.code,
  22949. file: mod.file,
  22950. id: mod.id,
  22951. url: mod.url,
  22952. invalidate: !cached
  22953. };
  22954. }
  22955. const OTHER_SOURCE_MAP_REGEXP = new RegExp(`//# ${SOURCEMAPPING_URL}=data:application/json[^,]+base64,([A-Za-z0-9+/=]+)$`, "gm");
  22956. function inlineSourceMap(mod, result, startOffset) {
  22957. const map = result.map;
  22958. let code = result.code;
  22959. if (!map || !("version" in map) || code.includes("//# sourceMappingSource=vite-generated")) return result;
  22960. OTHER_SOURCE_MAP_REGEXP.lastIndex = 0;
  22961. if (OTHER_SOURCE_MAP_REGEXP.test(code)) code = code.replace(OTHER_SOURCE_MAP_REGEXP, "");
  22962. const sourceMap = startOffset ? Object.assign({}, map, { mappings: ";".repeat(startOffset) + map.mappings }) : map;
  22963. result.code = `${code.trimEnd()}\n//# sourceURL=${mod.id}\n${MODULE_RUNNER_SOURCEMAPPING_SOURCE}\n//# ${SOURCEMAPPING_URL}=${genSourceMapUrl(sourceMap)}\n`;
  22964. return result;
  22965. }
  22966. //#endregion
  22967. //#region src/node/optimizer/optimizer.ts
  22968. const debug$9 = createDebugger("vite:deps");
  22969. /**
  22970. * The amount to wait for requests to register newly found dependencies before triggering
  22971. * a re-bundle + page reload
  22972. */
  22973. const debounceMs = 100;
  22974. function createDepsOptimizer(environment) {
  22975. const { logger } = environment;
  22976. const sessionTimestamp = Date.now().toString();
  22977. let debounceProcessingHandle;
  22978. let closed = false;
  22979. const options = environment.config.optimizeDeps;
  22980. const { noDiscovery, holdUntilCrawlEnd } = options;
  22981. let metadata = initDepsOptimizerMetadata(environment, sessionTimestamp);
  22982. const depsOptimizer = {
  22983. init,
  22984. metadata,
  22985. registerMissingImport,
  22986. run: () => debouncedProcessing(0),
  22987. isOptimizedDepFile: createIsOptimizedDepFile(environment),
  22988. isOptimizedDepUrl: createIsOptimizedDepUrl(environment),
  22989. getOptimizedDepId: (depInfo) => `${depInfo.file}?v=${depInfo.browserHash}`,
  22990. close,
  22991. options
  22992. };
  22993. let newDepsDiscovered = false;
  22994. let newDepsToLog = [];
  22995. let newDepsToLogHandle;
  22996. const logNewlyDiscoveredDeps = () => {
  22997. if (newDepsToLog.length) {
  22998. logger.info(import_picocolors.default.green(`✨ new dependencies optimized: ${depsLogString(newDepsToLog)}`), { timestamp: true });
  22999. newDepsToLog = [];
  23000. }
  23001. };
  23002. let discoveredDepsWhileScanning = [];
  23003. const logDiscoveredDepsWhileScanning = () => {
  23004. if (discoveredDepsWhileScanning.length) {
  23005. logger.info(import_picocolors.default.green(`✨ discovered while scanning: ${depsLogString(discoveredDepsWhileScanning)}`), { timestamp: true });
  23006. discoveredDepsWhileScanning = [];
  23007. }
  23008. };
  23009. let depOptimizationProcessing = promiseWithResolvers();
  23010. let depOptimizationProcessingQueue = [];
  23011. const resolveEnqueuedProcessingPromises = () => {
  23012. for (const processing of depOptimizationProcessingQueue) processing.resolve();
  23013. depOptimizationProcessingQueue = [];
  23014. };
  23015. let enqueuedRerun;
  23016. let currentlyProcessing = false;
  23017. let firstRunCalled = false;
  23018. let warnAboutMissedDependencies = false;
  23019. let waitingForCrawlEnd = false;
  23020. let optimizationResult;
  23021. let discover;
  23022. async function close() {
  23023. closed = true;
  23024. await Promise.allSettled([
  23025. discover?.cancel(),
  23026. depsOptimizer.scanProcessing,
  23027. optimizationResult?.cancel()
  23028. ]);
  23029. }
  23030. let inited = false;
  23031. async function init() {
  23032. if (inited) return;
  23033. inited = true;
  23034. const cachedMetadata = await loadCachedDepOptimizationMetadata(environment);
  23035. firstRunCalled = !!cachedMetadata;
  23036. metadata = depsOptimizer.metadata = cachedMetadata || initDepsOptimizerMetadata(environment, sessionTimestamp);
  23037. if (!cachedMetadata) {
  23038. waitingForCrawlEnd = true;
  23039. currentlyProcessing = true;
  23040. const manuallyIncludedDeps = {};
  23041. await addManuallyIncludedOptimizeDeps(environment, manuallyIncludedDeps);
  23042. const manuallyIncludedDepsInfo = toDiscoveredDependencies(environment, manuallyIncludedDeps, sessionTimestamp);
  23043. for (const depInfo of Object.values(manuallyIncludedDepsInfo)) {
  23044. addOptimizedDepInfo(metadata, "discovered", {
  23045. ...depInfo,
  23046. processing: depOptimizationProcessing.promise
  23047. });
  23048. newDepsDiscovered = true;
  23049. }
  23050. environment.waitForRequestsIdle().then(onCrawlEnd);
  23051. if (noDiscovery) runOptimizer();
  23052. else depsOptimizer.scanProcessing = new Promise((resolve) => {
  23053. (async () => {
  23054. try {
  23055. debug$9?.(import_picocolors.default.green(`scanning for dependencies...`));
  23056. let deps;
  23057. try {
  23058. discover = discoverProjectDependencies(devToScanEnvironment(environment));
  23059. deps = await discover.result;
  23060. discover = void 0;
  23061. } catch (e) {
  23062. environment.logger.error(import_picocolors.default.red("(!) Failed to run dependency scan. Skipping dependency pre-bundling. " + e.stack));
  23063. return;
  23064. }
  23065. const manuallyIncluded = Object.keys(manuallyIncludedDepsInfo);
  23066. discoveredDepsWhileScanning.push(...Object.keys(metadata.discovered).filter((dep) => !deps[dep] && !manuallyIncluded.includes(dep)));
  23067. for (const id of Object.keys(deps)) if (!metadata.discovered[id]) addMissingDep(id, deps[id]);
  23068. const knownDeps = prepareKnownDeps();
  23069. startNextDiscoveredBatch();
  23070. optimizationResult = runOptimizeDeps(environment, knownDeps);
  23071. if (!holdUntilCrawlEnd) optimizationResult.result.then((result) => {
  23072. if (!waitingForCrawlEnd) return;
  23073. optimizationResult = void 0;
  23074. runOptimizer(result);
  23075. });
  23076. } catch (e) {
  23077. logger.error(e.stack || e.message);
  23078. } finally {
  23079. resolve();
  23080. depsOptimizer.scanProcessing = void 0;
  23081. }
  23082. })();
  23083. });
  23084. }
  23085. }
  23086. function startNextDiscoveredBatch() {
  23087. newDepsDiscovered = false;
  23088. depOptimizationProcessingQueue.push(depOptimizationProcessing);
  23089. depOptimizationProcessing = promiseWithResolvers();
  23090. }
  23091. function prepareKnownDeps() {
  23092. const knownDeps = {};
  23093. const metadata = depsOptimizer.metadata;
  23094. for (const dep of Object.keys(metadata.optimized)) knownDeps[dep] = { ...metadata.optimized[dep] };
  23095. for (const dep of Object.keys(metadata.discovered)) {
  23096. const { processing, ...info } = metadata.discovered[dep];
  23097. knownDeps[dep] = info;
  23098. }
  23099. return knownDeps;
  23100. }
  23101. async function runOptimizer(preRunResult) {
  23102. const isRerun = firstRunCalled;
  23103. firstRunCalled = true;
  23104. enqueuedRerun = void 0;
  23105. if (debounceProcessingHandle) clearTimeout(debounceProcessingHandle);
  23106. if (closed) {
  23107. currentlyProcessing = false;
  23108. depOptimizationProcessing.resolve();
  23109. resolveEnqueuedProcessingPromises();
  23110. return;
  23111. }
  23112. currentlyProcessing = true;
  23113. try {
  23114. let processingResult;
  23115. if (preRunResult) processingResult = preRunResult;
  23116. else {
  23117. const knownDeps = prepareKnownDeps();
  23118. startNextDiscoveredBatch();
  23119. optimizationResult = runOptimizeDeps(environment, knownDeps);
  23120. processingResult = await optimizationResult.result;
  23121. optimizationResult = void 0;
  23122. }
  23123. if (closed) {
  23124. currentlyProcessing = false;
  23125. processingResult.cancel();
  23126. resolveEnqueuedProcessingPromises();
  23127. return;
  23128. }
  23129. const newData = processingResult.metadata;
  23130. const needsInteropMismatch = findInteropMismatches(metadata.discovered, newData.optimized);
  23131. const needsReload = needsInteropMismatch.length > 0 || metadata.hash !== newData.hash || Object.keys(metadata.optimized).some((dep) => {
  23132. return metadata.optimized[dep].fileHash !== newData.optimized[dep].fileHash;
  23133. });
  23134. const commitProcessing = async () => {
  23135. await processingResult.commit();
  23136. for (const id in metadata.discovered) if (!newData.optimized[id]) addOptimizedDepInfo(newData, "discovered", metadata.discovered[id]);
  23137. if (!needsReload) {
  23138. newData.browserHash = metadata.browserHash;
  23139. for (const dep in newData.chunks) newData.chunks[dep].browserHash = metadata.browserHash;
  23140. for (const dep in newData.optimized) newData.optimized[dep].browserHash = (metadata.optimized[dep] || metadata.discovered[dep]).browserHash;
  23141. }
  23142. for (const o in newData.optimized) {
  23143. const discovered = metadata.discovered[o];
  23144. if (discovered) {
  23145. const optimized = newData.optimized[o];
  23146. discovered.browserHash = optimized.browserHash;
  23147. discovered.fileHash = optimized.fileHash;
  23148. discovered.needsInterop = optimized.needsInterop;
  23149. discovered.processing = void 0;
  23150. }
  23151. }
  23152. if (isRerun) newDepsToLog.push(...Object.keys(newData.optimized).filter((dep) => !metadata.optimized[dep]));
  23153. metadata = depsOptimizer.metadata = newData;
  23154. resolveEnqueuedProcessingPromises();
  23155. };
  23156. if (!needsReload) {
  23157. await commitProcessing();
  23158. if (!debug$9) {
  23159. if (newDepsToLogHandle) clearTimeout(newDepsToLogHandle);
  23160. newDepsToLogHandle = setTimeout(() => {
  23161. newDepsToLogHandle = void 0;
  23162. logNewlyDiscoveredDeps();
  23163. if (warnAboutMissedDependencies) {
  23164. logDiscoveredDepsWhileScanning();
  23165. logger.info(import_picocolors.default.magenta(`❗ add these dependencies to optimizeDeps.include to speed up cold start`), { timestamp: true });
  23166. warnAboutMissedDependencies = false;
  23167. }
  23168. }, 2 * debounceMs);
  23169. } else debug$9(import_picocolors.default.green(`✨ ${!isRerun ? `dependencies optimized` : `optimized dependencies unchanged`}`));
  23170. } else if (newDepsDiscovered) {
  23171. processingResult.cancel();
  23172. debug$9?.(import_picocolors.default.green(`✨ delaying reload as new dependencies have been found...`));
  23173. } else {
  23174. await commitProcessing();
  23175. if (!debug$9) {
  23176. if (newDepsToLogHandle) clearTimeout(newDepsToLogHandle);
  23177. newDepsToLogHandle = void 0;
  23178. logNewlyDiscoveredDeps();
  23179. if (warnAboutMissedDependencies) {
  23180. logDiscoveredDepsWhileScanning();
  23181. logger.info(import_picocolors.default.magenta(`❗ add these dependencies to optimizeDeps.include to avoid a full page reload during cold start`), { timestamp: true });
  23182. warnAboutMissedDependencies = false;
  23183. }
  23184. }
  23185. logger.info(import_picocolors.default.green(`✨ optimized dependencies changed. reloading`), { timestamp: true });
  23186. 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 });
  23187. fullReload();
  23188. }
  23189. } catch (e) {
  23190. logger.error(import_picocolors.default.red(`error while updating dependencies:\n${e.stack}`), {
  23191. timestamp: true,
  23192. error: e
  23193. });
  23194. resolveEnqueuedProcessingPromises();
  23195. metadata.discovered = {};
  23196. }
  23197. currentlyProcessing = false;
  23198. enqueuedRerun?.();
  23199. }
  23200. function fullReload() {
  23201. environment.moduleGraph.invalidateAll();
  23202. environment.hot.send({
  23203. type: "full-reload",
  23204. path: "*"
  23205. });
  23206. }
  23207. async function rerun() {
  23208. const depsString = depsLogString(Object.keys(metadata.discovered));
  23209. debug$9?.(import_picocolors.default.green(`new dependencies found: ${depsString}`));
  23210. runOptimizer();
  23211. }
  23212. function getDiscoveredBrowserHash(hash, deps, missing) {
  23213. return getHash(hash + JSON.stringify(deps) + JSON.stringify(missing) + sessionTimestamp);
  23214. }
  23215. function registerMissingImport(id, resolved) {
  23216. const optimized = metadata.optimized[id];
  23217. if (optimized) return optimized;
  23218. const chunk = metadata.chunks[id];
  23219. if (chunk) return chunk;
  23220. let missing = metadata.discovered[id];
  23221. if (missing) return missing;
  23222. missing = addMissingDep(id, resolved);
  23223. if (!waitingForCrawlEnd) debouncedProcessing();
  23224. return missing;
  23225. }
  23226. function addMissingDep(id, resolved) {
  23227. newDepsDiscovered = true;
  23228. return addOptimizedDepInfo(metadata, "discovered", {
  23229. id,
  23230. file: getOptimizedDepPath(environment, id),
  23231. src: resolved,
  23232. browserHash: getDiscoveredBrowserHash(metadata.hash, depsFromOptimizedDepInfo(metadata.optimized), depsFromOptimizedDepInfo(metadata.discovered)),
  23233. processing: depOptimizationProcessing.promise,
  23234. exportsData: extractExportsData(environment, resolved)
  23235. });
  23236. }
  23237. function debouncedProcessing(timeout = debounceMs) {
  23238. enqueuedRerun = void 0;
  23239. if (debounceProcessingHandle) clearTimeout(debounceProcessingHandle);
  23240. if (newDepsToLogHandle) clearTimeout(newDepsToLogHandle);
  23241. newDepsToLogHandle = void 0;
  23242. debounceProcessingHandle = setTimeout(() => {
  23243. debounceProcessingHandle = void 0;
  23244. enqueuedRerun = rerun;
  23245. if (!currentlyProcessing) enqueuedRerun();
  23246. }, timeout);
  23247. }
  23248. async function onCrawlEnd() {
  23249. waitingForCrawlEnd = false;
  23250. debug$9?.(import_picocolors.default.green(`✨ static imports crawl ended`));
  23251. if (closed) return;
  23252. await depsOptimizer.scanProcessing;
  23253. if (optimizationResult && !options.noDiscovery) {
  23254. const afterScanResult = optimizationResult.result;
  23255. optimizationResult = void 0;
  23256. const result = await afterScanResult;
  23257. currentlyProcessing = false;
  23258. const crawlDeps = Object.keys(metadata.discovered);
  23259. const scanDeps = Object.keys(result.metadata.optimized);
  23260. if (scanDeps.length === 0 && crawlDeps.length === 0) {
  23261. debug$9?.(import_picocolors.default.green(`✨ no dependencies found by the scanner or crawling static imports`));
  23262. startNextDiscoveredBatch();
  23263. runOptimizer(result);
  23264. return;
  23265. }
  23266. const needsInteropMismatch = findInteropMismatches(metadata.discovered, result.metadata.optimized);
  23267. const scannerMissedDeps = crawlDeps.some((dep) => !scanDeps.includes(dep));
  23268. if (needsInteropMismatch.length > 0 || scannerMissedDeps) {
  23269. result.cancel();
  23270. for (const dep of scanDeps) if (!crawlDeps.includes(dep)) addMissingDep(dep, result.metadata.optimized[dep].src);
  23271. if (scannerMissedDeps) debug$9?.(import_picocolors.default.yellow(`✨ new dependencies were found while crawling that weren't detected by the scanner`));
  23272. debug$9?.(import_picocolors.default.green(`✨ re-running optimizer`));
  23273. debouncedProcessing(0);
  23274. } else {
  23275. debug$9?.(import_picocolors.default.green(`✨ using post-scan optimizer result, the scanner found every used dependency`));
  23276. startNextDiscoveredBatch();
  23277. runOptimizer(result);
  23278. }
  23279. } else if (!holdUntilCrawlEnd) {
  23280. if (newDepsDiscovered) {
  23281. debug$9?.(import_picocolors.default.green(`✨ new dependencies were found while crawling static imports, re-running optimizer`));
  23282. warnAboutMissedDependencies = true;
  23283. debouncedProcessing(0);
  23284. }
  23285. } else {
  23286. const crawlDeps = Object.keys(metadata.discovered);
  23287. currentlyProcessing = false;
  23288. if (crawlDeps.length === 0) {
  23289. debug$9?.(import_picocolors.default.green(`✨ no dependencies found while crawling the static imports`));
  23290. firstRunCalled = true;
  23291. }
  23292. debouncedProcessing(0);
  23293. }
  23294. }
  23295. return depsOptimizer;
  23296. }
  23297. function createExplicitDepsOptimizer(environment) {
  23298. const depsOptimizer = {
  23299. metadata: initDepsOptimizerMetadata(environment),
  23300. isOptimizedDepFile: createIsOptimizedDepFile(environment),
  23301. isOptimizedDepUrl: createIsOptimizedDepUrl(environment),
  23302. getOptimizedDepId: (depInfo) => `${depInfo.file}?v=${depInfo.browserHash}`,
  23303. registerMissingImport: () => {
  23304. throw new Error(`Vite Internal Error: registerMissingImport is not supported in dev ${environment.name}`);
  23305. },
  23306. init,
  23307. run: () => {},
  23308. close: async () => {},
  23309. options: environment.config.optimizeDeps
  23310. };
  23311. let inited = false;
  23312. async function init() {
  23313. if (inited) return;
  23314. inited = true;
  23315. depsOptimizer.metadata = await optimizeExplicitEnvironmentDeps(environment);
  23316. }
  23317. return depsOptimizer;
  23318. }
  23319. function findInteropMismatches(discovered, optimized) {
  23320. const needsInteropMismatch = [];
  23321. for (const dep in discovered) {
  23322. const discoveredDepInfo = discovered[dep];
  23323. if (discoveredDepInfo.needsInterop === void 0) continue;
  23324. const depInfo = optimized[dep];
  23325. if (!depInfo) continue;
  23326. if (depInfo.needsInterop !== discoveredDepInfo.needsInterop) {
  23327. needsInteropMismatch.push(dep);
  23328. debug$9?.(import_picocolors.default.cyan(`✨ needsInterop mismatch detected for ${dep}`));
  23329. }
  23330. }
  23331. return needsInteropMismatch;
  23332. }
  23333. //#endregion
  23334. //#region src/node/server/moduleGraph.ts
  23335. var EnvironmentModuleNode = class {
  23336. environment;
  23337. /**
  23338. * Public served url path, starts with /
  23339. */
  23340. url;
  23341. /**
  23342. * Resolved file system path + query
  23343. */
  23344. id = null;
  23345. file = null;
  23346. type;
  23347. info;
  23348. meta;
  23349. importers = /* @__PURE__ */ new Set();
  23350. importedModules = /* @__PURE__ */ new Set();
  23351. acceptedHmrDeps = /* @__PURE__ */ new Set();
  23352. acceptedHmrExports = null;
  23353. importedBindings = null;
  23354. isSelfAccepting;
  23355. transformResult = null;
  23356. ssrModule = null;
  23357. ssrError = null;
  23358. lastHMRTimestamp = 0;
  23359. /**
  23360. * `import.meta.hot.invalidate` is called by the client.
  23361. * If there's multiple clients, multiple `invalidate` request is received.
  23362. * This property is used to dedupe those request to avoid multiple updates happening.
  23363. * @internal
  23364. */
  23365. lastHMRInvalidationReceived = false;
  23366. lastInvalidationTimestamp = 0;
  23367. /**
  23368. * If the module only needs to update its imports timestamp (e.g. within an HMR chain),
  23369. * it is considered soft-invalidated. In this state, its `transformResult` should exist,
  23370. * and the next `transformRequest` for this module will replace the timestamps.
  23371. *
  23372. * By default the value is `undefined` if it's not soft/hard-invalidated. If it gets
  23373. * soft-invalidated, this will contain the previous `transformResult` value. If it gets
  23374. * hard-invalidated, this will be set to `'HARD_INVALIDATED'`.
  23375. * @internal
  23376. */
  23377. invalidationState;
  23378. /**
  23379. * The module urls that are statically imported in the code. This information is separated
  23380. * out from `importedModules` as only importers that statically import the module can be
  23381. * soft invalidated. Other imports (e.g. watched files) needs the importer to be hard invalidated.
  23382. * @internal
  23383. */
  23384. staticImportedUrls;
  23385. /**
  23386. * @param setIsSelfAccepting - set `false` to set `isSelfAccepting` later. e.g. #7870
  23387. */
  23388. constructor(url, environment, setIsSelfAccepting = true) {
  23389. this.environment = environment;
  23390. this.url = url;
  23391. this.type = isDirectCSSRequest(url) ? "css" : "js";
  23392. if (setIsSelfAccepting) this.isSelfAccepting = false;
  23393. }
  23394. };
  23395. var EnvironmentModuleGraph = class {
  23396. environment;
  23397. urlToModuleMap = /* @__PURE__ */ new Map();
  23398. idToModuleMap = /* @__PURE__ */ new Map();
  23399. etagToModuleMap = /* @__PURE__ */ new Map();
  23400. fileToModulesMap = /* @__PURE__ */ new Map();
  23401. /**
  23402. * @internal
  23403. */
  23404. _unresolvedUrlToModuleMap = /* @__PURE__ */ new Map();
  23405. /**
  23406. * @internal
  23407. */
  23408. _resolveId;
  23409. /** @internal */
  23410. _hasResolveFailedErrorModules = /* @__PURE__ */ new Set();
  23411. constructor(environment, resolveId) {
  23412. this.environment = environment;
  23413. this._resolveId = resolveId;
  23414. }
  23415. async getModuleByUrl(rawUrl) {
  23416. rawUrl = removeImportQuery(removeTimestampQuery(rawUrl));
  23417. const mod = this._getUnresolvedUrlToModule(rawUrl);
  23418. if (mod) return mod;
  23419. const [url] = await this._resolveUrl(rawUrl);
  23420. return this.urlToModuleMap.get(url);
  23421. }
  23422. getModuleById(id) {
  23423. return this.idToModuleMap.get(removeTimestampQuery(id));
  23424. }
  23425. getModulesByFile(file) {
  23426. return this.fileToModulesMap.get(file);
  23427. }
  23428. onFileChange(file) {
  23429. const mods = this.getModulesByFile(file);
  23430. if (mods) {
  23431. const seen = /* @__PURE__ */ new Set();
  23432. mods.forEach((mod) => {
  23433. this.invalidateModule(mod, seen);
  23434. });
  23435. }
  23436. }
  23437. onFileDelete(file) {
  23438. const mods = this.getModulesByFile(file);
  23439. if (mods) mods.forEach((mod) => {
  23440. mod.importedModules.forEach((importedMod) => {
  23441. importedMod.importers.delete(mod);
  23442. });
  23443. });
  23444. }
  23445. invalidateModule(mod, seen = /* @__PURE__ */ new Set(), timestamp = monotonicDateNow(), isHmr = false, softInvalidate = false) {
  23446. const prevInvalidationState = mod.invalidationState;
  23447. if (softInvalidate) mod.invalidationState ??= mod.transformResult ?? "HARD_INVALIDATED";
  23448. else mod.invalidationState = "HARD_INVALIDATED";
  23449. if (seen.has(mod) && prevInvalidationState === mod.invalidationState) return;
  23450. seen.add(mod);
  23451. if (isHmr) {
  23452. mod.lastHMRTimestamp = timestamp;
  23453. mod.lastHMRInvalidationReceived = false;
  23454. } else mod.lastInvalidationTimestamp = timestamp;
  23455. const etag = mod.transformResult?.etag;
  23456. if (etag) this.etagToModuleMap.delete(etag);
  23457. mod.transformResult = null;
  23458. mod.ssrModule = null;
  23459. mod.ssrError = null;
  23460. mod.importers.forEach((importer) => {
  23461. if (!importer.acceptedHmrDeps.has(mod)) {
  23462. const shouldSoftInvalidateImporter = (importer.staticImportedUrls?.has(mod.url) || softInvalidate) && importer.type === "js";
  23463. this.invalidateModule(importer, seen, timestamp, isHmr, shouldSoftInvalidateImporter);
  23464. }
  23465. });
  23466. this._hasResolveFailedErrorModules.delete(mod);
  23467. }
  23468. invalidateAll() {
  23469. const timestamp = monotonicDateNow();
  23470. const seen = /* @__PURE__ */ new Set();
  23471. this.idToModuleMap.forEach((mod) => {
  23472. this.invalidateModule(mod, seen, timestamp);
  23473. });
  23474. }
  23475. /**
  23476. * Update the module graph based on a module's updated imports information
  23477. * If there are dependencies that no longer have any importers, they are
  23478. * returned as a Set.
  23479. *
  23480. * @param staticImportedUrls Subset of `importedModules` where they're statically imported in code.
  23481. * This is only used for soft invalidations so `undefined` is fine but may cause more runtime processing.
  23482. */
  23483. async updateModuleInfo(mod, importedModules, importedBindings, acceptedModules, acceptedExports, isSelfAccepting, staticImportedUrls) {
  23484. mod.isSelfAccepting = isSelfAccepting;
  23485. const prevImports = mod.importedModules;
  23486. let noLongerImported;
  23487. let resolvePromises = [];
  23488. let resolveResults = new Array(importedModules.size);
  23489. let index = 0;
  23490. for (const imported of importedModules) {
  23491. const nextIndex = index++;
  23492. if (typeof imported === "string") resolvePromises.push(this.ensureEntryFromUrl(imported).then((dep) => {
  23493. dep.importers.add(mod);
  23494. resolveResults[nextIndex] = dep;
  23495. }));
  23496. else {
  23497. imported.importers.add(mod);
  23498. resolveResults[nextIndex] = imported;
  23499. }
  23500. }
  23501. if (resolvePromises.length) await Promise.all(resolvePromises);
  23502. mod.importedModules = new Set(resolveResults);
  23503. prevImports.forEach((dep) => {
  23504. if (!mod.importedModules.has(dep)) {
  23505. dep.importers.delete(mod);
  23506. if (!dep.importers.size) (noLongerImported || (noLongerImported = /* @__PURE__ */ new Set())).add(dep);
  23507. }
  23508. });
  23509. resolvePromises = [];
  23510. resolveResults = new Array(acceptedModules.size);
  23511. index = 0;
  23512. for (const accepted of acceptedModules) {
  23513. const nextIndex = index++;
  23514. if (typeof accepted === "string") resolvePromises.push(this.ensureEntryFromUrl(accepted).then((dep) => {
  23515. resolveResults[nextIndex] = dep;
  23516. }));
  23517. else resolveResults[nextIndex] = accepted;
  23518. }
  23519. if (resolvePromises.length) await Promise.all(resolvePromises);
  23520. mod.acceptedHmrDeps = new Set(resolveResults);
  23521. mod.staticImportedUrls = staticImportedUrls;
  23522. mod.acceptedHmrExports = acceptedExports;
  23523. mod.importedBindings = importedBindings;
  23524. return noLongerImported;
  23525. }
  23526. async ensureEntryFromUrl(rawUrl, setIsSelfAccepting = true) {
  23527. return this._ensureEntryFromUrl(rawUrl, setIsSelfAccepting);
  23528. }
  23529. /**
  23530. * @internal
  23531. */
  23532. async _ensureEntryFromUrl(rawUrl, setIsSelfAccepting = true, resolved) {
  23533. rawUrl = removeImportQuery(removeTimestampQuery(rawUrl));
  23534. let mod = this._getUnresolvedUrlToModule(rawUrl);
  23535. if (mod) return mod;
  23536. const modPromise = (async () => {
  23537. const [url, resolvedId, meta] = await this._resolveUrl(rawUrl, resolved);
  23538. mod = this.idToModuleMap.get(resolvedId);
  23539. if (!mod) {
  23540. mod = new EnvironmentModuleNode(url, this.environment, setIsSelfAccepting);
  23541. if (meta) mod.meta = meta;
  23542. this.urlToModuleMap.set(url, mod);
  23543. mod.id = resolvedId;
  23544. this.idToModuleMap.set(resolvedId, mod);
  23545. const file = mod.file = cleanUrl(resolvedId);
  23546. let fileMappedModules = this.fileToModulesMap.get(file);
  23547. if (!fileMappedModules) {
  23548. fileMappedModules = /* @__PURE__ */ new Set();
  23549. this.fileToModulesMap.set(file, fileMappedModules);
  23550. }
  23551. fileMappedModules.add(mod);
  23552. } else if (!this.urlToModuleMap.has(url)) this.urlToModuleMap.set(url, mod);
  23553. this._setUnresolvedUrlToModule(rawUrl, mod);
  23554. return mod;
  23555. })();
  23556. this._setUnresolvedUrlToModule(rawUrl, modPromise);
  23557. return modPromise;
  23558. }
  23559. createFileOnlyEntry(file) {
  23560. file = normalizePath(file);
  23561. let fileMappedModules = this.fileToModulesMap.get(file);
  23562. if (!fileMappedModules) {
  23563. fileMappedModules = /* @__PURE__ */ new Set();
  23564. this.fileToModulesMap.set(file, fileMappedModules);
  23565. }
  23566. const url = `${FS_PREFIX}${file}`;
  23567. for (const m of fileMappedModules) if ((m.url === url || m.id === file) && m.type === "asset") return m;
  23568. const mod = new EnvironmentModuleNode(url, this.environment);
  23569. mod.type = "asset";
  23570. mod.file = file;
  23571. fileMappedModules.add(mod);
  23572. return mod;
  23573. }
  23574. async resolveUrl(url) {
  23575. url = removeImportQuery(removeTimestampQuery(url));
  23576. const mod = await this._getUnresolvedUrlToModule(url);
  23577. if (mod?.id) return [
  23578. mod.url,
  23579. mod.id,
  23580. mod.meta
  23581. ];
  23582. return this._resolveUrl(url);
  23583. }
  23584. updateModuleTransformResult(mod, result) {
  23585. if (this.environment === "client") {
  23586. const prevEtag = mod.transformResult?.etag;
  23587. if (prevEtag) this.etagToModuleMap.delete(prevEtag);
  23588. if (result?.etag) this.etagToModuleMap.set(result.etag, mod);
  23589. }
  23590. mod.transformResult = result;
  23591. }
  23592. getModuleByEtag(etag) {
  23593. return this.etagToModuleMap.get(etag);
  23594. }
  23595. /**
  23596. * @internal
  23597. */
  23598. _getUnresolvedUrlToModule(url) {
  23599. return this._unresolvedUrlToModuleMap.get(url);
  23600. }
  23601. /**
  23602. * @internal
  23603. */
  23604. _setUnresolvedUrlToModule(url, mod) {
  23605. this._unresolvedUrlToModuleMap.set(url, mod);
  23606. }
  23607. /**
  23608. * @internal
  23609. */
  23610. async _resolveUrl(url, alreadyResolved) {
  23611. const resolved = alreadyResolved ?? await this._resolveId(url);
  23612. const resolvedId = resolved?.id || url;
  23613. if (url !== resolvedId && !url.includes("\0") && !url.startsWith(`virtual:`)) {
  23614. const ext = extname(cleanUrl(resolvedId));
  23615. if (ext) {
  23616. const pathname = cleanUrl(url);
  23617. if (!pathname.endsWith(ext)) url = pathname + ext + url.slice(pathname.length);
  23618. }
  23619. }
  23620. return [
  23621. url,
  23622. resolvedId,
  23623. resolved?.meta
  23624. ];
  23625. }
  23626. };
  23627. //#endregion
  23628. //#region ../../node_modules/.pnpm/totalist@3.0.1/node_modules/totalist/sync/index.mjs
  23629. function totalist(dir, callback, pre = "") {
  23630. dir = resolve$1(".", dir);
  23631. let arr = readdirSync(dir);
  23632. let i = 0, abs, stats;
  23633. for (; i < arr.length; i++) {
  23634. abs = join$1(dir, arr[i]);
  23635. stats = statSync(abs);
  23636. stats.isDirectory() ? totalist(abs, callback, join$1(pre, arr[i])) : callback(join$1(pre, arr[i]), abs, stats);
  23637. }
  23638. }
  23639. //#endregion
  23640. //#region ../../node_modules/.pnpm/@polka+url@1.0.0-next.29/node_modules/@polka/url/build.mjs
  23641. /**
  23642. * @typedef ParsedURL
  23643. * @type {import('.').ParsedURL}
  23644. */
  23645. /**
  23646. * @typedef Request
  23647. * @property {string} url
  23648. * @property {ParsedURL} _parsedUrl
  23649. */
  23650. /**
  23651. * @param {Request} req
  23652. * @returns {ParsedURL|void}
  23653. */
  23654. function parse$1(req) {
  23655. let raw = req.url;
  23656. if (raw == null) return;
  23657. let prev = req._parsedUrl;
  23658. if (prev && prev.raw === raw) return prev;
  23659. let pathname = raw, search = "", query, hash;
  23660. if (raw.length > 1) {
  23661. let idx = raw.indexOf("#", 1);
  23662. if (idx !== -1) {
  23663. hash = raw.substring(idx);
  23664. pathname = raw.substring(0, idx);
  23665. }
  23666. idx = pathname.indexOf("?", 1);
  23667. if (idx !== -1) {
  23668. search = pathname.substring(idx);
  23669. pathname = pathname.substring(0, idx);
  23670. if (search.length > 1) query = qs.parse(search.substring(1));
  23671. }
  23672. }
  23673. return req._parsedUrl = {
  23674. pathname,
  23675. search,
  23676. query,
  23677. hash,
  23678. raw
  23679. };
  23680. }
  23681. //#endregion
  23682. //#region ../../node_modules/.pnpm/sirv@3.0.2_patch_hash=c07c56eb72faea34341d465cde2314e89db472106ed378181e3447893af6bf95/node_modules/sirv/build.mjs
  23683. const noop = () => {};
  23684. function isMatch(uri, arr) {
  23685. for (let i = 0; i < arr.length; i++) if (arr[i].test(uri)) return true;
  23686. }
  23687. function toAssume(uri, extns) {
  23688. let i = 0, x, len = uri.length - 1;
  23689. if (uri.charCodeAt(len) === 47) uri = uri.substring(0, len);
  23690. let arr = [], tmp = `${uri}/index`;
  23691. for (; i < extns.length; i++) {
  23692. x = extns[i] ? `.${extns[i]}` : "";
  23693. if (uri) arr.push(uri + x);
  23694. arr.push(tmp + x);
  23695. }
  23696. return arr;
  23697. }
  23698. function viaCache(cache, uri, extns) {
  23699. let i = 0, data, arr = toAssume(uri, extns);
  23700. for (; i < arr.length; i++) if (data = cache[arr[i]]) return data;
  23701. }
  23702. function viaLocal(dir, isEtag, uri, extns, shouldServe) {
  23703. let i = 0, arr = toAssume(uri, extns);
  23704. let abs, stats, name, headers;
  23705. for (; i < arr.length; i++) {
  23706. abs = normalize(join(dir, name = arr[i]));
  23707. if (abs.startsWith(dir) && fs$1.existsSync(abs)) {
  23708. stats = fs$1.statSync(abs);
  23709. if (stats.isDirectory()) continue;
  23710. if (shouldServe && !shouldServe(abs)) continue;
  23711. headers = toHeaders(name, stats, isEtag);
  23712. headers["Cache-Control"] = isEtag ? "no-cache" : "no-store";
  23713. return {
  23714. abs,
  23715. stats,
  23716. headers
  23717. };
  23718. }
  23719. }
  23720. }
  23721. function is404(req, res) {
  23722. return res.statusCode = 404, res.end();
  23723. }
  23724. function send$1(req, res, file, stats, headers) {
  23725. let code = 200, tmp, opts = {};
  23726. headers = { ...headers };
  23727. for (let key in headers) {
  23728. tmp = res.getHeader(key);
  23729. if (tmp) headers[key] = tmp;
  23730. }
  23731. if (tmp = res.getHeader("content-type")) headers["Content-Type"] = tmp;
  23732. if (req.headers.range) {
  23733. code = 206;
  23734. let [x, y] = req.headers.range.replace("bytes=", "").split("-");
  23735. let end = opts.end = parseInt(y, 10) || stats.size - 1;
  23736. let start = opts.start = parseInt(x, 10) || 0;
  23737. if (end >= stats.size) end = stats.size - 1;
  23738. if (start >= stats.size) {
  23739. res.setHeader("Content-Range", `bytes */${stats.size}`);
  23740. res.statusCode = 416;
  23741. return res.end();
  23742. }
  23743. headers["Content-Range"] = `bytes ${start}-${end}/${stats.size}`;
  23744. headers["Content-Length"] = end - start + 1;
  23745. headers["Accept-Ranges"] = "bytes";
  23746. }
  23747. res.writeHead(code, headers);
  23748. fs$1.createReadStream(file, opts).pipe(res);
  23749. }
  23750. const ENCODING = {
  23751. ".br": "br",
  23752. ".gz": "gzip"
  23753. };
  23754. function toHeaders(name, stats, isEtag) {
  23755. let enc = ENCODING[name.slice(-3)];
  23756. let ctype = lookup(name.slice(0, enc && -3)) || "";
  23757. if (ctype === "text/html") ctype += ";charset=utf-8";
  23758. let headers = {
  23759. "Content-Length": stats.size,
  23760. "Content-Type": ctype,
  23761. "Last-Modified": stats.mtime.toUTCString()
  23762. };
  23763. if (enc) headers["Content-Encoding"] = enc;
  23764. if (isEtag) headers["ETag"] = `W/"${stats.size}-${stats.mtime.getTime()}"`;
  23765. return headers;
  23766. }
  23767. function build_default$1(dir, opts = {}) {
  23768. dir = resolve(dir || ".");
  23769. let isNotFound = opts.onNoMatch || is404;
  23770. let setHeaders = opts.setHeaders || noop;
  23771. let extensions = opts.extensions || ["html", "htm"];
  23772. let gzips = opts.gzip && extensions.map((x) => `${x}.gz`).concat("gz");
  23773. let brots = opts.brotli && extensions.map((x) => `${x}.br`).concat("br");
  23774. const FILES = {};
  23775. let fallback = "/";
  23776. let isEtag = !!opts.etag;
  23777. let isSPA = !!opts.single;
  23778. if (typeof opts.single === "string") {
  23779. let idx = opts.single.lastIndexOf(".");
  23780. fallback += !!~idx ? opts.single.substring(0, idx) : opts.single;
  23781. }
  23782. let ignores = [];
  23783. if (opts.ignores !== false) {
  23784. ignores.push(/[/]([A-Za-z\s\d~$._-]+\.\w+){1,}$/);
  23785. if (opts.dotfiles) ignores.push(/\/\.\w/);
  23786. else ignores.push(/\/\.well-known/);
  23787. [].concat(opts.ignores || []).forEach((x) => {
  23788. ignores.push(new RegExp(x, "i"));
  23789. });
  23790. }
  23791. let cc = opts.maxAge != null && `public,max-age=${opts.maxAge}`;
  23792. if (cc && opts.immutable) cc += ",immutable";
  23793. else if (cc && opts.maxAge === 0) cc += ",must-revalidate";
  23794. if (!opts.dev) totalist(dir, (name, abs, stats) => {
  23795. if (/\.well-known[\\+\/]/.test(name)) {} else if (!opts.dotfiles && /(^\.|[\\+|\/+]\.)/.test(name)) return;
  23796. let headers = toHeaders(name, stats, isEtag);
  23797. if (cc) headers["Cache-Control"] = cc;
  23798. FILES["/" + name.normalize().replace(/\\+/g, "/")] = {
  23799. abs,
  23800. stats,
  23801. headers
  23802. };
  23803. });
  23804. let lookup = opts.dev ? viaLocal.bind(0, dir.endsWith(sep) ? dir : dir + sep, isEtag) : viaCache.bind(0, FILES);
  23805. return function(req, res, next) {
  23806. let extns = [""];
  23807. let pathname = parse$1(req).pathname;
  23808. let val = req.headers["accept-encoding"] || "";
  23809. if (gzips && val.includes("gzip")) extns.unshift(...gzips);
  23810. if (brots && /(br|brotli)/i.test(val)) extns.unshift(...brots);
  23811. extns.push(...extensions);
  23812. if (pathname.indexOf("%") !== -1) try {
  23813. pathname = decodeURI(pathname);
  23814. } catch (err) {}
  23815. let data = lookup(pathname, extns, opts.shouldServe) || isSPA && !isMatch(pathname, ignores) && lookup(fallback, extns, opts.shouldServe);
  23816. if (!data) return next ? next() : isNotFound(req, res);
  23817. if (isEtag && req.headers["if-none-match"] === data.headers["ETag"]) {
  23818. res.writeHead(304);
  23819. return res.end();
  23820. }
  23821. if (gzips || brots) res.setHeader("Vary", "Accept-Encoding");
  23822. setHeaders(res, pathname, data.stats);
  23823. send$1(req, res, data.abs, data.stats, data.headers);
  23824. };
  23825. }
  23826. //#endregion
  23827. //#region src/node/server/middlewares/static.ts
  23828. const knownJavascriptExtensionRE = /\.(?:[tj]sx?|[cm][tj]s)$/;
  23829. const ERR_DENIED_FILE = "ERR_DENIED_FILE";
  23830. const sirvOptions = ({ config, getHeaders, disableFsServeCheck }) => {
  23831. return {
  23832. dev: true,
  23833. etag: true,
  23834. extensions: [],
  23835. setHeaders(res, pathname) {
  23836. if (knownJavascriptExtensionRE.test(pathname)) res.setHeader("Content-Type", "text/javascript");
  23837. const headers = getHeaders();
  23838. if (headers) for (const name in headers) res.setHeader(name, headers[name]);
  23839. },
  23840. shouldServe: disableFsServeCheck ? void 0 : (filePath) => {
  23841. const servingAccessResult = checkLoadingAccess(config, filePath);
  23842. if (servingAccessResult === "denied") {
  23843. const error = /* @__PURE__ */ new Error("denied access");
  23844. error.code = ERR_DENIED_FILE;
  23845. error.path = filePath;
  23846. throw error;
  23847. }
  23848. if (servingAccessResult === "fallback") return false;
  23849. return true;
  23850. }
  23851. };
  23852. };
  23853. function servePublicMiddleware(server, publicFiles) {
  23854. const dir = server.config.publicDir;
  23855. const serve = build_default$1(dir, sirvOptions({
  23856. config: server.config,
  23857. getHeaders: () => server.config.server.headers,
  23858. disableFsServeCheck: true
  23859. }));
  23860. const toFilePath = (url) => {
  23861. let filePath = cleanUrl(url);
  23862. if (filePath.indexOf("%") !== -1) try {
  23863. filePath = decodeURI(filePath);
  23864. } catch {}
  23865. return normalizePath(filePath);
  23866. };
  23867. return function viteServePublicMiddleware(req, res, next) {
  23868. if (publicFiles && !publicFiles.has(toFilePath(req.url)) || isImportRequest(req.url) || isInternalRequest(req.url) || urlRE$1.test(req.url)) return next();
  23869. serve(req, res, next);
  23870. };
  23871. }
  23872. function serveStaticMiddleware(server) {
  23873. const dir = server.config.root;
  23874. const serve = build_default$1(dir, sirvOptions({
  23875. config: server.config,
  23876. getHeaders: () => server.config.server.headers
  23877. }));
  23878. return function viteServeStaticMiddleware(req, res, next) {
  23879. const cleanedUrl = cleanUrl(req.url);
  23880. if (cleanedUrl.endsWith("/") || path.extname(cleanedUrl) === ".html" || isInternalRequest(req.url) || req.url?.startsWith("//")) return next();
  23881. const url = new URL(req.url, "http://example.com");
  23882. const pathname = decodeURIIfPossible(url.pathname);
  23883. if (pathname === void 0) return next();
  23884. let redirectedPathname;
  23885. for (const { find, replacement } of server.config.resolve.alias) if (typeof find === "string" ? pathname.startsWith(find) : find.test(pathname)) {
  23886. redirectedPathname = pathname.replace(find, replacement);
  23887. break;
  23888. }
  23889. if (redirectedPathname) {
  23890. if (redirectedPathname.startsWith(withTrailingSlash(dir))) redirectedPathname = redirectedPathname.slice(dir.length);
  23891. }
  23892. const resolvedPathname = redirectedPathname || pathname;
  23893. let fileUrl = path.resolve(dir, removeLeadingSlash(resolvedPathname));
  23894. if (resolvedPathname.endsWith("/") && fileUrl[fileUrl.length - 1] !== "/") fileUrl = withTrailingSlash(fileUrl);
  23895. if (redirectedPathname) {
  23896. url.pathname = encodeURI(redirectedPathname);
  23897. req.url = url.href.slice(url.origin.length);
  23898. }
  23899. try {
  23900. serve(req, res, next);
  23901. } catch (e) {
  23902. if (e && "code" in e && e.code === ERR_DENIED_FILE) {
  23903. respondWithAccessDenied(e.path, server, res);
  23904. return;
  23905. }
  23906. throw e;
  23907. }
  23908. };
  23909. }
  23910. function serveRawFsMiddleware(server) {
  23911. const serveFromRoot = build_default$1("/", sirvOptions({
  23912. config: server.config,
  23913. getHeaders: () => server.config.server.headers
  23914. }));
  23915. return function viteServeRawFsMiddleware(req, res, next) {
  23916. if (req.url.startsWith(FS_PREFIX)) {
  23917. const url = new URL(req.url, "http://example.com");
  23918. const pathname = decodeURIIfPossible(url.pathname);
  23919. if (pathname === void 0) return next();
  23920. let newPathname = pathname.slice(FS_PREFIX.length);
  23921. if (isWindows) newPathname = newPathname.replace(/^[A-Z]:/i, "");
  23922. url.pathname = encodeURI(newPathname);
  23923. req.url = url.href.slice(url.origin.length);
  23924. try {
  23925. serveFromRoot(req, res, next);
  23926. } catch (e) {
  23927. if (e && "code" in e && e.code === ERR_DENIED_FILE) {
  23928. respondWithAccessDenied(e.path, server, res);
  23929. return;
  23930. }
  23931. throw e;
  23932. }
  23933. } else next();
  23934. };
  23935. }
  23936. function isFileServingAllowed(configOrUrl, urlOrServer) {
  23937. const config = typeof urlOrServer === "string" ? configOrUrl : urlOrServer.config;
  23938. const url = typeof urlOrServer === "string" ? urlOrServer : configOrUrl;
  23939. if (!config.server.fs.strict) return true;
  23940. return isFileLoadingAllowed(config, fsPathFromUrl(url));
  23941. }
  23942. /**
  23943. * Warning: parameters are not validated, only works with normalized absolute paths
  23944. *
  23945. * @param targetPath - normalized absolute path
  23946. * @param filePath - normalized absolute path
  23947. */
  23948. function isFileInTargetPath(targetPath, filePath) {
  23949. return isSameFilePath(targetPath, filePath) || isParentDirectory(targetPath, filePath);
  23950. }
  23951. /**
  23952. * Warning: parameters are not validated, only works with normalized absolute paths
  23953. */
  23954. function isFileLoadingAllowed(config, filePath) {
  23955. const { fs } = config.server;
  23956. if (!fs.strict) return true;
  23957. const filePathWithoutTrailingSlash = filePath.endsWith("/") ? filePath.slice(0, -1) : filePath;
  23958. if (config.fsDenyGlob(filePathWithoutTrailingSlash)) return false;
  23959. if (config.safeModulePaths.has(filePath)) return true;
  23960. if (fs.allow.some((uri) => isFileInTargetPath(uri, filePath))) return true;
  23961. return false;
  23962. }
  23963. function checkLoadingAccess(config, path) {
  23964. if (isFileLoadingAllowed(config, slash(path))) return "allowed";
  23965. if (isFileReadable(path)) return "denied";
  23966. return "fallback";
  23967. }
  23968. function respondWithAccessDenied(id, server, res) {
  23969. const urlMessage = `The request id "${id}" is outside of Vite serving allow list.`;
  23970. const hintMessage = `
  23971. ${server.config.server.fs.allow.map((i) => `- ${i}`).join("\n")}
  23972. Refer to docs https://vite.dev/config/server-options.html#server-fs-allow for configurations and more details.`;
  23973. server.config.logger.error(urlMessage);
  23974. server.config.logger.warnOnce(hintMessage + "\n");
  23975. res.statusCode = 403;
  23976. res.write(renderRestrictedErrorHTML(urlMessage + "\n" + hintMessage));
  23977. res.end();
  23978. }
  23979. function renderRestrictedErrorHTML(msg) {
  23980. return String.raw`
  23981. <body>
  23982. <h1>403 Restricted</h1>
  23983. <p>${(0, import_escape_html.default)(msg).replace(/\n/g, "<br/>")}</p>
  23984. <style>
  23985. body {
  23986. padding: 1em 2em;
  23987. }
  23988. </style>
  23989. </body>
  23990. `;
  23991. }
  23992. //#endregion
  23993. //#region src/node/server/transformRequest.ts
  23994. var import_etag = /* @__PURE__ */ __toESM(require_etag(), 1);
  23995. const ERR_LOAD_URL = "ERR_LOAD_URL";
  23996. const ERR_LOAD_PUBLIC_URL = "ERR_LOAD_PUBLIC_URL";
  23997. const ERR_DENIED_ID = "ERR_DENIED_ID";
  23998. const debugLoad = createDebugger("vite:load");
  23999. const debugTransform = createDebugger("vite:transform");
  24000. const debugCache$1 = createDebugger("vite:cache");
  24001. function transformRequest(environment, url, options = {}) {
  24002. if (environment._closing && environment.config.dev.recoverable) throwClosedServerError();
  24003. const timestamp = monotonicDateNow();
  24004. url = removeTimestampQuery(url);
  24005. const pending = environment._pendingRequests.get(url);
  24006. if (pending) return environment.moduleGraph.getModuleByUrl(url).then((module) => {
  24007. if (!module || pending.timestamp > module.lastInvalidationTimestamp) return pending.request;
  24008. else {
  24009. pending.abort();
  24010. return transformRequest(environment, url, options);
  24011. }
  24012. });
  24013. const request = doTransform(environment, url, options, timestamp);
  24014. let cleared = false;
  24015. const clearCache = () => {
  24016. if (!cleared) {
  24017. environment._pendingRequests.delete(url);
  24018. cleared = true;
  24019. }
  24020. };
  24021. environment._pendingRequests.set(url, {
  24022. request,
  24023. timestamp,
  24024. abort: clearCache
  24025. });
  24026. return request.finally(clearCache);
  24027. }
  24028. async function doTransform(environment, url, options, timestamp) {
  24029. const { pluginContainer } = environment;
  24030. let module = await environment.moduleGraph.getModuleByUrl(url);
  24031. if (module) {
  24032. const cached = await getCachedTransformResult(environment, url, module, timestamp);
  24033. if (cached) return cached;
  24034. }
  24035. const resolved = module ? void 0 : await pluginContainer.resolveId(url, void 0) ?? void 0;
  24036. const id = module?.id ?? resolved?.id ?? url;
  24037. module ??= environment.moduleGraph.getModuleById(id);
  24038. if (module) {
  24039. await environment.moduleGraph._ensureEntryFromUrl(url, void 0, resolved);
  24040. const cached = await getCachedTransformResult(environment, url, module, timestamp);
  24041. if (cached) return cached;
  24042. }
  24043. const result = loadAndTransform(environment, id, url, options, timestamp, module, resolved);
  24044. const { depsOptimizer } = environment;
  24045. if (!depsOptimizer?.isOptimizedDepFile(id)) environment._registerRequestProcessing(id, () => result);
  24046. return result;
  24047. }
  24048. async function getCachedTransformResult(environment, url, module, timestamp) {
  24049. const prettyUrl = debugCache$1 ? prettifyUrl(url, environment.config.root) : "";
  24050. const softInvalidatedTransformResult = await handleModuleSoftInvalidation(environment, module, timestamp);
  24051. if (softInvalidatedTransformResult) {
  24052. debugCache$1?.(`[memory-hmr] ${prettyUrl}`);
  24053. return softInvalidatedTransformResult;
  24054. }
  24055. const cached = module.transformResult;
  24056. if (cached) {
  24057. debugCache$1?.(`[memory] ${prettyUrl}`);
  24058. return cached;
  24059. }
  24060. }
  24061. async function loadAndTransform(environment, id, url, options, timestamp, mod, resolved) {
  24062. const { config, pluginContainer, logger } = environment;
  24063. const prettyUrl = debugLoad || debugTransform ? prettifyUrl(url, config.root) : "";
  24064. const moduleGraph = environment.moduleGraph;
  24065. if (options.allowId && !options.allowId(id)) {
  24066. const err = /* @__PURE__ */ new Error(`Denied ID ${id}`);
  24067. err.code = ERR_DENIED_ID;
  24068. err.id = id;
  24069. throw err;
  24070. }
  24071. let code = null;
  24072. let map = null;
  24073. let moduleType;
  24074. const loadStart = debugLoad ? performance$1.now() : 0;
  24075. const loadResult = await pluginContainer.load(id);
  24076. if (loadResult == null) {
  24077. const file = cleanUrl(id);
  24078. if (environment.config.consumer === "server" || isFileLoadingAllowed(environment.getTopLevelConfig(), slash(file))) {
  24079. try {
  24080. code = await fsp.readFile(file, "utf-8");
  24081. debugLoad?.(`${timeFrom(loadStart)} [fs] ${prettyUrl}`);
  24082. } catch (e) {
  24083. if (e.code !== "ENOENT" && e.code !== "EISDIR") throw e;
  24084. }
  24085. if (code != null && environment.pluginContainer.watcher) ensureWatchedFile(environment.pluginContainer.watcher, file, config.root);
  24086. }
  24087. if (code) try {
  24088. const extracted = extractSourcemapFromFile(code, file);
  24089. if (extracted) {
  24090. code = extracted.code;
  24091. map = extracted.map;
  24092. }
  24093. } catch (e) {
  24094. logger.warn(`Failed to load source map for ${file}.\n${e}`, { timestamp: true });
  24095. }
  24096. } else {
  24097. debugLoad?.(`${timeFrom(loadStart)} [plugin] ${prettyUrl}`);
  24098. if (isObject$1(loadResult)) {
  24099. code = loadResult.code;
  24100. map = loadResult.map;
  24101. moduleType = loadResult.moduleType;
  24102. } else code = loadResult;
  24103. }
  24104. if (code == null) {
  24105. const isPublicFile = checkPublicFile(url, environment.getTopLevelConfig());
  24106. let publicDirName = path.relative(config.root, config.publicDir);
  24107. if (publicDirName[0] !== ".") publicDirName = "/" + publicDirName;
  24108. 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?`;
  24109. const importerMod = moduleGraph.idToModuleMap.get(id)?.importers.values().next().value;
  24110. const importer = importerMod?.file || importerMod?.url;
  24111. const err = /* @__PURE__ */ new Error(`Failed to load url ${url} (resolved id: ${id})${importer ? ` in ${importer}` : ""}. ${msg}`);
  24112. err.code = isPublicFile ? ERR_LOAD_PUBLIC_URL : ERR_LOAD_URL;
  24113. throw err;
  24114. }
  24115. if (moduleType === void 0) {
  24116. const guessedModuleType = getModuleTypeFromId(id);
  24117. if (guessedModuleType && guessedModuleType !== "js") moduleType = guessedModuleType;
  24118. }
  24119. if (environment._closing && environment.config.dev.recoverable) throwClosedServerError();
  24120. mod ??= await moduleGraph._ensureEntryFromUrl(url, void 0, resolved);
  24121. const transformStart = debugTransform ? performance$1.now() : 0;
  24122. const transformResult = await pluginContainer.transform(code, id, {
  24123. inMap: map,
  24124. moduleType
  24125. });
  24126. const originalCode = code;
  24127. if (transformResult.code === originalCode) debugTransform?.(timeFrom(transformStart) + import_picocolors.default.dim(` [skipped] ${prettyUrl}`));
  24128. else {
  24129. debugTransform?.(`${timeFrom(transformStart)} ${prettyUrl}`);
  24130. code = transformResult.code;
  24131. map = transformResult.map;
  24132. }
  24133. let normalizedMap;
  24134. if (typeof map === "string") normalizedMap = JSON.parse(map);
  24135. else if (map) normalizedMap = map;
  24136. else normalizedMap = null;
  24137. if (normalizedMap && "version" in normalizedMap && mod.file) {
  24138. if (normalizedMap.mappings) await injectSourcesContent(normalizedMap, mod.file, logger);
  24139. const sourcemapPath = `${mod.file}.map`;
  24140. applySourcemapIgnoreList(normalizedMap, sourcemapPath, config.server.sourcemapIgnoreList, logger);
  24141. if (path.isAbsolute(mod.file)) {
  24142. let modDirname;
  24143. for (let sourcesIndex = 0; sourcesIndex < normalizedMap.sources.length; ++sourcesIndex) {
  24144. const sourcePath = normalizedMap.sources[sourcesIndex];
  24145. if (sourcePath) {
  24146. if (path.isAbsolute(sourcePath)) {
  24147. modDirname ??= path.dirname(mod.file);
  24148. normalizedMap.sources[sourcesIndex] = path.relative(modDirname, sourcePath);
  24149. }
  24150. }
  24151. }
  24152. }
  24153. }
  24154. if (environment._closing && environment.config.dev.recoverable) throwClosedServerError();
  24155. const topLevelConfig = environment.getTopLevelConfig();
  24156. const result = environment.config.dev.moduleRunnerTransform ? await ssrTransform(code, normalizedMap, url, originalCode, { json: { stringify: topLevelConfig.json.stringify === true && topLevelConfig.json.namedExports !== true } }) : {
  24157. code,
  24158. map: normalizedMap,
  24159. etag: (0, import_etag.default)(code, { weak: true })
  24160. };
  24161. if (timestamp > mod.lastInvalidationTimestamp) moduleGraph.updateModuleTransformResult(mod, result);
  24162. return result;
  24163. }
  24164. /**
  24165. * When a module is soft-invalidated, we can preserve its previous `transformResult` and
  24166. * return similar code to before:
  24167. *
  24168. * - Client: We need to transform the import specifiers with new timestamps
  24169. * - SSR: We don't need to change anything as `ssrLoadModule` controls it
  24170. */
  24171. async function handleModuleSoftInvalidation(environment, mod, timestamp) {
  24172. const transformResult = mod.invalidationState;
  24173. mod.invalidationState = void 0;
  24174. if (!transformResult || transformResult === "HARD_INVALIDATED") return;
  24175. if (mod.transformResult) throw new Error(`Internal server error: Soft-invalidated module "${mod.url}" should not have existing transform result`);
  24176. let result;
  24177. if (transformResult.ssr) result = transformResult;
  24178. else {
  24179. await init;
  24180. const source = transformResult.code;
  24181. const s = new MagicString(source);
  24182. const [imports] = parse$2(source, mod.id || void 0);
  24183. for (const imp of imports) {
  24184. let rawUrl = source.slice(imp.s, imp.e);
  24185. if (rawUrl === "import.meta") continue;
  24186. const hasQuotes = rawUrl[0] === "\"" || rawUrl[0] === "'";
  24187. if (hasQuotes) rawUrl = rawUrl.slice(1, -1);
  24188. const urlWithoutTimestamp = removeTimestampQuery(rawUrl);
  24189. const hmrUrl = unwrapId(stripBase(removeImportQuery(urlWithoutTimestamp), environment.config.base));
  24190. for (const importedMod of mod.importedModules) {
  24191. if (importedMod.url !== hmrUrl) continue;
  24192. if (importedMod.lastHMRTimestamp > 0) {
  24193. const replacedUrl = injectQuery(urlWithoutTimestamp, `t=${importedMod.lastHMRTimestamp}`);
  24194. const start = hasQuotes ? imp.s + 1 : imp.s;
  24195. const end = hasQuotes ? imp.e - 1 : imp.e;
  24196. s.overwrite(start, end, replacedUrl);
  24197. }
  24198. if (imp.d === -1 && environment.config.dev.preTransformRequests) environment.warmupRequest(hmrUrl);
  24199. break;
  24200. }
  24201. }
  24202. const code = s.toString();
  24203. result = {
  24204. ...transformResult,
  24205. code,
  24206. etag: (0, import_etag.default)(code, { weak: true })
  24207. };
  24208. }
  24209. if (timestamp > mod.lastInvalidationTimestamp) environment.moduleGraph.updateModuleTransformResult(mod, result);
  24210. return result;
  24211. }
  24212. const defaultModuleTypes = {
  24213. js: "js",
  24214. mjs: "js",
  24215. cjs: "js",
  24216. jsx: "jsx",
  24217. ts: "ts",
  24218. mts: "ts",
  24219. cts: "ts",
  24220. tsx: "tsx",
  24221. json: "json",
  24222. txt: "text",
  24223. css: "css"
  24224. };
  24225. function getModuleTypeFromId(id) {
  24226. let pos = -1;
  24227. while ((pos = id.indexOf(".", pos + 1)) >= 0) {
  24228. const moduleType = defaultModuleTypes[id.slice(pos + 1)];
  24229. if (moduleType) return moduleType;
  24230. }
  24231. }
  24232. //#endregion
  24233. //#region src/node/server/warmup.ts
  24234. function warmupFiles(server, environment) {
  24235. const { root } = server.config;
  24236. mapFiles(environment.config.dev.warmup, root).then((files) => {
  24237. for (const file of files) warmupFile(server, environment, file);
  24238. });
  24239. }
  24240. async function warmupFile(server, environment, file) {
  24241. if (file.endsWith(".html")) {
  24242. const url = htmlFileToUrl(file, server.config.root);
  24243. if (url) try {
  24244. const html = await fsp.readFile(file, "utf-8");
  24245. await server.transformIndexHtml(url, html);
  24246. } catch (e) {
  24247. environment.logger.error(`Pre-transform error (${import_picocolors.default.cyan(file)}): ${e.message}`, {
  24248. error: e,
  24249. timestamp: true
  24250. });
  24251. }
  24252. } else {
  24253. const url = fileToUrl(file, server.config.root);
  24254. await environment.warmupRequest(url);
  24255. }
  24256. }
  24257. function htmlFileToUrl(file, root) {
  24258. const url = path.relative(root, file);
  24259. if (url[0] === ".") return;
  24260. return "/" + normalizePath(url);
  24261. }
  24262. function fileToUrl(file, root) {
  24263. const url = path.relative(root, file);
  24264. if (url[0] === ".") return path.posix.join(FS_PREFIX, normalizePath(file));
  24265. return "/" + normalizePath(url);
  24266. }
  24267. async function mapFiles(files, root) {
  24268. if (!files.length) return [];
  24269. const result = [];
  24270. const globs = [];
  24271. for (const file of files) if (isDynamicPattern(file)) globs.push(file);
  24272. else if (path.isAbsolute(file)) result.push(file);
  24273. else result.push(path.resolve(root, file));
  24274. if (globs.length) result.push(...await glob(globs, {
  24275. absolute: true,
  24276. cwd: root,
  24277. expandDirectories: false,
  24278. ignore: ["**/.git/**", "**/node_modules/**"]
  24279. }));
  24280. return result;
  24281. }
  24282. //#endregion
  24283. //#region src/node/server/environment.ts
  24284. var DevEnvironment = class extends BaseEnvironment {
  24285. mode = "dev";
  24286. moduleGraph;
  24287. depsOptimizer;
  24288. /**
  24289. * @internal
  24290. */
  24291. _remoteRunnerOptions;
  24292. get pluginContainer() {
  24293. if (!this._pluginContainer) throw new Error(`${this.name} environment.pluginContainer called before initialized`);
  24294. return this._pluginContainer;
  24295. }
  24296. /**
  24297. * @internal
  24298. */
  24299. _pluginContainer;
  24300. /**
  24301. * @internal
  24302. */
  24303. _closing = false;
  24304. /**
  24305. * @internal
  24306. */
  24307. _pendingRequests;
  24308. /**
  24309. * @internal
  24310. */
  24311. _crawlEndFinder;
  24312. /**
  24313. * Hot channel for this environment. If not provided or disabled,
  24314. * it will be a noop channel that does nothing.
  24315. *
  24316. * @example
  24317. * environment.hot.send({ type: 'full-reload' })
  24318. */
  24319. hot;
  24320. constructor(name, config, context) {
  24321. let options = config.environments[name];
  24322. if (!options) throw new Error(`Environment "${name}" is not defined in the config.`);
  24323. if (context.options) options = mergeConfig(options, context.options);
  24324. super(name, config, options);
  24325. this._pendingRequests = /* @__PURE__ */ new Map();
  24326. this.moduleGraph = new EnvironmentModuleGraph(name, (url) => this.pluginContainer.resolveId(url, void 0));
  24327. this._crawlEndFinder = setupOnCrawlEnd();
  24328. this._remoteRunnerOptions = context.remoteRunner ?? {};
  24329. this.hot = context.transport ? isWebSocketServer in context.transport ? context.transport : normalizeHotChannel(context.transport, context.hot) : normalizeHotChannel({}, context.hot);
  24330. this.hot.setInvokeHandler({
  24331. fetchModule: (id, importer, options) => {
  24332. return this.fetchModule(id, importer, options);
  24333. },
  24334. getBuiltins: async () => {
  24335. return this.config.resolve.builtins.map((builtin) => typeof builtin === "string" ? {
  24336. type: "string",
  24337. value: builtin
  24338. } : {
  24339. type: "RegExp",
  24340. source: builtin.source,
  24341. flags: builtin.flags
  24342. });
  24343. }
  24344. });
  24345. this.hot.on("vite:invalidate", async ({ path, message, firstInvalidatedBy }, client) => {
  24346. this.invalidateModule({
  24347. path,
  24348. message,
  24349. firstInvalidatedBy
  24350. }, client);
  24351. });
  24352. if (!context.disableDepsOptimizer) {
  24353. const { optimizeDeps } = this.config;
  24354. if (context.depsOptimizer) this.depsOptimizer = context.depsOptimizer;
  24355. else if (isDepOptimizationDisabled(optimizeDeps)) this.depsOptimizer = void 0;
  24356. else this.depsOptimizer = (optimizeDeps.noDiscovery ? createExplicitDepsOptimizer : createDepsOptimizer)(this);
  24357. }
  24358. }
  24359. async init(options) {
  24360. if (this._initiated) return;
  24361. this._initiated = true;
  24362. this._pluginContainer = await createEnvironmentPluginContainer(this, this.config.plugins, options?.watcher);
  24363. }
  24364. /**
  24365. * When the dev server is restarted, the methods are called in the following order:
  24366. * - new instance `init`
  24367. * - previous instance `close`
  24368. * - new instance `listen`
  24369. */
  24370. async listen(server) {
  24371. this.hot.listen();
  24372. await this.depsOptimizer?.init();
  24373. warmupFiles(server, this);
  24374. }
  24375. fetchModule(id, importer, options) {
  24376. return fetchModule(this, id, importer, {
  24377. ...this._remoteRunnerOptions,
  24378. ...options
  24379. });
  24380. }
  24381. async reloadModule(module) {
  24382. if (this.config.server.hmr !== false && module.file) updateModules(this, module.file, [module], monotonicDateNow());
  24383. }
  24384. transformRequest(url, options) {
  24385. return transformRequest(this, url, options);
  24386. }
  24387. async warmupRequest(url) {
  24388. try {
  24389. await this.transformRequest(url);
  24390. } catch (e) {
  24391. if (e?.code === "ERR_OUTDATED_OPTIMIZED_DEP" || e?.code === "ERR_CLOSED_SERVER") return;
  24392. this.logger.error(buildErrorMessage(e, [`Pre-transform error: ${e.message}`], false), {
  24393. error: e,
  24394. timestamp: true
  24395. });
  24396. }
  24397. }
  24398. invalidateModule(m, _client) {
  24399. const mod = this.moduleGraph.urlToModuleMap.get(m.path);
  24400. if (mod && mod.isSelfAccepting && mod.lastHMRTimestamp > 0 && !mod.lastHMRInvalidationReceived) {
  24401. mod.lastHMRInvalidationReceived = true;
  24402. this.logger.info(import_picocolors.default.yellow(`hmr invalidate `) + import_picocolors.default.dim(m.path) + (m.message ? ` ${m.message}` : ""), { timestamp: true });
  24403. const file = getShortName(mod.file, this.config.root);
  24404. updateModules(this, file, [...mod.importers].filter((imp) => imp !== mod), mod.lastHMRTimestamp, m.firstInvalidatedBy);
  24405. }
  24406. }
  24407. async close() {
  24408. this._closing = true;
  24409. this._crawlEndFinder.cancel();
  24410. await Promise.allSettled([
  24411. this.pluginContainer.close(),
  24412. this.depsOptimizer?.close(),
  24413. isWebSocketServer in this.hot ? Promise.resolve() : this.hot.close(),
  24414. (async () => {
  24415. while (this._pendingRequests.size > 0) await Promise.allSettled([...this._pendingRequests.values()].map((pending) => pending.request));
  24416. })()
  24417. ]);
  24418. }
  24419. /**
  24420. * Calling `await environment.waitForRequestsIdle(id)` will wait until all static imports
  24421. * are processed after the first transformRequest call. If called from a load or transform
  24422. * plugin hook, the id needs to be passed as a parameter to avoid deadlocks.
  24423. * Calling this function after the first static imports section of the module graph has been
  24424. * processed will resolve immediately.
  24425. * @experimental
  24426. */
  24427. waitForRequestsIdle(ignoredId) {
  24428. return this._crawlEndFinder.waitForRequestsIdle(ignoredId);
  24429. }
  24430. /**
  24431. * @internal
  24432. */
  24433. _registerRequestProcessing(id, done) {
  24434. this._crawlEndFinder.registerRequestProcessing(id, done);
  24435. }
  24436. };
  24437. const callCrawlEndIfIdleAfterMs = 50;
  24438. function setupOnCrawlEnd() {
  24439. const registeredIds = /* @__PURE__ */ new Set();
  24440. const seenIds = /* @__PURE__ */ new Set();
  24441. const onCrawlEndPromiseWithResolvers = promiseWithResolvers();
  24442. let timeoutHandle;
  24443. let cancelled = false;
  24444. function cancel() {
  24445. cancelled = true;
  24446. }
  24447. function registerRequestProcessing(id, done) {
  24448. if (!seenIds.has(id)) {
  24449. seenIds.add(id);
  24450. registeredIds.add(id);
  24451. done().catch(() => {}).finally(() => markIdAsDone(id));
  24452. }
  24453. }
  24454. function waitForRequestsIdle(ignoredId) {
  24455. if (ignoredId) {
  24456. seenIds.add(ignoredId);
  24457. markIdAsDone(ignoredId);
  24458. } else checkIfCrawlEndAfterTimeout();
  24459. return onCrawlEndPromiseWithResolvers.promise;
  24460. }
  24461. function markIdAsDone(id) {
  24462. registeredIds.delete(id);
  24463. checkIfCrawlEndAfterTimeout();
  24464. }
  24465. function checkIfCrawlEndAfterTimeout() {
  24466. if (cancelled || registeredIds.size > 0) return;
  24467. if (timeoutHandle) clearTimeout(timeoutHandle);
  24468. timeoutHandle = setTimeout(callOnCrawlEndWhenIdle, callCrawlEndIfIdleAfterMs);
  24469. }
  24470. async function callOnCrawlEndWhenIdle() {
  24471. if (cancelled || registeredIds.size > 0) return;
  24472. onCrawlEndPromiseWithResolvers.resolve();
  24473. }
  24474. return {
  24475. registerRequestProcessing,
  24476. waitForRequestsIdle,
  24477. cancel
  24478. };
  24479. }
  24480. //#endregion
  24481. //#region src/node/server/environments/fullBundleEnvironment.ts
  24482. const debug$8 = createDebugger("vite:full-bundle-mode");
  24483. var MemoryFiles = class {
  24484. files = /* @__PURE__ */ new Map();
  24485. get size() {
  24486. return this.files.size;
  24487. }
  24488. get(file) {
  24489. const result = this.files.get(file);
  24490. if (result === void 0) return;
  24491. if (typeof result === "function") {
  24492. const content = result();
  24493. this.files.set(file, content);
  24494. return content;
  24495. }
  24496. return result;
  24497. }
  24498. set(file, content) {
  24499. this.files.set(file, content);
  24500. }
  24501. has(file) {
  24502. return this.files.has(file);
  24503. }
  24504. clear() {
  24505. this.files.clear();
  24506. }
  24507. };
  24508. var FullBundleDevEnvironment = class extends DevEnvironment {
  24509. devEngine;
  24510. clients = new Clients();
  24511. invalidateCalledModules = /* @__PURE__ */ new Map();
  24512. debouncedFullReload = debounce(20, () => {
  24513. this.hot.send({
  24514. type: "full-reload",
  24515. path: "*"
  24516. });
  24517. this.logger.info(import_picocolors.default.green(`page reload`), { timestamp: true });
  24518. });
  24519. memoryFiles = new MemoryFiles();
  24520. constructor(name, config, context) {
  24521. if (name !== "client") throw new Error("currently full bundle mode is only available for client environment");
  24522. super(name, config, {
  24523. ...context,
  24524. disableDepsOptimizer: true
  24525. });
  24526. }
  24527. async listen(_server) {
  24528. this.hot.listen();
  24529. debug$8?.("INITIAL: setup bundle options");
  24530. const rollupOptions = await this.getRolldownOptions();
  24531. if (Array.isArray(rollupOptions.output) && rollupOptions.output.length > 1) throw new Error("multiple output options are not supported in dev mode");
  24532. const outputOptions = Array.isArray(rollupOptions.output) ? rollupOptions.output[0] : rollupOptions.output;
  24533. this.hot.on("vite:module-loaded", (payload, client) => {
  24534. const clientId = this.clients.setupIfNeeded(client);
  24535. this.devEngine.registerModules(clientId, payload.modules);
  24536. });
  24537. this.hot.on("vite:client:disconnect", (_payload, client) => {
  24538. const clientId = this.clients.delete(client);
  24539. if (clientId) this.devEngine.removeClient(clientId);
  24540. });
  24541. this.devEngine = await dev(rollupOptions, outputOptions, {
  24542. onHmrUpdates: (result) => {
  24543. if (result instanceof Error) {
  24544. for (const client of this.clients.getAll()) client.send({
  24545. type: "error",
  24546. err: prepareError(result)
  24547. });
  24548. return;
  24549. }
  24550. const { updates, changedFiles } = result;
  24551. if (changedFiles.length === 0) return;
  24552. if (updates.every((update) => update.update.type === "Noop")) {
  24553. debug$8?.(`ignored file change for ${changedFiles.join(", ")}`);
  24554. return;
  24555. }
  24556. for (const { clientId, update } of updates) {
  24557. const client = this.clients.get(clientId);
  24558. if (client) {
  24559. this.invalidateCalledModules.get(client)?.clear();
  24560. this.handleHmrOutput(client, changedFiles, update);
  24561. }
  24562. }
  24563. },
  24564. onOutput: (result) => {
  24565. if (result instanceof Error) {
  24566. this.logger.error(import_picocolors.default.red(`✘ Build error: ${result.message}`), { error: result });
  24567. this.hot.send({
  24568. type: "error",
  24569. err: prepareError(result)
  24570. });
  24571. return;
  24572. }
  24573. for (const outputFile of result.output) this.memoryFiles.set(outputFile.fileName, () => {
  24574. const source = outputFile.type === "chunk" ? outputFile.code : outputFile.source;
  24575. return {
  24576. source,
  24577. etag: (0, import_etag.default)(Buffer.from(source), { weak: true })
  24578. };
  24579. });
  24580. },
  24581. watch: { skipWrite: true }
  24582. });
  24583. debug$8?.("INITIAL: setup dev engine");
  24584. this.devEngine.run().then(() => {
  24585. debug$8?.("INITIAL: run done");
  24586. }, (e) => {
  24587. debug$8?.("INITIAL: run error", e);
  24588. });
  24589. this.waitForInitialBuildFinish().then(() => {
  24590. debug$8?.("INITIAL: build done");
  24591. this.hot.send({
  24592. type: "full-reload",
  24593. path: "*"
  24594. });
  24595. });
  24596. }
  24597. async waitForInitialBuildFinish() {
  24598. await this.devEngine.ensureCurrentBuildFinish();
  24599. while (this.memoryFiles.size === 0) {
  24600. await setTimeout$1(10);
  24601. await this.devEngine.ensureCurrentBuildFinish();
  24602. }
  24603. }
  24604. async warmupRequest(_url) {}
  24605. invalidateModule(m, client) {
  24606. (async () => {
  24607. const invalidateCalledModules = this.invalidateCalledModules.get(client);
  24608. if (invalidateCalledModules?.has(m.path)) {
  24609. debug$8?.(`INVALIDATE: invalidate received from ${m.path}, but ignored because it was already invalidated`);
  24610. return;
  24611. }
  24612. debug$8?.(`INVALIDATE: invalidate received from ${m.path}, re-triggering HMR`);
  24613. if (!invalidateCalledModules) this.invalidateCalledModules.set(client, /* @__PURE__ */ new Set([]));
  24614. this.invalidateCalledModules.get(client).add(m.path);
  24615. let update;
  24616. try {
  24617. update = (await this.devEngine.invalidate(m.path, m.firstInvalidatedBy)).find((u) => this.clients.get(u.clientId) === client)?.update;
  24618. } catch (e) {
  24619. client.send({
  24620. type: "error",
  24621. err: prepareError(e)
  24622. });
  24623. return;
  24624. }
  24625. if (!update) return;
  24626. 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 });
  24627. this.handleHmrOutput(client, [m.path], update, { firstInvalidatedBy: m.firstInvalidatedBy });
  24628. })();
  24629. }
  24630. async triggerBundleRegenerationIfStale() {
  24631. const bundleState = await this.devEngine.getBundleState();
  24632. const shouldTrigger = bundleState.hasStaleOutput && !bundleState.lastFullBuildFailed;
  24633. if (shouldTrigger) {
  24634. this.devEngine.ensureLatestBuildOutput().then(() => {
  24635. this.debouncedFullReload();
  24636. });
  24637. debug$8?.(`TRIGGER: access to stale bundle, triggered bundle re-generation`);
  24638. }
  24639. return shouldTrigger;
  24640. }
  24641. async close() {
  24642. this.memoryFiles.clear();
  24643. await Promise.all([super.close(), this.devEngine.close()]);
  24644. }
  24645. async getRolldownOptions() {
  24646. const chunkMetadataMap = new ChunkMetadataMap();
  24647. const rolldownOptions = resolveRolldownOptions(this, chunkMetadataMap);
  24648. rolldownOptions.experimental ??= {};
  24649. rolldownOptions.experimental.devMode = { implement: await getHmrImplementation(this.getTopLevelConfig()) };
  24650. if (rolldownOptions.optimization) rolldownOptions.optimization.inlineConst = false;
  24651. if (Array.isArray(rolldownOptions.output)) for (const output of rolldownOptions.output) {
  24652. output.entryFileNames = "assets/[name].js";
  24653. output.chunkFileNames = "assets/[name]-[hash].js";
  24654. output.assetFileNames = "assets/[name]-[hash][extname]";
  24655. output.minify = false;
  24656. output.sourcemap = true;
  24657. }
  24658. else {
  24659. rolldownOptions.output ??= {};
  24660. rolldownOptions.output.entryFileNames = "assets/[name].js";
  24661. rolldownOptions.output.chunkFileNames = "assets/[name]-[hash].js";
  24662. rolldownOptions.output.assetFileNames = "assets/[name]-[hash][extname]";
  24663. rolldownOptions.output.minify = false;
  24664. rolldownOptions.output.sourcemap = true;
  24665. }
  24666. return rolldownOptions;
  24667. }
  24668. handleHmrOutput(client, files, hmrOutput, invalidateInformation) {
  24669. if (hmrOutput.type === "Noop") return;
  24670. const shortFile = files.map((file) => getShortName(file, this.config.root)).join(", ");
  24671. if (hmrOutput.type === "FullReload") {
  24672. const reason = hmrOutput.reason ? import_picocolors.default.dim(` (${hmrOutput.reason})`) : "";
  24673. this.logger.info(import_picocolors.default.green(`trigger page reload `) + import_picocolors.default.dim(shortFile) + reason, {
  24674. clear: !invalidateInformation,
  24675. timestamp: true
  24676. });
  24677. this.devEngine.ensureLatestBuildOutput().then(() => {
  24678. this.debouncedFullReload();
  24679. });
  24680. return;
  24681. }
  24682. debug$8?.(`handle hmr output for ${shortFile}`, {
  24683. ...hmrOutput,
  24684. code: typeof hmrOutput.code === "string" ? "[code]" : hmrOutput.code
  24685. });
  24686. this.memoryFiles.set(hmrOutput.filename, { source: hmrOutput.code });
  24687. if (hmrOutput.sourcemapFilename && hmrOutput.sourcemap) this.memoryFiles.set(hmrOutput.sourcemapFilename, { source: hmrOutput.sourcemap });
  24688. const updates = hmrOutput.hmrBoundaries.map((boundary) => {
  24689. return {
  24690. type: "js-update",
  24691. url: hmrOutput.filename,
  24692. path: boundary.boundary,
  24693. acceptedPath: boundary.acceptedVia,
  24694. firstInvalidatedBy: invalidateInformation?.firstInvalidatedBy,
  24695. timestamp: Date.now()
  24696. };
  24697. });
  24698. client.send({
  24699. type: "update",
  24700. updates
  24701. });
  24702. this.logger.info(import_picocolors.default.green(`hmr update `) + import_picocolors.default.dim([...new Set(updates.map((u) => u.path))].join(", ")), {
  24703. clear: !invalidateInformation,
  24704. timestamp: true
  24705. });
  24706. }
  24707. };
  24708. var Clients = class {
  24709. clientToId = /* @__PURE__ */ new Map();
  24710. idToClient = /* @__PURE__ */ new Map();
  24711. setupIfNeeded(client) {
  24712. const id = this.clientToId.get(client);
  24713. if (id) return id;
  24714. const newId = randomUUID();
  24715. this.clientToId.set(client, newId);
  24716. this.idToClient.set(newId, client);
  24717. return newId;
  24718. }
  24719. get(id) {
  24720. return this.idToClient.get(id);
  24721. }
  24722. getAll() {
  24723. return Array.from(this.idToClient.values());
  24724. }
  24725. delete(client) {
  24726. const id = this.clientToId.get(client);
  24727. if (id) {
  24728. this.clientToId.delete(client);
  24729. this.idToClient.delete(id);
  24730. return id;
  24731. }
  24732. }
  24733. };
  24734. function debounce(time, cb) {
  24735. let timer;
  24736. return () => {
  24737. if (timer) {
  24738. globalThis.clearTimeout(timer);
  24739. timer = null;
  24740. }
  24741. timer = globalThis.setTimeout(cb, time);
  24742. };
  24743. }
  24744. //#endregion
  24745. //#region src/node/server/middlewares/htmlFallback.ts
  24746. const debug$7 = createDebugger("vite:html-fallback");
  24747. function htmlFallbackMiddleware(root, spaFallback, clientEnvironment) {
  24748. const memoryFiles = clientEnvironment instanceof FullBundleDevEnvironment ? clientEnvironment.memoryFiles : void 0;
  24749. function checkFileExists(relativePath) {
  24750. return memoryFiles?.has(relativePath.slice(1)) ?? fs.existsSync(path.join(root, relativePath));
  24751. }
  24752. return function viteHtmlFallbackMiddleware(req, _res, next) {
  24753. 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();
  24754. const url = cleanUrl(req.url);
  24755. let pathname;
  24756. try {
  24757. pathname = decodeURIComponent(url);
  24758. } catch {
  24759. return next();
  24760. }
  24761. if (pathname.endsWith(".html")) {
  24762. if (checkFileExists(pathname)) {
  24763. debug$7?.(`Rewriting ${req.method} ${req.url} to ${url}`);
  24764. req.url = url;
  24765. return next();
  24766. }
  24767. } else if (pathname.endsWith("/")) {
  24768. if (checkFileExists(joinUrlSegments(pathname, "index.html"))) {
  24769. const newUrl = url + "index.html";
  24770. debug$7?.(`Rewriting ${req.method} ${req.url} to ${newUrl}`);
  24771. req.url = newUrl;
  24772. return next();
  24773. }
  24774. } else if (checkFileExists(pathname + ".html")) {
  24775. const newUrl = url + ".html";
  24776. debug$7?.(`Rewriting ${req.method} ${req.url} to ${newUrl}`);
  24777. req.url = newUrl;
  24778. return next();
  24779. }
  24780. if (spaFallback) {
  24781. debug$7?.(`Rewriting ${req.method} ${req.url} to /index.html`);
  24782. req.url = "/index.html";
  24783. }
  24784. next();
  24785. };
  24786. }
  24787. //#endregion
  24788. //#region src/node/server/send.ts
  24789. const debug$6 = createDebugger("vite:send", { onlyWhenFocused: true });
  24790. const alias = {
  24791. js: "text/javascript",
  24792. css: "text/css",
  24793. html: "text/html",
  24794. json: "application/json"
  24795. };
  24796. function send(req, res, content, type, options) {
  24797. const { etag = (0, import_etag.default)(content, { weak: true }), cacheControl = "no-cache", headers, map } = options;
  24798. if (res.writableEnded) return;
  24799. if (req.headers["if-none-match"] === etag) {
  24800. res.statusCode = 304;
  24801. res.end();
  24802. return;
  24803. }
  24804. res.setHeader("Content-Type", alias[type] || type);
  24805. res.setHeader("Cache-Control", cacheControl);
  24806. res.setHeader("Etag", etag);
  24807. if (headers) for (const name in headers) res.setHeader(name, headers[name]);
  24808. if (map && "version" in map && map.mappings) {
  24809. if (type === "js" || type === "css") content = getCodeWithSourcemap(type, content.toString(), map);
  24810. } else if (type === "js" && (!map || map.mappings !== "")) {
  24811. const code = content.toString();
  24812. if (import_convert_source_map.default.mapFileCommentRegex.test(code)) debug$6?.(`Skipped injecting fallback sourcemap for ${req.url}`);
  24813. else {
  24814. const urlWithoutTimestamp = removeTimestampQuery(req.url);
  24815. content = getCodeWithSourcemap(type, code, new MagicString(code).generateMap({
  24816. source: path.basename(urlWithoutTimestamp),
  24817. hires: "boundary",
  24818. includeContent: true
  24819. }));
  24820. }
  24821. }
  24822. res.statusCode = 200;
  24823. if (req.method === "HEAD") res.end();
  24824. else res.end(content);
  24825. }
  24826. //#endregion
  24827. //#region src/node/server/middlewares/transform.ts
  24828. const debugCache = createDebugger("vite:cache");
  24829. const knownIgnoreList = new Set(["/", "/favicon.ico"]);
  24830. const documentFetchDests = new Set([
  24831. "document",
  24832. "iframe",
  24833. "frame",
  24834. "fencedframe"
  24835. ]);
  24836. function isDocumentFetchDest(req) {
  24837. const fetchDest = req.headers["sec-fetch-dest"];
  24838. return fetchDest !== void 0 && documentFetchDests.has(fetchDest);
  24839. }
  24840. const urlRE = /[?&]url\b/;
  24841. const rawRE = /[?&]raw\b/;
  24842. const inlineRE$1 = /[?&]inline\b/;
  24843. const svgRE = /\.svg\b/;
  24844. function isServerAccessDeniedForTransform(config, id) {
  24845. if (rawRE.test(id) || urlRE.test(id) || inlineRE$1.test(id) || svgRE.test(id)) return checkLoadingAccess(config, id) !== "allowed";
  24846. return false;
  24847. }
  24848. /**
  24849. * A middleware that short-circuits the middleware chain to serve cached transformed modules
  24850. */
  24851. function cachedTransformMiddleware(server) {
  24852. return function viteCachedTransformMiddleware(req, res, next) {
  24853. const environment = server.environments.client;
  24854. if (isDocumentFetchDest(req)) {
  24855. res.appendHeader("Vary", "Sec-Fetch-Dest");
  24856. return next();
  24857. }
  24858. const ifNoneMatch = req.headers["if-none-match"];
  24859. if (ifNoneMatch) {
  24860. const moduleByEtag = environment.moduleGraph.getModuleByEtag(ifNoneMatch);
  24861. if (moduleByEtag?.transformResult?.etag === ifNoneMatch && moduleByEtag.url === req.url) {
  24862. if (!isCSSRequest(req.url)) {
  24863. debugCache?.(`[304] ${prettifyUrl(req.url, server.config.root)}`);
  24864. res.statusCode = 304;
  24865. return res.end();
  24866. }
  24867. }
  24868. }
  24869. next();
  24870. };
  24871. }
  24872. function transformMiddleware(server) {
  24873. const { root, publicDir } = server.config;
  24874. const publicDirInRoot = publicDir.startsWith(withTrailingSlash(root));
  24875. const publicPath = `${publicDir.slice(root.length)}/`;
  24876. return async function viteTransformMiddleware(req, res, next) {
  24877. const environment = server.environments.client;
  24878. if (req.method !== "GET" && req.method !== "HEAD" || knownIgnoreList.has(req.url) || isDocumentFetchDest(req)) return next();
  24879. let url;
  24880. try {
  24881. url = decodeURI(removeTimestampQuery(req.url)).replace(NULL_BYTE_PLACEHOLDER, "\0");
  24882. } catch (e) {
  24883. if (e instanceof URIError) {
  24884. server.config.logger.warn(import_picocolors.default.yellow(`Malformed URI sequence in request URL: ${removeTimestampQuery(req.url)}`));
  24885. return next();
  24886. }
  24887. return next(e);
  24888. }
  24889. const withoutQuery = cleanUrl(url);
  24890. try {
  24891. if (withoutQuery.endsWith(".map")) if (environment.depsOptimizer?.isOptimizedDepUrl(url)) {
  24892. const sourcemapPath = url.startsWith(FS_PREFIX) ? fsPathFromId(url) : normalizePath(path.resolve(server.config.root, url.slice(1)));
  24893. try {
  24894. const map = JSON.parse(await fsp.readFile(sourcemapPath, "utf-8"));
  24895. applySourcemapIgnoreList(map, sourcemapPath, server.config.server.sourcemapIgnoreList, server.config.logger);
  24896. return send(req, res, JSON.stringify(map), "json", { headers: server.config.server.headers });
  24897. } catch {
  24898. const dummySourceMap = {
  24899. version: 3,
  24900. file: sourcemapPath.replace(/\.map$/, ""),
  24901. sources: [],
  24902. sourcesContent: [],
  24903. names: [],
  24904. mappings: ";;;;;;;;;"
  24905. };
  24906. return send(req, res, JSON.stringify(dummySourceMap), "json", {
  24907. cacheControl: "no-cache",
  24908. headers: server.config.server.headers
  24909. });
  24910. }
  24911. } else {
  24912. const originalUrl = url.replace(/\.map($|\?)/, "$1");
  24913. const map = (await environment.moduleGraph.getModuleByUrl(originalUrl))?.transformResult?.map;
  24914. if (map) return send(req, res, JSON.stringify(map), "json", { headers: server.config.server.headers });
  24915. else return next();
  24916. }
  24917. if (publicDirInRoot && url.startsWith(publicPath)) warnAboutExplicitPublicPathInUrl(url);
  24918. if (req.headers["sec-fetch-dest"] === "script" || isJSRequest(url) || isImportRequest(url) || isCSSRequest(url) || isHTMLProxy(url)) {
  24919. url = removeImportQuery(url);
  24920. url = unwrapId(url);
  24921. if (isCSSRequest(url)) {
  24922. if (req.headers.accept?.includes("text/css") && !isDirectRequest(url)) url = injectQuery(url, "direct");
  24923. const ifNoneMatch = req.headers["if-none-match"];
  24924. if (ifNoneMatch && (await environment.moduleGraph.getModuleByUrl(url))?.transformResult?.etag === ifNoneMatch) {
  24925. debugCache?.(`[304] ${prettifyUrl(url, server.config.root)}`);
  24926. res.statusCode = 304;
  24927. return res.end();
  24928. }
  24929. }
  24930. const result = await environment.transformRequest(url, { allowId(id) {
  24931. return id[0] === "\0" || !isServerAccessDeniedForTransform(server.config, id);
  24932. } });
  24933. if (result) {
  24934. const depsOptimizer = environment.depsOptimizer;
  24935. const type = isDirectCSSRequest(url) ? "css" : "js";
  24936. const isDep = DEP_VERSION_RE.test(url) || depsOptimizer?.isOptimizedDepUrl(url);
  24937. return send(req, res, result.code, type, {
  24938. etag: result.etag,
  24939. cacheControl: isDep ? "max-age=31536000,immutable" : "no-cache",
  24940. headers: server.config.server.headers,
  24941. map: result.map
  24942. });
  24943. }
  24944. }
  24945. } catch (e) {
  24946. if (e?.code === "ERR_OPTIMIZE_DEPS_PROCESSING_ERROR") {
  24947. if (!res.writableEnded) {
  24948. res.statusCode = 504;
  24949. res.statusMessage = "Optimize Deps Processing Error";
  24950. res.end();
  24951. }
  24952. server.config.logger.error(e.message);
  24953. return;
  24954. }
  24955. if (e?.code === "ERR_OUTDATED_OPTIMIZED_DEP") {
  24956. if (!res.writableEnded) {
  24957. res.statusCode = 504;
  24958. res.statusMessage = "Outdated Optimize Dep";
  24959. res.end();
  24960. }
  24961. return;
  24962. }
  24963. if (e?.code === "ERR_CLOSED_SERVER") {
  24964. if (!res.writableEnded) {
  24965. res.statusCode = 504;
  24966. res.statusMessage = "Outdated Request";
  24967. res.end();
  24968. }
  24969. return;
  24970. }
  24971. if (e?.code === "ERR_FILE_NOT_FOUND_IN_OPTIMIZED_DEP_DIR") {
  24972. if (!res.writableEnded) {
  24973. res.statusCode = 404;
  24974. res.end();
  24975. }
  24976. server.config.logger.warn(import_picocolors.default.yellow(e.message));
  24977. return;
  24978. }
  24979. if (e?.code === "ERR_LOAD_URL") return next();
  24980. if (e?.code === "ERR_DENIED_ID") {
  24981. const id = e.id;
  24982. const servingAccessResult = checkLoadingAccess(server.config, id);
  24983. if (servingAccessResult === "denied") {
  24984. respondWithAccessDenied(id, server, res);
  24985. return true;
  24986. }
  24987. if (servingAccessResult === "fallback") {
  24988. next();
  24989. return true;
  24990. }
  24991. throw new Error(`Unexpected access result for id ${id}`);
  24992. }
  24993. return next(e);
  24994. }
  24995. next();
  24996. };
  24997. function warnAboutExplicitPublicPathInUrl(url) {
  24998. let warning;
  24999. if (isImportRequest(url)) {
  25000. const rawUrl = removeImportQuery(url);
  25001. 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, "/"))}.`;
  25002. else warning = `Assets in public directory cannot be imported from JavaScript.
  25003. 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"))}.`;
  25004. } 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, "/"))}.`;
  25005. server.config.logger.warn(import_picocolors.default.yellow(warning));
  25006. }
  25007. }
  25008. //#endregion
  25009. //#region src/node/server/middlewares/indexHtml.ts
  25010. function createDevHtmlTransformFn(config) {
  25011. const [preHooks, normalHooks, postHooks] = resolveHtmlTransforms(config.plugins);
  25012. const transformHooks = [
  25013. preImportMapHook(config),
  25014. injectCspNonceMetaTagHook(config),
  25015. ...preHooks,
  25016. htmlEnvHook(config),
  25017. devHtmlHook,
  25018. ...normalHooks,
  25019. ...postHooks,
  25020. injectNonceAttributeTagHook(config),
  25021. postImportMapHook()
  25022. ];
  25023. const pluginContext = new BasicMinimalPluginContext({
  25024. ...basePluginContextMeta,
  25025. watchMode: true
  25026. }, config.logger);
  25027. return (server, url, html, originalUrl) => {
  25028. return applyHtmlTransforms(html, transformHooks, pluginContext, {
  25029. path: url,
  25030. filename: getHtmlFilename(url, server),
  25031. server,
  25032. originalUrl
  25033. });
  25034. };
  25035. }
  25036. function getHtmlFilename(url, server) {
  25037. if (url.startsWith(FS_PREFIX)) return decodeURIComponent(fsPathFromId(url));
  25038. else return decodeURIComponent(normalizePath(path.join(server.config.root, url.slice(1))));
  25039. }
  25040. function shouldPreTransform(url, config) {
  25041. return !checkPublicFile(url, config) && (isJSRequest(url) || isCSSRequest(url));
  25042. }
  25043. const wordCharRE = /\w/;
  25044. function isBareRelative(url) {
  25045. return wordCharRE.test(url[0]) && !url.includes(":");
  25046. }
  25047. const processNodeUrl = (url, useSrcSetReplacer, config, htmlPath, originalUrl, server, isClassicScriptLink) => {
  25048. const replacer = (url) => {
  25049. if (url[0] === "/" && url[1] !== "/" || (url[0] === "." || isBareRelative(url)) && originalUrl && originalUrl !== "/" && htmlPath === "/index.html") url = path.posix.join(config.base, url);
  25050. let preTransformUrl;
  25051. if (!isClassicScriptLink && shouldPreTransform(url, config)) {
  25052. if (url[0] === "/" && url[1] !== "/") preTransformUrl = url;
  25053. else if (url[0] === "." || isBareRelative(url)) preTransformUrl = path.posix.join(config.base, path.posix.dirname(htmlPath), url);
  25054. }
  25055. if (server) {
  25056. const mod = server.environments.client.moduleGraph.urlToModuleMap.get(preTransformUrl || url);
  25057. if (mod && mod.lastHMRTimestamp > 0) url = injectQuery(url, `t=${mod.lastHMRTimestamp}`);
  25058. }
  25059. if (server && preTransformUrl) {
  25060. try {
  25061. preTransformUrl = decodeURI(preTransformUrl);
  25062. } catch {
  25063. return url;
  25064. }
  25065. preTransformRequest(server, preTransformUrl, config.decodedBase);
  25066. }
  25067. return url;
  25068. };
  25069. return useSrcSetReplacer ? processSrcSetSync(url, ({ url }) => replacer(url)) : replacer(url);
  25070. };
  25071. const devHtmlHook = async (html, { path: htmlPath, filename, server, originalUrl }) => {
  25072. const { config, watcher } = server;
  25073. const base = config.base || "/";
  25074. const decodedBase = config.decodedBase || "/";
  25075. let proxyModulePath;
  25076. let proxyModuleUrl;
  25077. const trailingSlash = htmlPath.endsWith("/");
  25078. if (!trailingSlash && fs.existsSync(filename)) {
  25079. proxyModulePath = htmlPath;
  25080. proxyModuleUrl = proxyModulePath;
  25081. } else {
  25082. proxyModulePath = `\0${`${htmlPath}${trailingSlash ? "index.html" : ""}`}`;
  25083. proxyModuleUrl = wrapId(proxyModulePath);
  25084. }
  25085. proxyModuleUrl = joinUrlSegments(decodedBase, proxyModuleUrl);
  25086. const s = new MagicString(html);
  25087. let inlineModuleIndex = -1;
  25088. const proxyCacheUrl = decodeURI(cleanUrl(proxyModulePath).replace(normalizePath(config.root), ""));
  25089. const styleUrl = [];
  25090. const inlineStyles = [];
  25091. const inlineModulePaths = [];
  25092. const addInlineModule = (node, ext) => {
  25093. inlineModuleIndex++;
  25094. const contentNode = node.childNodes[0];
  25095. const code = contentNode.value;
  25096. let map;
  25097. if (proxyModulePath[0] !== "\0") {
  25098. map = new MagicString(html).snip(contentNode.sourceCodeLocation.startOffset, contentNode.sourceCodeLocation.endOffset).generateMap({ hires: "boundary" });
  25099. map.sources = [filename];
  25100. map.file = filename;
  25101. }
  25102. addToHTMLProxyCache(config, proxyCacheUrl, inlineModuleIndex, {
  25103. code,
  25104. map
  25105. });
  25106. const modulePath = `${proxyModuleUrl}?html-proxy&index=${inlineModuleIndex}.${ext}`;
  25107. inlineModulePaths.push(modulePath);
  25108. s.update(node.sourceCodeLocation.startOffset, node.sourceCodeLocation.endOffset, `<script type="module" src="${modulePath}"><\/script>`);
  25109. preTransformRequest(server, modulePath, decodedBase);
  25110. };
  25111. await traverseHtml(html, filename, config.logger.warn, (node) => {
  25112. if (!nodeIsElement(node)) return;
  25113. if (node.nodeName === "script") {
  25114. const { src, srcSourceCodeLocation, isModule, isIgnored } = getScriptInfo(node);
  25115. if (isIgnored) removeViteIgnoreAttr(s, node.sourceCodeLocation);
  25116. else if (src) {
  25117. const processedUrl = processNodeUrl(src.value, false, config, htmlPath, originalUrl, server, !isModule);
  25118. if (processedUrl !== src.value) overwriteAttrValue(s, srcSourceCodeLocation, processedUrl);
  25119. } else if (isModule && node.childNodes.length) addInlineModule(node, "js");
  25120. else if (node.childNodes.length) {
  25121. const scriptNode = node.childNodes[node.childNodes.length - 1];
  25122. for (const { url, start, end } of extractImportExpressionFromClassicScript(scriptNode)) {
  25123. const processedUrl = processNodeUrl(url, false, config, htmlPath, originalUrl);
  25124. if (processedUrl !== url) s.update(start, end, processedUrl);
  25125. }
  25126. }
  25127. }
  25128. const inlineStyle = findNeedTransformStyleAttribute(node);
  25129. if (inlineStyle) {
  25130. inlineModuleIndex++;
  25131. inlineStyles.push({
  25132. index: inlineModuleIndex,
  25133. location: inlineStyle.location,
  25134. code: inlineStyle.attr.value
  25135. });
  25136. }
  25137. if (node.nodeName === "style" && node.childNodes.length) {
  25138. const children = node.childNodes[0];
  25139. styleUrl.push({
  25140. start: children.sourceCodeLocation.startOffset,
  25141. end: children.sourceCodeLocation.endOffset,
  25142. code: children.value
  25143. });
  25144. }
  25145. const assetAttributes = getNodeAssetAttributes(node);
  25146. for (const attr of assetAttributes) if (attr.type === "remove") s.remove(attr.location.startOffset, attr.location.endOffset);
  25147. else {
  25148. const processedUrl = processNodeUrl(attr.value, attr.type === "srcset", config, htmlPath, originalUrl);
  25149. if (processedUrl !== attr.value) overwriteAttrValue(s, attr.location, processedUrl);
  25150. }
  25151. });
  25152. const clientModuleGraph = server?.environments.client.moduleGraph;
  25153. if (clientModuleGraph) await Promise.all(inlineModulePaths.map(async (url) => {
  25154. const module = await clientModuleGraph.getModuleByUrl(url);
  25155. if (module) clientModuleGraph.invalidateModule(module);
  25156. }));
  25157. await Promise.all([...styleUrl.map(async ({ start, end, code }, index) => {
  25158. const url = `${proxyModulePath}?html-proxy&direct&index=${index}.css`;
  25159. const mod = await server.environments.client.moduleGraph.ensureEntryFromUrl(url, false);
  25160. ensureWatchedFile(watcher, mod.file, config.root);
  25161. const result = await server.environments.client.pluginContainer.transform(code, mod.id);
  25162. let content = "";
  25163. if (result.map && "version" in result.map) {
  25164. if (result.map.mappings) await injectSourcesContent(result.map, proxyModulePath, config.logger);
  25165. content = getCodeWithSourcemap("css", result.code, result.map);
  25166. } else content = result.code;
  25167. s.overwrite(start, end, content);
  25168. }), ...inlineStyles.map(async ({ index, location, code }) => {
  25169. const url = `${proxyModulePath}?html-proxy&inline-css&style-attr&index=${index}.css`;
  25170. const mod = await server.environments.client.moduleGraph.ensureEntryFromUrl(url, false);
  25171. ensureWatchedFile(watcher, mod.file, config.root);
  25172. await server?.environments.client.pluginContainer.transform(code, mod.id);
  25173. const hash = getHash(cleanUrl(mod.id));
  25174. overwriteAttrValue(s, location, htmlProxyResult.get(`${hash}_${index}`) ?? "");
  25175. })]);
  25176. html = s.toString();
  25177. return {
  25178. html,
  25179. tags: [{
  25180. tag: "script",
  25181. attrs: {
  25182. type: "module",
  25183. src: path.posix.join(base, CLIENT_PUBLIC_PATH)
  25184. },
  25185. injectTo: "head-prepend"
  25186. }]
  25187. };
  25188. };
  25189. function indexHtmlMiddleware(root, server) {
  25190. const isDev = isDevServer(server);
  25191. const fullBundleEnv = isDev && server.environments.client instanceof FullBundleDevEnvironment ? server.environments.client : void 0;
  25192. return async function viteIndexHtmlMiddleware(req, res, next) {
  25193. if (res.writableEnded) return next();
  25194. const url = req.url && cleanUrl(req.url);
  25195. if (url?.endsWith(".html") && req.headers["sec-fetch-dest"] !== "script") {
  25196. if (fullBundleEnv) {
  25197. const filePath = decodeURIComponent(url).slice(1);
  25198. let file = fullBundleEnv.memoryFiles.get(filePath);
  25199. if (!file && fullBundleEnv.memoryFiles.size !== 0) return next();
  25200. if ([
  25201. "document",
  25202. "iframe",
  25203. "frame",
  25204. "fencedframe",
  25205. "",
  25206. void 0
  25207. ].includes(req.headers["sec-fetch-dest"]) && (await fullBundleEnv.triggerBundleRegenerationIfStale() || file === void 0)) file = { source: await generateFallbackHtml(server) };
  25208. if (!file) return next();
  25209. return send(req, res, typeof file.source === "string" ? file.source : Buffer.from(file.source), "html", {
  25210. headers: isDev ? server.config.server.headers : server.config.preview.headers,
  25211. etag: file.etag
  25212. });
  25213. }
  25214. let filePath;
  25215. if (isDev && url.startsWith(FS_PREFIX)) filePath = decodeURIComponent(fsPathFromId(url));
  25216. else filePath = normalizePath(path.resolve(path.join(root, decodeURIComponent(url))));
  25217. if (isDev) {
  25218. const servingAccessResult = checkLoadingAccess(server.config, filePath);
  25219. if (servingAccessResult === "denied") return respondWithAccessDenied(filePath, server, res);
  25220. if (servingAccessResult === "fallback") return next();
  25221. } else if (!isParentDirectory(root, filePath)) return next();
  25222. if (fs.existsSync(filePath)) {
  25223. const headers = isDev ? server.config.server.headers : server.config.preview.headers;
  25224. try {
  25225. let html = await fsp.readFile(filePath, "utf-8");
  25226. if (isDev) html = await server.transformIndexHtml(url, html, req.originalUrl);
  25227. return send(req, res, html, "html", { headers });
  25228. } catch (e) {
  25229. return next(e);
  25230. }
  25231. }
  25232. }
  25233. next();
  25234. };
  25235. }
  25236. function preTransformRequest(server, decodedUrl, decodedBase) {
  25237. if (!server.config.server.preTransformRequests) return;
  25238. decodedUrl = unwrapId(stripBase(decodedUrl, decodedBase));
  25239. server.warmupRequest(decodedUrl);
  25240. }
  25241. async function generateFallbackHtml(server) {
  25242. return `
  25243. <!DOCTYPE html>
  25244. <html lang="en">
  25245. <head>
  25246. <script type="module">
  25247. ${(await getHmrImplementation(server.config)).replaceAll("<\/script>", "<\\/script>")}
  25248. <\/script>
  25249. <style>
  25250. :root {
  25251. --page-bg: #ffffff;
  25252. --text-color: #1d1d1f;
  25253. --spinner-track: #f5f5f7;
  25254. --spinner-accent: #0071e3;
  25255. }
  25256. @media (prefers-color-scheme: dark) {
  25257. :root {
  25258. --page-bg: #1e1e1e;
  25259. --text-color: #f5f5f5;
  25260. --spinner-track: #424242;
  25261. }
  25262. }
  25263. body {
  25264. margin: 0;
  25265. min-height: 100vh;
  25266. display: flex;
  25267. background-color: var(--page-bg);
  25268. color: var(--text-color);
  25269. }
  25270. .container {
  25271. margin: auto;
  25272. padding: 2rem;
  25273. text-align: center;
  25274. border-radius: 1rem;
  25275. }
  25276. .spinner {
  25277. width: 3rem;
  25278. height: 3rem;
  25279. margin: 2rem auto;
  25280. border: 3px solid var(--spinner-track);
  25281. border-top-color: var(--spinner-accent);
  25282. border-radius: 50%;
  25283. animation: spin 1s linear infinite;
  25284. }
  25285. @keyframes spin { to { transform: rotate(360deg) } }
  25286. </style>
  25287. </head>
  25288. <body>
  25289. <div class="container">
  25290. <h1>Bundling in progress</h1>
  25291. <p>The page will automatically reload when ready.</p>
  25292. <div class="spinner"></div>
  25293. </div>
  25294. </body>
  25295. </html>
  25296. `;
  25297. }
  25298. //#endregion
  25299. //#region src/node/server/middlewares/time.ts
  25300. const logTime = createDebugger("vite:time");
  25301. function timeMiddleware(root) {
  25302. return function viteTimeMiddleware(req, res, next) {
  25303. const start = performance$1.now();
  25304. const end = res.end;
  25305. res.end = (...args) => {
  25306. logTime?.(`${timeFrom(start)} ${prettifyUrl(req.url, root)}`);
  25307. return end.call(res, ...args);
  25308. };
  25309. next();
  25310. };
  25311. }
  25312. //#endregion
  25313. //#region src/node/server/mixedModuleGraph.ts
  25314. /**
  25315. * Backward compatible ModuleNode and ModuleGraph with mixed nodes from both the client and ssr environments
  25316. * It would be good to take the types names for the new EnvironmentModuleNode and EnvironmentModuleGraph but we can't
  25317. * do that at this point without breaking to much code in the ecosystem.
  25318. * We are going to deprecate these types and we can try to use them back in the future.
  25319. */
  25320. const EMPTY_OBJECT$1 = Object.freeze({});
  25321. var ModuleNode = class {
  25322. _moduleGraph;
  25323. _clientModule;
  25324. _ssrModule;
  25325. constructor(moduleGraph, clientModule, ssrModule) {
  25326. this._moduleGraph = moduleGraph;
  25327. this._clientModule = clientModule;
  25328. this._ssrModule = ssrModule;
  25329. }
  25330. _get(prop) {
  25331. return this._clientModule?.[prop] ?? this._ssrModule?.[prop];
  25332. }
  25333. _set(prop, value) {
  25334. if (this._clientModule) this._clientModule[prop] = value;
  25335. if (this._ssrModule) this._ssrModule[prop] = value;
  25336. }
  25337. _wrapModuleSet(prop, module) {
  25338. if (!module) return /* @__PURE__ */ new Set();
  25339. return createBackwardCompatibleModuleSet(this._moduleGraph, prop, module);
  25340. }
  25341. _getModuleSetUnion(prop) {
  25342. const importedModules = /* @__PURE__ */ new Set();
  25343. const ids = /* @__PURE__ */ new Set();
  25344. if (this._clientModule) for (const mod of this._clientModule[prop]) {
  25345. if (mod.id) ids.add(mod.id);
  25346. importedModules.add(this._moduleGraph.getBackwardCompatibleModuleNode(mod));
  25347. }
  25348. if (this._ssrModule) {
  25349. for (const mod of this._ssrModule[prop]) if (mod.id && !ids.has(mod.id)) importedModules.add(this._moduleGraph.getBackwardCompatibleModuleNode(mod));
  25350. }
  25351. return importedModules;
  25352. }
  25353. _getModuleInfoUnion(prop) {
  25354. const _clientValue = this._clientModule?.[prop];
  25355. const _ssrValue = this._ssrModule?.[prop];
  25356. if (_clientValue == null && _ssrValue == null) return void 0;
  25357. return new Proxy({}, { get: (_, key) => {
  25358. if (key === "meta") return this.meta || EMPTY_OBJECT$1;
  25359. if (_clientValue) {
  25360. if (key in _clientValue) return _clientValue[key];
  25361. }
  25362. if (_ssrValue) {
  25363. if (key in _ssrValue) return _ssrValue[key];
  25364. }
  25365. } });
  25366. }
  25367. _getModuleObjectUnion(prop) {
  25368. const _clientValue = this._clientModule?.[prop];
  25369. const _ssrValue = this._ssrModule?.[prop];
  25370. if (_clientValue == null && _ssrValue == null) return void 0;
  25371. const info = {};
  25372. if (_ssrValue) Object.assign(info, _ssrValue);
  25373. if (_clientValue) Object.assign(info, _clientValue);
  25374. return info;
  25375. }
  25376. get url() {
  25377. return this._get("url");
  25378. }
  25379. set url(value) {
  25380. this._set("url", value);
  25381. }
  25382. get id() {
  25383. return this._get("id");
  25384. }
  25385. set id(value) {
  25386. this._set("id", value);
  25387. }
  25388. get file() {
  25389. return this._get("file");
  25390. }
  25391. set file(value) {
  25392. this._set("file", value);
  25393. }
  25394. get type() {
  25395. return this._get("type");
  25396. }
  25397. get info() {
  25398. return this._getModuleInfoUnion("info");
  25399. }
  25400. get meta() {
  25401. return this._getModuleObjectUnion("meta");
  25402. }
  25403. get importers() {
  25404. return this._getModuleSetUnion("importers");
  25405. }
  25406. get clientImportedModules() {
  25407. return this._wrapModuleSet("importedModules", this._clientModule);
  25408. }
  25409. get ssrImportedModules() {
  25410. return this._wrapModuleSet("importedModules", this._ssrModule);
  25411. }
  25412. get importedModules() {
  25413. return this._getModuleSetUnion("importedModules");
  25414. }
  25415. get acceptedHmrDeps() {
  25416. return this._wrapModuleSet("acceptedHmrDeps", this._clientModule);
  25417. }
  25418. get acceptedHmrExports() {
  25419. return this._clientModule?.acceptedHmrExports ?? null;
  25420. }
  25421. get importedBindings() {
  25422. return this._clientModule?.importedBindings ?? null;
  25423. }
  25424. get isSelfAccepting() {
  25425. return this._clientModule?.isSelfAccepting;
  25426. }
  25427. get transformResult() {
  25428. return this._clientModule?.transformResult ?? null;
  25429. }
  25430. set transformResult(value) {
  25431. if (this._clientModule) this._clientModule.transformResult = value;
  25432. }
  25433. get ssrTransformResult() {
  25434. return this._ssrModule?.transformResult ?? null;
  25435. }
  25436. set ssrTransformResult(value) {
  25437. if (this._ssrModule) this._ssrModule.transformResult = value;
  25438. }
  25439. get ssrModule() {
  25440. return this._ssrModule?.ssrModule ?? null;
  25441. }
  25442. get ssrError() {
  25443. return this._ssrModule?.ssrError ?? null;
  25444. }
  25445. get lastHMRTimestamp() {
  25446. return Math.max(this._clientModule?.lastHMRTimestamp ?? 0, this._ssrModule?.lastHMRTimestamp ?? 0);
  25447. }
  25448. set lastHMRTimestamp(value) {
  25449. if (this._clientModule) this._clientModule.lastHMRTimestamp = value;
  25450. if (this._ssrModule) this._ssrModule.lastHMRTimestamp = value;
  25451. }
  25452. get lastInvalidationTimestamp() {
  25453. return Math.max(this._clientModule?.lastInvalidationTimestamp ?? 0, this._ssrModule?.lastInvalidationTimestamp ?? 0);
  25454. }
  25455. get invalidationState() {
  25456. return this._clientModule?.invalidationState;
  25457. }
  25458. get ssrInvalidationState() {
  25459. return this._ssrModule?.invalidationState;
  25460. }
  25461. };
  25462. function mapIterator(iterable, transform) {
  25463. return {
  25464. [Symbol.iterator]() {
  25465. return this;
  25466. },
  25467. next() {
  25468. const r = iterable.next();
  25469. return r.done ? r : {
  25470. value: transform(r.value),
  25471. done: false
  25472. };
  25473. }
  25474. };
  25475. }
  25476. var ModuleGraph = class {
  25477. /** @internal */
  25478. _moduleGraphs;
  25479. /** @internal */
  25480. get _client() {
  25481. return this._moduleGraphs.client();
  25482. }
  25483. /** @internal */
  25484. get _ssr() {
  25485. return this._moduleGraphs.ssr();
  25486. }
  25487. urlToModuleMap;
  25488. idToModuleMap;
  25489. etagToModuleMap;
  25490. fileToModulesMap;
  25491. moduleNodeCache = new DualWeakMap();
  25492. constructor(moduleGraphs) {
  25493. this._moduleGraphs = moduleGraphs;
  25494. const getModuleMapUnion = (prop) => () => {
  25495. if (this._ssr[prop].size === 0) return this._client[prop];
  25496. const map = new Map(this._client[prop]);
  25497. for (const [key, module] of this._ssr[prop]) if (!map.has(key)) map.set(key, module);
  25498. return map;
  25499. };
  25500. this.urlToModuleMap = createBackwardCompatibleModuleMap(this, "urlToModuleMap", getModuleMapUnion("urlToModuleMap"));
  25501. this.idToModuleMap = createBackwardCompatibleModuleMap(this, "idToModuleMap", getModuleMapUnion("idToModuleMap"));
  25502. this.etagToModuleMap = createBackwardCompatibleModuleMap(this, "etagToModuleMap", () => this._client.etagToModuleMap);
  25503. this.fileToModulesMap = createBackwardCompatibleFileToModulesMap(this);
  25504. }
  25505. getModuleById(id) {
  25506. const clientModule = this._client.getModuleById(id);
  25507. const ssrModule = this._ssr.getModuleById(id);
  25508. if (!clientModule && !ssrModule) return;
  25509. return this.getBackwardCompatibleModuleNodeDual(clientModule, ssrModule);
  25510. }
  25511. async getModuleByUrl(url, _ssr) {
  25512. const [clientModule, ssrModule] = await Promise.all([this._client.getModuleByUrl(url), this._ssr.getModuleByUrl(url)]);
  25513. if (!clientModule && !ssrModule) return;
  25514. return this.getBackwardCompatibleModuleNodeDual(clientModule, ssrModule);
  25515. }
  25516. getModulesByFile(file) {
  25517. const clientModules = this._client.getModulesByFile(file);
  25518. const ssrModules = this._ssr.getModulesByFile(file);
  25519. if (!clientModules && !ssrModules) return;
  25520. const result = /* @__PURE__ */ new Set();
  25521. if (clientModules) for (const mod of clientModules) result.add(this.getBackwardCompatibleBrowserModuleNode(mod));
  25522. if (ssrModules) {
  25523. for (const mod of ssrModules) if (mod.id == null || !this._client.getModuleById(mod.id)) result.add(this.getBackwardCompatibleServerModuleNode(mod));
  25524. }
  25525. return result;
  25526. }
  25527. onFileChange(file) {
  25528. this._client.onFileChange(file);
  25529. this._ssr.onFileChange(file);
  25530. }
  25531. onFileDelete(file) {
  25532. this._client.onFileDelete(file);
  25533. this._ssr.onFileDelete(file);
  25534. }
  25535. /** @internal */
  25536. _getModuleGraph(environment) {
  25537. switch (environment) {
  25538. case "client": return this._client;
  25539. case "ssr": return this._ssr;
  25540. default: throw new Error(`Invalid module node environment ${environment}`);
  25541. }
  25542. }
  25543. invalidateModule(mod, seen = /* @__PURE__ */ new Set(), timestamp = monotonicDateNow(), isHmr = false, softInvalidate = false) {
  25544. if (mod._clientModule) this._client.invalidateModule(mod._clientModule, new Set([...seen].map((mod) => mod._clientModule).filter(Boolean)), timestamp, isHmr, softInvalidate);
  25545. if (mod._ssrModule) this._ssr.invalidateModule(mod._ssrModule, new Set([...seen].map((mod) => mod._ssrModule).filter(Boolean)), timestamp, isHmr, softInvalidate);
  25546. }
  25547. invalidateAll() {
  25548. this._client.invalidateAll();
  25549. this._ssr.invalidateAll();
  25550. }
  25551. async ensureEntryFromUrl(rawUrl, ssr, setIsSelfAccepting = true) {
  25552. const module = await (ssr ? this._ssr : this._client).ensureEntryFromUrl(rawUrl, setIsSelfAccepting);
  25553. return this.getBackwardCompatibleModuleNode(module);
  25554. }
  25555. createFileOnlyEntry(file) {
  25556. const clientModule = this._client.createFileOnlyEntry(file);
  25557. const ssrModule = this._ssr.createFileOnlyEntry(file);
  25558. return this.getBackwardCompatibleModuleNodeDual(clientModule, ssrModule);
  25559. }
  25560. async resolveUrl(url, ssr) {
  25561. return ssr ? this._ssr.resolveUrl(url) : this._client.resolveUrl(url);
  25562. }
  25563. updateModuleTransformResult(mod, result, ssr) {
  25564. const environment = ssr ? "ssr" : "client";
  25565. this._getModuleGraph(environment).updateModuleTransformResult(environment === "client" ? mod._clientModule : mod._ssrModule, result);
  25566. }
  25567. getModuleByEtag(etag) {
  25568. const mod = this._client.etagToModuleMap.get(etag);
  25569. return mod && this.getBackwardCompatibleBrowserModuleNode(mod);
  25570. }
  25571. getBackwardCompatibleBrowserModuleNode(clientModule) {
  25572. return this.getBackwardCompatibleModuleNodeDual(clientModule, clientModule.id ? this._ssr.getModuleById(clientModule.id) : void 0);
  25573. }
  25574. getBackwardCompatibleServerModuleNode(ssrModule) {
  25575. return this.getBackwardCompatibleModuleNodeDual(ssrModule.id ? this._client.getModuleById(ssrModule.id) : void 0, ssrModule);
  25576. }
  25577. getBackwardCompatibleModuleNode(mod) {
  25578. return mod.environment === "client" ? this.getBackwardCompatibleBrowserModuleNode(mod) : this.getBackwardCompatibleServerModuleNode(mod);
  25579. }
  25580. getBackwardCompatibleModuleNodeDual(clientModule, ssrModule) {
  25581. const cached = this.moduleNodeCache.get(clientModule, ssrModule);
  25582. if (cached) return cached;
  25583. const moduleNode = new ModuleNode(this, clientModule, ssrModule);
  25584. this.moduleNodeCache.set(clientModule, ssrModule, moduleNode);
  25585. return moduleNode;
  25586. }
  25587. };
  25588. var DualWeakMap = class {
  25589. map = /* @__PURE__ */ new WeakMap();
  25590. undefinedKey = {};
  25591. get(key1, key2) {
  25592. const k1 = key1 ?? this.undefinedKey;
  25593. const k2 = key2 ?? this.undefinedKey;
  25594. return this.map.get(k1)?.get(k2);
  25595. }
  25596. set(key1, key2, value) {
  25597. const k1 = key1 ?? this.undefinedKey;
  25598. const k2 = key2 ?? this.undefinedKey;
  25599. if (!this.map.has(k1)) this.map.set(k1, /* @__PURE__ */ new Map());
  25600. this.map.get(k1).set(k2, value);
  25601. }
  25602. };
  25603. function createBackwardCompatibleModuleSet(moduleGraph, prop, module) {
  25604. return {
  25605. [Symbol.iterator]() {
  25606. return this.keys();
  25607. },
  25608. has(key) {
  25609. if (!key.id) return false;
  25610. const keyModule = moduleGraph._getModuleGraph(module.environment).getModuleById(key.id);
  25611. return keyModule !== void 0 && module[prop].has(keyModule);
  25612. },
  25613. values() {
  25614. return this.keys();
  25615. },
  25616. keys() {
  25617. return mapIterator(module[prop].keys(), (mod) => moduleGraph.getBackwardCompatibleModuleNode(mod));
  25618. },
  25619. get size() {
  25620. return module[prop].size;
  25621. },
  25622. forEach(callback, thisArg) {
  25623. return module[prop].forEach((mod) => {
  25624. const backwardCompatibleMod = moduleGraph.getBackwardCompatibleModuleNode(mod);
  25625. callback.call(thisArg, backwardCompatibleMod, backwardCompatibleMod, this);
  25626. });
  25627. }
  25628. };
  25629. }
  25630. function createBackwardCompatibleModuleMap(moduleGraph, prop, getModuleMap) {
  25631. return {
  25632. [Symbol.iterator]() {
  25633. return this.entries();
  25634. },
  25635. get(key) {
  25636. const clientModule = moduleGraph._client[prop].get(key);
  25637. const ssrModule = moduleGraph._ssr[prop].get(key);
  25638. if (!clientModule && !ssrModule) return;
  25639. return moduleGraph.getBackwardCompatibleModuleNodeDual(clientModule, ssrModule);
  25640. },
  25641. set(key, mod) {
  25642. const clientModule = mod._clientModule;
  25643. if (clientModule) moduleGraph._client[prop].set(key, clientModule);
  25644. const ssrModule = mod._ssrModule;
  25645. if (ssrModule) moduleGraph._ssr[prop].set(key, ssrModule);
  25646. },
  25647. keys() {
  25648. return getModuleMap().keys();
  25649. },
  25650. values() {
  25651. return mapIterator(getModuleMap().values(), (mod) => moduleGraph.getBackwardCompatibleModuleNode(mod));
  25652. },
  25653. entries() {
  25654. return mapIterator(getModuleMap().entries(), ([key, mod]) => [key, moduleGraph.getBackwardCompatibleModuleNode(mod)]);
  25655. },
  25656. get size() {
  25657. return getModuleMap().size;
  25658. },
  25659. forEach(callback, thisArg) {
  25660. return getModuleMap().forEach((mod, key) => {
  25661. const backwardCompatibleMod = moduleGraph.getBackwardCompatibleModuleNode(mod);
  25662. callback.call(thisArg, backwardCompatibleMod, key, this);
  25663. });
  25664. }
  25665. };
  25666. }
  25667. function createBackwardCompatibleFileToModulesMap(moduleGraph) {
  25668. const getFileToModulesMap = () => {
  25669. if (!moduleGraph._ssr.fileToModulesMap.size) return moduleGraph._client.fileToModulesMap;
  25670. const map = new Map(moduleGraph._client.fileToModulesMap);
  25671. for (const [key, modules] of moduleGraph._ssr.fileToModulesMap) {
  25672. const modulesSet = map.get(key);
  25673. if (!modulesSet) map.set(key, modules);
  25674. else for (const ssrModule of modules) {
  25675. let hasModule = false;
  25676. for (const clientModule of modulesSet) {
  25677. hasModule ||= clientModule.id === ssrModule.id;
  25678. if (hasModule) break;
  25679. }
  25680. if (!hasModule) modulesSet.add(ssrModule);
  25681. }
  25682. }
  25683. return map;
  25684. };
  25685. const getBackwardCompatibleModules = (modules) => new Set([...modules].map((mod) => moduleGraph.getBackwardCompatibleModuleNode(mod)));
  25686. return {
  25687. [Symbol.iterator]() {
  25688. return this.entries();
  25689. },
  25690. get(key) {
  25691. const clientModules = moduleGraph._client.fileToModulesMap.get(key);
  25692. const ssrModules = moduleGraph._ssr.fileToModulesMap.get(key);
  25693. if (!clientModules && !ssrModules) return;
  25694. const modules = clientModules ?? /* @__PURE__ */ new Set();
  25695. if (ssrModules) {
  25696. for (const ssrModule of ssrModules) if (ssrModule.id) {
  25697. let found = false;
  25698. for (const mod of modules) {
  25699. found ||= mod.id === ssrModule.id;
  25700. if (found) break;
  25701. }
  25702. if (!found) modules.add(ssrModule);
  25703. }
  25704. }
  25705. return getBackwardCompatibleModules(modules);
  25706. },
  25707. keys() {
  25708. return getFileToModulesMap().keys();
  25709. },
  25710. values() {
  25711. return mapIterator(getFileToModulesMap().values(), getBackwardCompatibleModules);
  25712. },
  25713. entries() {
  25714. return mapIterator(getFileToModulesMap().entries(), ([key, modules]) => [key, getBackwardCompatibleModules(modules)]);
  25715. },
  25716. get size() {
  25717. return getFileToModulesMap().size;
  25718. },
  25719. forEach(callback, thisArg) {
  25720. return getFileToModulesMap().forEach((modules, key) => {
  25721. callback.call(thisArg, getBackwardCompatibleModules(modules), key, this);
  25722. });
  25723. }
  25724. };
  25725. }
  25726. //#endregion
  25727. //#region src/node/server/middlewares/notFound.ts
  25728. function notFoundMiddleware() {
  25729. return function vite404Middleware(_, res) {
  25730. res.statusCode = 404;
  25731. res.end();
  25732. };
  25733. }
  25734. //#endregion
  25735. //#region src/node/server/middlewares/hostCheck.ts
  25736. function getAdditionalAllowedHosts(resolvedServerOptions, resolvedPreviewOptions) {
  25737. const list = [];
  25738. if (typeof resolvedServerOptions.host === "string" && resolvedServerOptions.host) list.push(resolvedServerOptions.host);
  25739. if (typeof resolvedServerOptions.hmr === "object" && resolvedServerOptions.hmr.host) list.push(resolvedServerOptions.hmr.host);
  25740. if (typeof resolvedPreviewOptions.host === "string" && resolvedPreviewOptions.host) list.push(resolvedPreviewOptions.host);
  25741. if (resolvedServerOptions.origin) try {
  25742. const serverOriginUrl = new URL(resolvedServerOptions.origin);
  25743. list.push(serverOriginUrl.hostname);
  25744. } catch {}
  25745. return list;
  25746. }
  25747. function hostValidationMiddleware(allowedHosts, isPreview) {
  25748. return hostValidationMiddleware$2({
  25749. allowedHosts: Object.freeze([...allowedHosts]),
  25750. generateErrorMessage(hostname) {
  25751. const hostnameWithQuotes = JSON.stringify(hostname);
  25752. return `Blocked request. This host (${hostnameWithQuotes}) is not allowed.\nTo allow this host, add ${hostnameWithQuotes} to \`${`${isPreview ? "preview" : "server"}.allowedHosts`}\` in vite.config.js.`;
  25753. }
  25754. });
  25755. }
  25756. //#endregion
  25757. //#region src/node/server/middlewares/rejectInvalidRequest.ts
  25758. /**
  25759. * disallows request that contains `#` in the URL
  25760. */
  25761. function rejectInvalidRequestMiddleware() {
  25762. return function viteRejectInvalidRequestMiddleware(req, res, next) {
  25763. if (req.url?.includes("#")) {
  25764. res.writeHead(400);
  25765. res.end();
  25766. return;
  25767. }
  25768. return next();
  25769. };
  25770. }
  25771. //#endregion
  25772. //#region src/node/server/middlewares/memoryFiles.ts
  25773. function memoryFilesMiddleware(server) {
  25774. const memoryFiles = server.environments.client instanceof FullBundleDevEnvironment ? server.environments.client.memoryFiles : void 0;
  25775. if (!memoryFiles) throw new Error("memoryFilesMiddleware can only be used for fullBundleMode");
  25776. const headers = server.config.server.headers;
  25777. return function viteMemoryFilesMiddleware(req, res, next) {
  25778. const cleanedUrl = cleanUrl(req.url);
  25779. if (cleanedUrl.endsWith(".html")) return next();
  25780. const filePath = decodeURIComponent(cleanedUrl).slice(1);
  25781. const file = memoryFiles.get(filePath);
  25782. if (file) {
  25783. if (file.etag) {
  25784. if (req.headers["if-none-match"] === file.etag) {
  25785. res.statusCode = 304;
  25786. res.end();
  25787. return;
  25788. }
  25789. res.setHeader("Etag", file.etag);
  25790. }
  25791. const mime = lookup(filePath);
  25792. if (mime) res.setHeader("Content-Type", mime);
  25793. for (const name in headers) res.setHeader(name, headers[name]);
  25794. return res.end(file.source);
  25795. }
  25796. next();
  25797. };
  25798. }
  25799. //#endregion
  25800. //#region src/node/server/middlewares/rejectNoCorsRequest.ts
  25801. /**
  25802. * A middleware that rejects no-cors mode requests that are not same-origin.
  25803. *
  25804. * We should avoid untrusted sites to load the script to avoid attacks like GHSA-4v9v-hfq4-rm2v.
  25805. * This is because:
  25806. * - the path of HMR patch files / entry point files can be predictable
  25807. * - the HMR patch files may not include ESM syntax
  25808. * (if they include ESM syntax, loading as a classic script would fail)
  25809. * - the HMR runtime in the browser has the list of all loaded modules
  25810. *
  25811. * https://github.com/webpack/webpack-dev-server/security/advisories/GHSA-4v9v-hfq4-rm2v
  25812. * https://green.sapphi.red/blog/local-server-security-best-practices#_2-using-xssi-and-modifying-the-prototype
  25813. * https://green.sapphi.red/blog/local-server-security-best-practices#properly-check-the-request-origin
  25814. */
  25815. function rejectNoCorsRequestMiddleware() {
  25816. return function viteRejectNoCorsRequestMiddleware(req, res, next) {
  25817. if (req.headers["sec-fetch-mode"] === "no-cors" && req.headers["sec-fetch-site"] !== "same-origin" && req.headers["sec-fetch-dest"] === "script") {
  25818. res.statusCode = 403;
  25819. res.end("Cross-origin requests for classic scripts must be made with CORS mode enabled. Make sure to set the \"crossorigin\" attribute on your <script> tag.");
  25820. return;
  25821. }
  25822. return next();
  25823. };
  25824. }
  25825. //#endregion
  25826. //#region src/node/server/index.ts
  25827. var import_connect = /* @__PURE__ */ __toESM(require_connect(), 1);
  25828. var import_lib = /* @__PURE__ */ __toESM(require_lib$1(), 1);
  25829. var import_chokidar = /* @__PURE__ */ __toESM(require_chokidar(), 1);
  25830. var import_launch_editor_middleware = /* @__PURE__ */ __toESM(require_launch_editor_middleware(), 1);
  25831. var import_dist = require_dist();
  25832. const usedConfigs = /* @__PURE__ */ new WeakSet();
  25833. async function resolveForwardConsoleOptions(value) {
  25834. value ??= (await (0, import_dist.determineAgent)()).isAgent;
  25835. if (value === false) return {
  25836. enabled: false,
  25837. unhandledErrors: false,
  25838. logLevels: []
  25839. };
  25840. if (value === true) return {
  25841. enabled: true,
  25842. unhandledErrors: true,
  25843. logLevels: ["error", "warn"]
  25844. };
  25845. const unhandledErrors = value.unhandledErrors ?? true;
  25846. const logLevels = value.logLevels ?? [];
  25847. return {
  25848. enabled: unhandledErrors || logLevels.length > 0,
  25849. unhandledErrors,
  25850. logLevels
  25851. };
  25852. }
  25853. function createServer$2(inlineConfig = {}) {
  25854. return _createServer(inlineConfig, { listen: true });
  25855. }
  25856. async function _createServer(inlineConfig = {}, options) {
  25857. const config = isResolvedConfig(inlineConfig) ? inlineConfig : await resolveConfig(inlineConfig, "serve");
  25858. if (usedConfigs.has(config)) throw new Error(`There is already a server associated with the config.`);
  25859. if (config.command !== "serve") throw new Error(`Config was resolved for a "build", expected a "serve" command.`);
  25860. usedConfigs.add(config);
  25861. const initPublicFilesPromise = initPublicFiles(config);
  25862. const { root, server: serverConfig } = config;
  25863. const httpsOptions = await resolveHttpsConfig(config.server.https);
  25864. const { middlewareMode } = serverConfig;
  25865. const resolvedOutDirs = getResolvedOutDirs(config.root, config.build.outDir, config.build.rollupOptions.output);
  25866. const emptyOutDir = resolveEmptyOutDir(config.build.emptyOutDir, config.root, resolvedOutDirs);
  25867. const resolvedWatchOptions = resolveChokidarOptions({
  25868. disableGlobbing: true,
  25869. ...serverConfig.watch
  25870. }, resolvedOutDirs, emptyOutDir, config.cacheDir);
  25871. const middlewares = (0, import_connect.default)();
  25872. const httpServer = middlewareMode ? null : await resolveHttpServer(middlewares, httpsOptions);
  25873. const ws = createWebSocketServer(httpServer, config, httpsOptions);
  25874. const publicFiles = await initPublicFilesPromise;
  25875. const { publicDir } = config;
  25876. if (httpServer) setClientErrorHandler(httpServer, config.logger);
  25877. const watcher = serverConfig.watch !== null ? import_chokidar.watch([
  25878. ...config.experimental.bundledDev ? [] : [root],
  25879. ...config.configFileDependencies,
  25880. ...getEnvFilesForMode(config.mode, config.envDir),
  25881. ...publicDir && publicFiles ? [publicDir] : []
  25882. ], resolvedWatchOptions) : createNoopWatcher(resolvedWatchOptions);
  25883. const environments = {};
  25884. await Promise.all(Object.entries(config.environments).map(async ([name, environmentOptions]) => {
  25885. const environment = await environmentOptions.dev.createEnvironment(name, config, { ws });
  25886. environments[name] = environment;
  25887. const previousInstance = options.previousEnvironments?.[environment.name];
  25888. await environment.init({
  25889. watcher,
  25890. previousInstance
  25891. });
  25892. }));
  25893. let moduleGraph = new ModuleGraph({
  25894. client: () => environments.client.moduleGraph,
  25895. ssr: () => environments.ssr.moduleGraph
  25896. });
  25897. let pluginContainer = createPluginContainer(environments);
  25898. const closeHttpServer = createServerCloseFn(httpServer);
  25899. const devHtmlTransformFn = createDevHtmlTransformFn(config);
  25900. let closeServerPromise;
  25901. const closeServer = async () => {
  25902. if (!middlewareMode) teardownSIGTERMListener(closeServerAndExit);
  25903. await Promise.allSettled([
  25904. watcher.close(),
  25905. ws.close(),
  25906. Promise.allSettled(Object.values(server.environments).map((environment) => environment.close())),
  25907. closeHttpServer(),
  25908. server._ssrCompatModuleRunner?.close()
  25909. ]);
  25910. server.resolvedUrls = null;
  25911. server._ssrCompatModuleRunner = void 0;
  25912. };
  25913. let hot = ws;
  25914. let server = {
  25915. config,
  25916. middlewares,
  25917. httpServer,
  25918. watcher,
  25919. ws,
  25920. get hot() {
  25921. warnFutureDeprecation(config, "removeServerHot");
  25922. return hot;
  25923. },
  25924. set hot(h) {
  25925. hot = h;
  25926. },
  25927. environments,
  25928. get pluginContainer() {
  25929. warnFutureDeprecation(config, "removeServerPluginContainer");
  25930. return pluginContainer;
  25931. },
  25932. set pluginContainer(p) {
  25933. pluginContainer = p;
  25934. },
  25935. get moduleGraph() {
  25936. warnFutureDeprecation(config, "removeServerModuleGraph");
  25937. return moduleGraph;
  25938. },
  25939. set moduleGraph(graph) {
  25940. moduleGraph = graph;
  25941. },
  25942. resolvedUrls: null,
  25943. ssrTransform(code, inMap, url, originalCode = code) {
  25944. return ssrTransform(code, inMap, url, originalCode, { json: { stringify: config.json.stringify === true && config.json.namedExports !== true } });
  25945. },
  25946. transformRequest(url, options) {
  25947. warnFutureDeprecation(config, "removeServerTransformRequest");
  25948. return server.environments[options?.ssr ? "ssr" : "client"].transformRequest(url);
  25949. },
  25950. warmupRequest(url, options) {
  25951. warnFutureDeprecation(config, "removeServerWarmupRequest");
  25952. return server.environments[options?.ssr ? "ssr" : "client"].warmupRequest(url);
  25953. },
  25954. transformIndexHtml(url, html, originalUrl) {
  25955. return devHtmlTransformFn(server, url, html, originalUrl);
  25956. },
  25957. async ssrLoadModule(url, opts) {
  25958. warnFutureDeprecation(config, "removeSsrLoadModule");
  25959. return ssrLoadModule(url, server, opts?.fixStacktrace);
  25960. },
  25961. ssrFixStacktrace(e) {
  25962. warnFutureDeprecation(config, "removeSsrLoadModule", "ssrFixStacktrace doesn't need to be used for Environment Module Runners.");
  25963. ssrFixStacktrace(e, server.environments.ssr.moduleGraph);
  25964. },
  25965. ssrRewriteStacktrace(stack) {
  25966. warnFutureDeprecation(config, "removeSsrLoadModule", "ssrRewriteStacktrace doesn't need to be used for Environment Module Runners.");
  25967. return ssrRewriteStacktrace(stack, server.environments.ssr.moduleGraph).result;
  25968. },
  25969. async reloadModule(module) {
  25970. warnFutureDeprecation(config, "removeServerReloadModule");
  25971. if (serverConfig.hmr !== false && module.file) {
  25972. const environmentModule = module._clientModule ?? module._ssrModule;
  25973. updateModules(environments[environmentModule.environment], module.file, [environmentModule], monotonicDateNow());
  25974. }
  25975. },
  25976. async listen(port, isRestart) {
  25977. const hostname = await resolveHostname(config.server.host);
  25978. if (httpServer) httpServer.prependListener("listening", () => {
  25979. server.resolvedUrls = resolveServerUrls(httpServer, config.server, hostname, httpsOptions, config);
  25980. });
  25981. await startServer(server, hostname, port);
  25982. if (httpServer) {
  25983. if (!isRestart && config.server.open) server.openBrowser();
  25984. }
  25985. return server;
  25986. },
  25987. openBrowser() {
  25988. const options = server.config.server;
  25989. const url = getServerUrlByHost(server.resolvedUrls, options.host);
  25990. if (url) {
  25991. const path = typeof options.open === "string" ? new URL(options.open, url).href : url;
  25992. if (server.config.server.preTransformRequests) setTimeout(() => {
  25993. (path.startsWith("https:") ? get$1 : get)(path, { headers: { Accept: "text/html" } }, (res) => {
  25994. res.on("end", () => {});
  25995. }).on("error", () => {}).end();
  25996. }, 0);
  25997. openBrowser(path, true, server.config.logger);
  25998. } else server.config.logger.warn("No URL available to open in browser");
  25999. },
  26000. async close() {
  26001. if (!closeServerPromise) closeServerPromise = closeServer();
  26002. return closeServerPromise;
  26003. },
  26004. printUrls() {
  26005. if (server.resolvedUrls) printServerUrls(server.resolvedUrls, serverConfig.host, config.logger.info);
  26006. else if (middlewareMode) throw new Error("cannot print server URLs in middleware mode.");
  26007. else throw new Error("cannot print server URLs before server.listen is called.");
  26008. },
  26009. bindCLIShortcuts(options) {
  26010. bindCLIShortcuts(server, options);
  26011. },
  26012. async restart(forceOptimize) {
  26013. if (!server._restartPromise) {
  26014. server._forceOptimizeOnRestart = !!forceOptimize;
  26015. server._restartPromise = restartServer(server).finally(() => {
  26016. server._restartPromise = null;
  26017. server._forceOptimizeOnRestart = false;
  26018. });
  26019. }
  26020. return server._restartPromise;
  26021. },
  26022. waitForRequestsIdle(ignoredId) {
  26023. return environments.client.waitForRequestsIdle(ignoredId);
  26024. },
  26025. _setInternalServer(_server) {
  26026. server = _server;
  26027. },
  26028. _restartPromise: null,
  26029. _forceOptimizeOnRestart: false,
  26030. _shortcutsState: options.previousShortcutsState
  26031. };
  26032. const reflexServer = new Proxy(server, {
  26033. get: (_, property) => {
  26034. return server[property];
  26035. },
  26036. set: (_, property, value) => {
  26037. server[property] = value;
  26038. return true;
  26039. }
  26040. });
  26041. const closeServerAndExit = async (_, exitCode) => {
  26042. try {
  26043. await server.close();
  26044. } finally {
  26045. process.exitCode ??= exitCode ? 128 + exitCode : void 0;
  26046. process.exit();
  26047. }
  26048. };
  26049. if (!middlewareMode) setupSIGTERMListener(closeServerAndExit);
  26050. const onHMRUpdate = async (type, file) => {
  26051. if (serverConfig.hmr !== false) await handleHMRUpdate(type, file, server);
  26052. };
  26053. const onFileAddUnlink = async (file, isUnlink) => {
  26054. file = normalizePath(file);
  26055. reloadOnTsconfigChange(server, file);
  26056. await Promise.all(Object.values(server.environments).map((environment) => environment.pluginContainer.watchChange(file, { event: isUnlink ? "delete" : "create" })));
  26057. if (publicDir && publicFiles) {
  26058. if (file.startsWith(publicDir)) {
  26059. const path = file.slice(publicDir.length);
  26060. publicFiles[isUnlink ? "delete" : "add"](path);
  26061. if (!isUnlink) {
  26062. const clientModuleGraph = server.environments.client.moduleGraph;
  26063. const etag = (await clientModuleGraph.getModuleByUrl(path))?.transformResult?.etag;
  26064. if (etag) clientModuleGraph.etagToModuleMap.delete(etag);
  26065. }
  26066. }
  26067. }
  26068. if (isUnlink) for (const environment of Object.values(server.environments)) environment.moduleGraph.onFileDelete(file);
  26069. await onHMRUpdate(isUnlink ? "delete" : "create", file);
  26070. };
  26071. watcher.on("change", async (file) => {
  26072. file = normalizePath(file);
  26073. reloadOnTsconfigChange(server, file);
  26074. await Promise.all(Object.values(server.environments).map((environment) => environment.pluginContainer.watchChange(file, { event: "update" })));
  26075. for (const environment of Object.values(server.environments)) environment.moduleGraph.onFileChange(file);
  26076. await onHMRUpdate("update", file);
  26077. });
  26078. watcher.on("add", (file) => {
  26079. onFileAddUnlink(file, false);
  26080. });
  26081. watcher.on("unlink", (file) => {
  26082. onFileAddUnlink(file, true);
  26083. });
  26084. if (!middlewareMode && httpServer) httpServer.once("listening", () => {
  26085. serverConfig.port = httpServer.address().port;
  26086. });
  26087. if (process.env.DEBUG) middlewares.use(timeMiddleware(root));
  26088. middlewares.use(rejectInvalidRequestMiddleware());
  26089. middlewares.use(rejectNoCorsRequestMiddleware());
  26090. const { cors } = serverConfig;
  26091. if (cors !== false) middlewares.use((0, import_lib.default)(typeof cors === "boolean" ? {} : cors));
  26092. const { allowedHosts } = serverConfig;
  26093. if (allowedHosts !== true && !serverConfig.https) middlewares.use(hostValidationMiddleware(allowedHosts, false));
  26094. const configureServerContext = new BasicMinimalPluginContext({
  26095. ...basePluginContextMeta,
  26096. watchMode: true
  26097. }, config.logger);
  26098. const postHooks = [];
  26099. for (const hook of config.getSortedPluginHooks("configureServer")) postHooks.push(await hook.call(configureServerContext, reflexServer));
  26100. if (!config.experimental.bundledDev) middlewares.use(cachedTransformMiddleware(server));
  26101. const { proxy } = serverConfig;
  26102. if (proxy) {
  26103. const middlewareServer = (isObject$1(middlewareMode) ? middlewareMode.server : null) || httpServer;
  26104. middlewares.use(proxyMiddleware(middlewareServer, proxy, config));
  26105. }
  26106. if (config.base !== "/") middlewares.use(baseMiddleware(config.rawBase, !!middlewareMode));
  26107. middlewares.use("/__open-in-editor", (0, import_launch_editor_middleware.default)());
  26108. middlewares.use(function viteHMRPingMiddleware(req, res, next) {
  26109. if (req.headers["accept"] === "text/x-vite-ping") res.writeHead(204).end();
  26110. else next();
  26111. });
  26112. if (publicDir) middlewares.use(servePublicMiddleware(server, publicFiles));
  26113. if (config.experimental.bundledDev) middlewares.use(memoryFilesMiddleware(server));
  26114. else {
  26115. middlewares.use(transformMiddleware(server));
  26116. middlewares.use(serveRawFsMiddleware(server));
  26117. middlewares.use(serveStaticMiddleware(server));
  26118. }
  26119. if (config.appType === "spa" || config.appType === "mpa") middlewares.use(htmlFallbackMiddleware(root, config.appType === "spa", server.environments.client));
  26120. postHooks.forEach((fn) => fn && fn());
  26121. if (config.appType === "spa" || config.appType === "mpa") {
  26122. middlewares.use(indexHtmlMiddleware(root, server));
  26123. middlewares.use(notFoundMiddleware());
  26124. }
  26125. middlewares.use(errorMiddleware(server, !!middlewareMode));
  26126. let initingServer;
  26127. let serverInited = false;
  26128. const initServer = async (onListen) => {
  26129. if (serverInited) return;
  26130. if (initingServer) return initingServer;
  26131. initingServer = (async function() {
  26132. if (!config.experimental.bundledDev) await environments.client.pluginContainer.buildStart();
  26133. if (onListen || options.listen) await Promise.all(Object.values(environments).map((e) => e.listen(server)));
  26134. initingServer = void 0;
  26135. serverInited = true;
  26136. })();
  26137. return initingServer;
  26138. };
  26139. if (!middlewareMode && httpServer) {
  26140. const listen = httpServer.listen.bind(httpServer);
  26141. httpServer.listen = (async (port, ...args) => {
  26142. try {
  26143. await initServer(true);
  26144. } catch (e) {
  26145. httpServer.emit("error", e);
  26146. return;
  26147. }
  26148. return listen(port, ...args);
  26149. });
  26150. } else await initServer(false);
  26151. return server;
  26152. }
  26153. async function startServer(server, hostname, inlinePort) {
  26154. const httpServer = server.httpServer;
  26155. if (!httpServer) throw new Error("Cannot call server.listen in middleware mode.");
  26156. const options = server.config.server;
  26157. const configPort = inlinePort ?? options.port;
  26158. const port = (!configPort || configPort === server._configServerPort ? server._currentServerPort : configPort) ?? 5173;
  26159. server._configServerPort = configPort;
  26160. server._currentServerPort = await httpServerStart(httpServer, {
  26161. port,
  26162. strictPort: options.strictPort,
  26163. host: hostname.host,
  26164. logger: server.config.logger
  26165. });
  26166. }
  26167. function createServerCloseFn(server) {
  26168. if (!server) return () => Promise.resolve();
  26169. let hasListened = false;
  26170. const openSockets = /* @__PURE__ */ new Set();
  26171. server.on("connection", (socket) => {
  26172. openSockets.add(socket);
  26173. socket.on("close", () => {
  26174. openSockets.delete(socket);
  26175. });
  26176. });
  26177. server.once("listening", () => {
  26178. hasListened = true;
  26179. });
  26180. return () => new Promise((resolve, reject) => {
  26181. openSockets.forEach((s) => s.destroy());
  26182. if (hasListened) server.close((err) => {
  26183. if (err) reject(err);
  26184. else resolve();
  26185. });
  26186. else resolve();
  26187. });
  26188. }
  26189. function resolvedAllowDir(root, dir) {
  26190. return normalizePath(path.resolve(root, dir));
  26191. }
  26192. const _serverConfigDefaults = Object.freeze({
  26193. port: DEFAULT_DEV_PORT,
  26194. strictPort: false,
  26195. host: "localhost",
  26196. allowedHosts: [],
  26197. https: void 0,
  26198. open: false,
  26199. proxy: void 0,
  26200. cors: { origin: defaultAllowedOrigins },
  26201. headers: {},
  26202. warmup: {
  26203. clientFiles: [],
  26204. ssrFiles: []
  26205. },
  26206. middlewareMode: false,
  26207. fs: {
  26208. strict: true,
  26209. deny: [
  26210. ".env",
  26211. ".env.*",
  26212. "*.{crt,pem}",
  26213. "**/.git/**"
  26214. ]
  26215. },
  26216. preTransformRequests: true,
  26217. perEnvironmentStartEndDuringDev: false,
  26218. perEnvironmentWatchChangeDuringDev: false,
  26219. forwardConsole: void 0
  26220. });
  26221. const serverConfigDefaults = _serverConfigDefaults;
  26222. async function resolveServerOptions(root, raw, logger) {
  26223. const _server = mergeWithDefaults({
  26224. ..._serverConfigDefaults,
  26225. host: void 0,
  26226. sourcemapIgnoreList: isInNodeModules
  26227. }, raw ?? {});
  26228. const server = {
  26229. ..._server,
  26230. fs: {
  26231. ..._server.fs,
  26232. allow: raw?.fs?.allow ?? [searchForWorkspaceRoot(root)]
  26233. },
  26234. sourcemapIgnoreList: _server.sourcemapIgnoreList === false ? () => false : _server.sourcemapIgnoreList,
  26235. forwardConsole: await resolveForwardConsoleOptions(_server.forwardConsole)
  26236. };
  26237. let allowDirs = server.fs.allow;
  26238. if (process.versions.pnp) {
  26239. const cwd = searchForPackageRoot(root);
  26240. try {
  26241. const yarnCacheDir = execSync(`yarn config get ${execSync("yarn config get enableGlobalCache", { cwd }).toString().trim() === "true" ? "globalFolder" : "cacheFolder"}`, { cwd }).toString().trim();
  26242. allowDirs.push(yarnCacheDir);
  26243. } catch (e) {
  26244. logger.warn(`Get yarn cache dir error: ${e.message}`, { timestamp: true });
  26245. }
  26246. }
  26247. allowDirs = allowDirs.map((i) => resolvedAllowDir(root, i));
  26248. const resolvedClientDir = resolvedAllowDir(root, CLIENT_DIR);
  26249. if (!allowDirs.some((dir) => isParentDirectory(dir, resolvedClientDir))) allowDirs.push(resolvedClientDir);
  26250. server.fs.allow = allowDirs;
  26251. if (server.origin?.endsWith("/")) {
  26252. server.origin = server.origin.slice(0, -1);
  26253. logger.warn(import_picocolors.default.yellow(`${import_picocolors.default.bold("(!)")} server.origin should not end with "/". Using "${server.origin}" instead.`));
  26254. }
  26255. if (process.env.__VITE_ADDITIONAL_SERVER_ALLOWED_HOSTS && Array.isArray(server.allowedHosts)) {
  26256. const additionalHost = process.env.__VITE_ADDITIONAL_SERVER_ALLOWED_HOSTS;
  26257. server.allowedHosts = [...server.allowedHosts, additionalHost];
  26258. }
  26259. return server;
  26260. }
  26261. async function restartServer(server) {
  26262. global.__vite_start_time = performance$1.now();
  26263. let inlineConfig = server.config.inlineConfig;
  26264. if (server._forceOptimizeOnRestart) inlineConfig = mergeConfig(inlineConfig, { forceOptimizeDeps: true });
  26265. {
  26266. let newServer = null;
  26267. try {
  26268. newServer = await _createServer(inlineConfig, {
  26269. listen: false,
  26270. previousEnvironments: server.environments,
  26271. previousShortcutsState: server._shortcutsState
  26272. });
  26273. } catch (err) {
  26274. server.config.logger.error(err.message, { timestamp: true });
  26275. server.config.logger.error("server restart failed", { timestamp: true });
  26276. return;
  26277. }
  26278. server._shortcutsState = void 0;
  26279. await server.close();
  26280. const middlewares = server.middlewares;
  26281. newServer._configServerPort = server._configServerPort;
  26282. newServer._currentServerPort = server._currentServerPort;
  26283. newServer._restartPromise = server._restartPromise;
  26284. newServer._forceOptimizeOnRestart = server._forceOptimizeOnRestart;
  26285. Object.assign(server, newServer);
  26286. middlewares.stack = newServer.middlewares.stack;
  26287. server.middlewares = middlewares;
  26288. newServer._setInternalServer(server);
  26289. }
  26290. const { logger, server: { port, middlewareMode } } = server.config;
  26291. if (!middlewareMode) await server.listen(port, true);
  26292. else await Promise.all(Object.values(server.environments).map((e) => e.listen(server)));
  26293. logger.info("server restarted.", { timestamp: true });
  26294. if (server._shortcutsState?.options) bindCLIShortcuts(server, { print: false }, true);
  26295. }
  26296. /**
  26297. * Internal function to restart the Vite server and print URLs if changed
  26298. */
  26299. async function restartServerWithUrls(server) {
  26300. if (server.config.server.middlewareMode) {
  26301. await server.restart();
  26302. return;
  26303. }
  26304. const { port: prevPort, host: prevHost } = server.config.server;
  26305. const prevUrls = server.resolvedUrls;
  26306. await server.restart();
  26307. const { logger, server: { port, host } } = server.config;
  26308. if ((port ?? 5173) !== (prevPort ?? 5173) || host !== prevHost || diffDnsOrderChange(prevUrls, server.resolvedUrls)) {
  26309. logger.info("");
  26310. server.printUrls();
  26311. }
  26312. }
  26313. //#endregion
  26314. //#region src/node/server/hmr.ts
  26315. const debugHmr = createDebugger("vite:hmr");
  26316. const whitespaceRE = /\s/;
  26317. const normalizedClientDir = normalizePath(CLIENT_DIR);
  26318. function getShortName(file, root) {
  26319. return file.startsWith(withTrailingSlash(root)) ? path.posix.relative(root, file) : file;
  26320. }
  26321. const normalizeHotChannel = (channel, enableHmr, normalizeClient = true) => {
  26322. const normalizedListenerMap = /* @__PURE__ */ new WeakMap();
  26323. const normalizedClients = /* @__PURE__ */ new WeakMap();
  26324. let invokeHandlers;
  26325. let listenerForInvokeHandler;
  26326. const handleInvoke = async (payload) => {
  26327. if (!invokeHandlers) return { error: {
  26328. name: "TransportError",
  26329. message: "invokeHandlers is not set",
  26330. stack: (/* @__PURE__ */ new Error()).stack
  26331. } };
  26332. const { name, data: args } = payload.data;
  26333. try {
  26334. const invokeHandler = invokeHandlers[name];
  26335. return { result: await invokeHandler(...args) };
  26336. } catch (error) {
  26337. return { error: {
  26338. name: error.name,
  26339. message: error.message,
  26340. stack: error.stack,
  26341. ...error
  26342. } };
  26343. }
  26344. };
  26345. return {
  26346. ...channel,
  26347. on: (event, fn) => {
  26348. if (event === "connection" || !normalizeClient) {
  26349. channel.on?.(event, fn);
  26350. return;
  26351. }
  26352. const listenerWithNormalizedClient = (data, client) => {
  26353. if (!normalizedClients.has(client)) normalizedClients.set(client, { send: (...args) => {
  26354. let payload;
  26355. if (typeof args[0] === "string") payload = {
  26356. type: "custom",
  26357. event: args[0],
  26358. data: args[1]
  26359. };
  26360. else payload = args[0];
  26361. client.send(payload);
  26362. } });
  26363. fn(data, normalizedClients.get(client));
  26364. };
  26365. normalizedListenerMap.set(fn, listenerWithNormalizedClient);
  26366. channel.on?.(event, listenerWithNormalizedClient);
  26367. },
  26368. off: (event, fn) => {
  26369. if (event === "connection" || !normalizeClient) {
  26370. channel.off?.(event, fn);
  26371. return;
  26372. }
  26373. const normalizedListener = normalizedListenerMap.get(fn);
  26374. if (normalizedListener) channel.off?.(event, normalizedListener);
  26375. },
  26376. setInvokeHandler(_invokeHandlers) {
  26377. invokeHandlers = _invokeHandlers;
  26378. if (!_invokeHandlers) {
  26379. if (listenerForInvokeHandler) channel.off?.("vite:invoke", listenerForInvokeHandler);
  26380. return;
  26381. }
  26382. listenerForInvokeHandler = async (payload, client) => {
  26383. const responseInvoke = payload.id.replace("send", "response");
  26384. client.send({
  26385. type: "custom",
  26386. event: "vite:invoke",
  26387. data: {
  26388. name: payload.name,
  26389. id: responseInvoke,
  26390. data: await handleInvoke({
  26391. type: "custom",
  26392. event: "vite:invoke",
  26393. data: payload
  26394. })
  26395. }
  26396. });
  26397. };
  26398. channel.on?.("vite:invoke", listenerForInvokeHandler);
  26399. },
  26400. handleInvoke,
  26401. send: (...args) => {
  26402. let payload;
  26403. if (typeof args[0] === "string") payload = {
  26404. type: "custom",
  26405. event: args[0],
  26406. data: args[1]
  26407. };
  26408. else payload = args[0];
  26409. if (enableHmr || payload.type === "connected" || payload.type === "ping" || payload.type === "custom" || payload.type === "error") channel.send?.(payload);
  26410. },
  26411. listen() {
  26412. return channel.listen?.();
  26413. },
  26414. close() {
  26415. return channel.close?.();
  26416. }
  26417. };
  26418. };
  26419. function getSortedPluginsByHotUpdateHook(plugins) {
  26420. const sortedPlugins = [];
  26421. let pre = 0, normal = 0, post = 0;
  26422. for (const plugin of plugins) {
  26423. const hook = plugin["hotUpdate"] ?? plugin["handleHotUpdate"];
  26424. if (hook) {
  26425. if (typeof hook === "object") {
  26426. if (hook.order === "pre") {
  26427. sortedPlugins.splice(pre++, 0, plugin);
  26428. continue;
  26429. }
  26430. if (hook.order === "post") {
  26431. sortedPlugins.splice(pre + normal + post++, 0, plugin);
  26432. continue;
  26433. }
  26434. }
  26435. sortedPlugins.splice(pre + normal++, 0, plugin);
  26436. }
  26437. }
  26438. return sortedPlugins;
  26439. }
  26440. const sortedHotUpdatePluginsCache = /* @__PURE__ */ new WeakMap();
  26441. function getSortedHotUpdatePlugins(environment) {
  26442. let sortedPlugins = sortedHotUpdatePluginsCache.get(environment);
  26443. if (!sortedPlugins) {
  26444. sortedPlugins = getSortedPluginsByHotUpdateHook(environment.plugins);
  26445. sortedHotUpdatePluginsCache.set(environment, sortedPlugins);
  26446. }
  26447. return sortedPlugins;
  26448. }
  26449. async function handleHMRUpdate(type, file, server) {
  26450. const { config } = server;
  26451. const mixedModuleGraph = ignoreDeprecationWarnings(() => server.moduleGraph);
  26452. const environments = Object.values(server.environments);
  26453. const shortFile = getShortName(file, config.root);
  26454. const isConfig = file === config.configFile;
  26455. const isConfigDependency = config.configFileDependencies.some((name) => file === name);
  26456. const isEnv = config.envDir !== false && getEnvFilesForMode(config.mode, config.envDir).includes(file);
  26457. if (isConfig || isConfigDependency || isEnv) {
  26458. debugHmr?.(`[config change] ${import_picocolors.default.dim(shortFile)}`);
  26459. config.logger.info(import_picocolors.default.green(`${normalizePath(path.relative(process.cwd(), file))} changed, restarting server...`), {
  26460. clear: true,
  26461. timestamp: true
  26462. });
  26463. try {
  26464. await restartServerWithUrls(server);
  26465. } catch (e) {
  26466. config.logger.error(import_picocolors.default.red(e));
  26467. }
  26468. return;
  26469. }
  26470. debugHmr?.(`[file change] ${import_picocolors.default.dim(shortFile)}`);
  26471. if (file.startsWith(withTrailingSlash(normalizedClientDir))) {
  26472. environments.forEach(({ hot }) => hot.send({
  26473. type: "full-reload",
  26474. path: "*",
  26475. triggeredBy: path.resolve(config.root, file)
  26476. }));
  26477. return;
  26478. }
  26479. if (config.experimental.bundledDev) return;
  26480. const timestamp = monotonicDateNow();
  26481. const contextMeta = {
  26482. type,
  26483. file,
  26484. timestamp,
  26485. read: () => readModifiedFile(file),
  26486. server
  26487. };
  26488. const hotMap = /* @__PURE__ */ new Map();
  26489. for (const environment of Object.values(server.environments)) {
  26490. const mods = new Set(environment.moduleGraph.getModulesByFile(file));
  26491. if (type === "create") for (const mod of environment.moduleGraph._hasResolveFailedErrorModules) mods.add(mod);
  26492. const options = {
  26493. ...contextMeta,
  26494. modules: [...mods]
  26495. };
  26496. hotMap.set(environment, { options });
  26497. }
  26498. const mixedMods = new Set(mixedModuleGraph.getModulesByFile(file));
  26499. const mixedHmrContext = {
  26500. ...contextMeta,
  26501. modules: [...mixedMods]
  26502. };
  26503. const contextForHandleHotUpdate = new BasicMinimalPluginContext({
  26504. ...basePluginContextMeta,
  26505. watchMode: true
  26506. }, config.logger);
  26507. const clientEnvironment = server.environments.client;
  26508. const ssrEnvironment = server.environments.ssr;
  26509. const clientContext = clientEnvironment.pluginContainer.minimalContext;
  26510. const clientHotUpdateOptions = hotMap.get(clientEnvironment).options;
  26511. const ssrHotUpdateOptions = hotMap.get(ssrEnvironment)?.options;
  26512. try {
  26513. for (const plugin of getSortedHotUpdatePlugins(server.environments.client)) if (plugin.hotUpdate) {
  26514. const filteredModules = await getHookHandler(plugin.hotUpdate).call(clientContext, clientHotUpdateOptions);
  26515. if (filteredModules) {
  26516. clientHotUpdateOptions.modules = filteredModules;
  26517. mixedHmrContext.modules = mixedHmrContext.modules.filter((mixedMod) => filteredModules.some((mod) => mixedMod.id === mod.id) || ssrHotUpdateOptions?.modules.some((ssrMod) => ssrMod.id === mixedMod.id));
  26518. mixedHmrContext.modules.push(...filteredModules.filter((mod) => !mixedHmrContext.modules.some((mixedMod) => mixedMod.id === mod.id)).map((mod) => mixedModuleGraph.getBackwardCompatibleModuleNode(mod)));
  26519. }
  26520. } else if (type === "update") {
  26521. warnFutureDeprecation(config, "removePluginHookHandleHotUpdate", `Used in plugin "${plugin.name}".`, false);
  26522. const filteredModules = await getHookHandler(plugin.handleHotUpdate).call(contextForHandleHotUpdate, mixedHmrContext);
  26523. if (filteredModules) {
  26524. mixedHmrContext.modules = filteredModules;
  26525. clientHotUpdateOptions.modules = clientHotUpdateOptions.modules.filter((mod) => filteredModules.some((mixedMod) => mod.id === mixedMod.id));
  26526. clientHotUpdateOptions.modules.push(...filteredModules.filter((mixedMod) => !clientHotUpdateOptions.modules.some((mod) => mod.id === mixedMod.id)).map((mixedMod) => mixedMod._clientModule).filter(Boolean));
  26527. if (ssrHotUpdateOptions) {
  26528. ssrHotUpdateOptions.modules = ssrHotUpdateOptions.modules.filter((mod) => filteredModules.some((mixedMod) => mod.id === mixedMod.id));
  26529. ssrHotUpdateOptions.modules.push(...filteredModules.filter((mixedMod) => !ssrHotUpdateOptions.modules.some((mod) => mod.id === mixedMod.id)).map((mixedMod) => mixedMod._ssrModule).filter(Boolean));
  26530. }
  26531. }
  26532. }
  26533. } catch (error) {
  26534. hotMap.get(server.environments.client).error = error;
  26535. }
  26536. for (const environment of Object.values(server.environments)) {
  26537. if (environment.name === "client") continue;
  26538. const hot = hotMap.get(environment);
  26539. const context = environment.pluginContainer.minimalContext;
  26540. try {
  26541. for (const plugin of getSortedHotUpdatePlugins(environment)) if (plugin.hotUpdate) {
  26542. const filteredModules = await getHookHandler(plugin.hotUpdate).call(context, hot.options);
  26543. if (filteredModules) hot.options.modules = filteredModules;
  26544. }
  26545. } catch (error) {
  26546. hot.error = error;
  26547. }
  26548. }
  26549. async function hmr(environment) {
  26550. try {
  26551. const { options, error } = hotMap.get(environment);
  26552. if (error) throw error;
  26553. if (!options.modules.length) {
  26554. if (file.endsWith(".html") && environment.name === "client") {
  26555. environment.logger.info(import_picocolors.default.green(`page reload `) + import_picocolors.default.dim(shortFile), {
  26556. clear: true,
  26557. timestamp: true
  26558. });
  26559. environment.hot.send({
  26560. type: "full-reload",
  26561. path: config.server.middlewareMode ? "*" : "/" + normalizePath(path.relative(config.root, file))
  26562. });
  26563. } else debugHmr?.(`(${environment.name}) [no modules matched] ${import_picocolors.default.dim(shortFile)}`);
  26564. return;
  26565. }
  26566. updateModules(environment, shortFile, options.modules, timestamp);
  26567. } catch (err) {
  26568. environment.hot.send({
  26569. type: "error",
  26570. err: prepareError(err)
  26571. });
  26572. }
  26573. }
  26574. await (server.config.server.hotUpdateEnvironments ?? ((server, hmr) => {
  26575. return Promise.all(Object.values(server.environments).map((environment) => hmr(environment)));
  26576. }))(server, hmr);
  26577. }
  26578. function updateModules(environment, file, modules, timestamp, firstInvalidatedBy) {
  26579. const { hot } = environment;
  26580. const updates = [];
  26581. const invalidatedModules = /* @__PURE__ */ new Set();
  26582. const traversedModules = /* @__PURE__ */ new Set();
  26583. let needFullReload = modules.length === 0;
  26584. for (const mod of modules) {
  26585. const boundaries = [];
  26586. const hasDeadEnd = propagateUpdate(mod, traversedModules, boundaries);
  26587. environment.moduleGraph.invalidateModule(mod, invalidatedModules, timestamp, true);
  26588. if (needFullReload) continue;
  26589. if (hasDeadEnd) {
  26590. needFullReload = hasDeadEnd;
  26591. continue;
  26592. }
  26593. if (firstInvalidatedBy && boundaries.some(({ acceptedVia }) => normalizeHmrUrl(acceptedVia.url) === firstInvalidatedBy)) {
  26594. needFullReload = "circular import invalidate";
  26595. continue;
  26596. }
  26597. updates.push(...boundaries.map(({ boundary, acceptedVia, isWithinCircularImport }) => ({
  26598. type: `${boundary.type}-update`,
  26599. timestamp,
  26600. path: normalizeHmrUrl(boundary.url),
  26601. acceptedPath: normalizeHmrUrl(acceptedVia.url),
  26602. explicitImportRequired: boundary.type === "js" ? isExplicitImportRequired(acceptedVia.url) : false,
  26603. isWithinCircularImport,
  26604. firstInvalidatedBy
  26605. })));
  26606. }
  26607. const isClientHtmlChange = file.endsWith(".html") && environment.name === "client" && modules.every((mod) => mod.type !== "js");
  26608. if (needFullReload || isClientHtmlChange) {
  26609. const reason = typeof needFullReload === "string" ? import_picocolors.default.dim(` (${needFullReload})`) : "";
  26610. environment.logger.info(import_picocolors.default.green(`page reload `) + import_picocolors.default.dim(file) + reason, {
  26611. clear: !firstInvalidatedBy,
  26612. timestamp: true
  26613. });
  26614. hot.send({
  26615. type: "full-reload",
  26616. triggeredBy: path.resolve(environment.config.root, file),
  26617. path: !isClientHtmlChange || environment.config.server.middlewareMode || updates.length > 0 ? "*" : "/" + file
  26618. });
  26619. return;
  26620. }
  26621. if (updates.length === 0) {
  26622. debugHmr?.(import_picocolors.default.yellow(`no update happened `) + import_picocolors.default.dim(file));
  26623. return;
  26624. }
  26625. environment.logger.info(import_picocolors.default.green(`hmr update `) + import_picocolors.default.dim([...new Set(updates.map((u) => u.path))].join(", ")), {
  26626. clear: !firstInvalidatedBy,
  26627. timestamp: true
  26628. });
  26629. hot.send({
  26630. type: "update",
  26631. updates
  26632. });
  26633. }
  26634. function areAllImportsAccepted(importedBindings, acceptedExports) {
  26635. for (const binding of importedBindings) if (!acceptedExports.has(binding)) return false;
  26636. return true;
  26637. }
  26638. function propagateUpdate(node, traversedModules, boundaries, currentChain = [node]) {
  26639. if (traversedModules.has(node)) return false;
  26640. traversedModules.add(node);
  26641. if (node.id && node.isSelfAccepting === void 0) {
  26642. debugHmr?.(`[propagate update] stop propagation because not analyzed: ${import_picocolors.default.dim(node.id)}`);
  26643. return false;
  26644. }
  26645. if (node.isSelfAccepting) {
  26646. const boundary = node;
  26647. boundaries.push({
  26648. boundary,
  26649. acceptedVia: boundary,
  26650. isWithinCircularImport: isNodeWithinCircularImports(node, currentChain)
  26651. });
  26652. return false;
  26653. }
  26654. if (node.acceptedHmrExports) {
  26655. const boundary = node;
  26656. boundaries.push({
  26657. boundary,
  26658. acceptedVia: boundary,
  26659. isWithinCircularImport: isNodeWithinCircularImports(node, currentChain)
  26660. });
  26661. } else if (!node.importers.size) return true;
  26662. for (const importer of node.importers) {
  26663. const subChain = currentChain.concat(importer);
  26664. if (importer.acceptedHmrDeps.has(node)) {
  26665. boundaries.push({
  26666. boundary: importer,
  26667. acceptedVia: node,
  26668. isWithinCircularImport: isNodeWithinCircularImports(importer, subChain)
  26669. });
  26670. continue;
  26671. }
  26672. if (node.id && node.acceptedHmrExports && importer.importedBindings) {
  26673. const importedBindingsFromNode = importer.importedBindings.get(node.id);
  26674. if (importedBindingsFromNode && areAllImportsAccepted(importedBindingsFromNode, node.acceptedHmrExports)) continue;
  26675. }
  26676. if (!currentChain.includes(importer) && propagateUpdate(importer, traversedModules, boundaries, subChain)) return true;
  26677. }
  26678. return false;
  26679. }
  26680. /**
  26681. * Check importers recursively if it's an import loop. An accepted module within
  26682. * an import loop cannot recover its execution order and should be reloaded.
  26683. *
  26684. * @param node The node that accepts HMR and is a boundary
  26685. * @param nodeChain The chain of nodes/imports that lead to the node.
  26686. * (The last node in the chain imports the `node` parameter)
  26687. * @param currentChain The current chain tracked from the `node` parameter
  26688. * @param traversedModules The set of modules that have traversed
  26689. */
  26690. function isNodeWithinCircularImports(node, nodeChain, currentChain = [node], traversedModules = /* @__PURE__ */ new Set()) {
  26691. if (traversedModules.has(node)) return false;
  26692. traversedModules.add(node);
  26693. for (const importer of node.importers) {
  26694. if (importer === node) continue;
  26695. const importerIndex = nodeChain.indexOf(importer);
  26696. if (importerIndex > -1) {
  26697. if (debugHmr) {
  26698. const importChain = [
  26699. importer,
  26700. ...[...currentChain].reverse(),
  26701. ...nodeChain.slice(importerIndex, -1).reverse()
  26702. ];
  26703. debugHmr(import_picocolors.default.yellow(`circular imports detected: `) + importChain.map((m) => import_picocolors.default.dim(m.url)).join(" -> "));
  26704. }
  26705. return true;
  26706. }
  26707. if (!currentChain.includes(importer)) {
  26708. const result = isNodeWithinCircularImports(importer, nodeChain, currentChain.concat(importer), traversedModules);
  26709. if (result) return result;
  26710. }
  26711. }
  26712. return false;
  26713. }
  26714. function handlePrunedModules(mods, { hot }) {
  26715. const t = monotonicDateNow();
  26716. mods.forEach((mod) => {
  26717. mod.lastHMRTimestamp = t;
  26718. mod.lastHMRInvalidationReceived = false;
  26719. debugHmr?.(`[dispose] ${import_picocolors.default.dim(mod.file)}`);
  26720. });
  26721. hot.send({
  26722. type: "prune",
  26723. paths: [...mods].map((m) => m.url)
  26724. });
  26725. }
  26726. var LexerState = /* @__PURE__ */ function(LexerState) {
  26727. LexerState[LexerState["inCall"] = 0] = "inCall";
  26728. LexerState[LexerState["inSingleQuoteString"] = 1] = "inSingleQuoteString";
  26729. LexerState[LexerState["inDoubleQuoteString"] = 2] = "inDoubleQuoteString";
  26730. LexerState[LexerState["inTemplateString"] = 3] = "inTemplateString";
  26731. LexerState[LexerState["inArray"] = 4] = "inArray";
  26732. return LexerState;
  26733. }(LexerState || {});
  26734. /**
  26735. * Lex import.meta.hot.accept() for accepted deps.
  26736. * Since hot.accept() can only accept string literals or array of string
  26737. * literals, we don't really need a heavy @babel/parse call on the entire source.
  26738. *
  26739. * @returns selfAccepts
  26740. */
  26741. function lexAcceptedHmrDeps(code, start, urls) {
  26742. let state = LexerState.inCall;
  26743. let prevState = LexerState.inCall;
  26744. let currentDep = "";
  26745. function addDep(index) {
  26746. urls.add({
  26747. url: currentDep,
  26748. start: index - currentDep.length - 1,
  26749. end: index + 1
  26750. });
  26751. currentDep = "";
  26752. }
  26753. for (let i = start; i < code.length; i++) {
  26754. const char = code.charAt(i);
  26755. switch (state) {
  26756. case LexerState.inCall:
  26757. case LexerState.inArray:
  26758. if (char === `'`) {
  26759. prevState = state;
  26760. state = LexerState.inSingleQuoteString;
  26761. } else if (char === `"`) {
  26762. prevState = state;
  26763. state = LexerState.inDoubleQuoteString;
  26764. } else if (char === "`") {
  26765. prevState = state;
  26766. state = LexerState.inTemplateString;
  26767. } else if (whitespaceRE.test(char)) continue;
  26768. else if (state === LexerState.inCall) if (char === `[`) state = LexerState.inArray;
  26769. else return true;
  26770. else if (char === `]`) return false;
  26771. else if (char === ",") continue;
  26772. else error(i);
  26773. break;
  26774. case LexerState.inSingleQuoteString:
  26775. if (char === `'`) {
  26776. addDep(i);
  26777. if (prevState === LexerState.inCall) return false;
  26778. else state = prevState;
  26779. } else currentDep += char;
  26780. break;
  26781. case LexerState.inDoubleQuoteString:
  26782. if (char === `"`) {
  26783. addDep(i);
  26784. if (prevState === LexerState.inCall) return false;
  26785. else state = prevState;
  26786. } else currentDep += char;
  26787. break;
  26788. case LexerState.inTemplateString:
  26789. if (char === "`") {
  26790. addDep(i);
  26791. if (prevState === LexerState.inCall) return false;
  26792. else state = prevState;
  26793. } else if (char === "$" && code.charAt(i + 1) === "{") error(i);
  26794. else currentDep += char;
  26795. break;
  26796. default: throw new Error("unknown import.meta.hot lexer state");
  26797. }
  26798. }
  26799. return false;
  26800. }
  26801. function lexAcceptedHmrExports(code, start, exportNames) {
  26802. const urls = /* @__PURE__ */ new Set();
  26803. lexAcceptedHmrDeps(code, start, urls);
  26804. for (const { url } of urls) exportNames.add(url);
  26805. return urls.size > 0;
  26806. }
  26807. function normalizeHmrUrl(url) {
  26808. if (url[0] !== "." && url[0] !== "/") url = wrapId(url);
  26809. return url;
  26810. }
  26811. function error(pos) {
  26812. const err = /* @__PURE__ */ new Error("import.meta.hot.accept() can only accept string literals or an Array of string literals.");
  26813. err.pos = pos;
  26814. throw err;
  26815. }
  26816. async function readModifiedFile(file) {
  26817. const content = await fsp.readFile(file, "utf-8");
  26818. if (!content) {
  26819. const mtime = (await fsp.stat(file)).mtimeMs;
  26820. for (let n = 0; n < 10; n++) {
  26821. await new Promise((r) => setTimeout(r, 10));
  26822. if ((await fsp.stat(file)).mtimeMs !== mtime) break;
  26823. }
  26824. return await fsp.readFile(file, "utf-8");
  26825. } else return content;
  26826. }
  26827. function createServerHotChannel() {
  26828. const innerEmitter = new EventEmitter();
  26829. const outsideEmitter = new EventEmitter();
  26830. return {
  26831. send(payload) {
  26832. outsideEmitter.emit("send", payload);
  26833. },
  26834. off(event, listener) {
  26835. innerEmitter.off(event, listener);
  26836. },
  26837. on: ((event, listener) => {
  26838. innerEmitter.on(event, listener);
  26839. }),
  26840. close() {
  26841. innerEmitter.removeAllListeners();
  26842. outsideEmitter.removeAllListeners();
  26843. },
  26844. listen() {
  26845. innerEmitter.emit("connection");
  26846. },
  26847. api: {
  26848. innerEmitter,
  26849. outsideEmitter
  26850. }
  26851. };
  26852. }
  26853. //#endregion
  26854. //#region src/node/external.ts
  26855. const debug$5 = createDebugger("vite:external");
  26856. const isExternalCache = /* @__PURE__ */ new WeakMap();
  26857. function shouldExternalize(environment, id, importer) {
  26858. let isExternal = isExternalCache.get(environment);
  26859. if (!isExternal) {
  26860. isExternal = createIsExternal(environment);
  26861. isExternalCache.set(environment, isExternal);
  26862. }
  26863. return isExternal(id, importer);
  26864. }
  26865. function createIsConfiguredAsExternal(environment) {
  26866. const { config } = environment;
  26867. const { root, resolve } = config;
  26868. const { external, noExternal } = resolve;
  26869. const noExternalFilter = typeof noExternal !== "boolean" && !(Array.isArray(noExternal) && noExternal.length === 0) && createFilter$1(void 0, noExternal, { resolve: false });
  26870. const targetConditions = resolve.externalConditions;
  26871. const resolveOptions = {
  26872. ...resolve,
  26873. root,
  26874. isProduction: false,
  26875. isBuild: true,
  26876. conditions: targetConditions
  26877. };
  26878. const isExternalizable = (id, importer, configuredAsExternal) => {
  26879. if (!bareImportRE.test(id) || id.includes("\0")) return false;
  26880. try {
  26881. const resolved = tryNodeResolve(id, config.command === "build" ? void 0 : importer, resolveOptions, void 0, false);
  26882. if (!resolved) return false;
  26883. if (!configuredAsExternal && !isInNodeModules(resolved.id)) return false;
  26884. return canExternalizeFile(resolved.id);
  26885. } catch {
  26886. debug$5?.(`Failed to node resolve "${id}". Skipping externalizing it by default.`);
  26887. return false;
  26888. }
  26889. };
  26890. return (id, importer) => {
  26891. if (external !== true && external.includes(id)) return true;
  26892. const pkgName = getNpmPackageName(id);
  26893. if (!pkgName) return isExternalizable(id, importer, false);
  26894. if (external !== true && external.includes(pkgName)) return isExternalizable(id, importer, true);
  26895. if (typeof noExternal === "boolean") return !noExternal;
  26896. if (noExternalFilter && !noExternalFilter(pkgName)) return false;
  26897. return isExternalizable(id, importer, external === true);
  26898. };
  26899. }
  26900. function createIsExternal(environment) {
  26901. const processedIds = /* @__PURE__ */ new Map();
  26902. const isConfiguredAsExternal = createIsConfiguredAsExternal(environment);
  26903. return (id, importer) => {
  26904. if (processedIds.has(id)) return processedIds.get(id);
  26905. let isExternal = false;
  26906. if (id[0] !== "." && !path.isAbsolute(id)) isExternal = isBuiltin(environment.config.resolve.builtins, id) || isConfiguredAsExternal(id, importer);
  26907. processedIds.set(id, isExternal);
  26908. return isExternal;
  26909. };
  26910. }
  26911. function canExternalizeFile(filePath) {
  26912. const ext = path.extname(filePath);
  26913. return !ext || ext === ".js" || ext === ".mjs" || ext === ".cjs";
  26914. }
  26915. //#endregion
  26916. //#region src/node/plugins/worker.ts
  26917. var WorkerOutputCache = class {
  26918. /**
  26919. * worker bundle information for each input id
  26920. * used to bundle the same worker file only once
  26921. */
  26922. bundles = /* @__PURE__ */ new Map();
  26923. /** list of assets emitted for the worker bundles */
  26924. assets = /* @__PURE__ */ new Map();
  26925. fileNameHash = /* @__PURE__ */ new Map();
  26926. invalidatedBundles = /* @__PURE__ */ new Set();
  26927. saveWorkerBundle(file, watchedFiles, outputEntryFilename, outputEntryCode, outputAssets, logger) {
  26928. for (const asset of outputAssets) this.saveAsset(asset, logger);
  26929. const bundle = {
  26930. entryFilename: outputEntryFilename,
  26931. entryCode: outputEntryCode,
  26932. entryUrlPlaceholder: this.generateEntryUrlPlaceholder(outputEntryFilename),
  26933. referencedAssets: new Set(outputAssets.map((asset) => asset.fileName)),
  26934. watchedFiles
  26935. };
  26936. this.bundles.set(file, bundle);
  26937. return bundle;
  26938. }
  26939. saveAsset(asset, logger) {
  26940. const duplicateAsset = this.assets.get(asset.fileName);
  26941. if (duplicateAsset) {
  26942. 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.`));
  26943. }
  26944. this.assets.set(asset.fileName, asset);
  26945. }
  26946. invalidateAffectedBundles(file) {
  26947. for (const [bundleInputFile, bundle] of this.bundles.entries()) if (bundle.watchedFiles.includes(file)) this.invalidatedBundles.add(bundleInputFile);
  26948. }
  26949. removeBundleIfInvalidated(file) {
  26950. if (this.invalidatedBundles.has(file)) {
  26951. this.invalidatedBundles.delete(file);
  26952. this.removeBundle(file);
  26953. }
  26954. }
  26955. removeBundle(file) {
  26956. const bundle = this.bundles.get(file);
  26957. if (!bundle) return;
  26958. this.bundles.delete(file);
  26959. this.fileNameHash.delete(getHash(bundle.entryFilename));
  26960. this.assets.delete(bundle.entryFilename);
  26961. const keptBundles = [...this.bundles.values()];
  26962. for (const asset of bundle.referencedAssets) if (keptBundles.every((b) => !b.referencedAssets.has(asset))) this.assets.delete(asset);
  26963. }
  26964. getWorkerBundle(file) {
  26965. return this.bundles.get(file);
  26966. }
  26967. getAssets() {
  26968. return this.assets.values();
  26969. }
  26970. getEntryFilenameFromHash(hash) {
  26971. return this.fileNameHash.get(hash);
  26972. }
  26973. generateEntryUrlPlaceholder(entryFilename) {
  26974. const hash = getHash(entryFilename);
  26975. if (!this.fileNameHash.has(hash)) this.fileNameHash.set(hash, entryFilename);
  26976. return `__VITE_WORKER_ASSET__${hash}__`;
  26977. }
  26978. };
  26979. const workerOrSharedWorkerRE = /(?:\?|&)(worker|sharedworker)(?:&|$)/;
  26980. const workerFileRE = /(?:\?|&)worker_file&type=(\w+)(?:&|$)/;
  26981. const inlineRE = /[?&]inline\b/;
  26982. const WORKER_FILE_ID = "worker_file";
  26983. const workerOutputCaches = /* @__PURE__ */ new WeakMap();
  26984. async function bundleWorkerEntry(config, id) {
  26985. const input = cleanUrl(id);
  26986. const workerOutput = workerOutputCaches.get(config.mainConfig || config);
  26987. workerOutput.removeBundleIfInvalidated(input);
  26988. const bundleInfo = workerOutput.getWorkerBundle(input);
  26989. if (bundleInfo) return bundleInfo;
  26990. const newBundleChain = [...config.bundleChain, input];
  26991. 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(" -> ")}`);
  26992. const { rolldown } = await import("rolldown");
  26993. const { plugins, rollupOptions, format } = config.worker;
  26994. const workerEnvironment = new BuildEnvironment("client", await plugins(newBundleChain));
  26995. await workerEnvironment.init();
  26996. const chunkMetadataMap = new ChunkMetadataMap();
  26997. const bundle = await rolldown({
  26998. ...rollupOptions,
  26999. input,
  27000. plugins: workerEnvironment.plugins.map((p) => injectEnvironmentToHooks(workerEnvironment, chunkMetadataMap, p)),
  27001. onLog(level, log) {
  27002. onRollupLog(level, log, workerEnvironment);
  27003. },
  27004. moduleTypes: {
  27005. ".css": "js",
  27006. ...rollupOptions.moduleTypes
  27007. },
  27008. preserveEntrySignatures: false
  27009. });
  27010. let result;
  27011. let watchedFiles;
  27012. try {
  27013. const workerOutputConfig = config.worker.rollupOptions.output;
  27014. const workerConfig = workerOutputConfig ? Array.isArray(workerOutputConfig) ? workerOutputConfig[0] || {} : workerOutputConfig : {};
  27015. result = await bundle.generate({
  27016. entryFileNames: path.posix.join(config.build.assetsDir, "[name]-[hash].js"),
  27017. chunkFileNames: path.posix.join(config.build.assetsDir, "[name]-[hash].js"),
  27018. assetFileNames: path.posix.join(config.build.assetsDir, "[name]-[hash].[ext]"),
  27019. minify: config.build.minify === "oxc" ? true : config.build.minify === false ? "dce-only" : void 0,
  27020. ...workerConfig,
  27021. format,
  27022. sourcemap: config.build.sourcemap
  27023. });
  27024. watchedFiles = (await bundle.watchFiles).map((f) => normalizePath(f));
  27025. } catch (e) {
  27026. 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");
  27027. throw e;
  27028. } finally {
  27029. await bundle.close();
  27030. }
  27031. const { output: [outputChunk, ...outputChunks] } = result;
  27032. const assets = outputChunks.map((outputChunk) => outputChunk.type === "asset" ? outputChunk : {
  27033. fileName: outputChunk.fileName,
  27034. originalFileName: null,
  27035. originalFileNames: [],
  27036. source: outputChunk.code
  27037. });
  27038. if ((config.build.sourcemap === "hidden" || config.build.sourcemap === true) && outputChunk.map) assets.push({
  27039. fileName: outputChunk.fileName + ".map",
  27040. originalFileName: null,
  27041. originalFileNames: [],
  27042. source: outputChunk.map.toString()
  27043. });
  27044. return workerOutputCaches.get(config.mainConfig || config).saveWorkerBundle(input, watchedFiles, outputChunk.fileName, outputChunk.code, assets, config.logger);
  27045. }
  27046. const workerAssetUrlRE = /__VITE_WORKER_ASSET__([a-z\d]{8})__/g;
  27047. async function workerFileToUrl(config, id) {
  27048. const workerOutput = workerOutputCaches.get(config.mainConfig || config);
  27049. const bundle = await bundleWorkerEntry(config, id);
  27050. workerOutput.saveAsset({
  27051. fileName: bundle.entryFilename,
  27052. originalFileName: null,
  27053. originalFileNames: [],
  27054. source: bundle.entryCode
  27055. }, config.logger);
  27056. return bundle;
  27057. }
  27058. function webWorkerPostPlugin(config) {
  27059. if (config.isBundled) return perEnvironmentPlugin("native:web-worker-post-plugin", (environment) => {
  27060. if (environment.config.worker.format === "iife") return viteWebWorkerPostPlugin();
  27061. });
  27062. return {
  27063. name: "vite:worker-post",
  27064. transform: {
  27065. filter: { code: "import.meta" },
  27066. order: "post",
  27067. async handler(code, id) {
  27068. if (this.environment.config.worker.format === "iife") {
  27069. await init;
  27070. let imports;
  27071. try {
  27072. imports = parse$2(code)[0];
  27073. } catch {
  27074. return;
  27075. }
  27076. let injectedImportMeta = false;
  27077. let s;
  27078. for (const { s: start, e: end, d: dynamicIndex } of imports) if (dynamicIndex === -2) if (code.slice(end, end + 4) === ".url") {
  27079. s ||= new MagicString(code);
  27080. s.overwrite(start, end + 4, "self.location.href");
  27081. } else {
  27082. s ||= new MagicString(code);
  27083. if (!injectedImportMeta) {
  27084. s.prepend("const _vite_importMeta = { url: self.location.href };\n");
  27085. injectedImportMeta = true;
  27086. }
  27087. s.overwrite(start, end, "_vite_importMeta");
  27088. }
  27089. if (!s) return;
  27090. return {
  27091. code: s.toString(),
  27092. map: s.generateMap({
  27093. hires: "boundary",
  27094. source: id
  27095. })
  27096. };
  27097. }
  27098. }
  27099. }
  27100. };
  27101. }
  27102. function webWorkerPlugin(config) {
  27103. const isBuild = config.command === "build";
  27104. const isWorker = config.isWorker;
  27105. workerOutputCaches.set(config, new WorkerOutputCache());
  27106. const emittedAssets = /* @__PURE__ */ new Set();
  27107. return {
  27108. name: "vite:worker",
  27109. buildStart() {
  27110. if (isWorker) return;
  27111. emittedAssets.clear();
  27112. },
  27113. load: {
  27114. filter: { id: workerOrSharedWorkerRE },
  27115. async handler(id) {
  27116. const workerMatch = workerOrSharedWorkerRE.exec(id);
  27117. if (!workerMatch) return;
  27118. const { format } = config.worker;
  27119. const workerConstructor = workerMatch[1] === "sharedworker" ? "SharedWorker" : "Worker";
  27120. const workerType = config.isBundled ? format === "es" ? "module" : "classic" : "module";
  27121. const workerTypeOption = `{
  27122. ${workerType === "module" ? `type: "module",` : ""}
  27123. name: options?.name
  27124. }`;
  27125. let urlCode;
  27126. if (config.isBundled) if (isWorker && config.bundleChain.at(-1) === cleanUrl(id)) urlCode = "self.location.href";
  27127. else if (inlineRE.test(id)) {
  27128. const result = await bundleWorkerEntry(config, id);
  27129. for (const file of result.watchedFiles) this.addWatchFile(file);
  27130. const jsContent = `const jsContent = ${JSON.stringify(result.entryCode)};`;
  27131. return {
  27132. code: workerConstructor === "Worker" ? `${jsContent}
  27133. 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" });
  27134. export default function WorkerWrapper(options) {
  27135. let objURL;
  27136. try {
  27137. objURL = blob && (self.URL || self.webkitURL).createObjectURL(blob);
  27138. if (!objURL) throw ''
  27139. const worker = new ${workerConstructor}(objURL, ${workerTypeOption});
  27140. worker.addEventListener("error", () => {
  27141. (self.URL || self.webkitURL).revokeObjectURL(objURL);
  27142. });
  27143. return worker;
  27144. } catch(e) {
  27145. return new ${workerConstructor}(
  27146. 'data:text/javascript;charset=utf-8,' + encodeURIComponent(jsContent),
  27147. ${workerTypeOption}
  27148. );
  27149. }
  27150. }` : `${jsContent}
  27151. export default function WorkerWrapper(options) {
  27152. return new ${workerConstructor}(
  27153. 'data:text/javascript;charset=utf-8,' + encodeURIComponent(jsContent),
  27154. ${workerTypeOption}
  27155. );
  27156. }
  27157. `,
  27158. map: { mappings: "" }
  27159. };
  27160. } else {
  27161. const result = await workerFileToUrl(config, id);
  27162. let url;
  27163. if (this.environment.config.command === "serve" && this.environment.config.experimental.bundledDev) url = toOutputFilePathInJSForBundledDev(this.environment, result.entryFilename);
  27164. else url = result.entryUrlPlaceholder;
  27165. urlCode = JSON.stringify(url);
  27166. for (const file of result.watchedFiles) this.addWatchFile(file);
  27167. }
  27168. else {
  27169. let url = await fileToUrl$1(this, cleanUrl(id));
  27170. url = injectQuery(url, `${WORKER_FILE_ID}&type=${workerType}`);
  27171. urlCode = JSON.stringify(url);
  27172. }
  27173. if (urlRE$1.test(id)) return {
  27174. code: `export default ${urlCode}`,
  27175. map: { mappings: "" }
  27176. };
  27177. return {
  27178. code: `export default function WorkerWrapper(options) {
  27179. return new ${workerConstructor}(
  27180. ${urlCode},
  27181. ${workerTypeOption}
  27182. );
  27183. }`,
  27184. map: { mappings: "" }
  27185. };
  27186. }
  27187. },
  27188. transform: {
  27189. filter: { id: workerFileRE },
  27190. async handler(raw, id) {
  27191. const workerFileMatch = workerFileRE.exec(id);
  27192. if (workerFileMatch) {
  27193. const workerType = workerFileMatch[1];
  27194. let injectEnv = "";
  27195. if (workerType === "classic") injectEnv = `importScripts(${JSON.stringify(path.posix.join(config.base, ENV_PUBLIC_PATH))})\n`;
  27196. else if (workerType === "module") injectEnv = `import ${JSON.stringify(ENV_PUBLIC_PATH)}\n`;
  27197. else if (workerType === "ignore") if (config.isBundled) injectEnv = "";
  27198. else {
  27199. const environment = this.environment;
  27200. injectEnv = ((environment.mode === "dev" ? environment.moduleGraph : void 0)?.getModuleById(ENV_ENTRY))?.transformResult?.code || "";
  27201. }
  27202. if (injectEnv) {
  27203. const s = new MagicString(raw);
  27204. s.prepend(injectEnv + ";\n");
  27205. return {
  27206. code: s.toString(),
  27207. map: s.generateMap({ hires: "boundary" })
  27208. };
  27209. }
  27210. }
  27211. }
  27212. },
  27213. ...isBuild ? { renderChunk(code, chunk, outputOptions) {
  27214. let s;
  27215. const result = () => {
  27216. return s && {
  27217. code: s.toString(),
  27218. map: this.environment.config.build.sourcemap ? s.generateMap({ hires: "boundary" }) : null
  27219. };
  27220. };
  27221. workerAssetUrlRE.lastIndex = 0;
  27222. if (workerAssetUrlRE.test(code)) {
  27223. const toRelativeRuntime = createToImportMetaURLBasedRelativeRuntime(outputOptions.format, this.environment.config.isWorker);
  27224. let match;
  27225. s = new MagicString(code);
  27226. workerAssetUrlRE.lastIndex = 0;
  27227. const workerOutputCache = workerOutputCaches.get(config.mainConfig || config);
  27228. while (match = workerAssetUrlRE.exec(code)) {
  27229. const [full, hash] = match;
  27230. const filename = workerOutputCache.getEntryFilenameFromHash(hash);
  27231. if (!filename) {
  27232. this.warn(`Could not find worker asset for hash: ${hash}`);
  27233. continue;
  27234. }
  27235. const replacement = toOutputFilePathInJS(this.environment, filename, "asset", chunk.fileName, "js", toRelativeRuntime);
  27236. const replacementString = typeof replacement === "string" ? JSON.stringify(encodeURIPath(replacement)).slice(1, -1) : `"+${replacement.runtime}+"`;
  27237. s.update(match.index, match.index + full.length, replacementString);
  27238. }
  27239. }
  27240. return result();
  27241. } } : {},
  27242. generateBundle(opts, bundle) {
  27243. if (this.environment.config.isOutputOptionsForLegacyChunks?.(opts) || isWorker) return;
  27244. for (const asset of workerOutputCaches.get(config).getAssets()) {
  27245. if (emittedAssets.has(asset.fileName)) continue;
  27246. emittedAssets.add(asset.fileName);
  27247. const duplicateAsset = bundle[asset.fileName];
  27248. if (duplicateAsset) {
  27249. if (isSameContent(duplicateAsset.type === "asset" ? duplicateAsset.source : duplicateAsset.code, asset.source)) continue;
  27250. }
  27251. this.emitFile({
  27252. type: "asset",
  27253. fileName: asset.fileName,
  27254. source: asset.source
  27255. });
  27256. }
  27257. },
  27258. watchChange(file) {
  27259. if (isWorker) return;
  27260. workerOutputCaches.get(config).invalidateAffectedBundles(normalizePath(file));
  27261. }
  27262. };
  27263. }
  27264. function isSameContent(a, b) {
  27265. if (typeof a === "string") {
  27266. if (typeof b === "string") return a === b;
  27267. return Buffer.from(a).equals(b);
  27268. }
  27269. return Buffer.from(b).equals(a);
  27270. }
  27271. //#endregion
  27272. //#region src/node/plugins/preAlias.ts
  27273. /**
  27274. * A plugin to avoid an aliased AND optimized dep from being aliased in src
  27275. */
  27276. function preAliasPlugin(config) {
  27277. const findPatterns = getAliasPatterns(config.resolve.alias);
  27278. return {
  27279. name: "vite:pre-alias",
  27280. applyToEnvironment(environment) {
  27281. return !isDepOptimizationDisabled(environment.config.optimizeDeps);
  27282. },
  27283. async resolveId(id, importer, options) {
  27284. const environment = this.environment;
  27285. const ssr = environment.config.consumer === "server";
  27286. const depsOptimizer = environment.depsOptimizer;
  27287. if (importer && depsOptimizer && bareImportRE.test(id) && !options.scan && id !== "@vite/client" && id !== "@vite/env") {
  27288. if (findPatterns.find((pattern) => matches(pattern, id))) {
  27289. const optimizedId = await tryOptimizedResolve(depsOptimizer, id, importer, config.resolve.preserveSymlinks, config.packageCache);
  27290. if (optimizedId) return optimizedId;
  27291. if (depsOptimizer.options.noDiscovery) return;
  27292. const resolved = await this.resolve(id, importer, options);
  27293. if (resolved && !depsOptimizer.isOptimizedDepFile(resolved.id)) {
  27294. const optimizeDeps = depsOptimizer.options;
  27295. const resolvedId = cleanUrl(resolved.id);
  27296. 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))) {
  27297. const optimizedInfo = depsOptimizer.registerMissingImport(id, resolvedId);
  27298. return { id: depsOptimizer.getOptimizedDepId(optimizedInfo) };
  27299. }
  27300. }
  27301. return resolved;
  27302. }
  27303. }
  27304. }
  27305. };
  27306. }
  27307. function optimizeAliasReplacementForSSR(id, optimizeDeps) {
  27308. if (optimizeDeps.include?.includes(id)) return true;
  27309. return false;
  27310. }
  27311. function matches(pattern, importee) {
  27312. if (pattern instanceof RegExp) return pattern.test(importee);
  27313. if (importee.length < pattern.length) return false;
  27314. if (importee === pattern) return true;
  27315. return importee.startsWith(withTrailingSlash(pattern));
  27316. }
  27317. function getAliasPatterns(entries) {
  27318. if (Array.isArray(entries)) return entries.map((entry) => entry.find);
  27319. return Object.entries(entries).map(([find]) => find);
  27320. }
  27321. function getAliasPatternMatcher(entries) {
  27322. const patterns = getAliasPatterns(entries);
  27323. return (importee) => patterns.some((pattern) => matches(pattern, importee));
  27324. }
  27325. //#endregion
  27326. //#region src/node/plugins/importAnalysis.ts
  27327. const debug$4 = createDebugger("vite:import-analysis");
  27328. const clientDir = normalizePath(CLIENT_DIR);
  27329. const skipRE = /\.(?:map|json)(?:$|\?)/;
  27330. const canSkipImportAnalysis = (id) => skipRE.test(id) || isDirectCSSRequest(id);
  27331. const optimizedDepChunkRE = /\/chunk-[A-Z\d]{8}\.js/;
  27332. const hasViteIgnoreRE = /\/\*\s*@vite-ignore\s*\*\//;
  27333. const urlIsStringRE = /^(?:'.*'|".*"|`.*`)$/;
  27334. const templateLiteralRE = /^\s*`(.*)`\s*$/;
  27335. function isExplicitImportRequired(url) {
  27336. return !isJSRequest(url) && !isCSSRequest(url);
  27337. }
  27338. function normalizeResolvedIdToUrl(environment, url, resolved) {
  27339. const root = environment.config.root;
  27340. const depsOptimizer = environment.depsOptimizer;
  27341. if (resolved.id.startsWith(withTrailingSlash(root))) url = resolved.id.slice(root.length);
  27342. 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);
  27343. else url = resolved.id;
  27344. if (url[0] !== "." && url[0] !== "/") url = wrapId(resolved.id);
  27345. return url;
  27346. }
  27347. function extractImportedBindings(id, source, importSpec, importedBindings) {
  27348. let bindings = importedBindings.get(id);
  27349. if (!bindings) {
  27350. bindings = /* @__PURE__ */ new Set();
  27351. importedBindings.set(id, bindings);
  27352. }
  27353. if (importSpec.d > -1 || importSpec.d === -2) {
  27354. bindings.add("*");
  27355. return;
  27356. }
  27357. const exp = source.slice(importSpec.ss, importSpec.se);
  27358. ESM_STATIC_IMPORT_RE.lastIndex = 0;
  27359. const match = ESM_STATIC_IMPORT_RE.exec(exp);
  27360. if (!match) return;
  27361. const parsed = parseStaticImport({
  27362. type: "static",
  27363. code: match[0],
  27364. start: match.index,
  27365. end: match.index + match[0].length,
  27366. imports: match.groups.imports,
  27367. specifier: match.groups.specifier
  27368. });
  27369. if (parsed.namespacedImport) bindings.add("*");
  27370. if (parsed.defaultImport) bindings.add("default");
  27371. if (parsed.namedImports) for (const name of Object.keys(parsed.namedImports)) bindings.add(name);
  27372. }
  27373. /**
  27374. * Dev-only plugin that lexes, resolves, rewrites and analyzes url imports.
  27375. *
  27376. * - Imports are resolved to ensure they exist on disk
  27377. *
  27378. * - Lexes HMR accept calls and updates import relationships in the module graph
  27379. *
  27380. * - Bare module imports are resolved (by @rollup-plugin/node-resolve) to
  27381. * absolute file paths, e.g.
  27382. *
  27383. * ```js
  27384. * import 'foo'
  27385. * ```
  27386. * is rewritten to
  27387. * ```js
  27388. * import '/@fs//project/node_modules/foo/dist/foo.js'
  27389. * ```
  27390. *
  27391. * - CSS imports are appended with `.js` since both the js module and the actual
  27392. * css (referenced via `<link>`) may go through the transform pipeline:
  27393. *
  27394. * ```js
  27395. * import './style.css'
  27396. * ```
  27397. * is rewritten to
  27398. * ```js
  27399. * import './style.css.js'
  27400. * ```
  27401. */
  27402. function importAnalysisPlugin(config) {
  27403. const { root, base } = config;
  27404. const clientPublicPath = path.posix.join(base, CLIENT_PUBLIC_PATH);
  27405. const enablePartialAccept = config.experimental.hmrPartialAccept;
  27406. const matchAlias = getAliasPatternMatcher(config.resolve.alias);
  27407. let _env;
  27408. let _ssrEnv;
  27409. function getEnv(ssr) {
  27410. if (!_ssrEnv || !_env) {
  27411. const importMetaEnvKeys = {};
  27412. const userDefineEnv = {};
  27413. for (const key in config.env) importMetaEnvKeys[key] = JSON.stringify(config.env[key]);
  27414. for (const key in config.define) if (key.startsWith("import.meta.env.")) userDefineEnv[key.slice(16)] = config.define[key];
  27415. const env = `import.meta.env = ${serializeDefine({
  27416. ...importMetaEnvKeys,
  27417. SSR: "__vite_ssr__",
  27418. ...userDefineEnv
  27419. })};`;
  27420. _ssrEnv = env.replace("__vite_ssr__", "true");
  27421. _env = env.replace("__vite_ssr__", "false");
  27422. }
  27423. return ssr ? _ssrEnv : _env;
  27424. }
  27425. return {
  27426. name: "vite:import-analysis",
  27427. async transform(source, importer) {
  27428. const environment = this.environment;
  27429. const ssr = environment.config.consumer === "server";
  27430. const moduleGraph = environment.moduleGraph;
  27431. if (canSkipImportAnalysis(importer)) {
  27432. debug$4?.(import_picocolors.default.dim(`[skipped] ${prettifyUrl(importer, root)}`));
  27433. return null;
  27434. }
  27435. const msAtStart = debug$4 ? performance$1.now() : 0;
  27436. await init;
  27437. let imports;
  27438. let exports;
  27439. source = stripBomTag(source);
  27440. try {
  27441. [imports, exports] = parse$2(source);
  27442. } catch (_e) {
  27443. const e = _e;
  27444. const { message, showCodeFrame } = createParseErrorInfo(importer, source);
  27445. this.error(message, showCodeFrame ? e.idx : void 0);
  27446. }
  27447. const depsOptimizer = environment.depsOptimizer;
  27448. const importerModule = moduleGraph.getModuleById(importer);
  27449. if (!importerModule) throwOutdatedRequest(importer);
  27450. if (!imports.length && !this._addedImports) {
  27451. const prunedImports = await moduleGraph.updateModuleInfo(importerModule, /* @__PURE__ */ new Set(), null, /* @__PURE__ */ new Set(), null, false);
  27452. if (prunedImports) handlePrunedModules(prunedImports, environment);
  27453. debug$4?.(`${timeFrom(msAtStart)} ${import_picocolors.default.dim(`[no imports] ${prettifyUrl(importer, root)}`)}`);
  27454. return source;
  27455. }
  27456. let hasHMR = false;
  27457. let isSelfAccepting = false;
  27458. let hasEnv = false;
  27459. let needQueryInjectHelper = false;
  27460. let s;
  27461. const str = () => s || (s = new MagicString(source));
  27462. let isPartiallySelfAccepting = false;
  27463. const importedBindings = enablePartialAccept ? /* @__PURE__ */ new Map() : null;
  27464. const normalizeUrl = async (url, pos, forceSkipImportAnalysis = false) => {
  27465. let importerFile = importer;
  27466. if (depsOptimizer && moduleListContains(depsOptimizer.options.exclude, url)) {
  27467. await depsOptimizer.scanProcessing;
  27468. for (const optimizedModule of depsOptimizer.metadata.depInfoList) {
  27469. if (!optimizedModule.src) continue;
  27470. if (optimizedModule.file === importerModule.file) importerFile = optimizedModule.src;
  27471. }
  27472. }
  27473. const resolved = await this.resolve(url, importerFile).catch((e) => {
  27474. if (e instanceof Error) e.pos ??= pos;
  27475. throw e;
  27476. });
  27477. if (!resolved || resolved.meta?.["vite:alias"]?.noResolved) {
  27478. if (ssr) return [url, null];
  27479. importerModule.isSelfAccepting = false;
  27480. moduleGraph._hasResolveFailedErrorModules.add(importerModule);
  27481. return this.error(`Failed to resolve import "${url}" from "${normalizePath(path.relative(process.cwd(), importerFile))}". Does the file exist?`, pos);
  27482. }
  27483. if (isExternalUrl(resolved.id)) return [resolved.id, resolved.id];
  27484. url = normalizeResolvedIdToUrl(environment, url, resolved);
  27485. try {
  27486. const depModule = await moduleGraph._ensureEntryFromUrl(unwrapId(url), canSkipImportAnalysis(url) || forceSkipImportAnalysis, resolved);
  27487. if (environment.config.consumer === "client" && depModule.lastHMRTimestamp > 0) url = injectQuery(url, `t=${depModule.lastHMRTimestamp}`);
  27488. } catch (e) {
  27489. e.pos = pos;
  27490. throw e;
  27491. }
  27492. if (environment.config.consumer === "client") {
  27493. const isRelative = url[0] === ".";
  27494. const isSelfImport = !isRelative && cleanUrl(url) === cleanUrl(importer);
  27495. if (isExplicitImportRequired(url)) url = injectQuery(url, "import");
  27496. else if ((isRelative || isSelfImport) && !DEP_VERSION_RE.test(url)) {
  27497. const versionMatch = DEP_VERSION_RE.exec(importer);
  27498. if (versionMatch) url = injectQuery(url, versionMatch[1]);
  27499. }
  27500. }
  27501. if (!ssr) url = joinUrlSegments(base, url);
  27502. return [url, resolved.id];
  27503. };
  27504. const orderedImportedUrls = new Array(imports.length);
  27505. const orderedAcceptedUrls = new Array(imports.length);
  27506. const orderedAcceptedExports = new Array(imports.length);
  27507. let _isNodeModeResult = config.legacy?.inconsistentCjsInterop ? false : void 0;
  27508. const isNodeMode = () => {
  27509. _isNodeModeResult ??= isFilePathESM(importer, config.packageCache);
  27510. return _isNodeModeResult;
  27511. };
  27512. await Promise.all(imports.map(async (importSpecifier, index) => {
  27513. const { s: start, e: end, ss: expStart, se: expEnd, d: dynamicIndex, a: attributeIndex } = importSpecifier;
  27514. let specifier = importSpecifier.n;
  27515. const rawUrl = source.slice(start, end);
  27516. if (rawUrl === "import.meta") {
  27517. const prop = source.slice(end, end + 4);
  27518. if (prop === ".hot") {
  27519. hasHMR = true;
  27520. const endHot = end + 4 + (source[end + 4] === "?" ? 1 : 0);
  27521. if (source.slice(endHot, endHot + 7) === ".accept") if (source.slice(endHot, endHot + 14) === ".acceptExports") {
  27522. const importAcceptedExports = orderedAcceptedExports[index] = /* @__PURE__ */ new Set();
  27523. lexAcceptedHmrExports(source, source.indexOf("(", endHot + 14) + 1, importAcceptedExports);
  27524. isPartiallySelfAccepting = true;
  27525. } else {
  27526. const importAcceptedUrls = orderedAcceptedUrls[index] = /* @__PURE__ */ new Set();
  27527. if (lexAcceptedHmrDeps(source, source.indexOf("(", endHot + 7) + 1, importAcceptedUrls)) isSelfAccepting = true;
  27528. }
  27529. } else if (prop === ".env") hasEnv = true;
  27530. return;
  27531. } else if (templateLiteralRE.test(rawUrl)) {
  27532. if (!(rawUrl.includes("${") && rawUrl.includes("}"))) specifier = rawUrl.replace(templateLiteralRE, "$1");
  27533. }
  27534. const isDynamicImport = dynamicIndex > -1;
  27535. if (!isDynamicImport && attributeIndex > -1) str().remove(end + 1, expEnd);
  27536. if (specifier !== void 0) {
  27537. if ((isExternalUrl(specifier) && !specifier.startsWith("file://") || isDataUrl(specifier)) && !matchAlias(specifier)) return;
  27538. if (ssr && !matchAlias(specifier)) {
  27539. if (shouldExternalize(environment, specifier, importer)) return;
  27540. if (isBuiltin(environment.config.resolve.builtins, specifier)) return;
  27541. }
  27542. if (specifier === clientPublicPath) return;
  27543. 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.`);
  27544. let [url, resolvedId] = await normalizeUrl(specifier, start);
  27545. resolvedId = resolvedId || url;
  27546. config.safeModulePaths.add(fsPathFromUrl(stripBase(url, base)));
  27547. if (url !== specifier) {
  27548. let rewriteDone = false;
  27549. if (!depsOptimizer?.isOptimizedDepFile(importer) && depsOptimizer?.isOptimizedDepFile(resolvedId) && !optimizedDepChunkRE.test(resolvedId)) {
  27550. const file = cleanUrl(resolvedId);
  27551. const depInfo = optimizedDepInfoFromFile(depsOptimizer.metadata, file);
  27552. const needsInterop = await optimizedDepNeedsInterop(environment, depsOptimizer.metadata, file);
  27553. if (needsInterop === void 0) {
  27554. if (depInfo?.isDynamicEntry) config.logger.error(import_picocolors.default.red(`Vite Error, ${url} optimized info should be defined`));
  27555. } else if (needsInterop) {
  27556. debug$4?.(`${url} needs interop`);
  27557. interopNamedImports(str(), importSpecifier, url, index, importer, isNodeMode(), config);
  27558. rewriteDone = true;
  27559. }
  27560. } else if (url.startsWith(wrapId("__vite-browser-external")) && source.slice(expStart, start).includes("{")) {
  27561. interopNamedImports(str(), importSpecifier, url, index, importer, isNodeMode(), config);
  27562. rewriteDone = true;
  27563. }
  27564. if (!rewriteDone) {
  27565. const rewrittenUrl = JSON.stringify(url);
  27566. const s = isDynamicImport ? start : start - 1;
  27567. const e = isDynamicImport ? end : end + 1;
  27568. str().overwrite(s, e, rewrittenUrl, { contentOnly: true });
  27569. }
  27570. }
  27571. const hmrUrl = unwrapId(stripBase(url, base));
  27572. const isLocalImport = !isExternalUrl(hmrUrl) && !isDataUrl(hmrUrl);
  27573. if (isLocalImport) orderedImportedUrls[index] = hmrUrl;
  27574. if (enablePartialAccept && importedBindings) extractImportedBindings(resolvedId, source, importSpecifier, importedBindings);
  27575. if (!isDynamicImport && isLocalImport && environment.config.dev.preTransformRequests) {
  27576. const url = removeImportQuery(hmrUrl);
  27577. environment.warmupRequest(url);
  27578. }
  27579. } else if (!importer.startsWith(withTrailingSlash(clientDir))) {
  27580. if (!isInNodeModules(importer)) {
  27581. 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`));
  27582. }
  27583. if (!ssr) {
  27584. if (!urlIsStringRE.test(rawUrl) || isExplicitImportRequired(rawUrl.slice(1, -1))) {
  27585. needQueryInjectHelper = true;
  27586. str().overwrite(start, end, `__vite__injectQuery(${rawUrl}, 'import')`, { contentOnly: true });
  27587. }
  27588. }
  27589. }
  27590. }));
  27591. const _orderedImportedUrls = orderedImportedUrls.filter(isDefined);
  27592. const importedUrls = new Set(_orderedImportedUrls);
  27593. const staticImportedUrls = new Set(_orderedImportedUrls.map((url) => removeTimestampQuery(url)));
  27594. const acceptedUrls = mergeAcceptedUrls(orderedAcceptedUrls);
  27595. const acceptedExports = mergeAcceptedUrls(orderedAcceptedExports);
  27596. const isClassicWorker = importer.includes("worker_file") && importer.includes("type=classic");
  27597. if (hasEnv && !isClassicWorker) str().prepend(getEnv(ssr));
  27598. if (hasHMR && !ssr && !isClassicWorker) {
  27599. debugHmr?.(`${isSelfAccepting ? `[self-accepts]` : isPartiallySelfAccepting ? `[accepts-exports]` : acceptedUrls.size ? `[accepts-deps]` : `[detected api usage]`} ${prettifyUrl(importer, root)}`);
  27600. str().prepend(`import { createHotContext as __vite__createHotContext } from "${clientPublicPath}";import.meta.hot = __vite__createHotContext(${JSON.stringify(normalizeHmrUrl(importerModule.url))});`);
  27601. }
  27602. if (needQueryInjectHelper) if (isClassicWorker) str().append("\n" + __vite__injectQuery.toString());
  27603. else str().prepend(`import { injectQuery as __vite__injectQuery } from "${clientPublicPath}";`);
  27604. const normalizedAcceptedUrls = /* @__PURE__ */ new Set();
  27605. for (const { url, start, end } of acceptedUrls) {
  27606. let [normalized, resolvedId] = await normalizeUrl(url, start).catch(() => []);
  27607. if (resolvedId) {
  27608. const mod = moduleGraph.getModuleById(resolvedId);
  27609. if (!mod) {
  27610. this.error(`module was not found for ${JSON.stringify(resolvedId)}`, start);
  27611. return;
  27612. }
  27613. normalized = mod.url;
  27614. } else this.error({
  27615. message: `Failed to resolve ${JSON.stringify(url)} from ${importer}.`,
  27616. pos: start
  27617. });
  27618. normalizedAcceptedUrls.add(normalized);
  27619. const hmrAccept = normalizeHmrUrl(normalized);
  27620. str().overwrite(start, end, JSON.stringify(hmrAccept), { contentOnly: true });
  27621. }
  27622. if (!isCSSRequest(importer) || SPECIAL_QUERY_RE.test(importer)) {
  27623. const pluginImports = this._addedImports;
  27624. if (pluginImports) (await Promise.all([...pluginImports].map((id) => normalizeUrl(id, 0, true)))).forEach(([url]) => importedUrls.add(stripBase(url, base)));
  27625. if (ssr && importerModule.isSelfAccepting) isSelfAccepting = true;
  27626. if (!isSelfAccepting && isPartiallySelfAccepting && acceptedExports.size >= exports.length && exports.every((e) => acceptedExports.has(e.n))) isSelfAccepting = true;
  27627. const prunedImports = await moduleGraph.updateModuleInfo(importerModule, importedUrls, importedBindings, normalizedAcceptedUrls, isPartiallySelfAccepting ? acceptedExports : null, isSelfAccepting, staticImportedUrls);
  27628. if (prunedImports) handlePrunedModules(prunedImports, environment);
  27629. }
  27630. debug$4?.(`${timeFrom(msAtStart)} ${import_picocolors.default.dim(`[${importedUrls.size} imports rewritten] ${prettifyUrl(importer, root)}`)}`);
  27631. if (s) return transformStableResult(s, importer, config);
  27632. else return source;
  27633. }
  27634. };
  27635. }
  27636. function mergeAcceptedUrls(orderedUrls) {
  27637. const acceptedUrls = /* @__PURE__ */ new Set();
  27638. for (const urls of orderedUrls) {
  27639. if (!urls) continue;
  27640. for (const url of urls) acceptedUrls.add(url);
  27641. }
  27642. return acceptedUrls;
  27643. }
  27644. function createParseErrorInfo(importer, source) {
  27645. const isVue = importer.endsWith(".vue");
  27646. const isJsx = importer.endsWith(".jsx") || importer.endsWith(".tsx");
  27647. const maybeJSX = !isVue && isJSRequest(importer);
  27648. const probablyBinary = source.includes("�");
  27649. return {
  27650. 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.`),
  27651. showCodeFrame: !probablyBinary
  27652. };
  27653. }
  27654. const interopHelper = (m, n) => n || !m?.__esModule ? {
  27655. ...typeof m === "object" && !Array.isArray(m) || typeof m === "function" ? m : {},
  27656. default: m
  27657. } : m;
  27658. const interopHelperStr = interopHelper.toString().replaceAll("\n", "");
  27659. function interopNamedImports(str, importSpecifier, rewrittenUrl, importIndex, importer, isNodeMode, config) {
  27660. const source = str.original;
  27661. const { s: start, e: end, ss: expStart, se: expEnd, d: dynamicIndex } = importSpecifier;
  27662. const exp = source.slice(expStart, expEnd);
  27663. if (dynamicIndex > -1) str.overwrite(expStart, expEnd, `import('${rewrittenUrl}').then(m => (${interopHelperStr})(m.default, ${!!config.legacy?.inconsistentCjsInterop ? 0 : 1}))` + getLineBreaks(exp), { contentOnly: true });
  27664. else {
  27665. const rewritten = transformCjsImport(exp, rewrittenUrl, source.slice(start, end), importIndex, importer, isNodeMode, config);
  27666. if (rewritten) str.overwrite(expStart, expEnd, rewritten + getLineBreaks(exp), { contentOnly: true });
  27667. else str.overwrite(start, end, rewrittenUrl + getLineBreaks(source.slice(start, end)), { contentOnly: true });
  27668. }
  27669. }
  27670. function getLineBreaks(str) {
  27671. return str.includes("\n") ? "\n".repeat(str.split("\n").length - 1) : "";
  27672. }
  27673. /**
  27674. * Detect import statements to a known optimized CJS dependency and provide
  27675. * ES named imports interop. We do this by rewriting named imports to a variable
  27676. * assignment to the corresponding property on the `module.exports` of the cjs
  27677. * module. Note this doesn't support dynamic re-assignments from within the cjs
  27678. * module.
  27679. *
  27680. * Note that es-module-lexer treats `export * from '...'` as an import as well,
  27681. * so, we may encounter ExportAllDeclaration here, in which case `undefined`
  27682. * will be returned.
  27683. *
  27684. * Credits \@csr632 via #837
  27685. */
  27686. function transformCjsImport(importExp, url, rawUrl, importIndex, importer, isNodeMode, config) {
  27687. const node = parseAst(importExp).body[0];
  27688. 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}"\``));
  27689. else if (node.type === "ImportDeclaration" || node.type === "ExportNamedDeclaration") {
  27690. if (!node.specifiers.length) return `import "${url}"`;
  27691. const importNames = [];
  27692. const exportNames = [];
  27693. let defaultExports = "";
  27694. for (const spec of node.specifiers) if (spec.type === "ImportSpecifier") {
  27695. const importedName = getIdentifierNameOrLiteralValue(spec.imported);
  27696. importNames.push({
  27697. importedName,
  27698. localName: spec.local.name
  27699. });
  27700. } else if (spec.type === "ImportDefaultSpecifier") importNames.push({
  27701. importedName: "default",
  27702. localName: spec.local.name
  27703. });
  27704. else if (spec.type === "ImportNamespaceSpecifier") importNames.push({
  27705. importedName: "*",
  27706. localName: spec.local.name
  27707. });
  27708. else if (spec.type === "ExportSpecifier") {
  27709. const importedName = getIdentifierNameOrLiteralValue(spec.local);
  27710. const exportedName = getIdentifierNameOrLiteralValue(spec.exported);
  27711. if (exportedName === "default") {
  27712. defaultExports = makeLegalIdentifier(`__vite__cjsExportDefault_${importIndex}`);
  27713. importNames.push({
  27714. importedName,
  27715. localName: defaultExports
  27716. });
  27717. } else {
  27718. const localName = `__vite__cjsExport${spec.exported.type === "Literal" ? `L_${getHash(spec.exported.value)}` : "I_" + spec.exported.name}`;
  27719. importNames.push({
  27720. importedName,
  27721. localName
  27722. });
  27723. exportNames.push(`${localName} as ${spec.exported.type === "Literal" ? JSON.stringify(exportedName) : exportedName}`);
  27724. }
  27725. }
  27726. const cjsModuleName = makeLegalIdentifier(`__vite__cjsImport${importIndex}_${rawUrl}`);
  27727. const lines = [`import ${cjsModuleName} from "${url}"`];
  27728. importNames.forEach(({ importedName, localName }) => {
  27729. if (importedName === "*") lines.push(`const ${localName} = (${interopHelperStr})(${cjsModuleName}, ${+isNodeMode})`);
  27730. else if (importedName === "default") if (isNodeMode) lines.push(`const ${localName} = ${cjsModuleName}`);
  27731. else lines.push(`const ${localName} = !${cjsModuleName}.__esModule ? ${cjsModuleName} : ${cjsModuleName}.default`);
  27732. else lines.push(`const ${localName} = ${cjsModuleName}["${importedName}"]`);
  27733. });
  27734. if (defaultExports) lines.push(`export default ${defaultExports}`);
  27735. if (exportNames.length) lines.push(`export { ${exportNames.join(", ")} }`);
  27736. return lines.join("; ");
  27737. }
  27738. }
  27739. function getIdentifierNameOrLiteralValue(node) {
  27740. return node.type === "Identifier" ? node.name : node.value;
  27741. }
  27742. function __vite__injectQuery(url, queryToInject) {
  27743. if (url[0] !== "." && url[0] !== "/") return url;
  27744. const pathname = url.replace(/[?#].*$/, "");
  27745. const { search, hash } = new URL(url, "http://vite.dev");
  27746. return `${pathname}?${queryToInject}${search ? `&` + search.slice(1) : ""}${hash || ""}`;
  27747. }
  27748. //#endregion
  27749. //#region src/node/plugins/wasm.ts
  27750. const wasmHelperId = "\0vite/wasm-helper.js";
  27751. const wasmInitRE = /(?<![?#].*)\.wasm\?init/;
  27752. const wasmInitUrlRE = /__VITE_WASM_INIT__([\w$]+)__/g;
  27753. const wasmHelper = async (opts = {}, url) => {
  27754. let result;
  27755. if (url.startsWith("data:")) {
  27756. const urlContent = url.replace(/^data:.*?base64,/, "");
  27757. let bytes;
  27758. if (typeof Buffer === "function" && typeof Buffer.from === "function") bytes = Buffer.from(urlContent, "base64");
  27759. else if (typeof atob === "function") {
  27760. const binaryString = atob(urlContent);
  27761. bytes = new Uint8Array(binaryString.length);
  27762. for (let i = 0; i < binaryString.length; i++) bytes[i] = binaryString.charCodeAt(i);
  27763. } else throw new Error("Failed to decode base64-encoded data URL, Buffer and atob are not supported");
  27764. result = await WebAssembly.instantiate(bytes, opts);
  27765. } else result = await instantiateFromUrl(url, opts);
  27766. return result.instance;
  27767. };
  27768. const wasmHelperCode = wasmHelper.toString();
  27769. const instantiateFromUrl = async (url, opts) => {
  27770. const response = await fetch(url);
  27771. const contentType = response.headers.get("Content-Type") || "";
  27772. if ("instantiateStreaming" in WebAssembly && contentType.startsWith("application/wasm")) return WebAssembly.instantiateStreaming(response, opts);
  27773. else {
  27774. const buffer = await response.arrayBuffer();
  27775. return WebAssembly.instantiate(buffer, opts);
  27776. }
  27777. };
  27778. const instantiateFromUrlCode = instantiateFromUrl.toString();
  27779. const instantiateFromFile = async (fileUrlString, opts) => {
  27780. const { readFile } = await import("node:fs/promises");
  27781. const buffer = await readFile(new URL(
  27782. fileUrlString,
  27783. /** #__KEEP__ */
  27784. import.meta.url
  27785. ));
  27786. return WebAssembly.instantiate(buffer, opts);
  27787. };
  27788. const instantiateFromFileCode = instantiateFromFile.toString();
  27789. const wasmHelperPlugin = () => {
  27790. return perEnvironmentPlugin("vite:wasm-helper", (env) => {
  27791. return {
  27792. name: "vite:wasm-helper",
  27793. resolveId: {
  27794. filter: { id: exactRegex(wasmHelperId) },
  27795. handler(id) {
  27796. return id;
  27797. }
  27798. },
  27799. load: {
  27800. filter: { id: [exactRegex(wasmHelperId), wasmInitRE] },
  27801. async handler(id) {
  27802. const ssr = this.environment.config.consumer === "server";
  27803. if (id === wasmHelperId) return `
  27804. const instantiateFromUrl = ${ssr ? instantiateFromFileCode : instantiateFromUrlCode}
  27805. export default ${wasmHelperCode}
  27806. `;
  27807. id = id.split("?")[0];
  27808. let url = await fileToUrl$1(this, id, ssr);
  27809. assetUrlRE.lastIndex = 0;
  27810. if (ssr && assetUrlRE.test(url)) url = url.replace("__VITE_ASSET__", "__VITE_WASM_INIT__");
  27811. return `
  27812. import initWasm from "${wasmHelperId}"
  27813. export default opts => initWasm(opts, ${JSON.stringify(url)})
  27814. `;
  27815. }
  27816. },
  27817. renderChunk: env.config.consumer === "server" ? {
  27818. filter: { code: wasmInitUrlRE },
  27819. async handler(code, chunk, opts, meta) {
  27820. const toRelativeRuntime = createToImportMetaURLBasedRelativeRuntime(opts.format, this.environment.config.isWorker);
  27821. let match;
  27822. let s;
  27823. wasmInitUrlRE.lastIndex = 0;
  27824. while (match = wasmInitUrlRE.exec(code)) {
  27825. const [full, referenceId] = match;
  27826. const file = this.getFileName(referenceId);
  27827. chunk.viteMetadata.importedAssets.add(cleanUrl(file));
  27828. const { runtime } = toRelativeRuntime(file, chunk.fileName);
  27829. s ??= meta.magicString ?? new MagicString(code);
  27830. s.update(match.index, match.index + full.length, `"+${runtime}+"`);
  27831. }
  27832. if (!s) return null;
  27833. return meta.magicString ? { code: s } : {
  27834. code: s.toString(),
  27835. map: this.environment.config.build.sourcemap ? s.generateMap({ hires: "boundary" }) : null
  27836. };
  27837. }
  27838. } : void 0
  27839. };
  27840. });
  27841. };
  27842. //#endregion
  27843. //#region src/node/plugins/workerImportMetaUrl.ts
  27844. function err$1(e, pos) {
  27845. const error = new Error(e);
  27846. error.pos = pos;
  27847. return error;
  27848. }
  27849. function findClosingParen(input, fromIndex) {
  27850. let count = 1;
  27851. for (let i = fromIndex; i < input.length; i++) {
  27852. if (input[i] === "(") count++;
  27853. if (input[i] === ")") count--;
  27854. if (count === 0) return i;
  27855. }
  27856. return -1;
  27857. }
  27858. function extractWorkerTypeFromAst(expression, optsStartIndex) {
  27859. if (expression.type !== "ObjectExpression") return;
  27860. let lastSpreadElementIndex = -1;
  27861. let typeProperty = null;
  27862. let typePropertyIndex = -1;
  27863. for (let i = 0; i < expression.properties.length; i++) {
  27864. const property = expression.properties[i];
  27865. if (property.type === "SpreadElement") {
  27866. lastSpreadElementIndex = i;
  27867. continue;
  27868. }
  27869. if (property.type === "Property" && (property.key.type === "Identifier" && property.key.name === "type" || property.key.type === "Literal" && property.key.value === "type")) {
  27870. typeProperty = property;
  27871. typePropertyIndex = i;
  27872. }
  27873. }
  27874. if (typePropertyIndex === -1 && lastSpreadElementIndex === -1) return "classic";
  27875. 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);
  27876. if (typeProperty?.value.type !== "Literal") throw err$1("Expected worker options type property to be a literal value.", optsStartIndex);
  27877. return typeProperty?.value.value === "module" ? "module" : "classic";
  27878. }
  27879. async function parseWorkerOptions(rawOpts, optsStartIndex) {
  27880. let opts = {};
  27881. try {
  27882. opts = evalValue(rawOpts);
  27883. } catch {
  27884. const optsNode = (await parseAstAsync(`(${rawOpts})`)).body[0].expression;
  27885. const type = extractWorkerTypeFromAst(optsNode, optsStartIndex);
  27886. if (type) return { type };
  27887. 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);
  27888. }
  27889. if (opts == null) return {};
  27890. if (typeof opts !== "object") throw err$1(`Expected worker options to be an object, got ${typeof opts}`, optsStartIndex);
  27891. return opts;
  27892. }
  27893. async function getWorkerType(raw, clean, i) {
  27894. const commaIndex = clean.indexOf(",", i);
  27895. if (commaIndex === -1) return "classic";
  27896. const endIndex = findClosingParen(clean, i);
  27897. if (commaIndex > endIndex) return "classic";
  27898. let workerOptString = raw.substring(commaIndex + 1, endIndex);
  27899. if (hasViteIgnoreRE.test(workerOptString)) return "ignore";
  27900. const cleanWorkerOptString = clean.substring(commaIndex + 1, endIndex);
  27901. const trimmedCleanWorkerOptString = cleanWorkerOptString.trim();
  27902. if (!trimmedCleanWorkerOptString.length) return "classic";
  27903. if (trimmedCleanWorkerOptString.endsWith(",")) workerOptString = workerOptString.slice(0, cleanWorkerOptString.lastIndexOf(","));
  27904. const workerOpts = await parseWorkerOptions(workerOptString, commaIndex + 1);
  27905. if (workerOpts.type && (workerOpts.type === "module" || workerOpts.type === "classic")) return workerOpts.type;
  27906. return "classic";
  27907. }
  27908. const workerImportMetaUrlRE = /new\s+(?:Worker|SharedWorker)\s*\(\s*new\s+URL.+?import\.meta\.url/s;
  27909. function workerImportMetaUrlPlugin(config) {
  27910. const isBundled = config.isBundled;
  27911. let workerResolver;
  27912. const fsResolveOptions = {
  27913. ...config.resolve,
  27914. root: config.root,
  27915. isProduction: config.isProduction,
  27916. isBuild: config.command === "build",
  27917. packageCache: config.packageCache,
  27918. asSrc: true
  27919. };
  27920. return {
  27921. name: "vite:worker-import-meta-url",
  27922. applyToEnvironment(environment) {
  27923. return environment.config.consumer === "client";
  27924. },
  27925. transform: {
  27926. filter: { code: workerImportMetaUrlRE },
  27927. async handler(code, id) {
  27928. let s;
  27929. const cleanString = stripLiteral(code);
  27930. const workerImportMetaUrlRE = /\bnew\s+(?:Worker|SharedWorker)\s*\(\s*(new\s+URL\s*\(\s*('[^']+'|"[^"]+"|`[^`]+`)\s*,\s*import\.meta\.url\s*(?:,\s*)?\))/dg;
  27931. let match;
  27932. while (match = workerImportMetaUrlRE.exec(cleanString)) {
  27933. const [[, endIndex], [expStart, expEnd], [urlStart, urlEnd]] = match.indices;
  27934. const rawUrl = code.slice(urlStart, urlEnd);
  27935. if (rawUrl[0] === "`" && rawUrl.includes("${")) this.error(`\`new URL(url, import.meta.url)\` is not supported in dynamic template string.`, expStart);
  27936. s ||= new MagicString(code);
  27937. const workerType = await getWorkerType(code, cleanString, endIndex);
  27938. const url = rawUrl.slice(1, -1);
  27939. let file;
  27940. if (url[0] === ".") {
  27941. file = path.resolve(path.dirname(id), url);
  27942. file = slash(tryFsResolve(file, fsResolveOptions) ?? file);
  27943. } else {
  27944. workerResolver ??= createBackCompatIdResolver(config, {
  27945. extensions: [],
  27946. tryIndex: false,
  27947. preferRelative: true
  27948. });
  27949. file = await workerResolver(this.environment, url, id);
  27950. file ??= url[0] === "/" ? slash(path.join(config.publicDir, url)) : slash(path.resolve(path.dirname(id), url));
  27951. }
  27952. if (isBundled && config.isWorker && config.bundleChain.at(-1) === cleanUrl(file)) s.update(expStart, expEnd, "self.location.href");
  27953. else {
  27954. let builtUrl;
  27955. if (isBundled) {
  27956. const result = await workerFileToUrl(config, file);
  27957. if (this.environment.config.command === "serve" && this.environment.config.experimental.bundledDev) builtUrl = toOutputFilePathInJSForBundledDev(this.environment, result.entryFilename);
  27958. else builtUrl = result.entryUrlPlaceholder;
  27959. for (const file of result.watchedFiles) this.addWatchFile(file);
  27960. } else {
  27961. builtUrl = await fileToUrl$1(this, cleanUrl(file));
  27962. builtUrl = injectQuery(builtUrl, `${WORKER_FILE_ID}&type=${workerType}`);
  27963. }
  27964. s.update(expStart, expEnd, `new URL(/* @vite-ignore */ ${JSON.stringify(builtUrl)}, '' + import.meta.url)`);
  27965. }
  27966. }
  27967. if (s) return transformStableResult(s, id, config);
  27968. return null;
  27969. }
  27970. }
  27971. };
  27972. }
  27973. //#endregion
  27974. //#region src/node/plugins/importAnalysisBuild.ts
  27975. /**
  27976. * A flag for injected helpers. This flag will be set to `false` if the output
  27977. * target is not native es - so that injected helper logic can be conditionally
  27978. * dropped.
  27979. */
  27980. const isModernFlag = `__VITE_IS_MODERN__`;
  27981. const preloadMethod = `__vitePreload`;
  27982. const preloadMarker = `__VITE_PRELOAD__`;
  27983. const preloadHelperId = "\0vite/preload-helper.js";
  27984. const preloadMarkerRE = new RegExp(preloadMarker, "g");
  27985. function toRelativePath(filename, importer) {
  27986. const relPath = path.posix.relative(path.posix.dirname(importer), filename);
  27987. return relPath[0] === "." ? relPath : `./${relPath}`;
  27988. }
  27989. function findPreloadMarker(str, pos = 0) {
  27990. preloadMarkerRE.lastIndex = pos;
  27991. return preloadMarkerRE.exec(str)?.index ?? -1;
  27992. }
  27993. /**
  27994. * Helper for preloading CSS and direct imports of async chunks in parallel to
  27995. * the async chunk itself.
  27996. */
  27997. function detectScriptRel() {
  27998. const relList = typeof document !== "undefined" && document.createElement("link").relList;
  27999. return relList && relList.supports && relList.supports("modulepreload") ? "modulepreload" : "preload";
  28000. }
  28001. function preload(baseModule, deps, importerUrl) {
  28002. let promise = Promise.resolve();
  28003. if (__VITE_IS_MODERN__ && deps && deps.length > 0) {
  28004. const links = document.getElementsByTagName("link");
  28005. const cspNonceMeta = document.querySelector("meta[property=csp-nonce]");
  28006. const cspNonce = cspNonceMeta?.nonce || cspNonceMeta?.getAttribute("nonce");
  28007. function allSettled(promises) {
  28008. return Promise.all(promises.map((p) => Promise.resolve(p).then((value) => ({
  28009. status: "fulfilled",
  28010. value
  28011. }), (reason) => ({
  28012. status: "rejected",
  28013. reason
  28014. }))));
  28015. }
  28016. promise = allSettled(deps.map((dep) => {
  28017. dep = assetsURL(dep, importerUrl);
  28018. if (dep in seen) return;
  28019. seen[dep] = true;
  28020. const isCss = dep.endsWith(".css");
  28021. const cssSelector = isCss ? "[rel=\"stylesheet\"]" : "";
  28022. if (!!importerUrl) for (let i = links.length - 1; i >= 0; i--) {
  28023. const link = links[i];
  28024. if (link.href === dep && (!isCss || link.rel === "stylesheet")) return;
  28025. }
  28026. else if (document.querySelector(`link[href="${dep}"]${cssSelector}`)) return;
  28027. const link = document.createElement("link");
  28028. link.rel = isCss ? "stylesheet" : scriptRel;
  28029. if (!isCss) link.as = "script";
  28030. link.crossOrigin = "";
  28031. link.href = dep;
  28032. if (cspNonce) link.setAttribute("nonce", cspNonce);
  28033. document.head.appendChild(link);
  28034. if (isCss) return new Promise((res, rej) => {
  28035. link.addEventListener("load", res);
  28036. link.addEventListener("error", () => rej(/* @__PURE__ */ new Error(`Unable to preload CSS for ${dep}`)));
  28037. });
  28038. }));
  28039. }
  28040. function handlePreloadError(err) {
  28041. const e = new Event("vite:preloadError", { cancelable: true });
  28042. e.payload = err;
  28043. window.dispatchEvent(e);
  28044. if (!e.defaultPrevented) throw err;
  28045. }
  28046. return promise.then((res) => {
  28047. for (const item of res || []) {
  28048. if (item.status !== "rejected") continue;
  28049. handlePreloadError(item.reason);
  28050. }
  28051. return baseModule().catch(handlePreloadError);
  28052. });
  28053. }
  28054. function getPreloadCode(environment, renderBuiltUrlBoolean, isRelativeBase) {
  28055. const { modulePreload } = environment.config.build;
  28056. 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()}`;
  28057. }
  28058. /**
  28059. * Build only. During serve this is performed as part of ./importAnalysis.
  28060. */
  28061. function buildImportAnalysisPlugin(config) {
  28062. const getInsertPreload = (environment) => environment.config.consumer === "client" && !config.isWorker && !config.build.lib;
  28063. const renderBuiltUrl = config.experimental.renderBuiltUrl;
  28064. const isRelativeBase = config.base === "./" || config.base === "";
  28065. return [{
  28066. name: "vite:build-import-analysis",
  28067. renderChunk(code, _, { format }) {
  28068. if (code.indexOf(isModernFlag) > -1) {
  28069. const re = new RegExp(isModernFlag, "g");
  28070. const isModern = String(format === "es");
  28071. const isModernWithPadding = isModern + " ".repeat(isModernFlag.length - isModern.length);
  28072. return {
  28073. code: code.replace(re, isModernWithPadding),
  28074. map: null
  28075. };
  28076. }
  28077. return null;
  28078. },
  28079. async generateBundle({ format }, bundle) {
  28080. if (format !== "es") return;
  28081. await init;
  28082. if (!getInsertPreload(this.environment)) {
  28083. const removedPureCssFiles = removedPureCssFilesCache.get(config);
  28084. if (removedPureCssFiles && removedPureCssFiles.size > 0) for (const file in bundle) {
  28085. const chunk = bundle[file];
  28086. if (chunk.type === "chunk" && chunk.code.includes("import")) {
  28087. const code = chunk.code;
  28088. let imports;
  28089. try {
  28090. imports = parse$2(code)[0].filter((i) => i.d > -1);
  28091. } catch (e) {
  28092. const loc = numberToPos(code, e.idx);
  28093. this.error({
  28094. name: e.name,
  28095. message: e.message,
  28096. stack: e.stack,
  28097. cause: e.cause,
  28098. pos: e.idx,
  28099. loc: {
  28100. ...loc,
  28101. file: chunk.fileName
  28102. },
  28103. frame: generateCodeFrame(code, loc)
  28104. });
  28105. }
  28106. for (const imp of imports) {
  28107. const { n: name, s: start, e: end, ss: expStart, se: expEnd } = imp;
  28108. let url = name;
  28109. if (!url) {
  28110. const rawUrl = code.slice(start, end);
  28111. if (rawUrl[0] === `"` && rawUrl[rawUrl.length - 1] === `"` || rawUrl[0] === "`" && rawUrl[rawUrl.length - 1] === "`") url = rawUrl.slice(1, -1);
  28112. }
  28113. if (!url) continue;
  28114. const normalizedFile = path.posix.join(path.posix.dirname(chunk.fileName), url);
  28115. if (removedPureCssFiles.has(normalizedFile)) chunk.code = chunk.code.slice(0, expStart) + `Promise.resolve({${"".padEnd(expEnd - expStart - 19, " ")}})` + chunk.code.slice(expEnd);
  28116. }
  28117. }
  28118. }
  28119. return;
  28120. }
  28121. const buildSourcemap = this.environment.config.build.sourcemap;
  28122. const { modulePreload } = this.environment.config.build;
  28123. for (const file in bundle) {
  28124. const chunk = bundle[file];
  28125. if (chunk.type === "chunk" && chunk.code.indexOf(preloadMarker) > -1) {
  28126. const code = chunk.code;
  28127. let imports;
  28128. try {
  28129. imports = parse$2(code)[0].filter((i) => i.d > -1);
  28130. } catch (e) {
  28131. const loc = numberToPos(code, e.idx);
  28132. this.error({
  28133. name: e.name,
  28134. message: e.message,
  28135. stack: e.stack,
  28136. cause: e.cause,
  28137. pos: e.idx,
  28138. loc: {
  28139. ...loc,
  28140. file: chunk.fileName
  28141. },
  28142. frame: generateCodeFrame(code, loc)
  28143. });
  28144. }
  28145. const s = new MagicString(code);
  28146. const rewroteMarkerStartPos = /* @__PURE__ */ new Set();
  28147. const fileDeps = [];
  28148. const addFileDep = (url, runtime = false) => {
  28149. const index = fileDeps.findIndex((dep) => dep.url === url);
  28150. if (index === -1) return fileDeps.push({
  28151. url,
  28152. runtime
  28153. }) - 1;
  28154. else return index;
  28155. };
  28156. if (imports.length) for (let index = 0; index < imports.length; index++) {
  28157. const { n: name, s: start, e: end, ss: expStart, se: expEnd } = imports[index];
  28158. let url = name;
  28159. if (!url) {
  28160. const rawUrl = code.slice(start, end);
  28161. if (rawUrl[0] === `"` && rawUrl[rawUrl.length - 1] === `"` || rawUrl[0] === "`" && rawUrl[rawUrl.length - 1] === "`") url = rawUrl.slice(1, -1);
  28162. }
  28163. const deps = /* @__PURE__ */ new Set();
  28164. let hasRemovedPureCssChunk = false;
  28165. let normalizedFile = void 0;
  28166. if (url) {
  28167. normalizedFile = path.posix.join(path.posix.dirname(chunk.fileName), url);
  28168. const ownerFilename = chunk.fileName;
  28169. const analyzed = /* @__PURE__ */ new Set();
  28170. const addDeps = (filename) => {
  28171. if (filename === ownerFilename) return;
  28172. if (analyzed.has(filename)) return;
  28173. analyzed.add(filename);
  28174. const chunk = bundle[filename];
  28175. if (chunk) {
  28176. deps.add(chunk.fileName);
  28177. if (chunk.type === "chunk") {
  28178. chunk.imports.forEach(addDeps);
  28179. chunk.viteMetadata.importedCss.forEach((file) => {
  28180. deps.add(file);
  28181. });
  28182. }
  28183. } else {
  28184. const chunk = removedPureCssFilesCache.get(config).get(filename);
  28185. if (chunk) {
  28186. if (chunk.viteMetadata.importedCss.size) {
  28187. chunk.viteMetadata.importedCss.forEach((file) => {
  28188. deps.add(file);
  28189. });
  28190. hasRemovedPureCssChunk = true;
  28191. }
  28192. s.update(expStart, expEnd, "Promise.resolve({})");
  28193. }
  28194. }
  28195. };
  28196. addDeps(normalizedFile);
  28197. }
  28198. let markerStartPos = findPreloadMarker(code, end);
  28199. if (markerStartPos === -1 && imports.length === 1) markerStartPos = findPreloadMarker(code);
  28200. if (markerStartPos > 0) {
  28201. let depsArray = deps.size > 1 || hasRemovedPureCssChunk && deps.size > 0 ? modulePreload === false ? [...deps].filter((d) => d.endsWith(".css")) : [...deps] : [];
  28202. const resolveDependencies = modulePreload ? modulePreload.resolveDependencies : void 0;
  28203. if (resolveDependencies && normalizedFile) {
  28204. const cssDeps = [];
  28205. const otherDeps = [];
  28206. for (const dep of depsArray) (dep.endsWith(".css") ? cssDeps : otherDeps).push(dep);
  28207. depsArray = [...resolveDependencies(normalizedFile, otherDeps, {
  28208. hostId: file,
  28209. hostType: "js"
  28210. }), ...cssDeps];
  28211. }
  28212. let renderedDeps;
  28213. if (renderBuiltUrl) renderedDeps = depsArray.map((dep) => {
  28214. const replacement = toOutputFilePathInJS(this.environment, dep, "asset", chunk.fileName, "js", toRelativePath);
  28215. if (typeof replacement === "string") return addFileDep(replacement);
  28216. return addFileDep(replacement.runtime, true);
  28217. });
  28218. else renderedDeps = depsArray.map((d) => isRelativeBase ? addFileDep(toRelativePath(d, file)) : addFileDep(d));
  28219. s.update(markerStartPos, markerStartPos + preloadMarker.length, renderedDeps.length > 0 ? `__vite__mapDeps([${renderedDeps.join(",")}])` : `[]`);
  28220. rewroteMarkerStartPos.add(markerStartPos);
  28221. }
  28222. }
  28223. if (fileDeps.length > 0) {
  28224. 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`;
  28225. if (code.startsWith("#!")) s.prependLeft(code.indexOf("\n") + 1, mapDepsCode);
  28226. else s.prepend(mapDepsCode);
  28227. }
  28228. let markerStartPos = findPreloadMarker(code);
  28229. while (markerStartPos >= 0) {
  28230. if (!rewroteMarkerStartPos.has(markerStartPos)) s.update(markerStartPos, markerStartPos + preloadMarker.length, "void 0");
  28231. markerStartPos = findPreloadMarker(code, markerStartPos + preloadMarker.length);
  28232. }
  28233. if (s.hasChanged()) {
  28234. chunk.code = s.toString();
  28235. if (buildSourcemap && chunk.map) {
  28236. const nextMap = s.generateMap({
  28237. source: chunk.fileName,
  28238. hires: "boundary"
  28239. });
  28240. const originalFile = chunk.map.file;
  28241. const map = combineSourcemaps(chunk.fileName, [nextMap, chunk.map]);
  28242. map.toUrl = () => genSourceMapUrl(map);
  28243. if (originalFile) map.file = originalFile;
  28244. const originalDebugId = chunk.map.debugId;
  28245. chunk.map = map;
  28246. if (buildSourcemap === "inline") {
  28247. chunk.code = chunk.code.replace(import_convert_source_map.default.mapFileCommentRegex, "");
  28248. chunk.code += `\n//# sourceMappingURL=${genSourceMapUrl(map)}`;
  28249. } else {
  28250. if (originalDebugId) map.debugId = originalDebugId;
  28251. const mapAsset = bundle[chunk.fileName + ".map"];
  28252. if (mapAsset && mapAsset.type === "asset") mapAsset.source = map.toString();
  28253. }
  28254. }
  28255. }
  28256. }
  28257. }
  28258. }
  28259. }, perEnvironmentPlugin("native:import-analysis-build", (environment) => {
  28260. return viteBuildImportAnalysisPlugin({
  28261. preloadCode: getPreloadCode(environment, !!renderBuiltUrl, isRelativeBase),
  28262. insertPreload: getInsertPreload(environment),
  28263. optimizeModulePreloadRelativePaths: false,
  28264. renderBuiltUrl: !!renderBuiltUrl,
  28265. isRelativeBase
  28266. });
  28267. })];
  28268. }
  28269. //#endregion
  28270. //#region src/node/plugins/assetImportMetaUrl.ts
  28271. /**
  28272. * Convert `new URL('./foo.png', import.meta.url)` to its resolved built URL
  28273. *
  28274. * Supports template string with dynamic segments:
  28275. * ```
  28276. * new URL(`./dir/${name}.png`, import.meta.url)
  28277. * // transformed to
  28278. * import.meta.glob('./dir/**.png', { eager: true, import: 'default' })[`./dir/${name}.png`]
  28279. * ```
  28280. */
  28281. function assetImportMetaUrlPlugin(config) {
  28282. const { publicDir } = config;
  28283. let assetResolver;
  28284. const fsResolveOptions = {
  28285. ...config.resolve,
  28286. root: config.root,
  28287. isProduction: config.isProduction,
  28288. isBuild: config.command === "build",
  28289. packageCache: config.packageCache,
  28290. asSrc: true
  28291. };
  28292. return {
  28293. name: "vite:asset-import-meta-url",
  28294. applyToEnvironment(environment) {
  28295. return environment.config.consumer === "client";
  28296. },
  28297. transform: {
  28298. filter: {
  28299. id: { exclude: [exactRegex(preloadHelperId), exactRegex(CLIENT_ENTRY)] },
  28300. code: /new\s+URL.+import\.meta\.url/s
  28301. },
  28302. async handler(code, id) {
  28303. let s;
  28304. const assetImportMetaUrlRE = /\bnew\s+URL\s*\(\s*('[^']+'|"[^"]+"|`[^`]+`)\s*,\s*import\.meta\.url\s*(?:,\s*)?\)/dg;
  28305. const cleanString = stripLiteral(code);
  28306. let match;
  28307. while (match = assetImportMetaUrlRE.exec(cleanString)) {
  28308. const [[startIndex, endIndex], [urlStart, urlEnd]] = match.indices;
  28309. if (hasViteIgnoreRE.test(code.slice(startIndex, urlStart))) continue;
  28310. const rawUrl = code.slice(urlStart, urlEnd);
  28311. if (!s) s = new MagicString(code);
  28312. if (rawUrl[0] === "`" && rawUrl.includes("${")) {
  28313. const queryDelimiterIndex = getQueryDelimiterIndex(rawUrl);
  28314. const hasQueryDelimiter = queryDelimiterIndex !== -1;
  28315. const pureUrl = hasQueryDelimiter ? rawUrl.slice(0, queryDelimiterIndex) + "`" : rawUrl;
  28316. const queryString = hasQueryDelimiter ? rawUrl.slice(queryDelimiterIndex, -1) : "";
  28317. const templateLiteral = this.parse(pureUrl).body[0].expression;
  28318. if (templateLiteral.expressions.length) {
  28319. const pattern = buildGlobPattern(templateLiteral);
  28320. if (pattern[0] === "*") continue;
  28321. const globOptions = {
  28322. eager: true,
  28323. import: "default",
  28324. query: injectQuery(queryString, "url")
  28325. };
  28326. s.update(startIndex, endIndex, `new URL((import.meta.glob(${JSON.stringify(pattern)}, ${JSON.stringify(globOptions)}))[${pureUrl}], import.meta.url)`);
  28327. continue;
  28328. }
  28329. }
  28330. const url = rawUrl.slice(1, -1);
  28331. if (isDataUrl(url)) continue;
  28332. let file;
  28333. if (url[0] === ".") {
  28334. file = slash(path.resolve(path.dirname(id), url));
  28335. file = tryFsResolve(file, fsResolveOptions) ?? file;
  28336. } else {
  28337. assetResolver ??= createBackCompatIdResolver(config, {
  28338. extensions: [],
  28339. mainFields: [],
  28340. tryIndex: false,
  28341. preferRelative: true
  28342. });
  28343. file = await assetResolver(this.environment, url, id);
  28344. file ??= url[0] === "/" ? slash(path.join(publicDir, url)) : slash(path.resolve(path.dirname(id), url));
  28345. }
  28346. let builtUrl;
  28347. if (file) try {
  28348. if (publicDir && isParentDirectory(publicDir, file)) {
  28349. const publicPath = "/" + path.posix.relative(publicDir, file);
  28350. builtUrl = await fileToUrl$1(this, publicPath);
  28351. } else {
  28352. builtUrl = await fileToUrl$1(this, file);
  28353. if (tryStatSync(file)?.isFile()) this.addWatchFile(file);
  28354. }
  28355. } catch {}
  28356. if (!builtUrl) {
  28357. const rawExp = code.slice(startIndex, endIndex);
  28358. 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.`);
  28359. builtUrl = url;
  28360. }
  28361. s.update(startIndex, endIndex, `new URL(${JSON.stringify(builtUrl)}, '' + import.meta.url)`);
  28362. }
  28363. if (s) return transformStableResult(s, id, config);
  28364. }
  28365. }
  28366. };
  28367. }
  28368. function buildGlobPattern(ast) {
  28369. let pattern = "";
  28370. let lastIsGlob = false;
  28371. for (let i = 0; i < ast.quasis.length; i++) {
  28372. const str = ast.quasis[i].value.raw;
  28373. if (str) {
  28374. pattern += str;
  28375. lastIsGlob = false;
  28376. }
  28377. if (ast.expressions[i] && !lastIsGlob) {
  28378. pattern += "*";
  28379. lastIsGlob = true;
  28380. }
  28381. }
  28382. return pattern;
  28383. }
  28384. function getQueryDelimiterIndex(rawUrl) {
  28385. let bracketsStack = 0;
  28386. for (let i = 0; i < rawUrl.length; i++) if (rawUrl[i] === "{") bracketsStack++;
  28387. else if (rawUrl[i] === "}") bracketsStack--;
  28388. else if (rawUrl[i] === "?" && bracketsStack === 0) return i;
  28389. return -1;
  28390. }
  28391. //#endregion
  28392. //#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
  28393. var VariableDynamicImportError = class extends Error {};
  28394. const example = "For example: import(`./foo/${bar}.js`).";
  28395. function sanitizeString(str) {
  28396. if (str === "") return str;
  28397. if (str.includes("*")) throw new VariableDynamicImportError("A dynamic import cannot contain * characters.");
  28398. return escapePath(str);
  28399. }
  28400. function templateLiteralToGlob(node) {
  28401. let glob = "";
  28402. for (let i = 0; i < node.quasis.length; i += 1) {
  28403. glob += sanitizeString(node.quasis[i].value.raw);
  28404. if (node.expressions[i]) glob += expressionToGlob(node.expressions[i]);
  28405. }
  28406. return glob;
  28407. }
  28408. function callExpressionToGlob(node) {
  28409. const { callee } = node;
  28410. if (callee.type === "MemberExpression" && callee.property.type === "Identifier" && callee.property.name === "concat") return `${expressionToGlob(callee.object)}${node.arguments.map(expressionToGlob).join("")}`;
  28411. return "*";
  28412. }
  28413. function binaryExpressionToGlob(node) {
  28414. if (node.operator !== "+") throw new VariableDynamicImportError(`${node.operator} operator is not supported.`);
  28415. return `${expressionToGlob(node.left)}${expressionToGlob(node.right)}`;
  28416. }
  28417. function expressionToGlob(node) {
  28418. switch (node.type) {
  28419. case "TemplateLiteral": return templateLiteralToGlob(node);
  28420. case "CallExpression": return callExpressionToGlob(node);
  28421. case "BinaryExpression": return binaryExpressionToGlob(node);
  28422. case "Literal": return sanitizeString(node.value);
  28423. default: return "*";
  28424. }
  28425. }
  28426. const defaultProtocol = "file:";
  28427. const ignoredProtocols = [
  28428. "data:",
  28429. "http:",
  28430. "https:"
  28431. ];
  28432. function shouldIgnore(glob) {
  28433. const containsAsterisk = glob.includes("*");
  28434. const globURL = new URL(glob, defaultProtocol);
  28435. const containsIgnoredProtocol = ignoredProtocols.some((ignoredProtocol) => ignoredProtocol === globURL.protocol);
  28436. return !containsAsterisk || containsIgnoredProtocol;
  28437. }
  28438. function dynamicImportToGlob(node, sourceString) {
  28439. let glob = expressionToGlob(node);
  28440. if (shouldIgnore(glob)) return null;
  28441. glob = glob.replace(/\*\*/g, "*");
  28442. 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}`);
  28443. 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}`);
  28444. 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}`);
  28445. 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}`);
  28446. 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}`);
  28447. return glob;
  28448. }
  28449. //#endregion
  28450. //#region src/node/plugins/dynamicImportVars.ts
  28451. const dynamicImportHelperId = "\0vite/dynamic-import-helper.js";
  28452. const relativePathRE = /^\.{1,2}\//;
  28453. const hasDynamicImportRE = /\bimport\s*[(/]/;
  28454. const dynamicImportHelper = (glob, path, segs) => {
  28455. const v = glob[path];
  28456. if (v) return typeof v === "function" ? v() : Promise.resolve(v);
  28457. return new Promise((_, reject) => {
  28458. (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." : ""))));
  28459. });
  28460. };
  28461. function parseDynamicImportPattern(strings) {
  28462. const filename = strings.slice(1, -1);
  28463. const ast = parseAst(strings).body[0].expression;
  28464. const userPatternQuery = dynamicImportToGlob(ast, filename);
  28465. if (!userPatternQuery) return null;
  28466. const [userPattern] = userPatternQuery.split(requestQueryMaybeEscapedSplitRE, 2);
  28467. let [rawPattern, search] = filename.split(requestQuerySplitRE, 2);
  28468. let globParams = null;
  28469. if (search) {
  28470. search = "?" + search;
  28471. if (workerOrSharedWorkerRE.test(search) || urlRE$1.test(search) || rawRE$1.test(search)) globParams = {
  28472. query: search,
  28473. import: "*"
  28474. };
  28475. else globParams = { query: search };
  28476. }
  28477. return {
  28478. globParams,
  28479. userPattern,
  28480. rawPattern
  28481. };
  28482. }
  28483. async function transformDynamicImport(importSource, importer, resolve, root) {
  28484. if (importSource[1] !== "." && importSource[1] !== "/") {
  28485. const resolvedFileName = await resolve(importSource.slice(1, -1), importer);
  28486. if (!resolvedFileName) return null;
  28487. const relativeFileName = normalizePath(posix.relative(posix.dirname(normalizePath(importer)), normalizePath(resolvedFileName)));
  28488. importSource = "`" + (relativeFileName[0] === "." ? "" : "./") + relativeFileName + "`";
  28489. }
  28490. const dynamicImportPattern = parseDynamicImportPattern(importSource);
  28491. if (!dynamicImportPattern) return null;
  28492. const { globParams, rawPattern, userPattern } = dynamicImportPattern;
  28493. const params = globParams ? `, ${JSON.stringify(globParams)}` : "";
  28494. const dir = importer ? posix.dirname(importer) : root;
  28495. const normalized = rawPattern[0] === "/" ? posix.join(root, rawPattern.slice(1)) : posix.join(dir, rawPattern);
  28496. let newRawPattern = posix.relative(posix.dirname(importer), normalized);
  28497. if (!relativePathRE.test(newRawPattern)) newRawPattern = `./${newRawPattern}`;
  28498. const exp = `(import.meta.glob(${JSON.stringify(userPattern)}${params}))`;
  28499. return {
  28500. rawPattern: newRawPattern,
  28501. pattern: userPattern,
  28502. glob: exp
  28503. };
  28504. }
  28505. function dynamicImportVarsPlugin(config) {
  28506. const resolve = createBackCompatIdResolver(config, {
  28507. preferRelative: true,
  28508. tryIndex: false,
  28509. extensions: []
  28510. });
  28511. if (config.isBundled) return perEnvironmentPlugin("native:dynamic-import-vars", (environment) => {
  28512. const { include, exclude } = environment.config.build.dynamicImportVarsOptions;
  28513. return viteDynamicImportVarsPlugin({
  28514. include,
  28515. exclude,
  28516. resolver(id, importer) {
  28517. return resolve(environment, id, importer);
  28518. },
  28519. sourcemap: !!environment.config.build.sourcemap
  28520. });
  28521. });
  28522. const getFilter = perEnvironmentState((environment) => {
  28523. const { include, exclude } = environment.config.build.dynamicImportVarsOptions;
  28524. return createFilter$1(include, exclude);
  28525. });
  28526. return {
  28527. name: "vite:dynamic-import-vars",
  28528. resolveId: {
  28529. filter: { id: exactRegex(dynamicImportHelperId) },
  28530. handler(id) {
  28531. return id;
  28532. }
  28533. },
  28534. load: {
  28535. filter: { id: exactRegex(dynamicImportHelperId) },
  28536. handler(_id) {
  28537. return `export default ${dynamicImportHelper.toString()}`;
  28538. }
  28539. },
  28540. transform: {
  28541. filter: {
  28542. id: { exclude: exactRegex(CLIENT_ENTRY) },
  28543. code: hasDynamicImportRE
  28544. },
  28545. async handler(source, importer) {
  28546. const { environment } = this;
  28547. if (!getFilter(this)(importer)) return;
  28548. await init;
  28549. let imports = [];
  28550. try {
  28551. imports = parse$2(source)[0];
  28552. } catch {
  28553. return null;
  28554. }
  28555. if (!imports.length) return null;
  28556. let s;
  28557. let needDynamicImportHelper = false;
  28558. for (let index = 0; index < imports.length; index++) {
  28559. const { s: start, e: end, ss: expStart, se: expEnd, d: dynamicIndex } = imports[index];
  28560. if (dynamicIndex === -1 || source[start] !== "`") continue;
  28561. if (hasViteIgnoreRE.test(source.slice(expStart, expEnd))) continue;
  28562. s ||= new MagicString(source);
  28563. let result;
  28564. try {
  28565. result = await transformDynamicImport(source.slice(start, end), importer, (id, importer) => resolve(environment, id, importer), config.root);
  28566. } catch (error) {
  28567. this.warn(error);
  28568. }
  28569. if (!result) continue;
  28570. const { rawPattern, glob } = result;
  28571. needDynamicImportHelper = true;
  28572. s.overwrite(expStart, expEnd, `__variableDynamicImportRuntimeHelper(${glob}, \`${rawPattern}\`, ${rawPattern.split("/").length})`);
  28573. }
  28574. if (s) {
  28575. if (needDynamicImportHelper) s.prepend(`import __variableDynamicImportRuntimeHelper from "${dynamicImportHelperId}";`);
  28576. return transformStableResult(s, importer, config);
  28577. }
  28578. }
  28579. }
  28580. };
  28581. }
  28582. //#endregion
  28583. //#region src/node/plugins/importMetaGlob.ts
  28584. function importGlobPlugin(config) {
  28585. if (config.isBundled) return viteImportGlobPlugin({
  28586. root: config.root,
  28587. sourcemap: !!config.build.sourcemap,
  28588. restoreQueryExtension: config.experimental.importGlobRestoreExtension
  28589. });
  28590. const importGlobMaps = /* @__PURE__ */ new Map();
  28591. return {
  28592. name: "vite:import-glob",
  28593. buildStart() {
  28594. importGlobMaps.clear();
  28595. },
  28596. transform: {
  28597. filter: { code: "import.meta.glob" },
  28598. async handler(code, id) {
  28599. 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);
  28600. if (result) {
  28601. const allGlobs = result.matches.map((i) => i.globsResolved);
  28602. if (!importGlobMaps.has(this.environment)) importGlobMaps.set(this.environment, /* @__PURE__ */ new Map());
  28603. const globMatchers = allGlobs.map((globs) => {
  28604. const affirmed = [];
  28605. const negated = [];
  28606. for (const glob of globs) if (glob[0] === "!") negated.push(glob.slice(1));
  28607. else affirmed.push(glob);
  28608. const affirmedMatcher = picomatch(affirmed);
  28609. const negatedMatcher = picomatch(negated);
  28610. return (file) => {
  28611. return (affirmed.length === 0 || affirmedMatcher(file)) && !(negated.length > 0 && negatedMatcher(file));
  28612. };
  28613. });
  28614. importGlobMaps.get(this.environment).set(id, globMatchers);
  28615. return transformStableResult(result.s, id, config);
  28616. }
  28617. }
  28618. },
  28619. hotUpdate({ type, file, modules: oldModules }) {
  28620. if (type === "update") return;
  28621. const importGlobMap = importGlobMaps.get(this.environment);
  28622. if (!importGlobMap) return;
  28623. const modules = [];
  28624. for (const [id, globMatchers] of importGlobMap) if (globMatchers.some((matcher) => matcher(file))) {
  28625. const mod = this.environment.moduleGraph.getModuleById(id);
  28626. if (mod) modules.push(mod);
  28627. }
  28628. return modules.length > 0 ? [...oldModules, ...modules] : void 0;
  28629. }
  28630. };
  28631. }
  28632. const importGlobRE = /\bimport\.meta\.glob(?:<\w+>)?\s*\(/g;
  28633. const objectKeysRE = /\bObject\.keys\(\s*$/;
  28634. const objectValuesRE = /\bObject\.values\(\s*$/;
  28635. const knownOptions = {
  28636. as: ["string"],
  28637. eager: ["boolean"],
  28638. import: ["string"],
  28639. exhaustive: ["boolean"],
  28640. query: ["object", "string"],
  28641. base: ["string"]
  28642. };
  28643. const forceDefaultAs = ["raw", "url"];
  28644. function err(e, pos) {
  28645. const error = new Error(e);
  28646. error.pos = pos;
  28647. return error;
  28648. }
  28649. function parseGlobOptions(rawOpts, optsStartIndex, logger) {
  28650. let opts = {};
  28651. try {
  28652. opts = evalValue(rawOpts);
  28653. } catch {
  28654. throw err("Vite is unable to parse the glob options as the value is not static", optsStartIndex);
  28655. }
  28656. if (opts == null) return {};
  28657. for (const key in opts) {
  28658. if (!(key in knownOptions)) throw err(`Unknown glob option "${key}"`, optsStartIndex);
  28659. const allowedTypes = knownOptions[key];
  28660. const valueType = typeof opts[key];
  28661. if (!allowedTypes.includes(valueType)) throw err(`Expected glob option "${key}" to be of type ${allowedTypes.join(" or ")}, but got ${valueType}`, optsStartIndex);
  28662. }
  28663. if (opts.base) {
  28664. if (opts.base[0] === "!") throw err("Option \"base\" cannot start with \"!\"", optsStartIndex);
  28665. else if (opts.base[0] !== "/" && !opts.base.startsWith("./") && !opts.base.startsWith("../")) throw err(`Option "base" must start with '/', './' or '../', but got "${opts.base}"`, optsStartIndex);
  28666. }
  28667. if (typeof opts.query === "object") {
  28668. for (const key in opts.query) {
  28669. const value = opts.query[key];
  28670. if (![
  28671. "string",
  28672. "number",
  28673. "boolean"
  28674. ].includes(typeof value)) throw err(`Expected glob option "query.${key}" to be of type string, number, or boolean, but got ${typeof value}`, optsStartIndex);
  28675. }
  28676. opts.query = stringifyQuery(opts.query);
  28677. }
  28678. if (opts.as && logger) {
  28679. const importSuggestion = forceDefaultAs.includes(opts.as) ? `, import: 'default'` : "";
  28680. 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}\`.`));
  28681. }
  28682. if (opts.as && forceDefaultAs.includes(opts.as)) {
  28683. 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);
  28684. opts.import = opts.import || "default";
  28685. }
  28686. if (opts.as && opts.query) throw err("Options \"as\" and \"query\" cannot be used together", optsStartIndex);
  28687. if (opts.as) opts.query = opts.as;
  28688. if (opts.query && opts.query[0] !== "?") opts.query = `?${opts.query}`;
  28689. return opts;
  28690. }
  28691. async function parseImportGlob(code, importer, root, resolveId, logger) {
  28692. let cleanCode;
  28693. try {
  28694. cleanCode = stripLiteral(code);
  28695. } catch {
  28696. return [];
  28697. }
  28698. const tasks = Array.from(cleanCode.matchAll(importGlobRE)).map(async (match, index) => {
  28699. const start = match.index;
  28700. const err = (msg) => {
  28701. const e = /* @__PURE__ */ new Error(`Invalid glob import syntax: ${msg}`);
  28702. e.pos = start;
  28703. return e;
  28704. };
  28705. const end = findCorrespondingCloseParenthesisPosition(cleanCode, start + match[0].length) + 1;
  28706. if (end <= 0) throw err("Close parenthesis not found");
  28707. const rootAst = (await parseAstAsync(code.slice(start, end))).body[0];
  28708. if (rootAst.type !== "ExpressionStatement") throw err(`Expect CallExpression, got ${rootAst.type}`);
  28709. const ast = rootAst.expression;
  28710. if (ast.type !== "CallExpression") throw err(`Expect CallExpression, got ${ast.type}`);
  28711. if (ast.arguments.length < 1 || ast.arguments.length > 2) throw err(`Expected 1-2 arguments, but got ${ast.arguments.length}`);
  28712. const arg1 = ast.arguments[0];
  28713. const arg2 = ast.arguments[1];
  28714. const globs = [];
  28715. const validateLiteral = (element) => {
  28716. if (!element) return;
  28717. if (element.type === "Literal") {
  28718. if (typeof element.value !== "string") throw err(`Expected glob to be a string, but got "${typeof element.value}"`);
  28719. globs.push(element.value);
  28720. } else if (element.type === "TemplateLiteral") {
  28721. if (element.expressions.length !== 0) throw err(`Expected glob to be a string, but got dynamic template literal`);
  28722. globs.push(element.quasis[0].value.raw);
  28723. } else throw err("Could only use literals");
  28724. };
  28725. if (arg1.type === "ArrayExpression") for (const element of arg1.elements) validateLiteral(element);
  28726. else validateLiteral(arg1);
  28727. let options = {};
  28728. if (arg2) {
  28729. if (arg2.type !== "ObjectExpression") throw err(`Expected the second argument to be an object literal, but got "${arg2.type}"`);
  28730. options = parseGlobOptions(code.slice(start + arg2.start, start + arg2.end), start + arg2.start, logger);
  28731. }
  28732. const globsResolved = await Promise.all(globs.map((glob) => toAbsoluteGlob(glob, root, importer, resolveId, options.base)));
  28733. const isRelative = globs.every((i) => ".!".includes(i[0]));
  28734. const sliceCode = cleanCode.slice(0, start);
  28735. const onlyKeys = objectKeysRE.test(sliceCode);
  28736. let onlyValues = false;
  28737. if (!onlyKeys) onlyValues = objectValuesRE.test(sliceCode);
  28738. return {
  28739. index,
  28740. globs,
  28741. globsResolved,
  28742. isRelative,
  28743. options,
  28744. start,
  28745. end,
  28746. onlyKeys,
  28747. onlyValues
  28748. };
  28749. });
  28750. return (await Promise.all(tasks)).filter(Boolean);
  28751. }
  28752. function findCorrespondingCloseParenthesisPosition(cleanCode, openPos) {
  28753. const closePos = cleanCode.indexOf(")", openPos);
  28754. if (closePos < 0) return -1;
  28755. if (!cleanCode.slice(openPos, closePos).includes("(")) return closePos;
  28756. let remainingParenthesisCount = 0;
  28757. const cleanCodeLen = cleanCode.length;
  28758. for (let pos = openPos; pos < cleanCodeLen; pos++) switch (cleanCode[pos]) {
  28759. case "(":
  28760. remainingParenthesisCount++;
  28761. break;
  28762. case ")":
  28763. remainingParenthesisCount--;
  28764. if (remainingParenthesisCount <= 0) return pos;
  28765. }
  28766. return -1;
  28767. }
  28768. const importPrefix = "__vite_glob_";
  28769. const { basename: basename$1, dirname: dirname$1, relative: relative$1 } = posix;
  28770. /**
  28771. * @param optimizeExport for dynamicImportVar plugin don't need to optimize export.
  28772. */
  28773. async function transformGlobImport(code, id, root, resolveId, restoreQueryExtension = false, logger) {
  28774. id = slash(id);
  28775. root = slash(root);
  28776. const isVirtual = isVirtualModule(id);
  28777. const dir = isVirtual ? void 0 : dirname$1(id);
  28778. const matches = await parseImportGlob(code, isVirtual ? void 0 : id, root, resolveId, logger);
  28779. const matchedFiles = /* @__PURE__ */ new Set();
  28780. if (!matches.length) return null;
  28781. const s = new MagicString(code);
  28782. const staticImports = (await Promise.all(matches.map(async ({ globsResolved, isRelative, options, index, start, end, onlyKeys, onlyValues }) => {
  28783. const files = (await glob(globsResolved, {
  28784. absolute: true,
  28785. cwd: getCommonBase(globsResolved) ?? root,
  28786. dot: !!options.exhaustive,
  28787. expandDirectories: false,
  28788. ignore: options.exhaustive ? [] : ["**/node_modules/**"],
  28789. extglob: false
  28790. })).filter((file) => file !== id).sort();
  28791. const objectProps = [];
  28792. const staticImports = [];
  28793. const resolvePaths = (file) => {
  28794. if (!dir) {
  28795. if (!options.base && isRelative) throw new Error("In virtual modules, all globs must start with '/'");
  28796. const importPath = `/${relative$1(root, file)}`;
  28797. let filePath = options.base ? `${relative$1(posix.join(root, options.base), file)}` : importPath;
  28798. if (options.base && !filePath.startsWith("./") && !filePath.startsWith("../")) filePath = `./${filePath}`;
  28799. return {
  28800. filePath,
  28801. importPath
  28802. };
  28803. }
  28804. let importPath = relative$1(dir, file);
  28805. if (!importPath.startsWith("./") && !importPath.startsWith("../")) importPath = `./${importPath}`;
  28806. let filePath;
  28807. if (options.base) {
  28808. filePath = relative$1(posix.join(options.base[0] === "/" ? root : dir, options.base), file);
  28809. if (!filePath.startsWith("./") && !filePath.startsWith("../")) filePath = `./${filePath}`;
  28810. if (options.base[0] === "/") importPath = `/${relative$1(root, file)}`;
  28811. } else if (isRelative) filePath = importPath;
  28812. else {
  28813. filePath = relative$1(root, file);
  28814. if (!filePath.startsWith("./") && !filePath.startsWith("../")) filePath = `/${filePath}`;
  28815. }
  28816. return {
  28817. filePath,
  28818. importPath
  28819. };
  28820. };
  28821. files.forEach((file, i) => {
  28822. const paths = resolvePaths(file);
  28823. const filePath = paths.filePath;
  28824. let importPath = paths.importPath;
  28825. let importQuery = options.query ?? "";
  28826. if (onlyKeys) {
  28827. objectProps.push(`${JSON.stringify(filePath)}: 0`);
  28828. return;
  28829. }
  28830. if (importQuery && importQuery !== "?raw") {
  28831. const fileExtension = basename$1(file).split(".").slice(-1)[0];
  28832. if (fileExtension && restoreQueryExtension) importQuery = `${importQuery}&lang.${fileExtension}`;
  28833. }
  28834. importPath = `${importPath}${importQuery}`;
  28835. const importKey = options.import && options.import !== "*" ? options.import : void 0;
  28836. if (options.eager) {
  28837. const variableName = `${importPrefix}${index}_${i}`;
  28838. const expression = importKey ? `{ ${importKey} as ${variableName} }` : `* as ${variableName}`;
  28839. staticImports.push(`import ${expression} from ${JSON.stringify(importPath)}`);
  28840. objectProps.push(onlyValues ? `${variableName}` : `${JSON.stringify(filePath)}: ${variableName}`);
  28841. } else {
  28842. let importStatement = `import(${JSON.stringify(importPath)})`;
  28843. if (importKey) importStatement += `.then(m => m[${JSON.stringify(importKey)}])`;
  28844. objectProps.push(onlyValues ? `() => ${importStatement}` : `${JSON.stringify(filePath)}: () => ${importStatement}`);
  28845. }
  28846. });
  28847. files.forEach((i) => matchedFiles.add(i));
  28848. const originalLineBreakCount = code.slice(start, end).match(/\n/g)?.length ?? 0;
  28849. const lineBreaks = originalLineBreakCount > 0 ? "\n".repeat(originalLineBreakCount) : "";
  28850. let replacement = "";
  28851. if (onlyKeys) replacement = `{${objectProps.join(",")}${lineBreaks}}`;
  28852. else if (onlyValues) replacement = `[${objectProps.join(",")}${lineBreaks}]`;
  28853. else replacement = `/* #__PURE__ */ Object.assign({${objectProps.join(",")}${lineBreaks}})`;
  28854. s.overwrite(start, end, replacement);
  28855. return staticImports;
  28856. }))).flat();
  28857. if (staticImports.length) s.prepend(`${staticImports.join(";")};`);
  28858. return {
  28859. s,
  28860. matches,
  28861. files: matchedFiles
  28862. };
  28863. }
  28864. function globSafePath(path) {
  28865. return escapePath(normalizePath(path));
  28866. }
  28867. function lastNthChar(str, n) {
  28868. return str.charAt(str.length - 1 - n);
  28869. }
  28870. function globSafeResolvedPath(resolved, glob) {
  28871. let numEqual = 0;
  28872. const maxEqual = Math.min(resolved.length, glob.length);
  28873. while (numEqual < maxEqual && lastNthChar(resolved, numEqual) === lastNthChar(glob, numEqual)) numEqual += 1;
  28874. const staticPartEnd = resolved.length - numEqual;
  28875. const staticPart = resolved.slice(0, staticPartEnd);
  28876. const dynamicPart = resolved.slice(staticPartEnd);
  28877. return globSafePath(staticPart) + dynamicPart;
  28878. }
  28879. async function toAbsoluteGlob(glob, root, importer, resolveId, base) {
  28880. let pre = "";
  28881. if (glob[0] === "!") {
  28882. pre = "!";
  28883. glob = glob.slice(1);
  28884. }
  28885. root = globSafePath(root);
  28886. let dir;
  28887. if (base) if (base[0] === "/") dir = posix.join(root, base);
  28888. else dir = posix.resolve(importer ? globSafePath(dirname$1(importer)) : root, base);
  28889. else dir = importer ? globSafePath(dirname$1(importer)) : root;
  28890. if (glob[0] === "/") return pre + posix.join(root, glob.slice(1));
  28891. if (glob.startsWith("./")) return pre + posix.join(dir, glob.slice(2));
  28892. if (glob.startsWith("../")) return pre + posix.join(dir, glob);
  28893. if (glob.startsWith("**")) return pre + glob;
  28894. const isSubImportsPattern = glob[0] === "#" && glob.includes("*");
  28895. const resolved = normalizePath(await resolveId(glob, importer, { custom: { "vite:import-glob": { isSubImportsPattern } } }) || glob);
  28896. if (isAbsolute(resolved)) return pre + globSafeResolvedPath(resolved, glob);
  28897. throw new Error(`Invalid glob: "${glob}" (resolved: "${resolved}"). It must start with '/' or './'`);
  28898. }
  28899. function getCommonBase(globsResolved) {
  28900. const bases = globsResolved.filter((g) => g[0] !== "!").map((glob) => {
  28901. let { base } = picomatch.scan(glob);
  28902. if (posix.basename(base).includes(".")) base = posix.dirname(base);
  28903. return base;
  28904. });
  28905. if (!bases.length) return null;
  28906. let commonAncestor = "";
  28907. const dirS = bases[0].split("/");
  28908. for (let i = 0; i < dirS.length; i++) {
  28909. const candidate = dirS.slice(0, i + 1).join("/");
  28910. if (bases.every((base) => base.startsWith(candidate))) commonAncestor = candidate;
  28911. else break;
  28912. }
  28913. if (!commonAncestor) commonAncestor = "/";
  28914. return commonAncestor;
  28915. }
  28916. function isVirtualModule(id) {
  28917. return id.startsWith("virtual:") || id[0] === "\0" || !id.includes("/");
  28918. }
  28919. //#endregion
  28920. //#region src/node/plugins/pluginFilter.ts
  28921. function getMatcherString(glob, cwd) {
  28922. if (glob.startsWith("**") || path.isAbsolute(glob)) return slash(glob);
  28923. return slash(path.join(cwd, glob));
  28924. }
  28925. function patternToIdFilter(pattern, cwd) {
  28926. if (pattern instanceof RegExp) return (id) => {
  28927. const normalizedId = slash(id);
  28928. const result = pattern.test(normalizedId);
  28929. pattern.lastIndex = 0;
  28930. return result;
  28931. };
  28932. const matcher = picomatch(getMatcherString(pattern, cwd), { dot: true });
  28933. return (id) => {
  28934. return matcher(slash(id));
  28935. };
  28936. }
  28937. function patternToCodeFilter(pattern) {
  28938. if (pattern instanceof RegExp) return (code) => {
  28939. const result = pattern.test(code);
  28940. pattern.lastIndex = 0;
  28941. return result;
  28942. };
  28943. return (code) => code.includes(pattern);
  28944. }
  28945. function createFilter(exclude, include) {
  28946. if (!exclude && !include) return;
  28947. return (input) => {
  28948. if (exclude?.some((filter) => filter(input))) return false;
  28949. if (include?.some((filter) => filter(input))) return true;
  28950. return !(include && include.length > 0);
  28951. };
  28952. }
  28953. function normalizeFilter(filter) {
  28954. if (typeof filter === "string" || filter instanceof RegExp) return { include: [filter] };
  28955. if (Array.isArray(filter)) return { include: filter };
  28956. return {
  28957. include: filter.include ? arraify(filter.include) : void 0,
  28958. exclude: filter.exclude ? arraify(filter.exclude) : void 0
  28959. };
  28960. }
  28961. function createIdFilter(filter, cwd = process.cwd()) {
  28962. if (!filter) return;
  28963. const { exclude, include } = normalizeFilter(filter);
  28964. const excludeFilter = exclude?.map((p) => patternToIdFilter(p, cwd));
  28965. const includeFilter = include?.map((p) => patternToIdFilter(p, cwd));
  28966. return createFilter(excludeFilter, includeFilter);
  28967. }
  28968. function createCodeFilter(filter) {
  28969. if (!filter) return;
  28970. const { exclude, include } = normalizeFilter(filter);
  28971. const excludeFilter = exclude?.map(patternToCodeFilter);
  28972. const includeFilter = include?.map(patternToCodeFilter);
  28973. return createFilter(excludeFilter, includeFilter);
  28974. }
  28975. function createModuleTypeFilter(filter) {
  28976. if (!filter) return;
  28977. const include = Array.isArray(filter) ? filter : filter.include ?? [];
  28978. return (moduleType) => include.includes(moduleType);
  28979. }
  28980. function createFilterForTransform(idFilter, codeFilter, moduleTypeFilter, cwd) {
  28981. if (!idFilter && !codeFilter && !moduleTypeFilter) return;
  28982. const idFilterFn = createIdFilter(idFilter, cwd);
  28983. const codeFilterFn = createCodeFilter(codeFilter);
  28984. const moduleTypeFilterFn = createModuleTypeFilter(moduleTypeFilter);
  28985. return (id, code, moduleType) => {
  28986. let fallback = moduleTypeFilterFn?.(moduleType) ?? true;
  28987. if (!fallback) return false;
  28988. if (idFilterFn) fallback &&= idFilterFn(id);
  28989. if (!fallback) return false;
  28990. if (codeFilterFn) fallback &&= codeFilterFn(code);
  28991. return fallback;
  28992. };
  28993. }
  28994. //#endregion
  28995. //#region ../../node_modules/.pnpm/@vitest+utils@4.1.0-beta.6/node_modules/@vitest/utils/dist/helpers.js
  28996. function notNullish(v) {
  28997. return v != null;
  28998. }
  28999. function isPrimitive(value) {
  29000. return value === null || typeof value !== "function" && typeof value !== "object";
  29001. }
  29002. //#endregion
  29003. //#region ../../node_modules/.pnpm/@vitest+utils@4.1.0-beta.6/node_modules/@vitest/utils/dist/chunk-pathe.M-eThtNZ.js
  29004. const _DRIVE_LETTER_START_RE = /^[A-Za-z]:\//;
  29005. function normalizeWindowsPath(input = "") {
  29006. if (!input) return input;
  29007. return input.replace(/\\/g, "/").replace(_DRIVE_LETTER_START_RE, (r) => r.toUpperCase());
  29008. }
  29009. const _IS_ABSOLUTE_RE = /^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/;
  29010. function cwd() {
  29011. if (typeof process !== "undefined" && typeof process.cwd === "function") return process.cwd().replace(/\\/g, "/");
  29012. return "/";
  29013. }
  29014. const resolve$2 = function(...arguments_) {
  29015. arguments_ = arguments_.map((argument) => normalizeWindowsPath(argument));
  29016. let resolvedPath = "";
  29017. let resolvedAbsolute = false;
  29018. for (let index = arguments_.length - 1; index >= -1 && !resolvedAbsolute; index--) {
  29019. const path = index >= 0 ? arguments_[index] : cwd();
  29020. if (!path || path.length === 0) continue;
  29021. resolvedPath = `${path}/${resolvedPath}`;
  29022. resolvedAbsolute = isAbsolute$2(path);
  29023. }
  29024. resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute);
  29025. if (resolvedAbsolute && !isAbsolute$2(resolvedPath)) return `/${resolvedPath}`;
  29026. return resolvedPath.length > 0 ? resolvedPath : ".";
  29027. };
  29028. function normalizeString(path, allowAboveRoot) {
  29029. let res = "";
  29030. let lastSegmentLength = 0;
  29031. let lastSlash = -1;
  29032. let dots = 0;
  29033. let char = null;
  29034. for (let index = 0; index <= path.length; ++index) {
  29035. if (index < path.length) char = path[index];
  29036. else if (char === "/") break;
  29037. else char = "/";
  29038. if (char === "/") {
  29039. if (lastSlash === index - 1 || dots === 1);
  29040. else if (dots === 2) {
  29041. if (res.length < 2 || lastSegmentLength !== 2 || res[res.length - 1] !== "." || res[res.length - 2] !== ".") {
  29042. if (res.length > 2) {
  29043. const lastSlashIndex = res.lastIndexOf("/");
  29044. if (lastSlashIndex === -1) {
  29045. res = "";
  29046. lastSegmentLength = 0;
  29047. } else {
  29048. res = res.slice(0, lastSlashIndex);
  29049. lastSegmentLength = res.length - 1 - res.lastIndexOf("/");
  29050. }
  29051. lastSlash = index;
  29052. dots = 0;
  29053. continue;
  29054. } else if (res.length > 0) {
  29055. res = "";
  29056. lastSegmentLength = 0;
  29057. lastSlash = index;
  29058. dots = 0;
  29059. continue;
  29060. }
  29061. }
  29062. if (allowAboveRoot) {
  29063. res += res.length > 0 ? "/.." : "..";
  29064. lastSegmentLength = 2;
  29065. }
  29066. } else {
  29067. if (res.length > 0) res += `/${path.slice(lastSlash + 1, index)}`;
  29068. else res = path.slice(lastSlash + 1, index);
  29069. lastSegmentLength = index - lastSlash - 1;
  29070. }
  29071. lastSlash = index;
  29072. dots = 0;
  29073. } else if (char === "." && dots !== -1) ++dots;
  29074. else dots = -1;
  29075. }
  29076. return res;
  29077. }
  29078. const isAbsolute$2 = function(p) {
  29079. return _IS_ABSOLUTE_RE.test(p);
  29080. };
  29081. //#endregion
  29082. //#region ../../node_modules/.pnpm/@vitest+utils@4.1.0-beta.6/node_modules/@vitest/utils/dist/source-map.js
  29083. var comma = ",".charCodeAt(0);
  29084. var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  29085. var intToChar = new Uint8Array(64);
  29086. var charToInt = new Uint8Array(128);
  29087. for (let i = 0; i < chars.length; i++) {
  29088. const c = chars.charCodeAt(i);
  29089. intToChar[i] = c;
  29090. charToInt[c] = i;
  29091. }
  29092. function decodeInteger(reader, relative) {
  29093. let value = 0;
  29094. let shift = 0;
  29095. let integer = 0;
  29096. do {
  29097. integer = charToInt[reader.next()];
  29098. value |= (integer & 31) << shift;
  29099. shift += 5;
  29100. } while (integer & 32);
  29101. const shouldNegate = value & 1;
  29102. value >>>= 1;
  29103. if (shouldNegate) value = -2147483648 | -value;
  29104. return relative + value;
  29105. }
  29106. function hasMoreVlq(reader, max) {
  29107. if (reader.pos >= max) return false;
  29108. return reader.peek() !== comma;
  29109. }
  29110. var StringReader = class {
  29111. constructor(buffer) {
  29112. this.pos = 0;
  29113. this.buffer = buffer;
  29114. }
  29115. next() {
  29116. return this.buffer.charCodeAt(this.pos++);
  29117. }
  29118. peek() {
  29119. return this.buffer.charCodeAt(this.pos);
  29120. }
  29121. indexOf(char) {
  29122. const { buffer, pos } = this;
  29123. const idx = buffer.indexOf(char, pos);
  29124. return idx === -1 ? buffer.length : idx;
  29125. }
  29126. };
  29127. function decode(mappings) {
  29128. const { length } = mappings;
  29129. const reader = new StringReader(mappings);
  29130. const decoded = [];
  29131. let genColumn = 0;
  29132. let sourcesIndex = 0;
  29133. let sourceLine = 0;
  29134. let sourceColumn = 0;
  29135. let namesIndex = 0;
  29136. do {
  29137. const semi = reader.indexOf(";");
  29138. const line = [];
  29139. let sorted = true;
  29140. let lastCol = 0;
  29141. genColumn = 0;
  29142. while (reader.pos < semi) {
  29143. let seg;
  29144. genColumn = decodeInteger(reader, genColumn);
  29145. if (genColumn < lastCol) sorted = false;
  29146. lastCol = genColumn;
  29147. if (hasMoreVlq(reader, semi)) {
  29148. sourcesIndex = decodeInteger(reader, sourcesIndex);
  29149. sourceLine = decodeInteger(reader, sourceLine);
  29150. sourceColumn = decodeInteger(reader, sourceColumn);
  29151. if (hasMoreVlq(reader, semi)) {
  29152. namesIndex = decodeInteger(reader, namesIndex);
  29153. seg = [
  29154. genColumn,
  29155. sourcesIndex,
  29156. sourceLine,
  29157. sourceColumn,
  29158. namesIndex
  29159. ];
  29160. } else seg = [
  29161. genColumn,
  29162. sourcesIndex,
  29163. sourceLine,
  29164. sourceColumn
  29165. ];
  29166. } else seg = [genColumn];
  29167. line.push(seg);
  29168. reader.pos++;
  29169. }
  29170. if (!sorted) sort(line);
  29171. decoded.push(line);
  29172. reader.pos = semi + 1;
  29173. } while (reader.pos <= length);
  29174. return decoded;
  29175. }
  29176. function sort(line) {
  29177. line.sort(sortComparator);
  29178. }
  29179. function sortComparator(a, b) {
  29180. return a[0] - b[0];
  29181. }
  29182. var COLUMN = 0;
  29183. var SOURCES_INDEX = 1;
  29184. var SOURCE_LINE = 2;
  29185. var SOURCE_COLUMN = 3;
  29186. var NAMES_INDEX = 4;
  29187. var found = false;
  29188. function binarySearch(haystack, needle, low, high) {
  29189. while (low <= high) {
  29190. const mid = low + (high - low >> 1);
  29191. const cmp = haystack[mid][COLUMN] - needle;
  29192. if (cmp === 0) {
  29193. found = true;
  29194. return mid;
  29195. }
  29196. if (cmp < 0) low = mid + 1;
  29197. else high = mid - 1;
  29198. }
  29199. found = false;
  29200. return low - 1;
  29201. }
  29202. function upperBound(haystack, needle, index) {
  29203. for (let i = index + 1; i < haystack.length; index = i++) if (haystack[i][COLUMN] !== needle) break;
  29204. return index;
  29205. }
  29206. function lowerBound(haystack, needle, index) {
  29207. for (let i = index - 1; i >= 0; index = i--) if (haystack[i][COLUMN] !== needle) break;
  29208. return index;
  29209. }
  29210. function memoizedBinarySearch(haystack, needle, state, key) {
  29211. const { lastKey, lastNeedle, lastIndex } = state;
  29212. let low = 0;
  29213. let high = haystack.length - 1;
  29214. if (key === lastKey) {
  29215. if (needle === lastNeedle) {
  29216. found = lastIndex !== -1 && haystack[lastIndex][COLUMN] === needle;
  29217. return lastIndex;
  29218. }
  29219. if (needle >= lastNeedle) low = lastIndex === -1 ? 0 : lastIndex;
  29220. else high = lastIndex;
  29221. }
  29222. state.lastKey = key;
  29223. state.lastNeedle = needle;
  29224. return state.lastIndex = binarySearch(haystack, needle, low, high);
  29225. }
  29226. var LINE_GTR_ZERO = "`line` must be greater than 0 (lines start at line 1)";
  29227. var COL_GTR_EQ_ZERO = "`column` must be greater than or equal to 0 (columns start at column 0)";
  29228. var LEAST_UPPER_BOUND = -1;
  29229. var GREATEST_LOWER_BOUND = 1;
  29230. function cast(map) {
  29231. return map;
  29232. }
  29233. function decodedMappings(map) {
  29234. var _a;
  29235. return (_a = cast(map))._decoded || (_a._decoded = decode(cast(map)._encoded));
  29236. }
  29237. function originalPositionFor(map, needle) {
  29238. let { line, column, bias } = needle;
  29239. line--;
  29240. if (line < 0) throw new Error(LINE_GTR_ZERO);
  29241. if (column < 0) throw new Error(COL_GTR_EQ_ZERO);
  29242. const decoded = decodedMappings(map);
  29243. if (line >= decoded.length) return OMapping(null, null, null, null);
  29244. const segments = decoded[line];
  29245. const index = traceSegmentInternal(segments, cast(map)._decodedMemo, line, column, bias || GREATEST_LOWER_BOUND);
  29246. if (index === -1) return OMapping(null, null, null, null);
  29247. const segment = segments[index];
  29248. if (segment.length === 1) return OMapping(null, null, null, null);
  29249. const { names, resolvedSources } = map;
  29250. return OMapping(resolvedSources[segment[SOURCES_INDEX]], segment[SOURCE_LINE] + 1, segment[SOURCE_COLUMN], segment.length === 5 ? names[segment[NAMES_INDEX]] : null);
  29251. }
  29252. function OMapping(source, line, column, name) {
  29253. return {
  29254. source,
  29255. line,
  29256. column,
  29257. name
  29258. };
  29259. }
  29260. function traceSegmentInternal(segments, memo, line, column, bias) {
  29261. let index = memoizedBinarySearch(segments, column, memo, line);
  29262. if (found) index = (bias === LEAST_UPPER_BOUND ? upperBound : lowerBound)(segments, column, index);
  29263. else if (bias === LEAST_UPPER_BOUND) index++;
  29264. if (index === -1 || index === segments.length) return -1;
  29265. return index;
  29266. }
  29267. const CHROME_IE_STACK_REGEXP = /^\s*at .*(?:\S:\d+|\(native\))/m;
  29268. const SAFARI_NATIVE_CODE_REGEXP = /^(?:eval@)?(?:\[native code\])?$/;
  29269. const stackIgnorePatterns = [
  29270. "node:internal",
  29271. /\/packages\/\w+\/dist\//,
  29272. /\/@vitest\/\w+\/dist\//,
  29273. "/vitest/dist/",
  29274. "/vitest/src/",
  29275. "/node_modules/chai/",
  29276. "/node_modules/tinyspy/",
  29277. "/vite/dist/node/module-runner",
  29278. "/rolldown-vite/dist/node/module-runner",
  29279. "/deps/chunk-",
  29280. "/deps/@vitest",
  29281. "/deps/loupe",
  29282. "/deps/chai",
  29283. "/browser-playwright/dist/locators.js",
  29284. "/browser-webdriverio/dist/locators.js",
  29285. "/browser-preview/dist/locators.js",
  29286. /node:\w+/,
  29287. /__vitest_test__/,
  29288. /__vitest_browser__/,
  29289. "/@id/__x00__vitest/browser",
  29290. /\/deps\/vitest_/
  29291. ];
  29292. const NOW_LENGTH = Date.now().toString().length;
  29293. const REGEXP_VITEST = new RegExp(`vitest=\\d{${NOW_LENGTH}}`);
  29294. function extractLocation(urlLike) {
  29295. if (!urlLike.includes(":")) return [urlLike];
  29296. const parts = /(.+?)(?::(\d+))?(?::(\d+))?$/.exec(urlLike.replace(/^\(|\)$/g, ""));
  29297. if (!parts) return [urlLike];
  29298. let url = parts[1];
  29299. if (url.startsWith("async ")) url = url.slice(6);
  29300. if (url.startsWith("http:") || url.startsWith("https:")) {
  29301. const urlObj = new URL(url);
  29302. urlObj.searchParams.delete("import");
  29303. urlObj.searchParams.delete("browserv");
  29304. url = urlObj.pathname + urlObj.hash + urlObj.search;
  29305. }
  29306. if (url.startsWith("/@fs/")) {
  29307. const isWindows = /^\/@fs\/[a-zA-Z]:\//.test(url);
  29308. url = url.slice(isWindows ? 5 : 4);
  29309. }
  29310. if (url.includes("vitest=")) url = url.replace(REGEXP_VITEST, "").replace(/[?&]$/, "");
  29311. return [
  29312. url,
  29313. parts[2] || void 0,
  29314. parts[3] || void 0
  29315. ];
  29316. }
  29317. function parseSingleFFOrSafariStack(raw) {
  29318. let line = raw.trim();
  29319. if (SAFARI_NATIVE_CODE_REGEXP.test(line)) return null;
  29320. if (line.includes(" > eval")) line = line.replace(/ line (\d+)(?: > eval line \d+)* > eval:\d+:\d+/g, ":$1");
  29321. if (!line.includes("@")) return null;
  29322. let atIndex = -1;
  29323. let locationPart = "";
  29324. let functionName;
  29325. for (let i = 0; i < line.length; i++) if (line[i] === "@") {
  29326. const candidateLocation = line.slice(i + 1);
  29327. if (candidateLocation.includes(":") && candidateLocation.length >= 3) {
  29328. atIndex = i;
  29329. locationPart = candidateLocation;
  29330. functionName = i > 0 ? line.slice(0, i) : void 0;
  29331. break;
  29332. }
  29333. }
  29334. if (atIndex === -1 || !locationPart.includes(":") || locationPart.length < 3) return null;
  29335. const [url, lineNumber, columnNumber] = extractLocation(locationPart);
  29336. if (!url || !lineNumber || !columnNumber) return null;
  29337. return {
  29338. file: url,
  29339. method: functionName || "",
  29340. line: Number.parseInt(lineNumber),
  29341. column: Number.parseInt(columnNumber)
  29342. };
  29343. }
  29344. function parseSingleV8Stack(raw) {
  29345. let line = raw.trim();
  29346. if (!CHROME_IE_STACK_REGEXP.test(line)) return null;
  29347. if (line.includes("(eval ")) line = line.replace(/eval code/g, "eval").replace(/(\(eval at [^()]*)|(,.*$)/g, "");
  29348. let sanitizedLine = line.replace(/^\s+/, "").replace(/\(eval code/g, "(").replace(/^.*?\s+/, "");
  29349. const location = sanitizedLine.match(/ (\(.+\)$)/);
  29350. sanitizedLine = location ? sanitizedLine.replace(location[0], "") : sanitizedLine;
  29351. const [url, lineNumber, columnNumber] = extractLocation(location ? location[1] : sanitizedLine);
  29352. let method = location && sanitizedLine || "";
  29353. let file = url && ["eval", "<anonymous>"].includes(url) ? void 0 : url;
  29354. if (!file || !lineNumber || !columnNumber) return null;
  29355. if (method.startsWith("async ")) method = method.slice(6);
  29356. if (file.startsWith("file://")) file = file.slice(7);
  29357. file = file.startsWith("node:") || file.startsWith("internal:") ? file : resolve$2(file);
  29358. 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, "");
  29359. return {
  29360. method,
  29361. file,
  29362. line: Number.parseInt(lineNumber),
  29363. column: Number.parseInt(columnNumber)
  29364. };
  29365. }
  29366. function parseStacktrace(stack, options = {}) {
  29367. const { ignoreStackEntries = stackIgnorePatterns } = options;
  29368. let stacks = !CHROME_IE_STACK_REGEXP.test(stack) ? parseFFOrSafariStackTrace(stack) : parseV8Stacktrace(stack);
  29369. const helperIndex = stacks.findLastIndex((s) => s.method === "__VITEST_HELPER__" || s.method === "async*__VITEST_HELPER__");
  29370. if (helperIndex >= 0) stacks = stacks.slice(helperIndex + 1);
  29371. return stacks.map((stack) => {
  29372. if (options.getUrlId) stack.file = options.getUrlId(stack.file);
  29373. const map = options.getSourceMap?.(stack.file);
  29374. if (!map || typeof map !== "object" || !map.version) return shouldFilter(ignoreStackEntries, stack.file) ? null : stack;
  29375. const position = getOriginalPosition(new DecodedMap(map, stack.file), stack);
  29376. if (!position) return stack;
  29377. const { line, column, source, name } = position;
  29378. let file = source || stack.file;
  29379. if (file.match(/\/\w:\//)) file = file.slice(1);
  29380. if (shouldFilter(ignoreStackEntries, file)) return null;
  29381. if (line != null && column != null) return {
  29382. line,
  29383. column,
  29384. file,
  29385. method: name || stack.method
  29386. };
  29387. return stack;
  29388. }).filter((s) => s != null);
  29389. }
  29390. function shouldFilter(ignoreStackEntries, file) {
  29391. return ignoreStackEntries.some((p) => file.match(p));
  29392. }
  29393. function parseFFOrSafariStackTrace(stack) {
  29394. return stack.split("\n").map((line) => parseSingleFFOrSafariStack(line)).filter(notNullish);
  29395. }
  29396. function parseV8Stacktrace(stack) {
  29397. return stack.split("\n").map((line) => parseSingleV8Stack(line)).filter(notNullish);
  29398. }
  29399. function parseErrorStacktrace(e, options = {}) {
  29400. if (!e || isPrimitive(e)) return [];
  29401. if ("stacks" in e && e.stacks) return e.stacks;
  29402. const stackStr = e.stack || "";
  29403. let stackFrames = typeof stackStr === "string" ? parseStacktrace(stackStr, options) : [];
  29404. if (!stackFrames.length) {
  29405. const e_ = e;
  29406. if (e_.fileName != null && e_.lineNumber != null && e_.columnNumber != null) stackFrames = parseStacktrace(`${e_.fileName}:${e_.lineNumber}:${e_.columnNumber}`, options);
  29407. if (e_.sourceURL != null && e_.line != null && e_._column != null) stackFrames = parseStacktrace(`${e_.sourceURL}:${e_.line}:${e_.column}`, options);
  29408. }
  29409. if (options.frameFilter) stackFrames = stackFrames.filter((f) => options.frameFilter(e, f) !== false);
  29410. e.stacks = stackFrames;
  29411. return stackFrames;
  29412. }
  29413. var DecodedMap = class {
  29414. _encoded;
  29415. _decoded;
  29416. _decodedMemo;
  29417. url;
  29418. version;
  29419. names = [];
  29420. resolvedSources;
  29421. constructor(map, from) {
  29422. this.map = map;
  29423. const { mappings, names, sources } = map;
  29424. this.version = map.version;
  29425. this.names = names || [];
  29426. this._encoded = mappings || "";
  29427. this._decodedMemo = memoizedState();
  29428. this.url = from;
  29429. this.resolvedSources = (sources || []).map((s) => resolve$2(from, "..", s || ""));
  29430. }
  29431. };
  29432. function memoizedState() {
  29433. return {
  29434. lastKey: -1,
  29435. lastNeedle: -1,
  29436. lastIndex: -1
  29437. };
  29438. }
  29439. function getOriginalPosition(map, needle) {
  29440. const result = originalPositionFor(map, needle);
  29441. if (result.column == null) return null;
  29442. return result;
  29443. }
  29444. //#endregion
  29445. //#region src/node/plugins/forwardConsole.ts
  29446. function forwardConsolePlugin(pluginOpts) {
  29447. const sourceMapCache = /* @__PURE__ */ new Map();
  29448. return {
  29449. name: "vite:forward-console",
  29450. apply: "serve",
  29451. configureServer(server) {
  29452. for (const name of pluginOpts.environments) {
  29453. const environment = server.environments[name];
  29454. environment.hot.on("vite:forward-console", (payload) => {
  29455. if (payload.type === "error" || payload.type === "unhandled-rejection") {
  29456. const output = formatError(payload, environment, sourceMapCache);
  29457. environment.config.logger.error(output, { timestamp: true });
  29458. } else {
  29459. const output = import_picocolors.default.dim(`[console.${payload.data.level}] `) + payload.data.message;
  29460. if (payload.data.level === "error") environment.config.logger.error(output, { timestamp: true });
  29461. else if (payload.data.level === "warn") environment.config.logger.warn(output, { timestamp: true });
  29462. else environment.config.logger.info(output, { timestamp: true });
  29463. }
  29464. });
  29465. }
  29466. }
  29467. };
  29468. }
  29469. function formatError(payload, environment, sourceMapCache) {
  29470. const error = payload.data;
  29471. const stacks = parseErrorStacktrace(error, {
  29472. getUrlId(id) {
  29473. const moduleGraph = environment.moduleGraph;
  29474. if (moduleGraph.getModuleById(id)) return id;
  29475. const resolvedPath = normalizePath(path.resolve(environment.config.root, id.slice(1)));
  29476. if (moduleGraph.getModuleById(resolvedPath)) return resolvedPath;
  29477. const files = moduleGraph.getModulesByFile(resolvedPath);
  29478. if (files && files.size) return files.values().next().value.id;
  29479. return id;
  29480. },
  29481. getSourceMap(id) {
  29482. if (sourceMapCache.has(id)) return sourceMapCache.get(id);
  29483. const result = environment.moduleGraph.getModuleById(id)?.transformResult;
  29484. if (result && !result.map) try {
  29485. const filePath = id.split("?")[0];
  29486. const extracted = extractSourcemapFromFile(result.code, filePath);
  29487. sourceMapCache.set(id, extracted?.map);
  29488. return extracted?.map;
  29489. } catch {
  29490. sourceMapCache.set(id, null);
  29491. return null;
  29492. }
  29493. sourceMapCache.set(id, result?.map);
  29494. return result?.map;
  29495. },
  29496. ignoreStackEntries: []
  29497. });
  29498. const nearest = stacks.find((stack) => {
  29499. return [...environment.moduleGraph.getModulesByFile(stack.file) || []].some((m) => m.transformResult) && fs.existsSync(stack.file);
  29500. });
  29501. let output = "";
  29502. output += import_picocolors.default.red(`${payload.type === "unhandled-rejection" ? "[Unhandled rejection]" : "[Unhandled error]"} ${import_picocolors.default.bold(error.name)}: ${error.message}\n`);
  29503. for (const stack of stacks) {
  29504. const file = normalizePath(path.relative(environment.config.root, stack.file));
  29505. output += ` > ${[stack.method, `${file}:${stack.line}:${stack.column}`].filter(Boolean).join(" ")}\n`;
  29506. if (stack === nearest) {
  29507. const code = fs.readFileSync(stack.file, "utf-8");
  29508. output += generateCodeFrame(code, stack).replace(/^/gm, " ");
  29509. output += "\n";
  29510. }
  29511. }
  29512. return output;
  29513. }
  29514. //#endregion
  29515. //#region src/node/plugins/esbuildBannerFooterCompatPlugin.ts
  29516. /**
  29517. * This plugin supports `esbuild.banner` and `esbuild.footer` options.
  29518. * esbuild supported these options and Vite exposed them.
  29519. * But this should be done by plugin with transform hook.
  29520. * This plugin makes these options work in rolldown-vite as a backward compat for now.
  29521. */
  29522. function esbuildBannerFooterCompatPlugin(config) {
  29523. const options = config.esbuild;
  29524. if (!options) return;
  29525. const { include, exclude, banner, footer } = options;
  29526. if (!banner && !footer) return;
  29527. const filter = createFilter$1(include || /\.(m?ts|[jt]sx)$/, exclude || /\.js$/);
  29528. return {
  29529. name: "vite:esbuild-banner-footer-compat",
  29530. transform(code, id) {
  29531. if (filter(id) || filter(cleanUrl(id))) {
  29532. if (!(this.environment.mode === "dev" || this.environment.mode === "build" && this.environment.config.build.sourcemap)) {
  29533. if (banner) code = `${banner}\n${code}`;
  29534. if (footer) code = `${code}\n${footer}`;
  29535. return code;
  29536. }
  29537. let s;
  29538. const str = () => s || (s = new MagicString(code));
  29539. if (banner) str().prepend(`${banner}\n`);
  29540. if (footer) str().append(`${footer}\n`);
  29541. if (s) return {
  29542. code: s.toString(),
  29543. map: s.generateMap({ hires: "boundary" })
  29544. };
  29545. }
  29546. }
  29547. };
  29548. }
  29549. //#endregion
  29550. //#region src/node/plugins/index.ts
  29551. async function resolvePlugins(config, prePlugins, normalPlugins, postPlugins) {
  29552. const isBuild = config.command === "build";
  29553. const isBundled = config.isBundled;
  29554. const isWorker = config.isWorker;
  29555. const buildPlugins = isBundled ? await (await import("./build.js")).resolveBuildPlugins(config) : {
  29556. pre: [],
  29557. post: []
  29558. };
  29559. const { modulePreload } = config.build;
  29560. return [
  29561. !isBundled ? optimizedDepsPlugin() : null,
  29562. !isWorker ? watchPackageDataPlugin(config.packageCache) : null,
  29563. !isBundled ? preAliasPlugin(config) : null,
  29564. isBundled && !config.resolve.alias.some((v) => v.customResolver) ? viteAliasPlugin({ entries: config.resolve.alias.map((item) => {
  29565. return {
  29566. find: item.find,
  29567. replacement: item.replacement
  29568. };
  29569. }) }) : alias$1({
  29570. entries: config.resolve.alias,
  29571. customResolver: viteAliasCustomResolver
  29572. }),
  29573. ...prePlugins,
  29574. modulePreload !== false && modulePreload.polyfill ? modulePreloadPolyfillPlugin(config) : null,
  29575. ...oxcResolvePlugin({
  29576. root: config.root,
  29577. isProduction: config.isProduction,
  29578. isBuild,
  29579. packageCache: config.packageCache,
  29580. asSrc: true,
  29581. optimizeDeps: true,
  29582. externalize: true,
  29583. legacyInconsistentCjsInterop: config.legacy?.inconsistentCjsInterop
  29584. }, isWorker ? {
  29585. ...config,
  29586. consumer: "client",
  29587. optimizeDepsPluginNames: []
  29588. } : void 0),
  29589. htmlInlineProxyPlugin(config),
  29590. cssPlugin(config),
  29591. esbuildBannerFooterCompatPlugin(config),
  29592. config.oxc !== false ? oxcPlugin(config) : null,
  29593. viteJsonPlugin({
  29594. ...config.json,
  29595. minify: isBuild
  29596. }),
  29597. wasmHelperPlugin(),
  29598. webWorkerPlugin(config),
  29599. assetPlugin(config),
  29600. config.server.forwardConsole.enabled && forwardConsolePlugin({ environments: ["client"] }),
  29601. ...normalPlugins,
  29602. viteWasmFallbackPlugin(),
  29603. definePlugin(config),
  29604. cssPostPlugin(config),
  29605. isBundled && buildHtmlPlugin(config),
  29606. workerImportMetaUrlPlugin(config),
  29607. assetImportMetaUrlPlugin(config),
  29608. ...buildPlugins.pre,
  29609. dynamicImportVarsPlugin(config),
  29610. importGlobPlugin(config),
  29611. ...postPlugins,
  29612. ...buildPlugins.post,
  29613. ...isBundled ? [] : [
  29614. clientInjectionsPlugin(config),
  29615. cssAnalysisPlugin(config),
  29616. importAnalysisPlugin(config)
  29617. ]
  29618. ].filter(Boolean);
  29619. }
  29620. function createPluginHookUtils(plugins) {
  29621. const sortedPluginsCache = /* @__PURE__ */ new Map();
  29622. function getSortedPlugins(hookName) {
  29623. if (sortedPluginsCache.has(hookName)) return sortedPluginsCache.get(hookName);
  29624. const sorted = getSortedPluginsByHook(hookName, plugins);
  29625. sortedPluginsCache.set(hookName, sorted);
  29626. return sorted;
  29627. }
  29628. function getSortedPluginHooks(hookName) {
  29629. return getSortedPlugins(hookName).map((p) => getHookHandler(p[hookName])).filter(Boolean);
  29630. }
  29631. return {
  29632. getSortedPlugins,
  29633. getSortedPluginHooks
  29634. };
  29635. }
  29636. function getSortedPluginsByHook(hookName, plugins) {
  29637. const sortedPlugins = [];
  29638. let pre = 0, normal = 0, post = 0;
  29639. for (const plugin of plugins) {
  29640. const hook = plugin[hookName];
  29641. if (hook) {
  29642. if (typeof hook === "object") {
  29643. if (hook.order === "pre") {
  29644. sortedPlugins.splice(pre++, 0, plugin);
  29645. continue;
  29646. }
  29647. if (hook.order === "post") {
  29648. sortedPlugins.splice(pre + normal + post++, 0, plugin);
  29649. continue;
  29650. }
  29651. }
  29652. sortedPlugins.splice(pre + normal++, 0, plugin);
  29653. }
  29654. }
  29655. return sortedPlugins;
  29656. }
  29657. function getHookHandler(hook) {
  29658. return typeof hook === "object" ? hook.handler : hook;
  29659. }
  29660. const filterForPlugin = /* @__PURE__ */ new WeakMap();
  29661. function getCachedFilterForPlugin(plugin, hookName) {
  29662. let filters = filterForPlugin.get(plugin);
  29663. if (filters && hookName in filters) return filters[hookName];
  29664. if (!filters) {
  29665. filters = {};
  29666. filterForPlugin.set(plugin, filters);
  29667. }
  29668. let filter;
  29669. switch (hookName) {
  29670. case "resolveId": {
  29671. const rawFilter = extractFilter(plugin.resolveId)?.id;
  29672. filters.resolveId = createIdFilter(rawFilter);
  29673. filter = filters.resolveId;
  29674. break;
  29675. }
  29676. case "load": {
  29677. const rawFilter = extractFilter(plugin.load)?.id;
  29678. filters.load = createIdFilter(rawFilter);
  29679. filter = filters.load;
  29680. break;
  29681. }
  29682. case "transform": {
  29683. const rawFilters = extractFilter(plugin.transform);
  29684. filters.transform = createFilterForTransform(rawFilters?.id, rawFilters?.code, rawFilters?.moduleType);
  29685. filter = filters.transform;
  29686. break;
  29687. }
  29688. }
  29689. return filter;
  29690. }
  29691. function extractFilter(hook) {
  29692. return hook && "filter" in hook && hook.filter ? hook.filter : void 0;
  29693. }
  29694. const viteAliasCustomResolver = async function(id, importer, options) {
  29695. return await this.resolve(id, importer, options) || {
  29696. id,
  29697. meta: { "vite:alias": { noResolved: true } }
  29698. };
  29699. };
  29700. //#endregion
  29701. //#region src/node/server/pluginContainer.ts
  29702. /**
  29703. * This file is refactored into TypeScript based on
  29704. * https://github.com/preactjs/wmr/blob/main/packages/wmr/src/lib/rollup-plugin-container.js
  29705. */
  29706. /**
  29707. https://github.com/preactjs/wmr/blob/master/LICENSE
  29708. MIT License
  29709. Copyright (c) 2020 The Preact Authors
  29710. Permission is hereby granted, free of charge, to any person obtaining a copy
  29711. of this software and associated documentation files (the "Software"), to deal
  29712. in the Software without restriction, including without limitation the rights
  29713. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  29714. copies of the Software, and to permit persons to whom the Software is
  29715. furnished to do so, subject to the following conditions:
  29716. The above copyright notice and this permission notice shall be included in all
  29717. copies or substantial portions of the Software.
  29718. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  29719. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  29720. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  29721. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  29722. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  29723. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  29724. SOFTWARE.
  29725. */
  29726. const EMPTY_OBJECT = Object.freeze({});
  29727. const debugSourcemapCombineFilter = process.env.DEBUG_VITE_SOURCEMAP_COMBINE_FILTER;
  29728. const debugSourcemapCombine = createDebugger("vite:sourcemap-combine", { onlyWhenFocused: true });
  29729. const debugResolve = createDebugger("vite:resolve");
  29730. const debugPluginResolve = createDebugger("vite:plugin-resolve", { onlyWhenFocused: "vite:plugin" });
  29731. const debugPluginTransform = createDebugger("vite:plugin-transform", { onlyWhenFocused: "vite:plugin" });
  29732. const debugPluginContainerContext = createDebugger("vite:plugin-container-context");
  29733. const ERR_CLOSED_SERVER = "ERR_CLOSED_SERVER";
  29734. function throwClosedServerError() {
  29735. const err = /* @__PURE__ */ new Error("The server is being restarted or closed. Request is outdated");
  29736. err.code = ERR_CLOSED_SERVER;
  29737. throw err;
  29738. }
  29739. /**
  29740. * Create a plugin container with a set of plugins. We pass them as a parameter
  29741. * instead of using environment.plugins to allow the creation of different
  29742. * pipelines working with the same environment (used for createIdResolver).
  29743. */
  29744. async function createEnvironmentPluginContainer(environment, plugins, watcher, autoStart = true) {
  29745. const container = new EnvironmentPluginContainer(environment, plugins, watcher, autoStart);
  29746. await container.resolveRollupOptions();
  29747. return container;
  29748. }
  29749. var EnvironmentPluginContainer = class {
  29750. _pluginContextMap = /* @__PURE__ */ new Map();
  29751. _resolvedRollupOptions;
  29752. _processesing = /* @__PURE__ */ new Set();
  29753. _seenResolves = {};
  29754. _moduleNodeToLoadAddedImports = /* @__PURE__ */ new WeakMap();
  29755. getSortedPluginHooks;
  29756. getSortedPlugins;
  29757. moduleGraph;
  29758. watchFiles = /* @__PURE__ */ new Set();
  29759. minimalContext;
  29760. _started = false;
  29761. _buildStartPromise;
  29762. _closed = false;
  29763. /**
  29764. * @internal use `createEnvironmentPluginContainer` instead
  29765. */
  29766. constructor(environment, plugins, watcher, autoStart = true) {
  29767. this.environment = environment;
  29768. this.plugins = plugins;
  29769. this.watcher = watcher;
  29770. this._started = !autoStart;
  29771. this.minimalContext = new MinimalPluginContext({
  29772. ...basePluginContextMeta,
  29773. watchMode: true
  29774. }, environment);
  29775. const utils = createPluginHookUtils(plugins);
  29776. this.getSortedPlugins = utils.getSortedPlugins;
  29777. this.getSortedPluginHooks = utils.getSortedPluginHooks;
  29778. this.moduleGraph = environment.mode === "dev" ? environment.moduleGraph : void 0;
  29779. }
  29780. _updateModuleLoadAddedImports(id, addedImports) {
  29781. const module = this.moduleGraph?.getModuleById(id);
  29782. if (module) this._moduleNodeToLoadAddedImports.set(module, addedImports);
  29783. }
  29784. _getAddedImports(id) {
  29785. const module = this.moduleGraph?.getModuleById(id);
  29786. return module ? this._moduleNodeToLoadAddedImports.get(module) || null : null;
  29787. }
  29788. getModuleInfo(id) {
  29789. const module = this.moduleGraph?.getModuleById(id);
  29790. if (!module) return null;
  29791. if (!module.info) module.info = new Proxy({
  29792. id,
  29793. meta: module.meta || EMPTY_OBJECT
  29794. }, { get(info, key) {
  29795. if (key in info) return info[key];
  29796. if (key === "then") return;
  29797. throw Error(`[vite] The "${key}" property of ModuleInfo is not supported.`);
  29798. } });
  29799. return module.info ?? null;
  29800. }
  29801. handleHookPromise(maybePromise) {
  29802. if (!maybePromise?.then) return maybePromise;
  29803. const promise = maybePromise;
  29804. this._processesing.add(promise);
  29805. return promise.finally(() => this._processesing.delete(promise));
  29806. }
  29807. get options() {
  29808. return this._resolvedRollupOptions;
  29809. }
  29810. async resolveRollupOptions() {
  29811. if (!this._resolvedRollupOptions) {
  29812. let options = this.environment.config.build.rollupOptions;
  29813. for (const optionsHook of this.getSortedPluginHooks("options")) {
  29814. if (this._closed) throwClosedServerError();
  29815. options = await this.handleHookPromise(optionsHook.call(this.minimalContext, options)) || options;
  29816. }
  29817. this._resolvedRollupOptions = options;
  29818. }
  29819. return this._resolvedRollupOptions;
  29820. }
  29821. _getPluginContext(plugin) {
  29822. if (!this._pluginContextMap.has(plugin)) this._pluginContextMap.set(plugin, new PluginContext(plugin, this));
  29823. return this._pluginContextMap.get(plugin);
  29824. }
  29825. async hookParallel(hookName, context, args, condition) {
  29826. const parallelPromises = [];
  29827. for (const plugin of this.getSortedPlugins(hookName)) {
  29828. if (condition && !condition(plugin)) continue;
  29829. const hook = plugin[hookName];
  29830. const handler = getHookHandler(hook);
  29831. if (hook.sequential) {
  29832. await Promise.all(parallelPromises);
  29833. parallelPromises.length = 0;
  29834. await handler.apply(context(plugin), args(plugin));
  29835. } else parallelPromises.push(handler.apply(context(plugin), args(plugin)));
  29836. }
  29837. await Promise.all(parallelPromises);
  29838. }
  29839. async buildStart(_options) {
  29840. if (this._started) {
  29841. if (this._buildStartPromise) await this._buildStartPromise;
  29842. return;
  29843. }
  29844. this._started = true;
  29845. const config = this.environment.getTopLevelConfig();
  29846. this._buildStartPromise = this.handleHookPromise(this.hookParallel("buildStart", (plugin) => this._getPluginContext(plugin), () => [this.options], (plugin) => this.environment.name === "client" || config.server.perEnvironmentStartEndDuringDev || plugin.perEnvironmentStartEndDuringDev));
  29847. await this._buildStartPromise;
  29848. this._buildStartPromise = void 0;
  29849. }
  29850. async resolveId(rawId, importer = join(this.environment.config.root, "index.html"), options) {
  29851. if (!this._started) {
  29852. this.buildStart();
  29853. await this._buildStartPromise;
  29854. }
  29855. const skip = options?.skip;
  29856. const skipCalls = options?.skipCalls;
  29857. const scan = !!options?.scan;
  29858. const ssr = this.environment.config.consumer === "server";
  29859. const ctx = new ResolveIdContext(this, skip, skipCalls, scan);
  29860. const topLevelConfig = this.environment.getTopLevelConfig();
  29861. const mergedSkip = new Set(skip);
  29862. for (const call of skipCalls ?? []) if (call.called || call.id === rawId && call.importer === importer) mergedSkip.add(call.plugin);
  29863. const resolveStart = debugResolve ? performance$1.now() : 0;
  29864. let id = null;
  29865. const partial = {};
  29866. for (const plugin of this.getSortedPlugins("resolveId")) {
  29867. if (this._closed && this.environment.config.dev.recoverable) throwClosedServerError();
  29868. if (mergedSkip?.has(plugin)) continue;
  29869. const filter = getCachedFilterForPlugin(plugin, "resolveId");
  29870. if (filter && !filter(rawId)) continue;
  29871. ctx._plugin = plugin;
  29872. const normalizedOptions = {
  29873. kind: options?.kind,
  29874. attributes: options?.attributes ?? {},
  29875. custom: options?.custom,
  29876. isEntry: !!options?.isEntry,
  29877. ssr,
  29878. scan
  29879. };
  29880. if (isFutureDeprecationEnabled(topLevelConfig, "removePluginHookSsrArgument")) {
  29881. let ssrTemp = ssr;
  29882. Object.defineProperty(normalizedOptions, "ssr", {
  29883. get() {
  29884. warnFutureDeprecation(topLevelConfig, "removePluginHookSsrArgument", `Used in plugin "${plugin.name}".`);
  29885. return ssrTemp;
  29886. },
  29887. set(v) {
  29888. ssrTemp = v;
  29889. }
  29890. });
  29891. }
  29892. const pluginResolveStart = debugPluginResolve ? performance$1.now() : 0;
  29893. const handler = getHookHandler(plugin.resolveId);
  29894. const result = await this.handleHookPromise(handler.call(ctx, rawId, importer, normalizedOptions));
  29895. if (!result) continue;
  29896. if (typeof result === "string") id = result;
  29897. else {
  29898. id = result.id;
  29899. Object.assign(partial, result);
  29900. }
  29901. debugPluginResolve?.(timeFrom(pluginResolveStart), plugin.name, prettifyUrl(id, this.environment.config.root));
  29902. break;
  29903. }
  29904. if (debugResolve && rawId !== id && !rawId.startsWith(FS_PREFIX)) {
  29905. const key = rawId + id;
  29906. if (!this._seenResolves[key]) {
  29907. this._seenResolves[key] = true;
  29908. debugResolve(`${timeFrom(resolveStart)} ${import_picocolors.default.cyan(rawId)} -> ${import_picocolors.default.dim(id)}`);
  29909. }
  29910. }
  29911. if (id) {
  29912. partial.id = isExternalUrl(id) || id[0] === "\0" ? id : normalizePath(id);
  29913. return partial;
  29914. } else return null;
  29915. }
  29916. async load(id) {
  29917. let ssr = this.environment.config.consumer === "server";
  29918. const topLevelConfig = this.environment.getTopLevelConfig();
  29919. const options = { ssr };
  29920. const ctx = new LoadPluginContext(this);
  29921. for (const plugin of this.getSortedPlugins("load")) {
  29922. if (this._closed && this.environment.config.dev.recoverable) throwClosedServerError();
  29923. const filter = getCachedFilterForPlugin(plugin, "load");
  29924. if (filter && !filter(id)) continue;
  29925. ctx._plugin = plugin;
  29926. if (isFutureDeprecationEnabled(topLevelConfig, "removePluginHookSsrArgument")) Object.defineProperty(options, "ssr", {
  29927. get() {
  29928. warnFutureDeprecation(topLevelConfig, "removePluginHookSsrArgument", `Used in plugin "${plugin.name}".`);
  29929. return ssr;
  29930. },
  29931. set(v) {
  29932. ssr = v;
  29933. }
  29934. });
  29935. const handler = getHookHandler(plugin.load);
  29936. const result = await this.handleHookPromise(handler.call(ctx, id, options));
  29937. if (result != null) {
  29938. if (isObject$1(result)) ctx._updateModuleInfo(id, result);
  29939. this._updateModuleLoadAddedImports(id, ctx._addedImports);
  29940. return result;
  29941. }
  29942. }
  29943. this._updateModuleLoadAddedImports(id, ctx._addedImports);
  29944. return null;
  29945. }
  29946. async transform(code, id, options) {
  29947. let ssr = this.environment.config.consumer === "server";
  29948. const topLevelConfig = this.environment.getTopLevelConfig();
  29949. const optionsWithSSR = options ? {
  29950. ...options,
  29951. ssr,
  29952. moduleType: options.moduleType ?? "js"
  29953. } : {
  29954. ssr,
  29955. moduleType: "js"
  29956. };
  29957. const inMap = options?.inMap;
  29958. const ctx = new TransformPluginContext(this, id, code, inMap);
  29959. ctx._addedImports = this._getAddedImports(id);
  29960. for (const plugin of this.getSortedPlugins("transform")) {
  29961. if (this._closed && this.environment.config.dev.recoverable) throwClosedServerError();
  29962. const filter = getCachedFilterForPlugin(plugin, "transform");
  29963. if (filter && !filter(id, code, optionsWithSSR.moduleType)) continue;
  29964. if (isFutureDeprecationEnabled(topLevelConfig, "removePluginHookSsrArgument")) Object.defineProperty(optionsWithSSR, "ssr", {
  29965. get() {
  29966. warnFutureDeprecation(topLevelConfig, "removePluginHookSsrArgument", `Used in plugin "${plugin.name}".`);
  29967. return ssr;
  29968. },
  29969. set(v) {
  29970. ssr = v;
  29971. }
  29972. });
  29973. ctx._updateActiveInfo(plugin, id, code);
  29974. const start = debugPluginTransform ? performance$1.now() : 0;
  29975. let result;
  29976. const handler = getHookHandler(plugin.transform);
  29977. try {
  29978. result = await this.handleHookPromise(handler.call(ctx, code, id, optionsWithSSR));
  29979. } catch (e) {
  29980. ctx.error(e);
  29981. }
  29982. if (!result) continue;
  29983. debugPluginTransform?.(timeFrom(start), plugin.name, prettifyUrl(id, this.environment.config.root));
  29984. if (isObject$1(result)) {
  29985. if (result.code !== void 0) {
  29986. code = result.code;
  29987. if (result.map) {
  29988. if (debugSourcemapCombine) result.map.name = plugin.name;
  29989. ctx.sourcemapChain.push(result.map);
  29990. }
  29991. }
  29992. if (result.moduleType !== void 0) optionsWithSSR.moduleType = result.moduleType;
  29993. ctx._updateModuleInfo(id, result);
  29994. } else code = result;
  29995. }
  29996. return {
  29997. code,
  29998. map: ctx._getCombinedSourcemap(),
  29999. moduleType: optionsWithSSR.moduleType
  30000. };
  30001. }
  30002. async watchChange(id, change) {
  30003. const config = this.environment.getTopLevelConfig();
  30004. await this.hookParallel("watchChange", (plugin) => this._getPluginContext(plugin), () => [id, change], (plugin) => this.environment.name === "client" || config.server.perEnvironmentWatchChangeDuringDev || plugin.perEnvironmentWatchChangeDuringDev);
  30005. }
  30006. async close() {
  30007. if (this._closed) return;
  30008. this._closed = true;
  30009. await Promise.allSettled(Array.from(this._processesing));
  30010. const config = this.environment.getTopLevelConfig();
  30011. await this.hookParallel("buildEnd", (plugin) => this._getPluginContext(plugin), () => [], (plugin) => this.environment.name === "client" || config.server.perEnvironmentStartEndDuringDev || plugin.perEnvironmentStartEndDuringDev);
  30012. await this.hookParallel("closeBundle", (plugin) => this._getPluginContext(plugin), () => []);
  30013. }
  30014. };
  30015. const basePluginContextMeta = {
  30016. viteVersion: VERSION,
  30017. rollupVersion,
  30018. rolldownVersion
  30019. };
  30020. var BasicMinimalPluginContext = class {
  30021. constructor(meta, _logger) {
  30022. this.meta = meta;
  30023. this._logger = _logger;
  30024. }
  30025. get pluginName() {
  30026. return "";
  30027. }
  30028. debug(rawLog) {
  30029. const log = this._normalizeRawLog(rawLog);
  30030. const msg = buildErrorMessage(log, [`debug: ${log.message}`], false);
  30031. debugPluginContainerContext?.(msg);
  30032. }
  30033. info(rawLog) {
  30034. const log = this._normalizeRawLog(rawLog);
  30035. const msg = buildErrorMessage(log, [`info: ${log.message}`], false);
  30036. this._logger.info(msg, {
  30037. clear: true,
  30038. timestamp: true
  30039. });
  30040. }
  30041. warn(rawLog) {
  30042. const log = this._normalizeRawLog(rawLog);
  30043. const msg = buildErrorMessage(log, [import_picocolors.default.yellow(`warning: ${log.message}`)], false);
  30044. this._logger.warn(msg, {
  30045. clear: true,
  30046. timestamp: true
  30047. });
  30048. }
  30049. error(e) {
  30050. throw typeof e === "string" ? new Error(e) : e;
  30051. }
  30052. _normalizeRawLog(rawLog) {
  30053. const logValue = typeof rawLog === "function" ? rawLog() : rawLog;
  30054. return typeof logValue === "string" ? new Error(logValue) : logValue;
  30055. }
  30056. };
  30057. var MinimalPluginContext = class extends BasicMinimalPluginContext {
  30058. environment;
  30059. constructor(meta, environment) {
  30060. super(meta, environment.logger);
  30061. this.environment = environment;
  30062. }
  30063. };
  30064. const fsModule = {
  30065. appendFile: fsp.appendFile,
  30066. copyFile: fsp.copyFile,
  30067. mkdir: fsp.mkdir,
  30068. mkdtemp: fsp.mkdtemp,
  30069. readdir: fsp.readdir,
  30070. readFile: fsp.readFile,
  30071. realpath: fsp.realpath,
  30072. rename: fsp.rename,
  30073. rmdir: fsp.rmdir,
  30074. stat: fsp.stat,
  30075. lstat: fsp.lstat,
  30076. unlink: fsp.unlink,
  30077. writeFile: fsp.writeFile
  30078. };
  30079. var PluginContext = class extends MinimalPluginContext {
  30080. ssr = false;
  30081. _scan = false;
  30082. _activeId = null;
  30083. _activeCode = null;
  30084. _resolveSkips;
  30085. _resolveSkipCalls;
  30086. get pluginName() {
  30087. return this._plugin.name;
  30088. }
  30089. constructor(_plugin, _container) {
  30090. super(_container.minimalContext.meta, _container.environment);
  30091. this._plugin = _plugin;
  30092. this._container = _container;
  30093. }
  30094. fs = fsModule;
  30095. parse(code, opts) {
  30096. return parseAst(code, opts);
  30097. }
  30098. async resolve(id, importer, options) {
  30099. let skipCalls;
  30100. if (options?.skipSelf === false) skipCalls = this._resolveSkipCalls;
  30101. else if (this._resolveSkipCalls) {
  30102. const skipCallsTemp = [...this._resolveSkipCalls];
  30103. const sameCallIndex = this._resolveSkipCalls.findIndex((c) => c.id === id && c.importer === importer && c.plugin === this._plugin);
  30104. if (sameCallIndex !== -1) skipCallsTemp[sameCallIndex] = {
  30105. ...skipCallsTemp[sameCallIndex],
  30106. called: true
  30107. };
  30108. else skipCallsTemp.push({
  30109. id,
  30110. importer,
  30111. plugin: this._plugin
  30112. });
  30113. skipCalls = skipCallsTemp;
  30114. } else skipCalls = [{
  30115. id,
  30116. importer,
  30117. plugin: this._plugin
  30118. }];
  30119. let out = await this._container.resolveId(id, importer, {
  30120. attributes: options?.attributes,
  30121. custom: options?.custom,
  30122. isEntry: !!options?.isEntry,
  30123. skip: this._resolveSkips,
  30124. skipCalls,
  30125. scan: this._scan
  30126. });
  30127. if (typeof out === "string") out = { id: out };
  30128. return out;
  30129. }
  30130. async load(options) {
  30131. await this._container.moduleGraph?.ensureEntryFromUrl(unwrapId(options.id));
  30132. this._updateModuleInfo(options.id, options);
  30133. const loadResult = await this._container.load(options.id);
  30134. const code = typeof loadResult === "object" ? loadResult?.code : loadResult;
  30135. if (code != null) await this._container.transform(code, options.id);
  30136. const moduleInfo = this.getModuleInfo(options.id);
  30137. if (!moduleInfo) throw Error(`Failed to load module with id ${options.id}`);
  30138. return moduleInfo;
  30139. }
  30140. getModuleInfo(id) {
  30141. return this._container.getModuleInfo(id);
  30142. }
  30143. _updateModuleInfo(id, { meta }) {
  30144. if (meta) {
  30145. const moduleInfo = this.getModuleInfo(id);
  30146. if (moduleInfo) moduleInfo.meta = {
  30147. ...moduleInfo.meta,
  30148. ...meta
  30149. };
  30150. }
  30151. }
  30152. getModuleIds() {
  30153. return this._container.moduleGraph ? this._container.moduleGraph.idToModuleMap.keys() : Array.prototype[Symbol.iterator]();
  30154. }
  30155. addWatchFile(id) {
  30156. this._container.watchFiles.add(id);
  30157. if (this._container.watcher) ensureWatchedFile(this._container.watcher, id, this.environment.config.root);
  30158. }
  30159. getWatchFiles() {
  30160. return [...this._container.watchFiles];
  30161. }
  30162. emitFile(_assetOrFile) {
  30163. this._warnIncompatibleMethod(`emitFile`);
  30164. return "";
  30165. }
  30166. setAssetSource() {
  30167. this._warnIncompatibleMethod(`setAssetSource`);
  30168. }
  30169. getFileName() {
  30170. this._warnIncompatibleMethod(`getFileName`);
  30171. return "";
  30172. }
  30173. debug(log) {
  30174. const err = this._formatLog(typeof log === "function" ? log() : log);
  30175. super.debug(err);
  30176. }
  30177. info(log) {
  30178. const err = this._formatLog(typeof log === "function" ? log() : log);
  30179. super.info(err);
  30180. }
  30181. warn(log, position) {
  30182. const err = this._formatLog(typeof log === "function" ? log() : log, position);
  30183. super.warn(err);
  30184. }
  30185. error(e, position) {
  30186. throw this._formatLog(e, position);
  30187. }
  30188. _formatLog(e, position) {
  30189. const err = typeof e === "string" ? new Error(e) : e;
  30190. if (err.pluginCode) return err;
  30191. err.plugin = this._plugin.name;
  30192. if (this._activeId && !err.id) err.id = this._activeId;
  30193. if (this._activeCode) {
  30194. err.pluginCode = this._activeCode;
  30195. const pos = position ?? err.pos ?? err.position;
  30196. if (pos != null) {
  30197. let errLocation;
  30198. try {
  30199. errLocation = numberToPos(this._activeCode, pos);
  30200. } catch (err2) {
  30201. this.environment.logger.error(import_picocolors.default.red(`Error in error handler:\n${err2.stack || err2.message}\n`), { error: err2 });
  30202. throw err;
  30203. }
  30204. err.loc = err.loc || {
  30205. file: err.id,
  30206. ...errLocation
  30207. };
  30208. err.frame = err.frame || generateCodeFrame(this._activeCode, pos);
  30209. } else if (err.loc) {
  30210. if (!err.frame) {
  30211. let code = this._activeCode;
  30212. if (err.loc.file) {
  30213. err.id = normalizePath(err.loc.file);
  30214. try {
  30215. code = fs.readFileSync(err.loc.file, "utf-8");
  30216. } catch {}
  30217. }
  30218. err.frame = generateCodeFrame(code, err.loc);
  30219. }
  30220. } else if (err.line && err.column) {
  30221. err.loc = {
  30222. file: err.id,
  30223. line: err.line,
  30224. column: err.column
  30225. };
  30226. err.frame = err.frame || generateCodeFrame(this._activeCode, err.loc);
  30227. }
  30228. if (this instanceof TransformPluginContext && typeof err.loc?.line === "number" && typeof err.loc.column === "number") {
  30229. const rawSourceMap = this._getCombinedSourcemap();
  30230. if (rawSourceMap && "version" in rawSourceMap) {
  30231. const { source, line, column } = originalPositionFor$2(new TraceMap(rawSourceMap), {
  30232. line: Number(err.loc.line),
  30233. column: Number(err.loc.column)
  30234. });
  30235. if (source) err.loc = {
  30236. file: source,
  30237. line,
  30238. column
  30239. };
  30240. }
  30241. }
  30242. } else if (err.loc) {
  30243. if (!err.frame) {
  30244. let code = err.pluginCode;
  30245. if (err.loc.file) {
  30246. err.id = normalizePath(err.loc.file);
  30247. if (!code) try {
  30248. code = fs.readFileSync(err.loc.file, "utf-8");
  30249. } catch {}
  30250. }
  30251. if (code) err.frame = generateCodeFrame(`${code}`, err.loc);
  30252. }
  30253. }
  30254. if (typeof err.loc?.column !== "number" && typeof err.loc?.line !== "number" && !err.loc?.file) delete err.loc;
  30255. return err;
  30256. }
  30257. _warnIncompatibleMethod(method) {
  30258. 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.`));
  30259. }
  30260. };
  30261. var ResolveIdContext = class extends PluginContext {
  30262. constructor(container, skip, skipCalls, scan) {
  30263. super(null, container);
  30264. this._resolveSkips = skip;
  30265. this._resolveSkipCalls = skipCalls;
  30266. this._scan = scan;
  30267. }
  30268. };
  30269. var LoadPluginContext = class extends PluginContext {
  30270. _addedImports = null;
  30271. constructor(container) {
  30272. super(null, container);
  30273. }
  30274. addWatchFile(id) {
  30275. if (!this._addedImports) this._addedImports = /* @__PURE__ */ new Set();
  30276. this._addedImports.add(id);
  30277. super.addWatchFile(id);
  30278. }
  30279. };
  30280. var TransformPluginContext = class extends LoadPluginContext {
  30281. filename;
  30282. originalCode;
  30283. originalSourcemap = null;
  30284. sourcemapChain = [];
  30285. combinedMap = null;
  30286. constructor(container, id, code, inMap) {
  30287. super(container);
  30288. this.filename = id;
  30289. this.originalCode = code;
  30290. if (inMap) {
  30291. if (debugSourcemapCombine) inMap.name = "$inMap";
  30292. this.sourcemapChain.push(inMap);
  30293. }
  30294. }
  30295. _getCombinedSourcemap() {
  30296. if (debugSourcemapCombine && debugSourcemapCombineFilter && this.filename.includes(debugSourcemapCombineFilter)) {
  30297. debugSourcemapCombine("----------", this.filename);
  30298. debugSourcemapCombine(this.combinedMap);
  30299. debugSourcemapCombine(this.sourcemapChain);
  30300. debugSourcemapCombine("----------");
  30301. }
  30302. let combinedMap = this.combinedMap;
  30303. if (combinedMap && !("version" in combinedMap) && combinedMap.mappings === "") {
  30304. this.sourcemapChain.length = 0;
  30305. return combinedMap;
  30306. }
  30307. for (let m of this.sourcemapChain) {
  30308. if (typeof m === "string") m = JSON.parse(m);
  30309. if (!("version" in m)) {
  30310. if (m.mappings === "") {
  30311. combinedMap = { mappings: "" };
  30312. break;
  30313. }
  30314. combinedMap = null;
  30315. break;
  30316. }
  30317. if (!combinedMap) {
  30318. const sm = m;
  30319. if (sm.sources.length === 1 && !sm.sources[0]) combinedMap = {
  30320. ...sm,
  30321. sources: [this.filename],
  30322. sourcesContent: [this.originalCode]
  30323. };
  30324. else combinedMap = sm;
  30325. } else combinedMap = combineSourcemaps(cleanUrl(this.filename), [m, combinedMap]);
  30326. }
  30327. if (combinedMap !== this.combinedMap) {
  30328. this.combinedMap = combinedMap;
  30329. this.sourcemapChain.length = 0;
  30330. }
  30331. return this.combinedMap;
  30332. }
  30333. getCombinedSourcemap() {
  30334. const map = this._getCombinedSourcemap();
  30335. if (!map || !("version" in map) && map.mappings === "") return new MagicString(this.originalCode).generateMap({
  30336. includeContent: true,
  30337. hires: "boundary",
  30338. source: cleanUrl(this.filename)
  30339. });
  30340. return map;
  30341. }
  30342. _updateActiveInfo(plugin, id, code) {
  30343. this._plugin = plugin;
  30344. this._activeId = id;
  30345. this._activeCode = code;
  30346. }
  30347. };
  30348. var PluginContainer = class {
  30349. constructor(environments) {
  30350. this.environments = environments;
  30351. }
  30352. _getEnvironment(options) {
  30353. return options?.environment ? options.environment : this.environments[options?.ssr ? "ssr" : "client"];
  30354. }
  30355. _getPluginContainer(options) {
  30356. return this._getEnvironment(options).pluginContainer;
  30357. }
  30358. getModuleInfo(id) {
  30359. const clientModuleInfo = this.environments.client.pluginContainer.getModuleInfo(id);
  30360. const ssrModuleInfo = this.environments.ssr.pluginContainer.getModuleInfo(id);
  30361. if (clientModuleInfo == null && ssrModuleInfo == null) return null;
  30362. return new Proxy({}, { get: (_, key) => {
  30363. if (key === "meta") {
  30364. const meta = {};
  30365. if (ssrModuleInfo) Object.assign(meta, ssrModuleInfo.meta);
  30366. if (clientModuleInfo) Object.assign(meta, clientModuleInfo.meta);
  30367. return meta;
  30368. }
  30369. if (clientModuleInfo) {
  30370. if (key in clientModuleInfo) return clientModuleInfo[key];
  30371. }
  30372. if (ssrModuleInfo) {
  30373. if (key in ssrModuleInfo) return ssrModuleInfo[key];
  30374. }
  30375. } });
  30376. }
  30377. get options() {
  30378. return this.environments.client.pluginContainer.options;
  30379. }
  30380. async buildStart(_options) {
  30381. return this.environments.client.pluginContainer.buildStart(_options);
  30382. }
  30383. async watchChange(id, change) {
  30384. return this.environments.client.pluginContainer.watchChange(id, change);
  30385. }
  30386. async resolveId(rawId, importer, options) {
  30387. return this._getPluginContainer(options).resolveId(rawId, importer, options);
  30388. }
  30389. async load(id, options) {
  30390. return this._getPluginContainer(options).load(id);
  30391. }
  30392. async transform(code, id, options) {
  30393. return this._getPluginContainer(options).transform(code, id, options);
  30394. }
  30395. async close() {}
  30396. };
  30397. /**
  30398. * server.pluginContainer compatibility
  30399. *
  30400. * The default environment is in buildStart, buildEnd, watchChange, and closeBundle hooks,
  30401. * which are called once for all environments, or when no environment is passed in other hooks.
  30402. * The ssrEnvironment is needed for backward compatibility when the ssr flag is passed without
  30403. * an environment. The defaultEnvironment in the main pluginContainer in the server should be
  30404. * the client environment for backward compatibility.
  30405. **/
  30406. function createPluginContainer(environments) {
  30407. return new PluginContainer(environments);
  30408. }
  30409. //#endregion
  30410. //#region src/node/optimizer/scan.ts
  30411. var ScanEnvironment = class extends BaseEnvironment {
  30412. mode = "scan";
  30413. get pluginContainer() {
  30414. if (!this._pluginContainer) throw new Error(`${this.name} environment.pluginContainer called before initialized`);
  30415. return this._pluginContainer;
  30416. }
  30417. /**
  30418. * @internal
  30419. */
  30420. _pluginContainer;
  30421. async init() {
  30422. if (this._initiated) return;
  30423. this._initiated = true;
  30424. this._pluginContainer = await createEnvironmentPluginContainer(this, this.plugins, void 0, false);
  30425. }
  30426. };
  30427. function devToScanEnvironment(environment) {
  30428. return {
  30429. mode: "scan",
  30430. get name() {
  30431. return environment.name;
  30432. },
  30433. getTopLevelConfig() {
  30434. return environment.getTopLevelConfig();
  30435. },
  30436. get config() {
  30437. return environment.config;
  30438. },
  30439. get logger() {
  30440. return environment.logger;
  30441. },
  30442. get pluginContainer() {
  30443. return environment.pluginContainer;
  30444. },
  30445. get plugins() {
  30446. return environment.plugins;
  30447. }
  30448. };
  30449. }
  30450. const debug$3 = createDebugger("vite:deps");
  30451. const htmlTypesRE = /\.(?:html|vue|svelte|astro|imba)$/;
  30452. const importsRE = /(?<!\/\/.*)(?<=^|;|\*\/)\s*import(?!\s+type)(?:[\w*{}\n\r\t, ]+from)?\s*("[^"]+"|'[^']+')\s*(?=$|;|\/\/|\/\*)/gm;
  30453. function scanImports(environment) {
  30454. const start = performance$1.now();
  30455. const { config } = environment;
  30456. const scanContext = { cancelled: false };
  30457. async function cancel() {
  30458. scanContext.cancelled = true;
  30459. }
  30460. async function scan() {
  30461. const entries = await computeEntries(environment);
  30462. if (!entries.length) {
  30463. 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."));
  30464. return;
  30465. }
  30466. if (scanContext.cancelled) return;
  30467. debug$3?.(`Crawling dependencies using entries: ${entries.map((entry) => `\n ${import_picocolors.default.dim(entry)}`).join("")}`);
  30468. const deps = {};
  30469. const missing = {};
  30470. const context = await prepareRolldownScanner(environment, entries, deps, missing);
  30471. if (scanContext.cancelled) return;
  30472. try {
  30473. await context.build();
  30474. return {
  30475. deps: orderedDependencies(deps),
  30476. missing
  30477. };
  30478. } catch (e) {
  30479. e.message = import_picocolors.default.red(`\
  30480. Failed to scan for dependencies from entries:
  30481. ${entries.join("\n")}
  30482. `) + e.message;
  30483. throw e;
  30484. } finally {
  30485. 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")}`);
  30486. }
  30487. }
  30488. return {
  30489. cancel,
  30490. result: scan().then((res) => res ?? {
  30491. deps: {},
  30492. missing: {}
  30493. })
  30494. };
  30495. }
  30496. async function computeEntries(environment) {
  30497. let entries = [];
  30498. const explicitEntryPatterns = environment.config.optimizeDeps.entries;
  30499. const buildInput = environment.config.build.rollupOptions.input;
  30500. if (explicitEntryPatterns) entries = await globEntries(explicitEntryPatterns, environment);
  30501. else if (buildInput) {
  30502. const resolvePath = async (p) => {
  30503. const id = (await environment.pluginContainer.resolveId(p, path.join(process.cwd(), "*"), {
  30504. isEntry: true,
  30505. scan: true
  30506. }))?.id;
  30507. if (id === void 0) throw new Error(`failed to resolve rollupOptions.input value: ${JSON.stringify(p)}.`);
  30508. return id;
  30509. };
  30510. if (typeof buildInput === "string") entries = [await resolvePath(buildInput)];
  30511. else if (Array.isArray(buildInput)) entries = await Promise.all(buildInput.map(resolvePath));
  30512. else if (isObject$1(buildInput)) entries = await Promise.all(Object.values(buildInput).map(resolvePath));
  30513. else throw new Error("invalid rollupOptions.input value.");
  30514. } else entries = await globEntries("**/*.html", environment);
  30515. entries = entries.filter((entry) => isScannable(entry, environment.config.optimizeDeps.extensions) && fs.existsSync(entry));
  30516. return entries;
  30517. }
  30518. async function prepareRolldownScanner(environment, entries, deps, missing) {
  30519. const { plugins: pluginsFromConfig = [], ...rolldownOptions } = environment.config.optimizeDeps.rolldownOptions ?? {};
  30520. const plugins = await asyncFlatten(arraify(pluginsFromConfig));
  30521. plugins.push(...rolldownScanPlugin(environment, deps, missing, entries));
  30522. const transformOptions = deepClone(rolldownOptions.transform) ?? {};
  30523. if (transformOptions.jsx === void 0) transformOptions.jsx = {};
  30524. else if (transformOptions.jsx === "react" || transformOptions.jsx === "react-jsx") transformOptions.jsx = getRollupJsxPresets(transformOptions.jsx);
  30525. if (typeof transformOptions.jsx === "object") transformOptions.jsx.development ??= !environment.config.isProduction;
  30526. async function build() {
  30527. await scan({
  30528. ...rolldownOptions,
  30529. transform: transformOptions,
  30530. input: entries,
  30531. logLevel: "silent",
  30532. plugins
  30533. });
  30534. }
  30535. return { build };
  30536. }
  30537. function orderedDependencies(deps) {
  30538. const depsList = Object.entries(deps);
  30539. depsList.sort((a, b) => a[0].localeCompare(b[0]));
  30540. return Object.fromEntries(depsList);
  30541. }
  30542. async function globEntries(patterns, environment) {
  30543. const nodeModulesPatterns = [];
  30544. const regularPatterns = [];
  30545. for (const pattern of arraify(patterns)) if (pattern.includes("node_modules")) nodeModulesPatterns.push(pattern);
  30546. else regularPatterns.push(pattern);
  30547. const sharedOptions = {
  30548. absolute: true,
  30549. cwd: environment.config.root,
  30550. ignore: [`**/${environment.config.build.outDir}/**`, ...environment.config.optimizeDeps.entries ? [] : [`**/__tests__/**`, `**/coverage/**`]]
  30551. };
  30552. return (await Promise.all([glob(nodeModulesPatterns, sharedOptions), glob(regularPatterns, {
  30553. ...sharedOptions,
  30554. ignore: [...sharedOptions.ignore, "**/node_modules/**"]
  30555. })])).flat();
  30556. }
  30557. const scriptRE = /(<script(?:\s+[a-z_:][-\w:]*(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^"'<>=\s]+))?)*\s*>)(.*?)<\/script>/gis;
  30558. const commentRE = /<!--.*?-->/gs;
  30559. const srcRE = /\bsrc\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s'">]+))/i;
  30560. const typeRE = /\btype\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s'">]+))/i;
  30561. const langRE = /\blang\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s'">]+))/i;
  30562. const svelteScriptModuleRE = /\bcontext\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s'">]+))/i;
  30563. const svelteModuleRE = /\smodule\b/i;
  30564. function rolldownScanPlugin(environment, depImports, missing, entries) {
  30565. const seen = /* @__PURE__ */ new Map();
  30566. async function resolveId(id, importer) {
  30567. return environment.pluginContainer.resolveId(id, importer && normalizePath(importer), { scan: true });
  30568. }
  30569. const resolve = async (id, importer) => {
  30570. const key = id + (importer && path.dirname(importer));
  30571. if (seen.has(key)) return seen.get(key);
  30572. const res = (await resolveId(id, importer))?.id;
  30573. seen.set(key, res);
  30574. return res;
  30575. };
  30576. const optimizeDepsOptions = environment.config.optimizeDeps;
  30577. const include = optimizeDepsOptions.include;
  30578. const exclude = [
  30579. ...optimizeDepsOptions.exclude ?? [],
  30580. "@vite/client",
  30581. "@vite/env"
  30582. ];
  30583. const externalUnlessEntry = ({ path }) => ({
  30584. id: path,
  30585. external: !entries.includes(path)
  30586. });
  30587. const doTransformGlobImport = async (contents, id, loader) => {
  30588. let transpiledContents;
  30589. if (loader !== "js") {
  30590. const result = transformSync(id, contents, {
  30591. lang: loader,
  30592. tsconfig: false
  30593. });
  30594. if (result.errors.length > 0) throw new AggregateError(result.errors, "oxc transform error");
  30595. transpiledContents = result.code;
  30596. } else transpiledContents = contents;
  30597. return (await transformGlobImport(transpiledContents, id, environment.config.root, resolve))?.s.toString() || transpiledContents;
  30598. };
  30599. const scripts = {};
  30600. const htmlTypeOnLoadCallback = async (id) => {
  30601. let raw = await fsp.readFile(id, "utf-8");
  30602. raw = raw.replace(commentRE, "<!---->");
  30603. const isHtml = id.endsWith(".html");
  30604. let js = "";
  30605. let scriptId = 0;
  30606. const matches = raw.matchAll(scriptRE);
  30607. for (const [, openTag, content] of matches) {
  30608. const typeMatch = typeRE.exec(openTag);
  30609. const type = typeMatch && (typeMatch[1] || typeMatch[2] || typeMatch[3]);
  30610. const langMatch = langRE.exec(openTag);
  30611. const lang = langMatch && (langMatch[1] || langMatch[2] || langMatch[3]);
  30612. if (isHtml && type !== "module") continue;
  30613. if (type && !(type.includes("javascript") || type.includes("ecmascript") || type === "module")) continue;
  30614. let loader = "js";
  30615. if (lang === "ts" || lang === "tsx" || lang === "jsx") loader = lang;
  30616. else if (id.endsWith(".astro")) loader = "ts";
  30617. const srcMatch = srcRE.exec(openTag);
  30618. if (srcMatch) {
  30619. const src = srcMatch[1] || srcMatch[2] || srcMatch[3];
  30620. js += `import ${JSON.stringify(src)}\n`;
  30621. } else if (content.trim()) {
  30622. const contents = content + (loader.startsWith("ts") ? extractImportPaths(content) : "");
  30623. const key = `${id}?id=${scriptId++}`;
  30624. if (contents.includes("import.meta.glob")) scripts[key] = {
  30625. loader: "js",
  30626. contents: await doTransformGlobImport(contents, id, loader)
  30627. };
  30628. else scripts[key] = {
  30629. loader,
  30630. contents
  30631. };
  30632. const virtualModulePath = JSON.stringify(virtualModulePrefix + key);
  30633. let addedImport = false;
  30634. if (id.endsWith(".svelte")) {
  30635. let isModule = svelteModuleRE.test(openTag);
  30636. if (!isModule) {
  30637. const contextMatch = svelteScriptModuleRE.exec(openTag);
  30638. isModule = (contextMatch && (contextMatch[1] || contextMatch[2] || contextMatch[3])) === "module";
  30639. }
  30640. if (!isModule) {
  30641. addedImport = true;
  30642. js += `import ${virtualModulePath}\n`;
  30643. }
  30644. }
  30645. if (!addedImport) js += `export * from ${virtualModulePath}\n`;
  30646. }
  30647. }
  30648. if (!id.endsWith(".vue") || !js.includes("export default")) js += "\nexport default {}";
  30649. return js;
  30650. };
  30651. const ASSET_TYPE_RE = new RegExp(`\\.(${KNOWN_ASSET_TYPES.join("|")})$`);
  30652. return [
  30653. {
  30654. name: "vite:dep-scan:resolve-external-url",
  30655. resolveId: {
  30656. filter: { id: externalRE },
  30657. handler: (id) => ({
  30658. id,
  30659. external: true
  30660. })
  30661. }
  30662. },
  30663. {
  30664. name: "vite:dep-scan:resolve-data-url",
  30665. resolveId: {
  30666. filter: { id: dataUrlRE },
  30667. handler: (id) => ({
  30668. id,
  30669. external: true
  30670. })
  30671. }
  30672. },
  30673. {
  30674. name: "vite:dep-scan:local-scripts",
  30675. resolveId: {
  30676. filter: { id: virtualModuleRE },
  30677. handler: (id) => ({ id })
  30678. },
  30679. load: {
  30680. filter: { id: virtualModuleRE },
  30681. handler(id) {
  30682. const script = scripts[id.replace(virtualModulePrefix, "")];
  30683. return {
  30684. code: script.contents,
  30685. moduleType: script.loader
  30686. };
  30687. }
  30688. }
  30689. },
  30690. {
  30691. name: "vite:dep-scan:resolve",
  30692. async resolveId(id, importer) {
  30693. importer = importer && virtualModuleRE.test(importer) ? importer.replace(virtualModulePrefix, "") : importer;
  30694. if (htmlTypesRE.test(id)) {
  30695. const resolved = await resolve(id, importer);
  30696. if (!resolved) return;
  30697. if (isInNodeModules(resolved) && isOptimizable(resolved, optimizeDepsOptions)) return;
  30698. if (shouldExternalizeDep(resolved, id)) return externalUnlessEntry({ path: id });
  30699. return resolved;
  30700. }
  30701. if (/^[\w@][^:]/.test(id)) {
  30702. if (moduleListContains(exclude, id)) return externalUnlessEntry({ path: id });
  30703. if (depImports[id]) return externalUnlessEntry({ path: id });
  30704. const resolved = await resolve(id, importer);
  30705. if (resolved) {
  30706. if (shouldExternalizeDep(resolved, id)) return externalUnlessEntry({ path: id });
  30707. if (isInNodeModules(resolved) || include?.includes(id)) {
  30708. if (isOptimizable(resolved, optimizeDepsOptions)) depImports[id] = resolved;
  30709. return externalUnlessEntry({ path: id });
  30710. } else if (isScannable(resolved, optimizeDepsOptions.extensions)) return path.resolve(resolved);
  30711. else return externalUnlessEntry({ path: id });
  30712. } else missing[id] = normalizePath(importer);
  30713. }
  30714. if (CSS_LANGS_RE.test(id)) return externalUnlessEntry({ path: id });
  30715. if (/\.(?:json|json5|wasm)$/.test(id)) return externalUnlessEntry({ path: id });
  30716. if (ASSET_TYPE_RE.test(id)) return externalUnlessEntry({ path: id });
  30717. if (SPECIAL_QUERY_RE.test(id)) return {
  30718. id,
  30719. external: true
  30720. };
  30721. const resolved = await resolve(id, importer);
  30722. if (resolved) {
  30723. if (shouldExternalizeDep(resolved, id) || !isScannable(resolved, optimizeDepsOptions.extensions)) return externalUnlessEntry({ path: id });
  30724. return path.resolve(cleanUrl(resolved));
  30725. }
  30726. return externalUnlessEntry({ path: id });
  30727. }
  30728. },
  30729. {
  30730. name: "vite:dep-scan:load:html",
  30731. load: {
  30732. filter: { id: htmlTypesRE },
  30733. async handler(id) {
  30734. return {
  30735. code: await htmlTypeOnLoadCallback(id),
  30736. moduleType: "js"
  30737. };
  30738. }
  30739. }
  30740. },
  30741. ...environment.config.esbuild && environment.config.esbuild.jsxInject ? [{
  30742. name: "vite:dep-scan:transform:jsx-inject",
  30743. transform: {
  30744. filter: { id: /\.[jt]sx$/ },
  30745. handler(code) {
  30746. const esbuildConfig = environment.config.esbuild;
  30747. if (esbuildConfig && esbuildConfig.jsxInject) code = esbuildConfig.jsxInject + `\n` + code;
  30748. return code;
  30749. }
  30750. }
  30751. }] : [],
  30752. {
  30753. name: "vite:dep-scan:transform:js-glob",
  30754. transform: {
  30755. filter: { code: "import.meta.glob" },
  30756. async handler(code, id) {
  30757. if (JS_TYPES_RE.test(id)) {
  30758. let ext = path.extname(id).slice(1);
  30759. if (ext === "mjs") ext = "js";
  30760. return {
  30761. moduleType: "js",
  30762. code: await doTransformGlobImport(code, id, ext)
  30763. };
  30764. }
  30765. }
  30766. }
  30767. }
  30768. ];
  30769. }
  30770. /**
  30771. * when using TS + (Vue + `<script setup>`) or Svelte, imports may seem
  30772. * unused to esbuild and dropped in the build output, which prevents
  30773. * esbuild from crawling further.
  30774. * the solution is to add `import 'x'` for every source to force
  30775. * esbuild to keep crawling due to potential side effects.
  30776. */
  30777. function extractImportPaths(code) {
  30778. code = code.replace(multilineCommentsRE, "/* */").replace(singlelineCommentsRE, "");
  30779. let js = "";
  30780. let m;
  30781. importsRE.lastIndex = 0;
  30782. while ((m = importsRE.exec(code)) != null) js += `\nimport ${m[1]}`;
  30783. return js;
  30784. }
  30785. function shouldExternalizeDep(resolvedId, rawId) {
  30786. if (!path.isAbsolute(resolvedId)) return true;
  30787. if (resolvedId === rawId || resolvedId.includes("\0")) return true;
  30788. return false;
  30789. }
  30790. function isScannable(id, extensions) {
  30791. return JS_TYPES_RE.test(id) || htmlTypesRE.test(id) || extensions?.includes(path.extname(id)) || false;
  30792. }
  30793. //#endregion
  30794. //#region src/node/optimizer/resolve.ts
  30795. function createOptimizeDepsIncludeResolver(environment) {
  30796. const topLevelConfig = environment.getTopLevelConfig();
  30797. const resolve = createBackCompatIdResolver(topLevelConfig, {
  30798. asSrc: false,
  30799. scan: true,
  30800. packageCache: /* @__PURE__ */ new Map()
  30801. });
  30802. return async (id) => {
  30803. const lastArrowIndex = id.lastIndexOf(">");
  30804. if (lastArrowIndex === -1) return await resolve(environment, id, void 0);
  30805. const nestedRoot = id.substring(0, lastArrowIndex).trim();
  30806. const nestedPath = id.substring(lastArrowIndex + 1).trim();
  30807. const basedir = nestedResolveBasedir(nestedRoot, topLevelConfig.root, topLevelConfig.resolve.preserveSymlinks);
  30808. return await resolve(environment, nestedPath, path.resolve(basedir, "package.json"));
  30809. };
  30810. }
  30811. /**
  30812. * Expand the glob syntax in `optimizeDeps.include` to proper import paths
  30813. */
  30814. function expandGlobIds(id, config) {
  30815. const pkgName = getNpmPackageName(id);
  30816. if (!pkgName) return [];
  30817. const pkgData = resolvePackageData(pkgName, config.root, config.resolve.preserveSymlinks, config.packageCache);
  30818. if (!pkgData) return [];
  30819. const pattern = "." + id.slice(pkgName.length);
  30820. const exports = pkgData.data.exports;
  30821. if (exports) {
  30822. if (typeof exports === "string" || Array.isArray(exports)) return [pkgName];
  30823. const possibleExportPaths = [];
  30824. for (const key in exports) if (key[0] === ".") if (key.includes("*")) {
  30825. const exportsValue = getFirstExportStringValue(exports[key]);
  30826. if (!exportsValue) continue;
  30827. const exportValuePattern = exportsValue.replace(/\*/g, "**/*");
  30828. const exportsValueGlobRe = new RegExp(exportsValue.split("*").map(escapeRegex).join("(.*)"));
  30829. possibleExportPaths.push(...globSync(exportValuePattern, {
  30830. cwd: pkgData.dir,
  30831. expandDirectories: false,
  30832. ignore: ["node_modules"]
  30833. }).map((filePath) => {
  30834. if (exportsValue.startsWith("./")) filePath = "./" + filePath;
  30835. const matched = exportsValueGlobRe.exec(slash(filePath));
  30836. if (matched) {
  30837. let allGlobSame = matched.length === 2;
  30838. if (!allGlobSame) {
  30839. allGlobSame = true;
  30840. for (let i = 2; i < matched.length; i++) if (matched[i] !== matched[i - 1]) {
  30841. allGlobSame = false;
  30842. break;
  30843. }
  30844. }
  30845. if (allGlobSame) return key.replace("*", matched[1]).slice(2);
  30846. }
  30847. return "";
  30848. }).filter(Boolean));
  30849. } else possibleExportPaths.push(key.slice(2));
  30850. const isMatch = picomatch(pattern);
  30851. const matched = possibleExportPaths.filter((p) => isMatch(p)).map((match) => path.posix.join(pkgName, match));
  30852. matched.unshift(pkgName);
  30853. return matched;
  30854. } else {
  30855. const matched = globSync(pattern, {
  30856. cwd: pkgData.dir,
  30857. expandDirectories: false,
  30858. ignore: ["node_modules"]
  30859. }).map((match) => path.posix.join(pkgName, slash(match)));
  30860. matched.unshift(pkgName);
  30861. return matched;
  30862. }
  30863. }
  30864. function getFirstExportStringValue(obj) {
  30865. if (typeof obj === "string") return obj;
  30866. else if (Array.isArray(obj)) return obj[0];
  30867. else for (const key in obj) return getFirstExportStringValue(obj[key]);
  30868. }
  30869. /**
  30870. * Continuously resolve the basedir of packages separated by '>'
  30871. */
  30872. function nestedResolveBasedir(id, basedir, preserveSymlinks = false) {
  30873. const pkgs = id.split(">").map((pkg) => pkg.trim());
  30874. for (const pkg of pkgs) basedir = resolvePackageData(pkg, basedir, preserveSymlinks)?.dir || basedir;
  30875. return basedir;
  30876. }
  30877. //#endregion
  30878. //#region src/node/optimizer/rolldownDepPlugin.ts
  30879. const externalWithConversionNamespace = "vite:dep-pre-bundle:external-conversion";
  30880. const convertedExternalPrefix = "vite-dep-pre-bundle-external:";
  30881. const cjsExternalFacadeNamespace = "vite:cjs-external-facade";
  30882. const nonFacadePrefix = "vite-cjs-external-facade:";
  30883. const externalTypes = [
  30884. "css",
  30885. "less",
  30886. "sass",
  30887. "scss",
  30888. "styl",
  30889. "stylus",
  30890. "pcss",
  30891. "postcss",
  30892. "wasm",
  30893. "vue",
  30894. "svelte",
  30895. "marko",
  30896. "astro",
  30897. "imba",
  30898. "jsx",
  30899. "tsx",
  30900. ...KNOWN_ASSET_TYPES
  30901. ];
  30902. const optionalPeerDepNamespace = "optional-peer-dep:";
  30903. const browserExternalNamespace = "browser-external:";
  30904. function rolldownDepPlugin(environment, qualified, external) {
  30905. const { isProduction } = environment.config;
  30906. const { extensions } = environment.config.optimizeDeps;
  30907. const allExternalTypes = extensions ? externalTypes.filter((type) => !extensions.includes("." + type)) : externalTypes;
  30908. const esmPackageCache = /* @__PURE__ */ new Map();
  30909. const cjsPackageCache = /* @__PURE__ */ new Map();
  30910. const resolveAssets = (resolved, kind) => {
  30911. if (kind === "require-call") return { id: externalWithConversionNamespace + resolved };
  30912. return {
  30913. id: resolved,
  30914. external: "absolute"
  30915. };
  30916. };
  30917. const _resolve = createBackCompatIdResolver(environment.getTopLevelConfig(), {
  30918. asSrc: false,
  30919. scan: true,
  30920. packageCache: esmPackageCache
  30921. });
  30922. const _resolveRequire = createBackCompatIdResolver(environment.getTopLevelConfig(), {
  30923. asSrc: false,
  30924. isRequire: true,
  30925. scan: true,
  30926. packageCache: cjsPackageCache
  30927. });
  30928. const resolve = (id, importer, kind) => {
  30929. const _importer = importer && importer in qualified ? qualified[importer] : importer;
  30930. return (kind.startsWith("require") ? _resolveRequire : _resolve)(environment, id, _importer);
  30931. };
  30932. const resolveResult = (id, resolved, kind) => {
  30933. if (resolved.startsWith("__vite-browser-external")) return { id: browserExternalNamespace + id };
  30934. if (resolved.startsWith("__vite-optional-peer-dep")) return { id: optionalPeerDepNamespace + resolved };
  30935. if (allExternalTypesReg.test(resolved)) return resolveAssets(resolved, kind);
  30936. if (isBuiltin(environment.config.resolve.builtins, resolved)) return;
  30937. if (isExternalUrl(resolved)) return {
  30938. id: resolved,
  30939. external: "absolute"
  30940. };
  30941. return { id: path.resolve(resolved) };
  30942. };
  30943. const allExternalTypesReg = new RegExp(`\\.(` + allExternalTypes.join("|") + `)(\\?.*)?$`);
  30944. function resolveEntry(id) {
  30945. const flatId = flattenId(id);
  30946. if (flatId in qualified) return { id: qualified[flatId] };
  30947. }
  30948. const bundleOutputDir = path.join(environment.config.cacheDir, "deps");
  30949. return [{
  30950. name: "vite:dep-pre-bundle-assets",
  30951. resolveId: {
  30952. filter: { id: allExternalTypesReg },
  30953. async handler(id, importer, options) {
  30954. const kind = options.kind;
  30955. if (id.startsWith(convertedExternalPrefix)) return {
  30956. id: id.slice(29),
  30957. external: "absolute"
  30958. };
  30959. const resolved = await resolve(id, importer, kind);
  30960. if (resolved) {
  30961. if (JS_TYPES_RE.test(resolved)) return {
  30962. id: isWindows ? resolved.replaceAll("/", "\\") : resolved,
  30963. external: false
  30964. };
  30965. return resolveAssets(resolved, kind);
  30966. }
  30967. }
  30968. },
  30969. load: {
  30970. filter: { id: prefixRegex(externalWithConversionNamespace) },
  30971. handler(id) {
  30972. const path = id.slice(39);
  30973. const modulePath = `"${convertedExternalPrefix}${path}"`;
  30974. return { code: isCSSRequest(path) && !isModuleCSSRequest(path) ? `import ${modulePath};` : `export { default } from ${modulePath};export * from ${modulePath};` };
  30975. }
  30976. }
  30977. }, {
  30978. name: "vite:dep-pre-bundle",
  30979. buildEnd() {
  30980. esmPackageCache.clear();
  30981. cjsPackageCache.clear();
  30982. },
  30983. resolveId: {
  30984. filter: { id: /^[\w@][^:]/ },
  30985. async handler(id, importer, options) {
  30986. const kind = options.kind;
  30987. if (moduleListContains(external, id)) return {
  30988. id,
  30989. external: "absolute"
  30990. };
  30991. let entry;
  30992. if (!importer) {
  30993. if (entry = resolveEntry(id)) return entry;
  30994. const aliased = await _resolve(environment, id, void 0, true);
  30995. if (aliased && (entry = resolveEntry(aliased))) return entry;
  30996. }
  30997. const resolved = await resolve(id, importer, kind);
  30998. if (resolved) return resolveResult(id, resolved, kind);
  30999. }
  31000. },
  31001. load: {
  31002. filter: { id: [prefixRegex(browserExternalNamespace), prefixRegex(optionalPeerDepNamespace)] },
  31003. handler(id) {
  31004. if (id.startsWith(browserExternalNamespace)) {
  31005. const path = id.slice(17);
  31006. if (isProduction) return { code: "module.exports = {}" };
  31007. else return { code: `\
  31008. module.exports = Object.create(new Proxy({}, {
  31009. get(_, key) {
  31010. if (
  31011. key !== '__esModule' &&
  31012. key !== '__proto__' &&
  31013. key !== 'constructor' &&
  31014. key !== 'splice'
  31015. ) {
  31016. 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.\`)
  31017. }
  31018. }
  31019. }))` };
  31020. }
  31021. if (id.startsWith(optionalPeerDepNamespace)) {
  31022. const [, peerDep, parentDep] = id.slice(18).split(":");
  31023. return { code: `module.exports = {};throw new Error(\`Could not resolve "${peerDep}" imported by "${parentDep}". Is it installed?\`)` };
  31024. }
  31025. }
  31026. },
  31027. transform: {
  31028. filter: { code: /new\s+URL.+import\.meta\.url/s },
  31029. async handler(code, id) {
  31030. let s;
  31031. const assetImportMetaUrlRE = /\bnew\s+URL\s*\(\s*('[^']+'|"[^"]+"|`[^`]+`)\s*,\s*import\.meta\.url\s*(?:,\s*)?\)/dg;
  31032. const cleanString = stripLiteral(code);
  31033. let match;
  31034. while (match = assetImportMetaUrlRE.exec(cleanString)) {
  31035. const [[startIndex, endIndex], [urlStart, urlEnd]] = match.indices;
  31036. if (hasViteIgnoreRE.test(code.slice(startIndex, urlStart))) continue;
  31037. const rawUrl = code.slice(urlStart, urlEnd);
  31038. if (rawUrl[0] === "`" && rawUrl.includes("${")) continue;
  31039. const url = rawUrl.slice(1, -1);
  31040. if (isDataUrl(url) || isExternalUrl(url) || url.startsWith("/")) continue;
  31041. if (!s) s = new MagicString(code);
  31042. const absolutePath = path.resolve(path.dirname(id), url);
  31043. const normalizedRelativePath = normalizePath(path.relative(bundleOutputDir, absolutePath));
  31044. s.update(startIndex, endIndex, `new URL('' + ${JSON.stringify(normalizedRelativePath)}, import.meta.url)`);
  31045. }
  31046. if (s) return {
  31047. code: s.toString(),
  31048. map: s.generateMap({ hires: "boundary" })
  31049. };
  31050. }
  31051. }
  31052. }];
  31053. }
  31054. const matchesEntireLine = (text) => `^${escapeRegex(text)}$`;
  31055. function rolldownCjsExternalPlugin(externals, platform) {
  31056. if (platform === "node") return;
  31057. if (platform === "neutral") return;
  31058. const filter = new RegExp(externals.map(matchesEntireLine).join("|"));
  31059. return {
  31060. name: "cjs-external",
  31061. resolveId: {
  31062. filter: { id: [prefixRegex(nonFacadePrefix), filter] },
  31063. handler(id, _importer, options) {
  31064. if (id.startsWith(nonFacadePrefix)) return {
  31065. id: id.slice(25),
  31066. external: "absolute"
  31067. };
  31068. if (options.kind === "require-call") return { id: cjsExternalFacadeNamespace + id };
  31069. return {
  31070. id,
  31071. external: "absolute"
  31072. };
  31073. }
  31074. },
  31075. load: {
  31076. filter: { id: prefixRegex(cjsExternalFacadeNamespace) },
  31077. handler(id) {
  31078. const idWithoutNamespace = id.slice(24);
  31079. return { code: `\
  31080. import * as m from ${JSON.stringify(nonFacadePrefix + idWithoutNamespace)};
  31081. module.exports = ${isNodeBuiltin(idWithoutNamespace) ? "m.default" : "{ ...m }"};
  31082. ` };
  31083. }
  31084. }
  31085. };
  31086. }
  31087. //#endregion
  31088. //#region src/node/optimizer/index.ts
  31089. const debug$2 = createDebugger("vite:deps");
  31090. const jsExtensionRE = /\.js$/i;
  31091. function isDepOptimizationDisabled(optimizeDeps) {
  31092. return optimizeDeps.disabled === true || optimizeDeps.disabled === "dev" || !!optimizeDeps.noDiscovery && !optimizeDeps.include?.length;
  31093. }
  31094. /**
  31095. * Scan and optimize dependencies within a project.
  31096. * Used by Vite CLI when running `vite optimize`.
  31097. *
  31098. * @deprecated the optimization process runs automatically and does not need to be called
  31099. */
  31100. async function optimizeDeps(config, force = config.optimizeDeps.force, asCommand = false) {
  31101. const log = asCommand ? config.logger.info : debug$2;
  31102. config.logger.warn(import_picocolors.default.yellow("manually calling optimizeDeps is deprecated. This is done automatically and does not need to be called manually."));
  31103. const environment = new ScanEnvironment("client", config);
  31104. await environment.init();
  31105. const cachedMetadata = await loadCachedDepOptimizationMetadata(environment, force, asCommand);
  31106. if (cachedMetadata) return cachedMetadata;
  31107. const deps = await discoverProjectDependencies(environment).result;
  31108. await addManuallyIncludedOptimizeDeps(environment, deps);
  31109. const depsString = depsLogString(Object.keys(deps));
  31110. log?.(import_picocolors.default.green(`Optimizing dependencies:\n ${depsString}`));
  31111. const result = await runOptimizeDeps(environment, toDiscoveredDependencies(environment, deps)).result;
  31112. await result.commit();
  31113. return result.metadata;
  31114. }
  31115. async function optimizeExplicitEnvironmentDeps(environment) {
  31116. const cachedMetadata = await loadCachedDepOptimizationMetadata(environment, environment.config.optimizeDeps.force ?? false, false);
  31117. if (cachedMetadata) return cachedMetadata;
  31118. const deps = {};
  31119. await addManuallyIncludedOptimizeDeps(environment, deps);
  31120. const result = await runOptimizeDeps(environment, toDiscoveredDependencies(environment, deps)).result;
  31121. await result.commit();
  31122. return result.metadata;
  31123. }
  31124. function initDepsOptimizerMetadata(environment, timestamp) {
  31125. const { lockfileHash, configHash, hash } = getDepHash(environment);
  31126. return {
  31127. hash,
  31128. lockfileHash,
  31129. configHash,
  31130. browserHash: getOptimizedBrowserHash(hash, {}, timestamp),
  31131. optimized: {},
  31132. chunks: {},
  31133. discovered: {},
  31134. depInfoList: []
  31135. };
  31136. }
  31137. function addOptimizedDepInfo(metadata, type, depInfo) {
  31138. metadata[type][depInfo.id] = depInfo;
  31139. metadata.depInfoList.push(depInfo);
  31140. return depInfo;
  31141. }
  31142. let firstLoadCachedDepOptimizationMetadata = true;
  31143. /**
  31144. * Creates the initial dep optimization metadata, loading it from the deps cache
  31145. * if it exists and pre-bundling isn't forced
  31146. */
  31147. async function loadCachedDepOptimizationMetadata(environment, force = environment.config.optimizeDeps.force ?? false, asCommand = false) {
  31148. const log = asCommand ? environment.logger.info : debug$2;
  31149. if (firstLoadCachedDepOptimizationMetadata) {
  31150. firstLoadCachedDepOptimizationMetadata = false;
  31151. setTimeout(() => cleanupDepsCacheStaleDirs(environment.getTopLevelConfig()), 0).unref();
  31152. }
  31153. const depsCacheDir = getDepsCacheDir(environment);
  31154. if (!force) {
  31155. let cachedMetadata;
  31156. try {
  31157. const cachedMetadataPath = path.join(depsCacheDir, METADATA_FILENAME);
  31158. cachedMetadata = parseDepsOptimizerMetadata(await fsp.readFile(cachedMetadataPath, "utf-8"), depsCacheDir);
  31159. } catch {}
  31160. if (cachedMetadata) if (cachedMetadata.lockfileHash !== getLockfileHash(environment)) environment.logger.info("Re-optimizing dependencies because lockfile has changed", { timestamp: true });
  31161. else if (cachedMetadata.configHash !== getConfigHash(environment)) environment.logger.info("Re-optimizing dependencies because vite config has changed", { timestamp: true });
  31162. else {
  31163. log?.(`(${environment.name}) Hash is consistent. Skipping. Use --force to override.`);
  31164. return cachedMetadata;
  31165. }
  31166. } else environment.logger.info("Forced re-optimization of dependencies", { timestamp: true });
  31167. debug$2?.(`(${environment.name}) ${import_picocolors.default.green(`removing old cache dir ${depsCacheDir}`)}`);
  31168. await fsp.rm(depsCacheDir, {
  31169. recursive: true,
  31170. force: true
  31171. });
  31172. }
  31173. /**
  31174. * Initial optimizeDeps at server start. Perform a fast scan using esbuild to
  31175. * find deps to pre-bundle and include user hard-coded dependencies
  31176. */
  31177. function discoverProjectDependencies(environment) {
  31178. const { cancel, result } = scanImports(environment);
  31179. return {
  31180. cancel,
  31181. result: result.then(({ deps, missing }) => {
  31182. const missingIds = Object.keys(missing);
  31183. 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?`);
  31184. return deps;
  31185. })
  31186. };
  31187. }
  31188. function toDiscoveredDependencies(environment, deps, timestamp) {
  31189. const browserHash = getOptimizedBrowserHash(getDepHash(environment).hash, deps, timestamp);
  31190. const discovered = {};
  31191. for (const id in deps) {
  31192. const src = deps[id];
  31193. discovered[id] = {
  31194. id,
  31195. file: getOptimizedDepPath(environment, id),
  31196. src,
  31197. browserHash,
  31198. exportsData: extractExportsData(environment, src)
  31199. };
  31200. }
  31201. return discovered;
  31202. }
  31203. function depsLogString(qualifiedIds) {
  31204. return import_picocolors.default.yellow(qualifiedIds.join(`, `));
  31205. }
  31206. /**
  31207. * Internally, Vite uses this function to prepare a optimizeDeps run. When Vite starts, we can get
  31208. * the metadata and start the server without waiting for the optimizeDeps processing to be completed
  31209. */
  31210. function runOptimizeDeps(environment, depsInfo) {
  31211. const optimizerContext = { cancelled: false };
  31212. const depsCacheDir = getDepsCacheDir(environment);
  31213. const processingCacheDir = getProcessingDepsCacheDir(environment);
  31214. fs.mkdirSync(processingCacheDir, { recursive: true });
  31215. debug$2?.(import_picocolors.default.green(`creating package.json in ${processingCacheDir}`));
  31216. fs.writeFileSync(path.resolve(processingCacheDir, "package.json"), `{\n "type": "module"\n}\n`);
  31217. const metadata = initDepsOptimizerMetadata(environment);
  31218. metadata.browserHash = getOptimizedBrowserHash(metadata.hash, depsFromOptimizedDepInfo(depsInfo));
  31219. const qualifiedIds = Object.keys(depsInfo);
  31220. let cleaned = false;
  31221. let committed = false;
  31222. const cleanUp = () => {
  31223. if (!cleaned && !committed) {
  31224. cleaned = true;
  31225. debug$2?.(import_picocolors.default.green(`removing cache dir ${processingCacheDir}`));
  31226. try {
  31227. fs.rmSync(processingCacheDir, {
  31228. recursive: true,
  31229. force: true
  31230. });
  31231. } catch {}
  31232. }
  31233. };
  31234. const successfulResult = {
  31235. metadata,
  31236. cancel: cleanUp,
  31237. commit: async () => {
  31238. if (cleaned) throw new Error("Can not commit a Deps Optimization run as it was cancelled");
  31239. committed = true;
  31240. const dataPath = path.join(processingCacheDir, METADATA_FILENAME);
  31241. debug$2?.(import_picocolors.default.green(`creating ${METADATA_FILENAME} in ${processingCacheDir}`));
  31242. fs.writeFileSync(dataPath, stringifyDepsOptimizerMetadata(metadata, depsCacheDir));
  31243. const temporaryPath = depsCacheDir + getTempSuffix();
  31244. const depsCacheDirPresent = fs.existsSync(depsCacheDir);
  31245. if (isWindows) {
  31246. if (depsCacheDirPresent) {
  31247. debug$2?.(import_picocolors.default.green(`renaming ${depsCacheDir} to ${temporaryPath}`));
  31248. await safeRename(depsCacheDir, temporaryPath);
  31249. }
  31250. debug$2?.(import_picocolors.default.green(`renaming ${processingCacheDir} to ${depsCacheDir}`));
  31251. await safeRename(processingCacheDir, depsCacheDir);
  31252. } else {
  31253. if (depsCacheDirPresent) {
  31254. debug$2?.(import_picocolors.default.green(`renaming ${depsCacheDir} to ${temporaryPath}`));
  31255. fs.renameSync(depsCacheDir, temporaryPath);
  31256. }
  31257. debug$2?.(import_picocolors.default.green(`renaming ${processingCacheDir} to ${depsCacheDir}`));
  31258. fs.renameSync(processingCacheDir, depsCacheDir);
  31259. }
  31260. if (depsCacheDirPresent) {
  31261. debug$2?.(import_picocolors.default.green(`removing cache temp dir ${temporaryPath}`));
  31262. fsp.rm(temporaryPath, {
  31263. recursive: true,
  31264. force: true
  31265. });
  31266. }
  31267. }
  31268. };
  31269. if (!qualifiedIds.length) return {
  31270. cancel: async () => cleanUp(),
  31271. result: Promise.resolve(successfulResult)
  31272. };
  31273. const cancelledResult = {
  31274. metadata,
  31275. commit: async () => cleanUp(),
  31276. cancel: cleanUp
  31277. };
  31278. const start = performance$1.now();
  31279. const preparedRun = prepareRolldownOptimizerRun(environment, depsInfo, processingCacheDir, optimizerContext);
  31280. const runResult = preparedRun.then(({ context, idToExports }) => {
  31281. if (!context || optimizerContext.cancelled) return cancelledResult;
  31282. return context.build().then((result) => {
  31283. const depForEntryFileName = {};
  31284. for (const dep of Object.values(depsInfo)) {
  31285. const entryFileName = flattenId(dep.id) + ".js";
  31286. depForEntryFileName[entryFileName] = dep;
  31287. }
  31288. for (const chunk of result.output) {
  31289. if (chunk.type !== "chunk") continue;
  31290. if (chunk.isEntry) {
  31291. const { exportsData, file, id, ...info } = depForEntryFileName[chunk.fileName];
  31292. addOptimizedDepInfo(metadata, "optimized", {
  31293. id,
  31294. file,
  31295. ...info,
  31296. fileHash: getHash(metadata.hash + file + JSON.stringify(chunk.imports)),
  31297. browserHash: metadata.browserHash,
  31298. needsInterop: needsInterop(environment, id, idToExports[id], chunk)
  31299. });
  31300. } else {
  31301. const id = chunk.fileName.replace(jsExtensionRE, "");
  31302. const file = normalizePath(path.resolve(getDepsCacheDir(environment), chunk.fileName));
  31303. if (!findOptimizedDepInfoInRecord(metadata.optimized, (depInfo) => depInfo.file === file)) addOptimizedDepInfo(metadata, "chunks", {
  31304. id,
  31305. file,
  31306. needsInterop: false,
  31307. browserHash: metadata.browserHash,
  31308. isDynamicEntry: chunk.isDynamicEntry
  31309. });
  31310. }
  31311. }
  31312. debug$2?.(`Dependencies bundled in ${(performance$1.now() - start).toFixed(2)}ms`);
  31313. return successfulResult;
  31314. }).catch((e) => {
  31315. if (e.errors && e.message.includes("The build was canceled")) return cancelledResult;
  31316. e.message = import_picocolors.default.red("Error during dependency optimization:\n\n") + e.message;
  31317. throw e;
  31318. });
  31319. });
  31320. runResult.catch(() => {
  31321. cleanUp();
  31322. });
  31323. return {
  31324. async cancel() {
  31325. optimizerContext.cancelled = true;
  31326. const { context } = await preparedRun;
  31327. context?.cancel();
  31328. cleanUp();
  31329. },
  31330. result: runResult
  31331. };
  31332. }
  31333. async function prepareRolldownOptimizerRun(environment, depsInfo, processingCacheDir, optimizerContext) {
  31334. const flatIdDeps = {};
  31335. const idToExports = {};
  31336. const { optimizeDeps } = environment.config;
  31337. const { plugins: pluginsFromConfig = [], ...rolldownOptions } = optimizeDeps.rolldownOptions ?? {};
  31338. let jsxLoader = false;
  31339. await Promise.all(Object.keys(depsInfo).map(async (id) => {
  31340. const src = depsInfo[id].src;
  31341. const exportsData = await (depsInfo[id].exportsData ?? extractExportsData(environment, src));
  31342. if (exportsData.jsxLoader) jsxLoader = true;
  31343. const flatId = flattenId(id);
  31344. flatIdDeps[flatId] = isWindows ? src.replaceAll("/", "\\") : src;
  31345. idToExports[id] = exportsData;
  31346. }));
  31347. if (optimizerContext.cancelled) return {
  31348. context: void 0,
  31349. idToExports
  31350. };
  31351. const define = {
  31352. "process.env.NODE_ENV": environment.config.keepProcessEnv ? "process.env.NODE_ENV" : JSON.stringify(process.env.NODE_ENV || environment.config.mode),
  31353. ...rolldownOptions.transform?.define
  31354. };
  31355. const platform = optimizeDeps.rolldownOptions?.platform ?? (environment.config.consumer === "client" || environment.config.ssr.target === "webworker" ? "browser" : "node");
  31356. const external = [...optimizeDeps.exclude ?? []];
  31357. const plugins = await asyncFlatten(arraify(pluginsFromConfig));
  31358. if (external.length) plugins.push(rolldownCjsExternalPlugin(external, platform));
  31359. plugins.push(...rolldownDepPlugin(environment, flatIdDeps, external));
  31360. let canceled = false;
  31361. async function build() {
  31362. const bundle = await rolldown({
  31363. ...rolldownOptions,
  31364. input: flatIdDeps,
  31365. logLevel: "silent",
  31366. plugins,
  31367. platform,
  31368. transform: {
  31369. ...rolldownOptions.transform,
  31370. target: ESBUILD_BASELINE_WIDELY_AVAILABLE_TARGET,
  31371. define
  31372. },
  31373. resolve: {
  31374. extensions: [
  31375. ".tsx",
  31376. ".ts",
  31377. ".jsx",
  31378. ".js",
  31379. ".css",
  31380. ".json"
  31381. ],
  31382. ...rolldownOptions.resolve
  31383. },
  31384. moduleTypes: {
  31385. ".css": "js",
  31386. ...rolldownOptions.moduleTypes,
  31387. ...jsxLoader ? { ".js": "jsx" } : {}
  31388. }
  31389. });
  31390. if (canceled) {
  31391. await bundle.close();
  31392. throw new Error("The build was canceled");
  31393. }
  31394. const result = await bundle.write({
  31395. ...rolldownOptions.output,
  31396. format: "esm",
  31397. sourcemap: true,
  31398. dir: processingCacheDir,
  31399. entryFileNames: "[name].js"
  31400. });
  31401. await bundle.close();
  31402. return result;
  31403. }
  31404. function cancel() {
  31405. canceled = true;
  31406. }
  31407. return {
  31408. context: {
  31409. build,
  31410. cancel
  31411. },
  31412. idToExports
  31413. };
  31414. }
  31415. async function addManuallyIncludedOptimizeDeps(environment, deps) {
  31416. const { logger } = environment;
  31417. const { optimizeDeps } = environment.config;
  31418. const optimizeDepsInclude = optimizeDeps.include ?? [];
  31419. if (optimizeDepsInclude.length) {
  31420. const unableToOptimize = (id, msg) => {
  31421. if (optimizeDepsInclude.includes(id)) logger.warn(`${msg}: ${import_picocolors.default.cyan(id)}, present in ${environment.name} 'optimizeDeps.include'`);
  31422. };
  31423. const includes = [...optimizeDepsInclude];
  31424. for (let i = 0; i < includes.length; i++) {
  31425. const id = includes[i];
  31426. if (isDynamicPattern(id)) {
  31427. const globIds = expandGlobIds(id, environment.getTopLevelConfig());
  31428. includes.splice(i, 1, ...globIds);
  31429. i += globIds.length - 1;
  31430. }
  31431. }
  31432. const resolve = createOptimizeDepsIncludeResolver(environment);
  31433. for (const id of includes) {
  31434. const normalizedId = normalizeId(id);
  31435. if (!deps[normalizedId]) {
  31436. const entry = await resolve(id);
  31437. if (entry) if (isOptimizable(entry, optimizeDeps)) deps[normalizedId] = entry;
  31438. else unableToOptimize(id, "Cannot optimize dependency");
  31439. else unableToOptimize(id, "Failed to resolve dependency");
  31440. }
  31441. }
  31442. }
  31443. }
  31444. function depsFromOptimizedDepInfo(depsInfo) {
  31445. const obj = {};
  31446. for (const key in depsInfo) obj[key] = depsInfo[key].src;
  31447. return obj;
  31448. }
  31449. function getOptimizedDepPath(environment, id) {
  31450. return normalizePath(path.resolve(getDepsCacheDir(environment), flattenId(id) + ".js"));
  31451. }
  31452. function getDepsCacheSuffix(environment) {
  31453. return environment.name === "client" ? "" : `_${environment.name}`;
  31454. }
  31455. function getDepsCacheDir(environment) {
  31456. return getDepsCacheDirPrefix(environment) + getDepsCacheSuffix(environment);
  31457. }
  31458. function getProcessingDepsCacheDir(environment) {
  31459. return getDepsCacheDirPrefix(environment) + getDepsCacheSuffix(environment) + getTempSuffix();
  31460. }
  31461. function getTempSuffix() {
  31462. return "_temp_" + getHash(`${process.pid}:${Date.now().toString()}:${Math.random().toString(16).slice(2)}`);
  31463. }
  31464. function getDepsCacheDirPrefix(environment) {
  31465. return normalizePath(path.resolve(environment.config.cacheDir, "deps"));
  31466. }
  31467. function createIsOptimizedDepFile(environment) {
  31468. const depsCacheDirPrefix = getDepsCacheDirPrefix(environment);
  31469. return (id) => id.startsWith(depsCacheDirPrefix);
  31470. }
  31471. function createIsOptimizedDepUrl(environment) {
  31472. const { root } = environment.config;
  31473. const depsCacheDir = getDepsCacheDirPrefix(environment);
  31474. const depsCacheDirRelative = normalizePath(path.relative(root, depsCacheDir));
  31475. const depsCacheDirPrefix = depsCacheDirRelative.startsWith("../") ? `/@fs/${removeLeadingSlash(normalizePath(depsCacheDir))}` : `/${depsCacheDirRelative}`;
  31476. return function isOptimizedDepUrl(url) {
  31477. return url.startsWith(depsCacheDirPrefix);
  31478. };
  31479. }
  31480. function parseDepsOptimizerMetadata(jsonMetadata, depsCacheDir) {
  31481. const { hash, lockfileHash, configHash, browserHash, optimized, chunks } = JSON.parse(jsonMetadata, (key, value) => {
  31482. if (key === "file" || key === "src") return normalizePath(path.resolve(depsCacheDir, value));
  31483. return value;
  31484. });
  31485. if (!chunks || Object.values(optimized).some((depInfo) => !depInfo.fileHash)) return;
  31486. const metadata = {
  31487. hash,
  31488. lockfileHash,
  31489. configHash,
  31490. browserHash,
  31491. optimized: {},
  31492. discovered: {},
  31493. chunks: {},
  31494. depInfoList: []
  31495. };
  31496. for (const id of Object.keys(optimized)) addOptimizedDepInfo(metadata, "optimized", {
  31497. ...optimized[id],
  31498. id,
  31499. browserHash
  31500. });
  31501. for (const id of Object.keys(chunks)) addOptimizedDepInfo(metadata, "chunks", {
  31502. ...chunks[id],
  31503. id,
  31504. browserHash,
  31505. needsInterop: false
  31506. });
  31507. return metadata;
  31508. }
  31509. /**
  31510. * Stringify metadata for deps cache. Remove processing promises
  31511. * and individual dep info browserHash. Once the cache is reload
  31512. * the next time the server start we need to use the global
  31513. * browserHash to allow long term caching
  31514. */
  31515. function stringifyDepsOptimizerMetadata(metadata, depsCacheDir) {
  31516. const { hash, configHash, lockfileHash, browserHash, optimized, chunks } = metadata;
  31517. return JSON.stringify({
  31518. hash,
  31519. configHash,
  31520. lockfileHash,
  31521. browserHash,
  31522. optimized: Object.fromEntries(Object.values(optimized).map(({ id, src, file, fileHash, needsInterop, isDynamicEntry }) => [id, {
  31523. src,
  31524. file,
  31525. fileHash,
  31526. needsInterop,
  31527. isDynamicEntry
  31528. }])),
  31529. chunks: Object.fromEntries(Object.values(chunks).map(({ id, file, isDynamicEntry }) => [id, {
  31530. file,
  31531. isDynamicEntry
  31532. }]))
  31533. }, (key, value) => {
  31534. if (key === "file" || key === "src") return normalizePath(path.relative(depsCacheDir, value));
  31535. return value;
  31536. }, 2);
  31537. }
  31538. async function extractExportsData(environment, filePath) {
  31539. await init;
  31540. const { optimizeDeps } = environment.config;
  31541. const rolldownOptions = optimizeDeps.rolldownOptions ?? {};
  31542. if (optimizeDeps.extensions?.some((ext) => filePath.endsWith(ext))) {
  31543. const { plugins: pluginsFromConfig = [], ...remainingRolldownOptions } = rolldownOptions;
  31544. const plugins = await asyncFlatten(arraify(pluginsFromConfig));
  31545. plugins.unshift({
  31546. name: "externalize",
  31547. resolveId(id, importer) {
  31548. if (importer !== void 0) return {
  31549. id,
  31550. external: true
  31551. };
  31552. }
  31553. });
  31554. const [, exports, , hasModuleSyntax] = parse$2((await (await rolldown({
  31555. ...remainingRolldownOptions,
  31556. plugins,
  31557. input: [filePath],
  31558. moduleTypes: {
  31559. ".css": "js",
  31560. ...remainingRolldownOptions.moduleTypes
  31561. }
  31562. })).generate({
  31563. ...rolldownOptions.output,
  31564. format: "esm",
  31565. sourcemap: false
  31566. })).output[0].code);
  31567. return {
  31568. hasModuleSyntax,
  31569. exports: exports.map((e) => e.n)
  31570. };
  31571. }
  31572. let parseResult;
  31573. let usedJsxLoader = false;
  31574. const entryContent = fs.readFileSync(filePath, "utf-8");
  31575. try {
  31576. parseResult = parse$2(entryContent);
  31577. } catch {
  31578. const lang = rolldownOptions.moduleTypes?.[path.extname(filePath)] || "jsx";
  31579. debug$2?.(`Unable to parse: ${filePath}.\n Trying again with a ${lang} transform.`);
  31580. if (lang !== "jsx" && lang !== "tsx" && lang !== "ts") throw new Error(`Unable to parse : ${filePath}.`);
  31581. parseResult = parse$2((await transformWithOxc(entryContent, filePath, { lang }, void 0, environment.config)).code);
  31582. usedJsxLoader = true;
  31583. }
  31584. const [, exports, , hasModuleSyntax] = parseResult;
  31585. return {
  31586. hasModuleSyntax,
  31587. exports: exports.map((e) => e.n),
  31588. jsxLoader: usedJsxLoader
  31589. };
  31590. }
  31591. function needsInterop(environment, id, exportsData, output) {
  31592. if (environment.config.optimizeDeps.needsInterop?.includes(id)) return true;
  31593. const { hasModuleSyntax, exports } = exportsData;
  31594. if (!hasModuleSyntax) return true;
  31595. if (output) {
  31596. const generatedExports = output.exports;
  31597. if (isSingleDefaultExport(generatedExports) && !isSingleDefaultExport(exports)) return true;
  31598. }
  31599. return false;
  31600. }
  31601. function isSingleDefaultExport(exports) {
  31602. return exports.length === 1 && exports[0] === "default";
  31603. }
  31604. const lockfileFormats = [
  31605. {
  31606. path: "node_modules/.package-lock.json",
  31607. checkPatchesDir: "patches",
  31608. manager: "npm"
  31609. },
  31610. {
  31611. path: "node_modules/.yarn-state.yml",
  31612. checkPatchesDir: false,
  31613. manager: "yarn"
  31614. },
  31615. {
  31616. path: ".pnp.cjs",
  31617. checkPatchesDir: ".yarn/patches",
  31618. manager: "yarn"
  31619. },
  31620. {
  31621. path: ".pnp.js",
  31622. checkPatchesDir: ".yarn/patches",
  31623. manager: "yarn"
  31624. },
  31625. {
  31626. path: "node_modules/.yarn-integrity",
  31627. checkPatchesDir: "patches",
  31628. manager: "yarn"
  31629. },
  31630. {
  31631. path: "node_modules/.pnpm/lock.yaml",
  31632. checkPatchesDir: false,
  31633. manager: "pnpm"
  31634. },
  31635. {
  31636. path: ".rush/temp/shrinkwrap-deps.json",
  31637. checkPatchesDir: false,
  31638. manager: "pnpm"
  31639. },
  31640. {
  31641. path: "bun.lock",
  31642. checkPatchesDir: "patches",
  31643. manager: "bun"
  31644. },
  31645. {
  31646. path: "bun.lockb",
  31647. checkPatchesDir: "patches",
  31648. manager: "bun"
  31649. }
  31650. ].sort((_, { manager }) => {
  31651. return process.env.npm_config_user_agent?.startsWith(manager) ? 1 : -1;
  31652. });
  31653. const lockfilePaths = lockfileFormats.map((l) => l.path);
  31654. function getConfigHash(environment) {
  31655. const { config } = environment;
  31656. const { optimizeDeps } = config;
  31657. return getHash(JSON.stringify({
  31658. define: !config.keepProcessEnv ? process.env.NODE_ENV || config.mode : null,
  31659. root: config.root,
  31660. resolve: config.resolve,
  31661. assetsInclude: config.assetsInclude,
  31662. plugins: config.plugins.map((p) => p.name),
  31663. optimizeDeps: {
  31664. include: optimizeDeps.include ? unique(optimizeDeps.include).sort() : void 0,
  31665. exclude: optimizeDeps.exclude ? unique(optimizeDeps.exclude).sort() : void 0,
  31666. rolldownOptions: {
  31667. ...optimizeDeps.rolldownOptions,
  31668. plugins: void 0,
  31669. onLog: void 0,
  31670. onwarn: void 0,
  31671. checks: void 0,
  31672. output: {
  31673. ...optimizeDeps.rolldownOptions?.output,
  31674. plugins: void 0
  31675. }
  31676. }
  31677. },
  31678. optimizeDepsPluginNames: config.optimizeDepsPluginNames
  31679. }, (_, value) => {
  31680. if (typeof value === "function" || value instanceof RegExp) return value.toString();
  31681. return value;
  31682. }));
  31683. }
  31684. function getLockfileHash(environment) {
  31685. const lockfilePath = lookupFile(environment.config.root, lockfilePaths);
  31686. let content = lockfilePath ? fs.readFileSync(lockfilePath, "utf-8") : "";
  31687. if (lockfilePath) {
  31688. const normalizedLockfilePath = lockfilePath.replaceAll("\\", "/");
  31689. const lockfileFormat = lockfileFormats.find((f) => normalizedLockfilePath.endsWith(f.path));
  31690. if (lockfileFormat.checkPatchesDir) {
  31691. const baseDir = lockfilePath.slice(0, -lockfileFormat.path.length);
  31692. const stat = tryStatSync(path.join(baseDir, lockfileFormat.checkPatchesDir));
  31693. if (stat?.isDirectory()) content += stat.mtimeMs.toString();
  31694. }
  31695. }
  31696. return getHash(content);
  31697. }
  31698. function getDepHash(environment) {
  31699. const lockfileHash = getLockfileHash(environment);
  31700. const configHash = getConfigHash(environment);
  31701. return {
  31702. hash: getHash(lockfileHash + configHash),
  31703. lockfileHash,
  31704. configHash
  31705. };
  31706. }
  31707. function getOptimizedBrowserHash(hash, deps, timestamp = "") {
  31708. return getHash(hash + JSON.stringify(deps) + timestamp);
  31709. }
  31710. function optimizedDepInfoFromId(metadata, id) {
  31711. return metadata.optimized[id] || metadata.discovered[id] || metadata.chunks[id];
  31712. }
  31713. function optimizedDepInfoFromFile(metadata, file) {
  31714. return metadata.depInfoList.find((depInfo) => depInfo.file === file);
  31715. }
  31716. function findOptimizedDepInfoInRecord(dependenciesInfo, callbackFn) {
  31717. for (const o of Object.keys(dependenciesInfo)) {
  31718. const info = dependenciesInfo[o];
  31719. if (callbackFn(info, o)) return info;
  31720. }
  31721. }
  31722. async function optimizedDepNeedsInterop(environment, metadata, file) {
  31723. const depInfo = optimizedDepInfoFromFile(metadata, file);
  31724. if (depInfo?.src && depInfo.needsInterop === void 0) {
  31725. depInfo.exportsData ??= extractExportsData(environment, depInfo.src);
  31726. depInfo.needsInterop = needsInterop(environment, depInfo.id, await depInfo.exportsData);
  31727. }
  31728. return depInfo?.needsInterop;
  31729. }
  31730. const MAX_TEMP_DIR_AGE_MS = 1440 * 60 * 1e3;
  31731. async function cleanupDepsCacheStaleDirs(config) {
  31732. try {
  31733. const cacheDir = path.resolve(config.cacheDir);
  31734. if (fs.existsSync(cacheDir)) {
  31735. const dirents = await fsp.readdir(cacheDir, { withFileTypes: true });
  31736. for (const dirent of dirents) if (dirent.isDirectory() && dirent.name.includes("_temp_")) {
  31737. const tempDirPath = path.resolve(config.cacheDir, dirent.name);
  31738. const stats = await fsp.stat(tempDirPath).catch(() => null);
  31739. if (stats?.mtime && Date.now() - stats.mtime.getTime() > MAX_TEMP_DIR_AGE_MS) {
  31740. debug$2?.(`removing stale cache temp dir ${tempDirPath}`);
  31741. await fsp.rm(tempDirPath, {
  31742. recursive: true,
  31743. force: true
  31744. });
  31745. }
  31746. }
  31747. }
  31748. } catch (err) {
  31749. config.logger.error(err);
  31750. }
  31751. }
  31752. const GRACEFUL_RENAME_TIMEOUT = 5e3;
  31753. const safeRename = promisify(function gracefulRename(from, to, cb) {
  31754. const start = Date.now();
  31755. let backoff = 0;
  31756. fs.rename(from, to, function CB(er) {
  31757. if (er && (er.code === "EACCES" || er.code === "EPERM") && Date.now() - start < GRACEFUL_RENAME_TIMEOUT) {
  31758. setTimeout(function() {
  31759. fs.stat(to, function(stater, _st) {
  31760. if (stater && stater.code === "ENOENT") fs.rename(from, to, CB);
  31761. else CB(er);
  31762. });
  31763. }, backoff);
  31764. if (backoff < 100) backoff += 10;
  31765. return;
  31766. }
  31767. cb(er);
  31768. });
  31769. });
  31770. //#endregion
  31771. //#region src/node/plugins/resolve.ts
  31772. const normalizedClientEntry = normalizePath(CLIENT_ENTRY);
  31773. const normalizedEnvEntry = normalizePath(ENV_ENTRY);
  31774. const ERR_RESOLVE_PACKAGE_ENTRY_FAIL = "ERR_RESOLVE_PACKAGE_ENTRY_FAIL";
  31775. const browserExternalId = "__vite-browser-external";
  31776. const optionalPeerDepId = "__vite-optional-peer-dep";
  31777. const subpathImportsPrefix = "#";
  31778. const relativePrefixRE = /^\.\.?(?:[/\\]|$)/;
  31779. const startsWithWordCharRE = /^\w/;
  31780. const debug$1 = createDebugger("vite:resolve-details", { onlyWhenFocused: true });
  31781. const perEnvironmentOrWorkerPlugin = (name, overrideEnvConfig, f) => {
  31782. const envs = {};
  31783. const getEnvironmentPlugin = {
  31784. name: `${name}:get-environment`,
  31785. buildStart() {
  31786. envs[this.environment.name] = this.environment;
  31787. },
  31788. perEnvironmentStartEndDuringDev: true
  31789. };
  31790. const createGetEnvironment = (name) => () => envs[name];
  31791. if (overrideEnvConfig) return [getEnvironmentPlugin, f({
  31792. name: "client",
  31793. config: overrideEnvConfig
  31794. }, createGetEnvironment("client"))];
  31795. return [getEnvironmentPlugin, {
  31796. name,
  31797. applyToEnvironment(environment) {
  31798. return f(environment, createGetEnvironment(environment.name));
  31799. }
  31800. }];
  31801. };
  31802. function oxcResolvePlugin(resolveOptions, overrideEnvConfig) {
  31803. return [...resolveOptions.optimizeDeps && !resolveOptions.isBuild ? [optimizerResolvePlugin(resolveOptions)] : [], ...perEnvironmentOrWorkerPlugin("vite:resolve-builtin", overrideEnvConfig, (partialEnv, getEnv) => {
  31804. const depsOptimizerEnabled = resolveOptions.optimizeDeps && !resolveOptions.isBuild && !partialEnv.config.experimental.bundledDev && !isDepOptimizationDisabled(partialEnv.config.optimizeDeps);
  31805. const getDepsOptimizer = () => {
  31806. const env = getEnv();
  31807. if (env.mode !== "dev") throw new Error("The environment mode should be dev");
  31808. if (!env.depsOptimizer) throw new Error("The environment should have a depsOptimizer");
  31809. return env.depsOptimizer;
  31810. };
  31811. const options = {
  31812. ...partialEnv.config.resolve,
  31813. ...resolveOptions
  31814. };
  31815. const noExternal = Array.isArray(options.noExternal) || options.noExternal === true ? options.noExternal : [options.noExternal];
  31816. const plugin = viteResolvePlugin({
  31817. resolveOptions: {
  31818. isBuild: options.isBuild,
  31819. isProduction: options.isProduction,
  31820. asSrc: options.asSrc ?? false,
  31821. preferRelative: options.preferRelative ?? false,
  31822. isRequire: options.isRequire,
  31823. root: options.root,
  31824. scan: options.scan ?? false,
  31825. mainFields: options.skipMainField ? options.mainFields : options.mainFields.concat(["main"]),
  31826. conditions: options.conditions,
  31827. externalConditions: options.externalConditions,
  31828. extensions: options.extensions,
  31829. tryIndex: options.tryIndex ?? true,
  31830. tryPrefix: options.tryPrefix,
  31831. preserveSymlinks: options.preserveSymlinks,
  31832. tsconfigPaths: options.tsconfigPaths
  31833. },
  31834. environmentConsumer: partialEnv.config.consumer,
  31835. environmentName: partialEnv.name,
  31836. builtins: partialEnv.config.resolve.builtins,
  31837. external: options.external,
  31838. noExternal,
  31839. dedupe: options.dedupe,
  31840. disableCache: partialEnv.config.command === "serve" && partialEnv.config.server.watch === null,
  31841. legacyInconsistentCjsInterop: options.legacyInconsistentCjsInterop,
  31842. finalizeBareSpecifier: !depsOptimizerEnabled ? void 0 : (resolvedId, rawId, importer) => {
  31843. const depsOptimizer = getDepsOptimizer();
  31844. const isJsType = isOptimizable(resolvedId, depsOptimizer.options);
  31845. const exclude = depsOptimizer?.options.exclude;
  31846. const deepMatch = deepImportRE.exec(rawId);
  31847. const pkgId = deepMatch ? deepMatch[1] || deepMatch[2] : cleanUrl(rawId);
  31848. const skipOptimization = depsOptimizer.options.noDiscovery || !isJsType || importer && isInNodeModules(importer) || exclude?.includes(pkgId) || exclude?.includes(rawId) || SPECIAL_QUERY_RE.test(resolvedId);
  31849. let newId = resolvedId;
  31850. if (skipOptimization) {
  31851. const versionHash = depsOptimizer.metadata.browserHash;
  31852. if (versionHash && isJsType) newId = injectQuery(newId, `v=${versionHash}`);
  31853. } else {
  31854. const optimizedInfo = depsOptimizer.registerMissingImport(rawId, newId);
  31855. newId = depsOptimizer.getOptimizedDepId(optimizedInfo);
  31856. }
  31857. return newId;
  31858. },
  31859. finalizeOtherSpecifiers: !depsOptimizerEnabled ? void 0 : (resolvedId, rawId) => {
  31860. const newResolvedId = ensureVersionQuery(resolvedId, rawId, options, getDepsOptimizer());
  31861. return newResolvedId === resolvedId ? void 0 : newResolvedId;
  31862. },
  31863. resolveSubpathImports(id, importer, isRequire, scan) {
  31864. return resolveSubpathImports(id, importer, {
  31865. ...options,
  31866. isRequire: resolveOptions.isRequire ?? isRequire,
  31867. scan
  31868. });
  31869. },
  31870. ...partialEnv.config.command === "serve" ? { async onWarn(msg) {
  31871. getEnv().logger.warn(`warning: ${msg}`, {
  31872. clear: true,
  31873. timestamp: true
  31874. });
  31875. } } : {},
  31876. ...debug$1 ? { async onDebug(message) {
  31877. debug$1(message);
  31878. } } : {}
  31879. });
  31880. plugin.perEnvironmentWatchChangeDuringDev = true;
  31881. return plugin;
  31882. })];
  31883. }
  31884. function optimizerResolvePlugin(resolveOptions) {
  31885. const { root, asSrc } = resolveOptions;
  31886. return {
  31887. name: "vite:resolve-dev",
  31888. applyToEnvironment(environment) {
  31889. return !environment.config.experimental.bundledDev && !isDepOptimizationDisabled(environment.config.optimizeDeps);
  31890. },
  31891. resolveId: {
  31892. filter: { id: { exclude: [
  31893. /^\0/,
  31894. /^virtual:/,
  31895. /^\/virtual:/,
  31896. /^__vite-/
  31897. ] } },
  31898. async handler(id, importer, resolveOpts) {
  31899. const depsOptimizer = resolveOptions.optimizeDeps && this.environment.mode === "dev" ? this.environment.depsOptimizer : void 0;
  31900. if (!depsOptimizer) return;
  31901. const options = {
  31902. isRequire: resolveOpts.kind === "require-call",
  31903. ...this.environment.config.resolve,
  31904. ...resolveOptions,
  31905. scan: resolveOpts.scan ?? resolveOptions.scan
  31906. };
  31907. options.preferRelative ||= importer?.endsWith(".html");
  31908. if (asSrc && depsOptimizer.isOptimizedDepUrl(id)) return id.startsWith(FS_PREFIX) ? fsPathFromId(id) : normalizePath(path.resolve(root, id.slice(1)));
  31909. if (!isDataUrl(id) && !isExternalUrl(id)) {
  31910. if (id[0] === "." || options.preferRelative && startsWithWordCharRE.test(id)) {
  31911. const basedir = importer ? path.dirname(importer) : root;
  31912. const normalizedFsPath = normalizePath(path.resolve(basedir, id));
  31913. if (depsOptimizer.isOptimizedDepFile(normalizedFsPath)) {
  31914. if (!DEP_VERSION_RE.test(normalizedFsPath)) {
  31915. const browserHash = optimizedDepInfoFromFile(depsOptimizer.metadata, normalizedFsPath)?.browserHash;
  31916. if (browserHash) return injectQuery(normalizedFsPath, `v=${browserHash}`);
  31917. }
  31918. return normalizedFsPath;
  31919. }
  31920. }
  31921. if (bareImportRE.test(id)) {
  31922. let res;
  31923. if (asSrc && !options.scan && (res = await tryOptimizedResolve(depsOptimizer, id, importer, options.preserveSymlinks, options.packageCache))) return res;
  31924. }
  31925. }
  31926. }
  31927. }
  31928. };
  31929. }
  31930. function resolveSubpathImports(id, importer, options) {
  31931. if (!importer || !id.startsWith(subpathImportsPrefix)) return;
  31932. const basedir = path.dirname(importer);
  31933. const pkgData = findNearestPackageData(basedir, options.packageCache);
  31934. if (!pkgData) return;
  31935. let { file: idWithoutPostfix, postfix } = splitFileAndPostfix(id.slice(1));
  31936. idWithoutPostfix = "#" + idWithoutPostfix;
  31937. let importsPath = resolveExportsOrImports(pkgData.data, idWithoutPostfix, options, "imports");
  31938. if (importsPath?.[0] === ".") {
  31939. importsPath = path.relative(basedir, path.join(pkgData.dir, importsPath));
  31940. if (!relativePrefixRE.test(importsPath)) importsPath = `./${importsPath}`;
  31941. }
  31942. return importsPath + postfix;
  31943. }
  31944. function ensureVersionQuery(resolved, id, options, depsOptimizer) {
  31945. if (!options.isBuild && !options.scan && depsOptimizer && !(resolved === normalizedClientEntry || resolved === normalizedEnvEntry)) {
  31946. if ((isInNodeModules(id) || isInNodeModules(resolved)) && !DEP_VERSION_RE.test(resolved)) {
  31947. const versionHash = depsOptimizer.metadata.browserHash;
  31948. if (versionHash && isOptimizable(resolved, depsOptimizer.options)) resolved = injectQuery(resolved, `v=${versionHash}`);
  31949. }
  31950. }
  31951. return resolved;
  31952. }
  31953. function tryFsResolve(fsPath, options, tryIndex = true, skipPackageJson = false) {
  31954. const hashIndex = fsPath.indexOf("#");
  31955. if (hashIndex >= 0 && isInNodeModules(fsPath)) {
  31956. const queryIndex = fsPath.indexOf("?");
  31957. if (queryIndex < 0 || queryIndex > hashIndex) {
  31958. const file = queryIndex > hashIndex ? fsPath.slice(0, queryIndex) : fsPath;
  31959. const res = tryCleanFsResolve(file, options, tryIndex, skipPackageJson);
  31960. if (res) return res + fsPath.slice(file.length);
  31961. }
  31962. }
  31963. const { file, postfix } = splitFileAndPostfix(fsPath);
  31964. const res = tryCleanFsResolve(file, options, tryIndex, skipPackageJson);
  31965. if (res) return res + postfix;
  31966. }
  31967. const knownTsOutputRE = /\.(?:js|mjs|cjs|jsx)$/;
  31968. const isPossibleTsOutput = (url) => knownTsOutputRE.test(url);
  31969. function tryCleanFsResolve(file, options, tryIndex = true, skipPackageJson = false) {
  31970. const { tryPrefix, extensions, preserveSymlinks } = options;
  31971. const fileResult = tryResolveRealFileOrType(file, options.preserveSymlinks);
  31972. if (fileResult?.path) return fileResult.path;
  31973. let res;
  31974. const possibleJsToTs = isPossibleTsOutput(file);
  31975. if (possibleJsToTs || options.extensions.length || tryPrefix) {
  31976. const dirPath = path.dirname(file);
  31977. if (isDirectory(dirPath)) {
  31978. if (possibleJsToTs) {
  31979. const fileExt = path.extname(file);
  31980. const fileName = file.slice(0, -fileExt.length);
  31981. if (res = tryResolveRealFile(fileName + fileExt.replace("js", "ts"), preserveSymlinks)) return res;
  31982. if (fileExt === ".js" && (res = tryResolveRealFile(fileName + ".tsx", preserveSymlinks))) return res;
  31983. }
  31984. if (res = tryResolveRealFileWithExtensions(file, extensions, preserveSymlinks)) return res;
  31985. if (tryPrefix) {
  31986. const prefixed = `${dirPath}/${options.tryPrefix}${path.basename(file)}`;
  31987. if (res = tryResolveRealFile(prefixed, preserveSymlinks)) return res;
  31988. if (res = tryResolveRealFileWithExtensions(prefixed, extensions, preserveSymlinks)) return res;
  31989. }
  31990. }
  31991. }
  31992. if (tryIndex && fileResult?.type === "directory") {
  31993. const dirPath = file;
  31994. if (!skipPackageJson) {
  31995. let pkgPath = `${dirPath}/package.json`;
  31996. try {
  31997. if (fs.existsSync(pkgPath)) {
  31998. if (!options.preserveSymlinks) pkgPath = safeRealpathSync(pkgPath);
  31999. return resolvePackageEntry(dirPath, loadPackageData(pkgPath), options);
  32000. }
  32001. } catch (e) {
  32002. if (e.code !== ERR_RESOLVE_PACKAGE_ENTRY_FAIL && e.code !== "ENOENT") throw e;
  32003. }
  32004. }
  32005. if (res = tryResolveRealFileWithExtensions(`${dirPath}/index`, extensions, preserveSymlinks)) return res;
  32006. if (tryPrefix) {
  32007. if (res = tryResolveRealFileWithExtensions(`${dirPath}/${options.tryPrefix}index`, extensions, preserveSymlinks)) return res;
  32008. }
  32009. }
  32010. }
  32011. function tryNodeResolve(id, importer, options, depsOptimizer, externalize) {
  32012. const { root, dedupe, isBuild, preserveSymlinks, packageCache } = options;
  32013. const deepMatch = deepImportRE.exec(id);
  32014. const pkgId = deepMatch ? deepMatch[1] || deepMatch[2] : cleanUrl(id);
  32015. let basedir;
  32016. if (dedupe.includes(pkgId)) basedir = root;
  32017. else if (importer && path.isAbsolute(importer) && (importer.endsWith("*") || fs.existsSync(cleanUrl(importer)))) basedir = path.dirname(importer);
  32018. else basedir = root;
  32019. const isModuleBuiltin = (id) => isBuiltin(options.builtins, id);
  32020. let selfPkg = null;
  32021. if (!isModuleBuiltin(id) && !id.includes("\0") && bareImportRE.test(id)) {
  32022. const selfPackageData = findNearestPackageData(basedir, packageCache);
  32023. selfPkg = selfPackageData?.data.exports && selfPackageData.data.name === pkgId ? selfPackageData : null;
  32024. }
  32025. const pkg = selfPkg || resolvePackageData(pkgId, basedir, preserveSymlinks, packageCache);
  32026. if (!pkg) {
  32027. if (!options.disableOptionalPeerDepHandling && basedir !== root && !isModuleBuiltin(id) && !id.includes("\0") && bareImportRE.test(id)) {
  32028. const mainPkg = findNearestMainPackageData(basedir, packageCache)?.data;
  32029. if (mainPkg) {
  32030. const pkgName = getNpmPackageName(id);
  32031. if (pkgName != null && mainPkg.peerDependencies?.[pkgName] && mainPkg.peerDependenciesMeta?.[pkgName]?.optional) return { id: `${optionalPeerDepId}:${id}:${mainPkg.name}` };
  32032. }
  32033. }
  32034. return;
  32035. }
  32036. let resolved = (deepMatch ? resolveDeepImport : resolvePackageEntry)(deepMatch ? "." + id.slice(pkgId.length) : id, pkg, options, externalize);
  32037. if (!resolved) return;
  32038. const processResult = (resolved) => {
  32039. if (!externalize) return resolved;
  32040. if (!canExternalizeFile(resolved.id)) return resolved;
  32041. let resolvedId = id;
  32042. if (deepMatch && !pkg.data.exports && path.extname(id) !== path.extname(resolved.id)) {
  32043. const index = resolved.id.indexOf(id);
  32044. if (index > -1) {
  32045. resolvedId = resolved.id.slice(index);
  32046. debug$1?.(`[processResult] ${import_picocolors.default.cyan(id)} -> ${import_picocolors.default.dim(resolvedId)}`);
  32047. }
  32048. }
  32049. return {
  32050. ...resolved,
  32051. id: resolvedId,
  32052. external: true
  32053. };
  32054. };
  32055. if (!options.idOnly && (!options.scan && isBuild || externalize)) return processResult({
  32056. id: resolved,
  32057. moduleSideEffects: pkg.hasSideEffects(resolved),
  32058. packageJsonPath: findNearestPackagePath(resolved, options.legacyInconsistentCjsInterop, options.packageCache, isBuild)
  32059. });
  32060. if (!isInNodeModules(resolved) || !depsOptimizer || options.scan) return { id: resolved };
  32061. const isJsType = isOptimizable(resolved, depsOptimizer.options);
  32062. const exclude = depsOptimizer.options.exclude;
  32063. if (depsOptimizer.options.noDiscovery || !isJsType || importer && isInNodeModules(importer) || exclude?.includes(pkgId) || exclude?.includes(id) || SPECIAL_QUERY_RE.test(resolved)) {
  32064. const versionHash = depsOptimizer.metadata.browserHash;
  32065. if (versionHash && isJsType) resolved = injectQuery(resolved, `v=${versionHash}`);
  32066. } else {
  32067. const optimizedInfo = depsOptimizer.registerMissingImport(id, resolved);
  32068. resolved = depsOptimizer.getOptimizedDepId(optimizedInfo);
  32069. }
  32070. return { id: resolved };
  32071. }
  32072. async function tryOptimizedResolve(depsOptimizer, id, importer, preserveSymlinks, packageCache) {
  32073. await depsOptimizer.scanProcessing;
  32074. const metadata = depsOptimizer.metadata;
  32075. const depInfo = optimizedDepInfoFromId(metadata, id);
  32076. if (depInfo) return depsOptimizer.getOptimizedDepId(depInfo);
  32077. if (!importer) return;
  32078. let idPkgDir;
  32079. const nestedIdMatch = `> ${id}`;
  32080. for (const optimizedData of metadata.depInfoList) {
  32081. if (!optimizedData.src) continue;
  32082. if (!optimizedData.id.endsWith(nestedIdMatch)) continue;
  32083. if (idPkgDir == null) {
  32084. const pkgName = getNpmPackageName(id);
  32085. if (!pkgName) break;
  32086. idPkgDir = resolvePackageData(pkgName, importer, preserveSymlinks, packageCache)?.dir;
  32087. if (idPkgDir == null) break;
  32088. idPkgDir = normalizePath(idPkgDir);
  32089. }
  32090. if (optimizedData.src.startsWith(withTrailingSlash(idPkgDir))) return depsOptimizer.getOptimizedDepId(optimizedData);
  32091. }
  32092. }
  32093. function resolvePackageEntry(id, { dir, data, setResolvedCache, getResolvedCache }, options, externalize) {
  32094. const { file: idWithoutPostfix, postfix } = splitFileAndPostfix(id);
  32095. const cached = getResolvedCache(".", options);
  32096. if (cached) return cached + postfix;
  32097. try {
  32098. let entryPoint;
  32099. if (data.exports) entryPoint = resolveExportsOrImports(data, ".", options, "exports", externalize);
  32100. if (!entryPoint) {
  32101. for (const field of options.mainFields) if (field === "browser") {
  32102. entryPoint = tryResolveBrowserEntry(dir, data, options);
  32103. if (entryPoint) break;
  32104. } else if (typeof data[field] === "string") {
  32105. entryPoint = data[field];
  32106. break;
  32107. }
  32108. }
  32109. entryPoint ||= data.main;
  32110. const entryPoints = entryPoint ? [entryPoint] : [
  32111. "index.js",
  32112. "index.json",
  32113. "index.node"
  32114. ];
  32115. for (let entry of entryPoints) {
  32116. let skipPackageJson = false;
  32117. if (options.mainFields[0] === "sass" && !options.extensions.includes(path.extname(entry))) {
  32118. entry = "";
  32119. skipPackageJson = true;
  32120. } else {
  32121. const { browser: browserField } = data;
  32122. if (options.mainFields.includes("browser") && isObject$1(browserField)) entry = mapWithBrowserField(entry, browserField) || entry;
  32123. }
  32124. const resolvedEntryPoint = tryFsResolve(path.join(dir, entry), options, true, skipPackageJson);
  32125. if (resolvedEntryPoint) {
  32126. debug$1?.(`[package entry] ${import_picocolors.default.cyan(idWithoutPostfix)} -> ${import_picocolors.default.dim(resolvedEntryPoint)}${postfix !== "" ? ` (postfix: ${postfix})` : ""}`);
  32127. setResolvedCache(".", resolvedEntryPoint, options);
  32128. return resolvedEntryPoint + postfix;
  32129. }
  32130. }
  32131. } catch (e) {
  32132. packageEntryFailure(id, e.message);
  32133. }
  32134. packageEntryFailure(id);
  32135. }
  32136. function packageEntryFailure(id, details) {
  32137. 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 : "."));
  32138. err.code = ERR_RESOLVE_PACKAGE_ENTRY_FAIL;
  32139. throw err;
  32140. }
  32141. function getConditions(conditions, isProduction, isRequire) {
  32142. const resolvedConditions = conditions.map((condition) => {
  32143. if (condition === DEV_PROD_CONDITION) return isProduction ? "production" : "development";
  32144. return condition;
  32145. });
  32146. if (isRequire) resolvedConditions.push("require");
  32147. else resolvedConditions.push("import");
  32148. return resolvedConditions;
  32149. }
  32150. function resolveExportsOrImports(pkg, key, options, type, externalize) {
  32151. const conditions = getConditions(externalize ? options.externalConditions : options.conditions, options.isProduction, options.isRequire);
  32152. const result = (type === "imports" ? f : o)(pkg, key, {
  32153. conditions,
  32154. unsafe: true
  32155. });
  32156. return result ? result[0] : void 0;
  32157. }
  32158. function resolveDeepImport(id, { setResolvedCache, getResolvedCache, dir, data }, options, externalize) {
  32159. const cache = getResolvedCache(id, options);
  32160. if (cache) return cache;
  32161. let relativeId = id;
  32162. const { exports: exportsField, browser: browserField } = data;
  32163. if (exportsField) {
  32164. if (isObject$1(exportsField) && !Array.isArray(exportsField)) {
  32165. const { file, postfix } = splitFileAndPostfix(relativeId);
  32166. const exportsId = resolveExportsOrImports(data, file, options, "exports", externalize);
  32167. if (exportsId !== void 0) relativeId = exportsId + postfix;
  32168. else relativeId = void 0;
  32169. } else relativeId = void 0;
  32170. if (!relativeId) throw new Error(`Package subpath '${relativeId}' is not defined by "exports" in ${path.join(dir, "package.json")}.`);
  32171. } else if (options.mainFields.includes("browser") && isObject$1(browserField)) {
  32172. const { file, postfix } = splitFileAndPostfix(relativeId);
  32173. const mapped = mapWithBrowserField(file, browserField);
  32174. if (mapped) relativeId = mapped + postfix;
  32175. else if (mapped === false) {
  32176. setResolvedCache(id, browserExternalId, options);
  32177. return browserExternalId;
  32178. }
  32179. }
  32180. if (relativeId) {
  32181. const resolved = tryFsResolve(path.join(dir, relativeId), options, !exportsField);
  32182. if (resolved) {
  32183. debug$1?.(`[node/deep-import] ${import_picocolors.default.cyan(id)} -> ${import_picocolors.default.dim(resolved)}`);
  32184. setResolvedCache(id, resolved, options);
  32185. return resolved;
  32186. }
  32187. }
  32188. }
  32189. function tryResolveBrowserEntry(dir, data, options) {
  32190. const browserEntry = typeof data.browser === "string" ? data.browser : isObject$1(data.browser) && data.browser["."];
  32191. if (browserEntry) if (!options.isRequire && options.mainFields.includes("module") && typeof data.module === "string" && data.module !== browserEntry) {
  32192. const resolvedBrowserEntry = tryFsResolve(path.join(dir, browserEntry), options);
  32193. if (resolvedBrowserEntry) if (hasESMSyntax(fs.readFileSync(resolvedBrowserEntry, "utf-8"))) return browserEntry;
  32194. else return data.module;
  32195. } else return browserEntry;
  32196. }
  32197. /**
  32198. * given a relative path in pkg dir,
  32199. * return a relative path in pkg dir,
  32200. * mapped with the "map" object
  32201. *
  32202. * - Returning `undefined` means there is no browser mapping for this id
  32203. * - Returning `false` means this id is explicitly externalized for browser
  32204. */
  32205. function mapWithBrowserField(relativePathInPkgDir, map) {
  32206. const normalizedPath = path.posix.normalize(relativePathInPkgDir);
  32207. for (const key in map) {
  32208. const normalizedKey = path.posix.normalize(key);
  32209. if (normalizedPath === normalizedKey || equalWithoutSuffix(normalizedPath, normalizedKey, ".js") || equalWithoutSuffix(normalizedPath, normalizedKey, "/index.js")) return map[key];
  32210. }
  32211. }
  32212. function equalWithoutSuffix(path, key, suffix) {
  32213. return key.endsWith(suffix) && key.slice(0, -suffix.length) === path;
  32214. }
  32215. function tryResolveRealFile(file, preserveSymlinks) {
  32216. if (tryStatSync(file)?.isFile()) return getRealPath(file, preserveSymlinks);
  32217. }
  32218. function tryResolveRealFileWithExtensions(filePath, extensions, preserveSymlinks) {
  32219. for (const ext of extensions) {
  32220. const res = tryResolveRealFile(filePath + ext, preserveSymlinks);
  32221. if (res) return res;
  32222. }
  32223. }
  32224. function tryResolveRealFileOrType(file, preserveSymlinks) {
  32225. const fileStat = tryStatSync(file);
  32226. if (fileStat?.isFile()) return {
  32227. path: getRealPath(file, preserveSymlinks),
  32228. type: "file"
  32229. };
  32230. if (fileStat?.isDirectory()) return { type: "directory" };
  32231. }
  32232. function getRealPath(resolved, preserveSymlinks) {
  32233. if (!preserveSymlinks) resolved = safeRealpathSync(resolved);
  32234. return normalizePath(resolved);
  32235. }
  32236. function isDirectory(path) {
  32237. return tryStatSync(path)?.isDirectory() ?? false;
  32238. }
  32239. function findNearestPackagePath(file, legacyInconsistentCjsInterop, packageCache, isBuild) {
  32240. if (!isBuild || legacyInconsistentCjsInterop) return;
  32241. const pkgData = findNearestPackageData(file, packageCache);
  32242. return pkgData ? path.join(pkgData.dir, "package.json") : null;
  32243. }
  32244. //#endregion
  32245. //#region src/node/nodeResolve.ts
  32246. /**
  32247. * Resolve like Node.js using Vite's resolution algorithm with preconfigured options.
  32248. */
  32249. function nodeResolveWithVite(id, importer, options) {
  32250. return tryNodeResolve(id, importer, {
  32251. root: options.root,
  32252. isBuild: true,
  32253. isProduction: true,
  32254. preferRelative: false,
  32255. tryIndex: true,
  32256. mainFields: [],
  32257. conditions: ["node", ...isModuleSyncConditionEnabled ? ["module-sync"] : []],
  32258. externalConditions: [],
  32259. external: [],
  32260. noExternal: [],
  32261. dedupe: [],
  32262. extensions: DEFAULT_EXTENSIONS,
  32263. preserveSymlinks: false,
  32264. tsconfigPaths: false,
  32265. packageCache: void 0,
  32266. isRequire: options.isRequire,
  32267. builtins: nodeLikeBuiltins,
  32268. disableOptionalPeerDepHandling: true
  32269. })?.id;
  32270. }
  32271. //#endregion
  32272. //#region src/node/plugins/terser.ts
  32273. let terserPath;
  32274. function loadTerserPath(root) {
  32275. if (terserPath) return terserPath;
  32276. const resolved = nodeResolveWithVite("terser", void 0, { root }) ?? nodeResolveWithVite("terser", _dirname, { root });
  32277. if (resolved) return terserPath = resolved;
  32278. throw new Error("terser not found. Since Vite v3, terser has become an optional dependency. You need to install it.");
  32279. }
  32280. function terserPlugin(config) {
  32281. const { maxWorkers, ...terserOptions } = config.build.terserOptions;
  32282. const makeWorker = () => new WorkerWithFallback(() => async (terserPath, code, options) => {
  32283. const terser = await import(terserPath);
  32284. try {
  32285. return await terser.minify(code, options);
  32286. } catch (e) {
  32287. throw {
  32288. stack: e.stack,
  32289. ...e
  32290. };
  32291. }
  32292. }, {
  32293. shouldUseFake(_terserPath, _code, options) {
  32294. 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);
  32295. },
  32296. max: maxWorkers
  32297. });
  32298. let worker;
  32299. return {
  32300. name: "vite:terser",
  32301. applyToEnvironment(environment) {
  32302. return !!environment.config.build.minify;
  32303. },
  32304. async renderChunk(code, chunk, outputOptions) {
  32305. if (config.build.minify !== "terser" && !this.environment.config.isOutputOptionsForLegacyChunks?.(outputOptions)) return null;
  32306. worker ||= makeWorker();
  32307. const terserPath = pathToFileURL(loadTerserPath(config.root)).href;
  32308. try {
  32309. const res = await worker.run(terserPath, code, {
  32310. safari10: true,
  32311. ...terserOptions,
  32312. format: {
  32313. ...terserOptions.format,
  32314. preserve_annotations: config.build.lib && outputOptions.format === "es" ? true : terserOptions.format?.preserve_annotations
  32315. },
  32316. sourceMap: !!outputOptions.sourcemap,
  32317. module: outputOptions.format.startsWith("es"),
  32318. toplevel: outputOptions.format === "cjs"
  32319. });
  32320. return {
  32321. code: res.code,
  32322. map: res.map
  32323. };
  32324. } catch (e) {
  32325. if (e.line !== void 0 && e.col !== void 0) e.loc = {
  32326. file: chunk.fileName,
  32327. line: e.line,
  32328. column: e.col
  32329. };
  32330. if (e.pos !== void 0) e.frame = generateCodeFrame(code, e.pos);
  32331. throw e;
  32332. }
  32333. },
  32334. closeBundle() {
  32335. worker?.stop();
  32336. }
  32337. };
  32338. }
  32339. //#endregion
  32340. //#region src/node/ssr/ssrManifestPlugin.ts
  32341. function ssrManifestPlugin() {
  32342. const getSsrManifest = perEnvironmentState(() => {
  32343. return {};
  32344. });
  32345. return {
  32346. name: "vite:ssr-manifest",
  32347. applyToEnvironment(environment) {
  32348. return !!environment.config.build.ssrManifest;
  32349. },
  32350. generateBundle(_options, bundle) {
  32351. const config = this.environment.config;
  32352. const ssrManifest = getSsrManifest(this);
  32353. const { base } = config;
  32354. for (const file in bundle) {
  32355. const chunk = bundle[file];
  32356. if (chunk.type === "chunk") {
  32357. for (const id in chunk.modules) {
  32358. const normalizedId = normalizePath(relative(config.root, id));
  32359. const mappedChunks = ssrManifest[normalizedId] ?? (ssrManifest[normalizedId] = []);
  32360. if (!chunk.isEntry) {
  32361. mappedChunks.push(joinUrlSegments(base, chunk.fileName));
  32362. chunk.viteMetadata.importedCss.forEach((file) => {
  32363. mappedChunks.push(joinUrlSegments(base, file));
  32364. });
  32365. }
  32366. chunk.viteMetadata.importedAssets.forEach((file) => {
  32367. mappedChunks.push(joinUrlSegments(base, file));
  32368. });
  32369. }
  32370. if (chunk.code.includes(preloadMethod)) {
  32371. const code = chunk.code;
  32372. let imports = [];
  32373. try {
  32374. imports = parse$2(code)[0].filter((i) => i.n && i.d > -1);
  32375. } catch (_e) {
  32376. const e = _e;
  32377. const loc = numberToPos(code, e.idx);
  32378. this.error({
  32379. name: e.name,
  32380. message: e.message,
  32381. stack: e.stack,
  32382. cause: e.cause,
  32383. pos: e.idx,
  32384. loc: {
  32385. ...loc,
  32386. file: chunk.fileName
  32387. },
  32388. frame: generateCodeFrame(code, loc)
  32389. });
  32390. }
  32391. if (imports.length) for (let index = 0; index < imports.length; index++) {
  32392. const { s: start, e: end, n: name } = imports[index];
  32393. const url = code.slice(start, end);
  32394. const deps = [];
  32395. const ownerFilename = chunk.fileName;
  32396. const analyzed = /* @__PURE__ */ new Set();
  32397. const addDeps = (filename) => {
  32398. if (filename === ownerFilename) return;
  32399. if (analyzed.has(filename)) return;
  32400. analyzed.add(filename);
  32401. const chunk = bundle[filename];
  32402. if (chunk) {
  32403. chunk.viteMetadata.importedCss.forEach((file) => {
  32404. deps.push(joinUrlSegments(base, file));
  32405. });
  32406. chunk.imports.forEach(addDeps);
  32407. }
  32408. };
  32409. addDeps(normalizePath(join(dirname(chunk.fileName), url.slice(1, -1))));
  32410. ssrManifest[basename(name)] = deps;
  32411. }
  32412. }
  32413. }
  32414. }
  32415. this.emitFile({
  32416. fileName: typeof config.build.ssrManifest === "string" ? config.build.ssrManifest : ".vite/ssr-manifest.json",
  32417. type: "asset",
  32418. source: JSON.stringify(sortObjectKeys(ssrManifest), void 0, 2)
  32419. });
  32420. }
  32421. };
  32422. }
  32423. //#endregion
  32424. //#region src/node/plugins/license.ts
  32425. const licenseConfigDefaults = Object.freeze({ fileName: ".vite/license.md" });
  32426. const licenseFiles = [
  32427. /^license/i,
  32428. /^licence/i,
  32429. /^copying/i
  32430. ];
  32431. function licensePlugin() {
  32432. return {
  32433. name: "vite:license",
  32434. async generateBundle(_, bundle) {
  32435. const licenseOption = this.environment.config.build.license;
  32436. if (licenseOption === false) return;
  32437. const packageCache = /* @__PURE__ */ new Map();
  32438. const licenses = {};
  32439. for (const file in bundle) {
  32440. const chunk = bundle[file];
  32441. if (chunk.type === "asset") continue;
  32442. for (const moduleId of chunk.moduleIds) {
  32443. if (moduleId.startsWith("\0") || !isInNodeModules(moduleId)) continue;
  32444. const pkgData = findNearestMainPackageData(path.dirname(moduleId), packageCache);
  32445. if (!pkgData) continue;
  32446. const { name, version = "0.0.0", license } = pkgData.data;
  32447. const key = `${name}@${version}`;
  32448. if (licenses[key]) continue;
  32449. const entry = {
  32450. name,
  32451. version
  32452. };
  32453. if (license) entry.identifier = license.trim();
  32454. const licenseFile = findLicenseFile(pkgData.dir);
  32455. if (licenseFile) entry.text = fs.readFileSync(licenseFile, "utf-8").trim();
  32456. licenses[key] = entry;
  32457. }
  32458. }
  32459. const licenseEntries = Object.values(sortObjectKeys(licenses));
  32460. const licenseOutputFileName = typeof licenseOption === "object" ? licenseOption.fileName : licenseConfigDefaults.fileName;
  32461. if (licenseOutputFileName.endsWith(".json")) {
  32462. this.emitFile({
  32463. fileName: licenseOutputFileName,
  32464. type: "asset",
  32465. source: JSON.stringify(licenseEntries, null, 2)
  32466. });
  32467. return;
  32468. }
  32469. const markdown = licenseEntryToMarkdown(licenseEntries);
  32470. this.emitFile({
  32471. fileName: licenseOutputFileName,
  32472. type: "asset",
  32473. source: markdown
  32474. });
  32475. }
  32476. };
  32477. }
  32478. function licenseEntryToMarkdown(licenses) {
  32479. if (licenses.length === 0) return `\
  32480. # Licenses
  32481. The app does not bundle any dependencies with licenses.
  32482. `;
  32483. let text = `\
  32484. # Licenses
  32485. The app bundles dependencies which contain the following licenses:
  32486. `;
  32487. for (const license of licenses) {
  32488. const nameAndVersionText = `${license.name} - ${license.version}`;
  32489. const identifierText = license.identifier ? ` (${license.identifier})` : "";
  32490. text += `\n## ${nameAndVersionText}${identifierText}\n`;
  32491. if (license.text) text += `\n${license.text}\n`;
  32492. }
  32493. return text;
  32494. }
  32495. function findLicenseFile(pkgDir) {
  32496. const matchedFile = fs.readdirSync(pkgDir).find((file) => licenseFiles.some((re) => re.test(file)));
  32497. if (matchedFile) return path.join(pkgDir, matchedFile);
  32498. }
  32499. //#endregion
  32500. //#region src/node/plugins/prepareOutDir.ts
  32501. function prepareOutDirPlugin() {
  32502. const rendered = /* @__PURE__ */ new Set();
  32503. return {
  32504. name: "vite:prepare-out-dir",
  32505. options() {
  32506. rendered.delete(this.environment);
  32507. },
  32508. renderStart: {
  32509. order: "pre",
  32510. handler() {
  32511. if (rendered.has(this.environment)) return;
  32512. rendered.add(this.environment);
  32513. const { config } = this.environment;
  32514. if (config.build.write) {
  32515. const { root, build: options } = config;
  32516. const resolvedOutDirs = getResolvedOutDirs(root, options.outDir, options.rollupOptions.output);
  32517. prepareOutDir(resolvedOutDirs, resolveEmptyOutDir(options.emptyOutDir, root, resolvedOutDirs, this.environment.logger), this.environment);
  32518. }
  32519. }
  32520. }
  32521. };
  32522. }
  32523. function prepareOutDir(outDirs, emptyOutDir, environment) {
  32524. const { publicDir } = environment.config;
  32525. const outDirsArray = [...outDirs];
  32526. for (const outDir of outDirs) {
  32527. if (emptyOutDir !== false && fs.existsSync(outDir)) emptyDir(outDir, [...outDirsArray.map((dir) => {
  32528. const relative = path.relative(outDir, dir);
  32529. if (relative && !relative.startsWith("..") && !path.isAbsolute(relative)) return relative;
  32530. return "";
  32531. }).filter(Boolean), ".git"]);
  32532. if (environment.config.build.copyPublicDir && publicDir && fs.existsSync(publicDir)) {
  32533. 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`));
  32534. copyDir(publicDir, outDir);
  32535. }
  32536. }
  32537. }
  32538. function areSeparateFolders(a, b) {
  32539. const na = normalizePath(a);
  32540. const nb = normalizePath(b);
  32541. return na !== nb && !na.startsWith(withTrailingSlash(nb)) && !nb.startsWith(withTrailingSlash(na));
  32542. }
  32543. //#endregion
  32544. //#region src/node/build.ts
  32545. const _buildEnvironmentOptionsDefaults = Object.freeze({
  32546. target: "baseline-widely-available",
  32547. polyfillModulePreload: true,
  32548. modulePreload: true,
  32549. outDir: "dist",
  32550. assetsDir: "assets",
  32551. assetsInlineLimit: DEFAULT_ASSETS_INLINE_LIMIT,
  32552. sourcemap: false,
  32553. terserOptions: {},
  32554. rolldownOptions: {},
  32555. commonjsOptions: {
  32556. include: [/node_modules/],
  32557. extensions: [".js", ".cjs"]
  32558. },
  32559. dynamicImportVarsOptions: { exclude: [/node_modules/] },
  32560. write: true,
  32561. emptyOutDir: null,
  32562. copyPublicDir: true,
  32563. license: false,
  32564. manifest: false,
  32565. lib: false,
  32566. ssrManifest: false,
  32567. ssrEmitAssets: false,
  32568. reportCompressedSize: true,
  32569. chunkSizeWarningLimit: 500,
  32570. watch: null
  32571. });
  32572. const buildEnvironmentOptionsDefaults = _buildEnvironmentOptionsDefaults;
  32573. function resolveBuildEnvironmentOptions(raw, logger, consumer, isBundledDev) {
  32574. const deprecatedPolyfillModulePreload = raw.polyfillModulePreload;
  32575. const { polyfillModulePreload, ...rest } = raw;
  32576. raw = rest;
  32577. if (deprecatedPolyfillModulePreload !== void 0) logger.warn("polyfillModulePreload is deprecated. Use modulePreload.polyfill instead.");
  32578. if (deprecatedPolyfillModulePreload === false && raw.modulePreload === void 0) raw.modulePreload = { polyfill: false };
  32579. const merged = mergeWithDefaults({
  32580. ..._buildEnvironmentOptionsDefaults,
  32581. cssCodeSplit: !raw.lib,
  32582. minify: consumer === "server" || isBundledDev ? false : "oxc",
  32583. rollupOptions: {},
  32584. rolldownOptions: void 0,
  32585. ssr: consumer === "server",
  32586. emitAssets: consumer === "client",
  32587. createEnvironment: (name, config) => new BuildEnvironment(name, config)
  32588. }, raw);
  32589. setupRollupOptionCompat(merged, "build");
  32590. merged.rolldownOptions = {
  32591. platform: consumer === "server" ? "node" : "browser",
  32592. ...merged.rolldownOptions
  32593. };
  32594. if (merged.target === "baseline-widely-available") merged.target = ESBUILD_BASELINE_WIDELY_AVAILABLE_TARGET;
  32595. if (Array.isArray(merged.target)) merged.target = unique(merged.target);
  32596. if (merged.minify === "false") merged.minify = false;
  32597. else if (merged.minify === true) merged.minify = "oxc";
  32598. const defaultModulePreload = { polyfill: true };
  32599. return {
  32600. ...merged,
  32601. cssTarget: merged.cssTarget ?? merged.target,
  32602. cssMinify: merged.cssMinify ?? (consumer === "server" ? "lightningcss" : !!merged.minify),
  32603. modulePreload: merged.modulePreload === false ? false : merged.modulePreload === true ? defaultModulePreload : {
  32604. ...defaultModulePreload,
  32605. ...merged.modulePreload
  32606. }
  32607. };
  32608. }
  32609. async function resolveBuildPlugins(config) {
  32610. const isBuild = config.command === "build";
  32611. return {
  32612. pre: [
  32613. ...isBuild && !config.isWorker ? [prepareOutDirPlugin()] : [],
  32614. perEnvironmentPlugin("vite:rollup-options-plugins", async (environment) => (await asyncFlatten(arraify(environment.config.build.rollupOptions.plugins))).filter(Boolean)),
  32615. ...config.isWorker ? [webWorkerPostPlugin(config)] : []
  32616. ],
  32617. post: [
  32618. ...isBuild ? buildImportAnalysisPlugin(config) : [],
  32619. ...config.build.minify === "esbuild" ? [buildEsbuildPlugin()] : [],
  32620. ...isBuild ? [terserPlugin(config)] : [],
  32621. ...isBuild && !config.isWorker ? [
  32622. licensePlugin(),
  32623. manifestPlugin(),
  32624. ssrManifestPlugin(),
  32625. buildReporterPlugin(config)
  32626. ] : [],
  32627. viteLoadFallbackPlugin()
  32628. ]
  32629. };
  32630. }
  32631. /**
  32632. * Bundles a single environment for production.
  32633. * Returns a Promise containing the build result.
  32634. */
  32635. async function build(inlineConfig = {}) {
  32636. const builder = await createBuilder(inlineConfig, true);
  32637. const environment = Object.values(builder.environments)[0];
  32638. if (!environment) throw new Error("No environment found");
  32639. return builder.build(environment);
  32640. }
  32641. function resolveConfigToBuild(inlineConfig = {}, patchConfig, patchPlugins) {
  32642. return resolveConfig(inlineConfig, "build", "production", "production", false, patchConfig, patchPlugins);
  32643. }
  32644. function resolveRolldownOptions(environment, chunkMetadataMap) {
  32645. const { root, packageCache, build: options } = environment.config;
  32646. const libOptions = options.lib;
  32647. const { logger } = environment;
  32648. const ssr = environment.config.consumer === "server";
  32649. const resolve = (p) => path.resolve(root, p);
  32650. 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");
  32651. 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.");
  32652. if (options.cssCodeSplit === false) {
  32653. 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.`);
  32654. }
  32655. const outDir = resolve(options.outDir);
  32656. const plugins = environment.plugins.map((p) => injectEnvironmentToHooks(environment, chunkMetadataMap, p));
  32657. const rollupOptions = {
  32658. preserveEntrySignatures: ssr ? "allow-extension" : libOptions ? "strict" : false,
  32659. ...options.rollupOptions,
  32660. output: options.rollupOptions.output,
  32661. input,
  32662. plugins,
  32663. external: options.rollupOptions.external,
  32664. onLog(level, log) {
  32665. onRollupLog(level, log, environment);
  32666. },
  32667. transform: {
  32668. target: options.target === false ? void 0 : options.target,
  32669. ...options.rollupOptions.transform,
  32670. define: {
  32671. ...options.rollupOptions.transform?.define,
  32672. "process.env.NODE_ENV": "process.env.NODE_ENV"
  32673. }
  32674. },
  32675. moduleTypes: {
  32676. ...options.rollupOptions.moduleTypes,
  32677. ".css": "js"
  32678. },
  32679. experimental: {
  32680. ...options.rollupOptions.experimental,
  32681. viteMode: true
  32682. }
  32683. };
  32684. const isSsrTargetWebworkerEnvironment = environment.name === "ssr" && environment.getTopLevelConfig().ssr?.target === "webworker";
  32685. const buildOutputOptions = (output = {}) => {
  32686. 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.");
  32687. if (output.file) throw new Error("Vite does not support \"rollupOptions.output.file\". Please use \"rollupOptions.output.dir\" and \"rollupOptions.output.entryFileNames\" instead.");
  32688. if (output.sourcemap) logger.warnOnce(import_picocolors.default.yellow("Vite does not support \"rollupOptions.output.sourcemap\". Please use \"build.sourcemap\" instead."));
  32689. const format = output.format || "es";
  32690. const jsExt = ssr && !isSsrTargetWebworkerEnvironment || libOptions ? resolveOutputJsExtension(format, findNearestPackageData(root, packageCache)?.data.type) : "js";
  32691. return {
  32692. dir: outDir,
  32693. format,
  32694. exports: "auto",
  32695. sourcemap: options.sourcemap,
  32696. name: libOptions ? libOptions.name : void 0,
  32697. generatedCode: { preset: "es2015" },
  32698. entryFileNames: ssr ? `[name].${jsExt}` : libOptions ? ({ name }) => resolveLibFilename(libOptions, format, name, root, jsExt, packageCache) : path.posix.join(options.assetsDir, `[name]-[hash].${jsExt}`),
  32699. chunkFileNames: libOptions ? `[name]-[hash].${jsExt}` : path.posix.join(options.assetsDir, `[name]-[hash].${jsExt}`),
  32700. assetFileNames: libOptions ? `[name].[ext]` : path.posix.join(options.assetsDir, `[name]-[hash].[ext]`),
  32701. codeSplitting: output.codeSplitting ?? (output.format === "umd" || output.format === "iife" || isSsrTargetWebworkerEnvironment && (typeof input === "string" || Object.keys(input).length === 1) ? false : void 0),
  32702. comments: typeof output.comments === "boolean" ? output.comments : {
  32703. annotation: !options.minify || libOptions && (format === "es" || format === "esm"),
  32704. jsdoc: !options.minify,
  32705. legal: !options.minify,
  32706. ...output.comments
  32707. },
  32708. minify: options.minify === "oxc" ? libOptions && (format === "es" || format === "esm") ? {
  32709. compress: true,
  32710. mangle: true,
  32711. codegen: false
  32712. } : true : options.minify === false ? "dce-only" : false,
  32713. topLevelVar: true,
  32714. ...output
  32715. };
  32716. };
  32717. const outputs = resolveBuildOutputs(options.rollupOptions.output, libOptions, logger);
  32718. if (Array.isArray(outputs)) rollupOptions.output = outputs.map(buildOutputOptions);
  32719. else rollupOptions.output = buildOutputOptions(outputs);
  32720. return rollupOptions;
  32721. }
  32722. /**
  32723. * Build an App environment, or a App library (if libraryOptions is provided)
  32724. **/
  32725. async function buildEnvironment(environment) {
  32726. const { logger, config } = environment;
  32727. const { root, build: options } = config;
  32728. logger.info(import_picocolors.default.cyan(`vite v${VERSION} ${import_picocolors.default.green(`building ${environment.name} environment for ${environment.config.mode}...`)}`));
  32729. let bundle;
  32730. let startTime;
  32731. try {
  32732. const chunkMetadataMap = new ChunkMetadataMap();
  32733. const rollupOptions = resolveRolldownOptions(environment, chunkMetadataMap);
  32734. if (options.watch) {
  32735. logger.info(import_picocolors.default.cyan(`\nwatching for file changes...`));
  32736. const resolvedOutDirs = getResolvedOutDirs(root, options.outDir, options.rollupOptions.output);
  32737. const emptyOutDir = resolveEmptyOutDir(options.emptyOutDir, root, resolvedOutDirs, logger);
  32738. const resolvedChokidarOptions = resolveChokidarOptions({
  32739. ...(rollupOptions.watch || {}).chokidar,
  32740. ...options.watch.chokidar
  32741. }, resolvedOutDirs, emptyOutDir, environment.config.cacheDir);
  32742. const { watch } = await import("rolldown");
  32743. const watcher = watch({
  32744. ...rollupOptions,
  32745. watch: {
  32746. ...rollupOptions.watch,
  32747. ...options.watch,
  32748. watcher: convertToWatcherOptions(resolvedChokidarOptions)
  32749. }
  32750. });
  32751. watcher.on("event", (event) => {
  32752. if (event.code === "BUNDLE_START") {
  32753. logger.info(import_picocolors.default.cyan(`\nbuild started...`));
  32754. chunkMetadataMap.clearResetChunks();
  32755. } else if (event.code === "BUNDLE_END") {
  32756. event.result.close();
  32757. logger.info(import_picocolors.default.cyan(`built in ${event.duration}ms.`));
  32758. } else if (event.code === "ERROR") {
  32759. const e = event.error;
  32760. enhanceRollupError(e);
  32761. clearLine();
  32762. logger.error(e.message, { error: e });
  32763. }
  32764. });
  32765. return watcher;
  32766. }
  32767. const { rolldown } = await import("rolldown");
  32768. startTime = Date.now();
  32769. bundle = await rolldown(rollupOptions);
  32770. const res = [];
  32771. for (const output of arraify(rollupOptions.output)) res.push(await bundle[options.write ? "write" : "generate"](output));
  32772. for (const output of res) for (const chunk of output.output) injectChunkMetadata(chunkMetadataMap, chunk);
  32773. logger.info(`${import_picocolors.default.green(`✓ built in ${displayTime(Date.now() - startTime)}`)}`);
  32774. return Array.isArray(rollupOptions.output) ? res : res[0];
  32775. } catch (e) {
  32776. enhanceRollupError(e);
  32777. clearLine();
  32778. if (startTime) {
  32779. logger.error(`${import_picocolors.default.red("✗")} Build failed in ${displayTime(Date.now() - startTime)}`);
  32780. startTime = void 0;
  32781. }
  32782. throw e;
  32783. } finally {
  32784. if (bundle) await bundle.close();
  32785. }
  32786. }
  32787. function enhanceRollupError(e) {
  32788. const stackOnly = extractStack(e);
  32789. let msg = import_picocolors.default.red((e.plugin ? `[${e.plugin}] ` : "") + e.message);
  32790. 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})` : ""))}`;
  32791. else if (e.id) msg += `\nfile: ${import_picocolors.default.cyan(e.id + (e.loc ? `:${e.loc.line}:${e.loc.column}` : ""))}`;
  32792. if (e.frame) msg += `\n` + import_picocolors.default.yellow(normalizeCodeFrame(e.frame));
  32793. e.message = msg;
  32794. if (stackOnly !== void 0) e.stack = `${e.message}\n${stackOnly}`;
  32795. }
  32796. /**
  32797. * The stack string usually contains a copy of the message at the start of the stack.
  32798. * If the stack starts with the message, we remove it and just return the stack trace
  32799. * portion. Otherwise the original stack trace is used.
  32800. */
  32801. function extractStack(e) {
  32802. const { stack, name = "Error", message } = e;
  32803. if (!stack) return stack;
  32804. const expectedPrefix = `${name}: ${message}\n`;
  32805. if (stack.startsWith(expectedPrefix)) return stack.slice(expectedPrefix.length);
  32806. return stack;
  32807. }
  32808. /**
  32809. * Esbuild code frames have newlines at the start and end of the frame, rollup doesn't
  32810. * This function normalizes the frame to match the esbuild format which has more pleasing padding
  32811. */
  32812. function normalizeCodeFrame(frame) {
  32813. return `\n${frame.replace(/^\n|\n$/g, "")}\n`;
  32814. }
  32815. function resolveOutputJsExtension(format, type = "commonjs") {
  32816. if (type === "module") return format === "cjs" || format === "umd" ? "cjs" : "js";
  32817. else return format === "es" ? "mjs" : "js";
  32818. }
  32819. function resolveLibFilename(libOptions, format, entryName, root, extension, packageCache) {
  32820. if (typeof libOptions.fileName === "function") return libOptions.fileName(format, entryName);
  32821. const packageJson = findNearestMainPackageData(root, packageCache)?.data;
  32822. const name = libOptions.fileName || (packageJson && typeof libOptions.entry === "string" ? getPkgName(packageJson.name) : entryName);
  32823. if (!name) throw new Error("Name in package.json is required if option \"build.lib.fileName\" is not provided.");
  32824. extension ??= resolveOutputJsExtension(format, packageJson?.type);
  32825. if (format === "cjs" || format === "es") return `${name}.${extension}`;
  32826. return `${name}.${format}.${extension}`;
  32827. }
  32828. function resolveBuildOutputs(outputs, libOptions, logger) {
  32829. if (libOptions) {
  32830. const libHasMultipleEntries = typeof libOptions.entry !== "string" && Object.values(libOptions.entry).length > 1;
  32831. const libFormats = libOptions.formats || (libHasMultipleEntries ? ["es", "cjs"] : ["es", "umd"]);
  32832. if (!Array.isArray(outputs)) {
  32833. if (libFormats.includes("umd") || libFormats.includes("iife")) {
  32834. if (libHasMultipleEntries) throw new Error("Multiple entry points are not supported when output formats include \"umd\" or \"iife\".");
  32835. if (!libOptions.name) throw new Error("Option \"build.lib.name\" is required when output formats include \"umd\" or \"iife\".");
  32836. }
  32837. return libFormats.map((format) => ({
  32838. ...outputs,
  32839. format
  32840. }));
  32841. }
  32842. if (libOptions.formats) logger.warn(import_picocolors.default.yellow("\"build.lib.formats\" will be ignored because \"build.rollupOptions.output\" is already an array format."));
  32843. outputs.forEach((output) => {
  32844. 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\".");
  32845. });
  32846. }
  32847. return outputs;
  32848. }
  32849. const warningIgnoreList = [`CIRCULAR_DEPENDENCY`, `THIS_IS_UNDEFINED`];
  32850. const dynamicImportWarningIgnoreList = [`Unsupported expression`, `statically analyzed`];
  32851. function clearLine() {
  32852. if (process.stdout.isTTY && !process.env.CI) {
  32853. process.stdout.clearLine(0);
  32854. process.stdout.cursorTo(0);
  32855. }
  32856. }
  32857. function onRollupLog(level, log, environment) {
  32858. const debugLogger = createDebugger("vite:build");
  32859. const viteLog = (logLeveling, rawLogging) => {
  32860. const logging = typeof rawLogging === "object" ? rawLogging : { message: rawLogging };
  32861. if (logging.code === "UNRESOLVED_IMPORT") {
  32862. const id = logging.id;
  32863. const exporter = logging.exporter;
  32864. 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\``);
  32865. }
  32866. if (logLeveling === "warn") {
  32867. if (logging.plugin === "rollup-plugin-dynamic-import-variables" && dynamicImportWarningIgnoreList.some((msg) => logging.message.includes(msg))) return;
  32868. if (warningIgnoreList.includes(logging.code)) return;
  32869. }
  32870. let message = logging.message;
  32871. if (logging.plugin) message = `[plugin ${logging.plugin}] ${message}`;
  32872. switch (logLeveling) {
  32873. case "info":
  32874. environment.logger.info(message);
  32875. return;
  32876. case "warn":
  32877. environment.logger.warn(import_picocolors.default.yellow(message));
  32878. return;
  32879. case "error":
  32880. environment.logger.error(import_picocolors.default.red(message));
  32881. return;
  32882. case "debug":
  32883. debugLogger?.(message);
  32884. return;
  32885. default:
  32886. environment.logger.info(message);
  32887. return;
  32888. }
  32889. };
  32890. clearLine();
  32891. const userOnLog = environment.config.build.rollupOptions?.onLog;
  32892. const userOnWarn = environment.config.build.rollupOptions?.onwarn;
  32893. if (userOnLog) if (userOnWarn) userOnLog(level, log, normalizeUserOnWarn(userOnWarn, viteLog));
  32894. else userOnLog(level, log, viteLog);
  32895. else if (userOnWarn) normalizeUserOnWarn(userOnWarn, viteLog)(level, log);
  32896. else viteLog(level, log);
  32897. }
  32898. function normalizeUserOnWarn(userOnWarn, defaultHandler) {
  32899. return (logLevel, logging) => {
  32900. if (logLevel === "warn") userOnWarn(normalizeLog(logging), (log) => defaultHandler("warn", typeof log === "function" ? log() : log));
  32901. else defaultHandler(logLevel, logging);
  32902. };
  32903. }
  32904. const normalizeLog = (log) => typeof log === "string" ? { message: log } : log;
  32905. function resolveUserExternal(user, id, parentId, isResolved) {
  32906. if (typeof user === "function") return user(id, parentId, isResolved);
  32907. else if (Array.isArray(user)) return user.some((test) => isExternal(id, test));
  32908. else return isExternal(id, user);
  32909. }
  32910. function isExternal(id, test) {
  32911. if (typeof test === "string") return id === test;
  32912. else return test.test(id);
  32913. }
  32914. var ChunkMetadataMap = class {
  32915. _inner = /* @__PURE__ */ new Map();
  32916. _resetChunks = /* @__PURE__ */ new Set();
  32917. _getKey(chunk) {
  32918. return "preliminaryFileName" in chunk ? chunk.preliminaryFileName : chunk.fileName;
  32919. }
  32920. _getDefaultValue(chunk) {
  32921. return chunk.type === "chunk" ? {
  32922. importedAssets: /* @__PURE__ */ new Set(),
  32923. importedCss: /* @__PURE__ */ new Set(),
  32924. __modules: chunk.modules
  32925. } : {
  32926. importedAssets: /* @__PURE__ */ new Set(),
  32927. importedCss: /* @__PURE__ */ new Set()
  32928. };
  32929. }
  32930. get(chunk) {
  32931. const key = this._getKey(chunk);
  32932. if (!this._inner.has(key)) this._inner.set(key, this._getDefaultValue(chunk));
  32933. return this._inner.get(key);
  32934. }
  32935. reset(chunk) {
  32936. const key = this._getKey(chunk);
  32937. if (this._resetChunks.has(key)) return;
  32938. this._resetChunks.add(key);
  32939. this._inner.set(key, this._getDefaultValue(chunk));
  32940. }
  32941. clearResetChunks() {
  32942. this._resetChunks.clear();
  32943. }
  32944. };
  32945. function injectEnvironmentToHooks(environment, chunkMetadataMap, plugin) {
  32946. const { resolveId, load, transform } = plugin;
  32947. const clone = Object.assign(Object.create(Object.getPrototypeOf(plugin)), plugin);
  32948. for (const hook of Object.keys(clone)) switch (hook) {
  32949. case "resolveId":
  32950. clone[hook] = wrapEnvironmentResolveId(environment, resolveId, plugin.name);
  32951. break;
  32952. case "load":
  32953. clone[hook] = wrapEnvironmentLoad(environment, load, plugin.name);
  32954. break;
  32955. case "transform":
  32956. clone[hook] = wrapEnvironmentTransform(environment, transform, plugin.name);
  32957. break;
  32958. default:
  32959. if (ROLLUP_HOOKS.includes(hook)) clone[hook] = wrapEnvironmentHook(environment, chunkMetadataMap, plugin, hook);
  32960. break;
  32961. }
  32962. return clone;
  32963. }
  32964. const wrappedHookMap = /* @__PURE__ */ new WeakMap();
  32965. function wrapHookObject(hook, handler) {
  32966. const newHook = {
  32967. ...hook,
  32968. handler
  32969. };
  32970. if (!wrappedHookMap.has(hook)) {
  32971. wrappedHookMap.set(hook, []);
  32972. Object.defineProperty(hook, "filter", {
  32973. get() {
  32974. return wrappedHookMap.get(hook)[0].filter;
  32975. },
  32976. set(v) {
  32977. for (const h of wrappedHookMap.get(hook)) h.filter = v;
  32978. }
  32979. });
  32980. Object.defineProperty(hook, "order", {
  32981. get() {
  32982. return wrappedHookMap.get(hook)[0].order;
  32983. },
  32984. set(v) {
  32985. for (const h of wrappedHookMap.get(hook)) h.order = v;
  32986. }
  32987. });
  32988. }
  32989. wrappedHookMap.get(hook).push(newHook);
  32990. return newHook;
  32991. }
  32992. function wrapEnvironmentResolveId(environment, hook, pluginName) {
  32993. if (!hook) return;
  32994. const fn = getHookHandler(hook);
  32995. const handler = function(id, importer, options) {
  32996. return fn.call(injectEnvironmentInContext(this, environment), id, importer, injectSsrFlag(options, environment, pluginName));
  32997. };
  32998. if ("handler" in hook) return wrapHookObject(hook, handler);
  32999. else return handler;
  33000. }
  33001. function wrapEnvironmentLoad(environment, hook, pluginName) {
  33002. if (!hook) return;
  33003. const fn = getHookHandler(hook);
  33004. const handler = function(id, ...args) {
  33005. return fn.call(injectEnvironmentInContext(this, environment), id, injectSsrFlag(args[0], environment, pluginName));
  33006. };
  33007. if ("handler" in hook) return wrapHookObject(hook, handler);
  33008. else return handler;
  33009. }
  33010. function wrapEnvironmentTransform(environment, hook, pluginName) {
  33011. if (!hook) return;
  33012. const fn = getHookHandler(hook);
  33013. const handler = function(code, importer, ...args) {
  33014. return fn.call(injectEnvironmentInContext(this, environment), code, importer, injectSsrFlag(args[0], environment, pluginName));
  33015. };
  33016. if ("handler" in hook) return wrapHookObject(hook, handler);
  33017. else return handler;
  33018. }
  33019. function wrapEnvironmentHook(environment, chunkMetadataMap, plugin, hookName) {
  33020. const hook = plugin[hookName];
  33021. if (!hook) return;
  33022. const fn = getHookHandler(hook);
  33023. if (typeof fn !== "function") return hook;
  33024. const handler = function(...args) {
  33025. if (hookName === "renderChunk") injectChunkMetadata(chunkMetadataMap, args[1], true);
  33026. if (hookName === "augmentChunkHash") injectChunkMetadata(chunkMetadataMap, args[0]);
  33027. if (hookName === "generateBundle" || hookName === "writeBundle") {
  33028. const bundle = args[1];
  33029. for (const chunk of Object.values(bundle)) injectChunkMetadata(chunkMetadataMap, chunk);
  33030. }
  33031. return fn.call(injectEnvironmentInContext(this, environment), ...args);
  33032. };
  33033. if ("handler" in hook) return wrapHookObject(hook, handler);
  33034. else return handler;
  33035. }
  33036. function injectChunkMetadata(chunkMetadataMap, chunk, resetChunkMetadata = false) {
  33037. if (resetChunkMetadata) chunkMetadataMap.reset(chunk);
  33038. Object.defineProperty(chunk, "viteMetadata", {
  33039. value: chunkMetadataMap.get(chunk),
  33040. enumerable: true
  33041. });
  33042. if (chunk.type === "chunk") Object.defineProperty(chunk, "modules", {
  33043. get() {
  33044. return chunk.viteMetadata.__modules;
  33045. },
  33046. enumerable: true
  33047. });
  33048. }
  33049. function injectEnvironmentInContext(context, environment) {
  33050. context.meta.viteVersion ??= VERSION;
  33051. context.environment ??= environment;
  33052. return context;
  33053. }
  33054. function injectSsrFlag(options, environment, pluginName) {
  33055. let ssr = environment.config.consumer === "server";
  33056. const newOptions = {
  33057. ...options ?? {},
  33058. ssr
  33059. };
  33060. if (isFutureDeprecationEnabled(environment?.getTopLevelConfig(), "removePluginHookSsrArgument")) Object.defineProperty(newOptions, "ssr", {
  33061. get() {
  33062. warnFutureDeprecation(environment?.getTopLevelConfig(), "removePluginHookSsrArgument", `Used in plugin "${pluginName}".`);
  33063. return ssr;
  33064. },
  33065. set(v) {
  33066. ssr = v;
  33067. }
  33068. });
  33069. return newOptions;
  33070. }
  33071. const needsEscapeRegEx = /[\n\r'\\\u2028\u2029]/;
  33072. const quoteNewlineRegEx = /([\n\r'\u2028\u2029])/g;
  33073. const backSlashRegEx = /\\/g;
  33074. function escapeId(id) {
  33075. if (!needsEscapeRegEx.test(id)) return id;
  33076. return id.replace(backSlashRegEx, "\\\\").replace(quoteNewlineRegEx, "\\$1");
  33077. }
  33078. const getResolveUrl = (path, URL = "URL") => `new ${URL}(${path}).href`;
  33079. 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`);
  33080. const getFileUrlFromFullPath = (path) => `require('u' + 'rl').pathToFileURL(${path}).href`;
  33081. const getFileUrlFromRelativePath = (path) => getFileUrlFromFullPath(`__dirname + '/${escapeId(path)}'`);
  33082. const customRelativeUrlMechanisms = {
  33083. cjs: (relativePath) => `(typeof document === 'undefined' ? ${getFileUrlFromRelativePath(relativePath)} : ${getRelativeUrlFromDocument(relativePath)})`,
  33084. es: (relativePath) => getResolveUrl(`'${escapeId(partialEncodeURIPath(relativePath))}', import.meta.url`),
  33085. iife: (relativePath) => getRelativeUrlFromDocument(relativePath),
  33086. umd: (relativePath) => `(typeof document === 'undefined' && typeof location === 'undefined' ? ${getFileUrlFromRelativePath(relativePath)} : ${getRelativeUrlFromDocument(relativePath, true)})`,
  33087. "worker-iife": (relativePath) => getResolveUrl(`'${escapeId(partialEncodeURIPath(relativePath))}', self.location.href`)
  33088. };
  33089. function toOutputFilePathInJS(environment, filename, type, hostId, hostType, toRelative) {
  33090. const { experimental, base, decodedBase } = environment.config;
  33091. const ssr = environment.config.consumer === "server";
  33092. const { renderBuiltUrl } = experimental;
  33093. let relative = base === "" || base === "./";
  33094. if (renderBuiltUrl) {
  33095. const result = renderBuiltUrl(filename, {
  33096. hostId,
  33097. hostType,
  33098. type,
  33099. ssr
  33100. });
  33101. if (typeof result === "object") {
  33102. if (result.runtime) return { runtime: result.runtime };
  33103. if (typeof result.relative === "boolean") relative = result.relative;
  33104. } else if (result) return result;
  33105. }
  33106. if (relative && !ssr) return toRelative(filename, hostId);
  33107. return joinUrlSegments(decodedBase, filename);
  33108. }
  33109. function createToImportMetaURLBasedRelativeRuntime(format, isWorker) {
  33110. const toRelativePath = customRelativeUrlMechanisms[isWorker && format === "iife" ? "worker-iife" : format];
  33111. return (filename, importer) => ({ runtime: toRelativePath(path.posix.relative(path.dirname(importer), filename)) });
  33112. }
  33113. function toOutputFilePathWithoutRuntime(filename, type, hostId, hostType, config, toRelative) {
  33114. const { renderBuiltUrl } = config.experimental;
  33115. let relative = config.base === "" || config.base === "./";
  33116. if (renderBuiltUrl) {
  33117. const result = renderBuiltUrl(filename, {
  33118. hostId,
  33119. hostType,
  33120. type,
  33121. ssr: !!config.build.ssr
  33122. });
  33123. if (typeof result === "object") {
  33124. if (result.runtime) throw new Error(`{ runtime: "${result.runtime}" } is not supported for assets in ${hostType} files: ${filename}`);
  33125. if (typeof result.relative === "boolean") relative = result.relative;
  33126. } else if (result) return result;
  33127. }
  33128. if (relative && !config.build.ssr) return toRelative(filename, hostId);
  33129. else return joinUrlSegments(config.decodedBase, filename);
  33130. }
  33131. const toOutputFilePathInCss = toOutputFilePathWithoutRuntime;
  33132. const toOutputFilePathInHtml = toOutputFilePathWithoutRuntime;
  33133. var BuildEnvironment = class extends BaseEnvironment {
  33134. mode = "build";
  33135. isBuilt = false;
  33136. constructor(name, config, setup) {
  33137. let options = config.environments[name];
  33138. if (!options) throw new Error(`Environment "${name}" is not defined in the config.`);
  33139. if (setup?.options) options = mergeConfig(options, setup.options);
  33140. super(name, config, options);
  33141. }
  33142. async init() {
  33143. if (this._initiated) return;
  33144. this._initiated = true;
  33145. }
  33146. };
  33147. const _builderOptionsDefaults = Object.freeze({
  33148. sharedConfigBuild: false,
  33149. sharedPlugins: false
  33150. });
  33151. const builderOptionsDefaults = _builderOptionsDefaults;
  33152. function resolveBuilderOptions(options) {
  33153. if (!options) return;
  33154. return mergeWithDefaults({
  33155. ..._builderOptionsDefaults,
  33156. buildApp: async () => {}
  33157. }, options);
  33158. }
  33159. /**
  33160. * Creates a ViteBuilder to orchestrate building multiple environments.
  33161. * @experimental
  33162. */
  33163. async function createBuilder(inlineConfig = {}, useLegacyBuilder = false) {
  33164. const patchConfig = (resolved) => {
  33165. if (!(useLegacyBuilder ?? !resolved.builder)) return;
  33166. resolved.build = { ...resolved.environments[resolved.build.ssr ? "ssr" : "client"].build };
  33167. };
  33168. const config = await resolveConfigToBuild(inlineConfig, patchConfig);
  33169. useLegacyBuilder ??= !config.builder;
  33170. const configBuilder = config.builder ?? resolveBuilderOptions({});
  33171. const environments = {};
  33172. const builder = {
  33173. environments,
  33174. config,
  33175. async buildApp() {
  33176. const pluginContext = new BasicMinimalPluginContext({
  33177. ...basePluginContextMeta,
  33178. watchMode: false
  33179. }, config.logger);
  33180. let configBuilderBuildAppCalled = false;
  33181. for (const p of config.getSortedPlugins("buildApp")) {
  33182. const hook = p.buildApp;
  33183. if (!configBuilderBuildAppCalled && typeof hook === "object" && hook.order === "post") {
  33184. configBuilderBuildAppCalled = true;
  33185. await configBuilder.buildApp(builder);
  33186. }
  33187. await getHookHandler(hook).call(pluginContext, builder);
  33188. }
  33189. if (!configBuilderBuildAppCalled) await configBuilder.buildApp(builder);
  33190. if (Object.values(builder.environments).every((environment) => !environment.isBuilt)) for (const environment of Object.values(builder.environments)) await builder.build(environment);
  33191. },
  33192. async build(environment) {
  33193. const output = await buildEnvironment(environment);
  33194. environment.isBuilt = true;
  33195. return output;
  33196. },
  33197. async runDevTools() {
  33198. const devtoolsConfig = config.devtools;
  33199. if (devtoolsConfig.enabled) try {
  33200. const { start } = await import(`@vitejs/devtools/cli-commands`);
  33201. await start(devtoolsConfig.config);
  33202. } catch (e) {
  33203. config.logger.error(import_picocolors.default.red(`Failed to run Vite DevTools: ${e.message || e.stack}`), { error: e });
  33204. }
  33205. }
  33206. };
  33207. async function setupEnvironment(name, config) {
  33208. const environment = await config.build.createEnvironment(name, config);
  33209. await environment.init();
  33210. environments[name] = environment;
  33211. }
  33212. if (useLegacyBuilder) await setupEnvironment(config.build.ssr ? "ssr" : "client", config);
  33213. else {
  33214. const environmentConfigs = [];
  33215. for (const environmentName of Object.keys(config.environments)) {
  33216. let environmentConfig = config;
  33217. if (!configBuilder.sharedConfigBuild) {
  33218. const patchConfig = (resolved) => {
  33219. resolved.build = { ...resolved.environments[environmentName].build };
  33220. };
  33221. const patchPlugins = (resolvedPlugins) => {
  33222. let j = 0;
  33223. for (let i = 0; i < resolvedPlugins.length; i++) {
  33224. const environmentPlugin = resolvedPlugins[i];
  33225. if (configBuilder.sharedPlugins || environmentPlugin.sharedDuringBuild) {
  33226. for (let k = j; k < config.plugins.length; k++) if (environmentPlugin.name === config.plugins[k].name) {
  33227. resolvedPlugins[i] = config.plugins[k];
  33228. j = k + 1;
  33229. break;
  33230. }
  33231. }
  33232. }
  33233. };
  33234. environmentConfig = await resolveConfigToBuild(inlineConfig, patchConfig, patchPlugins);
  33235. }
  33236. environmentConfigs.push([environmentName, environmentConfig]);
  33237. }
  33238. await Promise.all(environmentConfigs.map(async ([environmentName, environmentConfig]) => await setupEnvironment(environmentName, environmentConfig)));
  33239. }
  33240. return builder;
  33241. }
  33242. //#endregion
  33243. //#region src/node/server/environments/runnableEnvironment.ts
  33244. function createRunnableDevEnvironment(name, config, context = {}) {
  33245. if (context.transport == null) context.transport = createServerHotChannel();
  33246. if (context.hot == null) context.hot = true;
  33247. return new RunnableDevEnvironment(name, config, context);
  33248. }
  33249. function isRunnableDevEnvironment(environment) {
  33250. return environment instanceof RunnableDevEnvironment;
  33251. }
  33252. var RunnableDevEnvironment = class extends DevEnvironment {
  33253. _runner;
  33254. _runnerFactory;
  33255. _runnerOptions;
  33256. constructor(name, config, context) {
  33257. super(name, config, context);
  33258. this._runnerFactory = context.runner;
  33259. this._runnerOptions = context.runnerOptions;
  33260. }
  33261. get runner() {
  33262. if (this._runner) return this._runner;
  33263. this._runner = (this._runnerFactory || createServerModuleRunner)(this, this._runnerOptions);
  33264. return this._runner;
  33265. }
  33266. async close() {
  33267. await super.close();
  33268. if (this._runner) await this._runner.close();
  33269. }
  33270. };
  33271. //#endregion
  33272. //#region ../../node_modules/.pnpm/@polka+compression@1.0.0-next.25/node_modules/@polka/compression/build.mjs
  33273. const NOOP = () => {};
  33274. const MIMES = /text|javascript|\/json|xml/i;
  33275. /**
  33276. * @param {any} chunk
  33277. * @param {BufferEncoding} enc
  33278. * @returns {number}
  33279. */
  33280. function getChunkSize(chunk, enc) {
  33281. return chunk ? Buffer.byteLength(chunk, enc) : 0;
  33282. }
  33283. /**
  33284. * @param {import('./index.d.mts').Options} [options]
  33285. * @returns {import('./index.d.mts').Middleware}
  33286. */
  33287. function build_default({ threshold = 1024, level = -1, brotli = false, gzip = true, mimes = MIMES } = {}) {
  33288. const brotliOpts = typeof brotli === "object" && brotli || {};
  33289. const gzipOpts = typeof gzip === "object" && gzip || {};
  33290. if (!zlib.createBrotliCompress) brotli = false;
  33291. return (req, res, next = NOOP) => {
  33292. const accept = req.headers["accept-encoding"] + "";
  33293. const encoding = (brotli && accept.match(/\bbr\b/) || gzip && accept.match(/\bgzip\b/) || [])[0];
  33294. if (req.method === "HEAD" || !encoding) return next();
  33295. /** @type {zlib.Gzip | zlib.BrotliCompress} */
  33296. let compress;
  33297. /** @type {Array<[string, function]>?} */
  33298. let pendingListeners = [];
  33299. let pendingStatus = 0;
  33300. let started = false;
  33301. let size = 0;
  33302. function start() {
  33303. started = true;
  33304. size = res.getHeader("Content-Length") | 0 || size;
  33305. const compressible = mimes.test(String(res.getHeader("Content-Type") || "text/plain"));
  33306. const cleartext = !res.getHeader("Content-Encoding");
  33307. const listeners = pendingListeners || [];
  33308. if (compressible && cleartext && size >= threshold) {
  33309. res.setHeader("Content-Encoding", encoding);
  33310. res.removeHeader("Content-Length");
  33311. if (encoding === "br") compress = zlib.createBrotliCompress({ params: Object.assign({
  33312. [zlib.constants.BROTLI_PARAM_QUALITY]: level,
  33313. [zlib.constants.BROTLI_PARAM_SIZE_HINT]: size
  33314. }, brotliOpts) });
  33315. else compress = zlib.createGzip(Object.assign({ level }, gzipOpts));
  33316. compress.on("data", (chunk) => write.call(res, chunk) || compress.pause());
  33317. on.call(res, "drain", () => compress.resume());
  33318. compress.on("end", () => end.call(res));
  33319. listeners.forEach((p) => compress.on.apply(compress, p));
  33320. } else {
  33321. pendingListeners = null;
  33322. listeners.forEach((p) => on.apply(res, p));
  33323. }
  33324. writeHead.call(res, pendingStatus || res.statusCode);
  33325. }
  33326. const { end, write, on, writeHead } = res;
  33327. res.writeHead = function(status, reason, headers) {
  33328. if (typeof reason !== "string") [headers, reason] = [reason, headers];
  33329. if (headers) for (let k in headers) res.setHeader(k, headers[k]);
  33330. pendingStatus = status;
  33331. return this;
  33332. };
  33333. res.write = function(chunk, enc) {
  33334. size += getChunkSize(chunk, enc);
  33335. if (!started) start();
  33336. if (!compress) return write.apply(this, arguments);
  33337. return compress.write.apply(compress, arguments);
  33338. };
  33339. res.end = function(chunk, enc) {
  33340. if (arguments.length > 0 && typeof chunk !== "function") size += getChunkSize(chunk, enc);
  33341. if (!started) start();
  33342. if (!compress) return end.apply(this, arguments);
  33343. return compress.end.apply(compress, arguments);
  33344. };
  33345. res.on = function(type, listener) {
  33346. if (!pendingListeners) on.call(this, type, listener);
  33347. else if (compress) compress.on(type, listener);
  33348. else pendingListeners.push([type, listener]);
  33349. return this;
  33350. };
  33351. next();
  33352. };
  33353. }
  33354. //#endregion
  33355. //#region src/node/preview.ts
  33356. function resolvePreviewOptions(preview, server) {
  33357. return {
  33358. port: preview?.port ?? 4173,
  33359. strictPort: preview?.strictPort ?? server.strictPort,
  33360. host: preview?.host ?? server.host,
  33361. allowedHosts: preview?.allowedHosts ?? server.allowedHosts,
  33362. https: preview?.https ?? server.https,
  33363. open: preview?.open ?? server.open,
  33364. proxy: preview?.proxy ?? server.proxy,
  33365. cors: preview?.cors ?? server.cors,
  33366. headers: preview?.headers ?? server.headers
  33367. };
  33368. }
  33369. /**
  33370. * Starts the Vite server in preview mode, to simulate a production deployment
  33371. */
  33372. async function preview(inlineConfig = {}) {
  33373. const config = await resolveConfig(inlineConfig, "serve", "production", "production", true);
  33374. const clientOutDir = config.environments.client.build.outDir;
  33375. const distDir = path.resolve(config.root, clientOutDir);
  33376. 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?`);
  33377. const httpsOptions = await resolveHttpsConfig(config.preview.https);
  33378. const app = (0, import_connect.default)();
  33379. const httpServer = await resolveHttpServer(app, httpsOptions);
  33380. setClientErrorHandler(httpServer, config.logger);
  33381. const options = config.preview;
  33382. const logger = config.logger;
  33383. const closeHttpServer = createServerCloseFn(httpServer);
  33384. let closeServerPromise;
  33385. const closeServer = async () => {
  33386. teardownSIGTERMListener(closeServerAndExit);
  33387. await closeHttpServer();
  33388. server.resolvedUrls = null;
  33389. };
  33390. const server = {
  33391. config,
  33392. middlewares: app,
  33393. httpServer,
  33394. async close() {
  33395. if (!closeServerPromise) closeServerPromise = closeServer();
  33396. return closeServerPromise;
  33397. },
  33398. resolvedUrls: null,
  33399. printUrls() {
  33400. if (server.resolvedUrls) printServerUrls(server.resolvedUrls, options.host, logger.info);
  33401. else throw new Error("cannot print server URLs before server is listening.");
  33402. },
  33403. bindCLIShortcuts(options) {
  33404. bindCLIShortcuts(server, options);
  33405. }
  33406. };
  33407. const closeServerAndExit = async (_, exitCode) => {
  33408. try {
  33409. await server.close();
  33410. } finally {
  33411. process.exitCode ??= exitCode ? 128 + exitCode : void 0;
  33412. process.exit();
  33413. }
  33414. };
  33415. setupSIGTERMListener(closeServerAndExit);
  33416. const { cors } = config.preview;
  33417. if (cors !== false) app.use((0, import_lib.default)(typeof cors === "boolean" ? {} : cors));
  33418. const { allowedHosts } = config.preview;
  33419. if (allowedHosts !== true && !config.preview.https) app.use(hostValidationMiddleware(allowedHosts, true));
  33420. const configurePreviewServerContext = new BasicMinimalPluginContext({
  33421. ...basePluginContextMeta,
  33422. watchMode: false
  33423. }, config.logger);
  33424. const postHooks = [];
  33425. for (const hook of config.getSortedPluginHooks("configurePreviewServer")) postHooks.push(await hook.call(configurePreviewServerContext, server));
  33426. const { proxy } = config.preview;
  33427. if (proxy) app.use(proxyMiddleware(httpServer, proxy, config));
  33428. app.use(build_default());
  33429. if (config.base !== "/") app.use(baseMiddleware(config.rawBase, false));
  33430. const headers = config.preview.headers;
  33431. const viteAssetMiddleware = (...args) => build_default$1(distDir, {
  33432. etag: true,
  33433. dev: true,
  33434. extensions: [],
  33435. ignores: false,
  33436. setHeaders(res) {
  33437. if (headers) for (const name in headers) res.setHeader(name, headers[name]);
  33438. },
  33439. shouldServe(filePath) {
  33440. return shouldServeFile(filePath, distDir);
  33441. }
  33442. })(...args);
  33443. app.use(viteAssetMiddleware);
  33444. if (config.appType === "spa" || config.appType === "mpa") app.use(htmlFallbackMiddleware(distDir, config.appType === "spa"));
  33445. postHooks.forEach((fn) => fn && fn());
  33446. if (config.appType === "spa" || config.appType === "mpa") {
  33447. const normalizedDistDir = normalizePath(distDir);
  33448. app.use(indexHtmlMiddleware(normalizedDistDir, server));
  33449. app.use(notFoundMiddleware());
  33450. }
  33451. const hostname = await resolveHostname(options.host);
  33452. await httpServerStart(httpServer, {
  33453. port: options.port,
  33454. strictPort: options.strictPort,
  33455. host: hostname.host,
  33456. logger
  33457. });
  33458. server.resolvedUrls = resolveServerUrls(httpServer, config.preview, hostname, httpsOptions, config);
  33459. if (options.open) {
  33460. const url = getServerUrlByHost(server.resolvedUrls, options.host);
  33461. if (url) openBrowser(typeof options.open === "string" ? new URL(options.open, url).href : url, true, logger);
  33462. }
  33463. return server;
  33464. }
  33465. //#endregion
  33466. //#region src/node/ssr/index.ts
  33467. const _ssrConfigDefaults = Object.freeze({
  33468. target: "node",
  33469. optimizeDeps: {}
  33470. });
  33471. const ssrConfigDefaults = _ssrConfigDefaults;
  33472. function resolveSSROptions(ssr, preserveSymlinks) {
  33473. return mergeWithDefaults(mergeWithDefaults(_ssrConfigDefaults, { optimizeDeps: { esbuildOptions: { preserveSymlinks } } }), ssr ?? {});
  33474. }
  33475. //#endregion
  33476. //#region src/node/ssr/runnerImport.ts
  33477. /**
  33478. * Import any file using the default Vite environment.
  33479. * @experimental
  33480. */
  33481. async function runnerImport(moduleId, inlineConfig) {
  33482. const isModuleSyncConditionEnabled = (await import("#module-sync-enabled")).default;
  33483. const environment = createRunnableDevEnvironment("inline", await resolveConfig(mergeConfig(inlineConfig || {}, {
  33484. configFile: false,
  33485. envDir: false,
  33486. cacheDir: process.cwd(),
  33487. environments: { inline: {
  33488. consumer: "server",
  33489. dev: { moduleRunnerTransform: true },
  33490. resolve: {
  33491. external: true,
  33492. mainFields: [],
  33493. conditions: ["node", ...isModuleSyncConditionEnabled ? ["module-sync"] : []]
  33494. }
  33495. } }
  33496. }), "serve"), {
  33497. runnerOptions: { hmr: { logger: false } },
  33498. hot: false
  33499. });
  33500. await environment.init();
  33501. try {
  33502. const module = await environment.runner.import(moduleId);
  33503. return {
  33504. module,
  33505. dependencies: [...environment.runner.evaluatedModules.urlToIdModuleMap.values()].filter((m) => {
  33506. if (!m.meta || "externalize" in m.meta) return false;
  33507. return m.exports !== module;
  33508. }).map((m) => m.file)
  33509. };
  33510. } finally {
  33511. await environment.close();
  33512. }
  33513. }
  33514. //#endregion
  33515. //#region src/node/optimizer/pluginConverter.ts
  33516. function convertEsbuildPluginToRolldownPlugin(esbuildPlugin) {
  33517. const onStartCallbacks = [];
  33518. const onEndCallbacks = [];
  33519. const onDisposeCallbacks = [];
  33520. let resolveIdHandlers;
  33521. let loadHandlers;
  33522. let isSetupDone = false;
  33523. const setup = async (plugins, platform) => {
  33524. const onResolveCallbacks = [];
  33525. const onLoadCallbacks = [];
  33526. const pluginBuild = {
  33527. initialOptions: new Proxy({
  33528. platform,
  33529. plugins: plugins?.flatMap((p) => p && "name" in p ? [{
  33530. name: p.name,
  33531. setup() {}
  33532. }] : []) ?? []
  33533. }, { get(target, p, _receiver) {
  33534. if (p in target) return target[p];
  33535. throw new Error("Not implemented");
  33536. } }),
  33537. resolve() {
  33538. throw new Error("Not implemented");
  33539. },
  33540. onStart(callback) {
  33541. onStartCallbacks.push(callback);
  33542. },
  33543. onEnd(callback) {
  33544. onEndCallbacks.push(callback);
  33545. },
  33546. onResolve(options, callback) {
  33547. onResolveCallbacks.push([options, callback]);
  33548. },
  33549. onLoad(options, callback) {
  33550. onLoadCallbacks.push([options, callback]);
  33551. },
  33552. onDispose(callback) {
  33553. onDisposeCallbacks.push(callback);
  33554. },
  33555. get esbuild() {
  33556. throw new Error("Not implemented");
  33557. },
  33558. set esbuild(_) {
  33559. throw new Error("Not implemented");
  33560. }
  33561. };
  33562. await esbuildPlugin.setup(pluginBuild);
  33563. resolveIdHandlers = onResolveCallbacks.map(([options, callback]) => createResolveIdHandler(options, callback));
  33564. loadHandlers = onLoadCallbacks.map(([options, callback]) => createLoadHandler(options, callback));
  33565. isSetupDone = true;
  33566. };
  33567. const usedNamespaces = /* @__PURE__ */ new Set();
  33568. return {
  33569. name: esbuildPlugin.name,
  33570. async options(inputOptions) {
  33571. await setup(inputOptions.plugins, inputOptions.platform ?? "node");
  33572. },
  33573. async buildStart(inputOptions) {
  33574. if (!isSetupDone) await setup([{ name: "vite:dep-scan" }], inputOptions.platform ?? "node");
  33575. for (const cb of onStartCallbacks) cb();
  33576. },
  33577. generateBundle() {
  33578. const buildResult = new Proxy({}, { get(_target, _prop) {
  33579. throw new Error("Not implemented");
  33580. } });
  33581. for (const cb of onEndCallbacks) cb(buildResult);
  33582. },
  33583. async resolveId(id, importer, opts) {
  33584. for (const handler of resolveIdHandlers) {
  33585. const result = await handler.call(this, id, importer, opts);
  33586. if (result) {
  33587. if (typeof result === "object" && result.namespace) usedNamespaces.add(result.namespace);
  33588. return result;
  33589. }
  33590. }
  33591. if (usedNamespaces.size) {
  33592. const [importerWithoutNamespace, namespaceFromImporter] = idToPathAndNamespace(importer);
  33593. if (usedNamespaces.has(namespaceFromImporter)) return await this.resolve(id, importerWithoutNamespace, opts);
  33594. }
  33595. },
  33596. async load(id) {
  33597. for (const handler of loadHandlers) {
  33598. const result = await handler.call(this, id);
  33599. if (result) return result;
  33600. }
  33601. },
  33602. closeBundle() {
  33603. if (!this.meta.watchMode) for (const cb of onDisposeCallbacks) cb();
  33604. },
  33605. closeWatcher() {
  33606. for (const cb of onDisposeCallbacks) cb();
  33607. }
  33608. };
  33609. }
  33610. function createResolveIdHandler(options, callback) {
  33611. return async function(id, importer, opts) {
  33612. const [importerWithoutNamespace, importerNamespace] = idToPathAndNamespace(importer);
  33613. if (options.namespace !== void 0 && options.namespace !== importerNamespace) return;
  33614. if (options.filter !== void 0 && !options.filter.test(id)) return;
  33615. const result = await callback({
  33616. path: id,
  33617. importer: importerWithoutNamespace ?? "",
  33618. namespace: importerNamespace,
  33619. resolveDir: dirname(importerWithoutNamespace ?? ""),
  33620. kind: importerWithoutNamespace === void 0 ? "entry-point" : opts.kind === "new-url" || opts.kind === "hot-accept" ? "dynamic-import" : opts.kind,
  33621. pluginData: {},
  33622. with: {}
  33623. });
  33624. if (!result) return;
  33625. if (result.errors && result.errors.length > 0) throw new AggregateError(result.errors);
  33626. if (result.warnings && result.warnings.length > 0 || result.watchDirs && result.watchDirs.length > 0 || !result.path) throw new Error("not implemented");
  33627. for (const file of result.watchFiles ?? []) this.addWatchFile(file);
  33628. return {
  33629. id: result.namespace ? `${result.namespace}:${result.path}` : result.path,
  33630. external: result.external,
  33631. moduleSideEffects: result.sideEffects,
  33632. namespace: result.namespace
  33633. };
  33634. };
  33635. }
  33636. function createLoadHandler(options, callback) {
  33637. const textDecoder = new TextDecoder();
  33638. return async function(id) {
  33639. const [idWithoutNamespace, idNamespace] = idToPathAndNamespace(id);
  33640. if (options.namespace !== void 0 && options.namespace !== "file" && options.namespace !== idNamespace) return;
  33641. if (options.filter !== void 0 && !options.filter.test(id)) return;
  33642. const result = await callback.call(this, {
  33643. path: idWithoutNamespace,
  33644. namespace: idNamespace,
  33645. suffix: "",
  33646. pluginData: {},
  33647. with: {}
  33648. });
  33649. if (!result) return;
  33650. if (result.errors && result.errors.length > 0) throw new AggregateError(result.errors);
  33651. if (result.warnings && result.warnings.length > 0 || result.watchDirs && result.watchDirs.length > 0 || result.contents == null) throw new Error("not implemented");
  33652. for (const file of result.watchFiles ?? []) this.addWatchFile(file);
  33653. return {
  33654. code: typeof result.contents === "string" ? result.contents : textDecoder.decode(result.contents),
  33655. moduleType: result.loader
  33656. };
  33657. };
  33658. }
  33659. function idToPathAndNamespace(id) {
  33660. if (id === void 0) return [void 0, "file"];
  33661. const namespaceIndex = id.indexOf(":");
  33662. if (namespaceIndex >= 0) return [id.slice(namespaceIndex + 1), id.slice(0, namespaceIndex)];
  33663. else return [id, "file"];
  33664. }
  33665. //#endregion
  33666. //#region src/node/config.ts
  33667. const debug = createDebugger("vite:config", { depth: 10 });
  33668. const promisifiedRealpath = promisify(fs.realpath);
  33669. const SYMBOL_RESOLVED_CONFIG = Symbol("vite:resolved-config");
  33670. function defineConfig(config) {
  33671. return config;
  33672. }
  33673. function defaultCreateClientDevEnvironment(name, config, context) {
  33674. if (config.experimental.bundledDev) return new FullBundleDevEnvironment(name, config, {
  33675. hot: true,
  33676. transport: context.ws
  33677. });
  33678. return new DevEnvironment(name, config, {
  33679. hot: true,
  33680. transport: context.ws
  33681. });
  33682. }
  33683. function defaultCreateDevEnvironment(name, config) {
  33684. return createRunnableDevEnvironment(name, config);
  33685. }
  33686. async function resolveDevToolsConfig(config, host, logger) {
  33687. const isEnabled = config === true || !!(config && config.enabled);
  33688. const fallbackHostname = (await resolveHostname(host)).host ?? "localhost";
  33689. const fallbackConfig = {
  33690. config: { host: fallbackHostname },
  33691. enabled: false
  33692. };
  33693. if (!isEnabled) return fallbackConfig;
  33694. try {
  33695. const { normalizeDevToolsConfig } = await import("@vitejs/devtools/config");
  33696. return normalizeDevToolsConfig(config, fallbackHostname);
  33697. } catch (e) {
  33698. logger.error(import_picocolors.default.red(`Failed to load Vite DevTools config: ${e.message || e.stack}`), { error: e });
  33699. return fallbackConfig;
  33700. }
  33701. }
  33702. const configDefaults = Object.freeze({
  33703. define: {},
  33704. dev: {
  33705. warmup: [],
  33706. sourcemap: { js: true },
  33707. sourcemapIgnoreList: void 0
  33708. },
  33709. build: buildEnvironmentOptionsDefaults,
  33710. resolve: {
  33711. externalConditions: [...DEFAULT_EXTERNAL_CONDITIONS],
  33712. extensions: DEFAULT_EXTENSIONS,
  33713. dedupe: [],
  33714. noExternal: [],
  33715. external: [],
  33716. preserveSymlinks: false,
  33717. tsconfigPaths: false,
  33718. alias: []
  33719. },
  33720. base: "/",
  33721. publicDir: "public",
  33722. plugins: [],
  33723. html: { cspNonce: void 0 },
  33724. css: cssConfigDefaults,
  33725. json: {
  33726. namedExports: true,
  33727. stringify: "auto"
  33728. },
  33729. assetsInclude: void 0,
  33730. builder: builderOptionsDefaults,
  33731. server: serverConfigDefaults,
  33732. preview: { port: DEFAULT_PREVIEW_PORT },
  33733. experimental: {
  33734. importGlobRestoreExtension: false,
  33735. renderBuiltUrl: void 0,
  33736. hmrPartialAccept: false,
  33737. bundledDev: false
  33738. },
  33739. future: {
  33740. removePluginHookHandleHotUpdate: void 0,
  33741. removePluginHookSsrArgument: void 0,
  33742. removeServerModuleGraph: void 0,
  33743. removeServerHot: void 0,
  33744. removeServerTransformRequest: void 0,
  33745. removeServerWarmupRequest: void 0,
  33746. removeSsrLoadModule: void 0
  33747. },
  33748. legacy: { skipWebSocketTokenCheck: false },
  33749. logLevel: "info",
  33750. customLogger: void 0,
  33751. clearScreen: true,
  33752. envDir: void 0,
  33753. envPrefix: "VITE_",
  33754. worker: {
  33755. format: "iife",
  33756. plugins: () => []
  33757. },
  33758. optimizeDeps: {
  33759. include: [],
  33760. exclude: [],
  33761. needsInterop: [],
  33762. rolldownOptions: {},
  33763. extensions: [],
  33764. disabled: "build",
  33765. holdUntilCrawlEnd: true,
  33766. force: false,
  33767. ignoreOutdatedRequests: false
  33768. },
  33769. ssr: ssrConfigDefaults,
  33770. environments: {},
  33771. appType: "spa"
  33772. });
  33773. function resolveDevEnvironmentOptions(dev, environmentName, consumer, preTransformRequest) {
  33774. const resolved = mergeWithDefaults({
  33775. ...configDefaults.dev,
  33776. sourcemapIgnoreList: isInNodeModules,
  33777. preTransformRequests: preTransformRequest ?? consumer === "client",
  33778. createEnvironment: environmentName === "client" ? defaultCreateClientDevEnvironment : defaultCreateDevEnvironment,
  33779. recoverable: consumer === "client",
  33780. moduleRunnerTransform: consumer === "server"
  33781. }, dev ?? {});
  33782. return {
  33783. ...resolved,
  33784. sourcemapIgnoreList: resolved.sourcemapIgnoreList === false ? () => false : resolved.sourcemapIgnoreList
  33785. };
  33786. }
  33787. function resolveEnvironmentOptions(options, alias, preserveSymlinks, forceOptimizeDeps, logger, environmentName, isBundledDev, isSsrTargetWebworkerSet, preTransformRequests) {
  33788. const consumer = options.consumer ?? (environmentName === "client" ? "client" : "server");
  33789. const isSsrTargetWebworkerEnvironment = isSsrTargetWebworkerSet && environmentName === "ssr";
  33790. if (options.define?.["process.env"]) {
  33791. const processEnvDefine = options.define["process.env"];
  33792. if (typeof processEnvDefine === "object") {
  33793. const pathKey = Object.entries(processEnvDefine).find(([key, value]) => key.toLowerCase() === "path" && !!value)?.[0];
  33794. 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.`));
  33795. }
  33796. }
  33797. const resolve = resolveEnvironmentResolveOptions(options.resolve, alias, preserveSymlinks, logger, consumer, isSsrTargetWebworkerEnvironment);
  33798. return {
  33799. define: options.define,
  33800. resolve,
  33801. keepProcessEnv: options.keepProcessEnv ?? (isSsrTargetWebworkerEnvironment ? false : consumer === "server"),
  33802. consumer,
  33803. optimizeDeps: resolveDepOptimizationOptions(options.optimizeDeps, resolve.preserveSymlinks, forceOptimizeDeps, consumer, logger),
  33804. dev: resolveDevEnvironmentOptions(options.dev, environmentName, consumer, preTransformRequests),
  33805. build: resolveBuildEnvironmentOptions(options.build ?? {}, logger, consumer, isBundledDev),
  33806. plugins: void 0,
  33807. optimizeDepsPluginNames: void 0
  33808. };
  33809. }
  33810. function getDefaultEnvironmentOptions(config) {
  33811. return {
  33812. define: config.define,
  33813. resolve: {
  33814. ...config.resolve,
  33815. mainFields: void 0,
  33816. conditions: void 0
  33817. },
  33818. dev: config.dev,
  33819. build: config.build
  33820. };
  33821. }
  33822. /**
  33823. * Check and warn if `path` includes characters that don't work well in Vite,
  33824. * such as `#` and `?` and `*`.
  33825. */
  33826. function checkBadCharactersInPath(name, path, logger) {
  33827. const badChars = [];
  33828. if (path.includes("#")) badChars.push("#");
  33829. if (path.includes("?")) badChars.push("?");
  33830. if (path.includes("*")) badChars.push("*");
  33831. if (badChars.length > 0) {
  33832. const charString = badChars.map((c) => `"${c}"`).join(" and ");
  33833. 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.`));
  33834. }
  33835. }
  33836. const clientAlias = [{
  33837. find: /^\/?@vite\/env/,
  33838. replacement: path.posix.join(FS_PREFIX, normalizePath(ENV_ENTRY))
  33839. }, {
  33840. find: /^\/?@vite\/client/,
  33841. replacement: path.posix.join(FS_PREFIX, normalizePath(CLIENT_ENTRY))
  33842. }];
  33843. /**
  33844. * alias and preserveSymlinks are not per-environment options, but they are
  33845. * included in the resolved environment options for convenience.
  33846. */
  33847. function resolveEnvironmentResolveOptions(resolve, alias, preserveSymlinks, logger, consumer, isSsrTargetWebworkerEnvironment) {
  33848. const resolvedResolve = mergeWithDefaults({
  33849. ...configDefaults.resolve,
  33850. mainFields: consumer === void 0 || consumer === "client" || isSsrTargetWebworkerEnvironment ? DEFAULT_CLIENT_MAIN_FIELDS : DEFAULT_SERVER_MAIN_FIELDS,
  33851. conditions: consumer === void 0 || consumer === "client" || isSsrTargetWebworkerEnvironment ? DEFAULT_CLIENT_CONDITIONS : DEFAULT_SERVER_CONDITIONS.filter((c) => c !== "browser"),
  33852. builtins: resolve?.builtins ?? (consumer === "server" ? isSsrTargetWebworkerEnvironment && resolve?.noExternal === true ? [] : nodeLikeBuiltins : [])
  33853. }, resolve ?? {});
  33854. resolvedResolve.preserveSymlinks = preserveSymlinks;
  33855. resolvedResolve.alias = alias;
  33856. 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."));
  33857. return resolvedResolve;
  33858. }
  33859. function resolveResolveOptions(resolve, logger) {
  33860. const alias = normalizeAlias(mergeAlias(clientAlias, resolve?.alias || configDefaults.resolve.alias));
  33861. const preserveSymlinks = resolve?.preserveSymlinks ?? configDefaults.resolve.preserveSymlinks;
  33862. 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."));
  33863. 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."));
  33864. return resolveEnvironmentResolveOptions(resolve, alias, preserveSymlinks, logger, void 0);
  33865. }
  33866. function resolveDepOptimizationOptions(optimizeDeps, preserveSymlinks, forceOptimizeDeps, consumer, logger) {
  33867. if (optimizeDeps?.rolldownOptions && optimizeDeps?.rolldownOptions === optimizeDeps?.rollupOptions) delete optimizeDeps?.rollupOptions;
  33868. const merged = mergeWithDefaults({
  33869. ...configDefaults.optimizeDeps,
  33870. disabled: void 0,
  33871. noDiscovery: consumer !== "client",
  33872. force: forceOptimizeDeps ?? configDefaults.optimizeDeps.force
  33873. }, optimizeDeps ?? {});
  33874. setupRollupOptionCompat(merged, "optimizeDeps");
  33875. const rolldownOptions = merged.rolldownOptions;
  33876. if (merged.esbuildOptions && Object.keys(merged.esbuildOptions).length > 0) {
  33877. 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."));
  33878. rolldownOptions.resolve ??= {};
  33879. rolldownOptions.output ??= {};
  33880. rolldownOptions.transform ??= {};
  33881. const setResolveOptions = (key, value) => {
  33882. if (value !== void 0 && rolldownOptions.resolve[key] === void 0) rolldownOptions.resolve[key] = value;
  33883. };
  33884. if (merged.esbuildOptions.minify !== void 0 && rolldownOptions.output.minify === void 0) rolldownOptions.output.minify = merged.esbuildOptions.minify;
  33885. if (merged.esbuildOptions.treeShaking !== void 0 && rolldownOptions.treeshake === void 0) rolldownOptions.treeshake = merged.esbuildOptions.treeShaking;
  33886. if (merged.esbuildOptions.define !== void 0 && rolldownOptions.transform.define === void 0) rolldownOptions.transform.define = merged.esbuildOptions.define;
  33887. if (merged.esbuildOptions.loader !== void 0) {
  33888. const loader = merged.esbuildOptions.loader;
  33889. rolldownOptions.moduleTypes ??= {};
  33890. 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;
  33891. }
  33892. if (merged.esbuildOptions.preserveSymlinks !== void 0 && rolldownOptions.resolve.symlinks === void 0) rolldownOptions.resolve.symlinks = !merged.esbuildOptions.preserveSymlinks;
  33893. setResolveOptions("extensions", merged.esbuildOptions.resolveExtensions);
  33894. setResolveOptions("mainFields", merged.esbuildOptions.mainFields);
  33895. setResolveOptions("conditionNames", merged.esbuildOptions.conditions);
  33896. if (merged.esbuildOptions.keepNames !== void 0 && rolldownOptions.output.keepNames === void 0) rolldownOptions.output.keepNames = merged.esbuildOptions.keepNames;
  33897. if (merged.esbuildOptions.platform !== void 0 && rolldownOptions.platform === void 0) rolldownOptions.platform = merged.esbuildOptions.platform;
  33898. }
  33899. merged.esbuildOptions ??= {};
  33900. merged.esbuildOptions.preserveSymlinks ??= preserveSymlinks;
  33901. rolldownOptions.resolve ??= {};
  33902. rolldownOptions.resolve.symlinks ??= !preserveSymlinks;
  33903. rolldownOptions.output ??= {};
  33904. rolldownOptions.output.topLevelVar ??= true;
  33905. return merged;
  33906. }
  33907. async function setOptimizeDepsPluginNames(resolvedConfig) {
  33908. await Promise.all(Object.values(resolvedConfig.environments).map(async (environment) => {
  33909. const flattenedPlugins = await asyncFlatten([environment.optimizeDeps.rolldownOptions?.plugins ?? [], environment.optimizeDeps.rolldownOptions?.output?.plugins ?? []]);
  33910. const pluginNames = [];
  33911. for (const plugin of flattenedPlugins) if (plugin && "name" in plugin) pluginNames.push(plugin.name);
  33912. environment.optimizeDepsPluginNames = pluginNames;
  33913. }));
  33914. }
  33915. function applyDepOptimizationOptionCompat(resolvedConfig) {
  33916. if (resolvedConfig.optimizeDeps.esbuildOptions?.plugins && resolvedConfig.optimizeDeps.esbuildOptions.plugins.length > 0) {
  33917. resolvedConfig.optimizeDeps.rolldownOptions ??= {};
  33918. resolvedConfig.optimizeDeps.rolldownOptions.plugins ||= [];
  33919. resolvedConfig.optimizeDeps.rolldownOptions.plugins.push(...resolvedConfig.optimizeDeps.esbuildOptions.plugins.map((plugin) => convertEsbuildPluginToRolldownPlugin(plugin)));
  33920. }
  33921. }
  33922. function isResolvedConfig(inlineConfig) {
  33923. return SYMBOL_RESOLVED_CONFIG in inlineConfig && inlineConfig[SYMBOL_RESOLVED_CONFIG];
  33924. }
  33925. async function resolveConfig(inlineConfig, command, defaultMode = "development", defaultNodeEnv = "development", isPreview = false, patchConfig = void 0, patchPlugins = void 0) {
  33926. let config = inlineConfig;
  33927. config.build ??= {};
  33928. setupRollupOptionCompat(config.build, "build");
  33929. config.worker ??= {};
  33930. setupRollupOptionCompat(config.worker, "worker");
  33931. config.optimizeDeps ??= {};
  33932. setupRollupOptionCompat(config.optimizeDeps, "optimizeDeps");
  33933. if (config.ssr) {
  33934. config.ssr.optimizeDeps ??= {};
  33935. setupRollupOptionCompat(config.ssr.optimizeDeps, "ssr.optimizeDeps");
  33936. }
  33937. let configFileDependencies = [];
  33938. let mode = inlineConfig.mode || defaultMode;
  33939. const isNodeEnvSet = !!process.env.NODE_ENV;
  33940. const packageCache = /* @__PURE__ */ new Map();
  33941. if (!isNodeEnvSet) process.env.NODE_ENV = defaultNodeEnv;
  33942. const configEnv = {
  33943. mode,
  33944. command,
  33945. isSsrBuild: command === "build" && !!config.build?.ssr,
  33946. isPreview
  33947. };
  33948. let { configFile } = config;
  33949. if (configFile !== false) {
  33950. const loadResult = await loadConfigFromFile(configEnv, configFile, config.root, config.logLevel, config.customLogger, config.configLoader);
  33951. if (loadResult) {
  33952. config = mergeConfig(loadResult.config, config);
  33953. configFile = loadResult.path;
  33954. configFileDependencies = loadResult.dependencies;
  33955. }
  33956. }
  33957. mode = inlineConfig.mode || config.mode || mode;
  33958. configEnv.mode = mode;
  33959. const filterPlugin = (p) => {
  33960. if (!p) return false;
  33961. else if (!p.apply) return true;
  33962. else if (typeof p.apply === "function") return p.apply({
  33963. ...config,
  33964. mode
  33965. }, configEnv);
  33966. else return p.apply === command;
  33967. };
  33968. const [prePlugins, normalPlugins, postPlugins] = sortUserPlugins((await asyncFlatten(config.plugins || [])).filter(filterPlugin));
  33969. const isBuild = command === "build";
  33970. const userPlugins = [
  33971. ...prePlugins,
  33972. ...normalPlugins,
  33973. ...postPlugins
  33974. ];
  33975. config = await runConfigHook(config, userPlugins, configEnv);
  33976. config.environments ??= {};
  33977. if (!config.environments.ssr && (!isBuild || config.ssr || config.build?.ssr)) config.environments = {
  33978. ssr: {},
  33979. ...config.environments
  33980. };
  33981. if (!config.environments.client) config.environments = {
  33982. client: {},
  33983. ...config.environments
  33984. };
  33985. const logger = createLogger(config.logLevel, {
  33986. allowClearScreen: config.clearScreen,
  33987. customLogger: config.customLogger
  33988. });
  33989. const tsconfigPathsPlugin = userPlugins.find((p) => p.name === "vite-tsconfig-paths" || p.name === "vite-plugin-tsconfig-paths");
  33990. 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.`));
  33991. const resolvedRoot = normalizePath(config.root ? path.resolve(config.root) : process.cwd());
  33992. checkBadCharactersInPath("The project root", resolvedRoot, logger);
  33993. const configEnvironmentsClient = config.environments.client;
  33994. configEnvironmentsClient.dev ??= {};
  33995. const deprecatedSsrOptimizeDepsConfig = config.ssr?.optimizeDeps ?? {};
  33996. let configEnvironmentsSsr = config.environments.ssr;
  33997. const warmupOptions = config.server?.warmup;
  33998. if (warmupOptions?.clientFiles) configEnvironmentsClient.dev.warmup = warmupOptions.clientFiles;
  33999. if (warmupOptions?.ssrFiles) {
  34000. configEnvironmentsSsr ??= {};
  34001. configEnvironmentsSsr.dev ??= {};
  34002. configEnvironmentsSsr.dev.warmup = warmupOptions.ssrFiles;
  34003. }
  34004. if (configEnvironmentsSsr) {
  34005. configEnvironmentsSsr.optimizeDeps = mergeConfig(deprecatedSsrOptimizeDepsConfig, configEnvironmentsSsr.optimizeDeps ?? {});
  34006. configEnvironmentsSsr.resolve = mergeConfig({ resolve: {
  34007. conditions: config.ssr?.resolve?.conditions,
  34008. externalConditions: config.ssr?.resolve?.externalConditions,
  34009. mainFields: config.ssr?.resolve?.mainFields,
  34010. external: config.ssr?.external,
  34011. noExternal: config.ssr?.noExternal
  34012. } }, { resolve: configEnvironmentsSsr.resolve ?? {} }).resolve;
  34013. }
  34014. if (config.build?.ssrEmitAssets !== void 0) {
  34015. configEnvironmentsSsr ??= {};
  34016. configEnvironmentsSsr.build ??= {};
  34017. configEnvironmentsSsr.build.emitAssets = config.build.ssrEmitAssets;
  34018. }
  34019. if (!config.environments.client || !config.environments.ssr && !isBuild) throw new Error("Required environments configuration were stripped out in the config hook");
  34020. const defaultEnvironmentOptions = getDefaultEnvironmentOptions(config);
  34021. const defaultClientEnvironmentOptions = {
  34022. ...defaultEnvironmentOptions,
  34023. resolve: config.resolve,
  34024. optimizeDeps: config.optimizeDeps
  34025. };
  34026. const defaultNonClientEnvironmentOptions = {
  34027. ...defaultEnvironmentOptions,
  34028. dev: {
  34029. ...defaultEnvironmentOptions.dev,
  34030. createEnvironment: void 0,
  34031. warmup: void 0
  34032. },
  34033. build: {
  34034. ...defaultEnvironmentOptions.build,
  34035. createEnvironment: void 0
  34036. }
  34037. };
  34038. for (const name of Object.keys(config.environments)) config.environments[name] = mergeConfig(name === "client" ? defaultClientEnvironmentOptions : defaultNonClientEnvironmentOptions, config.environments[name]);
  34039. await runConfigEnvironmentHook(config.environments, userPlugins, logger, configEnv, config.ssr?.target === "webworker");
  34040. const isBundledDev = command === "serve" && !!config.experimental?.bundledDev;
  34041. config.resolve ??= {};
  34042. config.resolve.conditions = config.environments.client.resolve?.conditions;
  34043. config.resolve.mainFields = config.environments.client.resolve?.mainFields;
  34044. const resolvedDefaultResolve = resolveResolveOptions(config.resolve, logger);
  34045. const resolvedEnvironments = {};
  34046. 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);
  34047. const backwardCompatibleOptimizeDeps = resolvedEnvironments.client.optimizeDeps;
  34048. const resolvedDevEnvironmentOptions = resolveDevEnvironmentOptions(config.dev, void 0, void 0);
  34049. const resolvedBuildOptions = resolveBuildEnvironmentOptions(config.build ?? {}, logger, void 0, isBundledDev);
  34050. const ssr = resolveSSROptions({
  34051. ...config.ssr,
  34052. external: resolvedEnvironments.ssr?.resolve.external,
  34053. noExternal: resolvedEnvironments.ssr?.resolve.noExternal,
  34054. optimizeDeps: resolvedEnvironments.ssr?.optimizeDeps,
  34055. resolve: {
  34056. ...config.ssr?.resolve,
  34057. conditions: resolvedEnvironments.ssr?.resolve.conditions,
  34058. externalConditions: resolvedEnvironments.ssr?.resolve.externalConditions
  34059. }
  34060. }, resolvedDefaultResolve.preserveSymlinks);
  34061. let envDir = config.envFile === false ? false : config.envDir;
  34062. if (envDir !== false) envDir = config.envDir ? normalizePath(path.resolve(resolvedRoot, config.envDir)) : resolvedRoot;
  34063. const userEnv = loadEnv(mode, envDir, resolveEnvPrefix(config));
  34064. const userNodeEnv = process.env.VITE_USER_NODE_ENV;
  34065. if (!isNodeEnvSet && userNodeEnv) if (userNodeEnv === "development") process.env.NODE_ENV = "development";
  34066. 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.`);
  34067. const isProduction = process.env.NODE_ENV === "production";
  34068. const resolvedBase = config.base === "" || config.base === "./" ? !isBuild || config.build?.ssr ? "/" : "./" : resolveBaseUrl(config.base, isBuild, logger);
  34069. const pkgDir = findNearestPackageData(resolvedRoot, packageCache)?.dir;
  34070. const cacheDir = normalizePath(config.cacheDir ? path.resolve(resolvedRoot, config.cacheDir) : pkgDir ? path.join(pkgDir, `node_modules/.vite`) : path.join(resolvedRoot, `.vite`));
  34071. const assetsFilter = config.assetsInclude && (!Array.isArray(config.assetsInclude) || config.assetsInclude.length) ? createFilter$1(config.assetsInclude) : () => false;
  34072. const { publicDir } = config;
  34073. const resolvedPublicDir = publicDir !== false && publicDir !== "" ? normalizePath(path.resolve(resolvedRoot, typeof publicDir === "string" ? publicDir : configDefaults.publicDir)) : "";
  34074. const server = await resolveServerOptions(resolvedRoot, config.server, logger);
  34075. const builder = resolveBuilderOptions(config.builder);
  34076. const BASE_URL = resolvedBase;
  34077. const resolvedConfigContext = new BasicMinimalPluginContext({
  34078. ...basePluginContextMeta,
  34079. watchMode: command === "serve" && !isPreview || command === "build" && !!resolvedBuildOptions.watch
  34080. }, logger);
  34081. let resolved;
  34082. let createUserWorkerPlugins = config.worker?.plugins;
  34083. if (Array.isArray(createUserWorkerPlugins)) {
  34084. createUserWorkerPlugins = () => config.worker?.plugins;
  34085. 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"));
  34086. }
  34087. const createWorkerPlugins = async function(bundleChain) {
  34088. const rawWorkerUserPlugins = (await asyncFlatten(createUserWorkerPlugins?.() || [])).filter(filterPlugin);
  34089. let workerConfig = mergeConfig({}, config);
  34090. const [workerPrePlugins, workerNormalPlugins, workerPostPlugins] = sortUserPlugins(rawWorkerUserPlugins);
  34091. const workerUserPlugins = [
  34092. ...workerPrePlugins,
  34093. ...workerNormalPlugins,
  34094. ...workerPostPlugins
  34095. ];
  34096. workerConfig = await runConfigHook(workerConfig, workerUserPlugins, configEnv);
  34097. const workerResolved = {
  34098. ...workerConfig,
  34099. ...resolved,
  34100. isWorker: true,
  34101. mainConfig: resolved,
  34102. bundleChain
  34103. };
  34104. workerResolved.plugins = await resolvePlugins(workerResolved, workerPrePlugins, workerNormalPlugins, workerPostPlugins);
  34105. await Promise.all(createPluginHookUtils(workerResolved.plugins).getSortedPluginHooks("configResolved").map((hook) => hook.call(resolvedConfigContext, workerResolved)));
  34106. workerResolved.environments = {
  34107. ...workerResolved.environments,
  34108. client: {
  34109. ...workerResolved.environments.client,
  34110. plugins: await resolveEnvironmentPlugins(new PartialEnvironment("client", workerResolved))
  34111. }
  34112. };
  34113. return workerResolved;
  34114. };
  34115. const resolvedWorkerOptions = {
  34116. format: config.worker?.format || "iife",
  34117. plugins: createWorkerPlugins,
  34118. rollupOptions: config.worker?.rollupOptions || {},
  34119. rolldownOptions: config.worker?.rolldownOptions
  34120. };
  34121. setupRollupOptionCompat(resolvedWorkerOptions, "worker");
  34122. const base = withTrailingSlash(resolvedBase);
  34123. const preview = resolvePreviewOptions(config.preview, server);
  34124. const additionalAllowedHosts = getAdditionalAllowedHosts(server, preview);
  34125. if (Array.isArray(server.allowedHosts)) server.allowedHosts.push(...additionalAllowedHosts);
  34126. if (Array.isArray(preview.allowedHosts)) preview.allowedHosts.push(...additionalAllowedHosts);
  34127. let oxc = config.oxc;
  34128. 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)}\``);
  34129. else oxc = convertEsbuildConfigToOxcConfig(config.esbuild, logger);
  34130. 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."));
  34131. const experimental = mergeWithDefaults(configDefaults.experimental, config.experimental ?? {});
  34132. if (command === "serve" && experimental.bundledDev) experimental.renderBuiltUrl = void 0;
  34133. const resolvedDevToolsConfig = await resolveDevToolsConfig(config.devtools, server.host, logger);
  34134. resolved = {
  34135. configFile: configFile ? normalizePath(configFile) : void 0,
  34136. configFileDependencies: configFileDependencies.map((name) => normalizePath(path.resolve(name))),
  34137. inlineConfig,
  34138. root: resolvedRoot,
  34139. base,
  34140. decodedBase: decodeBase(base),
  34141. rawBase: resolvedBase,
  34142. publicDir: resolvedPublicDir,
  34143. cacheDir,
  34144. command,
  34145. mode,
  34146. isBundled: config.experimental?.bundledDev || isBuild,
  34147. isWorker: false,
  34148. mainConfig: null,
  34149. bundleChain: [],
  34150. isProduction,
  34151. plugins: userPlugins,
  34152. css: resolveCSSOptions(config.css),
  34153. json: mergeWithDefaults(configDefaults.json, config.json ?? {}),
  34154. esbuild: config.esbuild === false ? false : {
  34155. jsxDev: !isProduction,
  34156. charset: "utf8",
  34157. legalComments: "none",
  34158. ...config.esbuild
  34159. },
  34160. oxc: oxc === false ? false : {
  34161. ...oxc,
  34162. jsx: typeof oxc?.jsx === "string" ? oxc.jsx : {
  34163. development: oxc?.jsx?.development ?? !isProduction,
  34164. ...oxc?.jsx
  34165. }
  34166. },
  34167. server,
  34168. builder,
  34169. preview,
  34170. envDir,
  34171. env: {
  34172. ...userEnv,
  34173. BASE_URL,
  34174. MODE: mode,
  34175. DEV: !isProduction,
  34176. PROD: isProduction
  34177. },
  34178. assetsInclude(file) {
  34179. return DEFAULT_ASSETS_RE.test(file) || assetsFilter(file);
  34180. },
  34181. rawAssetsInclude: config.assetsInclude ? arraify(config.assetsInclude) : [],
  34182. logger,
  34183. packageCache,
  34184. worker: resolvedWorkerOptions,
  34185. appType: config.appType ?? "spa",
  34186. experimental,
  34187. future: config.future === "warn" ? {
  34188. removePluginHookHandleHotUpdate: "warn",
  34189. removePluginHookSsrArgument: "warn",
  34190. removeServerModuleGraph: "warn",
  34191. removeServerReloadModule: "warn",
  34192. removeServerPluginContainer: "warn",
  34193. removeServerHot: "warn",
  34194. removeServerTransformRequest: "warn",
  34195. removeServerWarmupRequest: "warn",
  34196. removeSsrLoadModule: "warn"
  34197. } : config.future,
  34198. ssr,
  34199. optimizeDeps: backwardCompatibleOptimizeDeps,
  34200. resolve: resolvedDefaultResolve,
  34201. dev: resolvedDevEnvironmentOptions,
  34202. build: resolvedBuildOptions,
  34203. devtools: resolvedDevToolsConfig,
  34204. environments: resolvedEnvironments,
  34205. webSocketToken: Buffer.from(crypto.getRandomValues(new Uint8Array(9))).toString("base64url"),
  34206. getSortedPlugins: void 0,
  34207. getSortedPluginHooks: void 0,
  34208. createResolver(options) {
  34209. const resolve = createIdResolver(this, options);
  34210. const clientEnvironment = new PartialEnvironment("client", this);
  34211. let ssrEnvironment;
  34212. return async (id, importer, aliasOnly, ssr) => {
  34213. if (ssr) ssrEnvironment ??= new PartialEnvironment("ssr", this);
  34214. return await resolve(ssr ? ssrEnvironment : clientEnvironment, id, importer, aliasOnly);
  34215. };
  34216. },
  34217. fsDenyGlob: picomatch(server.fs.deny.map((pattern) => pattern.includes("/") ? pattern : `**/${pattern}`), {
  34218. matchBase: false,
  34219. nocase: true,
  34220. dot: true
  34221. }),
  34222. safeModulePaths: /* @__PURE__ */ new Set(),
  34223. [SYMBOL_RESOLVED_CONFIG]: true
  34224. };
  34225. resolved = {
  34226. ...config,
  34227. ...resolved
  34228. };
  34229. patchConfig?.(resolved);
  34230. const resolvedPlugins = await resolvePlugins(resolved, prePlugins, normalPlugins, postPlugins);
  34231. patchPlugins?.(resolvedPlugins);
  34232. resolved.plugins = resolvedPlugins;
  34233. Object.assign(resolved, createPluginHookUtils(resolved.plugins));
  34234. await Promise.all(resolved.getSortedPluginHooks("configResolved").map((hook) => hook.call(resolvedConfigContext, resolved)));
  34235. for (const name of Object.keys(resolved.environments)) resolved.environments[name].plugins = await resolveEnvironmentPlugins(new PartialEnvironment(name, resolved));
  34236. optimizeDepsDisabledBackwardCompatibility(resolved, resolved.optimizeDeps);
  34237. optimizeDepsDisabledBackwardCompatibility(resolved, resolved.ssr.optimizeDeps, "ssr.");
  34238. if (!resolved.builder?.sharedConfigBuild && resolved.environments.ssr) resolved.environments.ssr.build.emitAssets = resolved.build.ssrEmitAssets || resolved.build.emitAssets;
  34239. if (resolved.devtools.enabled) resolved.build.rolldownOptions.devtools ??= {};
  34240. applyDepOptimizationOptionCompat(resolved);
  34241. await setOptimizeDepsPluginNames(resolved);
  34242. debug?.(`using resolved config: %O`, {
  34243. ...resolved,
  34244. plugins: resolved.plugins.map((p) => p.name),
  34245. worker: {
  34246. ...resolved.worker,
  34247. plugins: `() => plugins`
  34248. }
  34249. });
  34250. const outputOption = config.build?.rollupOptions?.output ?? [];
  34251. if (Array.isArray(outputOption)) {
  34252. const assetFileNamesList = outputOption.map((output) => output.assetFileNames);
  34253. if (assetFileNamesList.length > 1) {
  34254. const firstAssetFileNames = assetFileNamesList[0];
  34255. if (assetFileNamesList.some((assetFileNames) => assetFileNames !== firstAssetFileNames)) resolved.logger.warn(import_picocolors.default.yellow(`
  34256. assetFileNames isn't equal for every build.rollupOptions.output. A single pattern across all outputs is supported by Vite.
  34257. `));
  34258. }
  34259. }
  34260. if (config.legacy?.buildSsrCjsExternalHeuristics || config.ssr?.format === "cjs") resolved.logger.warn(import_picocolors.default.yellow(`
  34261. (!) Experimental legacy.buildSsrCjsExternalHeuristics and ssr.format were be removed in Vite 5.
  34262. The only SSR Output format is ESM. Find more information at https://github.com/vitejs/vite/discussions/13816.
  34263. `));
  34264. const resolvedBuildOutDir = normalizePath(path.resolve(resolved.root, resolved.build.outDir));
  34265. if (isParentDirectory(resolvedBuildOutDir, resolved.root) || resolvedBuildOutDir === resolved.root) resolved.logger.warn(import_picocolors.default.yellow(`
  34266. (!) 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.
  34267. `));
  34268. return resolved;
  34269. }
  34270. /**
  34271. * Resolve base url. Note that some users use Vite to build for non-web targets like
  34272. * electron or expects to deploy
  34273. */
  34274. function resolveBaseUrl(base = configDefaults.base, isBuild, logger) {
  34275. if (base[0] === ".") {
  34276. 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.`)));
  34277. return "/";
  34278. }
  34279. const isExternal = isExternalUrl(base);
  34280. if (!isExternal && base[0] !== "/") logger.warn(import_picocolors.default.yellow(import_picocolors.default.bold(`(!) "base" option should start with a slash.`)));
  34281. if (!isBuild || !isExternal) {
  34282. base = new URL(base, "http://vite.dev").pathname;
  34283. if (base[0] !== "/") base = "/" + base;
  34284. }
  34285. return base;
  34286. }
  34287. function decodeBase(base) {
  34288. try {
  34289. return decodeURI(base);
  34290. } catch {
  34291. throw new Error("The value passed to \"base\" option was malformed. It should be a valid URL.");
  34292. }
  34293. }
  34294. function sortUserPlugins(plugins) {
  34295. const prePlugins = [];
  34296. const postPlugins = [];
  34297. const normalPlugins = [];
  34298. if (plugins) plugins.flat().forEach((p) => {
  34299. if (p.enforce === "pre") prePlugins.push(p);
  34300. else if (p.enforce === "post") postPlugins.push(p);
  34301. else normalPlugins.push(p);
  34302. });
  34303. return [
  34304. prePlugins,
  34305. normalPlugins,
  34306. postPlugins
  34307. ];
  34308. }
  34309. async function loadConfigFromFile(configEnv, configFile, configRoot = process.cwd(), logLevel, customLogger, configLoader = "bundle") {
  34310. if (configLoader !== "bundle" && configLoader !== "runner" && configLoader !== "native") throw new Error(`Unsupported configLoader: ${configLoader}. Accepted values are 'bundle', 'runner', and 'native'.`);
  34311. const start = performance$1.now();
  34312. const getTime = () => `${(performance$1.now() - start).toFixed(2)}ms`;
  34313. let resolvedPath;
  34314. if (configFile) resolvedPath = path.resolve(configFile);
  34315. else for (const filename of DEFAULT_CONFIG_FILES) {
  34316. const filePath = path.resolve(configRoot, filename);
  34317. if (!fs.existsSync(filePath)) continue;
  34318. resolvedPath = filePath;
  34319. break;
  34320. }
  34321. if (!resolvedPath) {
  34322. debug?.("no config file found.");
  34323. return null;
  34324. }
  34325. try {
  34326. const { configExport, dependencies } = await (configLoader === "bundle" ? bundleAndLoadConfigFile : configLoader === "runner" ? runnerImportConfigFile : nativeImportConfigFile)(resolvedPath);
  34327. debug?.(`config file loaded in ${getTime()}`);
  34328. const config = await (typeof configExport === "function" ? configExport(configEnv) : configExport);
  34329. if (!isObject$1(config)) throw new Error(`config must export or return an object.`);
  34330. return {
  34331. path: normalizePath(resolvedPath),
  34332. config,
  34333. dependencies
  34334. };
  34335. } catch (e) {
  34336. const logger = createLogger(logLevel, { customLogger });
  34337. checkBadCharactersInPath("The config path", resolvedPath, logger);
  34338. logger.error(import_picocolors.default.red(`failed to load config from ${resolvedPath}`), { error: e });
  34339. throw e;
  34340. }
  34341. }
  34342. async function nativeImportConfigFile(resolvedPath) {
  34343. return {
  34344. configExport: (await import(pathToFileURL(resolvedPath).href + "?t=" + Date.now())).default,
  34345. dependencies: []
  34346. };
  34347. }
  34348. async function runnerImportConfigFile(resolvedPath) {
  34349. const { module, dependencies } = await runnerImport(resolvedPath);
  34350. return {
  34351. configExport: module.default,
  34352. dependencies
  34353. };
  34354. }
  34355. async function bundleAndLoadConfigFile(resolvedPath) {
  34356. const isESM = typeof process.versions.deno === "string" || isFilePathESM(resolvedPath);
  34357. const bundled = await bundleConfigFile(resolvedPath, isESM);
  34358. return {
  34359. configExport: await loadConfigFromBundledFile(resolvedPath, bundled.code, isESM),
  34360. dependencies: bundled.dependencies
  34361. };
  34362. }
  34363. async function bundleConfigFile(fileName, isESM) {
  34364. let importMetaResolverRegistered = false;
  34365. const root = path.dirname(fileName);
  34366. const dirnameVarName = "__vite_injected_original_dirname";
  34367. const filenameVarName = "__vite_injected_original_filename";
  34368. const importMetaUrlVarName = "__vite_injected_original_import_meta_url";
  34369. const importMetaResolveVarName = "__vite_injected_original_import_meta_resolve";
  34370. const importMetaResolveRegex = /import\.meta\s*\.\s*resolve/;
  34371. const bundle = await rolldown({
  34372. input: fileName,
  34373. platform: "node",
  34374. resolve: { mainFields: ["main"] },
  34375. transform: { define: {
  34376. __dirname: dirnameVarName,
  34377. __filename: filenameVarName,
  34378. "import.meta.url": importMetaUrlVarName,
  34379. "import.meta.dirname": dirnameVarName,
  34380. "import.meta.filename": filenameVarName,
  34381. "import.meta.resolve": importMetaResolveVarName,
  34382. "import.meta.main": "false"
  34383. } },
  34384. treeshake: false,
  34385. tsconfig: false,
  34386. plugins: [{
  34387. name: "externalize-deps",
  34388. resolveId: {
  34389. filter: { id: /^[^.#].*/ },
  34390. async handler(id, importer, { kind }) {
  34391. if (!importer || path.isAbsolute(id) || isNodeBuiltin(id)) return;
  34392. if (isNodeLikeBuiltin(id) || id.startsWith("npm:")) return {
  34393. id,
  34394. external: true
  34395. };
  34396. const isImport = isESM || kind === "dynamic-import";
  34397. let idFsPath;
  34398. try {
  34399. idFsPath = nodeResolveWithVite(id, importer, {
  34400. root,
  34401. isRequire: !isImport
  34402. });
  34403. } catch (e) {
  34404. if (!isImport) {
  34405. let canResolveWithImport = false;
  34406. try {
  34407. canResolveWithImport = !!nodeResolveWithVite(id, importer, { root });
  34408. } catch {}
  34409. 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.`);
  34410. }
  34411. throw e;
  34412. }
  34413. if (!idFsPath) return;
  34414. if (idFsPath.endsWith(".json")) return idFsPath;
  34415. if (idFsPath && isImport) idFsPath = pathToFileURL(idFsPath).href;
  34416. return {
  34417. id: idFsPath,
  34418. external: true
  34419. };
  34420. }
  34421. }
  34422. }, {
  34423. name: "inject-file-scope-variables",
  34424. transform: {
  34425. filter: { id: /\.[cm]?[jt]s$/ },
  34426. handler(code, id) {
  34427. let injectValues = `const ${dirnameVarName} = ${JSON.stringify(path.dirname(id))};const ${filenameVarName} = ${JSON.stringify(id)};const ${importMetaUrlVarName} = ${JSON.stringify(pathToFileURL(id).href)};`;
  34428. if (importMetaResolveRegex.test(code)) if (isESM) {
  34429. if (!importMetaResolverRegistered) {
  34430. importMetaResolverRegistered = true;
  34431. createImportMetaResolver();
  34432. }
  34433. injectValues += `const ${importMetaResolveVarName} = (specifier, importer = ${importMetaUrlVarName}) => (${importMetaResolveWithCustomHookString})(specifier, importer);`;
  34434. } else injectValues += `const ${importMetaResolveVarName} = (specifier, importer = ${importMetaUrlVarName}) => { throw new Error('import.meta.resolve is not supported in CJS config files') };`;
  34435. let injectedContents;
  34436. if (code.startsWith("#!")) {
  34437. let firstLineEndIndex = code.indexOf("\n");
  34438. if (firstLineEndIndex < 0) firstLineEndIndex = code.length;
  34439. injectedContents = code.slice(0, firstLineEndIndex + 1) + injectValues + code.slice(firstLineEndIndex + 1);
  34440. } else injectedContents = injectValues + code;
  34441. return {
  34442. code: injectedContents,
  34443. map: null
  34444. };
  34445. }
  34446. }
  34447. }]
  34448. });
  34449. const result = await bundle.generate({
  34450. format: isESM ? "esm" : "cjs",
  34451. sourcemap: "inline",
  34452. sourcemapPathTransform(relative) {
  34453. return path.resolve(fileName, relative);
  34454. },
  34455. codeSplitting: false
  34456. });
  34457. await bundle.close();
  34458. const entryChunk = result.output.find((chunk) => chunk.type === "chunk" && chunk.isEntry);
  34459. const bundleChunks = Object.fromEntries(result.output.flatMap((c) => c.type === "chunk" ? [[c.fileName, c]] : []));
  34460. const allModules = /* @__PURE__ */ new Set();
  34461. collectAllModules(bundleChunks, entryChunk.fileName, allModules);
  34462. return {
  34463. code: entryChunk.code,
  34464. dependencies: [...allModules].filter((m) => !m.startsWith("\0"))
  34465. };
  34466. }
  34467. function collectAllModules(bundle, fileName, allModules, analyzedModules = /* @__PURE__ */ new Set()) {
  34468. if (analyzedModules.has(fileName)) return;
  34469. analyzedModules.add(fileName);
  34470. const chunk = bundle[fileName];
  34471. for (const mod of chunk.moduleIds) allModules.add(mod);
  34472. for (const i of chunk.imports) {
  34473. analyzedModules.add(i);
  34474. collectAllModules(bundle, i, allModules, analyzedModules);
  34475. }
  34476. for (const i of chunk.dynamicImports) {
  34477. analyzedModules.add(i);
  34478. collectAllModules(bundle, i, allModules, analyzedModules);
  34479. }
  34480. }
  34481. const _require = createRequire(
  34482. /** #__KEEP__ */
  34483. import.meta.url
  34484. );
  34485. async function loadConfigFromBundledFile(fileName, bundledCode, isESM) {
  34486. if (isESM) {
  34487. let nodeModulesDir = typeof process.versions.deno === "string" ? void 0 : findNearestNodeModules(path.dirname(fileName));
  34488. if (nodeModulesDir) try {
  34489. await fsp.mkdir(path.resolve(nodeModulesDir, ".vite-temp/"), { recursive: true });
  34490. } catch (e) {
  34491. if (e.code === "EACCES") nodeModulesDir = void 0;
  34492. else throw e;
  34493. }
  34494. const hash = `timestamp-${Date.now()}-${Math.random().toString(16).slice(2)}`;
  34495. const tempFileName = nodeModulesDir ? path.resolve(nodeModulesDir, `.vite-temp/${path.basename(fileName)}.${hash}.mjs`) : `${fileName}.${hash}.mjs`;
  34496. await fsp.writeFile(tempFileName, bundledCode);
  34497. try {
  34498. return (await import(pathToFileURL(tempFileName).href)).default;
  34499. } finally {
  34500. fs.unlink(tempFileName, () => {});
  34501. }
  34502. } else {
  34503. const extension = path.extname(fileName);
  34504. const realFileName = await promisifiedRealpath(fileName);
  34505. const loaderExt = extension in _require.extensions ? extension : ".js";
  34506. const defaultLoader = _require.extensions[loaderExt];
  34507. _require.extensions[loaderExt] = (module, filename) => {
  34508. if (filename === realFileName) module._compile(bundledCode, filename);
  34509. else defaultLoader(module, filename);
  34510. };
  34511. delete _require.cache[_require.resolve(fileName)];
  34512. const raw = _require(fileName);
  34513. _require.extensions[loaderExt] = defaultLoader;
  34514. return raw.__esModule ? raw.default : raw;
  34515. }
  34516. }
  34517. async function runConfigHook(config, plugins, configEnv) {
  34518. let conf = config;
  34519. const context = new BasicMinimalPluginContext(basePluginContextMeta, createLogger(config.logLevel, {
  34520. allowClearScreen: config.clearScreen,
  34521. customLogger: config.customLogger
  34522. }));
  34523. for (const p of getSortedPluginsByHook("config", plugins)) {
  34524. const hook = p.config;
  34525. const res = await getHookHandler(hook).call(context, conf, configEnv);
  34526. if (res && res !== conf) {
  34527. 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.`);
  34528. if (res.esbuild) context.warn(`\`esbuild\` option was specified by ${JSON.stringify(p.name)} plugin. This option is deprecated, please use \`oxc\` instead.`);
  34529. 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.`);
  34530. conf = mergeConfig(conf, res);
  34531. }
  34532. }
  34533. return conf;
  34534. }
  34535. async function runConfigEnvironmentHook(environments, plugins, logger, configEnv, isSsrTargetWebworkerSet) {
  34536. const context = new BasicMinimalPluginContext(basePluginContextMeta, logger);
  34537. const environmentNames = Object.keys(environments);
  34538. for (const p of getSortedPluginsByHook("configEnvironment", plugins)) {
  34539. const hook = p.configEnvironment;
  34540. const handler = getHookHandler(hook);
  34541. for (const name of environmentNames) {
  34542. const res = await handler.call(context, name, environments[name], {
  34543. ...configEnv,
  34544. isSsrTargetWebworker: isSsrTargetWebworkerSet && name === "ssr"
  34545. });
  34546. if (res) environments[name] = mergeConfig(environments[name], res);
  34547. }
  34548. }
  34549. }
  34550. function optimizeDepsDisabledBackwardCompatibility(resolved, optimizeDeps, optimizeDepsPath = "") {
  34551. const optimizeDepsDisabled = optimizeDeps.disabled;
  34552. if (optimizeDepsDisabled !== void 0) {
  34553. if (optimizeDepsDisabled === true || optimizeDepsDisabled === "dev") {
  34554. const commonjsOptionsInclude = resolved.build.commonjsOptions.include;
  34555. const commonjsPluginDisabled = Array.isArray(commonjsOptionsInclude) && commonjsOptionsInclude.length === 0;
  34556. optimizeDeps.noDiscovery = true;
  34557. optimizeDeps.include = void 0;
  34558. if (commonjsPluginDisabled) resolved.build.commonjsOptions.include = void 0;
  34559. resolved.logger.warn(import_picocolors.default.yellow(`(!) Experimental ${optimizeDepsPath}optimizeDeps.disabled and deps pre-bundling during build were removed in Vite 5.1.
  34560. To disable the deps optimizer, set ${optimizeDepsPath}optimizeDeps.noDiscovery to true and ${optimizeDepsPath}optimizeDeps.include as undefined or empty.
  34561. Please remove ${optimizeDepsPath}optimizeDeps.disabled from your config.
  34562. ${commonjsPluginDisabled ? "Empty config.build.commonjsOptions.include will be ignored to support CJS during build. This config should also be removed." : ""}
  34563. `));
  34564. } 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.
  34565. Setting it to ${optimizeDepsDisabled} now has no effect.
  34566. Please remove ${optimizeDepsPath}optimizeDeps.disabled from your config.
  34567. `));
  34568. }
  34569. }
  34570. //#endregion
  34571. //#region src/node/server/environments/fetchableEnvironments.ts
  34572. function createFetchableDevEnvironment(name, config, context) {
  34573. if (typeof Request === "undefined" || typeof Response === "undefined") throw new TypeError("FetchableDevEnvironment requires a global `Request` and `Response` object.");
  34574. if (!context.handleRequest) throw new TypeError("FetchableDevEnvironment requires a `handleRequest` method during initialisation.");
  34575. return new FetchableDevEnvironment(name, config, context);
  34576. }
  34577. function isFetchableDevEnvironment(environment) {
  34578. return environment instanceof FetchableDevEnvironment;
  34579. }
  34580. var FetchableDevEnvironment = class extends DevEnvironment {
  34581. _handleRequest;
  34582. constructor(name, config, context) {
  34583. super(name, config, context);
  34584. this._handleRequest = context.handleRequest;
  34585. }
  34586. async dispatchFetch(request) {
  34587. if (!(request instanceof Request)) throw new TypeError("FetchableDevEnvironment `dispatchFetch` must receive a `Request` object.");
  34588. const response = await this._handleRequest(request);
  34589. if (!(response instanceof Response)) throw new TypeError("FetchableDevEnvironment `context.handleRequest` must return a `Response` object.");
  34590. return response;
  34591. }
  34592. };
  34593. //#endregion
  34594. //#region src/node/index.ts
  34595. /** @deprecated - use `parse` instead */
  34596. const parseAst$1 = parseAst;
  34597. /** @deprecated - use `parseAsync` instead */
  34598. const parseAstAsync$1 = parseAstAsync;
  34599. const esbuildVersion = "0.25.0";
  34600. //#endregion
  34601. export { depsFromOptimizedDepInfo as $, builderOptionsDefaults as A, searchForWorkspaceRoot as At, resolveBuilderOptions as B, transformWithEsbuild as Bt, resolvePreviewOptions as C, send 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 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, DevEnvironment as wt, runnerImport as x, restartServerWithUrls as xt, resolveDevToolsConfig as y, resolveForwardConsoleOptions as yt, resolveBuildPlugins as z, transformWithOxc as zt };