dep-DBxKXgDP.js 1.4 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496
  1. import * as fs$8 from 'node:fs';
  2. import fs__default, { promises as promises$1, existsSync as existsSync$1, readFileSync as readFileSync$1 } from 'node:fs';
  3. import path$b, { posix as posix$1, isAbsolute as isAbsolute$1, join as join$1, resolve as resolve$4, normalize, dirname as dirname$2, relative as relative$2, basename as basename$2, extname as extname$1 } from 'node:path';
  4. import fsp, { constants as constants$3 } from 'node:fs/promises';
  5. import require$$1$1, { fileURLToPath as fileURLToPath$1, URL as URL$3, pathToFileURL as pathToFileURL$1 } from 'node:url';
  6. import { promisify as promisify$4, format as format$2, inspect, stripVTControlCharacters } from 'node:util';
  7. import { performance as performance$1 } from 'node:perf_hooks';
  8. import require$$0$6, { createRequire as createRequire$1, builtinModules } from 'node:module';
  9. import crypto$2 from 'node:crypto';
  10. import picomatch$2 from 'picomatch';
  11. import esbuild, { transform as transform$1, formatMessages, build as build$3 } from 'esbuild';
  12. import { CLIENT_ENTRY, wildcardHosts, loopbackHosts, OPTIMIZABLE_ENTRY_RE, FS_PREFIX, CLIENT_PUBLIC_PATH, ENV_PUBLIC_PATH, DEFAULT_ASSETS_INLINE_LIMIT, SPECIAL_QUERY_RE, KNOWN_ASSET_TYPES, JS_TYPES_RE, CSS_LANGS_RE, METADATA_FILENAME, ESBUILD_MODULES_TARGET, ENV_ENTRY, DEP_VERSION_RE, DEV_PROD_CONDITION, ERR_OPTIMIZE_DEPS_PROCESSING_ERROR, ERR_FILE_NOT_FOUND_IN_OPTIMIZED_DEP_DIR, VITE_PACKAGE_DIR, defaultAllowedOrigins, DEFAULT_DEV_PORT, CLIENT_DIR, VERSION, ROLLUP_HOOKS, DEFAULT_PREVIEW_PORT, DEFAULT_ASSETS_RE, DEFAULT_CONFIG_FILES, DEFAULT_CLIENT_CONDITIONS, DEFAULT_SERVER_CONDITIONS, DEFAULT_CLIENT_MAIN_FIELDS, DEFAULT_SERVER_MAIN_FIELDS } from '../constants.js';
  13. import require$$0$2, { posix, isAbsolute, resolve as resolve$3, win32, relative as relative$1, join, dirname as dirname$1, extname, basename as basename$1, sep } from 'path';
  14. import require$$0$4, { statSync, existsSync, readFileSync, readdirSync } from 'fs';
  15. import { fdir } from 'fdir';
  16. import childProcess$2, { exec, execFile, execSync } from 'node:child_process';
  17. import { createServer as createServer$3, STATUS_CODES, get as get$2 } from 'node:http';
  18. import { createServer as createServer$2, get as get$1 } from 'node:https';
  19. import require$$0$3 from 'tty';
  20. import require$$1 from 'util';
  21. import require$$4$1 from 'net';
  22. import require$$0$7 from 'events';
  23. import require$$0$5 from 'url';
  24. import require$$1$2 from 'http';
  25. import require$$0$8 from 'stream';
  26. import require$$2 from 'os';
  27. import require$$2$1 from 'child_process';
  28. import os$3 from 'node:os';
  29. import net$1 from 'node:net';
  30. import { promises } from 'node:dns';
  31. import { ModuleRunner, ESModulesEvaluator } from 'vite/module-runner';
  32. import { parseAstAsync, parseAst } from 'rollup/parseAst';
  33. import { Buffer as Buffer$1 } from 'node:buffer';
  34. import { createRequire as createRequire$2 } from 'module';
  35. import readline from 'node:readline';
  36. import process$1 from 'node:process';
  37. import { EventEmitter as EventEmitter$4 } from 'node:events';
  38. import { glob, escapePath, isDynamicPattern, globSync } from 'tinyglobby';
  39. import require$$3 from 'crypto';
  40. import assert$1 from 'node:assert';
  41. import v8 from 'node:v8';
  42. import { Worker as Worker$1, MessageChannel } from 'node:worker_threads';
  43. import require$$1$3 from 'https';
  44. import require$$4$2 from 'tls';
  45. import zlib$1 from 'zlib';
  46. import require$$0$9 from 'buffer';
  47. import require$$4$3 from 'assert';
  48. import * as qs from 'node:querystring';
  49. import { gzip } from 'node:zlib';
  50. import { createRequire as __cjs_createRequire } from 'node:module';
  51. const __require = __cjs_createRequire(import.meta.url);
  52. var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
  53. function getDefaultExportFromCjs (x) {
  54. return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
  55. }
  56. var picocolors = {exports: {}};
  57. let p = process || {}, argv = p.argv || [], env$1 = p.env || {};
  58. let isColorSupported =
  59. !(!!env$1.NO_COLOR || argv.includes("--no-color")) &&
  60. (!!env$1.FORCE_COLOR || argv.includes("--color") || p.platform === "win32" || ((p.stdout || {}).isTTY && env$1.TERM !== "dumb") || !!env$1.CI);
  61. let formatter = (open, close, replace = open) =>
  62. input => {
  63. let string = "" + input, index = string.indexOf(close, open.length);
  64. return ~index ? open + replaceClose(string, close, replace, index) + close : open + string + close
  65. };
  66. let replaceClose = (string, close, replace, index) => {
  67. let result = "", cursor = 0;
  68. do {
  69. result += string.substring(cursor, index) + replace;
  70. cursor = index + close.length;
  71. index = string.indexOf(close, cursor);
  72. } while (~index)
  73. return result + string.substring(cursor)
  74. };
  75. let createColors = (enabled = isColorSupported) => {
  76. let f = enabled ? formatter : () => String;
  77. return {
  78. isColorSupported: enabled,
  79. reset: f("\x1b[0m", "\x1b[0m"),
  80. bold: f("\x1b[1m", "\x1b[22m", "\x1b[22m\x1b[1m"),
  81. dim: f("\x1b[2m", "\x1b[22m", "\x1b[22m\x1b[2m"),
  82. italic: f("\x1b[3m", "\x1b[23m"),
  83. underline: f("\x1b[4m", "\x1b[24m"),
  84. inverse: f("\x1b[7m", "\x1b[27m"),
  85. hidden: f("\x1b[8m", "\x1b[28m"),
  86. strikethrough: f("\x1b[9m", "\x1b[29m"),
  87. black: f("\x1b[30m", "\x1b[39m"),
  88. red: f("\x1b[31m", "\x1b[39m"),
  89. green: f("\x1b[32m", "\x1b[39m"),
  90. yellow: f("\x1b[33m", "\x1b[39m"),
  91. blue: f("\x1b[34m", "\x1b[39m"),
  92. magenta: f("\x1b[35m", "\x1b[39m"),
  93. cyan: f("\x1b[36m", "\x1b[39m"),
  94. white: f("\x1b[37m", "\x1b[39m"),
  95. gray: f("\x1b[90m", "\x1b[39m"),
  96. bgBlack: f("\x1b[40m", "\x1b[49m"),
  97. bgRed: f("\x1b[41m", "\x1b[49m"),
  98. bgGreen: f("\x1b[42m", "\x1b[49m"),
  99. bgYellow: f("\x1b[43m", "\x1b[49m"),
  100. bgBlue: f("\x1b[44m", "\x1b[49m"),
  101. bgMagenta: f("\x1b[45m", "\x1b[49m"),
  102. bgCyan: f("\x1b[46m", "\x1b[49m"),
  103. bgWhite: f("\x1b[47m", "\x1b[49m"),
  104. blackBright: f("\x1b[90m", "\x1b[39m"),
  105. redBright: f("\x1b[91m", "\x1b[39m"),
  106. greenBright: f("\x1b[92m", "\x1b[39m"),
  107. yellowBright: f("\x1b[93m", "\x1b[39m"),
  108. blueBright: f("\x1b[94m", "\x1b[39m"),
  109. magentaBright: f("\x1b[95m", "\x1b[39m"),
  110. cyanBright: f("\x1b[96m", "\x1b[39m"),
  111. whiteBright: f("\x1b[97m", "\x1b[39m"),
  112. bgBlackBright: f("\x1b[100m", "\x1b[49m"),
  113. bgRedBright: f("\x1b[101m", "\x1b[49m"),
  114. bgGreenBright: f("\x1b[102m", "\x1b[49m"),
  115. bgYellowBright: f("\x1b[103m", "\x1b[49m"),
  116. bgBlueBright: f("\x1b[104m", "\x1b[49m"),
  117. bgMagentaBright: f("\x1b[105m", "\x1b[49m"),
  118. bgCyanBright: f("\x1b[106m", "\x1b[49m"),
  119. bgWhiteBright: f("\x1b[107m", "\x1b[49m"),
  120. }
  121. };
  122. picocolors.exports = createColors();
  123. picocolors.exports.createColors = createColors;
  124. var picocolorsExports = picocolors.exports;
  125. var colors$1 = /*@__PURE__*/getDefaultExportFromCjs(picocolorsExports);
  126. const VALID_ID_PREFIX = `/@id/`;
  127. const NULL_BYTE_PLACEHOLDER = `__x00__`;
  128. let SOURCEMAPPING_URL = "sourceMa";
  129. SOURCEMAPPING_URL += "ppingURL";
  130. const MODULE_RUNNER_SOURCEMAPPING_SOURCE = "//# sourceMappingSource=vite-generated";
  131. const ERR_OUTDATED_OPTIMIZED_DEP = "ERR_OUTDATED_OPTIMIZED_DEP";
  132. const isWindows$3 = typeof process !== "undefined" && process.platform === "win32";
  133. function wrapId$1(id) {
  134. return id.startsWith(VALID_ID_PREFIX) ? id : VALID_ID_PREFIX + id.replace("\0", NULL_BYTE_PLACEHOLDER);
  135. }
  136. function unwrapId$1(id) {
  137. return id.startsWith(VALID_ID_PREFIX) ? id.slice(VALID_ID_PREFIX.length).replace(NULL_BYTE_PLACEHOLDER, "\0") : id;
  138. }
  139. const windowsSlashRE = /\\/g;
  140. function slash$1(p) {
  141. return p.replace(windowsSlashRE, "/");
  142. }
  143. const postfixRE = /[?#].*$/;
  144. function cleanUrl(url) {
  145. return url.replace(postfixRE, "");
  146. }
  147. function splitFileAndPostfix(path) {
  148. const file = cleanUrl(path);
  149. return { file, postfix: path.slice(file.length) };
  150. }
  151. function withTrailingSlash(path) {
  152. if (path[path.length - 1] !== "/") {
  153. return `${path}/`;
  154. }
  155. return path;
  156. }
  157. function promiseWithResolvers() {
  158. let resolve;
  159. let reject;
  160. const promise = new Promise((_resolve, _reject) => {
  161. resolve = _resolve;
  162. reject = _reject;
  163. });
  164. return { promise, resolve, reject };
  165. }
  166. // @ts-check
  167. /** @typedef { import('estree').BaseNode} BaseNode */
  168. /** @typedef {{
  169. skip: () => void;
  170. remove: () => void;
  171. replace: (node: BaseNode) => void;
  172. }} WalkerContext */
  173. let WalkerBase$1 = class WalkerBase {
  174. constructor() {
  175. /** @type {boolean} */
  176. this.should_skip = false;
  177. /** @type {boolean} */
  178. this.should_remove = false;
  179. /** @type {BaseNode | null} */
  180. this.replacement = null;
  181. /** @type {WalkerContext} */
  182. this.context = {
  183. skip: () => (this.should_skip = true),
  184. remove: () => (this.should_remove = true),
  185. replace: (node) => (this.replacement = node)
  186. };
  187. }
  188. /**
  189. *
  190. * @param {any} parent
  191. * @param {string} prop
  192. * @param {number} index
  193. * @param {BaseNode} node
  194. */
  195. replace(parent, prop, index, node) {
  196. if (parent) {
  197. if (index !== null) {
  198. parent[prop][index] = node;
  199. } else {
  200. parent[prop] = node;
  201. }
  202. }
  203. }
  204. /**
  205. *
  206. * @param {any} parent
  207. * @param {string} prop
  208. * @param {number} index
  209. */
  210. remove(parent, prop, index) {
  211. if (parent) {
  212. if (index !== null) {
  213. parent[prop].splice(index, 1);
  214. } else {
  215. delete parent[prop];
  216. }
  217. }
  218. }
  219. };
  220. // @ts-check
  221. /** @typedef { import('estree').BaseNode} BaseNode */
  222. /** @typedef { import('./walker.js').WalkerContext} WalkerContext */
  223. /** @typedef {(
  224. * this: WalkerContext,
  225. * node: BaseNode,
  226. * parent: BaseNode,
  227. * key: string,
  228. * index: number
  229. * ) => void} SyncHandler */
  230. let SyncWalker$1 = class SyncWalker extends WalkerBase$1 {
  231. /**
  232. *
  233. * @param {SyncHandler} enter
  234. * @param {SyncHandler} leave
  235. */
  236. constructor(enter, leave) {
  237. super();
  238. /** @type {SyncHandler} */
  239. this.enter = enter;
  240. /** @type {SyncHandler} */
  241. this.leave = leave;
  242. }
  243. /**
  244. *
  245. * @param {BaseNode} node
  246. * @param {BaseNode} parent
  247. * @param {string} [prop]
  248. * @param {number} [index]
  249. * @returns {BaseNode}
  250. */
  251. visit(node, parent, prop, index) {
  252. if (node) {
  253. if (this.enter) {
  254. const _should_skip = this.should_skip;
  255. const _should_remove = this.should_remove;
  256. const _replacement = this.replacement;
  257. this.should_skip = false;
  258. this.should_remove = false;
  259. this.replacement = null;
  260. this.enter.call(this.context, node, parent, prop, index);
  261. if (this.replacement) {
  262. node = this.replacement;
  263. this.replace(parent, prop, index, node);
  264. }
  265. if (this.should_remove) {
  266. this.remove(parent, prop, index);
  267. }
  268. const skipped = this.should_skip;
  269. const removed = this.should_remove;
  270. this.should_skip = _should_skip;
  271. this.should_remove = _should_remove;
  272. this.replacement = _replacement;
  273. if (skipped) return node;
  274. if (removed) return null;
  275. }
  276. for (const key in node) {
  277. const value = node[key];
  278. if (typeof value !== "object") {
  279. continue;
  280. } else if (Array.isArray(value)) {
  281. for (let i = 0; i < value.length; i += 1) {
  282. if (value[i] !== null && typeof value[i].type === 'string') {
  283. if (!this.visit(value[i], node, key, i)) {
  284. // removed
  285. i--;
  286. }
  287. }
  288. }
  289. } else if (value !== null && typeof value.type === "string") {
  290. this.visit(value, node, key, null);
  291. }
  292. }
  293. if (this.leave) {
  294. const _replacement = this.replacement;
  295. const _should_remove = this.should_remove;
  296. this.replacement = null;
  297. this.should_remove = false;
  298. this.leave.call(this.context, node, parent, prop, index);
  299. if (this.replacement) {
  300. node = this.replacement;
  301. this.replace(parent, prop, index, node);
  302. }
  303. if (this.should_remove) {
  304. this.remove(parent, prop, index);
  305. }
  306. const removed = this.should_remove;
  307. this.replacement = _replacement;
  308. this.should_remove = _should_remove;
  309. if (removed) return null;
  310. }
  311. }
  312. return node;
  313. }
  314. };
  315. // @ts-check
  316. /** @typedef { import('estree').BaseNode} BaseNode */
  317. /** @typedef { import('./sync.js').SyncHandler} SyncHandler */
  318. /** @typedef { import('./async.js').AsyncHandler} AsyncHandler */
  319. /**
  320. *
  321. * @param {BaseNode} ast
  322. * @param {{
  323. * enter?: SyncHandler
  324. * leave?: SyncHandler
  325. * }} walker
  326. * @returns {BaseNode}
  327. */
  328. function walk$2(ast, { enter, leave }) {
  329. const instance = new SyncWalker$1(enter, leave);
  330. return instance.visit(ast, null);
  331. }
  332. const extractors = {
  333. ArrayPattern(names, param) {
  334. for (const element of param.elements) {
  335. if (element)
  336. extractors[element.type](names, element);
  337. }
  338. },
  339. AssignmentPattern(names, param) {
  340. extractors[param.left.type](names, param.left);
  341. },
  342. Identifier(names, param) {
  343. names.push(param.name);
  344. },
  345. MemberExpression() { },
  346. ObjectPattern(names, param) {
  347. for (const prop of param.properties) {
  348. // @ts-ignore Typescript reports that this is not a valid type
  349. if (prop.type === 'RestElement') {
  350. extractors.RestElement(names, prop);
  351. }
  352. else {
  353. extractors[prop.value.type](names, prop.value);
  354. }
  355. }
  356. },
  357. RestElement(names, param) {
  358. extractors[param.argument.type](names, param.argument);
  359. }
  360. };
  361. const extractAssignedNames = function extractAssignedNames(param) {
  362. const names = [];
  363. extractors[param.type](names, param);
  364. return names;
  365. };
  366. const blockDeclarations = {
  367. const: true,
  368. let: true
  369. };
  370. class Scope {
  371. constructor(options = {}) {
  372. this.parent = options.parent;
  373. this.isBlockScope = !!options.block;
  374. this.declarations = Object.create(null);
  375. if (options.params) {
  376. options.params.forEach((param) => {
  377. extractAssignedNames(param).forEach((name) => {
  378. this.declarations[name] = true;
  379. });
  380. });
  381. }
  382. }
  383. addDeclaration(node, isBlockDeclaration, isVar) {
  384. if (!isBlockDeclaration && this.isBlockScope) {
  385. // it's a `var` or function node, and this
  386. // is a block scope, so we need to go up
  387. this.parent.addDeclaration(node, isBlockDeclaration, isVar);
  388. }
  389. else if (node.id) {
  390. extractAssignedNames(node.id).forEach((name) => {
  391. this.declarations[name] = true;
  392. });
  393. }
  394. }
  395. contains(name) {
  396. return this.declarations[name] || (this.parent ? this.parent.contains(name) : false);
  397. }
  398. }
  399. const attachScopes = function attachScopes(ast, propertyName = 'scope') {
  400. let scope = new Scope();
  401. walk$2(ast, {
  402. enter(n, parent) {
  403. const node = n;
  404. // function foo () {...}
  405. // class Foo {...}
  406. if (/(?:Function|Class)Declaration/.test(node.type)) {
  407. scope.addDeclaration(node, false, false);
  408. }
  409. // var foo = 1
  410. if (node.type === 'VariableDeclaration') {
  411. const { kind } = node;
  412. const isBlockDeclaration = blockDeclarations[kind];
  413. node.declarations.forEach((declaration) => {
  414. scope.addDeclaration(declaration, isBlockDeclaration, true);
  415. });
  416. }
  417. let newScope;
  418. // create new function scope
  419. if (node.type.includes('Function')) {
  420. const func = node;
  421. newScope = new Scope({
  422. parent: scope,
  423. block: false,
  424. params: func.params
  425. });
  426. // named function expressions - the name is considered
  427. // part of the function's scope
  428. if (func.type === 'FunctionExpression' && func.id) {
  429. newScope.addDeclaration(func, false, false);
  430. }
  431. }
  432. // create new for scope
  433. if (/For(?:In|Of)?Statement/.test(node.type)) {
  434. newScope = new Scope({
  435. parent: scope,
  436. block: true
  437. });
  438. }
  439. // create new block scope
  440. if (node.type === 'BlockStatement' && !parent.type.includes('Function')) {
  441. newScope = new Scope({
  442. parent: scope,
  443. block: true
  444. });
  445. }
  446. // catch clause has its own block scope
  447. if (node.type === 'CatchClause') {
  448. newScope = new Scope({
  449. parent: scope,
  450. params: node.param ? [node.param] : [],
  451. block: true
  452. });
  453. }
  454. if (newScope) {
  455. Object.defineProperty(node, propertyName, {
  456. value: newScope,
  457. configurable: true
  458. });
  459. scope = newScope;
  460. }
  461. },
  462. leave(n) {
  463. const node = n;
  464. if (node[propertyName])
  465. scope = scope.parent;
  466. }
  467. });
  468. return scope;
  469. };
  470. // Helper since Typescript can't detect readonly arrays with Array.isArray
  471. function isArray(arg) {
  472. return Array.isArray(arg);
  473. }
  474. function ensureArray(thing) {
  475. if (isArray(thing))
  476. return thing;
  477. if (thing == null)
  478. return [];
  479. return [thing];
  480. }
  481. const normalizePathRegExp = new RegExp(`\\${win32.sep}`, 'g');
  482. const normalizePath$5 = function normalizePath(filename) {
  483. return filename.replace(normalizePathRegExp, posix.sep);
  484. };
  485. function getMatcherString$1(id, resolutionBase) {
  486. if (resolutionBase === false || isAbsolute(id) || id.startsWith('**')) {
  487. return normalizePath$5(id);
  488. }
  489. // resolve('') is valid and will default to process.cwd()
  490. const basePath = normalizePath$5(resolve$3(resolutionBase || ''))
  491. // escape all possible (posix + win) path characters that might interfere with regex
  492. .replace(/[-^$*+?.()|[\]{}]/g, '\\$&');
  493. // Note that we use posix.join because:
  494. // 1. the basePath has been normalized to use /
  495. // 2. the incoming glob (id) matcher, also uses /
  496. // otherwise Node will force backslash (\) on windows
  497. return posix.join(basePath, normalizePath$5(id));
  498. }
  499. const createFilter$2 = function createFilter(include, exclude, options) {
  500. const resolutionBase = options && options.resolve;
  501. const getMatcher = (id) => id instanceof RegExp
  502. ? id
  503. : {
  504. test: (what) => {
  505. // this refactor is a tad overly verbose but makes for easy debugging
  506. const pattern = getMatcherString$1(id, resolutionBase);
  507. const fn = picomatch$2(pattern, { dot: true });
  508. const result = fn(what);
  509. return result;
  510. }
  511. };
  512. const includeMatchers = ensureArray(include).map(getMatcher);
  513. const excludeMatchers = ensureArray(exclude).map(getMatcher);
  514. if (!includeMatchers.length && !excludeMatchers.length)
  515. return (id) => typeof id === 'string' && !id.includes('\0');
  516. return function result(id) {
  517. if (typeof id !== 'string')
  518. return false;
  519. if (id.includes('\0'))
  520. return false;
  521. const pathId = normalizePath$5(id);
  522. for (let i = 0; i < excludeMatchers.length; ++i) {
  523. const matcher = excludeMatchers[i];
  524. if (matcher instanceof RegExp) {
  525. matcher.lastIndex = 0;
  526. }
  527. if (matcher.test(pathId))
  528. return false;
  529. }
  530. for (let i = 0; i < includeMatchers.length; ++i) {
  531. const matcher = includeMatchers[i];
  532. if (matcher instanceof RegExp) {
  533. matcher.lastIndex = 0;
  534. }
  535. if (matcher.test(pathId))
  536. return true;
  537. }
  538. return !includeMatchers.length;
  539. };
  540. };
  541. const reservedWords = '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';
  542. const builtins = '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';
  543. const forbiddenIdentifiers = new Set(`${reservedWords} ${builtins}`.split(' '));
  544. forbiddenIdentifiers.add('');
  545. const makeLegalIdentifier = function makeLegalIdentifier(str) {
  546. let identifier = str
  547. .replace(/-(\w)/g, (_, letter) => letter.toUpperCase())
  548. .replace(/[^$_a-zA-Z0-9]/g, '_');
  549. if (/\d/.test(identifier[0]) || forbiddenIdentifiers.has(identifier)) {
  550. identifier = `_${identifier}`;
  551. }
  552. return identifier || '_';
  553. };
  554. function stringify$5(obj) {
  555. return (JSON.stringify(obj) || 'undefined').replace(/[\u2028\u2029]/g, (char) => `\\u${`000${char.charCodeAt(0).toString(16)}`.slice(-4)}`);
  556. }
  557. function serializeArray(arr, indent, baseIndent) {
  558. let output = '[';
  559. const separator = indent ? `\n${baseIndent}${indent}` : '';
  560. for (let i = 0; i < arr.length; i++) {
  561. const key = arr[i];
  562. output += `${i > 0 ? ',' : ''}${separator}${serialize(key, indent, baseIndent + indent)}`;
  563. }
  564. return `${output}${indent ? `\n${baseIndent}` : ''}]`;
  565. }
  566. function serializeObject(obj, indent, baseIndent) {
  567. let output = '{';
  568. const separator = indent ? `\n${baseIndent}${indent}` : '';
  569. const entries = Object.entries(obj);
  570. for (let i = 0; i < entries.length; i++) {
  571. const [key, value] = entries[i];
  572. const stringKey = makeLegalIdentifier(key) === key ? key : stringify$5(key);
  573. output += `${i > 0 ? ',' : ''}${separator}${stringKey}:${indent ? ' ' : ''}${serialize(value, indent, baseIndent + indent)}`;
  574. }
  575. return `${output}${indent ? `\n${baseIndent}` : ''}}`;
  576. }
  577. function serialize(obj, indent, baseIndent) {
  578. if (typeof obj === 'object' && obj !== null) {
  579. if (Array.isArray(obj))
  580. return serializeArray(obj, indent, baseIndent);
  581. if (obj instanceof Date)
  582. return `new Date(${obj.getTime()})`;
  583. if (obj instanceof RegExp)
  584. return obj.toString();
  585. return serializeObject(obj, indent, baseIndent);
  586. }
  587. if (typeof obj === 'number') {
  588. if (obj === Infinity)
  589. return 'Infinity';
  590. if (obj === -Infinity)
  591. return '-Infinity';
  592. if (obj === 0)
  593. return 1 / obj === Infinity ? '0' : '-0';
  594. if (obj !== obj)
  595. return 'NaN'; // eslint-disable-line no-self-compare
  596. }
  597. if (typeof obj === 'symbol') {
  598. const key = Symbol.keyFor(obj);
  599. // eslint-disable-next-line no-undefined
  600. if (key !== undefined)
  601. return `Symbol.for(${stringify$5(key)})`;
  602. }
  603. if (typeof obj === 'bigint')
  604. return `${obj}n`;
  605. return stringify$5(obj);
  606. }
  607. // isWellFormed exists from Node.js 20
  608. const hasStringIsWellFormed = 'isWellFormed' in String.prototype;
  609. function isWellFormedString(input) {
  610. // @ts-expect-error String::isWellFormed exists from ES2024. tsconfig lib is set to ES6
  611. if (hasStringIsWellFormed)
  612. return input.isWellFormed();
  613. // https://github.com/tc39/proposal-is-usv-string/blob/main/README.md#algorithm
  614. return !/\p{Surrogate}/u.test(input);
  615. }
  616. const dataToEsm = function dataToEsm(data, options = {}) {
  617. var _a, _b;
  618. const t = options.compact ? '' : 'indent' in options ? options.indent : '\t';
  619. const _ = options.compact ? '' : ' ';
  620. const n = options.compact ? '' : '\n';
  621. const declarationType = options.preferConst ? 'const' : 'var';
  622. if (options.namedExports === false ||
  623. typeof data !== 'object' ||
  624. Array.isArray(data) ||
  625. data instanceof Date ||
  626. data instanceof RegExp ||
  627. data === null) {
  628. const code = serialize(data, options.compact ? null : t, '');
  629. const magic = _ || (/^[{[\-\/]/.test(code) ? '' : ' '); // eslint-disable-line no-useless-escape
  630. return `export default${magic}${code};`;
  631. }
  632. let maxUnderbarPrefixLength = 0;
  633. for (const key of Object.keys(data)) {
  634. const underbarPrefixLength = (_b = (_a = /^(_+)/.exec(key)) === null || _a === void 0 ? void 0 : _a[0].length) !== null && _b !== void 0 ? _b : 0;
  635. if (underbarPrefixLength > maxUnderbarPrefixLength) {
  636. maxUnderbarPrefixLength = underbarPrefixLength;
  637. }
  638. }
  639. const arbitraryNamePrefix = `${'_'.repeat(maxUnderbarPrefixLength + 1)}arbitrary`;
  640. let namedExportCode = '';
  641. const defaultExportRows = [];
  642. const arbitraryNameExportRows = [];
  643. for (const [key, value] of Object.entries(data)) {
  644. if (key === makeLegalIdentifier(key)) {
  645. if (options.objectShorthand)
  646. defaultExportRows.push(key);
  647. else
  648. defaultExportRows.push(`${key}:${_}${key}`);
  649. namedExportCode += `export ${declarationType} ${key}${_}=${_}${serialize(value, options.compact ? null : t, '')};${n}`;
  650. }
  651. else {
  652. defaultExportRows.push(`${stringify$5(key)}:${_}${serialize(value, options.compact ? null : t, '')}`);
  653. if (options.includeArbitraryNames && isWellFormedString(key)) {
  654. const variableName = `${arbitraryNamePrefix}${arbitraryNameExportRows.length}`;
  655. namedExportCode += `${declarationType} ${variableName}${_}=${_}${serialize(value, options.compact ? null : t, '')};${n}`;
  656. arbitraryNameExportRows.push(`${variableName} as ${JSON.stringify(key)}`);
  657. }
  658. }
  659. }
  660. const arbitraryExportCode = arbitraryNameExportRows.length > 0
  661. ? `export${_}{${n}${t}${arbitraryNameExportRows.join(`,${n}${t}`)}${n}};${n}`
  662. : '';
  663. const defaultExportCode = `export default${_}{${n}${t}${defaultExportRows.join(`,${n}${t}`)}${n}};${n}`;
  664. return `${namedExportCode}${arbitraryExportCode}${defaultExportCode}`;
  665. };
  666. var path$a = require$$0$2;
  667. var commondir = function (basedir, relfiles) {
  668. if (relfiles) {
  669. var files = relfiles.map(function (r) {
  670. return path$a.resolve(basedir, r);
  671. });
  672. }
  673. else {
  674. var files = basedir;
  675. }
  676. var res = files.slice(1).reduce(function (ps, file) {
  677. if (!file.match(/^([A-Za-z]:)?\/|\\/)) {
  678. throw new Error('relative path without a basedir');
  679. }
  680. var xs = file.split(/\/+|\\+/);
  681. for (
  682. var i = 0;
  683. ps[i] === xs[i] && i < Math.min(ps.length, xs.length);
  684. i++
  685. );
  686. return ps.slice(0, i);
  687. }, files[0].split(/\/+|\\+/));
  688. // Windows correctly handles paths with forward-slashes
  689. return res.length > 1 ? res.join('/') : '/'
  690. };
  691. var getCommonDir = /*@__PURE__*/getDefaultExportFromCjs(commondir);
  692. const comma = ','.charCodeAt(0);
  693. const semicolon = ';'.charCodeAt(0);
  694. const chars$1 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
  695. const intToChar = new Uint8Array(64); // 64 possible chars.
  696. const charToInt = new Uint8Array(128); // z is 122 in ASCII
  697. for (let i = 0; i < chars$1.length; i++) {
  698. const c = chars$1.charCodeAt(i);
  699. intToChar[i] = c;
  700. charToInt[c] = i;
  701. }
  702. function decodeInteger(reader, relative) {
  703. let value = 0;
  704. let shift = 0;
  705. let integer = 0;
  706. do {
  707. const c = reader.next();
  708. integer = charToInt[c];
  709. value |= (integer & 31) << shift;
  710. shift += 5;
  711. } while (integer & 32);
  712. const shouldNegate = value & 1;
  713. value >>>= 1;
  714. if (shouldNegate) {
  715. value = -2147483648 | -value;
  716. }
  717. return relative + value;
  718. }
  719. function encodeInteger(builder, num, relative) {
  720. let delta = num - relative;
  721. delta = delta < 0 ? (-delta << 1) | 1 : delta << 1;
  722. do {
  723. let clamped = delta & 0b011111;
  724. delta >>>= 5;
  725. if (delta > 0)
  726. clamped |= 0b100000;
  727. builder.write(intToChar[clamped]);
  728. } while (delta > 0);
  729. return num;
  730. }
  731. function hasMoreVlq(reader, max) {
  732. if (reader.pos >= max)
  733. return false;
  734. return reader.peek() !== comma;
  735. }
  736. const bufLength = 1024 * 16;
  737. // Provide a fallback for older environments.
  738. const td = typeof TextDecoder !== 'undefined'
  739. ? /* #__PURE__ */ new TextDecoder()
  740. : typeof Buffer !== 'undefined'
  741. ? {
  742. decode(buf) {
  743. const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength);
  744. return out.toString();
  745. },
  746. }
  747. : {
  748. decode(buf) {
  749. let out = '';
  750. for (let i = 0; i < buf.length; i++) {
  751. out += String.fromCharCode(buf[i]);
  752. }
  753. return out;
  754. },
  755. };
  756. class StringWriter {
  757. constructor() {
  758. this.pos = 0;
  759. this.out = '';
  760. this.buffer = new Uint8Array(bufLength);
  761. }
  762. write(v) {
  763. const { buffer } = this;
  764. buffer[this.pos++] = v;
  765. if (this.pos === bufLength) {
  766. this.out += td.decode(buffer);
  767. this.pos = 0;
  768. }
  769. }
  770. flush() {
  771. const { buffer, out, pos } = this;
  772. return pos > 0 ? out + td.decode(buffer.subarray(0, pos)) : out;
  773. }
  774. }
  775. class StringReader {
  776. constructor(buffer) {
  777. this.pos = 0;
  778. this.buffer = buffer;
  779. }
  780. next() {
  781. return this.buffer.charCodeAt(this.pos++);
  782. }
  783. peek() {
  784. return this.buffer.charCodeAt(this.pos);
  785. }
  786. indexOf(char) {
  787. const { buffer, pos } = this;
  788. const idx = buffer.indexOf(char, pos);
  789. return idx === -1 ? buffer.length : idx;
  790. }
  791. }
  792. function decode(mappings) {
  793. const { length } = mappings;
  794. const reader = new StringReader(mappings);
  795. const decoded = [];
  796. let genColumn = 0;
  797. let sourcesIndex = 0;
  798. let sourceLine = 0;
  799. let sourceColumn = 0;
  800. let namesIndex = 0;
  801. do {
  802. const semi = reader.indexOf(';');
  803. const line = [];
  804. let sorted = true;
  805. let lastCol = 0;
  806. genColumn = 0;
  807. while (reader.pos < semi) {
  808. let seg;
  809. genColumn = decodeInteger(reader, genColumn);
  810. if (genColumn < lastCol)
  811. sorted = false;
  812. lastCol = genColumn;
  813. if (hasMoreVlq(reader, semi)) {
  814. sourcesIndex = decodeInteger(reader, sourcesIndex);
  815. sourceLine = decodeInteger(reader, sourceLine);
  816. sourceColumn = decodeInteger(reader, sourceColumn);
  817. if (hasMoreVlq(reader, semi)) {
  818. namesIndex = decodeInteger(reader, namesIndex);
  819. seg = [genColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex];
  820. }
  821. else {
  822. seg = [genColumn, sourcesIndex, sourceLine, sourceColumn];
  823. }
  824. }
  825. else {
  826. seg = [genColumn];
  827. }
  828. line.push(seg);
  829. reader.pos++;
  830. }
  831. if (!sorted)
  832. sort(line);
  833. decoded.push(line);
  834. reader.pos = semi + 1;
  835. } while (reader.pos <= length);
  836. return decoded;
  837. }
  838. function sort(line) {
  839. line.sort(sortComparator$1);
  840. }
  841. function sortComparator$1(a, b) {
  842. return a[0] - b[0];
  843. }
  844. function encode$1(decoded) {
  845. const writer = new StringWriter();
  846. let sourcesIndex = 0;
  847. let sourceLine = 0;
  848. let sourceColumn = 0;
  849. let namesIndex = 0;
  850. for (let i = 0; i < decoded.length; i++) {
  851. const line = decoded[i];
  852. if (i > 0)
  853. writer.write(semicolon);
  854. if (line.length === 0)
  855. continue;
  856. let genColumn = 0;
  857. for (let j = 0; j < line.length; j++) {
  858. const segment = line[j];
  859. if (j > 0)
  860. writer.write(comma);
  861. genColumn = encodeInteger(writer, segment[0], genColumn);
  862. if (segment.length === 1)
  863. continue;
  864. sourcesIndex = encodeInteger(writer, segment[1], sourcesIndex);
  865. sourceLine = encodeInteger(writer, segment[2], sourceLine);
  866. sourceColumn = encodeInteger(writer, segment[3], sourceColumn);
  867. if (segment.length === 4)
  868. continue;
  869. namesIndex = encodeInteger(writer, segment[4], namesIndex);
  870. }
  871. }
  872. return writer.flush();
  873. }
  874. class BitSet {
  875. constructor(arg) {
  876. this.bits = arg instanceof BitSet ? arg.bits.slice() : [];
  877. }
  878. add(n) {
  879. this.bits[n >> 5] |= 1 << (n & 31);
  880. }
  881. has(n) {
  882. return !!(this.bits[n >> 5] & (1 << (n & 31)));
  883. }
  884. }
  885. class Chunk {
  886. constructor(start, end, content) {
  887. this.start = start;
  888. this.end = end;
  889. this.original = content;
  890. this.intro = '';
  891. this.outro = '';
  892. this.content = content;
  893. this.storeName = false;
  894. this.edited = false;
  895. {
  896. this.previous = null;
  897. this.next = null;
  898. }
  899. }
  900. appendLeft(content) {
  901. this.outro += content;
  902. }
  903. appendRight(content) {
  904. this.intro = this.intro + content;
  905. }
  906. clone() {
  907. const chunk = new Chunk(this.start, this.end, this.original);
  908. chunk.intro = this.intro;
  909. chunk.outro = this.outro;
  910. chunk.content = this.content;
  911. chunk.storeName = this.storeName;
  912. chunk.edited = this.edited;
  913. return chunk;
  914. }
  915. contains(index) {
  916. return this.start < index && index < this.end;
  917. }
  918. eachNext(fn) {
  919. let chunk = this;
  920. while (chunk) {
  921. fn(chunk);
  922. chunk = chunk.next;
  923. }
  924. }
  925. eachPrevious(fn) {
  926. let chunk = this;
  927. while (chunk) {
  928. fn(chunk);
  929. chunk = chunk.previous;
  930. }
  931. }
  932. edit(content, storeName, contentOnly) {
  933. this.content = content;
  934. if (!contentOnly) {
  935. this.intro = '';
  936. this.outro = '';
  937. }
  938. this.storeName = storeName;
  939. this.edited = true;
  940. return this;
  941. }
  942. prependLeft(content) {
  943. this.outro = content + this.outro;
  944. }
  945. prependRight(content) {
  946. this.intro = content + this.intro;
  947. }
  948. reset() {
  949. this.intro = '';
  950. this.outro = '';
  951. if (this.edited) {
  952. this.content = this.original;
  953. this.storeName = false;
  954. this.edited = false;
  955. }
  956. }
  957. split(index) {
  958. const sliceIndex = index - this.start;
  959. const originalBefore = this.original.slice(0, sliceIndex);
  960. const originalAfter = this.original.slice(sliceIndex);
  961. this.original = originalBefore;
  962. const newChunk = new Chunk(index, this.end, originalAfter);
  963. newChunk.outro = this.outro;
  964. this.outro = '';
  965. this.end = index;
  966. if (this.edited) {
  967. // after split we should save the edit content record into the correct chunk
  968. // to make sure sourcemap correct
  969. // For example:
  970. // ' test'.trim()
  971. // split -> ' ' + 'test'
  972. // ✔️ edit -> '' + 'test'
  973. // ✖️ edit -> 'test' + ''
  974. // TODO is this block necessary?...
  975. newChunk.edit('', false);
  976. this.content = '';
  977. } else {
  978. this.content = originalBefore;
  979. }
  980. newChunk.next = this.next;
  981. if (newChunk.next) newChunk.next.previous = newChunk;
  982. newChunk.previous = this;
  983. this.next = newChunk;
  984. return newChunk;
  985. }
  986. toString() {
  987. return this.intro + this.content + this.outro;
  988. }
  989. trimEnd(rx) {
  990. this.outro = this.outro.replace(rx, '');
  991. if (this.outro.length) return true;
  992. const trimmed = this.content.replace(rx, '');
  993. if (trimmed.length) {
  994. if (trimmed !== this.content) {
  995. this.split(this.start + trimmed.length).edit('', undefined, true);
  996. if (this.edited) {
  997. // save the change, if it has been edited
  998. this.edit(trimmed, this.storeName, true);
  999. }
  1000. }
  1001. return true;
  1002. } else {
  1003. this.edit('', undefined, true);
  1004. this.intro = this.intro.replace(rx, '');
  1005. if (this.intro.length) return true;
  1006. }
  1007. }
  1008. trimStart(rx) {
  1009. this.intro = this.intro.replace(rx, '');
  1010. if (this.intro.length) return true;
  1011. const trimmed = this.content.replace(rx, '');
  1012. if (trimmed.length) {
  1013. if (trimmed !== this.content) {
  1014. const newChunk = this.split(this.end - trimmed.length);
  1015. if (this.edited) {
  1016. // save the change, if it has been edited
  1017. newChunk.edit(trimmed, this.storeName, true);
  1018. }
  1019. this.edit('', undefined, true);
  1020. }
  1021. return true;
  1022. } else {
  1023. this.edit('', undefined, true);
  1024. this.outro = this.outro.replace(rx, '');
  1025. if (this.outro.length) return true;
  1026. }
  1027. }
  1028. }
  1029. function getBtoa() {
  1030. if (typeof globalThis !== 'undefined' && typeof globalThis.btoa === 'function') {
  1031. return (str) => globalThis.btoa(unescape(encodeURIComponent(str)));
  1032. } else if (typeof Buffer === 'function') {
  1033. return (str) => Buffer.from(str, 'utf-8').toString('base64');
  1034. } else {
  1035. return () => {
  1036. throw new Error('Unsupported environment: `window.btoa` or `Buffer` should be supported.');
  1037. };
  1038. }
  1039. }
  1040. const btoa$1 = /*#__PURE__*/ getBtoa();
  1041. let SourceMap$1 = class SourceMap {
  1042. constructor(properties) {
  1043. this.version = 3;
  1044. this.file = properties.file;
  1045. this.sources = properties.sources;
  1046. this.sourcesContent = properties.sourcesContent;
  1047. this.names = properties.names;
  1048. this.mappings = encode$1(properties.mappings);
  1049. if (typeof properties.x_google_ignoreList !== 'undefined') {
  1050. this.x_google_ignoreList = properties.x_google_ignoreList;
  1051. }
  1052. if (typeof properties.debugId !== 'undefined') {
  1053. this.debugId = properties.debugId;
  1054. }
  1055. }
  1056. toString() {
  1057. return JSON.stringify(this);
  1058. }
  1059. toUrl() {
  1060. return 'data:application/json;charset=utf-8;base64,' + btoa$1(this.toString());
  1061. }
  1062. };
  1063. function guessIndent(code) {
  1064. const lines = code.split('\n');
  1065. const tabbed = lines.filter((line) => /^\t+/.test(line));
  1066. const spaced = lines.filter((line) => /^ {2,}/.test(line));
  1067. if (tabbed.length === 0 && spaced.length === 0) {
  1068. return null;
  1069. }
  1070. // More lines tabbed than spaced? Assume tabs, and
  1071. // default to tabs in the case of a tie (or nothing
  1072. // to go on)
  1073. if (tabbed.length >= spaced.length) {
  1074. return '\t';
  1075. }
  1076. // Otherwise, we need to guess the multiple
  1077. const min = spaced.reduce((previous, current) => {
  1078. const numSpaces = /^ +/.exec(current)[0].length;
  1079. return Math.min(numSpaces, previous);
  1080. }, Infinity);
  1081. return new Array(min + 1).join(' ');
  1082. }
  1083. function getRelativePath(from, to) {
  1084. const fromParts = from.split(/[/\\]/);
  1085. const toParts = to.split(/[/\\]/);
  1086. fromParts.pop(); // get dirname
  1087. while (fromParts[0] === toParts[0]) {
  1088. fromParts.shift();
  1089. toParts.shift();
  1090. }
  1091. if (fromParts.length) {
  1092. let i = fromParts.length;
  1093. while (i--) fromParts[i] = '..';
  1094. }
  1095. return fromParts.concat(toParts).join('/');
  1096. }
  1097. const toString$1 = Object.prototype.toString;
  1098. function isObject$2(thing) {
  1099. return toString$1.call(thing) === '[object Object]';
  1100. }
  1101. function getLocator(source) {
  1102. const originalLines = source.split('\n');
  1103. const lineOffsets = [];
  1104. for (let i = 0, pos = 0; i < originalLines.length; i++) {
  1105. lineOffsets.push(pos);
  1106. pos += originalLines[i].length + 1;
  1107. }
  1108. return function locate(index) {
  1109. let i = 0;
  1110. let j = lineOffsets.length;
  1111. while (i < j) {
  1112. const m = (i + j) >> 1;
  1113. if (index < lineOffsets[m]) {
  1114. j = m;
  1115. } else {
  1116. i = m + 1;
  1117. }
  1118. }
  1119. const line = i - 1;
  1120. const column = index - lineOffsets[line];
  1121. return { line, column };
  1122. };
  1123. }
  1124. const wordRegex = /\w/;
  1125. class Mappings {
  1126. constructor(hires) {
  1127. this.hires = hires;
  1128. this.generatedCodeLine = 0;
  1129. this.generatedCodeColumn = 0;
  1130. this.raw = [];
  1131. this.rawSegments = this.raw[this.generatedCodeLine] = [];
  1132. this.pending = null;
  1133. }
  1134. addEdit(sourceIndex, content, loc, nameIndex) {
  1135. if (content.length) {
  1136. const contentLengthMinusOne = content.length - 1;
  1137. let contentLineEnd = content.indexOf('\n', 0);
  1138. let previousContentLineEnd = -1;
  1139. // Loop through each line in the content and add a segment, but stop if the last line is empty,
  1140. // else code afterwards would fill one line too many
  1141. while (contentLineEnd >= 0 && contentLengthMinusOne > contentLineEnd) {
  1142. const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
  1143. if (nameIndex >= 0) {
  1144. segment.push(nameIndex);
  1145. }
  1146. this.rawSegments.push(segment);
  1147. this.generatedCodeLine += 1;
  1148. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  1149. this.generatedCodeColumn = 0;
  1150. previousContentLineEnd = contentLineEnd;
  1151. contentLineEnd = content.indexOf('\n', contentLineEnd + 1);
  1152. }
  1153. const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
  1154. if (nameIndex >= 0) {
  1155. segment.push(nameIndex);
  1156. }
  1157. this.rawSegments.push(segment);
  1158. this.advance(content.slice(previousContentLineEnd + 1));
  1159. } else if (this.pending) {
  1160. this.rawSegments.push(this.pending);
  1161. this.advance(content);
  1162. }
  1163. this.pending = null;
  1164. }
  1165. addUneditedChunk(sourceIndex, chunk, original, loc, sourcemapLocations) {
  1166. let originalCharIndex = chunk.start;
  1167. let first = true;
  1168. // when iterating each char, check if it's in a word boundary
  1169. let charInHiresBoundary = false;
  1170. while (originalCharIndex < chunk.end) {
  1171. if (original[originalCharIndex] === '\n') {
  1172. loc.line += 1;
  1173. loc.column = 0;
  1174. this.generatedCodeLine += 1;
  1175. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  1176. this.generatedCodeColumn = 0;
  1177. first = true;
  1178. charInHiresBoundary = false;
  1179. } else {
  1180. if (this.hires || first || sourcemapLocations.has(originalCharIndex)) {
  1181. const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
  1182. if (this.hires === 'boundary') {
  1183. // in hires "boundary", group segments per word boundary than per char
  1184. if (wordRegex.test(original[originalCharIndex])) {
  1185. // for first char in the boundary found, start the boundary by pushing a segment
  1186. if (!charInHiresBoundary) {
  1187. this.rawSegments.push(segment);
  1188. charInHiresBoundary = true;
  1189. }
  1190. } else {
  1191. // for non-word char, end the boundary by pushing a segment
  1192. this.rawSegments.push(segment);
  1193. charInHiresBoundary = false;
  1194. }
  1195. } else {
  1196. this.rawSegments.push(segment);
  1197. }
  1198. }
  1199. loc.column += 1;
  1200. this.generatedCodeColumn += 1;
  1201. first = false;
  1202. }
  1203. originalCharIndex += 1;
  1204. }
  1205. this.pending = null;
  1206. }
  1207. advance(str) {
  1208. if (!str) return;
  1209. const lines = str.split('\n');
  1210. if (lines.length > 1) {
  1211. for (let i = 0; i < lines.length - 1; i++) {
  1212. this.generatedCodeLine++;
  1213. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  1214. }
  1215. this.generatedCodeColumn = 0;
  1216. }
  1217. this.generatedCodeColumn += lines[lines.length - 1].length;
  1218. }
  1219. }
  1220. const n$1 = '\n';
  1221. const warned = {
  1222. insertLeft: false,
  1223. insertRight: false,
  1224. storeName: false,
  1225. };
  1226. class MagicString {
  1227. constructor(string, options = {}) {
  1228. const chunk = new Chunk(0, string.length, string);
  1229. Object.defineProperties(this, {
  1230. original: { writable: true, value: string },
  1231. outro: { writable: true, value: '' },
  1232. intro: { writable: true, value: '' },
  1233. firstChunk: { writable: true, value: chunk },
  1234. lastChunk: { writable: true, value: chunk },
  1235. lastSearchedChunk: { writable: true, value: chunk },
  1236. byStart: { writable: true, value: {} },
  1237. byEnd: { writable: true, value: {} },
  1238. filename: { writable: true, value: options.filename },
  1239. indentExclusionRanges: { writable: true, value: options.indentExclusionRanges },
  1240. sourcemapLocations: { writable: true, value: new BitSet() },
  1241. storedNames: { writable: true, value: {} },
  1242. indentStr: { writable: true, value: undefined },
  1243. ignoreList: { writable: true, value: options.ignoreList },
  1244. offset: { writable: true, value: options.offset || 0 },
  1245. });
  1246. this.byStart[0] = chunk;
  1247. this.byEnd[string.length] = chunk;
  1248. }
  1249. addSourcemapLocation(char) {
  1250. this.sourcemapLocations.add(char);
  1251. }
  1252. append(content) {
  1253. if (typeof content !== 'string') throw new TypeError('outro content must be a string');
  1254. this.outro += content;
  1255. return this;
  1256. }
  1257. appendLeft(index, content) {
  1258. index = index + this.offset;
  1259. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  1260. this._split(index);
  1261. const chunk = this.byEnd[index];
  1262. if (chunk) {
  1263. chunk.appendLeft(content);
  1264. } else {
  1265. this.intro += content;
  1266. }
  1267. return this;
  1268. }
  1269. appendRight(index, content) {
  1270. index = index + this.offset;
  1271. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  1272. this._split(index);
  1273. const chunk = this.byStart[index];
  1274. if (chunk) {
  1275. chunk.appendRight(content);
  1276. } else {
  1277. this.outro += content;
  1278. }
  1279. return this;
  1280. }
  1281. clone() {
  1282. const cloned = new MagicString(this.original, { filename: this.filename, offset: this.offset });
  1283. let originalChunk = this.firstChunk;
  1284. let clonedChunk = (cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone());
  1285. while (originalChunk) {
  1286. cloned.byStart[clonedChunk.start] = clonedChunk;
  1287. cloned.byEnd[clonedChunk.end] = clonedChunk;
  1288. const nextOriginalChunk = originalChunk.next;
  1289. const nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone();
  1290. if (nextClonedChunk) {
  1291. clonedChunk.next = nextClonedChunk;
  1292. nextClonedChunk.previous = clonedChunk;
  1293. clonedChunk = nextClonedChunk;
  1294. }
  1295. originalChunk = nextOriginalChunk;
  1296. }
  1297. cloned.lastChunk = clonedChunk;
  1298. if (this.indentExclusionRanges) {
  1299. cloned.indentExclusionRanges = this.indentExclusionRanges.slice();
  1300. }
  1301. cloned.sourcemapLocations = new BitSet(this.sourcemapLocations);
  1302. cloned.intro = this.intro;
  1303. cloned.outro = this.outro;
  1304. return cloned;
  1305. }
  1306. generateDecodedMap(options) {
  1307. options = options || {};
  1308. const sourceIndex = 0;
  1309. const names = Object.keys(this.storedNames);
  1310. const mappings = new Mappings(options.hires);
  1311. const locate = getLocator(this.original);
  1312. if (this.intro) {
  1313. mappings.advance(this.intro);
  1314. }
  1315. this.firstChunk.eachNext((chunk) => {
  1316. const loc = locate(chunk.start);
  1317. if (chunk.intro.length) mappings.advance(chunk.intro);
  1318. if (chunk.edited) {
  1319. mappings.addEdit(
  1320. sourceIndex,
  1321. chunk.content,
  1322. loc,
  1323. chunk.storeName ? names.indexOf(chunk.original) : -1,
  1324. );
  1325. } else {
  1326. mappings.addUneditedChunk(sourceIndex, chunk, this.original, loc, this.sourcemapLocations);
  1327. }
  1328. if (chunk.outro.length) mappings.advance(chunk.outro);
  1329. });
  1330. return {
  1331. file: options.file ? options.file.split(/[/\\]/).pop() : undefined,
  1332. sources: [
  1333. options.source ? getRelativePath(options.file || '', options.source) : options.file || '',
  1334. ],
  1335. sourcesContent: options.includeContent ? [this.original] : undefined,
  1336. names,
  1337. mappings: mappings.raw,
  1338. x_google_ignoreList: this.ignoreList ? [sourceIndex] : undefined,
  1339. };
  1340. }
  1341. generateMap(options) {
  1342. return new SourceMap$1(this.generateDecodedMap(options));
  1343. }
  1344. _ensureindentStr() {
  1345. if (this.indentStr === undefined) {
  1346. this.indentStr = guessIndent(this.original);
  1347. }
  1348. }
  1349. _getRawIndentString() {
  1350. this._ensureindentStr();
  1351. return this.indentStr;
  1352. }
  1353. getIndentString() {
  1354. this._ensureindentStr();
  1355. return this.indentStr === null ? '\t' : this.indentStr;
  1356. }
  1357. indent(indentStr, options) {
  1358. const pattern = /^[^\r\n]/gm;
  1359. if (isObject$2(indentStr)) {
  1360. options = indentStr;
  1361. indentStr = undefined;
  1362. }
  1363. if (indentStr === undefined) {
  1364. this._ensureindentStr();
  1365. indentStr = this.indentStr || '\t';
  1366. }
  1367. if (indentStr === '') return this; // noop
  1368. options = options || {};
  1369. // Process exclusion ranges
  1370. const isExcluded = {};
  1371. if (options.exclude) {
  1372. const exclusions =
  1373. typeof options.exclude[0] === 'number' ? [options.exclude] : options.exclude;
  1374. exclusions.forEach((exclusion) => {
  1375. for (let i = exclusion[0]; i < exclusion[1]; i += 1) {
  1376. isExcluded[i] = true;
  1377. }
  1378. });
  1379. }
  1380. let shouldIndentNextCharacter = options.indentStart !== false;
  1381. const replacer = (match) => {
  1382. if (shouldIndentNextCharacter) return `${indentStr}${match}`;
  1383. shouldIndentNextCharacter = true;
  1384. return match;
  1385. };
  1386. this.intro = this.intro.replace(pattern, replacer);
  1387. let charIndex = 0;
  1388. let chunk = this.firstChunk;
  1389. while (chunk) {
  1390. const end = chunk.end;
  1391. if (chunk.edited) {
  1392. if (!isExcluded[charIndex]) {
  1393. chunk.content = chunk.content.replace(pattern, replacer);
  1394. if (chunk.content.length) {
  1395. shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === '\n';
  1396. }
  1397. }
  1398. } else {
  1399. charIndex = chunk.start;
  1400. while (charIndex < end) {
  1401. if (!isExcluded[charIndex]) {
  1402. const char = this.original[charIndex];
  1403. if (char === '\n') {
  1404. shouldIndentNextCharacter = true;
  1405. } else if (char !== '\r' && shouldIndentNextCharacter) {
  1406. shouldIndentNextCharacter = false;
  1407. if (charIndex === chunk.start) {
  1408. chunk.prependRight(indentStr);
  1409. } else {
  1410. this._splitChunk(chunk, charIndex);
  1411. chunk = chunk.next;
  1412. chunk.prependRight(indentStr);
  1413. }
  1414. }
  1415. }
  1416. charIndex += 1;
  1417. }
  1418. }
  1419. charIndex = chunk.end;
  1420. chunk = chunk.next;
  1421. }
  1422. this.outro = this.outro.replace(pattern, replacer);
  1423. return this;
  1424. }
  1425. insert() {
  1426. throw new Error(
  1427. 'magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)',
  1428. );
  1429. }
  1430. insertLeft(index, content) {
  1431. if (!warned.insertLeft) {
  1432. console.warn(
  1433. 'magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead',
  1434. );
  1435. warned.insertLeft = true;
  1436. }
  1437. return this.appendLeft(index, content);
  1438. }
  1439. insertRight(index, content) {
  1440. if (!warned.insertRight) {
  1441. console.warn(
  1442. 'magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead',
  1443. );
  1444. warned.insertRight = true;
  1445. }
  1446. return this.prependRight(index, content);
  1447. }
  1448. move(start, end, index) {
  1449. start = start + this.offset;
  1450. end = end + this.offset;
  1451. index = index + this.offset;
  1452. if (index >= start && index <= end) throw new Error('Cannot move a selection inside itself');
  1453. this._split(start);
  1454. this._split(end);
  1455. this._split(index);
  1456. const first = this.byStart[start];
  1457. const last = this.byEnd[end];
  1458. const oldLeft = first.previous;
  1459. const oldRight = last.next;
  1460. const newRight = this.byStart[index];
  1461. if (!newRight && last === this.lastChunk) return this;
  1462. const newLeft = newRight ? newRight.previous : this.lastChunk;
  1463. if (oldLeft) oldLeft.next = oldRight;
  1464. if (oldRight) oldRight.previous = oldLeft;
  1465. if (newLeft) newLeft.next = first;
  1466. if (newRight) newRight.previous = last;
  1467. if (!first.previous) this.firstChunk = last.next;
  1468. if (!last.next) {
  1469. this.lastChunk = first.previous;
  1470. this.lastChunk.next = null;
  1471. }
  1472. first.previous = newLeft;
  1473. last.next = newRight || null;
  1474. if (!newLeft) this.firstChunk = first;
  1475. if (!newRight) this.lastChunk = last;
  1476. return this;
  1477. }
  1478. overwrite(start, end, content, options) {
  1479. options = options || {};
  1480. return this.update(start, end, content, { ...options, overwrite: !options.contentOnly });
  1481. }
  1482. update(start, end, content, options) {
  1483. start = start + this.offset;
  1484. end = end + this.offset;
  1485. if (typeof content !== 'string') throw new TypeError('replacement content must be a string');
  1486. if (this.original.length !== 0) {
  1487. while (start < 0) start += this.original.length;
  1488. while (end < 0) end += this.original.length;
  1489. }
  1490. if (end > this.original.length) throw new Error('end is out of bounds');
  1491. if (start === end)
  1492. throw new Error(
  1493. 'Cannot overwrite a zero-length range – use appendLeft or prependRight instead',
  1494. );
  1495. this._split(start);
  1496. this._split(end);
  1497. if (options === true) {
  1498. if (!warned.storeName) {
  1499. console.warn(
  1500. 'The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string',
  1501. );
  1502. warned.storeName = true;
  1503. }
  1504. options = { storeName: true };
  1505. }
  1506. const storeName = options !== undefined ? options.storeName : false;
  1507. const overwrite = options !== undefined ? options.overwrite : false;
  1508. if (storeName) {
  1509. const original = this.original.slice(start, end);
  1510. Object.defineProperty(this.storedNames, original, {
  1511. writable: true,
  1512. value: true,
  1513. enumerable: true,
  1514. });
  1515. }
  1516. const first = this.byStart[start];
  1517. const last = this.byEnd[end];
  1518. if (first) {
  1519. let chunk = first;
  1520. while (chunk !== last) {
  1521. if (chunk.next !== this.byStart[chunk.end]) {
  1522. throw new Error('Cannot overwrite across a split point');
  1523. }
  1524. chunk = chunk.next;
  1525. chunk.edit('', false);
  1526. }
  1527. first.edit(content, storeName, !overwrite);
  1528. } else {
  1529. // must be inserting at the end
  1530. const newChunk = new Chunk(start, end, '').edit(content, storeName);
  1531. // TODO last chunk in the array may not be the last chunk, if it's moved...
  1532. last.next = newChunk;
  1533. newChunk.previous = last;
  1534. }
  1535. return this;
  1536. }
  1537. prepend(content) {
  1538. if (typeof content !== 'string') throw new TypeError('outro content must be a string');
  1539. this.intro = content + this.intro;
  1540. return this;
  1541. }
  1542. prependLeft(index, content) {
  1543. index = index + this.offset;
  1544. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  1545. this._split(index);
  1546. const chunk = this.byEnd[index];
  1547. if (chunk) {
  1548. chunk.prependLeft(content);
  1549. } else {
  1550. this.intro = content + this.intro;
  1551. }
  1552. return this;
  1553. }
  1554. prependRight(index, content) {
  1555. index = index + this.offset;
  1556. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  1557. this._split(index);
  1558. const chunk = this.byStart[index];
  1559. if (chunk) {
  1560. chunk.prependRight(content);
  1561. } else {
  1562. this.outro = content + this.outro;
  1563. }
  1564. return this;
  1565. }
  1566. remove(start, end) {
  1567. start = start + this.offset;
  1568. end = end + this.offset;
  1569. if (this.original.length !== 0) {
  1570. while (start < 0) start += this.original.length;
  1571. while (end < 0) end += this.original.length;
  1572. }
  1573. if (start === end) return this;
  1574. if (start < 0 || end > this.original.length) throw new Error('Character is out of bounds');
  1575. if (start > end) throw new Error('end must be greater than start');
  1576. this._split(start);
  1577. this._split(end);
  1578. let chunk = this.byStart[start];
  1579. while (chunk) {
  1580. chunk.intro = '';
  1581. chunk.outro = '';
  1582. chunk.edit('');
  1583. chunk = end > chunk.end ? this.byStart[chunk.end] : null;
  1584. }
  1585. return this;
  1586. }
  1587. reset(start, end) {
  1588. start = start + this.offset;
  1589. end = end + this.offset;
  1590. if (this.original.length !== 0) {
  1591. while (start < 0) start += this.original.length;
  1592. while (end < 0) end += this.original.length;
  1593. }
  1594. if (start === end) return this;
  1595. if (start < 0 || end > this.original.length) throw new Error('Character is out of bounds');
  1596. if (start > end) throw new Error('end must be greater than start');
  1597. this._split(start);
  1598. this._split(end);
  1599. let chunk = this.byStart[start];
  1600. while (chunk) {
  1601. chunk.reset();
  1602. chunk = end > chunk.end ? this.byStart[chunk.end] : null;
  1603. }
  1604. return this;
  1605. }
  1606. lastChar() {
  1607. if (this.outro.length) return this.outro[this.outro.length - 1];
  1608. let chunk = this.lastChunk;
  1609. do {
  1610. if (chunk.outro.length) return chunk.outro[chunk.outro.length - 1];
  1611. if (chunk.content.length) return chunk.content[chunk.content.length - 1];
  1612. if (chunk.intro.length) return chunk.intro[chunk.intro.length - 1];
  1613. } while ((chunk = chunk.previous));
  1614. if (this.intro.length) return this.intro[this.intro.length - 1];
  1615. return '';
  1616. }
  1617. lastLine() {
  1618. let lineIndex = this.outro.lastIndexOf(n$1);
  1619. if (lineIndex !== -1) return this.outro.substr(lineIndex + 1);
  1620. let lineStr = this.outro;
  1621. let chunk = this.lastChunk;
  1622. do {
  1623. if (chunk.outro.length > 0) {
  1624. lineIndex = chunk.outro.lastIndexOf(n$1);
  1625. if (lineIndex !== -1) return chunk.outro.substr(lineIndex + 1) + lineStr;
  1626. lineStr = chunk.outro + lineStr;
  1627. }
  1628. if (chunk.content.length > 0) {
  1629. lineIndex = chunk.content.lastIndexOf(n$1);
  1630. if (lineIndex !== -1) return chunk.content.substr(lineIndex + 1) + lineStr;
  1631. lineStr = chunk.content + lineStr;
  1632. }
  1633. if (chunk.intro.length > 0) {
  1634. lineIndex = chunk.intro.lastIndexOf(n$1);
  1635. if (lineIndex !== -1) return chunk.intro.substr(lineIndex + 1) + lineStr;
  1636. lineStr = chunk.intro + lineStr;
  1637. }
  1638. } while ((chunk = chunk.previous));
  1639. lineIndex = this.intro.lastIndexOf(n$1);
  1640. if (lineIndex !== -1) return this.intro.substr(lineIndex + 1) + lineStr;
  1641. return this.intro + lineStr;
  1642. }
  1643. slice(start = 0, end = this.original.length - this.offset) {
  1644. start = start + this.offset;
  1645. end = end + this.offset;
  1646. if (this.original.length !== 0) {
  1647. while (start < 0) start += this.original.length;
  1648. while (end < 0) end += this.original.length;
  1649. }
  1650. let result = '';
  1651. // find start chunk
  1652. let chunk = this.firstChunk;
  1653. while (chunk && (chunk.start > start || chunk.end <= start)) {
  1654. // found end chunk before start
  1655. if (chunk.start < end && chunk.end >= end) {
  1656. return result;
  1657. }
  1658. chunk = chunk.next;
  1659. }
  1660. if (chunk && chunk.edited && chunk.start !== start)
  1661. throw new Error(`Cannot use replaced character ${start} as slice start anchor.`);
  1662. const startChunk = chunk;
  1663. while (chunk) {
  1664. if (chunk.intro && (startChunk !== chunk || chunk.start === start)) {
  1665. result += chunk.intro;
  1666. }
  1667. const containsEnd = chunk.start < end && chunk.end >= end;
  1668. if (containsEnd && chunk.edited && chunk.end !== end)
  1669. throw new Error(`Cannot use replaced character ${end} as slice end anchor.`);
  1670. const sliceStart = startChunk === chunk ? start - chunk.start : 0;
  1671. const sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length;
  1672. result += chunk.content.slice(sliceStart, sliceEnd);
  1673. if (chunk.outro && (!containsEnd || chunk.end === end)) {
  1674. result += chunk.outro;
  1675. }
  1676. if (containsEnd) {
  1677. break;
  1678. }
  1679. chunk = chunk.next;
  1680. }
  1681. return result;
  1682. }
  1683. // TODO deprecate this? not really very useful
  1684. snip(start, end) {
  1685. const clone = this.clone();
  1686. clone.remove(0, start);
  1687. clone.remove(end, clone.original.length);
  1688. return clone;
  1689. }
  1690. _split(index) {
  1691. if (this.byStart[index] || this.byEnd[index]) return;
  1692. let chunk = this.lastSearchedChunk;
  1693. const searchForward = index > chunk.end;
  1694. while (chunk) {
  1695. if (chunk.contains(index)) return this._splitChunk(chunk, index);
  1696. chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start];
  1697. }
  1698. }
  1699. _splitChunk(chunk, index) {
  1700. if (chunk.edited && chunk.content.length) {
  1701. // zero-length edited chunks are a special case (overlapping replacements)
  1702. const loc = getLocator(this.original)(index);
  1703. throw new Error(
  1704. `Cannot split a chunk that has already been edited (${loc.line}:${loc.column} – "${chunk.original}")`,
  1705. );
  1706. }
  1707. const newChunk = chunk.split(index);
  1708. this.byEnd[index] = chunk;
  1709. this.byStart[index] = newChunk;
  1710. this.byEnd[newChunk.end] = newChunk;
  1711. if (chunk === this.lastChunk) this.lastChunk = newChunk;
  1712. this.lastSearchedChunk = chunk;
  1713. return true;
  1714. }
  1715. toString() {
  1716. let str = this.intro;
  1717. let chunk = this.firstChunk;
  1718. while (chunk) {
  1719. str += chunk.toString();
  1720. chunk = chunk.next;
  1721. }
  1722. return str + this.outro;
  1723. }
  1724. isEmpty() {
  1725. let chunk = this.firstChunk;
  1726. do {
  1727. if (
  1728. (chunk.intro.length && chunk.intro.trim()) ||
  1729. (chunk.content.length && chunk.content.trim()) ||
  1730. (chunk.outro.length && chunk.outro.trim())
  1731. )
  1732. return false;
  1733. } while ((chunk = chunk.next));
  1734. return true;
  1735. }
  1736. length() {
  1737. let chunk = this.firstChunk;
  1738. let length = 0;
  1739. do {
  1740. length += chunk.intro.length + chunk.content.length + chunk.outro.length;
  1741. } while ((chunk = chunk.next));
  1742. return length;
  1743. }
  1744. trimLines() {
  1745. return this.trim('[\\r\\n]');
  1746. }
  1747. trim(charType) {
  1748. return this.trimStart(charType).trimEnd(charType);
  1749. }
  1750. trimEndAborted(charType) {
  1751. const rx = new RegExp((charType || '\\s') + '+$');
  1752. this.outro = this.outro.replace(rx, '');
  1753. if (this.outro.length) return true;
  1754. let chunk = this.lastChunk;
  1755. do {
  1756. const end = chunk.end;
  1757. const aborted = chunk.trimEnd(rx);
  1758. // if chunk was trimmed, we have a new lastChunk
  1759. if (chunk.end !== end) {
  1760. if (this.lastChunk === chunk) {
  1761. this.lastChunk = chunk.next;
  1762. }
  1763. this.byEnd[chunk.end] = chunk;
  1764. this.byStart[chunk.next.start] = chunk.next;
  1765. this.byEnd[chunk.next.end] = chunk.next;
  1766. }
  1767. if (aborted) return true;
  1768. chunk = chunk.previous;
  1769. } while (chunk);
  1770. return false;
  1771. }
  1772. trimEnd(charType) {
  1773. this.trimEndAborted(charType);
  1774. return this;
  1775. }
  1776. trimStartAborted(charType) {
  1777. const rx = new RegExp('^' + (charType || '\\s') + '+');
  1778. this.intro = this.intro.replace(rx, '');
  1779. if (this.intro.length) return true;
  1780. let chunk = this.firstChunk;
  1781. do {
  1782. const end = chunk.end;
  1783. const aborted = chunk.trimStart(rx);
  1784. if (chunk.end !== end) {
  1785. // special case...
  1786. if (chunk === this.lastChunk) this.lastChunk = chunk.next;
  1787. this.byEnd[chunk.end] = chunk;
  1788. this.byStart[chunk.next.start] = chunk.next;
  1789. this.byEnd[chunk.next.end] = chunk.next;
  1790. }
  1791. if (aborted) return true;
  1792. chunk = chunk.next;
  1793. } while (chunk);
  1794. return false;
  1795. }
  1796. trimStart(charType) {
  1797. this.trimStartAborted(charType);
  1798. return this;
  1799. }
  1800. hasChanged() {
  1801. return this.original !== this.toString();
  1802. }
  1803. _replaceRegexp(searchValue, replacement) {
  1804. function getReplacement(match, str) {
  1805. if (typeof replacement === 'string') {
  1806. return replacement.replace(/\$(\$|&|\d+)/g, (_, i) => {
  1807. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#specifying_a_string_as_a_parameter
  1808. if (i === '$') return '$';
  1809. if (i === '&') return match[0];
  1810. const num = +i;
  1811. if (num < match.length) return match[+i];
  1812. return `$${i}`;
  1813. });
  1814. } else {
  1815. return replacement(...match, match.index, str, match.groups);
  1816. }
  1817. }
  1818. function matchAll(re, str) {
  1819. let match;
  1820. const matches = [];
  1821. while ((match = re.exec(str))) {
  1822. matches.push(match);
  1823. }
  1824. return matches;
  1825. }
  1826. if (searchValue.global) {
  1827. const matches = matchAll(searchValue, this.original);
  1828. matches.forEach((match) => {
  1829. if (match.index != null) {
  1830. const replacement = getReplacement(match, this.original);
  1831. if (replacement !== match[0]) {
  1832. this.overwrite(match.index, match.index + match[0].length, replacement);
  1833. }
  1834. }
  1835. });
  1836. } else {
  1837. const match = this.original.match(searchValue);
  1838. if (match && match.index != null) {
  1839. const replacement = getReplacement(match, this.original);
  1840. if (replacement !== match[0]) {
  1841. this.overwrite(match.index, match.index + match[0].length, replacement);
  1842. }
  1843. }
  1844. }
  1845. return this;
  1846. }
  1847. _replaceString(string, replacement) {
  1848. const { original } = this;
  1849. const index = original.indexOf(string);
  1850. if (index !== -1) {
  1851. this.overwrite(index, index + string.length, replacement);
  1852. }
  1853. return this;
  1854. }
  1855. replace(searchValue, replacement) {
  1856. if (typeof searchValue === 'string') {
  1857. return this._replaceString(searchValue, replacement);
  1858. }
  1859. return this._replaceRegexp(searchValue, replacement);
  1860. }
  1861. _replaceAllString(string, replacement) {
  1862. const { original } = this;
  1863. const stringLength = string.length;
  1864. for (
  1865. let index = original.indexOf(string);
  1866. index !== -1;
  1867. index = original.indexOf(string, index + stringLength)
  1868. ) {
  1869. const previous = original.slice(index, index + stringLength);
  1870. if (previous !== replacement) this.overwrite(index, index + stringLength, replacement);
  1871. }
  1872. return this;
  1873. }
  1874. replaceAll(searchValue, replacement) {
  1875. if (typeof searchValue === 'string') {
  1876. return this._replaceAllString(searchValue, replacement);
  1877. }
  1878. if (!searchValue.global) {
  1879. throw new TypeError(
  1880. 'MagicString.prototype.replaceAll called with a non-global RegExp argument',
  1881. );
  1882. }
  1883. return this._replaceRegexp(searchValue, replacement);
  1884. }
  1885. }
  1886. function isReference(node, parent) {
  1887. if (node.type === 'MemberExpression') {
  1888. return !node.computed && isReference(node.object, node);
  1889. }
  1890. if (node.type === 'Identifier') {
  1891. if (!parent)
  1892. return true;
  1893. switch (parent.type) {
  1894. // disregard `bar` in `foo.bar`
  1895. case 'MemberExpression': return parent.computed || node === parent.object;
  1896. // disregard the `foo` in `class {foo(){}}` but keep it in `class {[foo](){}}`
  1897. case 'MethodDefinition': return parent.computed;
  1898. // disregard the `foo` in `class {foo=bar}` but keep it in `class {[foo]=bar}` and `class {bar=foo}`
  1899. case 'FieldDefinition': return parent.computed || node === parent.value;
  1900. // disregard the `bar` in `{ bar: foo }`, but keep it in `{ [bar]: foo }`
  1901. case 'Property': return parent.computed || node === parent.value;
  1902. // disregard the `bar` in `export { foo as bar }` or
  1903. // the foo in `import { foo as bar }`
  1904. case 'ExportSpecifier':
  1905. case 'ImportSpecifier': return node === parent.local;
  1906. // disregard the `foo` in `foo: while (...) { ... break foo; ... continue foo;}`
  1907. case 'LabeledStatement':
  1908. case 'BreakStatement':
  1909. case 'ContinueStatement': return false;
  1910. default: return true;
  1911. }
  1912. }
  1913. return false;
  1914. }
  1915. var version$2 = "28.0.3";
  1916. var peerDependencies = {
  1917. rollup: "^2.68.0||^3.0.0||^4.0.0"
  1918. };
  1919. function tryParse(parse, code, id) {
  1920. try {
  1921. return parse(code, { allowReturnOutsideFunction: true });
  1922. } catch (err) {
  1923. err.message += ` in ${id}`;
  1924. throw err;
  1925. }
  1926. }
  1927. const firstpassGlobal = /\b(?:require|module|exports|global)\b/;
  1928. const firstpassNoGlobal = /\b(?:require|module|exports)\b/;
  1929. function hasCjsKeywords(code, ignoreGlobal) {
  1930. const firstpass = ignoreGlobal ? firstpassNoGlobal : firstpassGlobal;
  1931. return firstpass.test(code);
  1932. }
  1933. /* eslint-disable no-underscore-dangle */
  1934. function analyzeTopLevelStatements(parse, code, id) {
  1935. const ast = tryParse(parse, code, id);
  1936. let isEsModule = false;
  1937. let hasDefaultExport = false;
  1938. let hasNamedExports = false;
  1939. for (const node of ast.body) {
  1940. switch (node.type) {
  1941. case 'ExportDefaultDeclaration':
  1942. isEsModule = true;
  1943. hasDefaultExport = true;
  1944. break;
  1945. case 'ExportNamedDeclaration':
  1946. isEsModule = true;
  1947. if (node.declaration) {
  1948. hasNamedExports = true;
  1949. } else {
  1950. for (const specifier of node.specifiers) {
  1951. if (specifier.exported.name === 'default') {
  1952. hasDefaultExport = true;
  1953. } else {
  1954. hasNamedExports = true;
  1955. }
  1956. }
  1957. }
  1958. break;
  1959. case 'ExportAllDeclaration':
  1960. isEsModule = true;
  1961. if (node.exported && node.exported.name === 'default') {
  1962. hasDefaultExport = true;
  1963. } else {
  1964. hasNamedExports = true;
  1965. }
  1966. break;
  1967. case 'ImportDeclaration':
  1968. isEsModule = true;
  1969. break;
  1970. }
  1971. }
  1972. return { isEsModule, hasDefaultExport, hasNamedExports, ast };
  1973. }
  1974. /* eslint-disable import/prefer-default-export */
  1975. function deconflict(scopes, globals, identifier) {
  1976. let i = 1;
  1977. let deconflicted = makeLegalIdentifier(identifier);
  1978. const hasConflicts = () =>
  1979. scopes.some((scope) => scope.contains(deconflicted)) || globals.has(deconflicted);
  1980. while (hasConflicts()) {
  1981. deconflicted = makeLegalIdentifier(`${identifier}_${i}`);
  1982. i += 1;
  1983. }
  1984. for (const scope of scopes) {
  1985. scope.declarations[deconflicted] = true;
  1986. }
  1987. return deconflicted;
  1988. }
  1989. function getName(id) {
  1990. const name = makeLegalIdentifier(basename$1(id, extname(id)));
  1991. if (name !== 'index') {
  1992. return name;
  1993. }
  1994. return makeLegalIdentifier(basename$1(dirname$1(id)));
  1995. }
  1996. function normalizePathSlashes(path) {
  1997. return path.replace(/\\/g, '/');
  1998. }
  1999. const getVirtualPathForDynamicRequirePath = (path, commonDir) =>
  2000. `/${normalizePathSlashes(relative$1(commonDir, path))}`;
  2001. function capitalize(name) {
  2002. return name[0].toUpperCase() + name.slice(1);
  2003. }
  2004. function getStrictRequiresFilter({ strictRequires }) {
  2005. switch (strictRequires) {
  2006. // eslint-disable-next-line no-undefined
  2007. case undefined:
  2008. case true:
  2009. return { strictRequiresFilter: () => true, detectCyclesAndConditional: false };
  2010. case 'auto':
  2011. case 'debug':
  2012. case null:
  2013. return { strictRequiresFilter: () => false, detectCyclesAndConditional: true };
  2014. case false:
  2015. return { strictRequiresFilter: () => false, detectCyclesAndConditional: false };
  2016. default:
  2017. if (typeof strictRequires === 'string' || Array.isArray(strictRequires)) {
  2018. return {
  2019. strictRequiresFilter: createFilter$2(strictRequires),
  2020. detectCyclesAndConditional: false
  2021. };
  2022. }
  2023. throw new Error('Unexpected value for "strictRequires" option.');
  2024. }
  2025. }
  2026. function getPackageEntryPoint(dirPath) {
  2027. let entryPoint = 'index.js';
  2028. try {
  2029. if (existsSync(join(dirPath, 'package.json'))) {
  2030. entryPoint =
  2031. JSON.parse(readFileSync(join(dirPath, 'package.json'), { encoding: 'utf8' })).main ||
  2032. entryPoint;
  2033. }
  2034. } catch (ignored) {
  2035. // ignored
  2036. }
  2037. return entryPoint;
  2038. }
  2039. function isDirectory$1(path) {
  2040. try {
  2041. if (statSync(path).isDirectory()) return true;
  2042. } catch (ignored) {
  2043. // Nothing to do here
  2044. }
  2045. return false;
  2046. }
  2047. function getDynamicRequireModules(patterns, dynamicRequireRoot) {
  2048. const dynamicRequireModules = new Map();
  2049. const dirNames = new Set();
  2050. for (const pattern of !patterns || Array.isArray(patterns) ? patterns || [] : [patterns]) {
  2051. const isNegated = pattern.startsWith('!');
  2052. const modifyMap = (targetPath, resolvedPath) =>
  2053. isNegated
  2054. ? dynamicRequireModules.delete(targetPath)
  2055. : dynamicRequireModules.set(targetPath, resolvedPath);
  2056. // eslint-disable-next-line new-cap
  2057. for (const path of new fdir()
  2058. .withBasePath()
  2059. .withDirs()
  2060. .glob(isNegated ? pattern.substr(1) : pattern)
  2061. .crawl()
  2062. .sync()
  2063. .sort((a, b) => a.localeCompare(b, 'en'))) {
  2064. const resolvedPath = resolve$3(path);
  2065. const requirePath = normalizePathSlashes(resolvedPath);
  2066. if (isDirectory$1(resolvedPath)) {
  2067. dirNames.add(resolvedPath);
  2068. const modulePath = resolve$3(join(resolvedPath, getPackageEntryPoint(path)));
  2069. modifyMap(requirePath, modulePath);
  2070. modifyMap(normalizePathSlashes(modulePath), modulePath);
  2071. } else {
  2072. dirNames.add(dirname$1(resolvedPath));
  2073. modifyMap(requirePath, resolvedPath);
  2074. }
  2075. }
  2076. }
  2077. return {
  2078. commonDir: dirNames.size ? getCommonDir([...dirNames, dynamicRequireRoot]) : null,
  2079. dynamicRequireModules
  2080. };
  2081. }
  2082. const FAILED_REQUIRE_ERROR = `throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.');`;
  2083. const COMMONJS_REQUIRE_EXPORT = 'commonjsRequire';
  2084. const CREATE_COMMONJS_REQUIRE_EXPORT = 'createCommonjsRequire';
  2085. function getDynamicModuleRegistry(
  2086. isDynamicRequireModulesEnabled,
  2087. dynamicRequireModules,
  2088. commonDir,
  2089. ignoreDynamicRequires
  2090. ) {
  2091. if (!isDynamicRequireModulesEnabled) {
  2092. return `export function ${COMMONJS_REQUIRE_EXPORT}(path) {
  2093. ${FAILED_REQUIRE_ERROR}
  2094. }`;
  2095. }
  2096. const dynamicModuleImports = [...dynamicRequireModules.values()]
  2097. .map(
  2098. (id, index) =>
  2099. `import ${
  2100. id.endsWith('.json') ? `json${index}` : `{ __require as require${index} }`
  2101. } from ${JSON.stringify(id)};`
  2102. )
  2103. .join('\n');
  2104. const dynamicModuleProps = [...dynamicRequireModules.keys()]
  2105. .map(
  2106. (id, index) =>
  2107. `\t\t${JSON.stringify(getVirtualPathForDynamicRequirePath(id, commonDir))}: ${
  2108. id.endsWith('.json') ? `function () { return json${index}; }` : `require${index}`
  2109. }`
  2110. )
  2111. .join(',\n');
  2112. return `${dynamicModuleImports}
  2113. var dynamicModules;
  2114. function getDynamicModules() {
  2115. return dynamicModules || (dynamicModules = {
  2116. ${dynamicModuleProps}
  2117. });
  2118. }
  2119. export function ${CREATE_COMMONJS_REQUIRE_EXPORT}(originalModuleDir) {
  2120. function handleRequire(path) {
  2121. var resolvedPath = commonjsResolve(path, originalModuleDir);
  2122. if (resolvedPath !== null) {
  2123. return getDynamicModules()[resolvedPath]();
  2124. }
  2125. ${ignoreDynamicRequires ? 'return require(path);' : FAILED_REQUIRE_ERROR}
  2126. }
  2127. handleRequire.resolve = function (path) {
  2128. var resolvedPath = commonjsResolve(path, originalModuleDir);
  2129. if (resolvedPath !== null) {
  2130. return resolvedPath;
  2131. }
  2132. return require.resolve(path);
  2133. }
  2134. return handleRequire;
  2135. }
  2136. function commonjsResolve (path, originalModuleDir) {
  2137. var shouldTryNodeModules = isPossibleNodeModulesPath(path);
  2138. path = normalize(path);
  2139. var relPath;
  2140. if (path[0] === '/') {
  2141. originalModuleDir = '';
  2142. }
  2143. var modules = getDynamicModules();
  2144. var checkedExtensions = ['', '.js', '.json'];
  2145. while (true) {
  2146. if (!shouldTryNodeModules) {
  2147. relPath = normalize(originalModuleDir + '/' + path);
  2148. } else {
  2149. relPath = normalize(originalModuleDir + '/node_modules/' + path);
  2150. }
  2151. if (relPath.endsWith('/..')) {
  2152. break; // Travelled too far up, avoid infinite loop
  2153. }
  2154. for (var extensionIndex = 0; extensionIndex < checkedExtensions.length; extensionIndex++) {
  2155. var resolvedPath = relPath + checkedExtensions[extensionIndex];
  2156. if (modules[resolvedPath]) {
  2157. return resolvedPath;
  2158. }
  2159. }
  2160. if (!shouldTryNodeModules) break;
  2161. var nextDir = normalize(originalModuleDir + '/..');
  2162. if (nextDir === originalModuleDir) break;
  2163. originalModuleDir = nextDir;
  2164. }
  2165. return null;
  2166. }
  2167. function isPossibleNodeModulesPath (modulePath) {
  2168. var c0 = modulePath[0];
  2169. if (c0 === '/' || c0 === '\\\\') return false;
  2170. var c1 = modulePath[1], c2 = modulePath[2];
  2171. if ((c0 === '.' && (!c1 || c1 === '/' || c1 === '\\\\')) ||
  2172. (c0 === '.' && c1 === '.' && (!c2 || c2 === '/' || c2 === '\\\\'))) return false;
  2173. if (c1 === ':' && (c2 === '/' || c2 === '\\\\')) return false;
  2174. return true;
  2175. }
  2176. function normalize (path) {
  2177. path = path.replace(/\\\\/g, '/');
  2178. var parts = path.split('/');
  2179. var slashed = parts[0] === '';
  2180. for (var i = 1; i < parts.length; i++) {
  2181. if (parts[i] === '.' || parts[i] === '') {
  2182. parts.splice(i--, 1);
  2183. }
  2184. }
  2185. for (var i = 1; i < parts.length; i++) {
  2186. if (parts[i] !== '..') continue;
  2187. if (i > 0 && parts[i - 1] !== '..' && parts[i - 1] !== '.') {
  2188. parts.splice(--i, 2);
  2189. i--;
  2190. }
  2191. }
  2192. path = parts.join('/');
  2193. if (slashed && path[0] !== '/') path = '/' + path;
  2194. else if (path.length === 0) path = '.';
  2195. return path;
  2196. }`;
  2197. }
  2198. const isWrappedId = (id, suffix) => id.endsWith(suffix);
  2199. const wrapId = (id, suffix) => `\0${id}${suffix}`;
  2200. const unwrapId = (wrappedId, suffix) => wrappedId.slice(1, -suffix.length);
  2201. // A proxy module when a module is required from non-wrapped CommonJS. Is different for ESM and CommonJS requires.
  2202. const PROXY_SUFFIX = '?commonjs-proxy';
  2203. // Indicates that a required module is wrapped commonjs and needs special handling.
  2204. const WRAPPED_SUFFIX = '?commonjs-wrapped';
  2205. // Indicates that a required module is external
  2206. const EXTERNAL_SUFFIX = '?commonjs-external';
  2207. // A helper module that contains the exports object of a module
  2208. const EXPORTS_SUFFIX = '?commonjs-exports';
  2209. // A helper module that contains the module object of a module, e.g. when module.exports is reassigned
  2210. const MODULE_SUFFIX = '?commonjs-module';
  2211. // A special proxy for CommonJS entry points
  2212. const ENTRY_SUFFIX = '?commonjs-entry';
  2213. // A proxy when wrapped ESM is required from CommonJS
  2214. const ES_IMPORT_SUFFIX = '?commonjs-es-import';
  2215. const DYNAMIC_MODULES_ID = '\0commonjs-dynamic-modules';
  2216. const HELPERS_ID = '\0commonjsHelpers.js';
  2217. const IS_WRAPPED_COMMONJS = 'withRequireFunction';
  2218. // `x['default']` is used instead of `x.default` for backward compatibility with ES3 browsers.
  2219. // Minifiers like uglify will usually transpile it back if compatibility with ES3 is not enabled.
  2220. // This could be improved by inspecting Rollup's "generatedCode" option
  2221. const HELPERS = `
  2222. export var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
  2223. export function getDefaultExportFromCjs (x) {
  2224. return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
  2225. }
  2226. export function getDefaultExportFromNamespaceIfPresent (n) {
  2227. return n && Object.prototype.hasOwnProperty.call(n, 'default') ? n['default'] : n;
  2228. }
  2229. export function getDefaultExportFromNamespaceIfNotNamed (n) {
  2230. return n && Object.prototype.hasOwnProperty.call(n, 'default') && Object.keys(n).length === 1 ? n['default'] : n;
  2231. }
  2232. export function getAugmentedNamespace(n) {
  2233. if (Object.prototype.hasOwnProperty.call(n, '__esModule')) return n;
  2234. var f = n.default;
  2235. if (typeof f == "function") {
  2236. var a = function a () {
  2237. if (this instanceof a) {
  2238. return Reflect.construct(f, arguments, this.constructor);
  2239. }
  2240. return f.apply(this, arguments);
  2241. };
  2242. a.prototype = f.prototype;
  2243. } else a = {};
  2244. Object.defineProperty(a, '__esModule', {value: true});
  2245. Object.keys(n).forEach(function (k) {
  2246. var d = Object.getOwnPropertyDescriptor(n, k);
  2247. Object.defineProperty(a, k, d.get ? d : {
  2248. enumerable: true,
  2249. get: function () {
  2250. return n[k];
  2251. }
  2252. });
  2253. });
  2254. return a;
  2255. }
  2256. `;
  2257. function getHelpersModule() {
  2258. return HELPERS;
  2259. }
  2260. function getUnknownRequireProxy(id, requireReturnsDefault) {
  2261. if (requireReturnsDefault === true || id.endsWith('.json')) {
  2262. return `export { default } from ${JSON.stringify(id)};`;
  2263. }
  2264. const name = getName(id);
  2265. const exported =
  2266. requireReturnsDefault === 'auto'
  2267. ? `import { getDefaultExportFromNamespaceIfNotNamed } from "${HELPERS_ID}"; export default /*@__PURE__*/getDefaultExportFromNamespaceIfNotNamed(${name});`
  2268. : requireReturnsDefault === 'preferred'
  2269. ? `import { getDefaultExportFromNamespaceIfPresent } from "${HELPERS_ID}"; export default /*@__PURE__*/getDefaultExportFromNamespaceIfPresent(${name});`
  2270. : !requireReturnsDefault
  2271. ? `import { getAugmentedNamespace } from "${HELPERS_ID}"; export default /*@__PURE__*/getAugmentedNamespace(${name});`
  2272. : `export default ${name};`;
  2273. return `import * as ${name} from ${JSON.stringify(id)}; ${exported}`;
  2274. }
  2275. async function getStaticRequireProxy(id, requireReturnsDefault, loadModule) {
  2276. const name = getName(id);
  2277. const {
  2278. meta: { commonjs: commonjsMeta }
  2279. } = await loadModule({ id });
  2280. if (!commonjsMeta) {
  2281. return getUnknownRequireProxy(id, requireReturnsDefault);
  2282. }
  2283. if (commonjsMeta.isCommonJS) {
  2284. return `export { __moduleExports as default } from ${JSON.stringify(id)};`;
  2285. }
  2286. if (!requireReturnsDefault) {
  2287. return `import { getAugmentedNamespace } from "${HELPERS_ID}"; import * as ${name} from ${JSON.stringify(
  2288. id
  2289. )}; export default /*@__PURE__*/getAugmentedNamespace(${name});`;
  2290. }
  2291. if (
  2292. requireReturnsDefault !== true &&
  2293. (requireReturnsDefault === 'namespace' ||
  2294. !commonjsMeta.hasDefaultExport ||
  2295. (requireReturnsDefault === 'auto' && commonjsMeta.hasNamedExports))
  2296. ) {
  2297. return `import * as ${name} from ${JSON.stringify(id)}; export default ${name};`;
  2298. }
  2299. return `export { default } from ${JSON.stringify(id)};`;
  2300. }
  2301. function getEntryProxy(id, defaultIsModuleExports, getModuleInfo, shebang) {
  2302. const {
  2303. meta: { commonjs: commonjsMeta },
  2304. hasDefaultExport
  2305. } = getModuleInfo(id);
  2306. if (!commonjsMeta || commonjsMeta.isCommonJS !== IS_WRAPPED_COMMONJS) {
  2307. const stringifiedId = JSON.stringify(id);
  2308. let code = `export * from ${stringifiedId};`;
  2309. if (hasDefaultExport) {
  2310. code += `export { default } from ${stringifiedId};`;
  2311. }
  2312. return shebang + code;
  2313. }
  2314. const result = getEsImportProxy(id, defaultIsModuleExports, true);
  2315. return {
  2316. ...result,
  2317. code: shebang + result.code
  2318. };
  2319. }
  2320. function getEsImportProxy(id, defaultIsModuleExports, moduleSideEffects) {
  2321. const name = getName(id);
  2322. const exportsName = `${name}Exports`;
  2323. const requireModule = `require${capitalize(name)}`;
  2324. let code =
  2325. `import { getDefaultExportFromCjs } from "${HELPERS_ID}";\n` +
  2326. `import { __require as ${requireModule} } from ${JSON.stringify(id)};\n` +
  2327. `var ${exportsName} = ${moduleSideEffects ? '' : '/*@__PURE__*/ '}${requireModule}();\n` +
  2328. `export { ${exportsName} as __moduleExports };`;
  2329. if (defaultIsModuleExports === true) {
  2330. code += `\nexport { ${exportsName} as default };`;
  2331. } else if (defaultIsModuleExports === false) {
  2332. code += `\nexport default ${exportsName}.default;`;
  2333. } else {
  2334. code += `\nexport default /*@__PURE__*/getDefaultExportFromCjs(${exportsName});`;
  2335. }
  2336. return {
  2337. code,
  2338. syntheticNamedExports: '__moduleExports'
  2339. };
  2340. }
  2341. /* eslint-disable no-param-reassign, no-undefined */
  2342. function getCandidatesForExtension(resolved, extension) {
  2343. return [resolved + extension, `${resolved}${sep}index${extension}`];
  2344. }
  2345. function getCandidates(resolved, extensions) {
  2346. return extensions.reduce(
  2347. (paths, extension) => paths.concat(getCandidatesForExtension(resolved, extension)),
  2348. [resolved]
  2349. );
  2350. }
  2351. function resolveExtensions(importee, importer, extensions) {
  2352. // not our problem
  2353. if (importee[0] !== '.' || !importer) return undefined;
  2354. const resolved = resolve$3(dirname$1(importer), importee);
  2355. const candidates = getCandidates(resolved, extensions);
  2356. for (let i = 0; i < candidates.length; i += 1) {
  2357. try {
  2358. const stats = statSync(candidates[i]);
  2359. if (stats.isFile()) return { id: candidates[i] };
  2360. } catch (err) {
  2361. /* noop */
  2362. }
  2363. }
  2364. return undefined;
  2365. }
  2366. function getResolveId(extensions, isPossibleCjsId) {
  2367. const currentlyResolving = new Map();
  2368. return {
  2369. /**
  2370. * This is a Maps of importers to Sets of require sources being resolved at
  2371. * the moment by resolveRequireSourcesAndUpdateMeta
  2372. */
  2373. currentlyResolving,
  2374. async resolveId(importee, importer, resolveOptions) {
  2375. const customOptions = resolveOptions.custom;
  2376. // All logic below is specific to ES imports.
  2377. // Also, if we do not skip this logic for requires that are resolved while
  2378. // transforming a commonjs file, it can easily lead to deadlocks.
  2379. if (customOptions?.['node-resolve']?.isRequire) {
  2380. return null;
  2381. }
  2382. const currentlyResolvingForParent = currentlyResolving.get(importer);
  2383. if (currentlyResolvingForParent && currentlyResolvingForParent.has(importee)) {
  2384. this.warn({
  2385. code: 'THIS_RESOLVE_WITHOUT_OPTIONS',
  2386. message:
  2387. 'It appears a plugin has implemented a "resolveId" hook that uses "this.resolve" without forwarding the third "options" parameter of "resolveId". This is problematic as it can lead to wrong module resolutions especially for the node-resolve plugin and in certain cases cause early exit errors for the commonjs plugin.\nIn rare cases, this warning can appear if the same file is both imported and required from the same mixed ES/CommonJS module, in which case it can be ignored.',
  2388. url: 'https://rollupjs.org/guide/en/#resolveid'
  2389. });
  2390. return null;
  2391. }
  2392. if (isWrappedId(importee, WRAPPED_SUFFIX)) {
  2393. return unwrapId(importee, WRAPPED_SUFFIX);
  2394. }
  2395. if (
  2396. importee.endsWith(ENTRY_SUFFIX) ||
  2397. isWrappedId(importee, MODULE_SUFFIX) ||
  2398. isWrappedId(importee, EXPORTS_SUFFIX) ||
  2399. isWrappedId(importee, PROXY_SUFFIX) ||
  2400. isWrappedId(importee, ES_IMPORT_SUFFIX) ||
  2401. isWrappedId(importee, EXTERNAL_SUFFIX) ||
  2402. importee.startsWith(HELPERS_ID) ||
  2403. importee === DYNAMIC_MODULES_ID
  2404. ) {
  2405. return importee;
  2406. }
  2407. if (importer) {
  2408. if (
  2409. importer === DYNAMIC_MODULES_ID ||
  2410. // Proxies are only importing resolved ids, no need to resolve again
  2411. isWrappedId(importer, PROXY_SUFFIX) ||
  2412. isWrappedId(importer, ES_IMPORT_SUFFIX) ||
  2413. importer.endsWith(ENTRY_SUFFIX)
  2414. ) {
  2415. return importee;
  2416. }
  2417. if (isWrappedId(importer, EXTERNAL_SUFFIX)) {
  2418. // We need to return null for unresolved imports so that the proper warning is shown
  2419. if (
  2420. !(await this.resolve(
  2421. importee,
  2422. importer,
  2423. Object.assign({ skipSelf: true }, resolveOptions)
  2424. ))
  2425. ) {
  2426. return null;
  2427. }
  2428. // For other external imports, we need to make sure they are handled as external
  2429. return { id: importee, external: true };
  2430. }
  2431. }
  2432. if (importee.startsWith('\0')) {
  2433. return null;
  2434. }
  2435. // If this is an entry point or ESM import, we need to figure out if the importee is wrapped and
  2436. // if that is the case, we need to add a proxy.
  2437. const resolved =
  2438. (await this.resolve(
  2439. importee,
  2440. importer,
  2441. Object.assign({ skipSelf: true }, resolveOptions)
  2442. )) || resolveExtensions(importee, importer, extensions);
  2443. // Make sure that even if other plugins resolve again, we ignore our own proxies
  2444. if (
  2445. !resolved ||
  2446. resolved.external ||
  2447. resolved.id.endsWith(ENTRY_SUFFIX) ||
  2448. isWrappedId(resolved.id, ES_IMPORT_SUFFIX) ||
  2449. !isPossibleCjsId(resolved.id)
  2450. ) {
  2451. return resolved;
  2452. }
  2453. const moduleInfo = await this.load(resolved);
  2454. const {
  2455. meta: { commonjs: commonjsMeta }
  2456. } = moduleInfo;
  2457. if (commonjsMeta) {
  2458. const { isCommonJS } = commonjsMeta;
  2459. if (isCommonJS) {
  2460. if (resolveOptions.isEntry) {
  2461. moduleInfo.moduleSideEffects = true;
  2462. // We must not precede entry proxies with a `\0` as that will mess up relative external resolution
  2463. return resolved.id + ENTRY_SUFFIX;
  2464. }
  2465. if (isCommonJS === IS_WRAPPED_COMMONJS) {
  2466. return { id: wrapId(resolved.id, ES_IMPORT_SUFFIX), meta: { commonjs: { resolved } } };
  2467. }
  2468. }
  2469. }
  2470. return resolved;
  2471. }
  2472. };
  2473. }
  2474. function getRequireResolver(extensions, detectCyclesAndConditional, currentlyResolving) {
  2475. const knownCjsModuleTypes = Object.create(null);
  2476. const requiredIds = Object.create(null);
  2477. const unconditionallyRequiredIds = Object.create(null);
  2478. const dependencies = Object.create(null);
  2479. const getDependencies = (id) => dependencies[id] || (dependencies[id] = new Set());
  2480. const isCyclic = (id) => {
  2481. const dependenciesToCheck = new Set(getDependencies(id));
  2482. for (const dependency of dependenciesToCheck) {
  2483. if (dependency === id) {
  2484. return true;
  2485. }
  2486. for (const childDependency of getDependencies(dependency)) {
  2487. dependenciesToCheck.add(childDependency);
  2488. }
  2489. }
  2490. return false;
  2491. };
  2492. // Once a module is listed here, its type (wrapped or not) is fixed and may
  2493. // not change for the rest of the current build, to not break already
  2494. // transformed modules.
  2495. const fullyAnalyzedModules = Object.create(null);
  2496. const getTypeForFullyAnalyzedModule = (id) => {
  2497. const knownType = knownCjsModuleTypes[id];
  2498. if (knownType !== true || !detectCyclesAndConditional || fullyAnalyzedModules[id]) {
  2499. return knownType;
  2500. }
  2501. if (isCyclic(id)) {
  2502. return (knownCjsModuleTypes[id] = IS_WRAPPED_COMMONJS);
  2503. }
  2504. return knownType;
  2505. };
  2506. const setInitialParentType = (id, initialCommonJSType) => {
  2507. // Fully analyzed modules may never change type
  2508. if (fullyAnalyzedModules[id]) {
  2509. return;
  2510. }
  2511. knownCjsModuleTypes[id] = initialCommonJSType;
  2512. if (
  2513. detectCyclesAndConditional &&
  2514. knownCjsModuleTypes[id] === true &&
  2515. requiredIds[id] &&
  2516. !unconditionallyRequiredIds[id]
  2517. ) {
  2518. knownCjsModuleTypes[id] = IS_WRAPPED_COMMONJS;
  2519. }
  2520. };
  2521. const analyzeRequiredModule = async (parentId, resolved, isConditional, loadModule) => {
  2522. const childId = resolved.id;
  2523. requiredIds[childId] = true;
  2524. if (!(isConditional || knownCjsModuleTypes[parentId] === IS_WRAPPED_COMMONJS)) {
  2525. unconditionallyRequiredIds[childId] = true;
  2526. }
  2527. getDependencies(parentId).add(childId);
  2528. if (!isCyclic(childId)) {
  2529. // This makes sure the current transform handler waits for all direct
  2530. // dependencies to be loaded and transformed and therefore for all
  2531. // transitive CommonJS dependencies to be loaded as well so that all
  2532. // cycles have been found and knownCjsModuleTypes is reliable.
  2533. await loadModule(resolved);
  2534. }
  2535. };
  2536. const getTypeForImportedModule = async (resolved, loadModule) => {
  2537. if (resolved.id in knownCjsModuleTypes) {
  2538. // This handles cyclic ES dependencies
  2539. return knownCjsModuleTypes[resolved.id];
  2540. }
  2541. const {
  2542. meta: { commonjs }
  2543. } = await loadModule(resolved);
  2544. return (commonjs && commonjs.isCommonJS) || false;
  2545. };
  2546. return {
  2547. getWrappedIds: () =>
  2548. Object.keys(knownCjsModuleTypes).filter(
  2549. (id) => knownCjsModuleTypes[id] === IS_WRAPPED_COMMONJS
  2550. ),
  2551. isRequiredId: (id) => requiredIds[id],
  2552. async shouldTransformCachedModule({
  2553. id: parentId,
  2554. resolvedSources,
  2555. meta: { commonjs: parentMeta }
  2556. }) {
  2557. // We explicitly track ES modules to handle circular imports
  2558. if (!(parentMeta && parentMeta.isCommonJS)) knownCjsModuleTypes[parentId] = false;
  2559. if (isWrappedId(parentId, ES_IMPORT_SUFFIX)) return false;
  2560. const parentRequires = parentMeta && parentMeta.requires;
  2561. if (parentRequires) {
  2562. setInitialParentType(parentId, parentMeta.initialCommonJSType);
  2563. await Promise.all(
  2564. parentRequires.map(({ resolved, isConditional }) =>
  2565. analyzeRequiredModule(parentId, resolved, isConditional, this.load)
  2566. )
  2567. );
  2568. if (getTypeForFullyAnalyzedModule(parentId) !== parentMeta.isCommonJS) {
  2569. return true;
  2570. }
  2571. for (const {
  2572. resolved: { id }
  2573. } of parentRequires) {
  2574. if (getTypeForFullyAnalyzedModule(id) !== parentMeta.isRequiredCommonJS[id]) {
  2575. return true;
  2576. }
  2577. }
  2578. // Now that we decided to go with the cached copy, neither the parent
  2579. // module nor any of its children may change types anymore
  2580. fullyAnalyzedModules[parentId] = true;
  2581. for (const {
  2582. resolved: { id }
  2583. } of parentRequires) {
  2584. fullyAnalyzedModules[id] = true;
  2585. }
  2586. }
  2587. const parentRequireSet = new Set((parentRequires || []).map(({ resolved: { id } }) => id));
  2588. return (
  2589. await Promise.all(
  2590. Object.keys(resolvedSources)
  2591. .map((source) => resolvedSources[source])
  2592. .filter(({ id, external }) => !(external || parentRequireSet.has(id)))
  2593. .map(async (resolved) => {
  2594. if (isWrappedId(resolved.id, ES_IMPORT_SUFFIX)) {
  2595. return (
  2596. (await getTypeForImportedModule(
  2597. (
  2598. await this.load({ id: resolved.id })
  2599. ).meta.commonjs.resolved,
  2600. this.load
  2601. )) !== IS_WRAPPED_COMMONJS
  2602. );
  2603. }
  2604. return (await getTypeForImportedModule(resolved, this.load)) === IS_WRAPPED_COMMONJS;
  2605. })
  2606. )
  2607. ).some((shouldTransform) => shouldTransform);
  2608. },
  2609. /* eslint-disable no-param-reassign */
  2610. resolveRequireSourcesAndUpdateMeta:
  2611. (rollupContext) => async (parentId, isParentCommonJS, parentMeta, sources) => {
  2612. parentMeta.initialCommonJSType = isParentCommonJS;
  2613. parentMeta.requires = [];
  2614. parentMeta.isRequiredCommonJS = Object.create(null);
  2615. setInitialParentType(parentId, isParentCommonJS);
  2616. const currentlyResolvingForParent = currentlyResolving.get(parentId) || new Set();
  2617. currentlyResolving.set(parentId, currentlyResolvingForParent);
  2618. const requireTargets = await Promise.all(
  2619. sources.map(async ({ source, isConditional }) => {
  2620. // Never analyze or proxy internal modules
  2621. if (source.startsWith('\0')) {
  2622. return { id: source, allowProxy: false };
  2623. }
  2624. currentlyResolvingForParent.add(source);
  2625. const resolved =
  2626. (await rollupContext.resolve(source, parentId, {
  2627. skipSelf: false,
  2628. custom: { 'node-resolve': { isRequire: true } }
  2629. })) || resolveExtensions(source, parentId, extensions);
  2630. currentlyResolvingForParent.delete(source);
  2631. if (!resolved) {
  2632. return { id: wrapId(source, EXTERNAL_SUFFIX), allowProxy: false };
  2633. }
  2634. const childId = resolved.id;
  2635. if (resolved.external) {
  2636. return { id: wrapId(childId, EXTERNAL_SUFFIX), allowProxy: false };
  2637. }
  2638. parentMeta.requires.push({ resolved, isConditional });
  2639. await analyzeRequiredModule(parentId, resolved, isConditional, rollupContext.load);
  2640. return { id: childId, allowProxy: true };
  2641. })
  2642. );
  2643. parentMeta.isCommonJS = getTypeForFullyAnalyzedModule(parentId);
  2644. fullyAnalyzedModules[parentId] = true;
  2645. return requireTargets.map(({ id: dependencyId, allowProxy }, index) => {
  2646. // eslint-disable-next-line no-multi-assign
  2647. const isCommonJS = (parentMeta.isRequiredCommonJS[dependencyId] =
  2648. getTypeForFullyAnalyzedModule(dependencyId));
  2649. const isWrappedCommonJS = isCommonJS === IS_WRAPPED_COMMONJS;
  2650. fullyAnalyzedModules[dependencyId] = true;
  2651. return {
  2652. wrappedModuleSideEffects:
  2653. isWrappedCommonJS && rollupContext.getModuleInfo(dependencyId).moduleSideEffects,
  2654. source: sources[index].source,
  2655. id: allowProxy
  2656. ? wrapId(dependencyId, isWrappedCommonJS ? WRAPPED_SUFFIX : PROXY_SUFFIX)
  2657. : dependencyId,
  2658. isCommonJS
  2659. };
  2660. });
  2661. },
  2662. isCurrentlyResolving(source, parentId) {
  2663. const currentlyResolvingForParent = currentlyResolving.get(parentId);
  2664. return currentlyResolvingForParent && currentlyResolvingForParent.has(source);
  2665. }
  2666. };
  2667. }
  2668. function validateVersion(actualVersion, peerDependencyVersion, name) {
  2669. const versionRegexp = /\^(\d+\.\d+\.\d+)/g;
  2670. let minMajor = Infinity;
  2671. let minMinor = Infinity;
  2672. let minPatch = Infinity;
  2673. let foundVersion;
  2674. // eslint-disable-next-line no-cond-assign
  2675. while ((foundVersion = versionRegexp.exec(peerDependencyVersion))) {
  2676. const [foundMajor, foundMinor, foundPatch] = foundVersion[1].split('.').map(Number);
  2677. if (foundMajor < minMajor) {
  2678. minMajor = foundMajor;
  2679. minMinor = foundMinor;
  2680. minPatch = foundPatch;
  2681. }
  2682. }
  2683. if (!actualVersion) {
  2684. throw new Error(
  2685. `Insufficient ${name} version: "@rollup/plugin-commonjs" requires at least ${name}@${minMajor}.${minMinor}.${minPatch}.`
  2686. );
  2687. }
  2688. const [major, minor, patch] = actualVersion.split('.').map(Number);
  2689. if (
  2690. major < minMajor ||
  2691. (major === minMajor && (minor < minMinor || (minor === minMinor && patch < minPatch)))
  2692. ) {
  2693. throw new Error(
  2694. `Insufficient ${name} version: "@rollup/plugin-commonjs" requires at least ${name}@${minMajor}.${minMinor}.${minPatch} but found ${name}@${actualVersion}.`
  2695. );
  2696. }
  2697. }
  2698. const operators = {
  2699. '==': (x) => equals(x.left, x.right, false),
  2700. '!=': (x) => not(operators['=='](x)),
  2701. '===': (x) => equals(x.left, x.right, true),
  2702. '!==': (x) => not(operators['==='](x)),
  2703. '!': (x) => isFalsy(x.argument),
  2704. '&&': (x) => isTruthy(x.left) && isTruthy(x.right),
  2705. '||': (x) => isTruthy(x.left) || isTruthy(x.right)
  2706. };
  2707. function not(value) {
  2708. return value === null ? value : !value;
  2709. }
  2710. function equals(a, b, strict) {
  2711. if (a.type !== b.type) return null;
  2712. // eslint-disable-next-line eqeqeq
  2713. if (a.type === 'Literal') return strict ? a.value === b.value : a.value == b.value;
  2714. return null;
  2715. }
  2716. function isTruthy(node) {
  2717. if (!node) return false;
  2718. if (node.type === 'Literal') return !!node.value;
  2719. if (node.type === 'ParenthesizedExpression') return isTruthy(node.expression);
  2720. if (node.operator in operators) return operators[node.operator](node);
  2721. return null;
  2722. }
  2723. function isFalsy(node) {
  2724. return not(isTruthy(node));
  2725. }
  2726. function getKeypath(node) {
  2727. const parts = [];
  2728. while (node.type === 'MemberExpression') {
  2729. if (node.computed) return null;
  2730. parts.unshift(node.property.name);
  2731. // eslint-disable-next-line no-param-reassign
  2732. node = node.object;
  2733. }
  2734. if (node.type !== 'Identifier') return null;
  2735. const { name } = node;
  2736. parts.unshift(name);
  2737. return { name, keypath: parts.join('.') };
  2738. }
  2739. const KEY_COMPILED_ESM = '__esModule';
  2740. function getDefineCompiledEsmType(node) {
  2741. const definedPropertyWithExports = getDefinePropertyCallName(node, 'exports');
  2742. const definedProperty =
  2743. definedPropertyWithExports || getDefinePropertyCallName(node, 'module.exports');
  2744. if (definedProperty && definedProperty.key === KEY_COMPILED_ESM) {
  2745. return isTruthy(definedProperty.value)
  2746. ? definedPropertyWithExports
  2747. ? 'exports'
  2748. : 'module'
  2749. : false;
  2750. }
  2751. return false;
  2752. }
  2753. function getDefinePropertyCallName(node, targetName) {
  2754. const {
  2755. callee: { object, property }
  2756. } = node;
  2757. if (!object || object.type !== 'Identifier' || object.name !== 'Object') return;
  2758. if (!property || property.type !== 'Identifier' || property.name !== 'defineProperty') return;
  2759. if (node.arguments.length !== 3) return;
  2760. const targetNames = targetName.split('.');
  2761. const [target, key, value] = node.arguments;
  2762. if (targetNames.length === 1) {
  2763. if (target.type !== 'Identifier' || target.name !== targetNames[0]) {
  2764. return;
  2765. }
  2766. }
  2767. if (targetNames.length === 2) {
  2768. if (
  2769. target.type !== 'MemberExpression' ||
  2770. target.object.name !== targetNames[0] ||
  2771. target.property.name !== targetNames[1]
  2772. ) {
  2773. return;
  2774. }
  2775. }
  2776. if (value.type !== 'ObjectExpression' || !value.properties) return;
  2777. const valueProperty = value.properties.find((p) => p.key && p.key.name === 'value');
  2778. if (!valueProperty || !valueProperty.value) return;
  2779. // eslint-disable-next-line consistent-return
  2780. return { key: key.value, value: valueProperty.value };
  2781. }
  2782. function isShorthandProperty(parent) {
  2783. return parent && parent.type === 'Property' && parent.shorthand;
  2784. }
  2785. function wrapCode(magicString, uses, moduleName, exportsName, indentExclusionRanges) {
  2786. const args = [];
  2787. const passedArgs = [];
  2788. if (uses.module) {
  2789. args.push('module');
  2790. passedArgs.push(moduleName);
  2791. }
  2792. if (uses.exports) {
  2793. args.push('exports');
  2794. passedArgs.push(uses.module ? `${moduleName}.exports` : exportsName);
  2795. }
  2796. magicString
  2797. .trim()
  2798. .indent('\t', { exclude: indentExclusionRanges })
  2799. .prepend(`(function (${args.join(', ')}) {\n`)
  2800. // For some reason, this line is only indented correctly when using a
  2801. // require-wrapper if we have this leading space
  2802. .append(` \n} (${passedArgs.join(', ')}));`);
  2803. }
  2804. function rewriteExportsAndGetExportsBlock(
  2805. magicString,
  2806. moduleName,
  2807. exportsName,
  2808. exportedExportsName,
  2809. wrapped,
  2810. moduleExportsAssignments,
  2811. firstTopLevelModuleExportsAssignment,
  2812. exportsAssignmentsByName,
  2813. topLevelAssignments,
  2814. defineCompiledEsmExpressions,
  2815. deconflictedExportNames,
  2816. code,
  2817. HELPERS_NAME,
  2818. exportMode,
  2819. defaultIsModuleExports,
  2820. usesRequireWrapper,
  2821. requireName
  2822. ) {
  2823. const exports = [];
  2824. const exportDeclarations = [];
  2825. if (usesRequireWrapper) {
  2826. getExportsWhenUsingRequireWrapper(
  2827. magicString,
  2828. wrapped,
  2829. exportMode,
  2830. exports,
  2831. moduleExportsAssignments,
  2832. exportsAssignmentsByName,
  2833. moduleName,
  2834. exportsName,
  2835. requireName,
  2836. defineCompiledEsmExpressions
  2837. );
  2838. } else if (exportMode === 'replace') {
  2839. getExportsForReplacedModuleExports(
  2840. magicString,
  2841. exports,
  2842. exportDeclarations,
  2843. moduleExportsAssignments,
  2844. firstTopLevelModuleExportsAssignment,
  2845. exportsName,
  2846. defaultIsModuleExports,
  2847. HELPERS_NAME
  2848. );
  2849. } else {
  2850. if (exportMode === 'module') {
  2851. exportDeclarations.push(`var ${exportedExportsName} = ${moduleName}.exports`);
  2852. exports.push(`${exportedExportsName} as __moduleExports`);
  2853. } else {
  2854. exports.push(`${exportsName} as __moduleExports`);
  2855. }
  2856. if (wrapped) {
  2857. exportDeclarations.push(
  2858. getDefaultExportDeclaration(exportedExportsName, defaultIsModuleExports, HELPERS_NAME)
  2859. );
  2860. } else {
  2861. getExports(
  2862. magicString,
  2863. exports,
  2864. exportDeclarations,
  2865. moduleExportsAssignments,
  2866. exportsAssignmentsByName,
  2867. deconflictedExportNames,
  2868. topLevelAssignments,
  2869. moduleName,
  2870. exportsName,
  2871. exportedExportsName,
  2872. defineCompiledEsmExpressions,
  2873. HELPERS_NAME,
  2874. defaultIsModuleExports,
  2875. exportMode
  2876. );
  2877. }
  2878. }
  2879. if (exports.length) {
  2880. exportDeclarations.push(`export { ${exports.join(', ')} }`);
  2881. }
  2882. return `\n\n${exportDeclarations.join(';\n')};`;
  2883. }
  2884. function getExportsWhenUsingRequireWrapper(
  2885. magicString,
  2886. wrapped,
  2887. exportMode,
  2888. exports,
  2889. moduleExportsAssignments,
  2890. exportsAssignmentsByName,
  2891. moduleName,
  2892. exportsName,
  2893. requireName,
  2894. defineCompiledEsmExpressions
  2895. ) {
  2896. exports.push(`${requireName} as __require`);
  2897. if (wrapped) return;
  2898. if (exportMode === 'replace') {
  2899. rewriteModuleExportsAssignments(magicString, moduleExportsAssignments, exportsName);
  2900. } else {
  2901. rewriteModuleExportsAssignments(magicString, moduleExportsAssignments, `${moduleName}.exports`);
  2902. // Collect and rewrite named exports
  2903. for (const [exportName, { nodes }] of exportsAssignmentsByName) {
  2904. for (const { node, type } of nodes) {
  2905. magicString.overwrite(
  2906. node.start,
  2907. node.left.end,
  2908. `${
  2909. exportMode === 'module' && type === 'module' ? `${moduleName}.exports` : exportsName
  2910. }.${exportName}`
  2911. );
  2912. }
  2913. }
  2914. replaceDefineCompiledEsmExpressionsAndGetIfRestorable(
  2915. defineCompiledEsmExpressions,
  2916. magicString,
  2917. exportMode,
  2918. moduleName,
  2919. exportsName
  2920. );
  2921. }
  2922. }
  2923. function getExportsForReplacedModuleExports(
  2924. magicString,
  2925. exports,
  2926. exportDeclarations,
  2927. moduleExportsAssignments,
  2928. firstTopLevelModuleExportsAssignment,
  2929. exportsName,
  2930. defaultIsModuleExports,
  2931. HELPERS_NAME
  2932. ) {
  2933. for (const { left } of moduleExportsAssignments) {
  2934. magicString.overwrite(left.start, left.end, exportsName);
  2935. }
  2936. magicString.prependRight(firstTopLevelModuleExportsAssignment.left.start, 'var ');
  2937. exports.push(`${exportsName} as __moduleExports`);
  2938. exportDeclarations.push(
  2939. getDefaultExportDeclaration(exportsName, defaultIsModuleExports, HELPERS_NAME)
  2940. );
  2941. }
  2942. function getDefaultExportDeclaration(exportedExportsName, defaultIsModuleExports, HELPERS_NAME) {
  2943. return `export default ${
  2944. defaultIsModuleExports === true
  2945. ? exportedExportsName
  2946. : defaultIsModuleExports === false
  2947. ? `${exportedExportsName}.default`
  2948. : `/*@__PURE__*/${HELPERS_NAME}.getDefaultExportFromCjs(${exportedExportsName})`
  2949. }`;
  2950. }
  2951. function getExports(
  2952. magicString,
  2953. exports,
  2954. exportDeclarations,
  2955. moduleExportsAssignments,
  2956. exportsAssignmentsByName,
  2957. deconflictedExportNames,
  2958. topLevelAssignments,
  2959. moduleName,
  2960. exportsName,
  2961. exportedExportsName,
  2962. defineCompiledEsmExpressions,
  2963. HELPERS_NAME,
  2964. defaultIsModuleExports,
  2965. exportMode
  2966. ) {
  2967. let deconflictedDefaultExportName;
  2968. // Collect and rewrite module.exports assignments
  2969. for (const { left } of moduleExportsAssignments) {
  2970. magicString.overwrite(left.start, left.end, `${moduleName}.exports`);
  2971. }
  2972. // Collect and rewrite named exports
  2973. for (const [exportName, { nodes }] of exportsAssignmentsByName) {
  2974. const deconflicted = deconflictedExportNames[exportName];
  2975. let needsDeclaration = true;
  2976. for (const { node, type } of nodes) {
  2977. let replacement = `${deconflicted} = ${
  2978. exportMode === 'module' && type === 'module' ? `${moduleName}.exports` : exportsName
  2979. }.${exportName}`;
  2980. if (needsDeclaration && topLevelAssignments.has(node)) {
  2981. replacement = `var ${replacement}`;
  2982. needsDeclaration = false;
  2983. }
  2984. magicString.overwrite(node.start, node.left.end, replacement);
  2985. }
  2986. if (needsDeclaration) {
  2987. magicString.prepend(`var ${deconflicted};\n`);
  2988. }
  2989. if (exportName === 'default') {
  2990. deconflictedDefaultExportName = deconflicted;
  2991. } else {
  2992. exports.push(exportName === deconflicted ? exportName : `${deconflicted} as ${exportName}`);
  2993. }
  2994. }
  2995. const isRestorableCompiledEsm = replaceDefineCompiledEsmExpressionsAndGetIfRestorable(
  2996. defineCompiledEsmExpressions,
  2997. magicString,
  2998. exportMode,
  2999. moduleName,
  3000. exportsName
  3001. );
  3002. if (
  3003. defaultIsModuleExports === false ||
  3004. (defaultIsModuleExports === 'auto' &&
  3005. isRestorableCompiledEsm &&
  3006. moduleExportsAssignments.length === 0)
  3007. ) {
  3008. // If there is no deconflictedDefaultExportName, then we use the namespace as
  3009. // fallback because there can be no "default" property on the namespace
  3010. exports.push(`${deconflictedDefaultExportName || exportedExportsName} as default`);
  3011. } else if (
  3012. defaultIsModuleExports === true ||
  3013. (!isRestorableCompiledEsm && moduleExportsAssignments.length === 0)
  3014. ) {
  3015. exports.push(`${exportedExportsName} as default`);
  3016. } else {
  3017. exportDeclarations.push(
  3018. getDefaultExportDeclaration(exportedExportsName, defaultIsModuleExports, HELPERS_NAME)
  3019. );
  3020. }
  3021. }
  3022. function rewriteModuleExportsAssignments(magicString, moduleExportsAssignments, exportsName) {
  3023. for (const { left } of moduleExportsAssignments) {
  3024. magicString.overwrite(left.start, left.end, exportsName);
  3025. }
  3026. }
  3027. function replaceDefineCompiledEsmExpressionsAndGetIfRestorable(
  3028. defineCompiledEsmExpressions,
  3029. magicString,
  3030. exportMode,
  3031. moduleName,
  3032. exportsName
  3033. ) {
  3034. let isRestorableCompiledEsm = false;
  3035. for (const { node, type } of defineCompiledEsmExpressions) {
  3036. isRestorableCompiledEsm = true;
  3037. const moduleExportsExpression =
  3038. node.type === 'CallExpression' ? node.arguments[0] : node.left.object;
  3039. magicString.overwrite(
  3040. moduleExportsExpression.start,
  3041. moduleExportsExpression.end,
  3042. exportMode === 'module' && type === 'module' ? `${moduleName}.exports` : exportsName
  3043. );
  3044. }
  3045. return isRestorableCompiledEsm;
  3046. }
  3047. function isRequireExpression(node, scope) {
  3048. if (!node) return false;
  3049. if (node.type !== 'CallExpression') return false;
  3050. // Weird case of `require()` or `module.require()` without arguments
  3051. if (node.arguments.length === 0) return false;
  3052. return isRequire(node.callee, scope);
  3053. }
  3054. function isRequire(node, scope) {
  3055. return (
  3056. (node.type === 'Identifier' && node.name === 'require' && !scope.contains('require')) ||
  3057. (node.type === 'MemberExpression' && isModuleRequire(node, scope))
  3058. );
  3059. }
  3060. function isModuleRequire({ object, property }, scope) {
  3061. return (
  3062. object.type === 'Identifier' &&
  3063. object.name === 'module' &&
  3064. property.type === 'Identifier' &&
  3065. property.name === 'require' &&
  3066. !scope.contains('module')
  3067. );
  3068. }
  3069. function hasDynamicArguments(node) {
  3070. return (
  3071. node.arguments.length > 1 ||
  3072. (node.arguments[0].type !== 'Literal' &&
  3073. (node.arguments[0].type !== 'TemplateLiteral' || node.arguments[0].expressions.length > 0))
  3074. );
  3075. }
  3076. const reservedMethod = { resolve: true, cache: true, main: true };
  3077. function isNodeRequirePropertyAccess(parent) {
  3078. return parent && parent.property && reservedMethod[parent.property.name];
  3079. }
  3080. function getRequireStringArg(node) {
  3081. return node.arguments[0].type === 'Literal'
  3082. ? node.arguments[0].value
  3083. : node.arguments[0].quasis[0].value.cooked;
  3084. }
  3085. function getRequireHandlers() {
  3086. const requireExpressions = [];
  3087. function addRequireExpression(
  3088. sourceId,
  3089. node,
  3090. scope,
  3091. usesReturnValue,
  3092. isInsideTryBlock,
  3093. isInsideConditional,
  3094. toBeRemoved
  3095. ) {
  3096. requireExpressions.push({
  3097. sourceId,
  3098. node,
  3099. scope,
  3100. usesReturnValue,
  3101. isInsideTryBlock,
  3102. isInsideConditional,
  3103. toBeRemoved
  3104. });
  3105. }
  3106. async function rewriteRequireExpressionsAndGetImportBlock(
  3107. magicString,
  3108. topLevelDeclarations,
  3109. reassignedNames,
  3110. helpersName,
  3111. dynamicRequireName,
  3112. moduleName,
  3113. exportsName,
  3114. id,
  3115. exportMode,
  3116. resolveRequireSourcesAndUpdateMeta,
  3117. needsRequireWrapper,
  3118. isEsModule,
  3119. isDynamicRequireModulesEnabled,
  3120. getIgnoreTryCatchRequireStatementMode,
  3121. commonjsMeta
  3122. ) {
  3123. const imports = [];
  3124. imports.push(`import * as ${helpersName} from "${HELPERS_ID}"`);
  3125. if (dynamicRequireName) {
  3126. imports.push(
  3127. `import { ${
  3128. isDynamicRequireModulesEnabled ? CREATE_COMMONJS_REQUIRE_EXPORT : COMMONJS_REQUIRE_EXPORT
  3129. } as ${dynamicRequireName} } from "${DYNAMIC_MODULES_ID}"`
  3130. );
  3131. }
  3132. if (exportMode === 'module') {
  3133. imports.push(
  3134. `import { __module as ${moduleName} } from ${JSON.stringify(wrapId(id, MODULE_SUFFIX))}`,
  3135. `var ${exportsName} = ${moduleName}.exports`
  3136. );
  3137. } else if (exportMode === 'exports') {
  3138. imports.push(
  3139. `import { __exports as ${exportsName} } from ${JSON.stringify(wrapId(id, EXPORTS_SUFFIX))}`
  3140. );
  3141. }
  3142. const requiresBySource = collectSources(requireExpressions);
  3143. const requireTargets = await resolveRequireSourcesAndUpdateMeta(
  3144. id,
  3145. needsRequireWrapper ? IS_WRAPPED_COMMONJS : !isEsModule,
  3146. commonjsMeta,
  3147. Object.keys(requiresBySource).map((source) => {
  3148. return {
  3149. source,
  3150. isConditional: requiresBySource[source].every((require) => require.isInsideConditional)
  3151. };
  3152. })
  3153. );
  3154. processRequireExpressions(
  3155. imports,
  3156. requireTargets,
  3157. requiresBySource,
  3158. getIgnoreTryCatchRequireStatementMode,
  3159. magicString
  3160. );
  3161. return imports.length ? `${imports.join(';\n')};\n\n` : '';
  3162. }
  3163. return {
  3164. addRequireExpression,
  3165. rewriteRequireExpressionsAndGetImportBlock
  3166. };
  3167. }
  3168. function collectSources(requireExpressions) {
  3169. const requiresBySource = Object.create(null);
  3170. for (const requireExpression of requireExpressions) {
  3171. const { sourceId } = requireExpression;
  3172. if (!requiresBySource[sourceId]) {
  3173. requiresBySource[sourceId] = [];
  3174. }
  3175. const requires = requiresBySource[sourceId];
  3176. requires.push(requireExpression);
  3177. }
  3178. return requiresBySource;
  3179. }
  3180. function processRequireExpressions(
  3181. imports,
  3182. requireTargets,
  3183. requiresBySource,
  3184. getIgnoreTryCatchRequireStatementMode,
  3185. magicString
  3186. ) {
  3187. const generateRequireName = getGenerateRequireName();
  3188. for (const { source, id: resolvedId, isCommonJS, wrappedModuleSideEffects } of requireTargets) {
  3189. const requires = requiresBySource[source];
  3190. const name = generateRequireName(requires);
  3191. let usesRequired = false;
  3192. let needsImport = false;
  3193. for (const { node, usesReturnValue, toBeRemoved, isInsideTryBlock } of requires) {
  3194. const { canConvertRequire, shouldRemoveRequire } =
  3195. isInsideTryBlock && isWrappedId(resolvedId, EXTERNAL_SUFFIX)
  3196. ? getIgnoreTryCatchRequireStatementMode(source)
  3197. : { canConvertRequire: true, shouldRemoveRequire: false };
  3198. if (shouldRemoveRequire) {
  3199. if (usesReturnValue) {
  3200. magicString.overwrite(node.start, node.end, 'undefined');
  3201. } else {
  3202. magicString.remove(toBeRemoved.start, toBeRemoved.end);
  3203. }
  3204. } else if (canConvertRequire) {
  3205. needsImport = true;
  3206. if (isCommonJS === IS_WRAPPED_COMMONJS) {
  3207. magicString.overwrite(
  3208. node.start,
  3209. node.end,
  3210. `${wrappedModuleSideEffects ? '' : '/*@__PURE__*/ '}${name}()`
  3211. );
  3212. } else if (usesReturnValue) {
  3213. usesRequired = true;
  3214. magicString.overwrite(node.start, node.end, name);
  3215. } else {
  3216. magicString.remove(toBeRemoved.start, toBeRemoved.end);
  3217. }
  3218. }
  3219. }
  3220. if (needsImport) {
  3221. if (isCommonJS === IS_WRAPPED_COMMONJS) {
  3222. imports.push(`import { __require as ${name} } from ${JSON.stringify(resolvedId)}`);
  3223. } else {
  3224. imports.push(`import ${usesRequired ? `${name} from ` : ''}${JSON.stringify(resolvedId)}`);
  3225. }
  3226. }
  3227. }
  3228. }
  3229. function getGenerateRequireName() {
  3230. let uid = 0;
  3231. return (requires) => {
  3232. let name;
  3233. const hasNameConflict = ({ scope }) => scope.contains(name);
  3234. do {
  3235. name = `require$$${uid}`;
  3236. uid += 1;
  3237. } while (requires.some(hasNameConflict));
  3238. return name;
  3239. };
  3240. }
  3241. /* eslint-disable no-param-reassign, no-shadow, no-underscore-dangle, no-continue */
  3242. const exportsPattern = /^(?:module\.)?exports(?:\.([a-zA-Z_$][a-zA-Z_$0-9]*))?$/;
  3243. const functionType = /^(?:FunctionDeclaration|FunctionExpression|ArrowFunctionExpression)$/;
  3244. // There are three different types of CommonJS modules, described by their
  3245. // "exportMode":
  3246. // - exports: Only assignments to (module.)exports properties
  3247. // - replace: A single assignment to module.exports itself
  3248. // - module: Anything else
  3249. // Special cases:
  3250. // - usesRequireWrapper
  3251. // - isWrapped
  3252. async function transformCommonjs(
  3253. parse,
  3254. code,
  3255. id,
  3256. isEsModule,
  3257. ignoreGlobal,
  3258. ignoreRequire,
  3259. ignoreDynamicRequires,
  3260. getIgnoreTryCatchRequireStatementMode,
  3261. sourceMap,
  3262. isDynamicRequireModulesEnabled,
  3263. dynamicRequireModules,
  3264. commonDir,
  3265. astCache,
  3266. defaultIsModuleExports,
  3267. needsRequireWrapper,
  3268. resolveRequireSourcesAndUpdateMeta,
  3269. isRequired,
  3270. checkDynamicRequire,
  3271. commonjsMeta
  3272. ) {
  3273. const ast = astCache || tryParse(parse, code, id);
  3274. const magicString = new MagicString(code);
  3275. const uses = {
  3276. module: false,
  3277. exports: false,
  3278. global: false,
  3279. require: false
  3280. };
  3281. const virtualDynamicRequirePath =
  3282. isDynamicRequireModulesEnabled && getVirtualPathForDynamicRequirePath(dirname$1(id), commonDir);
  3283. let scope = attachScopes(ast, 'scope');
  3284. let lexicalDepth = 0;
  3285. let programDepth = 0;
  3286. let classBodyDepth = 0;
  3287. let currentTryBlockEnd = null;
  3288. let shouldWrap = false;
  3289. const globals = new Set();
  3290. // A conditionalNode is a node for which execution is not guaranteed. If such a node is a require
  3291. // or contains nested requires, those should be handled as function calls unless there is an
  3292. // unconditional require elsewhere.
  3293. let currentConditionalNodeEnd = null;
  3294. const conditionalNodes = new Set();
  3295. const { addRequireExpression, rewriteRequireExpressionsAndGetImportBlock } = getRequireHandlers();
  3296. // See which names are assigned to. This is necessary to prevent
  3297. // illegally replacing `var foo = require('foo')` with `import foo from 'foo'`,
  3298. // where `foo` is later reassigned. (This happens in the wild. CommonJS, sigh)
  3299. const reassignedNames = new Set();
  3300. const topLevelDeclarations = [];
  3301. const skippedNodes = new Set();
  3302. const moduleAccessScopes = new Set([scope]);
  3303. const exportsAccessScopes = new Set([scope]);
  3304. const moduleExportsAssignments = [];
  3305. let firstTopLevelModuleExportsAssignment = null;
  3306. const exportsAssignmentsByName = new Map();
  3307. const topLevelAssignments = new Set();
  3308. const topLevelDefineCompiledEsmExpressions = [];
  3309. const replacedGlobal = [];
  3310. const replacedThis = [];
  3311. const replacedDynamicRequires = [];
  3312. const importedVariables = new Set();
  3313. const indentExclusionRanges = [];
  3314. walk$2(ast, {
  3315. enter(node, parent) {
  3316. if (skippedNodes.has(node)) {
  3317. this.skip();
  3318. return;
  3319. }
  3320. if (currentTryBlockEnd !== null && node.start > currentTryBlockEnd) {
  3321. currentTryBlockEnd = null;
  3322. }
  3323. if (currentConditionalNodeEnd !== null && node.start > currentConditionalNodeEnd) {
  3324. currentConditionalNodeEnd = null;
  3325. }
  3326. if (currentConditionalNodeEnd === null && conditionalNodes.has(node)) {
  3327. currentConditionalNodeEnd = node.end;
  3328. }
  3329. programDepth += 1;
  3330. if (node.scope) ({ scope } = node);
  3331. if (functionType.test(node.type)) lexicalDepth += 1;
  3332. if (sourceMap) {
  3333. magicString.addSourcemapLocation(node.start);
  3334. magicString.addSourcemapLocation(node.end);
  3335. }
  3336. // eslint-disable-next-line default-case
  3337. switch (node.type) {
  3338. case 'AssignmentExpression':
  3339. if (node.left.type === 'MemberExpression') {
  3340. const flattened = getKeypath(node.left);
  3341. if (!flattened || scope.contains(flattened.name)) return;
  3342. const exportsPatternMatch = exportsPattern.exec(flattened.keypath);
  3343. if (!exportsPatternMatch || flattened.keypath === 'exports') return;
  3344. const [, exportName] = exportsPatternMatch;
  3345. uses[flattened.name] = true;
  3346. // we're dealing with `module.exports = ...` or `[module.]exports.foo = ...` –
  3347. if (flattened.keypath === 'module.exports') {
  3348. moduleExportsAssignments.push(node);
  3349. if (programDepth > 3) {
  3350. moduleAccessScopes.add(scope);
  3351. } else if (!firstTopLevelModuleExportsAssignment) {
  3352. firstTopLevelModuleExportsAssignment = node;
  3353. }
  3354. } else if (exportName === KEY_COMPILED_ESM) {
  3355. if (programDepth > 3) {
  3356. shouldWrap = true;
  3357. } else {
  3358. // The "type" is either "module" or "exports" to discern
  3359. // assignments to module.exports vs exports if needed
  3360. topLevelDefineCompiledEsmExpressions.push({ node, type: flattened.name });
  3361. }
  3362. } else {
  3363. const exportsAssignments = exportsAssignmentsByName.get(exportName) || {
  3364. nodes: [],
  3365. scopes: new Set()
  3366. };
  3367. exportsAssignments.nodes.push({ node, type: flattened.name });
  3368. exportsAssignments.scopes.add(scope);
  3369. exportsAccessScopes.add(scope);
  3370. exportsAssignmentsByName.set(exportName, exportsAssignments);
  3371. if (programDepth <= 3) {
  3372. topLevelAssignments.add(node);
  3373. }
  3374. }
  3375. skippedNodes.add(node.left);
  3376. } else {
  3377. for (const name of extractAssignedNames(node.left)) {
  3378. reassignedNames.add(name);
  3379. }
  3380. }
  3381. return;
  3382. case 'CallExpression': {
  3383. const defineCompiledEsmType = getDefineCompiledEsmType(node);
  3384. if (defineCompiledEsmType) {
  3385. if (programDepth === 3 && parent.type === 'ExpressionStatement') {
  3386. // skip special handling for [module.]exports until we know we render this
  3387. skippedNodes.add(node.arguments[0]);
  3388. topLevelDefineCompiledEsmExpressions.push({ node, type: defineCompiledEsmType });
  3389. } else {
  3390. shouldWrap = true;
  3391. }
  3392. return;
  3393. }
  3394. // Transform require.resolve
  3395. if (
  3396. isDynamicRequireModulesEnabled &&
  3397. node.callee.object &&
  3398. isRequire(node.callee.object, scope) &&
  3399. node.callee.property.name === 'resolve'
  3400. ) {
  3401. checkDynamicRequire(node.start);
  3402. uses.require = true;
  3403. const requireNode = node.callee.object;
  3404. replacedDynamicRequires.push(requireNode);
  3405. skippedNodes.add(node.callee);
  3406. return;
  3407. }
  3408. if (!isRequireExpression(node, scope)) {
  3409. const keypath = getKeypath(node.callee);
  3410. if (keypath && importedVariables.has(keypath.name)) {
  3411. // Heuristic to deoptimize requires after a required function has been called
  3412. currentConditionalNodeEnd = Infinity;
  3413. }
  3414. return;
  3415. }
  3416. skippedNodes.add(node.callee);
  3417. uses.require = true;
  3418. if (hasDynamicArguments(node)) {
  3419. if (isDynamicRequireModulesEnabled) {
  3420. checkDynamicRequire(node.start);
  3421. }
  3422. if (!ignoreDynamicRequires) {
  3423. replacedDynamicRequires.push(node.callee);
  3424. }
  3425. return;
  3426. }
  3427. const requireStringArg = getRequireStringArg(node);
  3428. if (!ignoreRequire(requireStringArg)) {
  3429. const usesReturnValue = parent.type !== 'ExpressionStatement';
  3430. const toBeRemoved =
  3431. parent.type === 'ExpressionStatement' &&
  3432. (!currentConditionalNodeEnd ||
  3433. // We should completely remove requires directly in a try-catch
  3434. // so that Rollup can remove up the try-catch
  3435. (currentTryBlockEnd !== null && currentTryBlockEnd < currentConditionalNodeEnd))
  3436. ? parent
  3437. : node;
  3438. addRequireExpression(
  3439. requireStringArg,
  3440. node,
  3441. scope,
  3442. usesReturnValue,
  3443. currentTryBlockEnd !== null,
  3444. currentConditionalNodeEnd !== null,
  3445. toBeRemoved
  3446. );
  3447. if (parent.type === 'VariableDeclarator' && parent.id.type === 'Identifier') {
  3448. for (const name of extractAssignedNames(parent.id)) {
  3449. importedVariables.add(name);
  3450. }
  3451. }
  3452. }
  3453. return;
  3454. }
  3455. case 'ClassBody':
  3456. classBodyDepth += 1;
  3457. return;
  3458. case 'ConditionalExpression':
  3459. case 'IfStatement':
  3460. // skip dead branches
  3461. if (isFalsy(node.test)) {
  3462. skippedNodes.add(node.consequent);
  3463. } else if (isTruthy(node.test)) {
  3464. if (node.alternate) {
  3465. skippedNodes.add(node.alternate);
  3466. }
  3467. } else {
  3468. conditionalNodes.add(node.consequent);
  3469. if (node.alternate) {
  3470. conditionalNodes.add(node.alternate);
  3471. }
  3472. }
  3473. return;
  3474. case 'ArrowFunctionExpression':
  3475. case 'FunctionDeclaration':
  3476. case 'FunctionExpression':
  3477. // requires in functions should be conditional unless it is an IIFE
  3478. if (
  3479. currentConditionalNodeEnd === null &&
  3480. !(parent.type === 'CallExpression' && parent.callee === node)
  3481. ) {
  3482. currentConditionalNodeEnd = node.end;
  3483. }
  3484. return;
  3485. case 'Identifier': {
  3486. const { name } = node;
  3487. if (
  3488. !isReference(node, parent) ||
  3489. scope.contains(name) ||
  3490. (parent.type === 'PropertyDefinition' && parent.key === node)
  3491. )
  3492. return;
  3493. switch (name) {
  3494. case 'require':
  3495. uses.require = true;
  3496. if (isNodeRequirePropertyAccess(parent)) {
  3497. return;
  3498. }
  3499. if (!ignoreDynamicRequires) {
  3500. if (isShorthandProperty(parent)) {
  3501. // as key and value are the same object, isReference regards
  3502. // both as references, so we need to skip now
  3503. skippedNodes.add(parent.value);
  3504. magicString.prependRight(node.start, 'require: ');
  3505. }
  3506. replacedDynamicRequires.push(node);
  3507. }
  3508. return;
  3509. case 'module':
  3510. case 'exports':
  3511. shouldWrap = true;
  3512. uses[name] = true;
  3513. return;
  3514. case 'global':
  3515. uses.global = true;
  3516. if (!ignoreGlobal) {
  3517. replacedGlobal.push(node);
  3518. }
  3519. return;
  3520. case 'define':
  3521. magicString.overwrite(node.start, node.end, 'undefined', {
  3522. storeName: true
  3523. });
  3524. return;
  3525. default:
  3526. globals.add(name);
  3527. return;
  3528. }
  3529. }
  3530. case 'LogicalExpression':
  3531. // skip dead branches
  3532. if (node.operator === '&&') {
  3533. if (isFalsy(node.left)) {
  3534. skippedNodes.add(node.right);
  3535. } else if (!isTruthy(node.left)) {
  3536. conditionalNodes.add(node.right);
  3537. }
  3538. } else if (node.operator === '||') {
  3539. if (isTruthy(node.left)) {
  3540. skippedNodes.add(node.right);
  3541. } else if (!isFalsy(node.left)) {
  3542. conditionalNodes.add(node.right);
  3543. }
  3544. }
  3545. return;
  3546. case 'MemberExpression':
  3547. if (!isDynamicRequireModulesEnabled && isModuleRequire(node, scope)) {
  3548. uses.require = true;
  3549. replacedDynamicRequires.push(node);
  3550. skippedNodes.add(node.object);
  3551. skippedNodes.add(node.property);
  3552. }
  3553. return;
  3554. case 'ReturnStatement':
  3555. // if top-level return, we need to wrap it
  3556. if (lexicalDepth === 0) {
  3557. shouldWrap = true;
  3558. }
  3559. return;
  3560. case 'ThisExpression':
  3561. // rewrite top-level `this` as `commonjsHelpers.commonjsGlobal`
  3562. if (lexicalDepth === 0 && !classBodyDepth) {
  3563. uses.global = true;
  3564. if (!ignoreGlobal) {
  3565. replacedThis.push(node);
  3566. }
  3567. }
  3568. return;
  3569. case 'TryStatement':
  3570. if (currentTryBlockEnd === null) {
  3571. currentTryBlockEnd = node.block.end;
  3572. }
  3573. if (currentConditionalNodeEnd === null) {
  3574. currentConditionalNodeEnd = node.end;
  3575. }
  3576. return;
  3577. case 'UnaryExpression':
  3578. // rewrite `typeof module`, `typeof module.exports` and `typeof exports` (https://github.com/rollup/rollup-plugin-commonjs/issues/151)
  3579. if (node.operator === 'typeof') {
  3580. const flattened = getKeypath(node.argument);
  3581. if (!flattened) return;
  3582. if (scope.contains(flattened.name)) return;
  3583. if (
  3584. !isEsModule &&
  3585. (flattened.keypath === 'module.exports' ||
  3586. flattened.keypath === 'module' ||
  3587. flattened.keypath === 'exports')
  3588. ) {
  3589. magicString.overwrite(node.start, node.end, `'object'`, {
  3590. storeName: false
  3591. });
  3592. }
  3593. }
  3594. return;
  3595. case 'VariableDeclaration':
  3596. if (!scope.parent) {
  3597. topLevelDeclarations.push(node);
  3598. }
  3599. return;
  3600. case 'TemplateElement':
  3601. if (node.value.raw.includes('\n')) {
  3602. indentExclusionRanges.push([node.start, node.end]);
  3603. }
  3604. }
  3605. },
  3606. leave(node) {
  3607. programDepth -= 1;
  3608. if (node.scope) scope = scope.parent;
  3609. if (functionType.test(node.type)) lexicalDepth -= 1;
  3610. if (node.type === 'ClassBody') classBodyDepth -= 1;
  3611. }
  3612. });
  3613. const nameBase = getName(id);
  3614. const exportsName = deconflict([...exportsAccessScopes], globals, nameBase);
  3615. const moduleName = deconflict([...moduleAccessScopes], globals, `${nameBase}Module`);
  3616. const requireName = deconflict([scope], globals, `require${capitalize(nameBase)}`);
  3617. const isRequiredName = deconflict([scope], globals, `hasRequired${capitalize(nameBase)}`);
  3618. const helpersName = deconflict([scope], globals, 'commonjsHelpers');
  3619. const dynamicRequireName =
  3620. replacedDynamicRequires.length > 0 &&
  3621. deconflict(
  3622. [scope],
  3623. globals,
  3624. isDynamicRequireModulesEnabled ? CREATE_COMMONJS_REQUIRE_EXPORT : COMMONJS_REQUIRE_EXPORT
  3625. );
  3626. const deconflictedExportNames = Object.create(null);
  3627. for (const [exportName, { scopes }] of exportsAssignmentsByName) {
  3628. deconflictedExportNames[exportName] = deconflict([...scopes], globals, exportName);
  3629. }
  3630. for (const node of replacedGlobal) {
  3631. magicString.overwrite(node.start, node.end, `${helpersName}.commonjsGlobal`, {
  3632. storeName: true
  3633. });
  3634. }
  3635. for (const node of replacedThis) {
  3636. magicString.overwrite(node.start, node.end, exportsName, {
  3637. storeName: true
  3638. });
  3639. }
  3640. for (const node of replacedDynamicRequires) {
  3641. magicString.overwrite(
  3642. node.start,
  3643. node.end,
  3644. isDynamicRequireModulesEnabled
  3645. ? `${dynamicRequireName}(${JSON.stringify(virtualDynamicRequirePath)})`
  3646. : dynamicRequireName,
  3647. {
  3648. contentOnly: true,
  3649. storeName: true
  3650. }
  3651. );
  3652. }
  3653. // We cannot wrap ES/mixed modules
  3654. shouldWrap = !isEsModule && (shouldWrap || (uses.exports && moduleExportsAssignments.length > 0));
  3655. if (
  3656. !(
  3657. shouldWrap ||
  3658. isRequired ||
  3659. needsRequireWrapper ||
  3660. uses.module ||
  3661. uses.exports ||
  3662. uses.require ||
  3663. topLevelDefineCompiledEsmExpressions.length > 0
  3664. ) &&
  3665. (ignoreGlobal || !uses.global)
  3666. ) {
  3667. return { meta: { commonjs: { isCommonJS: false } } };
  3668. }
  3669. let leadingComment = '';
  3670. if (code.startsWith('/*')) {
  3671. const commentEnd = code.indexOf('*/', 2) + 2;
  3672. leadingComment = `${code.slice(0, commentEnd)}\n`;
  3673. magicString.remove(0, commentEnd).trim();
  3674. }
  3675. let shebang = '';
  3676. if (code.startsWith('#!')) {
  3677. const shebangEndPosition = code.indexOf('\n') + 1;
  3678. shebang = code.slice(0, shebangEndPosition);
  3679. magicString.remove(0, shebangEndPosition).trim();
  3680. }
  3681. const exportMode = isEsModule
  3682. ? 'none'
  3683. : shouldWrap
  3684. ? uses.module
  3685. ? 'module'
  3686. : 'exports'
  3687. : firstTopLevelModuleExportsAssignment
  3688. ? exportsAssignmentsByName.size === 0 && topLevelDefineCompiledEsmExpressions.length === 0
  3689. ? 'replace'
  3690. : 'module'
  3691. : moduleExportsAssignments.length === 0
  3692. ? 'exports'
  3693. : 'module';
  3694. const exportedExportsName =
  3695. exportMode === 'module' ? deconflict([], globals, `${nameBase}Exports`) : exportsName;
  3696. const importBlock = await rewriteRequireExpressionsAndGetImportBlock(
  3697. magicString,
  3698. topLevelDeclarations,
  3699. reassignedNames,
  3700. helpersName,
  3701. dynamicRequireName,
  3702. moduleName,
  3703. exportsName,
  3704. id,
  3705. exportMode,
  3706. resolveRequireSourcesAndUpdateMeta,
  3707. needsRequireWrapper,
  3708. isEsModule,
  3709. isDynamicRequireModulesEnabled,
  3710. getIgnoreTryCatchRequireStatementMode,
  3711. commonjsMeta
  3712. );
  3713. const usesRequireWrapper = commonjsMeta.isCommonJS === IS_WRAPPED_COMMONJS;
  3714. const exportBlock = isEsModule
  3715. ? ''
  3716. : rewriteExportsAndGetExportsBlock(
  3717. magicString,
  3718. moduleName,
  3719. exportsName,
  3720. exportedExportsName,
  3721. shouldWrap,
  3722. moduleExportsAssignments,
  3723. firstTopLevelModuleExportsAssignment,
  3724. exportsAssignmentsByName,
  3725. topLevelAssignments,
  3726. topLevelDefineCompiledEsmExpressions,
  3727. deconflictedExportNames,
  3728. code,
  3729. helpersName,
  3730. exportMode,
  3731. defaultIsModuleExports,
  3732. usesRequireWrapper,
  3733. requireName
  3734. );
  3735. if (shouldWrap) {
  3736. wrapCode(magicString, uses, moduleName, exportsName, indentExclusionRanges);
  3737. }
  3738. if (usesRequireWrapper) {
  3739. magicString.trim().indent('\t', {
  3740. exclude: indentExclusionRanges
  3741. });
  3742. const exported = exportMode === 'module' ? `${moduleName}.exports` : exportsName;
  3743. magicString.prepend(
  3744. `var ${isRequiredName};
  3745. function ${requireName} () {
  3746. \tif (${isRequiredName}) return ${exported};
  3747. \t${isRequiredName} = 1;
  3748. `
  3749. ).append(`
  3750. \treturn ${exported};
  3751. }`);
  3752. if (exportMode === 'replace') {
  3753. magicString.prepend(`var ${exportsName};\n`);
  3754. }
  3755. }
  3756. magicString
  3757. .trim()
  3758. .prepend(shebang + leadingComment + importBlock)
  3759. .append(exportBlock);
  3760. return {
  3761. code: magicString.toString(),
  3762. map: sourceMap ? magicString.generateMap() : null,
  3763. syntheticNamedExports: isEsModule || usesRequireWrapper ? false : '__moduleExports',
  3764. meta: { commonjs: { ...commonjsMeta, shebang } }
  3765. };
  3766. }
  3767. const PLUGIN_NAME = 'commonjs';
  3768. function commonjs(options = {}) {
  3769. const {
  3770. ignoreGlobal,
  3771. ignoreDynamicRequires,
  3772. requireReturnsDefault: requireReturnsDefaultOption,
  3773. defaultIsModuleExports: defaultIsModuleExportsOption,
  3774. esmExternals
  3775. } = options;
  3776. const extensions = options.extensions || ['.js'];
  3777. const filter = createFilter$2(options.include, options.exclude);
  3778. const isPossibleCjsId = (id) => {
  3779. const extName = extname(id);
  3780. return extName === '.cjs' || (extensions.includes(extName) && filter(id));
  3781. };
  3782. const { strictRequiresFilter, detectCyclesAndConditional } = getStrictRequiresFilter(options);
  3783. const getRequireReturnsDefault =
  3784. typeof requireReturnsDefaultOption === 'function'
  3785. ? requireReturnsDefaultOption
  3786. : () => requireReturnsDefaultOption;
  3787. let esmExternalIds;
  3788. const isEsmExternal =
  3789. typeof esmExternals === 'function'
  3790. ? esmExternals
  3791. : Array.isArray(esmExternals)
  3792. ? ((esmExternalIds = new Set(esmExternals)), (id) => esmExternalIds.has(id))
  3793. : () => esmExternals;
  3794. const getDefaultIsModuleExports =
  3795. typeof defaultIsModuleExportsOption === 'function'
  3796. ? defaultIsModuleExportsOption
  3797. : () =>
  3798. typeof defaultIsModuleExportsOption === 'boolean' ? defaultIsModuleExportsOption : 'auto';
  3799. const dynamicRequireRoot =
  3800. typeof options.dynamicRequireRoot === 'string'
  3801. ? resolve$3(options.dynamicRequireRoot)
  3802. : process.cwd();
  3803. const { commonDir, dynamicRequireModules } = getDynamicRequireModules(
  3804. options.dynamicRequireTargets,
  3805. dynamicRequireRoot
  3806. );
  3807. const isDynamicRequireModulesEnabled = dynamicRequireModules.size > 0;
  3808. const ignoreRequire =
  3809. typeof options.ignore === 'function'
  3810. ? options.ignore
  3811. : Array.isArray(options.ignore)
  3812. ? (id) => options.ignore.includes(id)
  3813. : () => false;
  3814. const getIgnoreTryCatchRequireStatementMode = (id) => {
  3815. const mode =
  3816. typeof options.ignoreTryCatch === 'function'
  3817. ? options.ignoreTryCatch(id)
  3818. : Array.isArray(options.ignoreTryCatch)
  3819. ? options.ignoreTryCatch.includes(id)
  3820. : typeof options.ignoreTryCatch !== 'undefined'
  3821. ? options.ignoreTryCatch
  3822. : true;
  3823. return {
  3824. canConvertRequire: mode !== 'remove' && mode !== true,
  3825. shouldRemoveRequire: mode === 'remove'
  3826. };
  3827. };
  3828. const { currentlyResolving, resolveId } = getResolveId(extensions, isPossibleCjsId);
  3829. const sourceMap = options.sourceMap !== false;
  3830. // Initialized in buildStart
  3831. let requireResolver;
  3832. function transformAndCheckExports(code, id) {
  3833. const normalizedId = normalizePathSlashes(id);
  3834. const { isEsModule, hasDefaultExport, hasNamedExports, ast } = analyzeTopLevelStatements(
  3835. this.parse,
  3836. code,
  3837. id
  3838. );
  3839. const commonjsMeta = this.getModuleInfo(id).meta.commonjs || {};
  3840. if (hasDefaultExport) {
  3841. commonjsMeta.hasDefaultExport = true;
  3842. }
  3843. if (hasNamedExports) {
  3844. commonjsMeta.hasNamedExports = true;
  3845. }
  3846. if (
  3847. !dynamicRequireModules.has(normalizedId) &&
  3848. (!(hasCjsKeywords(code, ignoreGlobal) || requireResolver.isRequiredId(id)) ||
  3849. (isEsModule && !options.transformMixedEsModules))
  3850. ) {
  3851. commonjsMeta.isCommonJS = false;
  3852. return { meta: { commonjs: commonjsMeta } };
  3853. }
  3854. const needsRequireWrapper =
  3855. !isEsModule && (dynamicRequireModules.has(normalizedId) || strictRequiresFilter(id));
  3856. const checkDynamicRequire = (position) => {
  3857. const normalizedDynamicRequireRoot = normalizePathSlashes(dynamicRequireRoot);
  3858. if (normalizedId.indexOf(normalizedDynamicRequireRoot) !== 0) {
  3859. this.error(
  3860. {
  3861. code: 'DYNAMIC_REQUIRE_OUTSIDE_ROOT',
  3862. normalizedId,
  3863. normalizedDynamicRequireRoot,
  3864. message: `"${normalizedId}" contains dynamic require statements but it is not within the current dynamicRequireRoot "${normalizedDynamicRequireRoot}". You should set dynamicRequireRoot to "${dirname$1(
  3865. normalizedId
  3866. )}" or one of its parent directories.`
  3867. },
  3868. position
  3869. );
  3870. }
  3871. };
  3872. return transformCommonjs(
  3873. this.parse,
  3874. code,
  3875. id,
  3876. isEsModule,
  3877. ignoreGlobal || isEsModule,
  3878. ignoreRequire,
  3879. ignoreDynamicRequires && !isDynamicRequireModulesEnabled,
  3880. getIgnoreTryCatchRequireStatementMode,
  3881. sourceMap,
  3882. isDynamicRequireModulesEnabled,
  3883. dynamicRequireModules,
  3884. commonDir,
  3885. ast,
  3886. getDefaultIsModuleExports(id),
  3887. needsRequireWrapper,
  3888. requireResolver.resolveRequireSourcesAndUpdateMeta(this),
  3889. requireResolver.isRequiredId(id),
  3890. checkDynamicRequire,
  3891. commonjsMeta
  3892. );
  3893. }
  3894. return {
  3895. name: PLUGIN_NAME,
  3896. version: version$2,
  3897. options(rawOptions) {
  3898. // We inject the resolver in the beginning so that "catch-all-resolver" like node-resolver
  3899. // do not prevent our plugin from resolving entry points ot proxies.
  3900. const plugins = Array.isArray(rawOptions.plugins)
  3901. ? [...rawOptions.plugins]
  3902. : rawOptions.plugins
  3903. ? [rawOptions.plugins]
  3904. : [];
  3905. plugins.unshift({
  3906. name: 'commonjs--resolver',
  3907. resolveId
  3908. });
  3909. return { ...rawOptions, plugins };
  3910. },
  3911. buildStart({ plugins }) {
  3912. validateVersion(this.meta.rollupVersion, peerDependencies.rollup, 'rollup');
  3913. const nodeResolve = plugins.find(({ name }) => name === 'node-resolve');
  3914. if (nodeResolve) {
  3915. validateVersion(nodeResolve.version, '^13.0.6', '@rollup/plugin-node-resolve');
  3916. }
  3917. if (options.namedExports != null) {
  3918. this.warn(
  3919. 'The namedExports option from "@rollup/plugin-commonjs" is deprecated. Named exports are now handled automatically.'
  3920. );
  3921. }
  3922. requireResolver = getRequireResolver(
  3923. extensions,
  3924. detectCyclesAndConditional,
  3925. currentlyResolving
  3926. );
  3927. },
  3928. buildEnd() {
  3929. if (options.strictRequires === 'debug') {
  3930. const wrappedIds = requireResolver.getWrappedIds();
  3931. if (wrappedIds.length) {
  3932. this.warn({
  3933. code: 'WRAPPED_IDS',
  3934. ids: wrappedIds,
  3935. message: `The commonjs plugin automatically wrapped the following files:\n[\n${wrappedIds
  3936. .map((id) => `\t${JSON.stringify(relative$1(process.cwd(), id))}`)
  3937. .join(',\n')}\n]`
  3938. });
  3939. } else {
  3940. this.warn({
  3941. code: 'WRAPPED_IDS',
  3942. ids: wrappedIds,
  3943. message: 'The commonjs plugin did not wrap any files.'
  3944. });
  3945. }
  3946. }
  3947. },
  3948. async load(id) {
  3949. if (id === HELPERS_ID) {
  3950. return getHelpersModule();
  3951. }
  3952. if (isWrappedId(id, MODULE_SUFFIX)) {
  3953. const name = getName(unwrapId(id, MODULE_SUFFIX));
  3954. return {
  3955. code: `var ${name} = {exports: {}}; export {${name} as __module}`,
  3956. meta: { commonjs: { isCommonJS: false } }
  3957. };
  3958. }
  3959. if (isWrappedId(id, EXPORTS_SUFFIX)) {
  3960. const name = getName(unwrapId(id, EXPORTS_SUFFIX));
  3961. return {
  3962. code: `var ${name} = {}; export {${name} as __exports}`,
  3963. meta: { commonjs: { isCommonJS: false } }
  3964. };
  3965. }
  3966. if (isWrappedId(id, EXTERNAL_SUFFIX)) {
  3967. const actualId = unwrapId(id, EXTERNAL_SUFFIX);
  3968. return getUnknownRequireProxy(
  3969. actualId,
  3970. isEsmExternal(actualId) ? getRequireReturnsDefault(actualId) : true
  3971. );
  3972. }
  3973. // entry suffix is just appended to not mess up relative external resolution
  3974. if (id.endsWith(ENTRY_SUFFIX)) {
  3975. const acutalId = id.slice(0, -ENTRY_SUFFIX.length);
  3976. const {
  3977. meta: { commonjs: commonjsMeta }
  3978. } = this.getModuleInfo(acutalId);
  3979. const shebang = commonjsMeta?.shebang ?? '';
  3980. return getEntryProxy(
  3981. acutalId,
  3982. getDefaultIsModuleExports(acutalId),
  3983. this.getModuleInfo,
  3984. shebang
  3985. );
  3986. }
  3987. if (isWrappedId(id, ES_IMPORT_SUFFIX)) {
  3988. const actualId = unwrapId(id, ES_IMPORT_SUFFIX);
  3989. return getEsImportProxy(
  3990. actualId,
  3991. getDefaultIsModuleExports(actualId),
  3992. (await this.load({ id: actualId })).moduleSideEffects
  3993. );
  3994. }
  3995. if (id === DYNAMIC_MODULES_ID) {
  3996. return getDynamicModuleRegistry(
  3997. isDynamicRequireModulesEnabled,
  3998. dynamicRequireModules,
  3999. commonDir,
  4000. ignoreDynamicRequires
  4001. );
  4002. }
  4003. if (isWrappedId(id, PROXY_SUFFIX)) {
  4004. const actualId = unwrapId(id, PROXY_SUFFIX);
  4005. return getStaticRequireProxy(actualId, getRequireReturnsDefault(actualId), this.load);
  4006. }
  4007. return null;
  4008. },
  4009. shouldTransformCachedModule(...args) {
  4010. return requireResolver.shouldTransformCachedModule.call(this, ...args);
  4011. },
  4012. transform(code, id) {
  4013. if (!isPossibleCjsId(id)) return null;
  4014. try {
  4015. return transformAndCheckExports.call(this, code, id);
  4016. } catch (err) {
  4017. return this.error(err, err.pos);
  4018. }
  4019. }
  4020. };
  4021. }
  4022. function perEnvironmentState(initial) {
  4023. const stateMap = /* @__PURE__ */ new WeakMap();
  4024. return function(context) {
  4025. const { environment } = context;
  4026. let state = stateMap.get(environment);
  4027. if (!state) {
  4028. state = initial(environment);
  4029. stateMap.set(environment, state);
  4030. }
  4031. return state;
  4032. };
  4033. }
  4034. // Matches the scheme of a URL, eg "http://"
  4035. const schemeRegex = /^[\w+.-]+:\/\//;
  4036. /**
  4037. * Matches the parts of a URL:
  4038. * 1. Scheme, including ":", guaranteed.
  4039. * 2. User/password, including "@", optional.
  4040. * 3. Host, guaranteed.
  4041. * 4. Port, including ":", optional.
  4042. * 5. Path, including "/", optional.
  4043. * 6. Query, including "?", optional.
  4044. * 7. Hash, including "#", optional.
  4045. */
  4046. const urlRegex = /^([\w+.-]+:)\/\/([^@/#?]*@)?([^:/#?]*)(:\d+)?(\/[^#?]*)?(\?[^#]*)?(#.*)?/;
  4047. /**
  4048. * File URLs are weird. They dont' need the regular `//` in the scheme, they may or may not start
  4049. * with a leading `/`, they can have a domain (but only if they don't start with a Windows drive).
  4050. *
  4051. * 1. Host, optional.
  4052. * 2. Path, which may include "/", guaranteed.
  4053. * 3. Query, including "?", optional.
  4054. * 4. Hash, including "#", optional.
  4055. */
  4056. const fileRegex = /^file:(?:\/\/((?![a-z]:)[^/#?]*)?)?(\/?[^#?]*)(\?[^#]*)?(#.*)?/i;
  4057. function isAbsoluteUrl(input) {
  4058. return schemeRegex.test(input);
  4059. }
  4060. function isSchemeRelativeUrl(input) {
  4061. return input.startsWith('//');
  4062. }
  4063. function isAbsolutePath(input) {
  4064. return input.startsWith('/');
  4065. }
  4066. function isFileUrl(input) {
  4067. return input.startsWith('file:');
  4068. }
  4069. function isRelative(input) {
  4070. return /^[.?#]/.test(input);
  4071. }
  4072. function parseAbsoluteUrl(input) {
  4073. const match = urlRegex.exec(input);
  4074. return makeUrl(match[1], match[2] || '', match[3], match[4] || '', match[5] || '/', match[6] || '', match[7] || '');
  4075. }
  4076. function parseFileUrl(input) {
  4077. const match = fileRegex.exec(input);
  4078. const path = match[2];
  4079. return makeUrl('file:', '', match[1] || '', '', isAbsolutePath(path) ? path : '/' + path, match[3] || '', match[4] || '');
  4080. }
  4081. function makeUrl(scheme, user, host, port, path, query, hash) {
  4082. return {
  4083. scheme,
  4084. user,
  4085. host,
  4086. port,
  4087. path,
  4088. query,
  4089. hash,
  4090. type: 7 /* Absolute */,
  4091. };
  4092. }
  4093. function parseUrl$3(input) {
  4094. if (isSchemeRelativeUrl(input)) {
  4095. const url = parseAbsoluteUrl('http:' + input);
  4096. url.scheme = '';
  4097. url.type = 6 /* SchemeRelative */;
  4098. return url;
  4099. }
  4100. if (isAbsolutePath(input)) {
  4101. const url = parseAbsoluteUrl('http://foo.com' + input);
  4102. url.scheme = '';
  4103. url.host = '';
  4104. url.type = 5 /* AbsolutePath */;
  4105. return url;
  4106. }
  4107. if (isFileUrl(input))
  4108. return parseFileUrl(input);
  4109. if (isAbsoluteUrl(input))
  4110. return parseAbsoluteUrl(input);
  4111. const url = parseAbsoluteUrl('http://foo.com/' + input);
  4112. url.scheme = '';
  4113. url.host = '';
  4114. url.type = input
  4115. ? input.startsWith('?')
  4116. ? 3 /* Query */
  4117. : input.startsWith('#')
  4118. ? 2 /* Hash */
  4119. : 4 /* RelativePath */
  4120. : 1 /* Empty */;
  4121. return url;
  4122. }
  4123. function stripPathFilename(path) {
  4124. // If a path ends with a parent directory "..", then it's a relative path with excess parent
  4125. // paths. It's not a file, so we can't strip it.
  4126. if (path.endsWith('/..'))
  4127. return path;
  4128. const index = path.lastIndexOf('/');
  4129. return path.slice(0, index + 1);
  4130. }
  4131. function mergePaths(url, base) {
  4132. normalizePath$4(base, base.type);
  4133. // If the path is just a "/", then it was an empty path to begin with (remember, we're a relative
  4134. // path).
  4135. if (url.path === '/') {
  4136. url.path = base.path;
  4137. }
  4138. else {
  4139. // Resolution happens relative to the base path's directory, not the file.
  4140. url.path = stripPathFilename(base.path) + url.path;
  4141. }
  4142. }
  4143. /**
  4144. * The path can have empty directories "//", unneeded parents "foo/..", or current directory
  4145. * "foo/.". We need to normalize to a standard representation.
  4146. */
  4147. function normalizePath$4(url, type) {
  4148. const rel = type <= 4 /* RelativePath */;
  4149. const pieces = url.path.split('/');
  4150. // We need to preserve the first piece always, so that we output a leading slash. The item at
  4151. // pieces[0] is an empty string.
  4152. let pointer = 1;
  4153. // Positive is the number of real directories we've output, used for popping a parent directory.
  4154. // Eg, "foo/bar/.." will have a positive 2, and we can decrement to be left with just "foo".
  4155. let positive = 0;
  4156. // We need to keep a trailing slash if we encounter an empty directory (eg, splitting "foo/" will
  4157. // generate `["foo", ""]` pieces). And, if we pop a parent directory. But once we encounter a
  4158. // real directory, we won't need to append, unless the other conditions happen again.
  4159. let addTrailingSlash = false;
  4160. for (let i = 1; i < pieces.length; i++) {
  4161. const piece = pieces[i];
  4162. // An empty directory, could be a trailing slash, or just a double "//" in the path.
  4163. if (!piece) {
  4164. addTrailingSlash = true;
  4165. continue;
  4166. }
  4167. // If we encounter a real directory, then we don't need to append anymore.
  4168. addTrailingSlash = false;
  4169. // A current directory, which we can always drop.
  4170. if (piece === '.')
  4171. continue;
  4172. // A parent directory, we need to see if there are any real directories we can pop. Else, we
  4173. // have an excess of parents, and we'll need to keep the "..".
  4174. if (piece === '..') {
  4175. if (positive) {
  4176. addTrailingSlash = true;
  4177. positive--;
  4178. pointer--;
  4179. }
  4180. else if (rel) {
  4181. // If we're in a relativePath, then we need to keep the excess parents. Else, in an absolute
  4182. // URL, protocol relative URL, or an absolute path, we don't need to keep excess.
  4183. pieces[pointer++] = piece;
  4184. }
  4185. continue;
  4186. }
  4187. // We've encountered a real directory. Move it to the next insertion pointer, which accounts for
  4188. // any popped or dropped directories.
  4189. pieces[pointer++] = piece;
  4190. positive++;
  4191. }
  4192. let path = '';
  4193. for (let i = 1; i < pointer; i++) {
  4194. path += '/' + pieces[i];
  4195. }
  4196. if (!path || (addTrailingSlash && !path.endsWith('/..'))) {
  4197. path += '/';
  4198. }
  4199. url.path = path;
  4200. }
  4201. /**
  4202. * Attempts to resolve `input` URL/path relative to `base`.
  4203. */
  4204. function resolve$2(input, base) {
  4205. if (!input && !base)
  4206. return '';
  4207. const url = parseUrl$3(input);
  4208. let inputType = url.type;
  4209. if (base && inputType !== 7 /* Absolute */) {
  4210. const baseUrl = parseUrl$3(base);
  4211. const baseType = baseUrl.type;
  4212. switch (inputType) {
  4213. case 1 /* Empty */:
  4214. url.hash = baseUrl.hash;
  4215. // fall through
  4216. case 2 /* Hash */:
  4217. url.query = baseUrl.query;
  4218. // fall through
  4219. case 3 /* Query */:
  4220. case 4 /* RelativePath */:
  4221. mergePaths(url, baseUrl);
  4222. // fall through
  4223. case 5 /* AbsolutePath */:
  4224. // The host, user, and port are joined, you can't copy one without the others.
  4225. url.user = baseUrl.user;
  4226. url.host = baseUrl.host;
  4227. url.port = baseUrl.port;
  4228. // fall through
  4229. case 6 /* SchemeRelative */:
  4230. // The input doesn't have a schema at least, so we need to copy at least that over.
  4231. url.scheme = baseUrl.scheme;
  4232. }
  4233. if (baseType > inputType)
  4234. inputType = baseType;
  4235. }
  4236. normalizePath$4(url, inputType);
  4237. const queryHash = url.query + url.hash;
  4238. switch (inputType) {
  4239. // This is impossible, because of the empty checks at the start of the function.
  4240. // case UrlType.Empty:
  4241. case 2 /* Hash */:
  4242. case 3 /* Query */:
  4243. return queryHash;
  4244. case 4 /* RelativePath */: {
  4245. // The first char is always a "/", and we need it to be relative.
  4246. const path = url.path.slice(1);
  4247. if (!path)
  4248. return queryHash || '.';
  4249. if (isRelative(base || input) && !isRelative(path)) {
  4250. // If base started with a leading ".", or there is no base and input started with a ".",
  4251. // then we need to ensure that the relative path starts with a ".". We don't know if
  4252. // relative starts with a "..", though, so check before prepending.
  4253. return './' + path + queryHash;
  4254. }
  4255. return path + queryHash;
  4256. }
  4257. case 5 /* AbsolutePath */:
  4258. return url.path + queryHash;
  4259. default:
  4260. return url.scheme + '//' + url.user + url.host + url.port + url.path + queryHash;
  4261. }
  4262. }
  4263. function resolve$1(input, base) {
  4264. // The base is always treated as a directory, if it's not empty.
  4265. // https://github.com/mozilla/source-map/blob/8cb3ee57/lib/util.js#L327
  4266. // https://github.com/chromium/chromium/blob/da4adbb3/third_party/blink/renderer/devtools/front_end/sdk/SourceMap.js#L400-L401
  4267. if (base && !base.endsWith('/'))
  4268. base += '/';
  4269. return resolve$2(input, base);
  4270. }
  4271. /**
  4272. * Removes everything after the last "/", but leaves the slash.
  4273. */
  4274. function stripFilename(path) {
  4275. if (!path)
  4276. return '';
  4277. const index = path.lastIndexOf('/');
  4278. return path.slice(0, index + 1);
  4279. }
  4280. const COLUMN$1 = 0;
  4281. const SOURCES_INDEX$1 = 1;
  4282. const SOURCE_LINE$1 = 2;
  4283. const SOURCE_COLUMN$1 = 3;
  4284. const NAMES_INDEX$1 = 4;
  4285. function maybeSort(mappings, owned) {
  4286. const unsortedIndex = nextUnsortedSegmentLine(mappings, 0);
  4287. if (unsortedIndex === mappings.length)
  4288. return mappings;
  4289. // If we own the array (meaning we parsed it from JSON), then we're free to directly mutate it. If
  4290. // not, we do not want to modify the consumer's input array.
  4291. if (!owned)
  4292. mappings = mappings.slice();
  4293. for (let i = unsortedIndex; i < mappings.length; i = nextUnsortedSegmentLine(mappings, i + 1)) {
  4294. mappings[i] = sortSegments(mappings[i], owned);
  4295. }
  4296. return mappings;
  4297. }
  4298. function nextUnsortedSegmentLine(mappings, start) {
  4299. for (let i = start; i < mappings.length; i++) {
  4300. if (!isSorted(mappings[i]))
  4301. return i;
  4302. }
  4303. return mappings.length;
  4304. }
  4305. function isSorted(line) {
  4306. for (let j = 1; j < line.length; j++) {
  4307. if (line[j][COLUMN$1] < line[j - 1][COLUMN$1]) {
  4308. return false;
  4309. }
  4310. }
  4311. return true;
  4312. }
  4313. function sortSegments(line, owned) {
  4314. if (!owned)
  4315. line = line.slice();
  4316. return line.sort(sortComparator);
  4317. }
  4318. function sortComparator(a, b) {
  4319. return a[COLUMN$1] - b[COLUMN$1];
  4320. }
  4321. let found = false;
  4322. /**
  4323. * A binary search implementation that returns the index if a match is found.
  4324. * If no match is found, then the left-index (the index associated with the item that comes just
  4325. * before the desired index) is returned. To maintain proper sort order, a splice would happen at
  4326. * the next index:
  4327. *
  4328. * ```js
  4329. * const array = [1, 3];
  4330. * const needle = 2;
  4331. * const index = binarySearch(array, needle, (item, needle) => item - needle);
  4332. *
  4333. * assert.equal(index, 0);
  4334. * array.splice(index + 1, 0, needle);
  4335. * assert.deepEqual(array, [1, 2, 3]);
  4336. * ```
  4337. */
  4338. function binarySearch(haystack, needle, low, high) {
  4339. while (low <= high) {
  4340. const mid = low + ((high - low) >> 1);
  4341. const cmp = haystack[mid][COLUMN$1] - needle;
  4342. if (cmp === 0) {
  4343. found = true;
  4344. return mid;
  4345. }
  4346. if (cmp < 0) {
  4347. low = mid + 1;
  4348. }
  4349. else {
  4350. high = mid - 1;
  4351. }
  4352. }
  4353. found = false;
  4354. return low - 1;
  4355. }
  4356. function upperBound(haystack, needle, index) {
  4357. for (let i = index + 1; i < haystack.length; index = i++) {
  4358. if (haystack[i][COLUMN$1] !== needle)
  4359. break;
  4360. }
  4361. return index;
  4362. }
  4363. function lowerBound(haystack, needle, index) {
  4364. for (let i = index - 1; i >= 0; index = i--) {
  4365. if (haystack[i][COLUMN$1] !== needle)
  4366. break;
  4367. }
  4368. return index;
  4369. }
  4370. function memoizedState() {
  4371. return {
  4372. lastKey: -1,
  4373. lastNeedle: -1,
  4374. lastIndex: -1,
  4375. };
  4376. }
  4377. /**
  4378. * This overly complicated beast is just to record the last tested line/column and the resulting
  4379. * index, allowing us to skip a few tests if mappings are monotonically increasing.
  4380. */
  4381. function memoizedBinarySearch(haystack, needle, state, key) {
  4382. const { lastKey, lastNeedle, lastIndex } = state;
  4383. let low = 0;
  4384. let high = haystack.length - 1;
  4385. if (key === lastKey) {
  4386. if (needle === lastNeedle) {
  4387. found = lastIndex !== -1 && haystack[lastIndex][COLUMN$1] === needle;
  4388. return lastIndex;
  4389. }
  4390. if (needle >= lastNeedle) {
  4391. // lastIndex may be -1 if the previous needle was not found.
  4392. low = lastIndex === -1 ? 0 : lastIndex;
  4393. }
  4394. else {
  4395. high = lastIndex;
  4396. }
  4397. }
  4398. state.lastKey = key;
  4399. state.lastNeedle = needle;
  4400. return (state.lastIndex = binarySearch(haystack, needle, low, high));
  4401. }
  4402. const LINE_GTR_ZERO = '`line` must be greater than 0 (lines start at line 1)';
  4403. const COL_GTR_EQ_ZERO = '`column` must be greater than or equal to 0 (columns start at column 0)';
  4404. const LEAST_UPPER_BOUND = -1;
  4405. const GREATEST_LOWER_BOUND = 1;
  4406. class TraceMap {
  4407. constructor(map, mapUrl) {
  4408. const isString = typeof map === 'string';
  4409. if (!isString && map._decodedMemo)
  4410. return map;
  4411. const parsed = (isString ? JSON.parse(map) : map);
  4412. const { version, file, names, sourceRoot, sources, sourcesContent } = parsed;
  4413. this.version = version;
  4414. this.file = file;
  4415. this.names = names || [];
  4416. this.sourceRoot = sourceRoot;
  4417. this.sources = sources;
  4418. this.sourcesContent = sourcesContent;
  4419. this.ignoreList = parsed.ignoreList || parsed.x_google_ignoreList || undefined;
  4420. const from = resolve$1(sourceRoot || '', stripFilename(mapUrl));
  4421. this.resolvedSources = sources.map((s) => resolve$1(s || '', from));
  4422. const { mappings } = parsed;
  4423. if (typeof mappings === 'string') {
  4424. this._encoded = mappings;
  4425. this._decoded = undefined;
  4426. }
  4427. else {
  4428. this._encoded = undefined;
  4429. this._decoded = maybeSort(mappings, isString);
  4430. }
  4431. this._decodedMemo = memoizedState();
  4432. this._bySources = undefined;
  4433. this._bySourceMemos = undefined;
  4434. }
  4435. }
  4436. /**
  4437. * Typescript doesn't allow friend access to private fields, so this just casts the map into a type
  4438. * with public access modifiers.
  4439. */
  4440. function cast$2(map) {
  4441. return map;
  4442. }
  4443. /**
  4444. * Returns the encoded (VLQ string) form of the SourceMap's mappings field.
  4445. */
  4446. function encodedMappings(map) {
  4447. var _a;
  4448. var _b;
  4449. return ((_a = (_b = cast$2(map))._encoded) !== null && _a !== void 0 ? _a : (_b._encoded = encode$1(cast$2(map)._decoded)));
  4450. }
  4451. /**
  4452. * Returns the decoded (array of lines of segments) form of the SourceMap's mappings field.
  4453. */
  4454. function decodedMappings(map) {
  4455. var _a;
  4456. return ((_a = cast$2(map))._decoded || (_a._decoded = decode(cast$2(map)._encoded)));
  4457. }
  4458. /**
  4459. * A low-level API to find the segment associated with a generated line/column (think, from a
  4460. * stack trace). Line and column here are 0-based, unlike `originalPositionFor`.
  4461. */
  4462. function traceSegment(map, line, column) {
  4463. const decoded = decodedMappings(map);
  4464. // It's common for parent source maps to have pointers to lines that have no
  4465. // mapping (like a "//# sourceMappingURL=") at the end of the child file.
  4466. if (line >= decoded.length)
  4467. return null;
  4468. const segments = decoded[line];
  4469. const index = traceSegmentInternal(segments, cast$2(map)._decodedMemo, line, column, GREATEST_LOWER_BOUND);
  4470. return index === -1 ? null : segments[index];
  4471. }
  4472. /**
  4473. * A higher-level API to find the source/line/column associated with a generated line/column
  4474. * (think, from a stack trace). Line is 1-based, but column is 0-based, due to legacy behavior in
  4475. * `source-map` library.
  4476. */
  4477. function originalPositionFor$1(map, needle) {
  4478. let { line, column, bias } = needle;
  4479. line--;
  4480. if (line < 0)
  4481. throw new Error(LINE_GTR_ZERO);
  4482. if (column < 0)
  4483. throw new Error(COL_GTR_EQ_ZERO);
  4484. const decoded = decodedMappings(map);
  4485. // It's common for parent source maps to have pointers to lines that have no
  4486. // mapping (like a "//# sourceMappingURL=") at the end of the child file.
  4487. if (line >= decoded.length)
  4488. return OMapping(null, null, null, null);
  4489. const segments = decoded[line];
  4490. const index = traceSegmentInternal(segments, cast$2(map)._decodedMemo, line, column, bias || GREATEST_LOWER_BOUND);
  4491. if (index === -1)
  4492. return OMapping(null, null, null, null);
  4493. const segment = segments[index];
  4494. if (segment.length === 1)
  4495. return OMapping(null, null, null, null);
  4496. const { names, resolvedSources } = map;
  4497. return OMapping(resolvedSources[segment[SOURCES_INDEX$1]], segment[SOURCE_LINE$1] + 1, segment[SOURCE_COLUMN$1], segment.length === 5 ? names[segment[NAMES_INDEX$1]] : null);
  4498. }
  4499. /**
  4500. * Returns a sourcemap object (with decoded mappings) suitable for passing to a library that expects
  4501. * a sourcemap, or to JSON.stringify.
  4502. */
  4503. function decodedMap(map) {
  4504. return clone(map, decodedMappings(map));
  4505. }
  4506. /**
  4507. * Returns a sourcemap object (with encoded mappings) suitable for passing to a library that expects
  4508. * a sourcemap, or to JSON.stringify.
  4509. */
  4510. function encodedMap(map) {
  4511. return clone(map, encodedMappings(map));
  4512. }
  4513. function clone(map, mappings) {
  4514. return {
  4515. version: map.version,
  4516. file: map.file,
  4517. names: map.names,
  4518. sourceRoot: map.sourceRoot,
  4519. sources: map.sources,
  4520. sourcesContent: map.sourcesContent,
  4521. mappings,
  4522. ignoreList: map.ignoreList || map.x_google_ignoreList,
  4523. };
  4524. }
  4525. function OMapping(source, line, column, name) {
  4526. return { source, line, column, name };
  4527. }
  4528. function traceSegmentInternal(segments, memo, line, column, bias) {
  4529. let index = memoizedBinarySearch(segments, column, memo, line);
  4530. if (found) {
  4531. index = (bias === LEAST_UPPER_BOUND ? upperBound : lowerBound)(segments, column, index);
  4532. }
  4533. else if (bias === LEAST_UPPER_BOUND)
  4534. index++;
  4535. if (index === -1 || index === segments.length)
  4536. return -1;
  4537. return index;
  4538. }
  4539. /**
  4540. * SetArray acts like a `Set` (allowing only one occurrence of a string `key`), but provides the
  4541. * index of the `key` in the backing array.
  4542. *
  4543. * This is designed to allow synchronizing a second array with the contents of the backing array,
  4544. * like how in a sourcemap `sourcesContent[i]` is the source content associated with `source[i]`,
  4545. * and there are never duplicates.
  4546. */
  4547. class SetArray {
  4548. constructor() {
  4549. this._indexes = { __proto__: null };
  4550. this.array = [];
  4551. }
  4552. }
  4553. /**
  4554. * Typescript doesn't allow friend access to private fields, so this just casts the set into a type
  4555. * with public access modifiers.
  4556. */
  4557. function cast$1(set) {
  4558. return set;
  4559. }
  4560. /**
  4561. * Gets the index associated with `key` in the backing array, if it is already present.
  4562. */
  4563. function get(setarr, key) {
  4564. return cast$1(setarr)._indexes[key];
  4565. }
  4566. /**
  4567. * Puts `key` into the backing array, if it is not already present. Returns
  4568. * the index of the `key` in the backing array.
  4569. */
  4570. function put(setarr, key) {
  4571. // The key may or may not be present. If it is present, it's a number.
  4572. const index = get(setarr, key);
  4573. if (index !== undefined)
  4574. return index;
  4575. const { array, _indexes: indexes } = cast$1(setarr);
  4576. const length = array.push(key);
  4577. return (indexes[key] = length - 1);
  4578. }
  4579. /**
  4580. * Removes the key, if it exists in the set.
  4581. */
  4582. function remove(setarr, key) {
  4583. const index = get(setarr, key);
  4584. if (index === undefined)
  4585. return;
  4586. const { array, _indexes: indexes } = cast$1(setarr);
  4587. for (let i = index + 1; i < array.length; i++) {
  4588. const k = array[i];
  4589. array[i - 1] = k;
  4590. indexes[k]--;
  4591. }
  4592. indexes[key] = undefined;
  4593. array.pop();
  4594. }
  4595. const COLUMN = 0;
  4596. const SOURCES_INDEX = 1;
  4597. const SOURCE_LINE = 2;
  4598. const SOURCE_COLUMN = 3;
  4599. const NAMES_INDEX = 4;
  4600. const NO_NAME = -1;
  4601. /**
  4602. * Provides the state to generate a sourcemap.
  4603. */
  4604. class GenMapping {
  4605. constructor({ file, sourceRoot } = {}) {
  4606. this._names = new SetArray();
  4607. this._sources = new SetArray();
  4608. this._sourcesContent = [];
  4609. this._mappings = [];
  4610. this.file = file;
  4611. this.sourceRoot = sourceRoot;
  4612. this._ignoreList = new SetArray();
  4613. }
  4614. }
  4615. /**
  4616. * Typescript doesn't allow friend access to private fields, so this just casts the map into a type
  4617. * with public access modifiers.
  4618. */
  4619. function cast(map) {
  4620. return map;
  4621. }
  4622. /**
  4623. * Same as `addSegment`, but will only add the segment if it generates useful information in the
  4624. * resulting map. This only works correctly if segments are added **in order**, meaning you should
  4625. * not add a segment with a lower generated line/column than one that came before.
  4626. */
  4627. const maybeAddSegment = (map, genLine, genColumn, source, sourceLine, sourceColumn, name, content) => {
  4628. return addSegmentInternal(true, map, genLine, genColumn, source, sourceLine, sourceColumn, name);
  4629. };
  4630. /**
  4631. * Adds/removes the content of the source file to the source map.
  4632. */
  4633. function setSourceContent(map, source, content) {
  4634. const { _sources: sources, _sourcesContent: sourcesContent } = cast(map);
  4635. const index = put(sources, source);
  4636. sourcesContent[index] = content;
  4637. }
  4638. function setIgnore(map, source, ignore = true) {
  4639. const { _sources: sources, _sourcesContent: sourcesContent, _ignoreList: ignoreList } = cast(map);
  4640. const index = put(sources, source);
  4641. if (index === sourcesContent.length)
  4642. sourcesContent[index] = null;
  4643. if (ignore)
  4644. put(ignoreList, index);
  4645. else
  4646. remove(ignoreList, index);
  4647. }
  4648. /**
  4649. * Returns a sourcemap object (with decoded mappings) suitable for passing to a library that expects
  4650. * a sourcemap, or to JSON.stringify.
  4651. */
  4652. function toDecodedMap(map) {
  4653. const { _mappings: mappings, _sources: sources, _sourcesContent: sourcesContent, _names: names, _ignoreList: ignoreList, } = cast(map);
  4654. removeEmptyFinalLines(mappings);
  4655. return {
  4656. version: 3,
  4657. file: map.file || undefined,
  4658. names: names.array,
  4659. sourceRoot: map.sourceRoot || undefined,
  4660. sources: sources.array,
  4661. sourcesContent,
  4662. mappings,
  4663. ignoreList: ignoreList.array,
  4664. };
  4665. }
  4666. /**
  4667. * Returns a sourcemap object (with encoded mappings) suitable for passing to a library that expects
  4668. * a sourcemap, or to JSON.stringify.
  4669. */
  4670. function toEncodedMap(map) {
  4671. const decoded = toDecodedMap(map);
  4672. return Object.assign(Object.assign({}, decoded), { mappings: encode$1(decoded.mappings) });
  4673. }
  4674. // This split declaration is only so that terser can elminiate the static initialization block.
  4675. function addSegmentInternal(skipable, map, genLine, genColumn, source, sourceLine, sourceColumn, name, content) {
  4676. const { _mappings: mappings, _sources: sources, _sourcesContent: sourcesContent, _names: names, } = cast(map);
  4677. const line = getLine(mappings, genLine);
  4678. const index = getColumnIndex(line, genColumn);
  4679. if (!source) {
  4680. if (skipSourceless(line, index))
  4681. return;
  4682. return insert(line, index, [genColumn]);
  4683. }
  4684. const sourcesIndex = put(sources, source);
  4685. const namesIndex = name ? put(names, name) : NO_NAME;
  4686. if (sourcesIndex === sourcesContent.length)
  4687. sourcesContent[sourcesIndex] = null;
  4688. if (skipSource(line, index, sourcesIndex, sourceLine, sourceColumn, namesIndex)) {
  4689. return;
  4690. }
  4691. return insert(line, index, name
  4692. ? [genColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex]
  4693. : [genColumn, sourcesIndex, sourceLine, sourceColumn]);
  4694. }
  4695. function getLine(mappings, index) {
  4696. for (let i = mappings.length; i <= index; i++) {
  4697. mappings[i] = [];
  4698. }
  4699. return mappings[index];
  4700. }
  4701. function getColumnIndex(line, genColumn) {
  4702. let index = line.length;
  4703. for (let i = index - 1; i >= 0; index = i--) {
  4704. const current = line[i];
  4705. if (genColumn >= current[COLUMN])
  4706. break;
  4707. }
  4708. return index;
  4709. }
  4710. function insert(array, index, value) {
  4711. for (let i = array.length; i > index; i--) {
  4712. array[i] = array[i - 1];
  4713. }
  4714. array[index] = value;
  4715. }
  4716. function removeEmptyFinalLines(mappings) {
  4717. const { length } = mappings;
  4718. let len = length;
  4719. for (let i = len - 1; i >= 0; len = i, i--) {
  4720. if (mappings[i].length > 0)
  4721. break;
  4722. }
  4723. if (len < length)
  4724. mappings.length = len;
  4725. }
  4726. function skipSourceless(line, index) {
  4727. // The start of a line is already sourceless, so adding a sourceless segment to the beginning
  4728. // doesn't generate any useful information.
  4729. if (index === 0)
  4730. return true;
  4731. const prev = line[index - 1];
  4732. // If the previous segment is also sourceless, then adding another sourceless segment doesn't
  4733. // genrate any new information. Else, this segment will end the source/named segment and point to
  4734. // a sourceless position, which is useful.
  4735. return prev.length === 1;
  4736. }
  4737. function skipSource(line, index, sourcesIndex, sourceLine, sourceColumn, namesIndex) {
  4738. // A source/named segment at the start of a line gives position at that genColumn
  4739. if (index === 0)
  4740. return false;
  4741. const prev = line[index - 1];
  4742. // If the previous segment is sourceless, then we're transitioning to a source.
  4743. if (prev.length === 1)
  4744. return false;
  4745. // If the previous segment maps to the exact same source position, then this segment doesn't
  4746. // provide any new position information.
  4747. return (sourcesIndex === prev[SOURCES_INDEX] &&
  4748. sourceLine === prev[SOURCE_LINE] &&
  4749. sourceColumn === prev[SOURCE_COLUMN] &&
  4750. namesIndex === (prev.length === 5 ? prev[NAMES_INDEX] : NO_NAME));
  4751. }
  4752. const SOURCELESS_MAPPING = /* #__PURE__ */ SegmentObject('', -1, -1, '', null, false);
  4753. const EMPTY_SOURCES = [];
  4754. function SegmentObject(source, line, column, name, content, ignore) {
  4755. return { source, line, column, name, content, ignore };
  4756. }
  4757. function Source(map, sources, source, content, ignore) {
  4758. return {
  4759. map,
  4760. sources,
  4761. source,
  4762. content,
  4763. ignore,
  4764. };
  4765. }
  4766. /**
  4767. * MapSource represents a single sourcemap, with the ability to trace mappings into its child nodes
  4768. * (which may themselves be SourceMapTrees).
  4769. */
  4770. function MapSource(map, sources) {
  4771. return Source(map, sources, '', null, false);
  4772. }
  4773. /**
  4774. * A "leaf" node in the sourcemap tree, representing an original, unmodified source file. Recursive
  4775. * segment tracing ends at the `OriginalSource`.
  4776. */
  4777. function OriginalSource(source, content, ignore) {
  4778. return Source(null, EMPTY_SOURCES, source, content, ignore);
  4779. }
  4780. /**
  4781. * traceMappings is only called on the root level SourceMapTree, and begins the process of
  4782. * resolving each mapping in terms of the original source files.
  4783. */
  4784. function traceMappings(tree) {
  4785. // TODO: Eventually support sourceRoot, which has to be removed because the sources are already
  4786. // fully resolved. We'll need to make sources relative to the sourceRoot before adding them.
  4787. const gen = new GenMapping({ file: tree.map.file });
  4788. const { sources: rootSources, map } = tree;
  4789. const rootNames = map.names;
  4790. const rootMappings = decodedMappings(map);
  4791. for (let i = 0; i < rootMappings.length; i++) {
  4792. const segments = rootMappings[i];
  4793. for (let j = 0; j < segments.length; j++) {
  4794. const segment = segments[j];
  4795. const genCol = segment[0];
  4796. let traced = SOURCELESS_MAPPING;
  4797. // 1-length segments only move the current generated column, there's no source information
  4798. // to gather from it.
  4799. if (segment.length !== 1) {
  4800. const source = rootSources[segment[1]];
  4801. traced = originalPositionFor(source, segment[2], segment[3], segment.length === 5 ? rootNames[segment[4]] : '');
  4802. // If the trace is invalid, then the trace ran into a sourcemap that doesn't contain a
  4803. // respective segment into an original source.
  4804. if (traced == null)
  4805. continue;
  4806. }
  4807. const { column, line, name, content, source, ignore } = traced;
  4808. maybeAddSegment(gen, i, genCol, source, line, column, name);
  4809. if (source && content != null)
  4810. setSourceContent(gen, source, content);
  4811. if (ignore)
  4812. setIgnore(gen, source, true);
  4813. }
  4814. }
  4815. return gen;
  4816. }
  4817. /**
  4818. * originalPositionFor is only called on children SourceMapTrees. It recurses down into its own
  4819. * child SourceMapTrees, until we find the original source map.
  4820. */
  4821. function originalPositionFor(source, line, column, name) {
  4822. if (!source.map) {
  4823. return SegmentObject(source.source, line, column, name, source.content, source.ignore);
  4824. }
  4825. const segment = traceSegment(source.map, line, column);
  4826. // If we couldn't find a segment, then this doesn't exist in the sourcemap.
  4827. if (segment == null)
  4828. return null;
  4829. // 1-length segments only move the current generated column, there's no source information
  4830. // to gather from it.
  4831. if (segment.length === 1)
  4832. return SOURCELESS_MAPPING;
  4833. return originalPositionFor(source.sources[segment[1]], segment[2], segment[3], segment.length === 5 ? source.map.names[segment[4]] : name);
  4834. }
  4835. function asArray(value) {
  4836. if (Array.isArray(value))
  4837. return value;
  4838. return [value];
  4839. }
  4840. /**
  4841. * Recursively builds a tree structure out of sourcemap files, with each node
  4842. * being either an `OriginalSource` "leaf" or a `SourceMapTree` composed of
  4843. * `OriginalSource`s and `SourceMapTree`s.
  4844. *
  4845. * Every sourcemap is composed of a collection of source files and mappings
  4846. * into locations of those source files. When we generate a `SourceMapTree` for
  4847. * the sourcemap, we attempt to load each source file's own sourcemap. If it
  4848. * does not have an associated sourcemap, it is considered an original,
  4849. * unmodified source file.
  4850. */
  4851. function buildSourceMapTree(input, loader) {
  4852. const maps = asArray(input).map((m) => new TraceMap(m, ''));
  4853. const map = maps.pop();
  4854. for (let i = 0; i < maps.length; i++) {
  4855. if (maps[i].sources.length > 1) {
  4856. throw new Error(`Transformation map ${i} must have exactly one source file.\n` +
  4857. 'Did you specify these with the most recent transformation maps first?');
  4858. }
  4859. }
  4860. let tree = build$2(map, loader, '', 0);
  4861. for (let i = maps.length - 1; i >= 0; i--) {
  4862. tree = MapSource(maps[i], [tree]);
  4863. }
  4864. return tree;
  4865. }
  4866. function build$2(map, loader, importer, importerDepth) {
  4867. const { resolvedSources, sourcesContent, ignoreList } = map;
  4868. const depth = importerDepth + 1;
  4869. const children = resolvedSources.map((sourceFile, i) => {
  4870. // The loading context gives the loader more information about why this file is being loaded
  4871. // (eg, from which importer). It also allows the loader to override the location of the loaded
  4872. // sourcemap/original source, or to override the content in the sourcesContent field if it's
  4873. // an unmodified source file.
  4874. const ctx = {
  4875. importer,
  4876. depth,
  4877. source: sourceFile || '',
  4878. content: undefined,
  4879. ignore: undefined,
  4880. };
  4881. // Use the provided loader callback to retrieve the file's sourcemap.
  4882. // TODO: We should eventually support async loading of sourcemap files.
  4883. const sourceMap = loader(ctx.source, ctx);
  4884. const { source} = ctx;
  4885. // If there is a sourcemap, then we need to recurse into it to load its source files.
  4886. if (sourceMap)
  4887. return build$2(new TraceMap(sourceMap, source), loader, source, depth);
  4888. // Else, it's an unmodified source file.
  4889. // The contents of this unmodified source file can be overridden via the loader context,
  4890. // allowing it to be explicitly null or a string. If it remains undefined, we fall back to
  4891. // the importing sourcemap's `sourcesContent` field.
  4892. const sourceContent = sourcesContent ? sourcesContent[i] : null;
  4893. const ignored = ignoreList ? ignoreList.includes(i) : false;
  4894. return OriginalSource(source, sourceContent, ignored);
  4895. });
  4896. return MapSource(map, children);
  4897. }
  4898. /**
  4899. * A SourceMap v3 compatible sourcemap, which only includes fields that were
  4900. * provided to it.
  4901. */
  4902. class SourceMap {
  4903. constructor(map, options) {
  4904. const out = options.decodedMappings ? toDecodedMap(map) : toEncodedMap(map);
  4905. this.version = out.version; // SourceMap spec says this should be first.
  4906. this.file = out.file;
  4907. this.mappings = out.mappings;
  4908. this.names = out.names;
  4909. this.ignoreList = out.ignoreList;
  4910. this.sourceRoot = out.sourceRoot;
  4911. this.sources = out.sources;
  4912. if (!options.excludeContent) {
  4913. this.sourcesContent = out.sourcesContent;
  4914. }
  4915. }
  4916. toString() {
  4917. return JSON.stringify(this);
  4918. }
  4919. }
  4920. /**
  4921. * Traces through all the mappings in the root sourcemap, through the sources
  4922. * (and their sourcemaps), all the way back to the original source location.
  4923. *
  4924. * `loader` will be called every time we encounter a source file. If it returns
  4925. * a sourcemap, we will recurse into that sourcemap to continue the trace. If
  4926. * it returns a falsey value, that source file is treated as an original,
  4927. * unmodified source file.
  4928. *
  4929. * Pass `excludeContent` to exclude any self-containing source file content
  4930. * from the output sourcemap.
  4931. *
  4932. * Pass `decodedMappings` to receive a SourceMap with decoded (instead of
  4933. * VLQ encoded) mappings.
  4934. */
  4935. function remapping(input, loader, options) {
  4936. const opts = { excludeContent: false, decodedMappings: false };
  4937. const tree = buildSourceMapTree(input, loader);
  4938. return new SourceMap(traceMappings(tree), opts);
  4939. }
  4940. var node$1 = {exports: {}};
  4941. /**
  4942. * Helpers.
  4943. */
  4944. var ms$1;
  4945. var hasRequiredMs;
  4946. function requireMs () {
  4947. if (hasRequiredMs) return ms$1;
  4948. hasRequiredMs = 1;
  4949. var s = 1000;
  4950. var m = s * 60;
  4951. var h = m * 60;
  4952. var d = h * 24;
  4953. var w = d * 7;
  4954. var y = d * 365.25;
  4955. /**
  4956. * Parse or format the given `val`.
  4957. *
  4958. * Options:
  4959. *
  4960. * - `long` verbose formatting [false]
  4961. *
  4962. * @param {String|Number} val
  4963. * @param {Object} [options]
  4964. * @throws {Error} throw an error if val is not a non-empty string or a number
  4965. * @return {String|Number}
  4966. * @api public
  4967. */
  4968. ms$1 = function (val, options) {
  4969. options = options || {};
  4970. var type = typeof val;
  4971. if (type === 'string' && val.length > 0) {
  4972. return parse(val);
  4973. } else if (type === 'number' && isFinite(val)) {
  4974. return options.long ? fmtLong(val) : fmtShort(val);
  4975. }
  4976. throw new Error(
  4977. 'val is not a non-empty string or a valid number. val=' +
  4978. JSON.stringify(val)
  4979. );
  4980. };
  4981. /**
  4982. * Parse the given `str` and return milliseconds.
  4983. *
  4984. * @param {String} str
  4985. * @return {Number}
  4986. * @api private
  4987. */
  4988. function parse(str) {
  4989. str = String(str);
  4990. if (str.length > 100) {
  4991. return;
  4992. }
  4993. var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(
  4994. str
  4995. );
  4996. if (!match) {
  4997. return;
  4998. }
  4999. var n = parseFloat(match[1]);
  5000. var type = (match[2] || 'ms').toLowerCase();
  5001. switch (type) {
  5002. case 'years':
  5003. case 'year':
  5004. case 'yrs':
  5005. case 'yr':
  5006. case 'y':
  5007. return n * y;
  5008. case 'weeks':
  5009. case 'week':
  5010. case 'w':
  5011. return n * w;
  5012. case 'days':
  5013. case 'day':
  5014. case 'd':
  5015. return n * d;
  5016. case 'hours':
  5017. case 'hour':
  5018. case 'hrs':
  5019. case 'hr':
  5020. case 'h':
  5021. return n * h;
  5022. case 'minutes':
  5023. case 'minute':
  5024. case 'mins':
  5025. case 'min':
  5026. case 'm':
  5027. return n * m;
  5028. case 'seconds':
  5029. case 'second':
  5030. case 'secs':
  5031. case 'sec':
  5032. case 's':
  5033. return n * s;
  5034. case 'milliseconds':
  5035. case 'millisecond':
  5036. case 'msecs':
  5037. case 'msec':
  5038. case 'ms':
  5039. return n;
  5040. default:
  5041. return undefined;
  5042. }
  5043. }
  5044. /**
  5045. * Short format for `ms`.
  5046. *
  5047. * @param {Number} ms
  5048. * @return {String}
  5049. * @api private
  5050. */
  5051. function fmtShort(ms) {
  5052. var msAbs = Math.abs(ms);
  5053. if (msAbs >= d) {
  5054. return Math.round(ms / d) + 'd';
  5055. }
  5056. if (msAbs >= h) {
  5057. return Math.round(ms / h) + 'h';
  5058. }
  5059. if (msAbs >= m) {
  5060. return Math.round(ms / m) + 'm';
  5061. }
  5062. if (msAbs >= s) {
  5063. return Math.round(ms / s) + 's';
  5064. }
  5065. return ms + 'ms';
  5066. }
  5067. /**
  5068. * Long format for `ms`.
  5069. *
  5070. * @param {Number} ms
  5071. * @return {String}
  5072. * @api private
  5073. */
  5074. function fmtLong(ms) {
  5075. var msAbs = Math.abs(ms);
  5076. if (msAbs >= d) {
  5077. return plural(ms, msAbs, d, 'day');
  5078. }
  5079. if (msAbs >= h) {
  5080. return plural(ms, msAbs, h, 'hour');
  5081. }
  5082. if (msAbs >= m) {
  5083. return plural(ms, msAbs, m, 'minute');
  5084. }
  5085. if (msAbs >= s) {
  5086. return plural(ms, msAbs, s, 'second');
  5087. }
  5088. return ms + ' ms';
  5089. }
  5090. /**
  5091. * Pluralization helper.
  5092. */
  5093. function plural(ms, msAbs, n, name) {
  5094. var isPlural = msAbs >= n * 1.5;
  5095. return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');
  5096. }
  5097. return ms$1;
  5098. }
  5099. var common$4;
  5100. var hasRequiredCommon;
  5101. function requireCommon () {
  5102. if (hasRequiredCommon) return common$4;
  5103. hasRequiredCommon = 1;
  5104. /**
  5105. * This is the common logic for both the Node.js and web browser
  5106. * implementations of `debug()`.
  5107. */
  5108. function setup(env) {
  5109. createDebug.debug = createDebug;
  5110. createDebug.default = createDebug;
  5111. createDebug.coerce = coerce;
  5112. createDebug.disable = disable;
  5113. createDebug.enable = enable;
  5114. createDebug.enabled = enabled;
  5115. createDebug.humanize = requireMs();
  5116. createDebug.destroy = destroy;
  5117. Object.keys(env).forEach(key => {
  5118. createDebug[key] = env[key];
  5119. });
  5120. /**
  5121. * The currently active debug mode names, and names to skip.
  5122. */
  5123. createDebug.names = [];
  5124. createDebug.skips = [];
  5125. /**
  5126. * Map of special "%n" handling functions, for the debug "format" argument.
  5127. *
  5128. * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
  5129. */
  5130. createDebug.formatters = {};
  5131. /**
  5132. * Selects a color for a debug namespace
  5133. * @param {String} namespace The namespace string for the debug instance to be colored
  5134. * @return {Number|String} An ANSI color code for the given namespace
  5135. * @api private
  5136. */
  5137. function selectColor(namespace) {
  5138. let hash = 0;
  5139. for (let i = 0; i < namespace.length; i++) {
  5140. hash = ((hash << 5) - hash) + namespace.charCodeAt(i);
  5141. hash |= 0; // Convert to 32bit integer
  5142. }
  5143. return createDebug.colors[Math.abs(hash) % createDebug.colors.length];
  5144. }
  5145. createDebug.selectColor = selectColor;
  5146. /**
  5147. * Create a debugger with the given `namespace`.
  5148. *
  5149. * @param {String} namespace
  5150. * @return {Function}
  5151. * @api public
  5152. */
  5153. function createDebug(namespace) {
  5154. let prevTime;
  5155. let enableOverride = null;
  5156. let namespacesCache;
  5157. let enabledCache;
  5158. function debug(...args) {
  5159. // Disabled?
  5160. if (!debug.enabled) {
  5161. return;
  5162. }
  5163. const self = debug;
  5164. // Set `diff` timestamp
  5165. const curr = Number(new Date());
  5166. const ms = curr - (prevTime || curr);
  5167. self.diff = ms;
  5168. self.prev = prevTime;
  5169. self.curr = curr;
  5170. prevTime = curr;
  5171. args[0] = createDebug.coerce(args[0]);
  5172. if (typeof args[0] !== 'string') {
  5173. // Anything else let's inspect with %O
  5174. args.unshift('%O');
  5175. }
  5176. // Apply any `formatters` transformations
  5177. let index = 0;
  5178. args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {
  5179. // If we encounter an escaped % then don't increase the array index
  5180. if (match === '%%') {
  5181. return '%';
  5182. }
  5183. index++;
  5184. const formatter = createDebug.formatters[format];
  5185. if (typeof formatter === 'function') {
  5186. const val = args[index];
  5187. match = formatter.call(self, val);
  5188. // Now we need to remove `args[index]` since it's inlined in the `format`
  5189. args.splice(index, 1);
  5190. index--;
  5191. }
  5192. return match;
  5193. });
  5194. // Apply env-specific formatting (colors, etc.)
  5195. createDebug.formatArgs.call(self, args);
  5196. const logFn = self.log || createDebug.log;
  5197. logFn.apply(self, args);
  5198. }
  5199. debug.namespace = namespace;
  5200. debug.useColors = createDebug.useColors();
  5201. debug.color = createDebug.selectColor(namespace);
  5202. debug.extend = extend;
  5203. debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release.
  5204. Object.defineProperty(debug, 'enabled', {
  5205. enumerable: true,
  5206. configurable: false,
  5207. get: () => {
  5208. if (enableOverride !== null) {
  5209. return enableOverride;
  5210. }
  5211. if (namespacesCache !== createDebug.namespaces) {
  5212. namespacesCache = createDebug.namespaces;
  5213. enabledCache = createDebug.enabled(namespace);
  5214. }
  5215. return enabledCache;
  5216. },
  5217. set: v => {
  5218. enableOverride = v;
  5219. }
  5220. });
  5221. // Env-specific initialization logic for debug instances
  5222. if (typeof createDebug.init === 'function') {
  5223. createDebug.init(debug);
  5224. }
  5225. return debug;
  5226. }
  5227. function extend(namespace, delimiter) {
  5228. const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);
  5229. newDebug.log = this.log;
  5230. return newDebug;
  5231. }
  5232. /**
  5233. * Enables a debug mode by namespaces. This can include modes
  5234. * separated by a colon and wildcards.
  5235. *
  5236. * @param {String} namespaces
  5237. * @api public
  5238. */
  5239. function enable(namespaces) {
  5240. createDebug.save(namespaces);
  5241. createDebug.namespaces = namespaces;
  5242. createDebug.names = [];
  5243. createDebug.skips = [];
  5244. const split = (typeof namespaces === 'string' ? namespaces : '')
  5245. .trim()
  5246. .replace(' ', ',')
  5247. .split(',')
  5248. .filter(Boolean);
  5249. for (const ns of split) {
  5250. if (ns[0] === '-') {
  5251. createDebug.skips.push(ns.slice(1));
  5252. } else {
  5253. createDebug.names.push(ns);
  5254. }
  5255. }
  5256. }
  5257. /**
  5258. * Checks if the given string matches a namespace template, honoring
  5259. * asterisks as wildcards.
  5260. *
  5261. * @param {String} search
  5262. * @param {String} template
  5263. * @return {Boolean}
  5264. */
  5265. function matchesTemplate(search, template) {
  5266. let searchIndex = 0;
  5267. let templateIndex = 0;
  5268. let starIndex = -1;
  5269. let matchIndex = 0;
  5270. while (searchIndex < search.length) {
  5271. if (templateIndex < template.length && (template[templateIndex] === search[searchIndex] || template[templateIndex] === '*')) {
  5272. // Match character or proceed with wildcard
  5273. if (template[templateIndex] === '*') {
  5274. starIndex = templateIndex;
  5275. matchIndex = searchIndex;
  5276. templateIndex++; // Skip the '*'
  5277. } else {
  5278. searchIndex++;
  5279. templateIndex++;
  5280. }
  5281. } else if (starIndex !== -1) { // eslint-disable-line no-negated-condition
  5282. // Backtrack to the last '*' and try to match more characters
  5283. templateIndex = starIndex + 1;
  5284. matchIndex++;
  5285. searchIndex = matchIndex;
  5286. } else {
  5287. return false; // No match
  5288. }
  5289. }
  5290. // Handle trailing '*' in template
  5291. while (templateIndex < template.length && template[templateIndex] === '*') {
  5292. templateIndex++;
  5293. }
  5294. return templateIndex === template.length;
  5295. }
  5296. /**
  5297. * Disable debug output.
  5298. *
  5299. * @return {String} namespaces
  5300. * @api public
  5301. */
  5302. function disable() {
  5303. const namespaces = [
  5304. ...createDebug.names,
  5305. ...createDebug.skips.map(namespace => '-' + namespace)
  5306. ].join(',');
  5307. createDebug.enable('');
  5308. return namespaces;
  5309. }
  5310. /**
  5311. * Returns true if the given mode name is enabled, false otherwise.
  5312. *
  5313. * @param {String} name
  5314. * @return {Boolean}
  5315. * @api public
  5316. */
  5317. function enabled(name) {
  5318. for (const skip of createDebug.skips) {
  5319. if (matchesTemplate(name, skip)) {
  5320. return false;
  5321. }
  5322. }
  5323. for (const ns of createDebug.names) {
  5324. if (matchesTemplate(name, ns)) {
  5325. return true;
  5326. }
  5327. }
  5328. return false;
  5329. }
  5330. /**
  5331. * Coerce `val`.
  5332. *
  5333. * @param {Mixed} val
  5334. * @return {Mixed}
  5335. * @api private
  5336. */
  5337. function coerce(val) {
  5338. if (val instanceof Error) {
  5339. return val.stack || val.message;
  5340. }
  5341. return val;
  5342. }
  5343. /**
  5344. * XXX DO NOT USE. This is a temporary stub function.
  5345. * XXX It WILL be removed in the next major release.
  5346. */
  5347. function destroy() {
  5348. console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
  5349. }
  5350. createDebug.enable(createDebug.load());
  5351. return createDebug;
  5352. }
  5353. common$4 = setup;
  5354. return common$4;
  5355. }
  5356. /**
  5357. * Module dependencies.
  5358. */
  5359. (function (module, exports) {
  5360. const tty = require$$0$3;
  5361. const util = require$$1;
  5362. /**
  5363. * This is the Node.js implementation of `debug()`.
  5364. */
  5365. exports.init = init;
  5366. exports.log = log;
  5367. exports.formatArgs = formatArgs;
  5368. exports.save = save;
  5369. exports.load = load;
  5370. exports.useColors = useColors;
  5371. exports.destroy = util.deprecate(
  5372. () => {},
  5373. 'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'
  5374. );
  5375. /**
  5376. * Colors.
  5377. */
  5378. exports.colors = [6, 2, 3, 4, 5, 1];
  5379. try {
  5380. // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json)
  5381. // eslint-disable-next-line import/no-extraneous-dependencies
  5382. const supportsColor = require('supports-color');
  5383. if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) {
  5384. exports.colors = [
  5385. 20,
  5386. 21,
  5387. 26,
  5388. 27,
  5389. 32,
  5390. 33,
  5391. 38,
  5392. 39,
  5393. 40,
  5394. 41,
  5395. 42,
  5396. 43,
  5397. 44,
  5398. 45,
  5399. 56,
  5400. 57,
  5401. 62,
  5402. 63,
  5403. 68,
  5404. 69,
  5405. 74,
  5406. 75,
  5407. 76,
  5408. 77,
  5409. 78,
  5410. 79,
  5411. 80,
  5412. 81,
  5413. 92,
  5414. 93,
  5415. 98,
  5416. 99,
  5417. 112,
  5418. 113,
  5419. 128,
  5420. 129,
  5421. 134,
  5422. 135,
  5423. 148,
  5424. 149,
  5425. 160,
  5426. 161,
  5427. 162,
  5428. 163,
  5429. 164,
  5430. 165,
  5431. 166,
  5432. 167,
  5433. 168,
  5434. 169,
  5435. 170,
  5436. 171,
  5437. 172,
  5438. 173,
  5439. 178,
  5440. 179,
  5441. 184,
  5442. 185,
  5443. 196,
  5444. 197,
  5445. 198,
  5446. 199,
  5447. 200,
  5448. 201,
  5449. 202,
  5450. 203,
  5451. 204,
  5452. 205,
  5453. 206,
  5454. 207,
  5455. 208,
  5456. 209,
  5457. 214,
  5458. 215,
  5459. 220,
  5460. 221
  5461. ];
  5462. }
  5463. } catch (error) {
  5464. // Swallow - we only care if `supports-color` is available; it doesn't have to be.
  5465. }
  5466. /**
  5467. * Build up the default `inspectOpts` object from the environment variables.
  5468. *
  5469. * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js
  5470. */
  5471. exports.inspectOpts = Object.keys(process.env).filter(key => {
  5472. return /^debug_/i.test(key);
  5473. }).reduce((obj, key) => {
  5474. // Camel-case
  5475. const prop = key
  5476. .substring(6)
  5477. .toLowerCase()
  5478. .replace(/_([a-z])/g, (_, k) => {
  5479. return k.toUpperCase();
  5480. });
  5481. // Coerce string value into JS value
  5482. let val = process.env[key];
  5483. if (/^(yes|on|true|enabled)$/i.test(val)) {
  5484. val = true;
  5485. } else if (/^(no|off|false|disabled)$/i.test(val)) {
  5486. val = false;
  5487. } else if (val === 'null') {
  5488. val = null;
  5489. } else {
  5490. val = Number(val);
  5491. }
  5492. obj[prop] = val;
  5493. return obj;
  5494. }, {});
  5495. /**
  5496. * Is stdout a TTY? Colored output is enabled when `true`.
  5497. */
  5498. function useColors() {
  5499. return 'colors' in exports.inspectOpts ?
  5500. Boolean(exports.inspectOpts.colors) :
  5501. tty.isatty(process.stderr.fd);
  5502. }
  5503. /**
  5504. * Adds ANSI color escape codes if enabled.
  5505. *
  5506. * @api public
  5507. */
  5508. function formatArgs(args) {
  5509. const {namespace: name, useColors} = this;
  5510. if (useColors) {
  5511. const c = this.color;
  5512. const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c);
  5513. const prefix = ` ${colorCode};1m${name} \u001B[0m`;
  5514. args[0] = prefix + args[0].split('\n').join('\n' + prefix);
  5515. args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m');
  5516. } else {
  5517. args[0] = getDate() + name + ' ' + args[0];
  5518. }
  5519. }
  5520. function getDate() {
  5521. if (exports.inspectOpts.hideDate) {
  5522. return '';
  5523. }
  5524. return new Date().toISOString() + ' ';
  5525. }
  5526. /**
  5527. * Invokes `util.formatWithOptions()` with the specified arguments and writes to stderr.
  5528. */
  5529. function log(...args) {
  5530. return process.stderr.write(util.formatWithOptions(exports.inspectOpts, ...args) + '\n');
  5531. }
  5532. /**
  5533. * Save `namespaces`.
  5534. *
  5535. * @param {String} namespaces
  5536. * @api private
  5537. */
  5538. function save(namespaces) {
  5539. if (namespaces) {
  5540. process.env.DEBUG = namespaces;
  5541. } else {
  5542. // If you set a process.env field to null or undefined, it gets cast to the
  5543. // string 'null' or 'undefined'. Just delete instead.
  5544. delete process.env.DEBUG;
  5545. }
  5546. }
  5547. /**
  5548. * Load `namespaces`.
  5549. *
  5550. * @return {String} returns the previously persisted debug modes
  5551. * @api private
  5552. */
  5553. function load() {
  5554. return process.env.DEBUG;
  5555. }
  5556. /**
  5557. * Init logic for `debug` instances.
  5558. *
  5559. * Create a new `inspectOpts` object in case `useColors` is set
  5560. * differently for a particular `debug` instance.
  5561. */
  5562. function init(debug) {
  5563. debug.inspectOpts = {};
  5564. const keys = Object.keys(exports.inspectOpts);
  5565. for (let i = 0; i < keys.length; i++) {
  5566. debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]];
  5567. }
  5568. }
  5569. module.exports = requireCommon()(exports);
  5570. const {formatters} = module.exports;
  5571. /**
  5572. * Map %o to `util.inspect()`, all on a single line.
  5573. */
  5574. formatters.o = function (v) {
  5575. this.inspectOpts.colors = this.useColors;
  5576. return util.inspect(v, this.inspectOpts)
  5577. .split('\n')
  5578. .map(str => str.trim())
  5579. .join(' ');
  5580. };
  5581. /**
  5582. * Map %O to `util.inspect()`, allowing multiple lines if needed.
  5583. */
  5584. formatters.O = function (v) {
  5585. this.inspectOpts.colors = this.useColors;
  5586. return util.inspect(v, this.inspectOpts);
  5587. };
  5588. } (node$1, node$1.exports));
  5589. var nodeExports$1 = node$1.exports;
  5590. var debug$j = /*@__PURE__*/getDefaultExportFromCjs(nodeExports$1);
  5591. let pnp;
  5592. if (process.versions.pnp) {
  5593. try {
  5594. pnp = createRequire$1(import.meta.url)("pnpapi");
  5595. } catch {
  5596. }
  5597. }
  5598. function invalidatePackageData(packageCache, pkgPath) {
  5599. const pkgDir = normalizePath$3(path$b.dirname(pkgPath));
  5600. packageCache.forEach((pkg, cacheKey) => {
  5601. if (pkg.dir === pkgDir) {
  5602. packageCache.delete(cacheKey);
  5603. }
  5604. });
  5605. }
  5606. function resolvePackageData(pkgName, basedir, preserveSymlinks = false, packageCache) {
  5607. if (pnp) {
  5608. const cacheKey = getRpdCacheKey(pkgName, basedir, preserveSymlinks);
  5609. if (packageCache?.has(cacheKey)) return packageCache.get(cacheKey);
  5610. try {
  5611. const pkg = pnp.resolveToUnqualified(pkgName, basedir, {
  5612. considerBuiltins: false
  5613. });
  5614. if (!pkg) return null;
  5615. const pkgData = loadPackageData(path$b.join(pkg, "package.json"));
  5616. packageCache?.set(cacheKey, pkgData);
  5617. return pkgData;
  5618. } catch {
  5619. return null;
  5620. }
  5621. }
  5622. const originalBasedir = basedir;
  5623. while (basedir) {
  5624. if (packageCache) {
  5625. const cached = getRpdCache(
  5626. packageCache,
  5627. pkgName,
  5628. basedir,
  5629. originalBasedir,
  5630. preserveSymlinks
  5631. );
  5632. if (cached) return cached;
  5633. }
  5634. const pkg = path$b.join(basedir, "node_modules", pkgName, "package.json");
  5635. try {
  5636. if (fs__default.existsSync(pkg)) {
  5637. const pkgPath = preserveSymlinks ? pkg : safeRealpathSync(pkg);
  5638. const pkgData = loadPackageData(pkgPath);
  5639. if (packageCache) {
  5640. setRpdCache(
  5641. packageCache,
  5642. pkgData,
  5643. pkgName,
  5644. basedir,
  5645. originalBasedir,
  5646. preserveSymlinks
  5647. );
  5648. }
  5649. return pkgData;
  5650. }
  5651. } catch {
  5652. }
  5653. const nextBasedir = path$b.dirname(basedir);
  5654. if (nextBasedir === basedir) break;
  5655. basedir = nextBasedir;
  5656. }
  5657. return null;
  5658. }
  5659. function findNearestPackageData(basedir, packageCache) {
  5660. const originalBasedir = basedir;
  5661. while (basedir) {
  5662. if (packageCache) {
  5663. const cached = getFnpdCache(packageCache, basedir, originalBasedir);
  5664. if (cached) return cached;
  5665. }
  5666. const pkgPath = path$b.join(basedir, "package.json");
  5667. if (tryStatSync(pkgPath)?.isFile()) {
  5668. try {
  5669. const pkgData = loadPackageData(pkgPath);
  5670. if (packageCache) {
  5671. setFnpdCache(packageCache, pkgData, basedir, originalBasedir);
  5672. }
  5673. return pkgData;
  5674. } catch {
  5675. }
  5676. }
  5677. const nextBasedir = path$b.dirname(basedir);
  5678. if (nextBasedir === basedir) break;
  5679. basedir = nextBasedir;
  5680. }
  5681. return null;
  5682. }
  5683. function findNearestMainPackageData(basedir, packageCache) {
  5684. const nearestPackage = findNearestPackageData(basedir, packageCache);
  5685. return nearestPackage && (nearestPackage.data.name ? nearestPackage : findNearestMainPackageData(
  5686. path$b.dirname(nearestPackage.dir),
  5687. packageCache
  5688. ));
  5689. }
  5690. function loadPackageData(pkgPath) {
  5691. const data = JSON.parse(stripBomTag(fs__default.readFileSync(pkgPath, "utf-8")));
  5692. const pkgDir = normalizePath$3(path$b.dirname(pkgPath));
  5693. const { sideEffects } = data;
  5694. let hasSideEffects;
  5695. if (typeof sideEffects === "boolean") {
  5696. hasSideEffects = () => sideEffects;
  5697. } else if (Array.isArray(sideEffects)) {
  5698. if (sideEffects.length <= 0) {
  5699. hasSideEffects = () => false;
  5700. } else {
  5701. const finalPackageSideEffects = sideEffects.map((sideEffect) => {
  5702. if (sideEffect.includes("/")) {
  5703. return sideEffect;
  5704. }
  5705. return `**/${sideEffect}`;
  5706. });
  5707. hasSideEffects = createFilter$1(finalPackageSideEffects, null, {
  5708. resolve: pkgDir
  5709. });
  5710. }
  5711. } else {
  5712. hasSideEffects = () => null;
  5713. }
  5714. const resolvedCache = {};
  5715. const pkg = {
  5716. dir: pkgDir,
  5717. data,
  5718. hasSideEffects,
  5719. setResolvedCache(key, entry, options) {
  5720. resolvedCache[getResolveCacheKey(key, options)] = entry;
  5721. },
  5722. getResolvedCache(key, options) {
  5723. return resolvedCache[getResolveCacheKey(key, options)];
  5724. }
  5725. };
  5726. return pkg;
  5727. }
  5728. function getResolveCacheKey(key, options) {
  5729. return [
  5730. key,
  5731. options.isRequire ? "1" : "0",
  5732. options.conditions.join("_"),
  5733. options.extensions.join("_"),
  5734. options.mainFields.join("_")
  5735. ].join("|");
  5736. }
  5737. function findNearestNodeModules(basedir) {
  5738. while (basedir) {
  5739. const pkgPath = path$b.join(basedir, "node_modules");
  5740. if (tryStatSync(pkgPath)?.isDirectory()) {
  5741. return pkgPath;
  5742. }
  5743. const nextBasedir = path$b.dirname(basedir);
  5744. if (nextBasedir === basedir) break;
  5745. basedir = nextBasedir;
  5746. }
  5747. return null;
  5748. }
  5749. function watchPackageDataPlugin(packageCache) {
  5750. const watchQueue = /* @__PURE__ */ new Set();
  5751. const watchedDirs = /* @__PURE__ */ new Set();
  5752. const watchFileStub = (id) => {
  5753. watchQueue.add(id);
  5754. };
  5755. let watchFile = watchFileStub;
  5756. const setPackageData = packageCache.set.bind(packageCache);
  5757. packageCache.set = (id, pkg) => {
  5758. if (!isInNodeModules$1(pkg.dir) && !watchedDirs.has(pkg.dir)) {
  5759. watchedDirs.add(pkg.dir);
  5760. watchFile(path$b.join(pkg.dir, "package.json"));
  5761. }
  5762. return setPackageData(id, pkg);
  5763. };
  5764. return {
  5765. name: "vite:watch-package-data",
  5766. buildStart() {
  5767. watchFile = this.addWatchFile.bind(this);
  5768. watchQueue.forEach(watchFile);
  5769. watchQueue.clear();
  5770. },
  5771. buildEnd() {
  5772. watchFile = watchFileStub;
  5773. },
  5774. watchChange(id) {
  5775. if (id.endsWith("/package.json")) {
  5776. invalidatePackageData(packageCache, path$b.normalize(id));
  5777. }
  5778. }
  5779. };
  5780. }
  5781. function getRpdCache(packageCache, pkgName, basedir, originalBasedir, preserveSymlinks) {
  5782. const cacheKey = getRpdCacheKey(pkgName, basedir, preserveSymlinks);
  5783. const pkgData = packageCache.get(cacheKey);
  5784. if (pkgData) {
  5785. traverseBetweenDirs(originalBasedir, basedir, (dir) => {
  5786. packageCache.set(getRpdCacheKey(pkgName, dir, preserveSymlinks), pkgData);
  5787. });
  5788. return pkgData;
  5789. }
  5790. }
  5791. function setRpdCache(packageCache, pkgData, pkgName, basedir, originalBasedir, preserveSymlinks) {
  5792. packageCache.set(getRpdCacheKey(pkgName, basedir, preserveSymlinks), pkgData);
  5793. traverseBetweenDirs(originalBasedir, basedir, (dir) => {
  5794. packageCache.set(getRpdCacheKey(pkgName, dir, preserveSymlinks), pkgData);
  5795. });
  5796. }
  5797. function getRpdCacheKey(pkgName, basedir, preserveSymlinks) {
  5798. return `rpd_${pkgName}_${basedir}_${preserveSymlinks}`;
  5799. }
  5800. function getFnpdCache(packageCache, basedir, originalBasedir) {
  5801. const cacheKey = getFnpdCacheKey(basedir);
  5802. const pkgData = packageCache.get(cacheKey);
  5803. if (pkgData) {
  5804. traverseBetweenDirs(originalBasedir, basedir, (dir) => {
  5805. packageCache.set(getFnpdCacheKey(dir), pkgData);
  5806. });
  5807. return pkgData;
  5808. }
  5809. }
  5810. function setFnpdCache(packageCache, pkgData, basedir, originalBasedir) {
  5811. packageCache.set(getFnpdCacheKey(basedir), pkgData);
  5812. traverseBetweenDirs(originalBasedir, basedir, (dir) => {
  5813. packageCache.set(getFnpdCacheKey(dir), pkgData);
  5814. });
  5815. }
  5816. function getFnpdCacheKey(basedir) {
  5817. return `fnpd_${basedir}`;
  5818. }
  5819. function traverseBetweenDirs(longerDir, shorterDir, cb) {
  5820. while (longerDir !== shorterDir) {
  5821. cb(longerDir);
  5822. longerDir = path$b.dirname(longerDir);
  5823. }
  5824. }
  5825. const createFilter$1 = createFilter$2;
  5826. const replaceSlashOrColonRE = /[/:]/g;
  5827. const replaceDotRE = /\./g;
  5828. const replaceNestedIdRE = /\s*>\s*/g;
  5829. const replaceHashRE = /#/g;
  5830. const flattenId = (id) => {
  5831. const flatId = limitFlattenIdLength(
  5832. id.replace(replaceSlashOrColonRE, "_").replace(replaceDotRE, "__").replace(replaceNestedIdRE, "___").replace(replaceHashRE, "____")
  5833. );
  5834. return flatId;
  5835. };
  5836. const FLATTEN_ID_HASH_LENGTH = 8;
  5837. const FLATTEN_ID_MAX_FILE_LENGTH = 170;
  5838. const limitFlattenIdLength = (id, limit = FLATTEN_ID_MAX_FILE_LENGTH) => {
  5839. if (id.length <= limit) {
  5840. return id;
  5841. }
  5842. return id.slice(0, limit - (FLATTEN_ID_HASH_LENGTH + 1)) + "_" + getHash(id);
  5843. };
  5844. const normalizeId = (id) => id.replace(replaceNestedIdRE, " > ");
  5845. const NODE_BUILTIN_NAMESPACE = "node:";
  5846. const NPM_BUILTIN_NAMESPACE = "npm:";
  5847. const BUN_BUILTIN_NAMESPACE = "bun:";
  5848. const nodeBuiltins = builtinModules.filter((id) => !id.includes(":"));
  5849. const isBuiltinCache = /* @__PURE__ */ new WeakMap();
  5850. function isBuiltin(builtins, id) {
  5851. let isBuiltin2 = isBuiltinCache.get(builtins);
  5852. if (!isBuiltin2) {
  5853. isBuiltin2 = createIsBuiltin(builtins);
  5854. isBuiltinCache.set(builtins, isBuiltin2);
  5855. }
  5856. return isBuiltin2(id);
  5857. }
  5858. function createIsBuiltin(builtins) {
  5859. const plainBuiltinsSet = new Set(
  5860. builtins.filter((builtin) => typeof builtin === "string")
  5861. );
  5862. const regexBuiltins = builtins.filter(
  5863. (builtin) => typeof builtin !== "string"
  5864. );
  5865. return (id) => plainBuiltinsSet.has(id) || regexBuiltins.some((regexp) => regexp.test(id));
  5866. }
  5867. const nodeLikeBuiltins = [
  5868. ...nodeBuiltins,
  5869. new RegExp(`^${NODE_BUILTIN_NAMESPACE}`),
  5870. new RegExp(`^${NPM_BUILTIN_NAMESPACE}`),
  5871. new RegExp(`^${BUN_BUILTIN_NAMESPACE}`)
  5872. ];
  5873. function isNodeLikeBuiltin(id) {
  5874. return isBuiltin(nodeLikeBuiltins, id);
  5875. }
  5876. function isNodeBuiltin(id) {
  5877. if (id.startsWith(NODE_BUILTIN_NAMESPACE)) return true;
  5878. return nodeBuiltins.includes(id);
  5879. }
  5880. function isInNodeModules$1(id) {
  5881. return id.includes("node_modules");
  5882. }
  5883. function moduleListContains(moduleList, id) {
  5884. return moduleList?.some(
  5885. (m) => m === id || id.startsWith(withTrailingSlash(m))
  5886. );
  5887. }
  5888. function isOptimizable(id, optimizeDeps) {
  5889. const { extensions } = optimizeDeps;
  5890. return OPTIMIZABLE_ENTRY_RE.test(id) || (extensions?.some((ext) => id.endsWith(ext)) ?? false);
  5891. }
  5892. const bareImportRE = /^(?![a-zA-Z]:)[\w@](?!.*:\/\/)/;
  5893. const deepImportRE = /^([^@][^/]*)\/|^(@[^/]+\/[^/]+)\//;
  5894. const _require$1 = createRequire$1(import.meta.url);
  5895. const _dirname = path$b.dirname(fileURLToPath$1(import.meta.url));
  5896. const rollupVersion = resolvePackageData("rollup", _dirname, true)?.data.version ?? "";
  5897. const filter = process.env.VITE_DEBUG_FILTER;
  5898. const DEBUG = process.env.DEBUG;
  5899. function createDebugger(namespace, options = {}) {
  5900. const log = debug$j(namespace);
  5901. const { onlyWhenFocused, depth } = options;
  5902. if (depth && log.inspectOpts && log.inspectOpts.depth == null) {
  5903. log.inspectOpts.depth = options.depth;
  5904. }
  5905. let enabled = log.enabled;
  5906. if (enabled && onlyWhenFocused) {
  5907. const ns = typeof onlyWhenFocused === "string" ? onlyWhenFocused : namespace;
  5908. enabled = !!DEBUG?.includes(ns);
  5909. }
  5910. if (enabled) {
  5911. return (...args) => {
  5912. if (!filter || args.some((a) => a?.includes?.(filter))) {
  5913. log(...args);
  5914. }
  5915. };
  5916. }
  5917. }
  5918. function testCaseInsensitiveFS() {
  5919. if (!CLIENT_ENTRY.endsWith("client.mjs")) {
  5920. throw new Error(
  5921. `cannot test case insensitive FS, CLIENT_ENTRY const doesn't contain client.mjs`
  5922. );
  5923. }
  5924. if (!fs__default.existsSync(CLIENT_ENTRY)) {
  5925. throw new Error(
  5926. "cannot test case insensitive FS, CLIENT_ENTRY does not point to an existing file: " + CLIENT_ENTRY
  5927. );
  5928. }
  5929. return fs__default.existsSync(CLIENT_ENTRY.replace("client.mjs", "cLiEnT.mjs"));
  5930. }
  5931. const urlCanParse = (
  5932. // eslint-disable-next-line n/no-unsupported-features/node-builtins
  5933. URL$3.canParse ?? // URL.canParse is supported from Node.js 18.17.0+, 20.0.0+
  5934. ((path2, base) => {
  5935. try {
  5936. new URL$3(path2, base);
  5937. return true;
  5938. } catch {
  5939. return false;
  5940. }
  5941. })
  5942. );
  5943. const isCaseInsensitiveFS = testCaseInsensitiveFS();
  5944. const VOLUME_RE = /^[A-Z]:/i;
  5945. function normalizePath$3(id) {
  5946. return path$b.posix.normalize(isWindows$3 ? slash$1(id) : id);
  5947. }
  5948. function fsPathFromId(id) {
  5949. const fsPath = normalizePath$3(
  5950. id.startsWith(FS_PREFIX) ? id.slice(FS_PREFIX.length) : id
  5951. );
  5952. return fsPath[0] === "/" || VOLUME_RE.test(fsPath) ? fsPath : `/${fsPath}`;
  5953. }
  5954. function fsPathFromUrl(url) {
  5955. return fsPathFromId(cleanUrl(url));
  5956. }
  5957. function isParentDirectory(dir, file) {
  5958. dir = withTrailingSlash(dir);
  5959. return file.startsWith(dir) || isCaseInsensitiveFS && file.toLowerCase().startsWith(dir.toLowerCase());
  5960. }
  5961. function isSameFileUri(file1, file2) {
  5962. return file1 === file2 || isCaseInsensitiveFS && file1.toLowerCase() === file2.toLowerCase();
  5963. }
  5964. const externalRE = /^([a-z]+:)?\/\//;
  5965. const isExternalUrl = (url) => externalRE.test(url);
  5966. const dataUrlRE = /^\s*data:/i;
  5967. const isDataUrl = (url) => dataUrlRE.test(url);
  5968. const virtualModuleRE = /^virtual-module:.*/;
  5969. const virtualModulePrefix = "virtual-module:";
  5970. const knownJsSrcRE = /\.(?:[jt]sx?|m[jt]s|vue|marko|svelte|astro|imba|mdx)(?:$|\?)/;
  5971. const isJSRequest = (url) => {
  5972. url = cleanUrl(url);
  5973. if (knownJsSrcRE.test(url)) {
  5974. return true;
  5975. }
  5976. if (!path$b.extname(url) && url[url.length - 1] !== "/") {
  5977. return true;
  5978. }
  5979. return false;
  5980. };
  5981. const importQueryRE = /(\?|&)import=?(?:&|$)/;
  5982. const directRequestRE$1 = /(\?|&)direct=?(?:&|$)/;
  5983. const internalPrefixes = [
  5984. FS_PREFIX,
  5985. VALID_ID_PREFIX,
  5986. CLIENT_PUBLIC_PATH,
  5987. ENV_PUBLIC_PATH
  5988. ];
  5989. const InternalPrefixRE = new RegExp(`^(?:${internalPrefixes.join("|")})`);
  5990. const trailingSeparatorRE = /[?&]$/;
  5991. const isImportRequest = (url) => importQueryRE.test(url);
  5992. const isInternalRequest = (url) => InternalPrefixRE.test(url);
  5993. function removeImportQuery(url) {
  5994. return url.replace(importQueryRE, "$1").replace(trailingSeparatorRE, "");
  5995. }
  5996. function removeDirectQuery(url) {
  5997. return url.replace(directRequestRE$1, "$1").replace(trailingSeparatorRE, "");
  5998. }
  5999. const urlRE$1 = /(\?|&)url(?:&|$)/;
  6000. const rawRE$1 = /(\?|&)raw(?:&|$)/;
  6001. function removeUrlQuery(url) {
  6002. return url.replace(urlRE$1, "$1").replace(trailingSeparatorRE, "");
  6003. }
  6004. function injectQuery(url, queryToInject) {
  6005. const { file, postfix } = splitFileAndPostfix(url);
  6006. const normalizedFile = isWindows$3 ? slash$1(file) : file;
  6007. return `${normalizedFile}?${queryToInject}${postfix[0] === "?" ? `&${postfix.slice(1)}` : (
  6008. /* hash only */
  6009. postfix
  6010. )}`;
  6011. }
  6012. const timestampRE = /\bt=\d{13}&?\b/;
  6013. function removeTimestampQuery(url) {
  6014. return url.replace(timestampRE, "").replace(trailingSeparatorRE, "");
  6015. }
  6016. async function asyncReplace(input, re, replacer) {
  6017. let match;
  6018. let remaining = input;
  6019. let rewritten = "";
  6020. while (match = re.exec(remaining)) {
  6021. rewritten += remaining.slice(0, match.index);
  6022. rewritten += await replacer(match);
  6023. remaining = remaining.slice(match.index + match[0].length);
  6024. }
  6025. rewritten += remaining;
  6026. return rewritten;
  6027. }
  6028. function timeFrom(start, subtract = 0) {
  6029. const time = performance$1.now() - start - subtract;
  6030. const timeString = (time.toFixed(2) + `ms`).padEnd(5, " ");
  6031. if (time < 10) {
  6032. return colors$1.green(timeString);
  6033. } else if (time < 50) {
  6034. return colors$1.yellow(timeString);
  6035. } else {
  6036. return colors$1.red(timeString);
  6037. }
  6038. }
  6039. function prettifyUrl(url, root) {
  6040. url = removeTimestampQuery(url);
  6041. const isAbsoluteFile = url.startsWith(root);
  6042. if (isAbsoluteFile || url.startsWith(FS_PREFIX)) {
  6043. const file = path$b.posix.relative(
  6044. root,
  6045. isAbsoluteFile ? url : fsPathFromId(url)
  6046. );
  6047. return colors$1.dim(file);
  6048. } else {
  6049. return colors$1.dim(url);
  6050. }
  6051. }
  6052. function isObject$1(value) {
  6053. return Object.prototype.toString.call(value) === "[object Object]";
  6054. }
  6055. function isDefined(value) {
  6056. return value != null;
  6057. }
  6058. function tryStatSync(file) {
  6059. try {
  6060. return fs__default.statSync(file, { throwIfNoEntry: false });
  6061. } catch {
  6062. }
  6063. }
  6064. function lookupFile(dir, fileNames) {
  6065. while (dir) {
  6066. for (const fileName of fileNames) {
  6067. const fullPath = path$b.join(dir, fileName);
  6068. if (tryStatSync(fullPath)?.isFile()) return fullPath;
  6069. }
  6070. const parentDir = path$b.dirname(dir);
  6071. if (parentDir === dir) return;
  6072. dir = parentDir;
  6073. }
  6074. }
  6075. function isFilePathESM(filePath, packageCache) {
  6076. if (/\.m[jt]s$/.test(filePath)) {
  6077. return true;
  6078. } else if (/\.c[jt]s$/.test(filePath)) {
  6079. return false;
  6080. } else {
  6081. try {
  6082. const pkg = findNearestPackageData(path$b.dirname(filePath), packageCache);
  6083. return pkg?.data.type === "module";
  6084. } catch {
  6085. return false;
  6086. }
  6087. }
  6088. }
  6089. const splitRE = /\r?\n/g;
  6090. const range = 2;
  6091. function pad$1(source, n = 2) {
  6092. const lines = source.split(splitRE);
  6093. return lines.map((l) => ` `.repeat(n) + l).join(`
  6094. `);
  6095. }
  6096. function posToNumber(source, pos) {
  6097. if (typeof pos === "number") return pos;
  6098. const lines = source.split(splitRE);
  6099. const { line, column } = pos;
  6100. let start = 0;
  6101. for (let i = 0; i < line - 1 && i < lines.length; i++) {
  6102. start += lines[i].length + 1;
  6103. }
  6104. return start + column;
  6105. }
  6106. function numberToPos(source, offset) {
  6107. if (typeof offset !== "number") return offset;
  6108. if (offset > source.length) {
  6109. throw new Error(
  6110. `offset is longer than source length! offset ${offset} > length ${source.length}`
  6111. );
  6112. }
  6113. const lines = source.split(splitRE);
  6114. let counted = 0;
  6115. let line = 0;
  6116. let column = 0;
  6117. for (; line < lines.length; line++) {
  6118. const lineLength = lines[line].length + 1;
  6119. if (counted + lineLength >= offset) {
  6120. column = offset - counted + 1;
  6121. break;
  6122. }
  6123. counted += lineLength;
  6124. }
  6125. return { line: line + 1, column };
  6126. }
  6127. function generateCodeFrame(source, start = 0, end) {
  6128. start = Math.max(posToNumber(source, start), 0);
  6129. end = Math.min(
  6130. end !== void 0 ? posToNumber(source, end) : start,
  6131. source.length
  6132. );
  6133. const lines = source.split(splitRE);
  6134. let count = 0;
  6135. const res = [];
  6136. for (let i = 0; i < lines.length; i++) {
  6137. count += lines[i].length;
  6138. if (count >= start) {
  6139. for (let j = i - range; j <= i + range || end > count; j++) {
  6140. if (j < 0 || j >= lines.length) continue;
  6141. const line = j + 1;
  6142. res.push(
  6143. `${line}${" ".repeat(Math.max(3 - String(line).length, 0))}| ${lines[j]}`
  6144. );
  6145. const lineLength = lines[j].length;
  6146. if (j === i) {
  6147. const pad2 = Math.max(start - (count - lineLength), 0);
  6148. const length = Math.max(
  6149. 1,
  6150. end > count ? lineLength - pad2 : end - start
  6151. );
  6152. res.push(` | ` + " ".repeat(pad2) + "^".repeat(length));
  6153. } else if (j > i) {
  6154. if (end > count) {
  6155. const length = Math.max(Math.min(end - count, lineLength), 1);
  6156. res.push(` | ` + "^".repeat(length));
  6157. }
  6158. count += lineLength + 1;
  6159. }
  6160. }
  6161. break;
  6162. }
  6163. count++;
  6164. }
  6165. return res.join("\n");
  6166. }
  6167. function isFileReadable(filename) {
  6168. if (!tryStatSync(filename)) {
  6169. return false;
  6170. }
  6171. try {
  6172. fs__default.accessSync(filename, fs__default.constants.R_OK);
  6173. return true;
  6174. } catch {
  6175. return false;
  6176. }
  6177. }
  6178. const splitFirstDirRE = /(.+?)[\\/](.+)/;
  6179. function emptyDir(dir, skip) {
  6180. const skipInDir = [];
  6181. let nested = null;
  6182. if (skip?.length) {
  6183. for (const file of skip) {
  6184. if (path$b.dirname(file) !== ".") {
  6185. const matched = splitFirstDirRE.exec(file);
  6186. if (matched) {
  6187. nested ??= /* @__PURE__ */ new Map();
  6188. const [, nestedDir, skipPath] = matched;
  6189. let nestedSkip = nested.get(nestedDir);
  6190. if (!nestedSkip) {
  6191. nestedSkip = [];
  6192. nested.set(nestedDir, nestedSkip);
  6193. }
  6194. if (!nestedSkip.includes(skipPath)) {
  6195. nestedSkip.push(skipPath);
  6196. }
  6197. }
  6198. } else {
  6199. skipInDir.push(file);
  6200. }
  6201. }
  6202. }
  6203. for (const file of fs__default.readdirSync(dir)) {
  6204. if (skipInDir.includes(file)) {
  6205. continue;
  6206. }
  6207. if (nested?.has(file)) {
  6208. emptyDir(path$b.resolve(dir, file), nested.get(file));
  6209. } else {
  6210. fs__default.rmSync(path$b.resolve(dir, file), { recursive: true, force: true });
  6211. }
  6212. }
  6213. }
  6214. function copyDir(srcDir, destDir) {
  6215. fs__default.mkdirSync(destDir, { recursive: true });
  6216. for (const file of fs__default.readdirSync(srcDir)) {
  6217. const srcFile = path$b.resolve(srcDir, file);
  6218. if (srcFile === destDir) {
  6219. continue;
  6220. }
  6221. const destFile = path$b.resolve(destDir, file);
  6222. const stat = fs__default.statSync(srcFile);
  6223. if (stat.isDirectory()) {
  6224. copyDir(srcFile, destFile);
  6225. } else {
  6226. fs__default.copyFileSync(srcFile, destFile);
  6227. }
  6228. }
  6229. }
  6230. const ERR_SYMLINK_IN_RECURSIVE_READDIR = "ERR_SYMLINK_IN_RECURSIVE_READDIR";
  6231. async function recursiveReaddir(dir) {
  6232. if (!fs__default.existsSync(dir)) {
  6233. return [];
  6234. }
  6235. let dirents;
  6236. try {
  6237. dirents = await fsp.readdir(dir, { withFileTypes: true });
  6238. } catch (e) {
  6239. if (e.code === "EACCES") {
  6240. return [];
  6241. }
  6242. throw e;
  6243. }
  6244. if (dirents.some((dirent) => dirent.isSymbolicLink())) {
  6245. const err = new Error(
  6246. "Symbolic links are not supported in recursiveReaddir"
  6247. );
  6248. err.code = ERR_SYMLINK_IN_RECURSIVE_READDIR;
  6249. throw err;
  6250. }
  6251. const files = await Promise.all(
  6252. dirents.map((dirent) => {
  6253. const res = path$b.resolve(dir, dirent.name);
  6254. return dirent.isDirectory() ? recursiveReaddir(res) : normalizePath$3(res);
  6255. })
  6256. );
  6257. return files.flat(1);
  6258. }
  6259. let safeRealpathSync = isWindows$3 ? windowsSafeRealPathSync : fs__default.realpathSync.native;
  6260. const windowsNetworkMap = /* @__PURE__ */ new Map();
  6261. function windowsMappedRealpathSync(path2) {
  6262. const realPath = fs__default.realpathSync.native(path2);
  6263. if (realPath.startsWith("\\\\")) {
  6264. for (const [network, volume] of windowsNetworkMap) {
  6265. if (realPath.startsWith(network)) return realPath.replace(network, volume);
  6266. }
  6267. }
  6268. return realPath;
  6269. }
  6270. const parseNetUseRE = /^\w* +(\w:) +([^ ]+)\s/;
  6271. let firstSafeRealPathSyncRun = false;
  6272. function windowsSafeRealPathSync(path2) {
  6273. if (!firstSafeRealPathSyncRun) {
  6274. optimizeSafeRealPathSync();
  6275. firstSafeRealPathSyncRun = true;
  6276. }
  6277. return fs__default.realpathSync(path2);
  6278. }
  6279. function optimizeSafeRealPathSync() {
  6280. const nodeVersion = process.versions.node.split(".").map(Number);
  6281. if (nodeVersion[0] < 18 || nodeVersion[0] === 18 && nodeVersion[1] < 10) {
  6282. safeRealpathSync = fs__default.realpathSync;
  6283. return;
  6284. }
  6285. try {
  6286. fs__default.realpathSync.native(path$b.resolve("./"));
  6287. } catch (error) {
  6288. if (error.message.includes("EISDIR: illegal operation on a directory")) {
  6289. safeRealpathSync = fs__default.realpathSync;
  6290. return;
  6291. }
  6292. }
  6293. exec("net use", (error, stdout) => {
  6294. if (error) return;
  6295. const lines = stdout.split("\n");
  6296. for (const line of lines) {
  6297. const m = parseNetUseRE.exec(line);
  6298. if (m) windowsNetworkMap.set(m[2], m[1]);
  6299. }
  6300. if (windowsNetworkMap.size === 0) {
  6301. safeRealpathSync = fs__default.realpathSync.native;
  6302. } else {
  6303. safeRealpathSync = windowsMappedRealpathSync;
  6304. }
  6305. });
  6306. }
  6307. function ensureWatchedFile(watcher, file, root) {
  6308. if (file && // only need to watch if out of root
  6309. !file.startsWith(withTrailingSlash(root)) && // some rollup plugins use null bytes for private resolved Ids
  6310. !file.includes("\0") && fs__default.existsSync(file)) {
  6311. watcher.add(path$b.resolve(file));
  6312. }
  6313. }
  6314. function joinSrcset(ret) {
  6315. return ret.map(({ url, descriptor }) => url + (descriptor ? ` ${descriptor}` : "")).join(", ");
  6316. }
  6317. const imageCandidateRegex = /(?:^|\s|(?<=,))(?<url>[\w-]+\([^)]*\)|"[^"]*"|'[^']*'|[^,]\S*[^,])\s*(?:\s(?<descriptor>\w[^,]+))?(?:,|$)/g;
  6318. const escapedSpaceCharacters = /(?: |\\t|\\n|\\f|\\r)+/g;
  6319. function parseSrcset(string) {
  6320. const matches = string.trim().replace(escapedSpaceCharacters, " ").replace(/\r?\n/, "").replace(/,\s+/, ", ").replaceAll(/\s+/g, " ").matchAll(imageCandidateRegex);
  6321. return Array.from(matches, ({ groups }) => ({
  6322. url: groups?.url?.trim() ?? "",
  6323. descriptor: groups?.descriptor?.trim() ?? ""
  6324. })).filter(({ url }) => !!url);
  6325. }
  6326. function processSrcSet(srcs, replacer) {
  6327. return Promise.all(
  6328. parseSrcset(srcs).map(async ({ url, descriptor }) => ({
  6329. url: await replacer({ url, descriptor }),
  6330. descriptor
  6331. }))
  6332. ).then(joinSrcset);
  6333. }
  6334. function processSrcSetSync(srcs, replacer) {
  6335. return joinSrcset(
  6336. parseSrcset(srcs).map(({ url, descriptor }) => ({
  6337. url: replacer({ url, descriptor }),
  6338. descriptor
  6339. }))
  6340. );
  6341. }
  6342. const windowsDriveRE = /^[A-Z]:/;
  6343. const replaceWindowsDriveRE = /^([A-Z]):\//;
  6344. const linuxAbsolutePathRE = /^\/[^/]/;
  6345. function escapeToLinuxLikePath(path2) {
  6346. if (windowsDriveRE.test(path2)) {
  6347. return path2.replace(replaceWindowsDriveRE, "/windows/$1/");
  6348. }
  6349. if (linuxAbsolutePathRE.test(path2)) {
  6350. return `/linux${path2}`;
  6351. }
  6352. return path2;
  6353. }
  6354. const revertWindowsDriveRE = /^\/windows\/([A-Z])\//;
  6355. function unescapeToLinuxLikePath(path2) {
  6356. if (path2.startsWith("/linux/")) {
  6357. return path2.slice("/linux".length);
  6358. }
  6359. if (path2.startsWith("/windows/")) {
  6360. return path2.replace(revertWindowsDriveRE, "$1:/");
  6361. }
  6362. return path2;
  6363. }
  6364. const nullSourceMap = {
  6365. names: [],
  6366. sources: [],
  6367. mappings: "",
  6368. version: 3
  6369. };
  6370. function combineSourcemaps(filename, sourcemapList) {
  6371. if (sourcemapList.length === 0 || sourcemapList.every((m) => m.sources.length === 0)) {
  6372. return { ...nullSourceMap };
  6373. }
  6374. sourcemapList = sourcemapList.map((sourcemap) => {
  6375. const newSourcemaps = { ...sourcemap };
  6376. newSourcemaps.sources = sourcemap.sources.map(
  6377. (source) => source ? escapeToLinuxLikePath(source) : null
  6378. );
  6379. if (sourcemap.sourceRoot) {
  6380. newSourcemaps.sourceRoot = escapeToLinuxLikePath(sourcemap.sourceRoot);
  6381. }
  6382. return newSourcemaps;
  6383. });
  6384. const escapedFilename = escapeToLinuxLikePath(filename);
  6385. let map;
  6386. let mapIndex = 1;
  6387. const useArrayInterface = sourcemapList.slice(0, -1).find((m) => m.sources.length !== 1) === void 0;
  6388. if (useArrayInterface) {
  6389. map = remapping(sourcemapList, () => null);
  6390. } else {
  6391. map = remapping(sourcemapList[0], function loader(sourcefile) {
  6392. if (sourcefile === escapedFilename && sourcemapList[mapIndex]) {
  6393. return sourcemapList[mapIndex++];
  6394. } else {
  6395. return null;
  6396. }
  6397. });
  6398. }
  6399. if (!map.file) {
  6400. delete map.file;
  6401. }
  6402. map.sources = map.sources.map(
  6403. (source) => source ? unescapeToLinuxLikePath(source) : source
  6404. );
  6405. map.file = filename;
  6406. return map;
  6407. }
  6408. function unique(arr) {
  6409. return Array.from(new Set(arr));
  6410. }
  6411. async function getLocalhostAddressIfDiffersFromDNS() {
  6412. const [nodeResult, dnsResult] = await Promise.all([
  6413. promises.lookup("localhost"),
  6414. promises.lookup("localhost", { verbatim: true })
  6415. ]);
  6416. const isSame = nodeResult.family === dnsResult.family && nodeResult.address === dnsResult.address;
  6417. return isSame ? void 0 : nodeResult.address;
  6418. }
  6419. function diffDnsOrderChange(oldUrls, newUrls) {
  6420. return !(oldUrls === newUrls || oldUrls && newUrls && arrayEqual(oldUrls.local, newUrls.local) && arrayEqual(oldUrls.network, newUrls.network));
  6421. }
  6422. async function resolveHostname(optionsHost) {
  6423. let host;
  6424. if (optionsHost === void 0 || optionsHost === false) {
  6425. host = "localhost";
  6426. } else if (optionsHost === true) {
  6427. host = void 0;
  6428. } else {
  6429. host = optionsHost;
  6430. }
  6431. let name = host === void 0 || wildcardHosts.has(host) ? "localhost" : host;
  6432. if (host === "localhost") {
  6433. const localhostAddr = await getLocalhostAddressIfDiffersFromDNS();
  6434. if (localhostAddr) {
  6435. name = localhostAddr;
  6436. }
  6437. }
  6438. return { host, name };
  6439. }
  6440. async function resolveServerUrls(server, options, httpsOptions, config) {
  6441. const address = server.address();
  6442. const isAddressInfo = (x) => x?.address;
  6443. if (!isAddressInfo(address)) {
  6444. return { local: [], network: [] };
  6445. }
  6446. const local = [];
  6447. const network = [];
  6448. const hostname = await resolveHostname(options.host);
  6449. const protocol = options.https ? "https" : "http";
  6450. const port = address.port;
  6451. const base = config.rawBase === "./" || config.rawBase === "" ? "/" : config.rawBase;
  6452. if (hostname.host !== void 0 && !wildcardHosts.has(hostname.host)) {
  6453. let hostnameName = hostname.name;
  6454. if (hostnameName.includes(":")) {
  6455. hostnameName = `[${hostnameName}]`;
  6456. }
  6457. const address2 = `${protocol}://${hostnameName}:${port}${base}`;
  6458. if (loopbackHosts.has(hostname.host)) {
  6459. local.push(address2);
  6460. } else {
  6461. network.push(address2);
  6462. }
  6463. } else {
  6464. Object.values(os$3.networkInterfaces()).flatMap((nInterface) => nInterface ?? []).filter(
  6465. (detail) => detail.address && (detail.family === "IPv4" || // @ts-expect-error Node 18.0 - 18.3 returns number
  6466. detail.family === 4)
  6467. ).forEach((detail) => {
  6468. let host = detail.address.replace("127.0.0.1", hostname.name);
  6469. if (host.includes(":")) {
  6470. host = `[${host}]`;
  6471. }
  6472. const url = `${protocol}://${host}:${port}${base}`;
  6473. if (detail.address.includes("127.0.0.1")) {
  6474. local.push(url);
  6475. } else {
  6476. network.push(url);
  6477. }
  6478. });
  6479. }
  6480. const cert = httpsOptions?.cert && !Array.isArray(httpsOptions.cert) ? new crypto$2.X509Certificate(httpsOptions.cert) : void 0;
  6481. const hostnameFromCert = cert?.subjectAltName ? extractHostnamesFromSubjectAltName(cert.subjectAltName) : [];
  6482. if (hostnameFromCert.length > 0) {
  6483. const existings = /* @__PURE__ */ new Set([...local, ...network]);
  6484. local.push(
  6485. ...hostnameFromCert.map((hostname2) => `https://${hostname2}:${port}${base}`).filter((url) => !existings.has(url))
  6486. );
  6487. }
  6488. return { local, network };
  6489. }
  6490. function extractHostnamesFromSubjectAltName(subjectAltName) {
  6491. const hostnames = [];
  6492. let remaining = subjectAltName;
  6493. while (remaining) {
  6494. const nameEndIndex = remaining.indexOf(":");
  6495. const name = remaining.slice(0, nameEndIndex);
  6496. remaining = remaining.slice(nameEndIndex + 1);
  6497. if (!remaining) break;
  6498. const isQuoted = remaining[0] === '"';
  6499. let value;
  6500. if (isQuoted) {
  6501. const endQuoteIndex = remaining.indexOf('"', 1);
  6502. value = JSON.parse(remaining.slice(0, endQuoteIndex + 1));
  6503. remaining = remaining.slice(endQuoteIndex + 1);
  6504. } else {
  6505. const maybeEndIndex = remaining.indexOf(",");
  6506. const endIndex = maybeEndIndex === -1 ? remaining.length : maybeEndIndex;
  6507. value = remaining.slice(0, endIndex);
  6508. remaining = remaining.slice(endIndex);
  6509. }
  6510. remaining = remaining.slice(
  6511. /* for , */
  6512. 1
  6513. ).trimStart();
  6514. if (name === "DNS" && // [::1] might be included but skip it as it's already included as a local address
  6515. value !== "[::1]" && // skip *.IPv4 addresses, which is invalid
  6516. !(value.startsWith("*.") && net$1.isIPv4(value.slice(2)))) {
  6517. hostnames.push(value.replace("*", "vite"));
  6518. }
  6519. }
  6520. return hostnames;
  6521. }
  6522. function arraify(target) {
  6523. return Array.isArray(target) ? target : [target];
  6524. }
  6525. const multilineCommentsRE = /\/\*[^*]*\*+(?:[^/*][^*]*\*+)*\//g;
  6526. const singlelineCommentsRE = /\/\/.*/g;
  6527. const requestQuerySplitRE = /\?(?!.*[/|}])/;
  6528. const requestQueryMaybeEscapedSplitRE = /\\?\?(?!.*[/|}])/;
  6529. const blankReplacer = (match) => " ".repeat(match.length);
  6530. const hash$1 = (
  6531. // eslint-disable-next-line n/no-unsupported-features/node-builtins -- crypto.hash is supported in Node 21.7.0+, 20.12.0+
  6532. crypto$2.hash ?? ((algorithm, data, outputEncoding) => crypto$2.createHash(algorithm).update(data).digest(outputEncoding))
  6533. );
  6534. function getHash(text, length = 8) {
  6535. const h = hash$1("sha256", text, "hex").substring(0, length);
  6536. if (length <= 64) return h;
  6537. return h.padEnd(length, "_");
  6538. }
  6539. const requireResolveFromRootWithFallback = (root, id) => {
  6540. const found = resolvePackageData(id, root) || resolvePackageData(id, _dirname);
  6541. if (!found) {
  6542. const error = new Error(`${JSON.stringify(id)} not found.`);
  6543. error.code = "MODULE_NOT_FOUND";
  6544. throw error;
  6545. }
  6546. return _require$1.resolve(id, { paths: [root, _dirname] });
  6547. };
  6548. function emptyCssComments(raw) {
  6549. return raw.replace(multilineCommentsRE, blankReplacer);
  6550. }
  6551. function backwardCompatibleWorkerPlugins(plugins) {
  6552. if (Array.isArray(plugins)) {
  6553. return plugins;
  6554. }
  6555. if (typeof plugins === "function") {
  6556. return plugins();
  6557. }
  6558. return [];
  6559. }
  6560. function deepClone(value) {
  6561. if (Array.isArray(value)) {
  6562. return value.map((v) => deepClone(v));
  6563. }
  6564. if (isObject$1(value)) {
  6565. const cloned = {};
  6566. for (const key in value) {
  6567. cloned[key] = deepClone(value[key]);
  6568. }
  6569. return cloned;
  6570. }
  6571. if (typeof value === "function") {
  6572. return value;
  6573. }
  6574. if (value instanceof RegExp) {
  6575. return new RegExp(value);
  6576. }
  6577. if (typeof value === "object" && value != null) {
  6578. throw new Error("Cannot deep clone non-plain object");
  6579. }
  6580. return value;
  6581. }
  6582. function mergeWithDefaultsRecursively(defaults, values) {
  6583. const merged = defaults;
  6584. for (const key in values) {
  6585. const value = values[key];
  6586. if (value === void 0) continue;
  6587. const existing = merged[key];
  6588. if (existing === void 0) {
  6589. merged[key] = value;
  6590. continue;
  6591. }
  6592. if (isObject$1(existing) && isObject$1(value)) {
  6593. merged[key] = mergeWithDefaultsRecursively(existing, value);
  6594. continue;
  6595. }
  6596. merged[key] = value;
  6597. }
  6598. return merged;
  6599. }
  6600. function mergeWithDefaults(defaults, values) {
  6601. const clonedDefaults = deepClone(defaults);
  6602. return mergeWithDefaultsRecursively(clonedDefaults, values);
  6603. }
  6604. function mergeConfigRecursively(defaults, overrides, rootPath) {
  6605. const merged = { ...defaults };
  6606. for (const key in overrides) {
  6607. const value = overrides[key];
  6608. if (value == null) {
  6609. continue;
  6610. }
  6611. const existing = merged[key];
  6612. if (existing == null) {
  6613. merged[key] = value;
  6614. continue;
  6615. }
  6616. if (key === "alias" && (rootPath === "resolve" || rootPath === "")) {
  6617. merged[key] = mergeAlias(existing, value);
  6618. continue;
  6619. } else if (key === "assetsInclude" && rootPath === "") {
  6620. merged[key] = [].concat(existing, value);
  6621. continue;
  6622. } else if (key === "noExternal" && (rootPath === "ssr" || rootPath === "resolve") && (existing === true || value === true)) {
  6623. merged[key] = true;
  6624. continue;
  6625. } else if (key === "plugins" && rootPath === "worker") {
  6626. merged[key] = () => [
  6627. ...backwardCompatibleWorkerPlugins(existing),
  6628. ...backwardCompatibleWorkerPlugins(value)
  6629. ];
  6630. continue;
  6631. } else if (key === "server" && rootPath === "server.hmr") {
  6632. merged[key] = value;
  6633. continue;
  6634. }
  6635. if (Array.isArray(existing) || Array.isArray(value)) {
  6636. merged[key] = [...arraify(existing), ...arraify(value)];
  6637. continue;
  6638. }
  6639. if (isObject$1(existing) && isObject$1(value)) {
  6640. merged[key] = mergeConfigRecursively(
  6641. existing,
  6642. value,
  6643. rootPath ? `${rootPath}.${key}` : key
  6644. );
  6645. continue;
  6646. }
  6647. merged[key] = value;
  6648. }
  6649. return merged;
  6650. }
  6651. function mergeConfig(defaults, overrides, isRoot = true) {
  6652. if (typeof defaults === "function" || typeof overrides === "function") {
  6653. throw new Error(`Cannot merge config in form of callback`);
  6654. }
  6655. return mergeConfigRecursively(defaults, overrides, isRoot ? "" : ".");
  6656. }
  6657. function mergeAlias(a, b) {
  6658. if (!a) return b;
  6659. if (!b) return a;
  6660. if (isObject$1(a) && isObject$1(b)) {
  6661. return { ...a, ...b };
  6662. }
  6663. return [...normalizeAlias(b), ...normalizeAlias(a)];
  6664. }
  6665. function normalizeAlias(o = []) {
  6666. return Array.isArray(o) ? o.map(normalizeSingleAlias) : Object.keys(o).map(
  6667. (find) => normalizeSingleAlias({
  6668. find,
  6669. replacement: o[find]
  6670. })
  6671. );
  6672. }
  6673. function normalizeSingleAlias({
  6674. find,
  6675. replacement,
  6676. customResolver
  6677. }) {
  6678. if (typeof find === "string" && find.endsWith("/") && replacement.endsWith("/")) {
  6679. find = find.slice(0, find.length - 1);
  6680. replacement = replacement.slice(0, replacement.length - 1);
  6681. }
  6682. const alias = {
  6683. find,
  6684. replacement
  6685. };
  6686. if (customResolver) {
  6687. alias.customResolver = customResolver;
  6688. }
  6689. return alias;
  6690. }
  6691. function transformStableResult(s, id, config) {
  6692. return {
  6693. code: s.toString(),
  6694. map: config.command === "build" && config.build.sourcemap ? s.generateMap({ hires: "boundary", source: id }) : null
  6695. };
  6696. }
  6697. async function asyncFlatten(arr) {
  6698. do {
  6699. arr = (await Promise.all(arr)).flat(Infinity);
  6700. } while (arr.some((v) => v?.then));
  6701. return arr;
  6702. }
  6703. function stripBomTag(content) {
  6704. if (content.charCodeAt(0) === 65279) {
  6705. return content.slice(1);
  6706. }
  6707. return content;
  6708. }
  6709. const windowsDrivePathPrefixRE = /^[A-Za-z]:[/\\]/;
  6710. const isNonDriveRelativeAbsolutePath = (p) => {
  6711. if (!isWindows$3) return p[0] === "/";
  6712. return windowsDrivePathPrefixRE.test(p);
  6713. };
  6714. function shouldServeFile(filePath, root) {
  6715. if (!isCaseInsensitiveFS) return true;
  6716. return hasCorrectCase(filePath, root);
  6717. }
  6718. function hasCorrectCase(file, assets) {
  6719. if (file === assets) return true;
  6720. const parent = path$b.dirname(file);
  6721. if (fs__default.readdirSync(parent).includes(path$b.basename(file))) {
  6722. return hasCorrectCase(parent, assets);
  6723. }
  6724. return false;
  6725. }
  6726. function joinUrlSegments(a, b) {
  6727. if (!a || !b) {
  6728. return a || b || "";
  6729. }
  6730. if (a.endsWith("/")) {
  6731. a = a.substring(0, a.length - 1);
  6732. }
  6733. if (b[0] !== "/") {
  6734. b = "/" + b;
  6735. }
  6736. return a + b;
  6737. }
  6738. function removeLeadingSlash(str) {
  6739. return str[0] === "/" ? str.slice(1) : str;
  6740. }
  6741. function stripBase(path2, base) {
  6742. if (path2 === base) {
  6743. return "/";
  6744. }
  6745. const devBase = withTrailingSlash(base);
  6746. return path2.startsWith(devBase) ? path2.slice(devBase.length - 1) : path2;
  6747. }
  6748. function arrayEqual(a, b) {
  6749. if (a === b) return true;
  6750. if (a.length !== b.length) return false;
  6751. for (let i = 0; i < a.length; i++) {
  6752. if (a[i] !== b[i]) return false;
  6753. }
  6754. return true;
  6755. }
  6756. function evalValue(rawValue) {
  6757. const fn = new Function(`
  6758. var console, exports, global, module, process, require
  6759. return (
  6760. ${rawValue}
  6761. )
  6762. `);
  6763. return fn();
  6764. }
  6765. function getNpmPackageName(importPath) {
  6766. const parts = importPath.split("/");
  6767. if (parts[0][0] === "@") {
  6768. if (!parts[1]) return null;
  6769. return `${parts[0]}/${parts[1]}`;
  6770. } else {
  6771. return parts[0];
  6772. }
  6773. }
  6774. function getPkgName(name) {
  6775. return name[0] === "@" ? name.split("/")[1] : name;
  6776. }
  6777. const escapeRegexRE = /[-/\\^$*+?.()|[\]{}]/g;
  6778. function escapeRegex(str) {
  6779. return str.replace(escapeRegexRE, "\\$&");
  6780. }
  6781. function getPackageManagerCommand(type = "install") {
  6782. const packageManager = process.env.npm_config_user_agent?.split(" ")[0].split("/")[0] || "npm";
  6783. switch (type) {
  6784. case "install":
  6785. return packageManager === "npm" ? "npm install" : `${packageManager} add`;
  6786. case "uninstall":
  6787. return packageManager === "npm" ? "npm uninstall" : `${packageManager} remove`;
  6788. case "update":
  6789. return packageManager === "yarn" ? "yarn upgrade" : `${packageManager} update`;
  6790. default:
  6791. throw new TypeError(`Unknown command type: ${type}`);
  6792. }
  6793. }
  6794. function isDevServer(server) {
  6795. return "pluginContainer" in server;
  6796. }
  6797. function createSerialPromiseQueue() {
  6798. let previousTask;
  6799. return {
  6800. async run(f) {
  6801. const thisTask = f();
  6802. const depTasks = Promise.all([previousTask, thisTask]);
  6803. previousTask = depTasks;
  6804. const [, result] = await depTasks;
  6805. if (previousTask === depTasks) {
  6806. previousTask = void 0;
  6807. }
  6808. return result;
  6809. }
  6810. };
  6811. }
  6812. function sortObjectKeys(obj) {
  6813. const sorted = {};
  6814. for (const key of Object.keys(obj).sort()) {
  6815. sorted[key] = obj[key];
  6816. }
  6817. return sorted;
  6818. }
  6819. function displayTime(time) {
  6820. if (time < 1e3) {
  6821. return `${time}ms`;
  6822. }
  6823. time = time / 1e3;
  6824. if (time < 60) {
  6825. return `${time.toFixed(2)}s`;
  6826. }
  6827. const mins = Math.floor(time / 60);
  6828. const seconds = Math.round(time % 60);
  6829. if (seconds === 60) {
  6830. return `${mins + 1}m`;
  6831. }
  6832. return `${mins}m${seconds < 1 ? "" : ` ${seconds}s`}`;
  6833. }
  6834. function encodeURIPath(uri) {
  6835. if (uri.startsWith("data:")) return uri;
  6836. const filePath = cleanUrl(uri);
  6837. const postfix = filePath !== uri ? uri.slice(filePath.length) : "";
  6838. return encodeURI(filePath) + postfix;
  6839. }
  6840. function partialEncodeURIPath(uri) {
  6841. if (uri.startsWith("data:")) return uri;
  6842. const filePath = cleanUrl(uri);
  6843. const postfix = filePath !== uri ? uri.slice(filePath.length) : "";
  6844. return filePath.replaceAll("%", "%25") + postfix;
  6845. }
  6846. const sigtermCallbacks = /* @__PURE__ */ new Set();
  6847. const parentSigtermCallback = async (signal, exitCode) => {
  6848. await Promise.all([...sigtermCallbacks].map((cb) => cb(signal, exitCode)));
  6849. };
  6850. const setupSIGTERMListener = (callback) => {
  6851. if (sigtermCallbacks.size === 0) {
  6852. process.once("SIGTERM", parentSigtermCallback);
  6853. if (process.env.CI !== "true") {
  6854. process.stdin.on("end", parentSigtermCallback);
  6855. }
  6856. }
  6857. sigtermCallbacks.add(callback);
  6858. };
  6859. const teardownSIGTERMListener = (callback) => {
  6860. sigtermCallbacks.delete(callback);
  6861. if (sigtermCallbacks.size === 0) {
  6862. process.off("SIGTERM", parentSigtermCallback);
  6863. if (process.env.CI !== "true") {
  6864. process.stdin.off("end", parentSigtermCallback);
  6865. }
  6866. }
  6867. };
  6868. function getServerUrlByHost(resolvedUrls, host) {
  6869. if (typeof host === "string") {
  6870. const matchedUrl = [
  6871. ...resolvedUrls?.local ?? [],
  6872. ...resolvedUrls?.network ?? []
  6873. ].find((url) => url.includes(host));
  6874. if (matchedUrl) {
  6875. return matchedUrl;
  6876. }
  6877. }
  6878. return resolvedUrls?.local[0] ?? resolvedUrls?.network[0];
  6879. }
  6880. const LogLevels = {
  6881. silent: 0,
  6882. error: 1,
  6883. warn: 2,
  6884. info: 3
  6885. };
  6886. let lastType;
  6887. let lastMsg;
  6888. let sameCount = 0;
  6889. function clearScreen() {
  6890. const repeatCount = process.stdout.rows - 2;
  6891. const blank = repeatCount > 0 ? "\n".repeat(repeatCount) : "";
  6892. console.log(blank);
  6893. readline.cursorTo(process.stdout, 0, 0);
  6894. readline.clearScreenDown(process.stdout);
  6895. }
  6896. let timeFormatter;
  6897. function getTimeFormatter() {
  6898. timeFormatter ??= new Intl.DateTimeFormat(void 0, {
  6899. hour: "numeric",
  6900. minute: "numeric",
  6901. second: "numeric"
  6902. });
  6903. return timeFormatter;
  6904. }
  6905. function createLogger(level = "info", options = {}) {
  6906. if (options.customLogger) {
  6907. return options.customLogger;
  6908. }
  6909. const loggedErrors = /* @__PURE__ */ new WeakSet();
  6910. const {
  6911. prefix = "[vite]",
  6912. allowClearScreen = true,
  6913. console: console2 = globalThis.console
  6914. } = options;
  6915. const thresh = LogLevels[level];
  6916. const canClearScreen = allowClearScreen && process.stdout.isTTY && !process.env.CI;
  6917. const clear = canClearScreen ? clearScreen : () => {
  6918. };
  6919. function format(type, msg, options2 = {}) {
  6920. if (options2.timestamp) {
  6921. let tag = "";
  6922. if (type === "info") {
  6923. tag = colors$1.cyan(colors$1.bold(prefix));
  6924. } else if (type === "warn") {
  6925. tag = colors$1.yellow(colors$1.bold(prefix));
  6926. } else {
  6927. tag = colors$1.red(colors$1.bold(prefix));
  6928. }
  6929. const environment = options2.environment ? options2.environment + " " : "";
  6930. return `${colors$1.dim(getTimeFormatter().format(/* @__PURE__ */ new Date()))} ${tag} ${environment}${msg}`;
  6931. } else {
  6932. return msg;
  6933. }
  6934. }
  6935. function output(type, msg, options2 = {}) {
  6936. if (thresh >= LogLevels[type]) {
  6937. const method = type === "info" ? "log" : type;
  6938. if (options2.error) {
  6939. loggedErrors.add(options2.error);
  6940. }
  6941. if (canClearScreen) {
  6942. if (type === lastType && msg === lastMsg) {
  6943. sameCount++;
  6944. clear();
  6945. console2[method](
  6946. format(type, msg, options2),
  6947. colors$1.yellow(`(x${sameCount + 1})`)
  6948. );
  6949. } else {
  6950. sameCount = 0;
  6951. lastMsg = msg;
  6952. lastType = type;
  6953. if (options2.clear) {
  6954. clear();
  6955. }
  6956. console2[method](format(type, msg, options2));
  6957. }
  6958. } else {
  6959. console2[method](format(type, msg, options2));
  6960. }
  6961. }
  6962. }
  6963. const warnedMessages = /* @__PURE__ */ new Set();
  6964. const logger = {
  6965. hasWarned: false,
  6966. info(msg, opts) {
  6967. output("info", msg, opts);
  6968. },
  6969. warn(msg, opts) {
  6970. logger.hasWarned = true;
  6971. output("warn", msg, opts);
  6972. },
  6973. warnOnce(msg, opts) {
  6974. if (warnedMessages.has(msg)) return;
  6975. logger.hasWarned = true;
  6976. output("warn", msg, opts);
  6977. warnedMessages.add(msg);
  6978. },
  6979. error(msg, opts) {
  6980. logger.hasWarned = true;
  6981. output("error", msg, opts);
  6982. },
  6983. clearScreen(type) {
  6984. if (thresh >= LogLevels[type]) {
  6985. clear();
  6986. }
  6987. },
  6988. hasErrorLogged(error) {
  6989. return loggedErrors.has(error);
  6990. }
  6991. };
  6992. return logger;
  6993. }
  6994. function printServerUrls(urls, optionsHost, info) {
  6995. const colorUrl = (url) => colors$1.cyan(url.replace(/:(\d+)\//, (_, port) => `:${colors$1.bold(port)}/`));
  6996. for (const url of urls.local) {
  6997. info(` ${colors$1.green("\u279C")} ${colors$1.bold("Local")}: ${colorUrl(url)}`);
  6998. }
  6999. for (const url of urls.network) {
  7000. info(` ${colors$1.green("\u279C")} ${colors$1.bold("Network")}: ${colorUrl(url)}`);
  7001. }
  7002. if (urls.network.length === 0 && optionsHost === void 0) {
  7003. info(
  7004. colors$1.dim(` ${colors$1.green("\u279C")} ${colors$1.bold("Network")}: use `) + colors$1.bold("--host") + colors$1.dim(" to expose")
  7005. );
  7006. }
  7007. }
  7008. const groups = [
  7009. { name: "Assets", color: colors$1.green },
  7010. { name: "CSS", color: colors$1.magenta },
  7011. { name: "JS", color: colors$1.cyan }
  7012. ];
  7013. const COMPRESSIBLE_ASSETS_RE = /\.(?:html|json|svg|txt|xml|xhtml|wasm)$/;
  7014. function buildReporterPlugin(config) {
  7015. const compress = promisify$4(gzip);
  7016. const numberFormatter = new Intl.NumberFormat("en", {
  7017. maximumFractionDigits: 2,
  7018. minimumFractionDigits: 2
  7019. });
  7020. const displaySize = (bytes) => {
  7021. return `${numberFormatter.format(bytes / 1e3)} kB`;
  7022. };
  7023. const tty = process.stdout.isTTY && !process.env.CI;
  7024. const shouldLogInfo = LogLevels[config.logLevel || "info"] >= LogLevels.info;
  7025. const modulesReporter = shouldLogInfo ? perEnvironmentState((environment) => {
  7026. let hasTransformed = false;
  7027. let transformedCount = 0;
  7028. const logTransform = throttle((id) => {
  7029. writeLine(
  7030. `transforming (${transformedCount}) ${colors$1.dim(
  7031. path$b.relative(config.root, id)
  7032. )}`
  7033. );
  7034. });
  7035. return {
  7036. reset() {
  7037. transformedCount = 0;
  7038. },
  7039. register(id) {
  7040. transformedCount++;
  7041. if (!tty) {
  7042. if (!hasTransformed) {
  7043. config.logger.info(`transforming...`);
  7044. }
  7045. } else {
  7046. if (id.includes(`?`)) return;
  7047. logTransform(id);
  7048. }
  7049. hasTransformed = true;
  7050. },
  7051. log() {
  7052. if (tty) {
  7053. clearLine$1();
  7054. }
  7055. environment.logger.info(
  7056. `${colors$1.green(`\u2713`)} ${transformedCount} modules transformed.`
  7057. );
  7058. }
  7059. };
  7060. }) : void 0;
  7061. const chunksReporter = perEnvironmentState((environment) => {
  7062. let hasRenderedChunk = false;
  7063. let hasCompressChunk = false;
  7064. let chunkCount = 0;
  7065. let compressedCount = 0;
  7066. async function getCompressedSize(code) {
  7067. if (environment.config.consumer !== "client" || !environment.config.build.reportCompressedSize) {
  7068. return null;
  7069. }
  7070. if (shouldLogInfo && !hasCompressChunk) {
  7071. if (!tty) {
  7072. config.logger.info("computing gzip size...");
  7073. } else {
  7074. writeLine("computing gzip size (0)...");
  7075. }
  7076. hasCompressChunk = true;
  7077. }
  7078. const compressed = await compress(
  7079. typeof code === "string" ? code : Buffer.from(code)
  7080. );
  7081. compressedCount++;
  7082. if (shouldLogInfo && tty) {
  7083. writeLine(`computing gzip size (${compressedCount})...`);
  7084. }
  7085. return compressed.length;
  7086. }
  7087. return {
  7088. reset() {
  7089. chunkCount = 0;
  7090. compressedCount = 0;
  7091. },
  7092. register() {
  7093. chunkCount++;
  7094. if (shouldLogInfo) {
  7095. if (!tty) {
  7096. if (!hasRenderedChunk) {
  7097. environment.logger.info("rendering chunks...");
  7098. }
  7099. } else {
  7100. writeLine(`rendering chunks (${chunkCount})...`);
  7101. }
  7102. hasRenderedChunk = true;
  7103. }
  7104. },
  7105. async log(output, outDir) {
  7106. const chunkLimit = environment.config.build.chunkSizeWarningLimit;
  7107. let hasLargeChunks = false;
  7108. if (shouldLogInfo) {
  7109. const entries = (await Promise.all(
  7110. Object.values(output).map(
  7111. async (chunk) => {
  7112. if (chunk.type === "chunk") {
  7113. return {
  7114. name: chunk.fileName,
  7115. group: "JS",
  7116. size: Buffer.byteLength(chunk.code),
  7117. compressedSize: await getCompressedSize(chunk.code),
  7118. mapSize: chunk.map ? Buffer.byteLength(chunk.map.toString()) : null
  7119. };
  7120. } else {
  7121. if (chunk.fileName.endsWith(".map")) return null;
  7122. const isCSS = chunk.fileName.endsWith(".css");
  7123. const isCompressible = isCSS || COMPRESSIBLE_ASSETS_RE.test(chunk.fileName);
  7124. return {
  7125. name: chunk.fileName,
  7126. group: isCSS ? "CSS" : "Assets",
  7127. size: Buffer.byteLength(chunk.source),
  7128. mapSize: null,
  7129. // Rollup doesn't support CSS maps?
  7130. compressedSize: isCompressible ? await getCompressedSize(chunk.source) : null
  7131. };
  7132. }
  7133. }
  7134. )
  7135. )).filter(isDefined);
  7136. if (tty) clearLine$1();
  7137. let longest = 0;
  7138. let biggestSize = 0;
  7139. let biggestMap = 0;
  7140. let biggestCompressSize = 0;
  7141. for (const entry of entries) {
  7142. if (entry.name.length > longest) longest = entry.name.length;
  7143. if (entry.size > biggestSize) biggestSize = entry.size;
  7144. if (entry.mapSize && entry.mapSize > biggestMap) {
  7145. biggestMap = entry.mapSize;
  7146. }
  7147. if (entry.compressedSize && entry.compressedSize > biggestCompressSize) {
  7148. biggestCompressSize = entry.compressedSize;
  7149. }
  7150. }
  7151. const sizePad = displaySize(biggestSize).length;
  7152. const mapPad = displaySize(biggestMap).length;
  7153. const compressPad = displaySize(biggestCompressSize).length;
  7154. const relativeOutDir = normalizePath$3(
  7155. path$b.relative(
  7156. config.root,
  7157. path$b.resolve(
  7158. config.root,
  7159. outDir ?? environment.config.build.outDir
  7160. )
  7161. )
  7162. );
  7163. const assetsDir = path$b.join(environment.config.build.assetsDir, "/");
  7164. for (const group of groups) {
  7165. const filtered = entries.filter((e) => e.group === group.name);
  7166. if (!filtered.length) continue;
  7167. for (const entry of filtered.sort((a, z) => a.size - z.size)) {
  7168. const isLarge = group.name === "JS" && entry.size / 1e3 > chunkLimit;
  7169. if (isLarge) hasLargeChunks = true;
  7170. const sizeColor = isLarge ? colors$1.yellow : colors$1.dim;
  7171. let log = colors$1.dim(withTrailingSlash(relativeOutDir));
  7172. log += !config.build.lib && entry.name.startsWith(withTrailingSlash(assetsDir)) ? colors$1.dim(assetsDir) + group.color(
  7173. entry.name.slice(assetsDir.length).padEnd(longest + 2 - assetsDir.length)
  7174. ) : group.color(entry.name.padEnd(longest + 2));
  7175. log += colors$1.bold(
  7176. sizeColor(displaySize(entry.size).padStart(sizePad))
  7177. );
  7178. if (entry.compressedSize) {
  7179. log += colors$1.dim(
  7180. ` \u2502 gzip: ${displaySize(entry.compressedSize).padStart(
  7181. compressPad
  7182. )}`
  7183. );
  7184. }
  7185. if (entry.mapSize) {
  7186. log += colors$1.dim(
  7187. ` \u2502 map: ${displaySize(entry.mapSize).padStart(mapPad)}`
  7188. );
  7189. }
  7190. config.logger.info(log);
  7191. }
  7192. }
  7193. } else {
  7194. hasLargeChunks = Object.values(output).some((chunk) => {
  7195. return chunk.type === "chunk" && chunk.code.length / 1e3 > chunkLimit;
  7196. });
  7197. }
  7198. if (hasLargeChunks && environment.config.build.minify && !config.build.lib && environment.config.consumer === "client") {
  7199. environment.logger.warn(
  7200. colors$1.yellow(
  7201. `
  7202. (!) Some chunks are larger than ${chunkLimit} kB after minification. Consider:
  7203. - Using dynamic import() to code-split the application
  7204. - Use build.rollupOptions.output.manualChunks to improve chunking: https://rollupjs.org/configuration-options/#output-manualchunks
  7205. - Adjust chunk size limit for this warning via build.chunkSizeWarningLimit.`
  7206. )
  7207. );
  7208. }
  7209. }
  7210. };
  7211. });
  7212. return {
  7213. name: "vite:reporter",
  7214. sharedDuringBuild: true,
  7215. perEnvironmentStartEndDuringDev: true,
  7216. ...modulesReporter ? {
  7217. transform(_, id) {
  7218. modulesReporter(this).register(id);
  7219. },
  7220. buildStart() {
  7221. modulesReporter(this).reset();
  7222. },
  7223. buildEnd() {
  7224. modulesReporter(this).log();
  7225. }
  7226. } : {},
  7227. renderStart() {
  7228. chunksReporter(this).reset();
  7229. },
  7230. renderChunk(_, chunk, options) {
  7231. if (!options.inlineDynamicImports) {
  7232. for (const id of chunk.moduleIds) {
  7233. const module = this.getModuleInfo(id);
  7234. if (!module) continue;
  7235. if (module.importers.length && module.dynamicImporters.length) {
  7236. const detectedIneffectiveDynamicImport = module.dynamicImporters.some(
  7237. (id2) => !isInNodeModules$1(id2) && chunk.moduleIds.includes(id2)
  7238. );
  7239. if (detectedIneffectiveDynamicImport) {
  7240. this.warn(
  7241. `
  7242. (!) ${module.id} is dynamically imported by ${module.dynamicImporters.join(
  7243. ", "
  7244. )} but also statically imported by ${module.importers.join(
  7245. ", "
  7246. )}, dynamic import will not move module into another chunk.
  7247. `
  7248. );
  7249. }
  7250. }
  7251. }
  7252. }
  7253. chunksReporter(this).register();
  7254. },
  7255. generateBundle() {
  7256. if (shouldLogInfo && tty) clearLine$1();
  7257. },
  7258. async writeBundle({ dir }, output) {
  7259. await chunksReporter(this).log(output, dir);
  7260. }
  7261. };
  7262. }
  7263. function writeLine(output) {
  7264. clearLine$1();
  7265. if (output.length < process.stdout.columns) {
  7266. process.stdout.write(output);
  7267. } else {
  7268. process.stdout.write(output.substring(0, process.stdout.columns - 1));
  7269. }
  7270. }
  7271. function clearLine$1() {
  7272. process.stdout.clearLine(0);
  7273. process.stdout.cursorTo(0);
  7274. }
  7275. function throttle(fn) {
  7276. let timerHandle = null;
  7277. return (...args) => {
  7278. if (timerHandle) return;
  7279. fn(...args);
  7280. timerHandle = setTimeout(() => {
  7281. timerHandle = null;
  7282. }, 100);
  7283. };
  7284. }
  7285. const POSIX_SEP_RE = new RegExp('\\' + path$b.posix.sep, 'g');
  7286. const NATIVE_SEP_RE = new RegExp('\\' + path$b.sep, 'g');
  7287. /** @type {Map<string,RegExp>}*/
  7288. const PATTERN_REGEX_CACHE = new Map();
  7289. const GLOB_ALL_PATTERN = `**/*`;
  7290. const TS_EXTENSIONS = ['.ts', '.tsx', '.mts', '.cts'];
  7291. const JS_EXTENSIONS = ['.js', '.jsx', '.mjs', '.cjs'];
  7292. const TSJS_EXTENSIONS = TS_EXTENSIONS.concat(JS_EXTENSIONS);
  7293. const TS_EXTENSIONS_RE_GROUP = `\\.(?:${TS_EXTENSIONS.map((ext) => ext.substring(1)).join('|')})`;
  7294. const TSJS_EXTENSIONS_RE_GROUP = `\\.(?:${TSJS_EXTENSIONS.map((ext) => ext.substring(1)).join(
  7295. '|'
  7296. )})`;
  7297. const IS_POSIX = path$b.posix.sep === path$b.sep;
  7298. /**
  7299. * @template T
  7300. * @returns {{resolve:(result:T)=>void, reject:(error:any)=>void, promise: Promise<T>}}
  7301. */
  7302. function makePromise() {
  7303. let resolve, reject;
  7304. const promise = new Promise((res, rej) => {
  7305. resolve = res;
  7306. reject = rej;
  7307. });
  7308. return { promise, resolve, reject };
  7309. }
  7310. /**
  7311. * @param {string} filename
  7312. * @param {import('./cache.js').TSConfckCache} [cache]
  7313. * @returns {Promise<string|void>}
  7314. */
  7315. async function resolveTSConfigJson(filename, cache) {
  7316. if (path$b.extname(filename) !== '.json') {
  7317. return; // ignore files that are not json
  7318. }
  7319. const tsconfig = path$b.resolve(filename);
  7320. if (cache && (cache.hasParseResult(tsconfig) || cache.hasParseResult(filename))) {
  7321. return tsconfig;
  7322. }
  7323. return promises$1.stat(tsconfig).then((stat) => {
  7324. if (stat.isFile() || stat.isFIFO()) {
  7325. return tsconfig;
  7326. } else {
  7327. throw new Error(`${filename} exists but is not a regular file.`);
  7328. }
  7329. });
  7330. }
  7331. /**
  7332. *
  7333. * @param {string} dir an absolute directory path
  7334. * @returns {boolean} if dir path includes a node_modules segment
  7335. */
  7336. const isInNodeModules = IS_POSIX
  7337. ? (dir) => dir.includes('/node_modules/')
  7338. : (dir) => dir.match(/[/\\]node_modules[/\\]/);
  7339. /**
  7340. * convert posix separator to native separator
  7341. *
  7342. * eg.
  7343. * windows: C:/foo/bar -> c:\foo\bar
  7344. * linux: /foo/bar -> /foo/bar
  7345. *
  7346. * @param {string} filename with posix separators
  7347. * @returns {string} filename with native separators
  7348. */
  7349. const posix2native = IS_POSIX
  7350. ? (filename) => filename
  7351. : (filename) => filename.replace(POSIX_SEP_RE, path$b.sep);
  7352. /**
  7353. * convert native separator to posix separator
  7354. *
  7355. * eg.
  7356. * windows: C:\foo\bar -> c:/foo/bar
  7357. * linux: /foo/bar -> /foo/bar
  7358. *
  7359. * @param {string} filename - filename with native separators
  7360. * @returns {string} filename with posix separators
  7361. */
  7362. const native2posix = IS_POSIX
  7363. ? (filename) => filename
  7364. : (filename) => filename.replace(NATIVE_SEP_RE, path$b.posix.sep);
  7365. /**
  7366. * converts params to native separator, resolves path and converts native back to posix
  7367. *
  7368. * needed on windows to handle posix paths in tsconfig
  7369. *
  7370. * @param dir {string|null} directory to resolve from
  7371. * @param filename {string} filename or pattern to resolve
  7372. * @returns string
  7373. */
  7374. const resolve2posix = IS_POSIX
  7375. ? (dir, filename) => (dir ? path$b.resolve(dir, filename) : path$b.resolve(filename))
  7376. : (dir, filename) =>
  7377. native2posix(
  7378. dir
  7379. ? path$b.resolve(posix2native(dir), posix2native(filename))
  7380. : path$b.resolve(posix2native(filename))
  7381. );
  7382. /**
  7383. *
  7384. * @param {import('./public.d.ts').TSConfckParseResult} result
  7385. * @param {import('./public.d.ts').TSConfckParseOptions} [options]
  7386. * @returns {string[]}
  7387. */
  7388. function resolveReferencedTSConfigFiles(result, options) {
  7389. const dir = path$b.dirname(result.tsconfigFile);
  7390. return result.tsconfig.references.map((ref) => {
  7391. const refPath = ref.path.endsWith('.json')
  7392. ? ref.path
  7393. : path$b.join(ref.path, options?.configName ?? 'tsconfig.json');
  7394. return resolve2posix(dir, refPath);
  7395. });
  7396. }
  7397. /**
  7398. * @param {string} filename
  7399. * @param {import('./public.d.ts').TSConfckParseResult} result
  7400. * @returns {import('./public.d.ts').TSConfckParseResult}
  7401. */
  7402. function resolveSolutionTSConfig(filename, result) {
  7403. const allowJs = result.tsconfig.compilerOptions?.allowJs;
  7404. const extensions = allowJs ? TSJS_EXTENSIONS : TS_EXTENSIONS;
  7405. if (
  7406. result.referenced &&
  7407. extensions.some((ext) => filename.endsWith(ext)) &&
  7408. !isIncluded(filename, result)
  7409. ) {
  7410. const solutionTSConfig = result.referenced.find((referenced) =>
  7411. isIncluded(filename, referenced)
  7412. );
  7413. if (solutionTSConfig) {
  7414. return solutionTSConfig;
  7415. }
  7416. }
  7417. return result;
  7418. }
  7419. /**
  7420. *
  7421. * @param {string} filename
  7422. * @param {import('./public.d.ts').TSConfckParseResult} result
  7423. * @returns {boolean}
  7424. */
  7425. function isIncluded(filename, result) {
  7426. const dir = native2posix(path$b.dirname(result.tsconfigFile));
  7427. const files = (result.tsconfig.files || []).map((file) => resolve2posix(dir, file));
  7428. const absoluteFilename = resolve2posix(null, filename);
  7429. if (files.includes(filename)) {
  7430. return true;
  7431. }
  7432. const allowJs = result.tsconfig.compilerOptions?.allowJs;
  7433. const isIncluded = isGlobMatch(
  7434. absoluteFilename,
  7435. dir,
  7436. result.tsconfig.include || (result.tsconfig.files ? [] : [GLOB_ALL_PATTERN]),
  7437. allowJs
  7438. );
  7439. if (isIncluded) {
  7440. const isExcluded = isGlobMatch(absoluteFilename, dir, result.tsconfig.exclude || [], allowJs);
  7441. return !isExcluded;
  7442. }
  7443. return false;
  7444. }
  7445. /**
  7446. * test filenames agains glob patterns in tsconfig
  7447. *
  7448. * @param filename {string} posix style abolute path to filename to test
  7449. * @param dir {string} posix style absolute path to directory of tsconfig containing patterns
  7450. * @param patterns {string[]} glob patterns to match against
  7451. * @param allowJs {boolean} allowJs setting in tsconfig to include js extensions in checks
  7452. * @returns {boolean} true when at least one pattern matches filename
  7453. */
  7454. function isGlobMatch(filename, dir, patterns, allowJs) {
  7455. const extensions = allowJs ? TSJS_EXTENSIONS : TS_EXTENSIONS;
  7456. return patterns.some((pattern) => {
  7457. // filename must end with part of pattern that comes after last wildcard
  7458. let lastWildcardIndex = pattern.length;
  7459. let hasWildcard = false;
  7460. let hasExtension = false;
  7461. let hasSlash = false;
  7462. let lastSlashIndex = -1;
  7463. for (let i = pattern.length - 1; i > -1; i--) {
  7464. const c = pattern[i];
  7465. if (!hasWildcard) {
  7466. if (c === '*' || c === '?') {
  7467. lastWildcardIndex = i;
  7468. hasWildcard = true;
  7469. }
  7470. }
  7471. if (!hasSlash) {
  7472. if (c === '.') {
  7473. hasExtension = true;
  7474. } else if (c === '/') {
  7475. lastSlashIndex = i;
  7476. hasSlash = true;
  7477. }
  7478. }
  7479. if (hasWildcard && hasSlash) {
  7480. break;
  7481. }
  7482. }
  7483. if (!hasExtension && (!hasWildcard || lastWildcardIndex < lastSlashIndex)) {
  7484. // add implicit glob
  7485. pattern += `${pattern.endsWith('/') ? '' : '/'}${GLOB_ALL_PATTERN}`;
  7486. lastWildcardIndex = pattern.length - 1;
  7487. hasWildcard = true;
  7488. }
  7489. // if pattern does not end with wildcard, filename must end with pattern after last wildcard
  7490. if (
  7491. lastWildcardIndex < pattern.length - 1 &&
  7492. !filename.endsWith(pattern.slice(lastWildcardIndex + 1))
  7493. ) {
  7494. return false;
  7495. }
  7496. // if pattern ends with *, filename must end with a default extension
  7497. if (pattern.endsWith('*') && !extensions.some((ext) => filename.endsWith(ext))) {
  7498. return false;
  7499. }
  7500. // for **/* , filename must start with the dir
  7501. if (pattern === GLOB_ALL_PATTERN) {
  7502. return filename.startsWith(`${dir}/`);
  7503. }
  7504. const resolvedPattern = resolve2posix(dir, pattern);
  7505. // filename must start with part of pattern that comes before first wildcard
  7506. let firstWildcardIndex = -1;
  7507. for (let i = 0; i < resolvedPattern.length; i++) {
  7508. if (resolvedPattern[i] === '*' || resolvedPattern[i] === '?') {
  7509. firstWildcardIndex = i;
  7510. hasWildcard = true;
  7511. break;
  7512. }
  7513. }
  7514. if (
  7515. firstWildcardIndex > 1 &&
  7516. !filename.startsWith(resolvedPattern.slice(0, firstWildcardIndex - 1))
  7517. ) {
  7518. return false;
  7519. }
  7520. if (!hasWildcard) {
  7521. // no wildcard in pattern, filename must be equal to resolved pattern
  7522. return filename === resolvedPattern;
  7523. } else if (
  7524. firstWildcardIndex + GLOB_ALL_PATTERN.length ===
  7525. resolvedPattern.length - (pattern.length - 1 - lastWildcardIndex) &&
  7526. resolvedPattern.slice(firstWildcardIndex, firstWildcardIndex + GLOB_ALL_PATTERN.length) ===
  7527. GLOB_ALL_PATTERN
  7528. ) {
  7529. // singular glob-all pattern and we already validated prefix and suffix matches
  7530. return true;
  7531. }
  7532. // complex pattern, use regex to check it
  7533. if (PATTERN_REGEX_CACHE.has(resolvedPattern)) {
  7534. return PATTERN_REGEX_CACHE.get(resolvedPattern).test(filename);
  7535. }
  7536. const regex = pattern2regex(resolvedPattern, allowJs);
  7537. PATTERN_REGEX_CACHE.set(resolvedPattern, regex);
  7538. return regex.test(filename);
  7539. });
  7540. }
  7541. /**
  7542. * @param {string} resolvedPattern
  7543. * @param {boolean} allowJs
  7544. * @returns {RegExp}
  7545. */
  7546. function pattern2regex(resolvedPattern, allowJs) {
  7547. let regexStr = '^';
  7548. for (let i = 0; i < resolvedPattern.length; i++) {
  7549. const char = resolvedPattern[i];
  7550. if (char === '?') {
  7551. regexStr += '[^\\/]';
  7552. continue;
  7553. }
  7554. if (char === '*') {
  7555. if (resolvedPattern[i + 1] === '*' && resolvedPattern[i + 2] === '/') {
  7556. i += 2;
  7557. regexStr += '(?:[^\\/]*\\/)*'; // zero or more path segments
  7558. continue;
  7559. }
  7560. regexStr += '[^\\/]*';
  7561. continue;
  7562. }
  7563. if ('/.+^${}()|[]\\'.includes(char)) {
  7564. regexStr += `\\`;
  7565. }
  7566. regexStr += char;
  7567. }
  7568. // add known file endings if pattern ends on *
  7569. if (resolvedPattern.endsWith('*')) {
  7570. regexStr += allowJs ? TSJS_EXTENSIONS_RE_GROUP : TS_EXTENSIONS_RE_GROUP;
  7571. }
  7572. regexStr += '$';
  7573. return new RegExp(regexStr);
  7574. }
  7575. /**
  7576. * replace tokens like ${configDir}
  7577. * @param {import('./public.d.ts').TSConfckParseResult} result
  7578. */
  7579. function replaceTokens(result) {
  7580. if (result.tsconfig) {
  7581. result.tsconfig = JSON.parse(
  7582. JSON.stringify(result.tsconfig)
  7583. // replace ${configDir}
  7584. .replaceAll(/"\${configDir}/g, `"${native2posix(path$b.dirname(result.tsconfigFile))}`)
  7585. );
  7586. }
  7587. }
  7588. /**
  7589. * find the closest tsconfig.json file
  7590. *
  7591. * @param {string} filename - path to file to find tsconfig for (absolute or relative to cwd)
  7592. * @param {import('./public.d.ts').TSConfckFindOptions} [options] - options
  7593. * @returns {Promise<string|null>} absolute path to closest tsconfig.json or null if not found
  7594. */
  7595. async function find(filename, options) {
  7596. let dir = path$b.dirname(path$b.resolve(filename));
  7597. if (isInNodeModules(dir)) {
  7598. return null;
  7599. }
  7600. const cache = options?.cache;
  7601. const configName = options?.configName ?? 'tsconfig.json';
  7602. if (cache?.hasConfigPath(dir, configName)) {
  7603. return cache.getConfigPath(dir, configName);
  7604. }
  7605. const { /** @type {Promise<string|null>} */ promise, resolve, reject } = makePromise();
  7606. if (options?.root && !path$b.isAbsolute(options.root)) {
  7607. options.root = path$b.resolve(options.root);
  7608. }
  7609. findUp(dir, { promise, resolve, reject }, options);
  7610. return promise;
  7611. }
  7612. /**
  7613. *
  7614. * @param {string} dir
  7615. * @param {{promise:Promise<string|null>,resolve:(result:string|null)=>void,reject:(err:any)=>void}} madePromise
  7616. * @param {import('./public.d.ts').TSConfckFindOptions} [options] - options
  7617. */
  7618. function findUp(dir, { resolve, reject, promise }, options) {
  7619. const { cache, root, configName } = options ?? {};
  7620. if (cache) {
  7621. if (cache.hasConfigPath(dir, configName)) {
  7622. let cached;
  7623. try {
  7624. cached = cache.getConfigPath(dir, configName);
  7625. } catch (e) {
  7626. reject(e);
  7627. return;
  7628. }
  7629. if (cached?.then) {
  7630. cached.then(resolve).catch(reject);
  7631. } else {
  7632. resolve(cached);
  7633. }
  7634. } else {
  7635. cache.setConfigPath(dir, promise, configName);
  7636. }
  7637. }
  7638. const tsconfig = path$b.join(dir, options?.configName ?? 'tsconfig.json');
  7639. fs__default.stat(tsconfig, (err, stats) => {
  7640. if (stats && (stats.isFile() || stats.isFIFO())) {
  7641. resolve(tsconfig);
  7642. } else if (err?.code !== 'ENOENT') {
  7643. reject(err);
  7644. } else {
  7645. let parent;
  7646. if (root === dir || (parent = path$b.dirname(dir)) === dir) {
  7647. resolve(null);
  7648. } else {
  7649. findUp(parent, { promise, resolve, reject }, options);
  7650. }
  7651. }
  7652. });
  7653. }
  7654. /*
  7655. this file contains code from strip-bom and strip-json-comments by Sindre Sorhus
  7656. https://github.com/sindresorhus/strip-json-comments/blob/v4.0.0/index.js
  7657. https://github.com/sindresorhus/strip-bom/blob/v5.0.0/index.js
  7658. licensed under MIT, see ../LICENSE
  7659. */
  7660. /**
  7661. * convert content of tsconfig.json to regular json
  7662. *
  7663. * @param {string} tsconfigJson - content of tsconfig.json
  7664. * @returns {string} content as regular json, comments and dangling commas have been replaced with whitespace
  7665. */
  7666. function toJson(tsconfigJson) {
  7667. const stripped = stripDanglingComma(stripJsonComments(stripBom(tsconfigJson)));
  7668. if (stripped.trim() === '') {
  7669. // only whitespace left after stripping, return empty object so that JSON.parse still works
  7670. return '{}';
  7671. } else {
  7672. return stripped;
  7673. }
  7674. }
  7675. /**
  7676. * replace dangling commas from pseudo-json string with single space
  7677. * implementation heavily inspired by strip-json-comments
  7678. *
  7679. * @param {string} pseudoJson
  7680. * @returns {string}
  7681. */
  7682. function stripDanglingComma(pseudoJson) {
  7683. let insideString = false;
  7684. let offset = 0;
  7685. let result = '';
  7686. let danglingCommaPos = null;
  7687. for (let i = 0; i < pseudoJson.length; i++) {
  7688. const currentCharacter = pseudoJson[i];
  7689. if (currentCharacter === '"') {
  7690. const escaped = isEscaped(pseudoJson, i);
  7691. if (!escaped) {
  7692. insideString = !insideString;
  7693. }
  7694. }
  7695. if (insideString) {
  7696. danglingCommaPos = null;
  7697. continue;
  7698. }
  7699. if (currentCharacter === ',') {
  7700. danglingCommaPos = i;
  7701. continue;
  7702. }
  7703. if (danglingCommaPos) {
  7704. if (currentCharacter === '}' || currentCharacter === ']') {
  7705. result += pseudoJson.slice(offset, danglingCommaPos) + ' ';
  7706. offset = danglingCommaPos + 1;
  7707. danglingCommaPos = null;
  7708. } else if (!currentCharacter.match(/\s/)) {
  7709. danglingCommaPos = null;
  7710. }
  7711. }
  7712. }
  7713. return result + pseudoJson.substring(offset);
  7714. }
  7715. // start strip-json-comments
  7716. /**
  7717. *
  7718. * @param {string} jsonString
  7719. * @param {number} quotePosition
  7720. * @returns {boolean}
  7721. */
  7722. function isEscaped(jsonString, quotePosition) {
  7723. let index = quotePosition - 1;
  7724. let backslashCount = 0;
  7725. while (jsonString[index] === '\\') {
  7726. index -= 1;
  7727. backslashCount += 1;
  7728. }
  7729. return Boolean(backslashCount % 2);
  7730. }
  7731. /**
  7732. *
  7733. * @param {string} string
  7734. * @param {number?} start
  7735. * @param {number?} end
  7736. */
  7737. function strip(string, start, end) {
  7738. return string.slice(start, end).replace(/\S/g, ' ');
  7739. }
  7740. const singleComment = Symbol('singleComment');
  7741. const multiComment = Symbol('multiComment');
  7742. /**
  7743. * @param {string} jsonString
  7744. * @returns {string}
  7745. */
  7746. function stripJsonComments(jsonString) {
  7747. let isInsideString = false;
  7748. /** @type {false | symbol} */
  7749. let isInsideComment = false;
  7750. let offset = 0;
  7751. let result = '';
  7752. for (let index = 0; index < jsonString.length; index++) {
  7753. const currentCharacter = jsonString[index];
  7754. const nextCharacter = jsonString[index + 1];
  7755. if (!isInsideComment && currentCharacter === '"') {
  7756. const escaped = isEscaped(jsonString, index);
  7757. if (!escaped) {
  7758. isInsideString = !isInsideString;
  7759. }
  7760. }
  7761. if (isInsideString) {
  7762. continue;
  7763. }
  7764. if (!isInsideComment && currentCharacter + nextCharacter === '//') {
  7765. result += jsonString.slice(offset, index);
  7766. offset = index;
  7767. isInsideComment = singleComment;
  7768. index++;
  7769. } else if (isInsideComment === singleComment && currentCharacter + nextCharacter === '\r\n') {
  7770. index++;
  7771. isInsideComment = false;
  7772. result += strip(jsonString, offset, index);
  7773. offset = index;
  7774. } else if (isInsideComment === singleComment && currentCharacter === '\n') {
  7775. isInsideComment = false;
  7776. result += strip(jsonString, offset, index);
  7777. offset = index;
  7778. } else if (!isInsideComment && currentCharacter + nextCharacter === '/*') {
  7779. result += jsonString.slice(offset, index);
  7780. offset = index;
  7781. isInsideComment = multiComment;
  7782. index++;
  7783. } else if (isInsideComment === multiComment && currentCharacter + nextCharacter === '*/') {
  7784. index++;
  7785. isInsideComment = false;
  7786. result += strip(jsonString, offset, index + 1);
  7787. offset = index + 1;
  7788. }
  7789. }
  7790. return result + (isInsideComment ? strip(jsonString.slice(offset)) : jsonString.slice(offset));
  7791. }
  7792. // end strip-json-comments
  7793. // start strip-bom
  7794. /**
  7795. * @param {string} string
  7796. * @returns {string}
  7797. */
  7798. function stripBom(string) {
  7799. // Catches EFBBBF (UTF-8 BOM) because the buffer-to-string
  7800. // conversion translates it to FEFF (UTF-16 BOM).
  7801. if (string.charCodeAt(0) === 0xfeff) {
  7802. return string.slice(1);
  7803. }
  7804. return string;
  7805. }
  7806. // end strip-bom
  7807. const not_found_result = {
  7808. tsconfigFile: null,
  7809. tsconfig: {}
  7810. };
  7811. /**
  7812. * parse the closest tsconfig.json file
  7813. *
  7814. * @param {string} filename - path to a tsconfig .json or a source file or directory (absolute or relative to cwd)
  7815. * @param {import('./public.d.ts').TSConfckParseOptions} [options] - options
  7816. * @returns {Promise<import('./public.d.ts').TSConfckParseResult>}
  7817. * @throws {TSConfckParseError}
  7818. */
  7819. async function parse$e(filename, options) {
  7820. /** @type {import('./cache.js').TSConfckCache} */
  7821. const cache = options?.cache;
  7822. if (cache?.hasParseResult(filename)) {
  7823. return getParsedDeep(filename, cache, options);
  7824. }
  7825. const {
  7826. resolve,
  7827. reject,
  7828. /** @type {Promise<import('./public.d.ts').TSConfckParseResult>}*/
  7829. promise
  7830. } = makePromise();
  7831. cache?.setParseResult(filename, promise, true);
  7832. try {
  7833. let tsconfigFile =
  7834. (await resolveTSConfigJson(filename, cache)) || (await find(filename, options));
  7835. if (!tsconfigFile) {
  7836. resolve(not_found_result);
  7837. return promise;
  7838. }
  7839. let result;
  7840. if (filename !== tsconfigFile && cache?.hasParseResult(tsconfigFile)) {
  7841. result = await getParsedDeep(tsconfigFile, cache, options);
  7842. } else {
  7843. result = await parseFile$1(tsconfigFile, cache, filename === tsconfigFile);
  7844. await Promise.all([parseExtends(result, cache), parseReferences(result, options)]);
  7845. }
  7846. replaceTokens(result);
  7847. resolve(resolveSolutionTSConfig(filename, result));
  7848. } catch (e) {
  7849. reject(e);
  7850. }
  7851. return promise;
  7852. }
  7853. /**
  7854. * ensure extends and references are parsed
  7855. *
  7856. * @param {string} filename - cached file
  7857. * @param {import('./cache.js').TSConfckCache} cache - cache
  7858. * @param {import('./public.d.ts').TSConfckParseOptions} options - options
  7859. */
  7860. async function getParsedDeep(filename, cache, options) {
  7861. const result = await cache.getParseResult(filename);
  7862. if (
  7863. (result.tsconfig.extends && !result.extended) ||
  7864. (result.tsconfig.references && !result.referenced)
  7865. ) {
  7866. const promise = Promise.all([
  7867. parseExtends(result, cache),
  7868. parseReferences(result, options)
  7869. ]).then(() => result);
  7870. cache.setParseResult(filename, promise, true);
  7871. return promise;
  7872. }
  7873. return result;
  7874. }
  7875. /**
  7876. *
  7877. * @param {string} tsconfigFile - path to tsconfig file
  7878. * @param {import('./cache.js').TSConfckCache} [cache] - cache
  7879. * @param {boolean} [skipCache] - skip cache
  7880. * @returns {Promise<import('./public.d.ts').TSConfckParseResult>}
  7881. */
  7882. async function parseFile$1(tsconfigFile, cache, skipCache) {
  7883. if (
  7884. !skipCache &&
  7885. cache?.hasParseResult(tsconfigFile) &&
  7886. !cache.getParseResult(tsconfigFile)._isRootFile_
  7887. ) {
  7888. return cache.getParseResult(tsconfigFile);
  7889. }
  7890. const promise = promises$1
  7891. .readFile(tsconfigFile, 'utf-8')
  7892. .then(toJson)
  7893. .then((json) => {
  7894. const parsed = JSON.parse(json);
  7895. applyDefaults(parsed, tsconfigFile);
  7896. return {
  7897. tsconfigFile,
  7898. tsconfig: normalizeTSConfig(parsed, path$b.dirname(tsconfigFile))
  7899. };
  7900. })
  7901. .catch((e) => {
  7902. throw new TSConfckParseError(
  7903. `parsing ${tsconfigFile} failed: ${e}`,
  7904. 'PARSE_FILE',
  7905. tsconfigFile,
  7906. e
  7907. );
  7908. });
  7909. if (
  7910. !skipCache &&
  7911. (!cache?.hasParseResult(tsconfigFile) || !cache.getParseResult(tsconfigFile)._isRootFile_)
  7912. ) {
  7913. cache?.setParseResult(tsconfigFile, promise);
  7914. }
  7915. return promise;
  7916. }
  7917. /**
  7918. * normalize to match the output of ts.parseJsonConfigFileContent
  7919. *
  7920. * @param {any} tsconfig - typescript tsconfig output
  7921. * @param {string} dir - directory
  7922. */
  7923. function normalizeTSConfig(tsconfig, dir) {
  7924. // set baseUrl to absolute path
  7925. const baseUrl = tsconfig.compilerOptions?.baseUrl;
  7926. if (baseUrl && !baseUrl.startsWith('${') && !path$b.isAbsolute(baseUrl)) {
  7927. tsconfig.compilerOptions.baseUrl = resolve2posix(dir, baseUrl);
  7928. }
  7929. return tsconfig;
  7930. }
  7931. /**
  7932. *
  7933. * @param {import('./public.d.ts').TSConfckParseResult} result
  7934. * @param {import('./public.d.ts').TSConfckParseOptions} [options]
  7935. * @returns {Promise<void>}
  7936. */
  7937. async function parseReferences(result, options) {
  7938. if (!result.tsconfig.references) {
  7939. return;
  7940. }
  7941. const referencedFiles = resolveReferencedTSConfigFiles(result, options);
  7942. const referenced = await Promise.all(
  7943. referencedFiles.map((file) => parseFile$1(file, options?.cache))
  7944. );
  7945. await Promise.all(referenced.map((ref) => parseExtends(ref, options?.cache)));
  7946. referenced.forEach((ref) => {
  7947. ref.solution = result;
  7948. replaceTokens(ref);
  7949. });
  7950. result.referenced = referenced;
  7951. }
  7952. /**
  7953. * @param {import('./public.d.ts').TSConfckParseResult} result
  7954. * @param {import('./cache.js').TSConfckCache}[cache]
  7955. * @returns {Promise<void>}
  7956. */
  7957. async function parseExtends(result, cache) {
  7958. if (!result.tsconfig.extends) {
  7959. return;
  7960. }
  7961. // use result as first element in extended
  7962. // but dereference tsconfig so that mergeExtended can modify the original without affecting extended[0]
  7963. /** @type {import('./public.d.ts').TSConfckParseResult[]} */
  7964. const extended = [
  7965. { tsconfigFile: result.tsconfigFile, tsconfig: JSON.parse(JSON.stringify(result.tsconfig)) }
  7966. ];
  7967. // flatten extends graph into extended
  7968. let pos = 0;
  7969. /** @type {string[]} */
  7970. const extendsPath = [];
  7971. let currentBranchDepth = 0;
  7972. while (pos < extended.length) {
  7973. const extending = extended[pos];
  7974. extendsPath.push(extending.tsconfigFile);
  7975. if (extending.tsconfig.extends) {
  7976. // keep following this branch
  7977. currentBranchDepth += 1;
  7978. /** @type {string[]} */
  7979. let resolvedExtends;
  7980. if (!Array.isArray(extending.tsconfig.extends)) {
  7981. resolvedExtends = [resolveExtends(extending.tsconfig.extends, extending.tsconfigFile)];
  7982. } else {
  7983. // reverse because typescript 5.0 treats ['a','b','c'] as c extends b extends a
  7984. resolvedExtends = extending.tsconfig.extends
  7985. .reverse()
  7986. .map((ex) => resolveExtends(ex, extending.tsconfigFile));
  7987. }
  7988. const circularExtends = resolvedExtends.find((tsconfigFile) =>
  7989. extendsPath.includes(tsconfigFile)
  7990. );
  7991. if (circularExtends) {
  7992. const circle = extendsPath.concat([circularExtends]).join(' -> ');
  7993. throw new TSConfckParseError(
  7994. `Circular dependency in "extends": ${circle}`,
  7995. 'EXTENDS_CIRCULAR',
  7996. result.tsconfigFile
  7997. );
  7998. }
  7999. // add new extends to the list directly after current
  8000. extended.splice(
  8001. pos + 1,
  8002. 0,
  8003. ...(await Promise.all(resolvedExtends.map((file) => parseFile$1(file, cache))))
  8004. );
  8005. } else {
  8006. // reached a leaf, backtrack to the last branching point and continue
  8007. extendsPath.splice(-currentBranchDepth);
  8008. currentBranchDepth = 0;
  8009. }
  8010. pos = pos + 1;
  8011. }
  8012. result.extended = extended;
  8013. // skip first as it is the original config
  8014. for (const ext of result.extended.slice(1)) {
  8015. extendTSConfig(result, ext);
  8016. }
  8017. }
  8018. /**
  8019. *
  8020. * @param {string} extended
  8021. * @param {string} from
  8022. * @returns {string}
  8023. */
  8024. function resolveExtends(extended, from) {
  8025. if (extended === '..') {
  8026. // see #149
  8027. extended = '../tsconfig.json';
  8028. }
  8029. const req = createRequire$2(from);
  8030. let error;
  8031. try {
  8032. return req.resolve(extended);
  8033. } catch (e) {
  8034. error = e;
  8035. }
  8036. if (extended[0] !== '.' && !path$b.isAbsolute(extended)) {
  8037. try {
  8038. return req.resolve(`${extended}/tsconfig.json`);
  8039. } catch (e) {
  8040. error = e;
  8041. }
  8042. }
  8043. throw new TSConfckParseError(
  8044. `failed to resolve "extends":"${extended}" in ${from}`,
  8045. 'EXTENDS_RESOLVE',
  8046. from,
  8047. error
  8048. );
  8049. }
  8050. // references, extends and custom keys are not carried over
  8051. const EXTENDABLE_KEYS = [
  8052. 'compilerOptions',
  8053. 'files',
  8054. 'include',
  8055. 'exclude',
  8056. 'watchOptions',
  8057. 'compileOnSave',
  8058. 'typeAcquisition',
  8059. 'buildOptions'
  8060. ];
  8061. /**
  8062. *
  8063. * @param {import('./public.d.ts').TSConfckParseResult} extending
  8064. * @param {import('./public.d.ts').TSConfckParseResult} extended
  8065. * @returns void
  8066. */
  8067. function extendTSConfig(extending, extended) {
  8068. const extendingConfig = extending.tsconfig;
  8069. const extendedConfig = extended.tsconfig;
  8070. const relativePath = native2posix(
  8071. path$b.relative(path$b.dirname(extending.tsconfigFile), path$b.dirname(extended.tsconfigFile))
  8072. );
  8073. for (const key of Object.keys(extendedConfig).filter((key) => EXTENDABLE_KEYS.includes(key))) {
  8074. if (key === 'compilerOptions') {
  8075. if (!extendingConfig.compilerOptions) {
  8076. extendingConfig.compilerOptions = {};
  8077. }
  8078. for (const option of Object.keys(extendedConfig.compilerOptions)) {
  8079. if (Object.prototype.hasOwnProperty.call(extendingConfig.compilerOptions, option)) {
  8080. continue; // already set
  8081. }
  8082. extendingConfig.compilerOptions[option] = rebaseRelative(
  8083. option,
  8084. extendedConfig.compilerOptions[option],
  8085. relativePath
  8086. );
  8087. }
  8088. } else if (extendingConfig[key] === undefined) {
  8089. if (key === 'watchOptions') {
  8090. extendingConfig.watchOptions = {};
  8091. for (const option of Object.keys(extendedConfig.watchOptions)) {
  8092. extendingConfig.watchOptions[option] = rebaseRelative(
  8093. option,
  8094. extendedConfig.watchOptions[option],
  8095. relativePath
  8096. );
  8097. }
  8098. } else {
  8099. extendingConfig[key] = rebaseRelative(key, extendedConfig[key], relativePath);
  8100. }
  8101. }
  8102. }
  8103. }
  8104. const REBASE_KEYS = [
  8105. // root
  8106. 'files',
  8107. 'include',
  8108. 'exclude',
  8109. // compilerOptions
  8110. 'baseUrl',
  8111. 'rootDir',
  8112. 'rootDirs',
  8113. 'typeRoots',
  8114. 'outDir',
  8115. 'outFile',
  8116. 'declarationDir',
  8117. // watchOptions
  8118. 'excludeDirectories',
  8119. 'excludeFiles'
  8120. ];
  8121. /** @typedef {string | string[]} PathValue */
  8122. /**
  8123. *
  8124. * @param {string} key
  8125. * @param {PathValue} value
  8126. * @param {string} prependPath
  8127. * @returns {PathValue}
  8128. */
  8129. function rebaseRelative(key, value, prependPath) {
  8130. if (!REBASE_KEYS.includes(key)) {
  8131. return value;
  8132. }
  8133. if (Array.isArray(value)) {
  8134. return value.map((x) => rebasePath(x, prependPath));
  8135. } else {
  8136. return rebasePath(value, prependPath);
  8137. }
  8138. }
  8139. /**
  8140. *
  8141. * @param {string} value
  8142. * @param {string} prependPath
  8143. * @returns {string}
  8144. */
  8145. function rebasePath(value, prependPath) {
  8146. if (path$b.isAbsolute(value) || value.startsWith('${configDir}')) {
  8147. return value;
  8148. } else {
  8149. // relative paths use posix syntax in tsconfig
  8150. return path$b.posix.normalize(path$b.posix.join(prependPath, value));
  8151. }
  8152. }
  8153. class TSConfckParseError extends Error {
  8154. /**
  8155. * error code
  8156. * @type {string}
  8157. */
  8158. code;
  8159. /**
  8160. * error cause
  8161. * @type { Error | undefined}
  8162. */
  8163. cause;
  8164. /**
  8165. * absolute path of tsconfig file where the error happened
  8166. * @type {string}
  8167. */
  8168. tsconfigFile;
  8169. /**
  8170. *
  8171. * @param {string} message - error message
  8172. * @param {string} code - error code
  8173. * @param {string} tsconfigFile - path to tsconfig file
  8174. * @param {Error?} cause - cause of this error
  8175. */
  8176. constructor(message, code, tsconfigFile, cause) {
  8177. super(message);
  8178. // Set the prototype explicitly.
  8179. Object.setPrototypeOf(this, TSConfckParseError.prototype);
  8180. this.name = TSConfckParseError.name;
  8181. this.code = code;
  8182. this.cause = cause;
  8183. this.tsconfigFile = tsconfigFile;
  8184. }
  8185. }
  8186. /**
  8187. *
  8188. * @param {any} tsconfig
  8189. * @param {string} tsconfigFile
  8190. */
  8191. function applyDefaults(tsconfig, tsconfigFile) {
  8192. if (isJSConfig(tsconfigFile)) {
  8193. tsconfig.compilerOptions = {
  8194. ...DEFAULT_JSCONFIG_COMPILER_OPTIONS,
  8195. ...tsconfig.compilerOptions
  8196. };
  8197. }
  8198. }
  8199. const DEFAULT_JSCONFIG_COMPILER_OPTIONS = {
  8200. allowJs: true,
  8201. maxNodeModuleJsDepth: 2,
  8202. allowSyntheticDefaultImports: true,
  8203. skipLibCheck: true,
  8204. noEmit: true
  8205. };
  8206. /**
  8207. * @param {string} configFileName
  8208. */
  8209. function isJSConfig(configFileName) {
  8210. return path$b.basename(configFileName) === 'jsconfig.json';
  8211. }
  8212. /** @template T */
  8213. class TSConfckCache {
  8214. /**
  8215. * clear cache, use this if you have a long running process and tsconfig files have been added,changed or deleted
  8216. */
  8217. clear() {
  8218. this.#configPaths.clear();
  8219. this.#parsed.clear();
  8220. }
  8221. /**
  8222. * has cached closest config for files in dir
  8223. * @param {string} dir
  8224. * @param {string} [configName=tsconfig.json]
  8225. * @returns {boolean}
  8226. */
  8227. hasConfigPath(dir, configName = 'tsconfig.json') {
  8228. return this.#configPaths.has(`${dir}/${configName}`);
  8229. }
  8230. /**
  8231. * get cached closest tsconfig for files in dir
  8232. * @param {string} dir
  8233. * @param {string} [configName=tsconfig.json]
  8234. * @returns {Promise<string|null>|string|null}
  8235. * @throws {unknown} if cached value is an error
  8236. */
  8237. getConfigPath(dir, configName = 'tsconfig.json') {
  8238. const key = `${dir}/${configName}`;
  8239. const value = this.#configPaths.get(key);
  8240. if (value == null || value.length || value.then) {
  8241. return value;
  8242. } else {
  8243. throw value;
  8244. }
  8245. }
  8246. /**
  8247. * has parsed tsconfig for file
  8248. * @param {string} file
  8249. * @returns {boolean}
  8250. */
  8251. hasParseResult(file) {
  8252. return this.#parsed.has(file);
  8253. }
  8254. /**
  8255. * get parsed tsconfig for file
  8256. * @param {string} file
  8257. * @returns {Promise<T>|T}
  8258. * @throws {unknown} if cached value is an error
  8259. */
  8260. getParseResult(file) {
  8261. const value = this.#parsed.get(file);
  8262. if (value.then || value.tsconfig) {
  8263. return value;
  8264. } else {
  8265. throw value; // cached error, rethrow
  8266. }
  8267. }
  8268. /**
  8269. * @internal
  8270. * @private
  8271. * @param file
  8272. * @param {boolean} isRootFile a flag to check if current file which involking the parse() api, used to distinguish the normal cache which only parsed by parseFile()
  8273. * @param {Promise<T>} result
  8274. */
  8275. setParseResult(file, result, isRootFile = false) {
  8276. // _isRootFile_ is a temporary property for Promise result, used to prevent deadlock with cache
  8277. Object.defineProperty(result, '_isRootFile_', {
  8278. value: isRootFile,
  8279. writable: false,
  8280. enumerable: false,
  8281. configurable: false
  8282. });
  8283. this.#parsed.set(file, result);
  8284. result
  8285. .then((parsed) => {
  8286. if (this.#parsed.get(file) === result) {
  8287. this.#parsed.set(file, parsed);
  8288. }
  8289. })
  8290. .catch((e) => {
  8291. if (this.#parsed.get(file) === result) {
  8292. this.#parsed.set(file, e);
  8293. }
  8294. });
  8295. }
  8296. /**
  8297. * @internal
  8298. * @private
  8299. * @param {string} dir
  8300. * @param {Promise<string|null>} configPath
  8301. * @param {string} [configName=tsconfig.json]
  8302. */
  8303. setConfigPath(dir, configPath, configName = 'tsconfig.json') {
  8304. const key = `${dir}/${configName}`;
  8305. this.#configPaths.set(key, configPath);
  8306. configPath
  8307. .then((path) => {
  8308. if (this.#configPaths.get(key) === configPath) {
  8309. this.#configPaths.set(key, path);
  8310. }
  8311. })
  8312. .catch((e) => {
  8313. if (this.#configPaths.get(key) === configPath) {
  8314. this.#configPaths.set(key, e);
  8315. }
  8316. });
  8317. }
  8318. /**
  8319. * map directories to their closest tsconfig.json
  8320. * @internal
  8321. * @private
  8322. * @type{Map<string,(Promise<string|null>|string|null)>}
  8323. */
  8324. #configPaths = new Map();
  8325. /**
  8326. * map files to their parsed tsconfig result
  8327. * @internal
  8328. * @private
  8329. * @type {Map<string,(Promise<T>|T)> }
  8330. */
  8331. #parsed = new Map();
  8332. }
  8333. const debug$i = createDebugger("vite:esbuild");
  8334. const IIFE_BEGIN_RE = /(?:const|var)\s+\S+\s*=\s*function\([^()]*\)\s*\{\s*"use strict";/;
  8335. const validExtensionRE = /\.\w+$/;
  8336. const jsxExtensionsRE = /\.(?:j|t)sx\b/;
  8337. const defaultEsbuildSupported = {
  8338. "dynamic-import": true,
  8339. "import-meta": true
  8340. };
  8341. async function transformWithEsbuild(code, filename, options, inMap, config, watcher) {
  8342. let loader = options?.loader;
  8343. if (!loader) {
  8344. const ext = path$b.extname(validExtensionRE.test(filename) ? filename : cleanUrl(filename)).slice(1);
  8345. if (ext === "cjs" || ext === "mjs") {
  8346. loader = "js";
  8347. } else if (ext === "cts" || ext === "mts") {
  8348. loader = "ts";
  8349. } else {
  8350. loader = ext;
  8351. }
  8352. }
  8353. let tsconfigRaw = options?.tsconfigRaw;
  8354. if (typeof tsconfigRaw !== "string") {
  8355. const meaningfulFields = [
  8356. "alwaysStrict",
  8357. "experimentalDecorators",
  8358. "importsNotUsedAsValues",
  8359. "jsx",
  8360. "jsxFactory",
  8361. "jsxFragmentFactory",
  8362. "jsxImportSource",
  8363. "preserveValueImports",
  8364. "target",
  8365. "useDefineForClassFields",
  8366. "verbatimModuleSyntax"
  8367. ];
  8368. const compilerOptionsForFile = {};
  8369. if (loader === "ts" || loader === "tsx") {
  8370. try {
  8371. const { tsconfig: loadedTsconfig, tsconfigFile } = await loadTsconfigJsonForFile(filename, config);
  8372. if (watcher && tsconfigFile && config) {
  8373. ensureWatchedFile(watcher, tsconfigFile, config.root);
  8374. }
  8375. const loadedCompilerOptions = loadedTsconfig.compilerOptions ?? {};
  8376. for (const field of meaningfulFields) {
  8377. if (field in loadedCompilerOptions) {
  8378. compilerOptionsForFile[field] = loadedCompilerOptions[field];
  8379. }
  8380. }
  8381. } catch (e) {
  8382. if (e instanceof TSConfckParseError) {
  8383. if (watcher && e.tsconfigFile && config) {
  8384. ensureWatchedFile(watcher, e.tsconfigFile, config.root);
  8385. }
  8386. }
  8387. throw e;
  8388. }
  8389. }
  8390. const compilerOptions = {
  8391. ...compilerOptionsForFile,
  8392. ...tsconfigRaw?.compilerOptions
  8393. };
  8394. if (compilerOptions.useDefineForClassFields === void 0 && compilerOptions.target === void 0) {
  8395. compilerOptions.useDefineForClassFields = false;
  8396. }
  8397. if (options) {
  8398. if (options.jsx) compilerOptions.jsx = void 0;
  8399. if (options.jsxFactory) compilerOptions.jsxFactory = void 0;
  8400. if (options.jsxFragment) compilerOptions.jsxFragmentFactory = void 0;
  8401. if (options.jsxImportSource) compilerOptions.jsxImportSource = void 0;
  8402. }
  8403. tsconfigRaw = {
  8404. ...tsconfigRaw,
  8405. compilerOptions
  8406. };
  8407. }
  8408. const resolvedOptions = {
  8409. sourcemap: true,
  8410. // ensure source file name contains full query
  8411. sourcefile: filename,
  8412. ...options,
  8413. loader,
  8414. tsconfigRaw
  8415. };
  8416. delete resolvedOptions.include;
  8417. delete resolvedOptions.exclude;
  8418. delete resolvedOptions.jsxInject;
  8419. try {
  8420. const result = await transform$1(code, resolvedOptions);
  8421. let map;
  8422. if (inMap && resolvedOptions.sourcemap) {
  8423. const nextMap = JSON.parse(result.map);
  8424. nextMap.sourcesContent = [];
  8425. map = combineSourcemaps(filename, [
  8426. nextMap,
  8427. inMap
  8428. ]);
  8429. } else {
  8430. map = resolvedOptions.sourcemap && resolvedOptions.sourcemap !== "inline" ? JSON.parse(result.map) : { mappings: "" };
  8431. }
  8432. return {
  8433. ...result,
  8434. map
  8435. };
  8436. } catch (e) {
  8437. debug$i?.(`esbuild error with options used: `, resolvedOptions);
  8438. if (e.errors) {
  8439. e.frame = "";
  8440. e.errors.forEach((m) => {
  8441. if (m.text === "Experimental decorators are not currently enabled" || m.text === "Parameter decorators only work when experimental decorators are enabled") {
  8442. m.text += '. Vite 5 now uses esbuild 0.18 and you need to enable them by adding "experimentalDecorators": true in your "tsconfig.json" file.';
  8443. }
  8444. e.frame += `
  8445. ` + prettifyMessage(m, code);
  8446. });
  8447. e.loc = e.errors[0].location;
  8448. }
  8449. throw e;
  8450. }
  8451. }
  8452. function esbuildPlugin(config) {
  8453. const options = config.esbuild;
  8454. const { jsxInject, include, exclude, ...esbuildTransformOptions } = options;
  8455. const filter = createFilter$1(include || /\.(m?ts|[jt]sx)$/, exclude || /\.js$/);
  8456. const transformOptions = {
  8457. target: "esnext",
  8458. charset: "utf8",
  8459. ...esbuildTransformOptions,
  8460. minify: false,
  8461. minifyIdentifiers: false,
  8462. minifySyntax: false,
  8463. minifyWhitespace: false,
  8464. treeShaking: false,
  8465. // keepNames is not needed when minify is disabled.
  8466. // Also transforming multiple times with keepNames enabled breaks
  8467. // tree-shaking. (#9164)
  8468. keepNames: false,
  8469. supported: {
  8470. ...defaultEsbuildSupported,
  8471. ...esbuildTransformOptions.supported
  8472. }
  8473. };
  8474. let server;
  8475. return {
  8476. name: "vite:esbuild",
  8477. configureServer(_server) {
  8478. server = _server;
  8479. },
  8480. async transform(code, id) {
  8481. if (filter(id) || filter(cleanUrl(id))) {
  8482. const result = await transformWithEsbuild(
  8483. code,
  8484. id,
  8485. transformOptions,
  8486. void 0,
  8487. config,
  8488. server?.watcher
  8489. );
  8490. if (result.warnings.length) {
  8491. result.warnings.forEach((m) => {
  8492. this.warn(prettifyMessage(m, code));
  8493. });
  8494. }
  8495. if (jsxInject && jsxExtensionsRE.test(id)) {
  8496. result.code = jsxInject + ";" + result.code;
  8497. }
  8498. return {
  8499. code: result.code,
  8500. map: result.map
  8501. };
  8502. }
  8503. }
  8504. };
  8505. }
  8506. const rollupToEsbuildFormatMap = {
  8507. es: "esm",
  8508. cjs: "cjs",
  8509. // passing `var Lib = (() => {})()` to esbuild with format = "iife"
  8510. // will turn it to `(() => { var Lib = (() => {})() })()`,
  8511. // so we remove the format config to tell esbuild not doing this
  8512. //
  8513. // although esbuild doesn't change format, there is still possibility
  8514. // that `{ treeShaking: true }` removes a top-level no-side-effect variable
  8515. // like: `var Lib = 1`, which becomes `` after esbuild transforming,
  8516. // but thankfully rollup does not do this optimization now
  8517. iife: void 0
  8518. };
  8519. const buildEsbuildPlugin = () => {
  8520. return {
  8521. name: "vite:esbuild-transpile",
  8522. applyToEnvironment(environment) {
  8523. return environment.config.esbuild !== false;
  8524. },
  8525. async renderChunk(code, chunk, opts) {
  8526. if (opts.__vite_skip_esbuild__) {
  8527. return null;
  8528. }
  8529. const config = this.environment.config;
  8530. const options = resolveEsbuildTranspileOptions(config, opts.format);
  8531. if (!options) {
  8532. return null;
  8533. }
  8534. const res = await transformWithEsbuild(
  8535. code,
  8536. chunk.fileName,
  8537. options,
  8538. void 0,
  8539. config
  8540. );
  8541. if (config.build.lib) {
  8542. const esbuildCode = res.code;
  8543. const contentIndex = opts.format === "iife" ? Math.max(esbuildCode.search(IIFE_BEGIN_RE), 0) : opts.format === "umd" ? esbuildCode.indexOf(`(function(`) : 0;
  8544. if (contentIndex > 0) {
  8545. const esbuildHelpers = esbuildCode.slice(0, contentIndex);
  8546. res.code = esbuildCode.slice(contentIndex).replace(`"use strict";`, `"use strict";` + esbuildHelpers);
  8547. }
  8548. }
  8549. return res;
  8550. }
  8551. };
  8552. };
  8553. function resolveEsbuildTranspileOptions(config, format) {
  8554. const target = config.build.target;
  8555. const minify = config.build.minify === "esbuild";
  8556. if ((!target || target === "esnext") && !minify) {
  8557. return null;
  8558. }
  8559. const isEsLibBuild = config.build.lib && format === "es";
  8560. const esbuildOptions = config.esbuild || {};
  8561. const options = {
  8562. charset: "utf8",
  8563. ...esbuildOptions,
  8564. loader: "js",
  8565. target: target || void 0,
  8566. format: rollupToEsbuildFormatMap[format],
  8567. supported: {
  8568. ...defaultEsbuildSupported,
  8569. ...esbuildOptions.supported
  8570. }
  8571. };
  8572. if (!minify) {
  8573. return {
  8574. ...options,
  8575. minify: false,
  8576. minifyIdentifiers: false,
  8577. minifySyntax: false,
  8578. minifyWhitespace: false,
  8579. treeShaking: false
  8580. };
  8581. }
  8582. if (options.minifyIdentifiers != null || options.minifySyntax != null || options.minifyWhitespace != null) {
  8583. if (isEsLibBuild) {
  8584. return {
  8585. ...options,
  8586. minify: false,
  8587. minifyIdentifiers: options.minifyIdentifiers ?? true,
  8588. minifySyntax: options.minifySyntax ?? true,
  8589. minifyWhitespace: false,
  8590. treeShaking: true
  8591. };
  8592. } else {
  8593. return {
  8594. ...options,
  8595. minify: false,
  8596. minifyIdentifiers: options.minifyIdentifiers ?? true,
  8597. minifySyntax: options.minifySyntax ?? true,
  8598. minifyWhitespace: options.minifyWhitespace ?? true,
  8599. treeShaking: true
  8600. };
  8601. }
  8602. }
  8603. if (isEsLibBuild) {
  8604. return {
  8605. ...options,
  8606. minify: false,
  8607. minifyIdentifiers: true,
  8608. minifySyntax: true,
  8609. minifyWhitespace: false,
  8610. treeShaking: true
  8611. };
  8612. } else {
  8613. return {
  8614. ...options,
  8615. minify: true,
  8616. treeShaking: true
  8617. };
  8618. }
  8619. }
  8620. function prettifyMessage(m, code) {
  8621. let res = colors$1.yellow(m.text);
  8622. if (m.location) {
  8623. res += `
  8624. ` + generateCodeFrame(code, m.location);
  8625. }
  8626. return res + `
  8627. `;
  8628. }
  8629. let globalTSConfckCache;
  8630. const tsconfckCacheMap = /* @__PURE__ */ new WeakMap();
  8631. function getTSConfckCache(config) {
  8632. if (!config) {
  8633. return globalTSConfckCache ??= new TSConfckCache();
  8634. }
  8635. let cache = tsconfckCacheMap.get(config);
  8636. if (!cache) {
  8637. cache = new TSConfckCache();
  8638. tsconfckCacheMap.set(config, cache);
  8639. }
  8640. return cache;
  8641. }
  8642. async function loadTsconfigJsonForFile(filename, config) {
  8643. const { tsconfig, tsconfigFile } = await parse$e(filename, {
  8644. cache: getTSConfckCache(config)});
  8645. return { tsconfigFile, tsconfig };
  8646. }
  8647. async function reloadOnTsconfigChange(server, changedFile) {
  8648. if (changedFile.endsWith(".json")) {
  8649. const cache = getTSConfckCache(server.config);
  8650. if (changedFile.endsWith("/tsconfig.json") || cache.hasParseResult(changedFile)) {
  8651. server.config.logger.info(
  8652. `changed tsconfig file detected: ${changedFile} - Clearing cache and forcing full-reload to ensure TypeScript is compiled with updated config values.`,
  8653. { clear: server.config.clearScreen, timestamp: true }
  8654. );
  8655. for (const environment of Object.values(server.environments)) {
  8656. environment.moduleGraph.invalidateAll();
  8657. }
  8658. cache.clear();
  8659. for (const environment of Object.values(server.environments)) {
  8660. environment.hot.send({
  8661. type: "full-reload",
  8662. path: "*"
  8663. });
  8664. }
  8665. }
  8666. }
  8667. }
  8668. // src/realWorker.ts
  8669. // src/utils.ts
  8670. var AsyncFunction = async function() {
  8671. }.constructor;
  8672. var codeToDataUrl = (code) => `data:application/javascript,${encodeURIComponent(code + "\n//# sourceURL=[worker-eval(artichokie)]")}`;
  8673. var viteSsrDynamicImport = "__vite_ssr_dynamic_import__";
  8674. // src/realWorker.ts
  8675. var Worker = class {
  8676. /** @internal */
  8677. _isModule;
  8678. /** @internal */
  8679. _code;
  8680. /** @internal */
  8681. _parentFunctions;
  8682. /** @internal */
  8683. _max;
  8684. /** @internal */
  8685. _pool;
  8686. /** @internal */
  8687. _idlePool;
  8688. /** @internal */
  8689. _queue;
  8690. constructor(fn, options = {}) {
  8691. this._isModule = options.type === "module";
  8692. this._code = genWorkerCode(
  8693. fn,
  8694. this._isModule,
  8695. options.parentFunctions ?? {}
  8696. );
  8697. this._parentFunctions = options.parentFunctions ?? {};
  8698. const defaultMax = Math.max(
  8699. 1,
  8700. // os.availableParallelism is available from Node.js 18.14.0
  8701. (os$3.availableParallelism?.() ?? os$3.cpus().length) - 1
  8702. );
  8703. this._max = options.max || defaultMax;
  8704. this._pool = [];
  8705. this._idlePool = [];
  8706. this._queue = [];
  8707. }
  8708. async run(...args) {
  8709. const worker = await this._getAvailableWorker();
  8710. return new Promise((resolve, reject) => {
  8711. worker.currentResolve = resolve;
  8712. worker.currentReject = reject;
  8713. worker.postMessage({ args });
  8714. });
  8715. }
  8716. stop() {
  8717. this._pool.forEach((w) => w.unref());
  8718. this._queue.forEach(
  8719. ([, reject]) => reject(
  8720. new Error("Main worker pool stopped before a worker was available.")
  8721. )
  8722. );
  8723. this._pool = [];
  8724. this._idlePool = [];
  8725. this._queue = [];
  8726. }
  8727. /** @internal */
  8728. _createWorker(parentFunctionSyncMessagePort, parentFunctionAsyncMessagePort, lockState) {
  8729. const options = {
  8730. workerData: [
  8731. parentFunctionSyncMessagePort,
  8732. parentFunctionAsyncMessagePort,
  8733. lockState
  8734. ],
  8735. transferList: [
  8736. parentFunctionSyncMessagePort,
  8737. parentFunctionAsyncMessagePort
  8738. ]
  8739. };
  8740. if (this._isModule) {
  8741. return new Worker$1(
  8742. new URL(codeToDataUrl(this._code)),
  8743. options
  8744. );
  8745. }
  8746. return new Worker$1(this._code, {
  8747. ...options,
  8748. eval: true
  8749. });
  8750. }
  8751. /** @internal */
  8752. async _getAvailableWorker() {
  8753. if (this._idlePool.length) {
  8754. return this._idlePool.shift();
  8755. }
  8756. if (this._pool.length < this._max) {
  8757. const parentFunctionResponder = createParentFunctionResponder(
  8758. this._parentFunctions
  8759. );
  8760. const worker = this._createWorker(
  8761. parentFunctionResponder.workerPorts.sync,
  8762. parentFunctionResponder.workerPorts.async,
  8763. parentFunctionResponder.lockState
  8764. );
  8765. worker.on("message", async (args) => {
  8766. if ("result" in args) {
  8767. worker.currentResolve?.(args.result);
  8768. worker.currentResolve = null;
  8769. } else {
  8770. if (args.error instanceof ReferenceError) {
  8771. args.error.message += ". Maybe you forgot to pass the function to parentFunction?";
  8772. }
  8773. worker.currentReject?.(args.error);
  8774. worker.currentReject = null;
  8775. }
  8776. this._assignDoneWorker(worker);
  8777. });
  8778. worker.on("error", (err) => {
  8779. worker.currentReject?.(err);
  8780. worker.currentReject = null;
  8781. parentFunctionResponder.close();
  8782. });
  8783. worker.on("exit", (code) => {
  8784. const i = this._pool.indexOf(worker);
  8785. if (i > -1) this._pool.splice(i, 1);
  8786. if (code !== 0 && worker.currentReject) {
  8787. worker.currentReject(
  8788. new Error(`Worker stopped with non-0 exit code ${code}`)
  8789. );
  8790. worker.currentReject = null;
  8791. parentFunctionResponder.close();
  8792. }
  8793. });
  8794. this._pool.push(worker);
  8795. return worker;
  8796. }
  8797. let resolve;
  8798. let reject;
  8799. const onWorkerAvailablePromise = new Promise((r, rj) => {
  8800. resolve = r;
  8801. reject = rj;
  8802. });
  8803. this._queue.push([resolve, reject]);
  8804. return onWorkerAvailablePromise;
  8805. }
  8806. /** @internal */
  8807. _assignDoneWorker(worker) {
  8808. if (this._queue.length) {
  8809. const [resolve] = this._queue.shift();
  8810. resolve(worker);
  8811. return;
  8812. }
  8813. this._idlePool.push(worker);
  8814. }
  8815. };
  8816. function createParentFunctionResponder(parentFunctions) {
  8817. const lockState = new Int32Array(new SharedArrayBuffer(4));
  8818. const unlock = () => {
  8819. Atomics.store(lockState, 0, 0);
  8820. Atomics.notify(lockState, 0);
  8821. };
  8822. const parentFunctionSyncMessageChannel = new MessageChannel();
  8823. const parentFunctionAsyncMessageChannel = new MessageChannel();
  8824. const parentFunctionSyncMessagePort = parentFunctionSyncMessageChannel.port1;
  8825. const parentFunctionAsyncMessagePort = parentFunctionAsyncMessageChannel.port1;
  8826. const syncResponse = (data) => {
  8827. parentFunctionSyncMessagePort.postMessage(data);
  8828. unlock();
  8829. };
  8830. parentFunctionSyncMessagePort.on("message", async (args) => {
  8831. let syncResult;
  8832. try {
  8833. syncResult = parentFunctions[args.name](...args.args);
  8834. } catch (error) {
  8835. syncResponse({ id: args.id, error });
  8836. return;
  8837. }
  8838. if (!(typeof syncResult === "object" && syncResult !== null && "then" in syncResult && typeof syncResult.then === "function")) {
  8839. syncResponse({
  8840. id: args.id,
  8841. result: syncResult
  8842. });
  8843. return;
  8844. }
  8845. syncResponse({
  8846. id: args.id,
  8847. isAsync: true
  8848. });
  8849. try {
  8850. const result = await syncResult;
  8851. parentFunctionAsyncMessagePort.postMessage({ id: args.id, result });
  8852. } catch (error) {
  8853. parentFunctionAsyncMessagePort.postMessage({ id: args.id, error });
  8854. }
  8855. });
  8856. parentFunctionSyncMessagePort.unref();
  8857. return {
  8858. close: () => {
  8859. parentFunctionSyncMessagePort.close();
  8860. parentFunctionAsyncMessagePort.close();
  8861. },
  8862. lockState,
  8863. workerPorts: {
  8864. sync: parentFunctionSyncMessageChannel.port2,
  8865. async: parentFunctionAsyncMessageChannel.port2
  8866. }
  8867. };
  8868. }
  8869. function genWorkerCode(fn, isModule, parentFunctions) {
  8870. const createLock = (lockState) => {
  8871. return {
  8872. lock: () => {
  8873. Atomics.store(lockState, 0, 1);
  8874. },
  8875. waitUnlock: () => {
  8876. const status = Atomics.wait(lockState, 0, 1, 10 * 1e3);
  8877. if (status === "timed-out") {
  8878. throw new Error(status);
  8879. }
  8880. }
  8881. };
  8882. };
  8883. const createParentFunctionRequester = (syncPort, asyncPort, receive, lock) => {
  8884. let id = 0;
  8885. const resolvers = /* @__PURE__ */ new Map();
  8886. const call = (key) => (...args) => {
  8887. id++;
  8888. lock.lock();
  8889. syncPort.postMessage({ id, name: key, args });
  8890. lock.waitUnlock();
  8891. const resArgs = receive(syncPort).message;
  8892. if (resArgs.isAsync) {
  8893. let resolve, reject;
  8894. const promise = new Promise((res, rej) => {
  8895. resolve = res;
  8896. reject = rej;
  8897. });
  8898. resolvers.set(id, { resolve, reject });
  8899. return promise;
  8900. }
  8901. if ("error" in resArgs) {
  8902. throw resArgs.error;
  8903. } else {
  8904. return resArgs.result;
  8905. }
  8906. };
  8907. asyncPort.on("message", (args) => {
  8908. const id2 = args.id;
  8909. if (resolvers.has(id2)) {
  8910. const { resolve, reject } = resolvers.get(id2);
  8911. resolvers.delete(id2);
  8912. if ("result" in args) {
  8913. resolve(args.result);
  8914. } else {
  8915. reject(args.error);
  8916. }
  8917. }
  8918. });
  8919. return { call };
  8920. };
  8921. const fnString = fn.toString().replaceAll(viteSsrDynamicImport, "import");
  8922. return `
  8923. ${isModule ? "import { parentPort, receiveMessageOnPort, workerData } from 'worker_threads'" : "const { parentPort, receiveMessageOnPort, workerData } = require('worker_threads')"}
  8924. const [parentFunctionSyncMessagePort, parentFunctionAsyncMessagePort, lockState] = workerData
  8925. const createLock = ${createLock.toString()}
  8926. const parentFunctionRequester = (${createParentFunctionRequester.toString()})(
  8927. parentFunctionSyncMessagePort,
  8928. parentFunctionAsyncMessagePort,
  8929. receiveMessageOnPort,
  8930. createLock(lockState)
  8931. )
  8932. const doWorkPromise = (async () => {
  8933. ${Object.keys(parentFunctions).map(
  8934. (key) => `const ${key} = parentFunctionRequester.call(${JSON.stringify(key)});`
  8935. ).join("\n")}
  8936. return await (${fnString})()
  8937. })()
  8938. let doWork
  8939. parentPort.on('message', async (args) => {
  8940. doWork ||= await doWorkPromise
  8941. try {
  8942. const res = await doWork(...args.args)
  8943. parentPort.postMessage({ result: res })
  8944. } catch (e) {
  8945. parentPort.postMessage({ error: e })
  8946. }
  8947. })
  8948. `;
  8949. }
  8950. var importRe = /\bimport\s*\(/;
  8951. var internalImportName = "__artichokie_local_import__";
  8952. var FakeWorker = class {
  8953. /** @internal */
  8954. _fn;
  8955. constructor(fn, options = {}) {
  8956. const declareRequire = options.type !== "module";
  8957. const argsAndCode = genFakeWorkerArgsAndCode(
  8958. fn,
  8959. declareRequire,
  8960. options.parentFunctions ?? {}
  8961. );
  8962. const localImport = (specifier) => import(specifier);
  8963. const args = [
  8964. ...declareRequire ? [createRequire$1(import.meta.url)] : [],
  8965. localImport,
  8966. options.parentFunctions
  8967. ];
  8968. this._fn = new AsyncFunction(...argsAndCode)(...args);
  8969. }
  8970. async run(...args) {
  8971. try {
  8972. return await (await this._fn)(...args);
  8973. } catch (err) {
  8974. if (err instanceof ReferenceError) {
  8975. err.message += ". Maybe you forgot to pass the function to parentFunction?";
  8976. }
  8977. throw err;
  8978. }
  8979. }
  8980. stop() {
  8981. }
  8982. };
  8983. function genFakeWorkerArgsAndCode(fn, declareRequire, parentFunctions) {
  8984. const fnString = fn.toString().replace(importRe, `${internalImportName}(`).replaceAll(viteSsrDynamicImport, internalImportName);
  8985. return [
  8986. ...declareRequire ? ["require"] : [],
  8987. internalImportName,
  8988. "parentFunctions",
  8989. `
  8990. ${Object.keys(parentFunctions).map((key) => `const ${key} = parentFunctions[${JSON.stringify(key)}];`).join("\n")}
  8991. return await (${fnString})()
  8992. `
  8993. ];
  8994. }
  8995. // src/workerWithFallback.ts
  8996. var WorkerWithFallback = class {
  8997. /** @internal */
  8998. _disableReal;
  8999. /** @internal */
  9000. _realWorker;
  9001. /** @internal */
  9002. _fakeWorker;
  9003. /** @internal */
  9004. _shouldUseFake;
  9005. constructor(fn, options) {
  9006. this._disableReal = options.max !== void 0 && options.max <= 0;
  9007. this._realWorker = new Worker(fn, options);
  9008. this._fakeWorker = new FakeWorker(fn, options);
  9009. this._shouldUseFake = options.shouldUseFake;
  9010. }
  9011. async run(...args) {
  9012. const useFake = this._disableReal || this._shouldUseFake(...args);
  9013. return this[useFake ? "_fakeWorker" : "_realWorker"].run(...args);
  9014. }
  9015. stop() {
  9016. this._realWorker.stop();
  9017. this._fakeWorker.stop();
  9018. }
  9019. };
  9020. let terserPath;
  9021. const loadTerserPath = (root) => {
  9022. if (terserPath) return terserPath;
  9023. try {
  9024. terserPath = requireResolveFromRootWithFallback(root, "terser");
  9025. } catch (e) {
  9026. if (e.code === "MODULE_NOT_FOUND") {
  9027. throw new Error(
  9028. "terser not found. Since Vite v3, terser has become an optional dependency. You need to install it."
  9029. );
  9030. } else {
  9031. const message = new Error(`terser failed to load:
  9032. ${e.message}`);
  9033. message.stack = e.stack + "\n" + message.stack;
  9034. throw message;
  9035. }
  9036. }
  9037. return terserPath;
  9038. };
  9039. function terserPlugin(config) {
  9040. const { maxWorkers, ...terserOptions } = config.build.terserOptions;
  9041. const makeWorker = () => new WorkerWithFallback(
  9042. () => async (terserPath2, code, options) => {
  9043. const terser = require(terserPath2);
  9044. return terser.minify(code, options);
  9045. },
  9046. {
  9047. shouldUseFake(_terserPath, _code, options) {
  9048. 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");
  9049. },
  9050. max: maxWorkers
  9051. }
  9052. );
  9053. let worker;
  9054. return {
  9055. name: "vite:terser",
  9056. applyToEnvironment(environment) {
  9057. return !!environment.config.build.minify;
  9058. },
  9059. async renderChunk(code, _chunk, outputOptions) {
  9060. if (config.build.minify !== "terser" && // @ts-expect-error injected by @vitejs/plugin-legacy
  9061. !outputOptions.__vite_force_terser__) {
  9062. return null;
  9063. }
  9064. if (config.build.lib && outputOptions.format === "es") {
  9065. return null;
  9066. }
  9067. worker ||= makeWorker();
  9068. const terserPath2 = loadTerserPath(config.root);
  9069. const res = await worker.run(terserPath2, code, {
  9070. safari10: true,
  9071. ...terserOptions,
  9072. sourceMap: !!outputOptions.sourcemap,
  9073. module: outputOptions.format.startsWith("es"),
  9074. toplevel: outputOptions.format === "cjs"
  9075. });
  9076. return {
  9077. code: res.code,
  9078. map: res.map
  9079. };
  9080. },
  9081. closeBundle() {
  9082. worker?.stop();
  9083. }
  9084. };
  9085. }
  9086. async function resolveEnvironmentPlugins(environment) {
  9087. const environmentPlugins = [];
  9088. for (const plugin of environment.getTopLevelConfig().plugins) {
  9089. if (plugin.applyToEnvironment) {
  9090. const applied = await plugin.applyToEnvironment(environment);
  9091. if (!applied) {
  9092. continue;
  9093. }
  9094. if (applied !== true) {
  9095. environmentPlugins.push(
  9096. ...(await asyncFlatten(arraify(applied))).filter(
  9097. Boolean
  9098. )
  9099. );
  9100. continue;
  9101. }
  9102. }
  9103. environmentPlugins.push(plugin);
  9104. }
  9105. return environmentPlugins;
  9106. }
  9107. function perEnvironmentPlugin(name, applyToEnvironment) {
  9108. return {
  9109. name,
  9110. applyToEnvironment
  9111. };
  9112. }
  9113. const mimes = {
  9114. "3g2": "video/3gpp2",
  9115. "3gp": "video/3gpp",
  9116. "3gpp": "video/3gpp",
  9117. "3mf": "model/3mf",
  9118. "aac": "audio/aac",
  9119. "ac": "application/pkix-attr-cert",
  9120. "adp": "audio/adpcm",
  9121. "adts": "audio/aac",
  9122. "ai": "application/postscript",
  9123. "aml": "application/automationml-aml+xml",
  9124. "amlx": "application/automationml-amlx+zip",
  9125. "amr": "audio/amr",
  9126. "apng": "image/apng",
  9127. "appcache": "text/cache-manifest",
  9128. "appinstaller": "application/appinstaller",
  9129. "appx": "application/appx",
  9130. "appxbundle": "application/appxbundle",
  9131. "asc": "application/pgp-keys",
  9132. "atom": "application/atom+xml",
  9133. "atomcat": "application/atomcat+xml",
  9134. "atomdeleted": "application/atomdeleted+xml",
  9135. "atomsvc": "application/atomsvc+xml",
  9136. "au": "audio/basic",
  9137. "avci": "image/avci",
  9138. "avcs": "image/avcs",
  9139. "avif": "image/avif",
  9140. "aw": "application/applixware",
  9141. "bdoc": "application/bdoc",
  9142. "bin": "application/octet-stream",
  9143. "bmp": "image/bmp",
  9144. "bpk": "application/octet-stream",
  9145. "btf": "image/prs.btif",
  9146. "btif": "image/prs.btif",
  9147. "buffer": "application/octet-stream",
  9148. "ccxml": "application/ccxml+xml",
  9149. "cdfx": "application/cdfx+xml",
  9150. "cdmia": "application/cdmi-capability",
  9151. "cdmic": "application/cdmi-container",
  9152. "cdmid": "application/cdmi-domain",
  9153. "cdmio": "application/cdmi-object",
  9154. "cdmiq": "application/cdmi-queue",
  9155. "cer": "application/pkix-cert",
  9156. "cgm": "image/cgm",
  9157. "cjs": "application/node",
  9158. "class": "application/java-vm",
  9159. "coffee": "text/coffeescript",
  9160. "conf": "text/plain",
  9161. "cpl": "application/cpl+xml",
  9162. "cpt": "application/mac-compactpro",
  9163. "crl": "application/pkix-crl",
  9164. "css": "text/css",
  9165. "csv": "text/csv",
  9166. "cu": "application/cu-seeme",
  9167. "cwl": "application/cwl",
  9168. "cww": "application/prs.cww",
  9169. "davmount": "application/davmount+xml",
  9170. "dbk": "application/docbook+xml",
  9171. "deb": "application/octet-stream",
  9172. "def": "text/plain",
  9173. "deploy": "application/octet-stream",
  9174. "dib": "image/bmp",
  9175. "disposition-notification": "message/disposition-notification",
  9176. "dist": "application/octet-stream",
  9177. "distz": "application/octet-stream",
  9178. "dll": "application/octet-stream",
  9179. "dmg": "application/octet-stream",
  9180. "dms": "application/octet-stream",
  9181. "doc": "application/msword",
  9182. "dot": "application/msword",
  9183. "dpx": "image/dpx",
  9184. "drle": "image/dicom-rle",
  9185. "dsc": "text/prs.lines.tag",
  9186. "dssc": "application/dssc+der",
  9187. "dtd": "application/xml-dtd",
  9188. "dump": "application/octet-stream",
  9189. "dwd": "application/atsc-dwd+xml",
  9190. "ear": "application/java-archive",
  9191. "ecma": "application/ecmascript",
  9192. "elc": "application/octet-stream",
  9193. "emf": "image/emf",
  9194. "eml": "message/rfc822",
  9195. "emma": "application/emma+xml",
  9196. "emotionml": "application/emotionml+xml",
  9197. "eps": "application/postscript",
  9198. "epub": "application/epub+zip",
  9199. "exe": "application/octet-stream",
  9200. "exi": "application/exi",
  9201. "exp": "application/express",
  9202. "exr": "image/aces",
  9203. "ez": "application/andrew-inset",
  9204. "fdf": "application/fdf",
  9205. "fdt": "application/fdt+xml",
  9206. "fits": "image/fits",
  9207. "g3": "image/g3fax",
  9208. "gbr": "application/rpki-ghostbusters",
  9209. "geojson": "application/geo+json",
  9210. "gif": "image/gif",
  9211. "glb": "model/gltf-binary",
  9212. "gltf": "model/gltf+json",
  9213. "gml": "application/gml+xml",
  9214. "gpx": "application/gpx+xml",
  9215. "gram": "application/srgs",
  9216. "grxml": "application/srgs+xml",
  9217. "gxf": "application/gxf",
  9218. "gz": "application/gzip",
  9219. "h261": "video/h261",
  9220. "h263": "video/h263",
  9221. "h264": "video/h264",
  9222. "heic": "image/heic",
  9223. "heics": "image/heic-sequence",
  9224. "heif": "image/heif",
  9225. "heifs": "image/heif-sequence",
  9226. "hej2": "image/hej2k",
  9227. "held": "application/atsc-held+xml",
  9228. "hjson": "application/hjson",
  9229. "hlp": "application/winhlp",
  9230. "hqx": "application/mac-binhex40",
  9231. "hsj2": "image/hsj2",
  9232. "htm": "text/html",
  9233. "html": "text/html",
  9234. "ics": "text/calendar",
  9235. "ief": "image/ief",
  9236. "ifb": "text/calendar",
  9237. "iges": "model/iges",
  9238. "igs": "model/iges",
  9239. "img": "application/octet-stream",
  9240. "in": "text/plain",
  9241. "ini": "text/plain",
  9242. "ink": "application/inkml+xml",
  9243. "inkml": "application/inkml+xml",
  9244. "ipfix": "application/ipfix",
  9245. "iso": "application/octet-stream",
  9246. "its": "application/its+xml",
  9247. "jade": "text/jade",
  9248. "jar": "application/java-archive",
  9249. "jhc": "image/jphc",
  9250. "jls": "image/jls",
  9251. "jp2": "image/jp2",
  9252. "jpe": "image/jpeg",
  9253. "jpeg": "image/jpeg",
  9254. "jpf": "image/jpx",
  9255. "jpg": "image/jpeg",
  9256. "jpg2": "image/jp2",
  9257. "jpgm": "image/jpm",
  9258. "jpgv": "video/jpeg",
  9259. "jph": "image/jph",
  9260. "jpm": "image/jpm",
  9261. "jpx": "image/jpx",
  9262. "js": "text/javascript",
  9263. "json": "application/json",
  9264. "json5": "application/json5",
  9265. "jsonld": "application/ld+json",
  9266. "jsonml": "application/jsonml+json",
  9267. "jsx": "text/jsx",
  9268. "jt": "model/jt",
  9269. "jxl": "image/jxl",
  9270. "jxr": "image/jxr",
  9271. "jxra": "image/jxra",
  9272. "jxrs": "image/jxrs",
  9273. "jxs": "image/jxs",
  9274. "jxsc": "image/jxsc",
  9275. "jxsi": "image/jxsi",
  9276. "jxss": "image/jxss",
  9277. "kar": "audio/midi",
  9278. "ktx": "image/ktx",
  9279. "ktx2": "image/ktx2",
  9280. "less": "text/less",
  9281. "lgr": "application/lgr+xml",
  9282. "list": "text/plain",
  9283. "litcoffee": "text/coffeescript",
  9284. "log": "text/plain",
  9285. "lostxml": "application/lost+xml",
  9286. "lrf": "application/octet-stream",
  9287. "m1v": "video/mpeg",
  9288. "m21": "application/mp21",
  9289. "m2a": "audio/mpeg",
  9290. "m2t": "video/mp2t",
  9291. "m2ts": "video/mp2t",
  9292. "m2v": "video/mpeg",
  9293. "m3a": "audio/mpeg",
  9294. "m4a": "audio/mp4",
  9295. "m4p": "application/mp4",
  9296. "m4s": "video/iso.segment",
  9297. "ma": "application/mathematica",
  9298. "mads": "application/mads+xml",
  9299. "maei": "application/mmt-aei+xml",
  9300. "man": "text/troff",
  9301. "manifest": "text/cache-manifest",
  9302. "map": "application/json",
  9303. "mar": "application/octet-stream",
  9304. "markdown": "text/markdown",
  9305. "mathml": "application/mathml+xml",
  9306. "mb": "application/mathematica",
  9307. "mbox": "application/mbox",
  9308. "md": "text/markdown",
  9309. "mdx": "text/mdx",
  9310. "me": "text/troff",
  9311. "mesh": "model/mesh",
  9312. "meta4": "application/metalink4+xml",
  9313. "metalink": "application/metalink+xml",
  9314. "mets": "application/mets+xml",
  9315. "mft": "application/rpki-manifest",
  9316. "mid": "audio/midi",
  9317. "midi": "audio/midi",
  9318. "mime": "message/rfc822",
  9319. "mj2": "video/mj2",
  9320. "mjp2": "video/mj2",
  9321. "mjs": "text/javascript",
  9322. "mml": "text/mathml",
  9323. "mods": "application/mods+xml",
  9324. "mov": "video/quicktime",
  9325. "mp2": "audio/mpeg",
  9326. "mp21": "application/mp21",
  9327. "mp2a": "audio/mpeg",
  9328. "mp3": "audio/mpeg",
  9329. "mp4": "video/mp4",
  9330. "mp4a": "audio/mp4",
  9331. "mp4s": "application/mp4",
  9332. "mp4v": "video/mp4",
  9333. "mpd": "application/dash+xml",
  9334. "mpe": "video/mpeg",
  9335. "mpeg": "video/mpeg",
  9336. "mpf": "application/media-policy-dataset+xml",
  9337. "mpg": "video/mpeg",
  9338. "mpg4": "video/mp4",
  9339. "mpga": "audio/mpeg",
  9340. "mpp": "application/dash-patch+xml",
  9341. "mrc": "application/marc",
  9342. "mrcx": "application/marcxml+xml",
  9343. "ms": "text/troff",
  9344. "mscml": "application/mediaservercontrol+xml",
  9345. "msh": "model/mesh",
  9346. "msi": "application/octet-stream",
  9347. "msix": "application/msix",
  9348. "msixbundle": "application/msixbundle",
  9349. "msm": "application/octet-stream",
  9350. "msp": "application/octet-stream",
  9351. "mtl": "model/mtl",
  9352. "mts": "video/mp2t",
  9353. "musd": "application/mmt-usd+xml",
  9354. "mxf": "application/mxf",
  9355. "mxmf": "audio/mobile-xmf",
  9356. "mxml": "application/xv+xml",
  9357. "n3": "text/n3",
  9358. "nb": "application/mathematica",
  9359. "nq": "application/n-quads",
  9360. "nt": "application/n-triples",
  9361. "obj": "model/obj",
  9362. "oda": "application/oda",
  9363. "oga": "audio/ogg",
  9364. "ogg": "audio/ogg",
  9365. "ogv": "video/ogg",
  9366. "ogx": "application/ogg",
  9367. "omdoc": "application/omdoc+xml",
  9368. "onepkg": "application/onenote",
  9369. "onetmp": "application/onenote",
  9370. "onetoc": "application/onenote",
  9371. "onetoc2": "application/onenote",
  9372. "opf": "application/oebps-package+xml",
  9373. "opus": "audio/ogg",
  9374. "otf": "font/otf",
  9375. "owl": "application/rdf+xml",
  9376. "oxps": "application/oxps",
  9377. "p10": "application/pkcs10",
  9378. "p7c": "application/pkcs7-mime",
  9379. "p7m": "application/pkcs7-mime",
  9380. "p7s": "application/pkcs7-signature",
  9381. "p8": "application/pkcs8",
  9382. "pdf": "application/pdf",
  9383. "pfr": "application/font-tdpfr",
  9384. "pgp": "application/pgp-encrypted",
  9385. "pkg": "application/octet-stream",
  9386. "pki": "application/pkixcmp",
  9387. "pkipath": "application/pkix-pkipath",
  9388. "pls": "application/pls+xml",
  9389. "png": "image/png",
  9390. "prc": "model/prc",
  9391. "prf": "application/pics-rules",
  9392. "provx": "application/provenance+xml",
  9393. "ps": "application/postscript",
  9394. "pskcxml": "application/pskc+xml",
  9395. "pti": "image/prs.pti",
  9396. "qt": "video/quicktime",
  9397. "raml": "application/raml+yaml",
  9398. "rapd": "application/route-apd+xml",
  9399. "rdf": "application/rdf+xml",
  9400. "relo": "application/p2p-overlay+xml",
  9401. "rif": "application/reginfo+xml",
  9402. "rl": "application/resource-lists+xml",
  9403. "rld": "application/resource-lists-diff+xml",
  9404. "rmi": "audio/midi",
  9405. "rnc": "application/relax-ng-compact-syntax",
  9406. "rng": "application/xml",
  9407. "roa": "application/rpki-roa",
  9408. "roff": "text/troff",
  9409. "rq": "application/sparql-query",
  9410. "rs": "application/rls-services+xml",
  9411. "rsat": "application/atsc-rsat+xml",
  9412. "rsd": "application/rsd+xml",
  9413. "rsheet": "application/urc-ressheet+xml",
  9414. "rss": "application/rss+xml",
  9415. "rtf": "text/rtf",
  9416. "rtx": "text/richtext",
  9417. "rusd": "application/route-usd+xml",
  9418. "s3m": "audio/s3m",
  9419. "sbml": "application/sbml+xml",
  9420. "scq": "application/scvp-cv-request",
  9421. "scs": "application/scvp-cv-response",
  9422. "sdp": "application/sdp",
  9423. "senmlx": "application/senml+xml",
  9424. "sensmlx": "application/sensml+xml",
  9425. "ser": "application/java-serialized-object",
  9426. "setpay": "application/set-payment-initiation",
  9427. "setreg": "application/set-registration-initiation",
  9428. "sgi": "image/sgi",
  9429. "sgm": "text/sgml",
  9430. "sgml": "text/sgml",
  9431. "shex": "text/shex",
  9432. "shf": "application/shf+xml",
  9433. "shtml": "text/html",
  9434. "sieve": "application/sieve",
  9435. "sig": "application/pgp-signature",
  9436. "sil": "audio/silk",
  9437. "silo": "model/mesh",
  9438. "siv": "application/sieve",
  9439. "slim": "text/slim",
  9440. "slm": "text/slim",
  9441. "sls": "application/route-s-tsid+xml",
  9442. "smi": "application/smil+xml",
  9443. "smil": "application/smil+xml",
  9444. "snd": "audio/basic",
  9445. "so": "application/octet-stream",
  9446. "spdx": "text/spdx",
  9447. "spp": "application/scvp-vp-response",
  9448. "spq": "application/scvp-vp-request",
  9449. "spx": "audio/ogg",
  9450. "sql": "application/sql",
  9451. "sru": "application/sru+xml",
  9452. "srx": "application/sparql-results+xml",
  9453. "ssdl": "application/ssdl+xml",
  9454. "ssml": "application/ssml+xml",
  9455. "stk": "application/hyperstudio",
  9456. "stl": "model/stl",
  9457. "stpx": "model/step+xml",
  9458. "stpxz": "model/step-xml+zip",
  9459. "stpz": "model/step+zip",
  9460. "styl": "text/stylus",
  9461. "stylus": "text/stylus",
  9462. "svg": "image/svg+xml",
  9463. "svgz": "image/svg+xml",
  9464. "swidtag": "application/swid+xml",
  9465. "t": "text/troff",
  9466. "t38": "image/t38",
  9467. "td": "application/urc-targetdesc+xml",
  9468. "tei": "application/tei+xml",
  9469. "teicorpus": "application/tei+xml",
  9470. "text": "text/plain",
  9471. "tfi": "application/thraud+xml",
  9472. "tfx": "image/tiff-fx",
  9473. "tif": "image/tiff",
  9474. "tiff": "image/tiff",
  9475. "toml": "application/toml",
  9476. "tr": "text/troff",
  9477. "trig": "application/trig",
  9478. "ts": "video/mp2t",
  9479. "tsd": "application/timestamped-data",
  9480. "tsv": "text/tab-separated-values",
  9481. "ttc": "font/collection",
  9482. "ttf": "font/ttf",
  9483. "ttl": "text/turtle",
  9484. "ttml": "application/ttml+xml",
  9485. "txt": "text/plain",
  9486. "u3d": "model/u3d",
  9487. "u8dsn": "message/global-delivery-status",
  9488. "u8hdr": "message/global-headers",
  9489. "u8mdn": "message/global-disposition-notification",
  9490. "u8msg": "message/global",
  9491. "ubj": "application/ubjson",
  9492. "uri": "text/uri-list",
  9493. "uris": "text/uri-list",
  9494. "urls": "text/uri-list",
  9495. "vcard": "text/vcard",
  9496. "vrml": "model/vrml",
  9497. "vtt": "text/vtt",
  9498. "vxml": "application/voicexml+xml",
  9499. "war": "application/java-archive",
  9500. "wasm": "application/wasm",
  9501. "wav": "audio/wav",
  9502. "weba": "audio/webm",
  9503. "webm": "video/webm",
  9504. "webmanifest": "application/manifest+json",
  9505. "webp": "image/webp",
  9506. "wgsl": "text/wgsl",
  9507. "wgt": "application/widget",
  9508. "wif": "application/watcherinfo+xml",
  9509. "wmf": "image/wmf",
  9510. "woff": "font/woff",
  9511. "woff2": "font/woff2",
  9512. "wrl": "model/vrml",
  9513. "wsdl": "application/wsdl+xml",
  9514. "wspolicy": "application/wspolicy+xml",
  9515. "x3d": "model/x3d+xml",
  9516. "x3db": "model/x3d+fastinfoset",
  9517. "x3dbz": "model/x3d+binary",
  9518. "x3dv": "model/x3d-vrml",
  9519. "x3dvz": "model/x3d+vrml",
  9520. "x3dz": "model/x3d+xml",
  9521. "xaml": "application/xaml+xml",
  9522. "xav": "application/xcap-att+xml",
  9523. "xca": "application/xcap-caps+xml",
  9524. "xcs": "application/calendar+xml",
  9525. "xdf": "application/xcap-diff+xml",
  9526. "xdssc": "application/dssc+xml",
  9527. "xel": "application/xcap-el+xml",
  9528. "xenc": "application/xenc+xml",
  9529. "xer": "application/patch-ops-error+xml",
  9530. "xfdf": "application/xfdf",
  9531. "xht": "application/xhtml+xml",
  9532. "xhtml": "application/xhtml+xml",
  9533. "xhvml": "application/xv+xml",
  9534. "xlf": "application/xliff+xml",
  9535. "xm": "audio/xm",
  9536. "xml": "text/xml",
  9537. "xns": "application/xcap-ns+xml",
  9538. "xop": "application/xop+xml",
  9539. "xpl": "application/xproc+xml",
  9540. "xsd": "application/xml",
  9541. "xsf": "application/prs.xsf+xml",
  9542. "xsl": "application/xml",
  9543. "xslt": "application/xml",
  9544. "xspf": "application/xspf+xml",
  9545. "xvm": "application/xv+xml",
  9546. "xvml": "application/xv+xml",
  9547. "yaml": "text/yaml",
  9548. "yang": "application/yang",
  9549. "yin": "application/yin+xml",
  9550. "yml": "text/yaml",
  9551. "zip": "application/zip"
  9552. };
  9553. function lookup(extn) {
  9554. let tmp = ('' + extn).trim().toLowerCase();
  9555. let idx = tmp.lastIndexOf('.');
  9556. return mimes[!~idx ? tmp : tmp.substring(++idx)];
  9557. }
  9558. const publicFilesMap = /* @__PURE__ */ new WeakMap();
  9559. async function initPublicFiles(config) {
  9560. let fileNames;
  9561. try {
  9562. fileNames = await recursiveReaddir(config.publicDir);
  9563. } catch (e) {
  9564. if (e.code === ERR_SYMLINK_IN_RECURSIVE_READDIR) {
  9565. return;
  9566. }
  9567. throw e;
  9568. }
  9569. const publicFiles = new Set(
  9570. fileNames.map((fileName) => fileName.slice(config.publicDir.length))
  9571. );
  9572. publicFilesMap.set(config, publicFiles);
  9573. return publicFiles;
  9574. }
  9575. function getPublicFiles(config) {
  9576. return publicFilesMap.get(config);
  9577. }
  9578. function checkPublicFile(url, config) {
  9579. const { publicDir } = config;
  9580. if (!publicDir || url[0] !== "/") {
  9581. return;
  9582. }
  9583. const fileName = cleanUrl(url);
  9584. const publicFiles = getPublicFiles(config);
  9585. if (publicFiles) {
  9586. return publicFiles.has(fileName) ? normalizePath$3(path$b.join(publicDir, fileName)) : void 0;
  9587. }
  9588. const publicFile = normalizePath$3(path$b.join(publicDir, fileName));
  9589. if (!publicFile.startsWith(withTrailingSlash(publicDir))) {
  9590. return;
  9591. }
  9592. return fs__default.existsSync(publicFile) ? publicFile : void 0;
  9593. }
  9594. const assetUrlRE = /__VITE_ASSET__([\w$]+)__(?:\$_(.*?)__)?/g;
  9595. const jsSourceMapRE = /\.[cm]?js\.map$/;
  9596. const noInlineRE = /[?&]no-inline\b/;
  9597. const inlineRE$3 = /[?&]inline\b/;
  9598. const svgExtRE = /\.svg(?:$|\?)/;
  9599. const assetCache = /* @__PURE__ */ new WeakMap();
  9600. const cssEntriesMap = /* @__PURE__ */ new WeakMap();
  9601. function registerCustomMime() {
  9602. mimes["ico"] = "image/x-icon";
  9603. mimes["cur"] = "image/x-icon";
  9604. mimes["flac"] = "audio/flac";
  9605. mimes["eot"] = "application/vnd.ms-fontobject";
  9606. }
  9607. function renderAssetUrlInJS(pluginContext, chunk, opts, code) {
  9608. const { environment } = pluginContext;
  9609. const toRelativeRuntime = createToImportMetaURLBasedRelativeRuntime(
  9610. opts.format,
  9611. environment.config.isWorker
  9612. );
  9613. let match;
  9614. let s;
  9615. assetUrlRE.lastIndex = 0;
  9616. while (match = assetUrlRE.exec(code)) {
  9617. s ||= new MagicString(code);
  9618. const [full, referenceId, postfix = ""] = match;
  9619. const file = pluginContext.getFileName(referenceId);
  9620. chunk.viteMetadata.importedAssets.add(cleanUrl(file));
  9621. const filename = file + postfix;
  9622. const replacement = toOutputFilePathInJS(
  9623. environment,
  9624. filename,
  9625. "asset",
  9626. chunk.fileName,
  9627. "js",
  9628. toRelativeRuntime
  9629. );
  9630. const replacementString = typeof replacement === "string" ? JSON.stringify(encodeURIPath(replacement)).slice(1, -1) : `"+${replacement.runtime}+"`;
  9631. s.update(match.index, match.index + full.length, replacementString);
  9632. }
  9633. const publicAssetUrlMap = publicAssetUrlCache.get(
  9634. environment.getTopLevelConfig()
  9635. );
  9636. publicAssetUrlRE.lastIndex = 0;
  9637. while (match = publicAssetUrlRE.exec(code)) {
  9638. s ||= new MagicString(code);
  9639. const [full, hash] = match;
  9640. const publicUrl = publicAssetUrlMap.get(hash).slice(1);
  9641. const replacement = toOutputFilePathInJS(
  9642. environment,
  9643. publicUrl,
  9644. "public",
  9645. chunk.fileName,
  9646. "js",
  9647. toRelativeRuntime
  9648. );
  9649. const replacementString = typeof replacement === "string" ? JSON.stringify(encodeURIPath(replacement)).slice(1, -1) : `"+${replacement.runtime}+"`;
  9650. s.update(match.index, match.index + full.length, replacementString);
  9651. }
  9652. return s;
  9653. }
  9654. function assetPlugin(config) {
  9655. registerCustomMime();
  9656. return {
  9657. name: "vite:asset",
  9658. perEnvironmentStartEndDuringDev: true,
  9659. buildStart() {
  9660. assetCache.set(this.environment, /* @__PURE__ */ new Map());
  9661. cssEntriesMap.set(this.environment, /* @__PURE__ */ new Set());
  9662. },
  9663. resolveId: {
  9664. handler(id) {
  9665. if (!config.assetsInclude(cleanUrl(id)) && !urlRE$1.test(id)) {
  9666. return;
  9667. }
  9668. const publicFile = checkPublicFile(id, config);
  9669. if (publicFile) {
  9670. return id;
  9671. }
  9672. }
  9673. },
  9674. load: {
  9675. async handler(id) {
  9676. if (id[0] === "\0") {
  9677. return;
  9678. }
  9679. if (rawRE$1.test(id)) {
  9680. const file = checkPublicFile(id, config) || cleanUrl(id);
  9681. this.addWatchFile(file);
  9682. return `export default ${JSON.stringify(
  9683. await fsp.readFile(file, "utf-8")
  9684. )}`;
  9685. }
  9686. if (!urlRE$1.test(id) && !config.assetsInclude(cleanUrl(id))) {
  9687. return;
  9688. }
  9689. id = removeUrlQuery(id);
  9690. let url = await fileToUrl$1(this, id);
  9691. if (!url.startsWith("data:") && this.environment.mode === "dev") {
  9692. const mod = this.environment.moduleGraph.getModuleById(id);
  9693. if (mod && mod.lastHMRTimestamp > 0) {
  9694. url = injectQuery(url, `t=${mod.lastHMRTimestamp}`);
  9695. }
  9696. }
  9697. return {
  9698. code: `export default ${JSON.stringify(encodeURIPath(url))}`,
  9699. // Force rollup to keep this module from being shared between other entry points if it's an entrypoint.
  9700. // If the resulting chunk is empty, it will be removed in generateBundle.
  9701. moduleSideEffects: config.command === "build" && this.getModuleInfo(id)?.isEntry ? "no-treeshake" : false,
  9702. meta: config.command === "build" ? { "vite:asset": true } : void 0
  9703. };
  9704. }
  9705. },
  9706. renderChunk(code, chunk, opts) {
  9707. const s = renderAssetUrlInJS(this, chunk, opts, code);
  9708. if (s) {
  9709. return {
  9710. code: s.toString(),
  9711. map: this.environment.config.build.sourcemap ? s.generateMap({ hires: "boundary" }) : null
  9712. };
  9713. } else {
  9714. return null;
  9715. }
  9716. },
  9717. generateBundle(_, bundle) {
  9718. let importedFiles;
  9719. for (const file in bundle) {
  9720. const chunk = bundle[file];
  9721. if (chunk.type === "chunk" && chunk.isEntry && chunk.moduleIds.length === 1 && config.assetsInclude(chunk.moduleIds[0]) && this.getModuleInfo(chunk.moduleIds[0])?.meta["vite:asset"]) {
  9722. if (!importedFiles) {
  9723. importedFiles = /* @__PURE__ */ new Set();
  9724. for (const file2 in bundle) {
  9725. const chunk2 = bundle[file2];
  9726. if (chunk2.type === "chunk") {
  9727. for (const importedFile of chunk2.imports) {
  9728. importedFiles.add(importedFile);
  9729. }
  9730. for (const importedFile of chunk2.dynamicImports) {
  9731. importedFiles.add(importedFile);
  9732. }
  9733. }
  9734. }
  9735. }
  9736. if (!importedFiles.has(file)) {
  9737. delete bundle[file];
  9738. }
  9739. }
  9740. }
  9741. if (config.command === "build" && !this.environment.config.build.emitAssets) {
  9742. for (const file in bundle) {
  9743. if (bundle[file].type === "asset" && !file.endsWith("ssr-manifest.json") && !jsSourceMapRE.test(file)) {
  9744. delete bundle[file];
  9745. }
  9746. }
  9747. }
  9748. }
  9749. };
  9750. }
  9751. async function fileToUrl$1(pluginContext, id) {
  9752. const { environment } = pluginContext;
  9753. if (environment.config.command === "serve") {
  9754. return fileToDevUrl(environment, id);
  9755. } else {
  9756. return fileToBuiltUrl(pluginContext, id);
  9757. }
  9758. }
  9759. async function fileToDevUrl(environment, id, skipBase = false) {
  9760. const config = environment.getTopLevelConfig();
  9761. const publicFile = checkPublicFile(id, config);
  9762. if (inlineRE$3.test(id)) {
  9763. const file = publicFile || cleanUrl(id);
  9764. const content = await fsp.readFile(file);
  9765. return assetToDataURL(environment, file, content);
  9766. }
  9767. const cleanedId = cleanUrl(id);
  9768. if (svgExtRE.test(cleanedId)) {
  9769. const file = publicFile || cleanedId;
  9770. const content = await fsp.readFile(file);
  9771. if (shouldInline(environment, file, id, content, void 0, void 0)) {
  9772. return assetToDataURL(environment, file, content);
  9773. }
  9774. }
  9775. let rtn;
  9776. if (publicFile) {
  9777. rtn = id;
  9778. } else if (id.startsWith(withTrailingSlash(config.root))) {
  9779. rtn = "/" + path$b.posix.relative(config.root, id);
  9780. } else {
  9781. rtn = path$b.posix.join(FS_PREFIX, id);
  9782. }
  9783. if (skipBase) {
  9784. return rtn;
  9785. }
  9786. const base = joinUrlSegments(config.server.origin ?? "", config.decodedBase);
  9787. return joinUrlSegments(base, removeLeadingSlash(rtn));
  9788. }
  9789. function getPublicAssetFilename(hash, config) {
  9790. return publicAssetUrlCache.get(config)?.get(hash);
  9791. }
  9792. const publicAssetUrlCache = /* @__PURE__ */ new WeakMap();
  9793. const publicAssetUrlRE = /__VITE_PUBLIC_ASSET__([a-z\d]{8})__/g;
  9794. function publicFileToBuiltUrl(url, config) {
  9795. if (config.command !== "build") {
  9796. return joinUrlSegments(config.decodedBase, url);
  9797. }
  9798. const hash = getHash(url);
  9799. let cache = publicAssetUrlCache.get(config);
  9800. if (!cache) {
  9801. cache = /* @__PURE__ */ new Map();
  9802. publicAssetUrlCache.set(config, cache);
  9803. }
  9804. if (!cache.get(hash)) {
  9805. cache.set(hash, url);
  9806. }
  9807. return `__VITE_PUBLIC_ASSET__${hash}__`;
  9808. }
  9809. const GIT_LFS_PREFIX = Buffer$1.from("version https://git-lfs.github.com");
  9810. function isGitLfsPlaceholder(content) {
  9811. if (content.length < GIT_LFS_PREFIX.length) return false;
  9812. return GIT_LFS_PREFIX.compare(content, 0, GIT_LFS_PREFIX.length) === 0;
  9813. }
  9814. async function fileToBuiltUrl(pluginContext, id, skipPublicCheck = false, forceInline) {
  9815. const environment = pluginContext.environment;
  9816. const topLevelConfig = environment.getTopLevelConfig();
  9817. if (!skipPublicCheck) {
  9818. const publicFile = checkPublicFile(id, topLevelConfig);
  9819. if (publicFile) {
  9820. if (inlineRE$3.test(id)) {
  9821. id = publicFile;
  9822. } else {
  9823. return publicFileToBuiltUrl(id, topLevelConfig);
  9824. }
  9825. }
  9826. }
  9827. const cache = assetCache.get(environment);
  9828. const cached = cache.get(id);
  9829. if (cached) {
  9830. return cached;
  9831. }
  9832. let { file, postfix } = splitFileAndPostfix(id);
  9833. const content = await fsp.readFile(file);
  9834. let url;
  9835. if (shouldInline(environment, file, id, content, pluginContext, forceInline)) {
  9836. url = assetToDataURL(environment, file, content);
  9837. } else {
  9838. const originalFileName = normalizePath$3(
  9839. path$b.relative(environment.config.root, file)
  9840. );
  9841. const referenceId = pluginContext.emitFile({
  9842. type: "asset",
  9843. // Ignore directory structure for asset file names
  9844. name: path$b.basename(file),
  9845. originalFileName,
  9846. source: content
  9847. });
  9848. if (environment.config.command === "build" && noInlineRE.test(postfix)) {
  9849. postfix = postfix.replace(noInlineRE, "").replace(/^&/, "?");
  9850. }
  9851. url = `__VITE_ASSET__${referenceId}__${postfix ? `$_${postfix}__` : ``}`;
  9852. }
  9853. cache.set(id, url);
  9854. return url;
  9855. }
  9856. async function urlToBuiltUrl(pluginContext, url, importer, forceInline) {
  9857. const topLevelConfig = pluginContext.environment.getTopLevelConfig();
  9858. if (checkPublicFile(url, topLevelConfig)) {
  9859. return publicFileToBuiltUrl(url, topLevelConfig);
  9860. }
  9861. const file = url[0] === "/" ? path$b.join(topLevelConfig.root, url) : path$b.join(path$b.dirname(importer), url);
  9862. return fileToBuiltUrl(
  9863. pluginContext,
  9864. file,
  9865. // skip public check since we just did it above
  9866. true,
  9867. forceInline
  9868. );
  9869. }
  9870. function shouldInline(environment, file, id, content, buildPluginContext, forceInline) {
  9871. if (noInlineRE.test(id)) return false;
  9872. if (inlineRE$3.test(id)) return true;
  9873. if (buildPluginContext) {
  9874. if (environment.config.build.lib) return true;
  9875. if (buildPluginContext.getModuleInfo(id)?.isEntry) return false;
  9876. }
  9877. if (forceInline !== void 0) return forceInline;
  9878. if (file.endsWith(".html")) return false;
  9879. if (file.endsWith(".svg") && id.includes("#")) return false;
  9880. let limit;
  9881. const { assetsInlineLimit } = environment.config.build;
  9882. if (typeof assetsInlineLimit === "function") {
  9883. const userShouldInline = assetsInlineLimit(file, content);
  9884. if (userShouldInline != null) return userShouldInline;
  9885. limit = DEFAULT_ASSETS_INLINE_LIMIT;
  9886. } else {
  9887. limit = Number(assetsInlineLimit);
  9888. }
  9889. return content.length < limit && !isGitLfsPlaceholder(content);
  9890. }
  9891. function assetToDataURL(environment, file, content) {
  9892. if (environment.config.build.lib && isGitLfsPlaceholder(content)) {
  9893. environment.logger.warn(
  9894. colors$1.yellow(`Inlined file ${file} was not downloaded via Git LFS`)
  9895. );
  9896. }
  9897. if (file.endsWith(".svg")) {
  9898. return svgToDataURL(content);
  9899. } else {
  9900. const mimeType = lookup(file) ?? "application/octet-stream";
  9901. return `data:${mimeType};base64,${content.toString("base64")}`;
  9902. }
  9903. }
  9904. const nestedQuotesRE = /"[^"']*'[^"]*"|'[^'"]*"[^']*'/;
  9905. function svgToDataURL(content) {
  9906. const stringContent = content.toString();
  9907. if (stringContent.includes("<text") || stringContent.includes("<foreignObject") || nestedQuotesRE.test(stringContent)) {
  9908. return `data:image/svg+xml;base64,${content.toString("base64")}`;
  9909. } else {
  9910. return "data:image/svg+xml," + stringContent.trim().replaceAll(/>\s+</g, "><").replaceAll('"', "'").replaceAll("%", "%25").replaceAll("#", "%23").replaceAll("<", "%3c").replaceAll(">", "%3e").replaceAll(/\s+/g, "%20");
  9911. }
  9912. }
  9913. const endsWithJSRE = /\.[cm]?js$/;
  9914. function manifestPlugin() {
  9915. const getState = perEnvironmentState(() => {
  9916. return {
  9917. manifest: {},
  9918. outputCount: 0,
  9919. reset() {
  9920. this.manifest = {};
  9921. this.outputCount = 0;
  9922. }
  9923. };
  9924. });
  9925. return {
  9926. name: "vite:manifest",
  9927. perEnvironmentStartEndDuringDev: true,
  9928. applyToEnvironment(environment) {
  9929. return !!environment.config.build.manifest;
  9930. },
  9931. buildStart() {
  9932. getState(this).reset();
  9933. },
  9934. generateBundle({ format }, bundle) {
  9935. const state = getState(this);
  9936. const { manifest } = state;
  9937. const { root } = this.environment.config;
  9938. const buildOptions = this.environment.config.build;
  9939. function getChunkName(chunk) {
  9940. return getChunkOriginalFileName(chunk, root, format) ?? `_${path$b.basename(chunk.fileName)}`;
  9941. }
  9942. function getInternalImports(imports) {
  9943. const filteredImports = [];
  9944. for (const file of imports) {
  9945. if (bundle[file] === void 0) {
  9946. continue;
  9947. }
  9948. filteredImports.push(getChunkName(bundle[file]));
  9949. }
  9950. return filteredImports;
  9951. }
  9952. function createChunk(chunk) {
  9953. const manifestChunk = {
  9954. file: chunk.fileName,
  9955. name: chunk.name
  9956. };
  9957. if (chunk.facadeModuleId) {
  9958. manifestChunk.src = getChunkName(chunk);
  9959. }
  9960. if (chunk.isEntry) {
  9961. manifestChunk.isEntry = true;
  9962. }
  9963. if (chunk.isDynamicEntry) {
  9964. manifestChunk.isDynamicEntry = true;
  9965. }
  9966. if (chunk.imports.length) {
  9967. const internalImports = getInternalImports(chunk.imports);
  9968. if (internalImports.length > 0) {
  9969. manifestChunk.imports = internalImports;
  9970. }
  9971. }
  9972. if (chunk.dynamicImports.length) {
  9973. const internalImports = getInternalImports(chunk.dynamicImports);
  9974. if (internalImports.length > 0) {
  9975. manifestChunk.dynamicImports = internalImports;
  9976. }
  9977. }
  9978. if (chunk.viteMetadata?.importedCss.size) {
  9979. manifestChunk.css = [...chunk.viteMetadata.importedCss];
  9980. }
  9981. if (chunk.viteMetadata?.importedAssets.size) {
  9982. manifestChunk.assets = [...chunk.viteMetadata.importedAssets];
  9983. }
  9984. return manifestChunk;
  9985. }
  9986. function createAsset(asset, src, isEntry) {
  9987. const manifestChunk = {
  9988. file: asset.fileName,
  9989. src
  9990. };
  9991. if (isEntry) manifestChunk.isEntry = true;
  9992. return manifestChunk;
  9993. }
  9994. const entryCssReferenceIds = cssEntriesMap.get(this.environment);
  9995. const entryCssAssetFileNames = new Set(entryCssReferenceIds);
  9996. for (const id of entryCssReferenceIds) {
  9997. try {
  9998. const fileName = this.getFileName(id);
  9999. entryCssAssetFileNames.add(fileName);
  10000. } catch {
  10001. }
  10002. }
  10003. for (const file in bundle) {
  10004. const chunk = bundle[file];
  10005. if (chunk.type === "chunk") {
  10006. manifest[getChunkName(chunk)] = createChunk(chunk);
  10007. } else if (chunk.type === "asset" && chunk.names.length > 0) {
  10008. const src = chunk.originalFileNames.length > 0 ? chunk.originalFileNames[0] : `_${path$b.basename(chunk.fileName)}`;
  10009. const isEntry = entryCssAssetFileNames.has(chunk.fileName);
  10010. const asset = createAsset(chunk, src, isEntry);
  10011. const file2 = manifest[src]?.file;
  10012. if (!(file2 && endsWithJSRE.test(file2))) {
  10013. manifest[src] = asset;
  10014. }
  10015. for (const originalFileName of chunk.originalFileNames.slice(1)) {
  10016. const file3 = manifest[originalFileName]?.file;
  10017. if (!(file3 && endsWithJSRE.test(file3))) {
  10018. manifest[originalFileName] = asset;
  10019. }
  10020. }
  10021. }
  10022. }
  10023. state.outputCount++;
  10024. const output = buildOptions.rollupOptions.output;
  10025. const outputLength = Array.isArray(output) ? output.length : 1;
  10026. if (state.outputCount >= outputLength) {
  10027. this.emitFile({
  10028. fileName: typeof buildOptions.manifest === "string" ? buildOptions.manifest : ".vite/manifest.json",
  10029. type: "asset",
  10030. source: JSON.stringify(sortObjectKeys(manifest), void 0, 2)
  10031. });
  10032. }
  10033. }
  10034. };
  10035. }
  10036. function getChunkOriginalFileName(chunk, root, format) {
  10037. if (chunk.facadeModuleId) {
  10038. let name = normalizePath$3(path$b.relative(root, chunk.facadeModuleId));
  10039. if (format === "system" && !chunk.name.includes("-legacy")) {
  10040. const ext = path$b.extname(name);
  10041. const endPos = ext.length !== 0 ? -ext.length : void 0;
  10042. name = `${name.slice(0, endPos)}-legacy${ext}`;
  10043. }
  10044. return name.replace(/\0/g, "");
  10045. }
  10046. }
  10047. const dataUriRE = /^([^/]+\/[^;,]+)(;base64)?,([\s\S]*)$/;
  10048. const base64RE = /base64/i;
  10049. const dataUriPrefix = `\0/@data-uri/`;
  10050. function dataURIPlugin() {
  10051. let resolved;
  10052. return {
  10053. name: "vite:data-uri",
  10054. buildStart() {
  10055. resolved = /* @__PURE__ */ new Map();
  10056. },
  10057. resolveId(id) {
  10058. if (!id.trimStart().startsWith("data:")) {
  10059. return;
  10060. }
  10061. const uri = new URL$3(id);
  10062. if (uri.protocol !== "data:") {
  10063. return;
  10064. }
  10065. const match = dataUriRE.exec(uri.pathname);
  10066. if (!match) {
  10067. return;
  10068. }
  10069. const [, mime, format, data] = match;
  10070. if (mime !== "text/javascript") {
  10071. throw new Error(
  10072. `data URI with non-JavaScript mime type is not supported. If you're using legacy JavaScript MIME types (such as 'application/javascript'), please use 'text/javascript' instead.`
  10073. );
  10074. }
  10075. const base64 = format && base64RE.test(format.substring(1));
  10076. const content = base64 ? Buffer.from(data, "base64").toString("utf-8") : data;
  10077. resolved.set(id, content);
  10078. return dataUriPrefix + id;
  10079. },
  10080. load(id) {
  10081. if (id.startsWith(dataUriPrefix)) {
  10082. return resolved.get(id.slice(dataUriPrefix.length));
  10083. }
  10084. }
  10085. };
  10086. }
  10087. /* es-module-lexer 1.6.0 */
  10088. var ImportType;!function(A){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";}(ImportType||(ImportType={}));const A=1===new Uint8Array(new Uint16Array([1]).buffer)[0];function parse$d(E,g="@"){if(!C)return init.then((()=>parse$d(E)));const I=E.length+1,w=(C.__heap_base.value||C.__heap_base)+4*I-C.memory.buffer.byteLength;w>0&&C.memory.grow(Math.ceil(w/65536));const K=C.sa(I-1);if((A?B:Q)(E,new Uint16Array(C.memory.buffer,K,I)),!C.parse())throw Object.assign(new Error(`Parse error ${g}:${E.slice(0,C.e()).split("\n").length}:${C.e()-E.lastIndexOf("\n",C.e()-1)}`),{idx:C.e()});const o=[],D=[];for(;C.ri();){const A=C.is(),Q=C.ie(),B=C.it(),g=C.ai(),I=C.id(),w=C.ss(),K=C.se();let D;C.ip()&&(D=k(E.slice(-1===I?A-1:A,-1===I?Q+1:Q))),o.push({n:D,t:B,s:A,e:Q,ss:w,se:K,d:I,a:g});}for(;C.re();){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]:"";D.push({s:A,e:Q,ls:B,le:g,n:'"'===w||"'"===w?k(I):I,ln:'"'===o||"'"===o?k(K):K});}function k(A){try{return (0, eval)(A)}catch(A){}}return [o,D,!!C.f(),!!C.ms()]}function Q(A,Q){const B=A.length;let C=0;for(;C<B;){const B=A.charCodeAt(C);Q[C++]=(255&B)<<8|B>>>8;}}function B(A,Q){const B=A.length;let C=0;for(;C<B;)Q[C]=A.charCodeAt(C++);}let C;const E=()=>{return A="AGFzbQEAAAABKwhgAX8Bf2AEf39/fwBgAAF/YAAAYAF/AGADf39/AX9gAn9/AX9gA39/fwADMTAAAQECAgICAgICAgICAgICAgICAgIAAwMDBAQAAAUAAAAAAAMDAwAGAAAABwAGAgUEBQFwAQEBBQMBAAEGDwJ/AUHA8gALfwBBwPIACwd6FQZtZW1vcnkCAAJzYQAAAWUAAwJpcwAEAmllAAUCc3MABgJzZQAHAml0AAgCYWkACQJpZAAKAmlwAAsCZXMADAJlZQANA2VscwAOA2VsZQAPAnJpABACcmUAEQFmABICbXMAEwVwYXJzZQAUC19faGVhcF9iYXNlAwEKm0EwaAEBf0EAIAA2AoAKQQAoAtwJIgEgAEEBdGoiAEEAOwEAQQAgAEECaiIANgKECkEAIAA2AogKQQBBADYC4AlBAEEANgLwCUEAQQA2AugJQQBBADYC5AlBAEEANgL4CUEAQQA2AuwJIAEL0wEBA39BACgC8AkhBEEAQQAoAogKIgU2AvAJQQAgBDYC9AlBACAFQSRqNgKICiAEQSBqQeAJIAQbIAU2AgBBACgC1AkhBEEAKALQCSEGIAUgATYCACAFIAA2AgggBSACIAJBAmpBACAGIANGIgAbIAQgA0YiBBs2AgwgBSADNgIUIAVBADYCECAFIAI2AgQgBUEANgIgIAVBA0EBQQIgABsgBBs2AhwgBUEAKALQCSADRiICOgAYAkACQCACDQBBACgC1AkgA0cNAQtBAEEBOgCMCgsLXgEBf0EAKAL4CSIEQRBqQeQJIAQbQQAoAogKIgQ2AgBBACAENgL4CUEAIARBFGo2AogKQQBBAToAjAogBEEANgIQIAQgAzYCDCAEIAI2AgggBCABNgIEIAQgADYCAAsIAEEAKAKQCgsVAEEAKALoCSgCAEEAKALcCWtBAXULHgEBf0EAKALoCSgCBCIAQQAoAtwJa0EBdUF/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+wBGDQMMAgsCQCACQVhqDgMBAwEACyACQaABRw0CC0EAIAVBEGo2ArAKAkBBARApIgVBKkcNAEEAQQAoArAKQQJqNgKwCkEBECkhBQsgBUEoRg0BC0EAKAKwCiEBIAUQLBpBACgCsAoiBSABTQ0AIAQgAyABIAUQAkEAQQAoArAKQX5qNgKwCg8LIAQgA0EAQQAQAkEAIARBDGo2ArAKDwsQJQvcCAEGf0EAIQBBAEEAKAKwCiIBQQxqIgI2ArAKQQEQKSEDQQAoArAKIQQCQAJAAkACQAJAAkACQAJAIANBLkcNAEEAIARBAmo2ArAKAkBBARApIgNB8wBGDQAgA0HtAEcNB0EAKAKwCiIDQQJqQZwIQQYQLw0HAkBBACgCnAoiBBAqDQAgBC8BAEEuRg0ICyABIAEgA0EIakEAKALUCRABDwtBACgCsAoiA0ECakGiCEEKEC8NBgJAQQAoApwKIgQQKg0AIAQvAQBBLkYNBwsgA0EMaiEDDAELIANB8wBHDQEgBCACTQ0BQQYhAEEAIQIgBEECakGiCEEKEC8NAiAEQQxqIQMCQCAELwEMIgVBd2oiBEEXSw0AQQEgBHRBn4CABHENAQsgBUGgAUcNAgtBACADNgKwCkEBIQBBARApIQMLAkACQAJAAkAgA0H7AEYNACADQShHDQFBACgCpApBAC8BmAoiA0EDdGoiBEEAKAKwCjYCBEEAIANBAWo7AZgKIARBBTYCAEEAKAKcCi8BAEEuRg0HQQBBACgCsAoiBEECajYCsApBARApIQMgAUEAKAKwCkEAIAQQAQJAAkAgAA0AQQAoAvAJIQQMAQtBACgC8AkiBEEFNgIcC0EAQQAvAZYKIgBBAWo7AZYKQQAoAqgKIABBAnRqIAQ2AgACQCADQSJGDQAgA0EnRg0AQQBBACgCsApBfmo2ArAKDwsgAxAaQQBBACgCsApBAmoiAzYCsAoCQAJAAkBBARApQVdqDgQBAgIAAgtBAEEAKAKwCkECajYCsApBARApGkEAKALwCSIEIAM2AgQgBEEBOgAYIARBACgCsAoiAzYCEEEAIANBfmo2ArAKDwtBACgC8AkiBCADNgIEIARBAToAGEEAQQAvAZgKQX9qOwGYCiAEQQAoArAKQQJqNgIMQQBBAC8BlgpBf2o7AZYKDwtBAEEAKAKwCkF+ajYCsAoPCyAADQJBACgCsAohA0EALwGYCg0BA0ACQAJAAkAgA0EAKAK0Ck8NAEEBECkiA0EiRg0BIANBJ0YNASADQf0ARw0CQQBBACgCsApBAmo2ArAKC0EBECkhBEEAKAKwCiEDAkAgBEHmAEcNACADQQJqQawIQQYQLw0JC0EAIANBCGo2ArAKAkBBARApIgNBIkYNACADQSdHDQkLIAEgA0EAECsPCyADEBoLQQBBACgCsApBAmoiAzYCsAoMAAsLIAANAUEGIQBBACECAkAgA0FZag4EBAMDBAALIANBIkYNAwwCC0EAIANBfmo2ArAKDwtBDCEAQQEhAgtBACgCsAoiAyABIABBAXRqRw0AQQAgA0F+ajYCsAoPC0EALwGYCg0CQQAoArAKIQNBACgCtAohAANAIAMgAE8NAQJAAkAgAy8BACIEQSdGDQAgBEEiRw0BCyABIAQgAhArDwtBACADQQJqIgM2ArAKDAALCxAlCw8LQQBBACgCsApBfmo2ArAKC0cBA39BACgCsApBAmohAEEAKAK0CiEBAkADQCAAIgJBfmogAU8NASACQQJqIQAgAi8BAEF2ag4EAQAAAQALC0EAIAI2ArAKC5gBAQN/QQBBACgCsAoiAUECajYCsAogAUEGaiEBQQAoArQKIQIDQAJAAkACQCABQXxqIAJPDQAgAUF+ai8BACEDAkACQCAADQAgA0EqRg0BIANBdmoOBAIEBAIECyADQSpHDQMLIAEvAQBBL0cNAkEAIAFBfmo2ArAKDAELIAFBfmohAQtBACABNgKwCg8LIAFBAmohAQwACwuIAQEEf0EAKAKwCiEBQQAoArQKIQICQAJAA0AgASIDQQJqIQEgAyACTw0BIAEvAQAiBCAARg0CAkAgBEHcAEYNACAEQXZqDgQCAQECAQsgA0EEaiEBIAMvAQRBDUcNACADQQZqIAEgAy8BBkEKRhshAQwACwtBACABNgKwChAlDwtBACABNgKwCgtsAQF/AkACQCAAQV9qIgFBBUsNAEEBIAF0QTFxDQELIABBRmpB//8DcUEGSQ0AIABBKUcgAEFYakH//wNxQQdJcQ0AAkAgAEGlf2oOBAEAAAEACyAAQf0ARyAAQYV/akH//wNxQQRJcQ8LQQELLgEBf0EBIQECQCAAQaYJQQUQHQ0AIABBlghBAxAdDQAgAEGwCUECEB0hAQsgAQtGAQN/QQAhAwJAIAAgAkEBdCICayIEQQJqIgBBACgC3AkiBUkNACAAIAEgAhAvDQACQCAAIAVHDQBBAQ8LIAQQJiEDCyADC4MBAQJ/QQEhAQJAAkACQAJAAkACQCAALwEAIgJBRWoOBAUEBAEACwJAIAJBm39qDgQDBAQCAAsgAkEpRg0EIAJB+QBHDQMgAEF+akG8CUEGEB0PCyAAQX5qLwEAQT1GDwsgAEF+akG0CUEEEB0PCyAAQX5qQcgJQQMQHQ8LQQAhAQsgAQu0AwECf0EAIQECQAJAAkACQAJAAkACQAJAAkACQCAALwEAQZx/ag4UAAECCQkJCQMJCQQFCQkGCQcJCQgJCwJAAkAgAEF+ai8BAEGXf2oOBAAKCgEKCyAAQXxqQcoIQQIQHQ8LIABBfGpBzghBAxAdDwsCQAJAAkAgAEF+ai8BAEGNf2oOAwABAgoLAkAgAEF8ai8BACICQeEARg0AIAJB7ABHDQogAEF6akHlABAnDwsgAEF6akHjABAnDwsgAEF8akHUCEEEEB0PCyAAQXxqQdwIQQYQHQ8LIABBfmovAQBB7wBHDQYgAEF8ai8BAEHlAEcNBgJAIABBemovAQAiAkHwAEYNACACQeMARw0HIABBeGpB6AhBBhAdDwsgAEF4akH0CEECEB0PCyAAQX5qQfgIQQQQHQ8LQQEhASAAQX5qIgBB6QAQJw0EIABBgAlBBRAdDwsgAEF+akHkABAnDwsgAEF+akGKCUEHEB0PCyAAQX5qQZgJQQQQHQ8LAkAgAEF+ai8BACICQe8ARg0AIAJB5QBHDQEgAEF8akHuABAnDwsgAEF8akGgCUEDEB0hAQsgAQs0AQF/QQEhAQJAIABBd2pB//8DcUEFSQ0AIABBgAFyQaABRg0AIABBLkcgABAocSEBCyABCzABAX8CQAJAIABBd2oiAUEXSw0AQQEgAXRBjYCABHENAQsgAEGgAUYNAEEADwtBAQtOAQJ/QQAhAQJAAkAgAC8BACICQeUARg0AIAJB6wBHDQEgAEF+akH4CEEEEB0PCyAAQX5qLwEAQfUARw0AIABBfGpB3AhBBhAdIQELIAEL3gEBBH9BACgCsAohAEEAKAK0CiEBAkACQAJAA0AgACICQQJqIQAgAiABTw0BAkACQAJAIAAvAQAiA0Gkf2oOBQIDAwMBAAsgA0EkRw0CIAIvAQRB+wBHDQJBACACQQRqIgA2ArAKQQBBAC8BmAoiAkEBajsBmApBACgCpAogAkEDdGoiAkEENgIAIAIgADYCBA8LQQAgADYCsApBAEEALwGYCkF/aiIAOwGYCkEAKAKkCiAAQf//A3FBA3RqKAIAQQNHDQMMBAsgAkEEaiEADAALC0EAIAA2ArAKCxAlCwtwAQJ/AkACQANAQQBBACgCsAoiAEECaiIBNgKwCiAAQQAoArQKTw0BAkACQAJAIAEvAQAiAUGlf2oOAgECAAsCQCABQXZqDgQEAwMEAAsgAUEvRw0CDAQLEC4aDAELQQAgAEEEajYCsAoMAAsLECULCzUBAX9BAEEBOgD8CUEAKAKwCiEAQQBBACgCtApBAmo2ArAKQQAgAEEAKALcCWtBAXU2ApAKC0MBAn9BASEBAkAgAC8BACICQXdqQf//A3FBBUkNACACQYABckGgAUYNAEEAIQEgAhAoRQ0AIAJBLkcgABAqcg8LIAELPQECf0EAIQICQEEAKALcCSIDIABLDQAgAC8BACABRw0AAkAgAyAARw0AQQEPCyAAQX5qLwEAECAhAgsgAgtoAQJ/QQEhAQJAAkAgAEFfaiICQQVLDQBBASACdEExcQ0BCyAAQfj/A3FBKEYNACAAQUZqQf//A3FBBkkNAAJAIABBpX9qIgJBA0sNACACQQFHDQELIABBhX9qQf//A3FBBEkhAQsgAQucAQEDf0EAKAKwCiEBAkADQAJAAkAgAS8BACICQS9HDQACQCABLwECIgFBKkYNACABQS9HDQQQGAwCCyAAEBkMAQsCQAJAIABFDQAgAkF3aiIBQRdLDQFBASABdEGfgIAEcUUNAQwCCyACECFFDQMMAQsgAkGgAUcNAgtBAEEAKAKwCiIDQQJqIgE2ArAKIANBACgCtApJDQALCyACCzEBAX9BACEBAkAgAC8BAEEuRw0AIABBfmovAQBBLkcNACAAQXxqLwEAQS5GIQELIAELnAQBAX8CQCABQSJGDQAgAUEnRg0AECUPC0EAKAKwCiEDIAEQGiAAIANBAmpBACgCsApBACgC0AkQAQJAIAJFDQBBACgC8AlBBDYCHAtBAEEAKAKwCkECajYCsAoCQAJAAkACQEEAECkiAUHhAEYNACABQfcARg0BQQAoArAKIQEMAgtBACgCsAoiAUECakHACEEKEC8NAUEGIQAMAgtBACgCsAoiAS8BAkHpAEcNACABLwEEQfQARw0AQQQhACABLwEGQegARg0BC0EAIAFBfmo2ArAKDwtBACABIABBAXRqNgKwCgJAQQEQKUH7AEYNAEEAIAE2ArAKDwtBACgCsAoiAiEAA0BBACAAQQJqNgKwCgJAAkACQEEBECkiAEEiRg0AIABBJ0cNAUEnEBpBAEEAKAKwCkECajYCsApBARApIQAMAgtBIhAaQQBBACgCsApBAmo2ArAKQQEQKSEADAELIAAQLCEACwJAIABBOkYNAEEAIAE2ArAKDwtBAEEAKAKwCkECajYCsAoCQEEBECkiAEEiRg0AIABBJ0YNAEEAIAE2ArAKDwsgABAaQQBBACgCsApBAmo2ArAKAkACQEEBECkiAEEsRg0AIABB/QBGDQFBACABNgKwCg8LQQBBACgCsApBAmo2ArAKQQEQKUH9AEYNAEEAKAKwCiEADAELC0EAKALwCSIBIAI2AhAgAUEAKAKwCkECajYCDAttAQJ/AkACQANAAkAgAEH//wNxIgFBd2oiAkEXSw0AQQEgAnRBn4CABHENAgsgAUGgAUYNASAAIQIgARAoDQJBACECQQBBACgCsAoiAEECajYCsAogAC8BAiIADQAMAgsLIAAhAgsgAkH//wNxC6sBAQR/AkACQEEAKAKwCiICLwEAIgNB4QBGDQAgASEEIAAhBQwBC0EAIAJBBGo2ArAKQQEQKSECQQAoArAKIQUCQAJAIAJBIkYNACACQSdGDQAgAhAsGkEAKAKwCiEEDAELIAIQGkEAQQAoArAKQQJqIgQ2ArAKC0EBECkhA0EAKAKwCiECCwJAIAIgBUYNACAFIARBACAAIAAgAUYiAhtBACABIAIbEAILIAMLcgEEf0EAKAKwCiEAQQAoArQKIQECQAJAA0AgAEECaiECIAAgAU8NAQJAAkAgAi8BACIDQaR/ag4CAQQACyACIQAgA0F2ag4EAgEBAgELIABBBGohAAwACwtBACACNgKwChAlQQAPC0EAIAI2ArAKQd0AC0kBA39BACEDAkAgAkUNAAJAA0AgAC0AACIEIAEtAAAiBUcNASABQQFqIQEgAEEBaiEAIAJBf2oiAg0ADAILCyAEIAVrIQMLIAMLC+wBAgBBgAgLzgEAAHgAcABvAHIAdABtAHAAbwByAHQAZgBvAHIAZQB0AGEAbwB1AHIAYwBlAHIAbwBtAHUAbgBjAHQAaQBvAG4AcwBzAGUAcgB0AHYAbwB5AGkAZQBkAGUAbABlAGMAbwBuAHQAaQBuAGkAbgBzAHQAYQBuAHQAeQBiAHIAZQBhAHIAZQB0AHUAcgBkAGUAYgB1AGcAZwBlAGEAdwBhAGkAdABoAHIAdwBoAGkAbABlAGkAZgBjAGEAdABjAGYAaQBuAGEAbABsAGUAbABzAABB0AkLEAEAAAACAAAAAAQAAEA5AAA=","undefined"!=typeof Buffer?Buffer.from(A,"base64"):Uint8Array.from(atob(A),(A=>A.charCodeAt(0)));var A;};const init=WebAssembly.compile(E()).then(WebAssembly.instantiate).then((({exports:A})=>{C=A;}));
  10089. var convertSourceMap$1 = {};
  10090. (function (exports) {
  10091. Object.defineProperty(exports, 'commentRegex', {
  10092. get: function getCommentRegex () {
  10093. // Groups: 1: media type, 2: MIME type, 3: charset, 4: encoding, 5: data.
  10094. return /^\s*?\/[\/\*][@#]\s+?sourceMappingURL=data:(((?:application|text)\/json)(?:;charset=([^;,]+?)?)?)?(?:;(base64))?,(.*?)$/mg;
  10095. }
  10096. });
  10097. Object.defineProperty(exports, 'mapFileCommentRegex', {
  10098. get: function getMapFileCommentRegex () {
  10099. // Matches sourceMappingURL in either // or /* comment styles.
  10100. return /(?:\/\/[@#][ \t]+?sourceMappingURL=([^\s'"`]+?)[ \t]*?$)|(?:\/\*[@#][ \t]+sourceMappingURL=([^*]+?)[ \t]*?(?:\*\/){1}[ \t]*?$)/mg;
  10101. }
  10102. });
  10103. var decodeBase64;
  10104. if (typeof Buffer !== 'undefined') {
  10105. if (typeof Buffer.from === 'function') {
  10106. decodeBase64 = decodeBase64WithBufferFrom;
  10107. } else {
  10108. decodeBase64 = decodeBase64WithNewBuffer;
  10109. }
  10110. } else {
  10111. decodeBase64 = decodeBase64WithAtob;
  10112. }
  10113. function decodeBase64WithBufferFrom(base64) {
  10114. return Buffer.from(base64, 'base64').toString();
  10115. }
  10116. function decodeBase64WithNewBuffer(base64) {
  10117. if (typeof value === 'number') {
  10118. throw new TypeError('The value to decode must not be of type number.');
  10119. }
  10120. return new Buffer(base64, 'base64').toString();
  10121. }
  10122. function decodeBase64WithAtob(base64) {
  10123. return decodeURIComponent(escape(atob(base64)));
  10124. }
  10125. function stripComment(sm) {
  10126. return sm.split(',').pop();
  10127. }
  10128. function readFromFileMap(sm, read) {
  10129. var r = exports.mapFileCommentRegex.exec(sm);
  10130. // for some odd reason //# .. captures in 1 and /* .. */ in 2
  10131. var filename = r[1] || r[2];
  10132. try {
  10133. var sm = read(filename);
  10134. if (sm != null && typeof sm.catch === 'function') {
  10135. return sm.catch(throwError);
  10136. } else {
  10137. return sm;
  10138. }
  10139. } catch (e) {
  10140. throwError(e);
  10141. }
  10142. function throwError(e) {
  10143. throw new Error('An error occurred while trying to read the map file at ' + filename + '\n' + e.stack);
  10144. }
  10145. }
  10146. function Converter (sm, opts) {
  10147. opts = opts || {};
  10148. if (opts.hasComment) {
  10149. sm = stripComment(sm);
  10150. }
  10151. if (opts.encoding === 'base64') {
  10152. sm = decodeBase64(sm);
  10153. } else if (opts.encoding === 'uri') {
  10154. sm = decodeURIComponent(sm);
  10155. }
  10156. if (opts.isJSON || opts.encoding) {
  10157. sm = JSON.parse(sm);
  10158. }
  10159. this.sourcemap = sm;
  10160. }
  10161. Converter.prototype.toJSON = function (space) {
  10162. return JSON.stringify(this.sourcemap, null, space);
  10163. };
  10164. if (typeof Buffer !== 'undefined') {
  10165. if (typeof Buffer.from === 'function') {
  10166. Converter.prototype.toBase64 = encodeBase64WithBufferFrom;
  10167. } else {
  10168. Converter.prototype.toBase64 = encodeBase64WithNewBuffer;
  10169. }
  10170. } else {
  10171. Converter.prototype.toBase64 = encodeBase64WithBtoa;
  10172. }
  10173. function encodeBase64WithBufferFrom() {
  10174. var json = this.toJSON();
  10175. return Buffer.from(json, 'utf8').toString('base64');
  10176. }
  10177. function encodeBase64WithNewBuffer() {
  10178. var json = this.toJSON();
  10179. if (typeof json === 'number') {
  10180. throw new TypeError('The json to encode must not be of type number.');
  10181. }
  10182. return new Buffer(json, 'utf8').toString('base64');
  10183. }
  10184. function encodeBase64WithBtoa() {
  10185. var json = this.toJSON();
  10186. return btoa(unescape(encodeURIComponent(json)));
  10187. }
  10188. Converter.prototype.toURI = function () {
  10189. var json = this.toJSON();
  10190. return encodeURIComponent(json);
  10191. };
  10192. Converter.prototype.toComment = function (options) {
  10193. var encoding, content, data;
  10194. if (options != null && options.encoding === 'uri') {
  10195. encoding = '';
  10196. content = this.toURI();
  10197. } else {
  10198. encoding = ';base64';
  10199. content = this.toBase64();
  10200. }
  10201. data = 'sourceMappingURL=data:application/json;charset=utf-8' + encoding + ',' + content;
  10202. return options != null && options.multiline ? '/*# ' + data + ' */' : '//# ' + data;
  10203. };
  10204. // returns copy instead of original
  10205. Converter.prototype.toObject = function () {
  10206. return JSON.parse(this.toJSON());
  10207. };
  10208. Converter.prototype.addProperty = function (key, value) {
  10209. if (this.sourcemap.hasOwnProperty(key)) throw new Error('property "' + key + '" already exists on the sourcemap, use set property instead');
  10210. return this.setProperty(key, value);
  10211. };
  10212. Converter.prototype.setProperty = function (key, value) {
  10213. this.sourcemap[key] = value;
  10214. return this;
  10215. };
  10216. Converter.prototype.getProperty = function (key) {
  10217. return this.sourcemap[key];
  10218. };
  10219. exports.fromObject = function (obj) {
  10220. return new Converter(obj);
  10221. };
  10222. exports.fromJSON = function (json) {
  10223. return new Converter(json, { isJSON: true });
  10224. };
  10225. exports.fromURI = function (uri) {
  10226. return new Converter(uri, { encoding: 'uri' });
  10227. };
  10228. exports.fromBase64 = function (base64) {
  10229. return new Converter(base64, { encoding: 'base64' });
  10230. };
  10231. exports.fromComment = function (comment) {
  10232. var m, encoding;
  10233. comment = comment
  10234. .replace(/^\/\*/g, '//')
  10235. .replace(/\*\/$/g, '');
  10236. m = exports.commentRegex.exec(comment);
  10237. encoding = m && m[4] || 'uri';
  10238. return new Converter(comment, { encoding: encoding, hasComment: true });
  10239. };
  10240. function makeConverter(sm) {
  10241. return new Converter(sm, { isJSON: true });
  10242. }
  10243. exports.fromMapFileComment = function (comment, read) {
  10244. if (typeof read === 'string') {
  10245. throw new Error(
  10246. 'String directory paths are no longer supported with `fromMapFileComment`\n' +
  10247. 'Please review the Upgrading documentation at https://github.com/thlorenz/convert-source-map#upgrading'
  10248. )
  10249. }
  10250. var sm = readFromFileMap(comment, read);
  10251. if (sm != null && typeof sm.then === 'function') {
  10252. return sm.then(makeConverter);
  10253. } else {
  10254. return makeConverter(sm);
  10255. }
  10256. };
  10257. // Finds last sourcemap comment in file or returns null if none was found
  10258. exports.fromSource = function (content) {
  10259. var m = content.match(exports.commentRegex);
  10260. return m ? exports.fromComment(m.pop()) : null;
  10261. };
  10262. // Finds last sourcemap comment in file or returns null if none was found
  10263. exports.fromMapFileSource = function (content, read) {
  10264. if (typeof read === 'string') {
  10265. throw new Error(
  10266. 'String directory paths are no longer supported with `fromMapFileSource`\n' +
  10267. 'Please review the Upgrading documentation at https://github.com/thlorenz/convert-source-map#upgrading'
  10268. )
  10269. }
  10270. var m = content.match(exports.mapFileCommentRegex);
  10271. return m ? exports.fromMapFileComment(m.pop(), read) : null;
  10272. };
  10273. exports.removeComments = function (src) {
  10274. return src.replace(exports.commentRegex, '');
  10275. };
  10276. exports.removeMapFileComments = function (src) {
  10277. return src.replace(exports.mapFileCommentRegex, '');
  10278. };
  10279. exports.generateMapFileComment = function (file, options) {
  10280. var data = 'sourceMappingURL=' + file;
  10281. return options && options.multiline ? '/*# ' + data + ' */' : '//# ' + data;
  10282. };
  10283. } (convertSourceMap$1));
  10284. var convertSourceMap = /*@__PURE__*/getDefaultExportFromCjs(convertSourceMap$1);
  10285. const debug$h = createDebugger("vite:sourcemap", {
  10286. onlyWhenFocused: true
  10287. });
  10288. const virtualSourceRE = /^(?:dep:|browser-external:|virtual:)|\0/;
  10289. async function computeSourceRoute(map, file) {
  10290. let sourceRoot;
  10291. try {
  10292. sourceRoot = await fsp.realpath(
  10293. path$b.resolve(path$b.dirname(file), map.sourceRoot || "")
  10294. );
  10295. } catch {
  10296. }
  10297. return sourceRoot;
  10298. }
  10299. async function injectSourcesContent(map, file, logger) {
  10300. let sourceRootPromise;
  10301. const missingSources = [];
  10302. const sourcesContent = map.sourcesContent || [];
  10303. const sourcesContentPromises = [];
  10304. for (let index = 0; index < map.sources.length; index++) {
  10305. const sourcePath = map.sources[index];
  10306. if (sourcesContent[index] == null && sourcePath && !virtualSourceRE.test(sourcePath)) {
  10307. sourcesContentPromises.push(
  10308. (async () => {
  10309. sourceRootPromise ??= computeSourceRoute(map, file);
  10310. const sourceRoot = await sourceRootPromise;
  10311. let resolvedSourcePath = cleanUrl(decodeURI(sourcePath));
  10312. if (sourceRoot) {
  10313. resolvedSourcePath = path$b.resolve(sourceRoot, resolvedSourcePath);
  10314. }
  10315. sourcesContent[index] = await fsp.readFile(resolvedSourcePath, "utf-8").catch(() => {
  10316. missingSources.push(resolvedSourcePath);
  10317. return null;
  10318. });
  10319. })()
  10320. );
  10321. }
  10322. }
  10323. await Promise.all(sourcesContentPromises);
  10324. map.sourcesContent = sourcesContent;
  10325. if (missingSources.length) {
  10326. logger.warnOnce(`Sourcemap for "${file}" points to missing source files`);
  10327. debug$h?.(`Missing sources:
  10328. ` + missingSources.join(`
  10329. `));
  10330. }
  10331. }
  10332. function genSourceMapUrl(map) {
  10333. if (typeof map !== "string") {
  10334. map = JSON.stringify(map);
  10335. }
  10336. return `data:application/json;base64,${Buffer.from(map).toString("base64")}`;
  10337. }
  10338. function getCodeWithSourcemap(type, code, map) {
  10339. if (debug$h) {
  10340. code += `
  10341. /*${JSON.stringify(map, null, 2).replace(/\*\//g, "*\\/")}*/
  10342. `;
  10343. }
  10344. if (type === "js") {
  10345. code += `
  10346. //# sourceMappingURL=${genSourceMapUrl(map)}`;
  10347. } else if (type === "css") {
  10348. code += `
  10349. /*# sourceMappingURL=${genSourceMapUrl(map)} */`;
  10350. }
  10351. return code;
  10352. }
  10353. function applySourcemapIgnoreList(map, sourcemapPath, sourcemapIgnoreList, logger) {
  10354. let { x_google_ignoreList } = map;
  10355. if (x_google_ignoreList === void 0) {
  10356. x_google_ignoreList = [];
  10357. }
  10358. for (let sourcesIndex = 0; sourcesIndex < map.sources.length; ++sourcesIndex) {
  10359. const sourcePath = map.sources[sourcesIndex];
  10360. if (!sourcePath) continue;
  10361. const ignoreList = sourcemapIgnoreList(
  10362. path$b.isAbsolute(sourcePath) ? sourcePath : path$b.resolve(path$b.dirname(sourcemapPath), sourcePath),
  10363. sourcemapPath
  10364. );
  10365. if (logger && typeof ignoreList !== "boolean") {
  10366. logger.warn("sourcemapIgnoreList function must return a boolean.");
  10367. }
  10368. if (ignoreList && !x_google_ignoreList.includes(sourcesIndex)) {
  10369. x_google_ignoreList.push(sourcesIndex);
  10370. }
  10371. }
  10372. if (x_google_ignoreList.length > 0) {
  10373. if (!map.x_google_ignoreList) map.x_google_ignoreList = x_google_ignoreList;
  10374. }
  10375. }
  10376. async function extractSourcemapFromFile(code, filePath) {
  10377. const map = (convertSourceMap.fromSource(code) || await convertSourceMap.fromMapFileSource(
  10378. code,
  10379. createConvertSourceMapReadMap(filePath)
  10380. ))?.toObject();
  10381. if (map) {
  10382. return {
  10383. code: code.replace(convertSourceMap.mapFileCommentRegex, blankReplacer),
  10384. map
  10385. };
  10386. }
  10387. }
  10388. function createConvertSourceMapReadMap(originalFileName) {
  10389. return (filename) => {
  10390. return fsp.readFile(
  10391. path$b.resolve(path$b.dirname(originalFileName), filename),
  10392. "utf-8"
  10393. );
  10394. };
  10395. }
  10396. var src$1 = {};
  10397. // @ts-check
  10398. const path$9 = require$$0$2;
  10399. const fs$7 = require$$0$4;
  10400. const os$2 = require$$2;
  10401. const url$4 = require$$0$5;
  10402. const fsReadFileAsync = fs$7.promises.readFile;
  10403. /** @type {(name: string, sync: boolean) => string[]} */
  10404. function getDefaultSearchPlaces(name, sync) {
  10405. return [
  10406. 'package.json',
  10407. `.${name}rc.json`,
  10408. `.${name}rc.js`,
  10409. `.${name}rc.cjs`,
  10410. ...(sync ? [] : [`.${name}rc.mjs`]),
  10411. `.config/${name}rc`,
  10412. `.config/${name}rc.json`,
  10413. `.config/${name}rc.js`,
  10414. `.config/${name}rc.cjs`,
  10415. ...(sync ? [] : [`.config/${name}rc.mjs`]),
  10416. `${name}.config.js`,
  10417. `${name}.config.cjs`,
  10418. ...(sync ? [] : [`${name}.config.mjs`]),
  10419. ];
  10420. }
  10421. /**
  10422. * @type {(p: string) => string}
  10423. *
  10424. * see #17
  10425. * On *nix, if cwd is not under homedir,
  10426. * the last path will be '', ('/build' -> '')
  10427. * but it should be '/' actually.
  10428. * And on Windows, this will never happen. ('C:\build' -> 'C:')
  10429. */
  10430. function parentDir(p) {
  10431. return path$9.dirname(p) || path$9.sep;
  10432. }
  10433. /** @type {import('./index').LoaderSync} */
  10434. const jsonLoader = (_, content) => JSON.parse(content);
  10435. // Use plain require in webpack context for dynamic import
  10436. const requireFunc =
  10437. typeof __webpack_require__ === 'function' ? __non_webpack_require__ : __require;
  10438. /** @type {import('./index').LoadersSync} */
  10439. const defaultLoadersSync = Object.freeze({
  10440. '.js': requireFunc,
  10441. '.json': requireFunc,
  10442. '.cjs': requireFunc,
  10443. noExt: jsonLoader,
  10444. });
  10445. src$1.defaultLoadersSync = defaultLoadersSync;
  10446. /** @type {import('./index').Loader} */
  10447. const dynamicImport = async id => {
  10448. try {
  10449. const fileUrl = url$4.pathToFileURL(id).href;
  10450. const mod = await import(/* webpackIgnore: true */ fileUrl);
  10451. return mod.default;
  10452. } catch (e) {
  10453. try {
  10454. return requireFunc(id);
  10455. } catch (/** @type {any} */ requireE) {
  10456. if (
  10457. requireE.code === 'ERR_REQUIRE_ESM' ||
  10458. (requireE instanceof SyntaxError &&
  10459. requireE
  10460. .toString()
  10461. .includes('Cannot use import statement outside a module'))
  10462. ) {
  10463. throw e;
  10464. }
  10465. throw requireE;
  10466. }
  10467. }
  10468. };
  10469. /** @type {import('./index').Loaders} */
  10470. const defaultLoaders = Object.freeze({
  10471. '.js': dynamicImport,
  10472. '.mjs': dynamicImport,
  10473. '.cjs': dynamicImport,
  10474. '.json': jsonLoader,
  10475. noExt: jsonLoader,
  10476. });
  10477. src$1.defaultLoaders = defaultLoaders;
  10478. /**
  10479. * @param {string} name
  10480. * @param {import('./index').Options | import('./index').OptionsSync} options
  10481. * @param {boolean} sync
  10482. * @returns {Required<import('./index').Options | import('./index').OptionsSync>}
  10483. */
  10484. function getOptions(name, options, sync) {
  10485. /** @type {Required<import('./index').Options>} */
  10486. const conf = {
  10487. stopDir: os$2.homedir(),
  10488. searchPlaces: getDefaultSearchPlaces(name, sync),
  10489. ignoreEmptySearchPlaces: true,
  10490. cache: true,
  10491. transform: x => x,
  10492. packageProp: [name],
  10493. ...options,
  10494. loaders: {
  10495. ...(sync ? defaultLoadersSync : defaultLoaders),
  10496. ...options.loaders,
  10497. },
  10498. };
  10499. conf.searchPlaces.forEach(place => {
  10500. const key = path$9.extname(place) || 'noExt';
  10501. const loader = conf.loaders[key];
  10502. if (!loader) {
  10503. throw new Error(`Missing loader for extension "${place}"`);
  10504. }
  10505. if (typeof loader !== 'function') {
  10506. throw new Error(
  10507. `Loader for extension "${place}" is not a function: Received ${typeof loader}.`,
  10508. );
  10509. }
  10510. });
  10511. return conf;
  10512. }
  10513. /** @type {(props: string | string[], obj: Record<string, any>) => unknown} */
  10514. function getPackageProp(props, obj) {
  10515. if (typeof props === 'string' && props in obj) return obj[props];
  10516. return (
  10517. (Array.isArray(props) ? props : props.split('.')).reduce(
  10518. (acc, prop) => (acc === undefined ? acc : acc[prop]),
  10519. obj,
  10520. ) || null
  10521. );
  10522. }
  10523. /** @param {string} filepath */
  10524. function validateFilePath(filepath) {
  10525. if (!filepath) throw new Error('load must pass a non-empty string');
  10526. }
  10527. /** @type {(loader: import('./index').Loader, ext: string) => void} */
  10528. function validateLoader(loader, ext) {
  10529. if (!loader) throw new Error(`No loader specified for extension "${ext}"`);
  10530. if (typeof loader !== 'function') throw new Error('loader is not a function');
  10531. }
  10532. /** @type {(enableCache: boolean) => <T>(c: Map<string, T>, filepath: string, res: T) => T} */
  10533. const makeEmplace = enableCache => (c, filepath, res) => {
  10534. if (enableCache) c.set(filepath, res);
  10535. return res;
  10536. };
  10537. /** @type {import('./index').lilconfig} */
  10538. src$1.lilconfig = function lilconfig(name, options) {
  10539. const {
  10540. ignoreEmptySearchPlaces,
  10541. loaders,
  10542. packageProp,
  10543. searchPlaces,
  10544. stopDir,
  10545. transform,
  10546. cache,
  10547. } = getOptions(name, options ?? {}, false);
  10548. const searchCache = new Map();
  10549. const loadCache = new Map();
  10550. const emplace = makeEmplace(cache);
  10551. return {
  10552. async search(searchFrom = process.cwd()) {
  10553. /** @type {import('./index').LilconfigResult} */
  10554. const result = {
  10555. config: null,
  10556. filepath: '',
  10557. };
  10558. /** @type {Set<string>} */
  10559. const visited = new Set();
  10560. let dir = searchFrom;
  10561. dirLoop: while (true) {
  10562. if (cache) {
  10563. const r = searchCache.get(dir);
  10564. if (r !== undefined) {
  10565. for (const p of visited) searchCache.set(p, r);
  10566. return r;
  10567. }
  10568. visited.add(dir);
  10569. }
  10570. for (const searchPlace of searchPlaces) {
  10571. const filepath = path$9.join(dir, searchPlace);
  10572. try {
  10573. await fs$7.promises.access(filepath);
  10574. } catch {
  10575. continue;
  10576. }
  10577. const content = String(await fsReadFileAsync(filepath));
  10578. const loaderKey = path$9.extname(searchPlace) || 'noExt';
  10579. const loader = loaders[loaderKey];
  10580. // handle package.json
  10581. if (searchPlace === 'package.json') {
  10582. const pkg = await loader(filepath, content);
  10583. const maybeConfig = getPackageProp(packageProp, pkg);
  10584. if (maybeConfig != null) {
  10585. result.config = maybeConfig;
  10586. result.filepath = filepath;
  10587. break dirLoop;
  10588. }
  10589. continue;
  10590. }
  10591. // handle other type of configs
  10592. const isEmpty = content.trim() === '';
  10593. if (isEmpty && ignoreEmptySearchPlaces) continue;
  10594. if (isEmpty) {
  10595. result.isEmpty = true;
  10596. result.config = undefined;
  10597. } else {
  10598. validateLoader(loader, loaderKey);
  10599. result.config = await loader(filepath, content);
  10600. }
  10601. result.filepath = filepath;
  10602. break dirLoop;
  10603. }
  10604. if (dir === stopDir || dir === parentDir(dir)) break dirLoop;
  10605. dir = parentDir(dir);
  10606. }
  10607. const transformed =
  10608. // not found
  10609. result.filepath === '' && result.config === null
  10610. ? transform(null)
  10611. : transform(result);
  10612. if (cache) {
  10613. for (const p of visited) searchCache.set(p, transformed);
  10614. }
  10615. return transformed;
  10616. },
  10617. async load(filepath) {
  10618. validateFilePath(filepath);
  10619. const absPath = path$9.resolve(process.cwd(), filepath);
  10620. if (cache && loadCache.has(absPath)) {
  10621. return loadCache.get(absPath);
  10622. }
  10623. const {base, ext} = path$9.parse(absPath);
  10624. const loaderKey = ext || 'noExt';
  10625. const loader = loaders[loaderKey];
  10626. validateLoader(loader, loaderKey);
  10627. const content = String(await fsReadFileAsync(absPath));
  10628. if (base === 'package.json') {
  10629. const pkg = await loader(absPath, content);
  10630. return emplace(
  10631. loadCache,
  10632. absPath,
  10633. transform({
  10634. config: getPackageProp(packageProp, pkg),
  10635. filepath: absPath,
  10636. }),
  10637. );
  10638. }
  10639. /** @type {import('./index').LilconfigResult} */
  10640. const result = {
  10641. config: null,
  10642. filepath: absPath,
  10643. };
  10644. // handle other type of configs
  10645. const isEmpty = content.trim() === '';
  10646. if (isEmpty && ignoreEmptySearchPlaces)
  10647. return emplace(
  10648. loadCache,
  10649. absPath,
  10650. transform({
  10651. config: undefined,
  10652. filepath: absPath,
  10653. isEmpty: true,
  10654. }),
  10655. );
  10656. // cosmiconfig returns undefined for empty files
  10657. result.config = isEmpty ? undefined : await loader(absPath, content);
  10658. return emplace(
  10659. loadCache,
  10660. absPath,
  10661. transform(isEmpty ? {...result, isEmpty, config: undefined} : result),
  10662. );
  10663. },
  10664. clearLoadCache() {
  10665. if (cache) loadCache.clear();
  10666. },
  10667. clearSearchCache() {
  10668. if (cache) searchCache.clear();
  10669. },
  10670. clearCaches() {
  10671. if (cache) {
  10672. loadCache.clear();
  10673. searchCache.clear();
  10674. }
  10675. },
  10676. };
  10677. };
  10678. /** @type {import('./index').lilconfigSync} */
  10679. src$1.lilconfigSync = function lilconfigSync(name, options) {
  10680. const {
  10681. ignoreEmptySearchPlaces,
  10682. loaders,
  10683. packageProp,
  10684. searchPlaces,
  10685. stopDir,
  10686. transform,
  10687. cache,
  10688. } = getOptions(name, options ?? {}, true);
  10689. const searchCache = new Map();
  10690. const loadCache = new Map();
  10691. const emplace = makeEmplace(cache);
  10692. return {
  10693. search(searchFrom = process.cwd()) {
  10694. /** @type {import('./index').LilconfigResult} */
  10695. const result = {
  10696. config: null,
  10697. filepath: '',
  10698. };
  10699. /** @type {Set<string>} */
  10700. const visited = new Set();
  10701. let dir = searchFrom;
  10702. dirLoop: while (true) {
  10703. if (cache) {
  10704. const r = searchCache.get(dir);
  10705. if (r !== undefined) {
  10706. for (const p of visited) searchCache.set(p, r);
  10707. return r;
  10708. }
  10709. visited.add(dir);
  10710. }
  10711. for (const searchPlace of searchPlaces) {
  10712. const filepath = path$9.join(dir, searchPlace);
  10713. try {
  10714. fs$7.accessSync(filepath);
  10715. } catch {
  10716. continue;
  10717. }
  10718. const loaderKey = path$9.extname(searchPlace) || 'noExt';
  10719. const loader = loaders[loaderKey];
  10720. const content = String(fs$7.readFileSync(filepath));
  10721. // handle package.json
  10722. if (searchPlace === 'package.json') {
  10723. const pkg = loader(filepath, content);
  10724. const maybeConfig = getPackageProp(packageProp, pkg);
  10725. if (maybeConfig != null) {
  10726. result.config = maybeConfig;
  10727. result.filepath = filepath;
  10728. break dirLoop;
  10729. }
  10730. continue;
  10731. }
  10732. // handle other type of configs
  10733. const isEmpty = content.trim() === '';
  10734. if (isEmpty && ignoreEmptySearchPlaces) continue;
  10735. if (isEmpty) {
  10736. result.isEmpty = true;
  10737. result.config = undefined;
  10738. } else {
  10739. validateLoader(loader, loaderKey);
  10740. result.config = loader(filepath, content);
  10741. }
  10742. result.filepath = filepath;
  10743. break dirLoop;
  10744. }
  10745. if (dir === stopDir || dir === parentDir(dir)) break dirLoop;
  10746. dir = parentDir(dir);
  10747. }
  10748. const transformed =
  10749. // not found
  10750. result.filepath === '' && result.config === null
  10751. ? transform(null)
  10752. : transform(result);
  10753. if (cache) {
  10754. for (const p of visited) searchCache.set(p, transformed);
  10755. }
  10756. return transformed;
  10757. },
  10758. load(filepath) {
  10759. validateFilePath(filepath);
  10760. const absPath = path$9.resolve(process.cwd(), filepath);
  10761. if (cache && loadCache.has(absPath)) {
  10762. return loadCache.get(absPath);
  10763. }
  10764. const {base, ext} = path$9.parse(absPath);
  10765. const loaderKey = ext || 'noExt';
  10766. const loader = loaders[loaderKey];
  10767. validateLoader(loader, loaderKey);
  10768. const content = String(fs$7.readFileSync(absPath));
  10769. if (base === 'package.json') {
  10770. const pkg = loader(absPath, content);
  10771. return transform({
  10772. config: getPackageProp(packageProp, pkg),
  10773. filepath: absPath,
  10774. });
  10775. }
  10776. const result = {
  10777. config: null,
  10778. filepath: absPath,
  10779. };
  10780. // handle other type of configs
  10781. const isEmpty = content.trim() === '';
  10782. if (isEmpty && ignoreEmptySearchPlaces)
  10783. return emplace(
  10784. loadCache,
  10785. absPath,
  10786. transform({
  10787. filepath: absPath,
  10788. config: undefined,
  10789. isEmpty: true,
  10790. }),
  10791. );
  10792. // cosmiconfig returns undefined for empty files
  10793. result.config = isEmpty ? undefined : loader(absPath, content);
  10794. return emplace(
  10795. loadCache,
  10796. absPath,
  10797. transform(isEmpty ? {...result, isEmpty, config: undefined} : result),
  10798. );
  10799. },
  10800. clearLoadCache() {
  10801. if (cache) loadCache.clear();
  10802. },
  10803. clearSearchCache() {
  10804. if (cache) searchCache.clear();
  10805. },
  10806. clearCaches() {
  10807. if (cache) {
  10808. loadCache.clear();
  10809. searchCache.clear();
  10810. }
  10811. },
  10812. };
  10813. };
  10814. // @ts-check
  10815. const { createRequire } = require$$0$6;
  10816. const { fileURLToPath, pathToFileURL } = require$$1$1;
  10817. const TS_EXT_RE = /\.[mc]?ts$/;
  10818. let tsx;
  10819. let jiti;
  10820. let importError = [];
  10821. /**
  10822. * @param {string} name
  10823. * @param {string} rootFile
  10824. * @returns {Promise<any>}
  10825. */
  10826. async function req$3(name, rootFile = fileURLToPath(import.meta.url)) {
  10827. let url = createRequire(rootFile).resolve(name);
  10828. try {
  10829. return (await import(`${pathToFileURL(url)}?t=${Date.now()}`)).default
  10830. } catch (err) {
  10831. if (!TS_EXT_RE.test(url)) {
  10832. /* c8 ignore start */
  10833. throw err
  10834. }
  10835. }
  10836. if (tsx === undefined) {
  10837. try {
  10838. tsx = await import('tsx/cjs/api');
  10839. } catch (error) {
  10840. importError.push(error);
  10841. }
  10842. }
  10843. if (tsx) {
  10844. let loaded = tsx.require(name, rootFile);
  10845. return loaded && '__esModule' in loaded ? loaded.default : loaded
  10846. }
  10847. if (jiti === undefined) {
  10848. try {
  10849. jiti = (await import('jiti')).default;
  10850. } catch (error) {
  10851. importError.push(error);
  10852. }
  10853. }
  10854. if (jiti) {
  10855. return jiti(rootFile, { interopDefault: true })(name)
  10856. }
  10857. throw new Error(
  10858. `'tsx' or 'jiti' is required for the TypeScript configuration files. Make sure it is installed\nError: ${importError
  10859. .map(error => error.message)
  10860. .join('\n')}`
  10861. )
  10862. }
  10863. var req_1 = req$3;
  10864. // @ts-check
  10865. const req$2 = req_1;
  10866. /**
  10867. * Load Options
  10868. *
  10869. * @private
  10870. * @method options
  10871. *
  10872. * @param {Object} config PostCSS Config
  10873. *
  10874. * @return {Promise<Object>} options PostCSS Options
  10875. */
  10876. async function options(config, file) {
  10877. if (config.parser && typeof config.parser === 'string') {
  10878. try {
  10879. config.parser = await req$2(config.parser, file);
  10880. } catch (err) {
  10881. throw new Error(
  10882. `Loading PostCSS Parser failed: ${err.message}\n\n(@${file})`
  10883. )
  10884. }
  10885. }
  10886. if (config.syntax && typeof config.syntax === 'string') {
  10887. try {
  10888. config.syntax = await req$2(config.syntax, file);
  10889. } catch (err) {
  10890. throw new Error(
  10891. `Loading PostCSS Syntax failed: ${err.message}\n\n(@${file})`
  10892. )
  10893. }
  10894. }
  10895. if (config.stringifier && typeof config.stringifier === 'string') {
  10896. try {
  10897. config.stringifier = await req$2(config.stringifier, file);
  10898. } catch (err) {
  10899. throw new Error(
  10900. `Loading PostCSS Stringifier failed: ${err.message}\n\n(@${file})`
  10901. )
  10902. }
  10903. }
  10904. return config
  10905. }
  10906. var options_1 = options;
  10907. // @ts-check
  10908. const req$1 = req_1;
  10909. /**
  10910. * Plugin Loader
  10911. *
  10912. * @private
  10913. * @method load
  10914. *
  10915. * @param {String} plugin PostCSS Plugin Name
  10916. * @param {Object} options PostCSS Plugin Options
  10917. *
  10918. * @return {Promise<Function>} PostCSS Plugin
  10919. */
  10920. async function load(plugin, options, file) {
  10921. try {
  10922. if (
  10923. options === null ||
  10924. options === undefined ||
  10925. Object.keys(options).length === 0
  10926. ) {
  10927. return await req$1(plugin, file)
  10928. } else {
  10929. return (await req$1(plugin, file))(options)
  10930. /* c8 ignore next */
  10931. }
  10932. } catch (err) {
  10933. throw new Error(
  10934. `Loading PostCSS Plugin failed: ${err.message}\n\n(@${file})`
  10935. )
  10936. }
  10937. }
  10938. /**
  10939. * Load Plugins
  10940. *
  10941. * @private
  10942. * @method plugins
  10943. *
  10944. * @param {Object} config PostCSS Config Plugins
  10945. *
  10946. * @return {Promise<Array>} plugins PostCSS Plugins
  10947. */
  10948. async function plugins(config, file) {
  10949. let list = [];
  10950. if (Array.isArray(config.plugins)) {
  10951. list = config.plugins.filter(Boolean);
  10952. } else {
  10953. list = Object.entries(config.plugins)
  10954. .filter(([, options]) => {
  10955. return options !== false
  10956. })
  10957. .map(([plugin, options]) => {
  10958. return load(plugin, options, file)
  10959. });
  10960. list = await Promise.all(list);
  10961. }
  10962. if (list.length && list.length > 0) {
  10963. list.forEach((plugin, i) => {
  10964. if (plugin.default) {
  10965. plugin = plugin.default;
  10966. }
  10967. if (plugin.postcss === true) {
  10968. plugin = plugin();
  10969. } else if (plugin.postcss) {
  10970. plugin = plugin.postcss;
  10971. }
  10972. if (
  10973. !(
  10974. (typeof plugin === 'object' && Array.isArray(plugin.plugins)) ||
  10975. (typeof plugin === 'object' && plugin.postcssPlugin) ||
  10976. typeof plugin === 'function'
  10977. )
  10978. ) {
  10979. throw new TypeError(
  10980. `Invalid PostCSS Plugin found at: plugins[${i}]\n\n(@${file})`
  10981. )
  10982. }
  10983. });
  10984. }
  10985. return list
  10986. }
  10987. var plugins_1 = plugins;
  10988. // @ts-check
  10989. const { resolve } = path$b;
  10990. const config$1 = src$1;
  10991. const loadOptions = options_1;
  10992. const loadPlugins = plugins_1;
  10993. const req = req_1;
  10994. const interopRequireDefault = obj =>
  10995. obj && obj.__esModule ? obj : { default: obj };
  10996. /**
  10997. * Process the result from cosmiconfig
  10998. *
  10999. * @param {Object} ctx Config Context
  11000. * @param {Object} result Cosmiconfig result
  11001. *
  11002. * @return {Promise<Object>} PostCSS Config
  11003. */
  11004. async function processResult(ctx, result) {
  11005. let file = result.filepath || '';
  11006. let projectConfig = interopRequireDefault(result.config).default || {};
  11007. if (typeof projectConfig === 'function') {
  11008. projectConfig = projectConfig(ctx);
  11009. } else {
  11010. projectConfig = Object.assign({}, projectConfig, ctx);
  11011. }
  11012. if (!projectConfig.plugins) {
  11013. projectConfig.plugins = [];
  11014. }
  11015. let res = {
  11016. file,
  11017. options: await loadOptions(projectConfig, file),
  11018. plugins: await loadPlugins(projectConfig, file)
  11019. };
  11020. delete projectConfig.plugins;
  11021. return res
  11022. }
  11023. /**
  11024. * Builds the Config Context
  11025. *
  11026. * @param {Object} ctx Config Context
  11027. *
  11028. * @return {Object} Config Context
  11029. */
  11030. function createContext(ctx) {
  11031. /**
  11032. * @type {Object}
  11033. *
  11034. * @prop {String} cwd=process.cwd() Config search start location
  11035. * @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`
  11036. */
  11037. ctx = Object.assign(
  11038. {
  11039. cwd: process.cwd(),
  11040. env: process.env.NODE_ENV
  11041. },
  11042. ctx
  11043. );
  11044. if (!ctx.env) {
  11045. process.env.NODE_ENV = 'development';
  11046. }
  11047. return ctx
  11048. }
  11049. async function loader(filepath) {
  11050. return req(filepath)
  11051. }
  11052. let yaml;
  11053. async function yamlLoader(_, content) {
  11054. if (!yaml) {
  11055. try {
  11056. yaml = await import('yaml');
  11057. } catch (e) {
  11058. /* c8 ignore start */
  11059. throw new Error(
  11060. `'yaml' is required for the YAML configuration files. Make sure it is installed\nError: ${e.message}`
  11061. )
  11062. }
  11063. }
  11064. return yaml.parse(content);
  11065. }
  11066. /** @return {import('lilconfig').Options} */
  11067. const withLoaders = (options = {}) => {
  11068. let moduleName = 'postcss';
  11069. return {
  11070. ...options,
  11071. loaders: {
  11072. ...options.loaders,
  11073. '.cjs': loader,
  11074. '.cts': loader,
  11075. '.js': loader,
  11076. '.mjs': loader,
  11077. '.mts': loader,
  11078. '.ts': loader,
  11079. '.yaml': yamlLoader,
  11080. '.yml': yamlLoader
  11081. },
  11082. searchPlaces: [
  11083. ...(options.searchPlaces || []),
  11084. 'package.json',
  11085. `.${moduleName}rc`,
  11086. `.${moduleName}rc.json`,
  11087. `.${moduleName}rc.yaml`,
  11088. `.${moduleName}rc.yml`,
  11089. `.${moduleName}rc.ts`,
  11090. `.${moduleName}rc.cts`,
  11091. `.${moduleName}rc.mts`,
  11092. `.${moduleName}rc.js`,
  11093. `.${moduleName}rc.cjs`,
  11094. `.${moduleName}rc.mjs`,
  11095. `${moduleName}.config.ts`,
  11096. `${moduleName}.config.cts`,
  11097. `${moduleName}.config.mts`,
  11098. `${moduleName}.config.js`,
  11099. `${moduleName}.config.cjs`,
  11100. `${moduleName}.config.mjs`
  11101. ]
  11102. }
  11103. };
  11104. /**
  11105. * Load Config
  11106. *
  11107. * @method rc
  11108. *
  11109. * @param {Object} ctx Config Context
  11110. * @param {String} path Config Path
  11111. * @param {Object} options Config Options
  11112. *
  11113. * @return {Promise} config PostCSS Config
  11114. */
  11115. function rc(ctx, path, options) {
  11116. /**
  11117. * @type {Object} The full Config Context
  11118. */
  11119. ctx = createContext(ctx);
  11120. /**
  11121. * @type {String} `process.cwd()`
  11122. */
  11123. path = path ? resolve(path) : process.cwd();
  11124. return config$1
  11125. .lilconfig('postcss', withLoaders(options))
  11126. .search(path)
  11127. .then(result => {
  11128. if (!result) {
  11129. throw new Error(`No PostCSS Config found in: ${path}`)
  11130. }
  11131. return processResult(ctx, result)
  11132. })
  11133. }
  11134. /**
  11135. * Autoload Config for PostCSS
  11136. *
  11137. * @author Michael Ciniawsky @michael-ciniawsky <michael.ciniawsky@gmail.com>
  11138. * @license MIT
  11139. *
  11140. * @module postcss-load-config
  11141. * @version 2.1.0
  11142. *
  11143. * @requires comsiconfig
  11144. * @requires ./options
  11145. * @requires ./plugins
  11146. */
  11147. var src = rc;
  11148. var postcssrc = /*@__PURE__*/getDefaultExportFromCjs(src);
  11149. function matches$1(pattern, importee) {
  11150. if (pattern instanceof RegExp) {
  11151. return pattern.test(importee);
  11152. }
  11153. if (importee.length < pattern.length) {
  11154. return false;
  11155. }
  11156. if (importee === pattern) {
  11157. return true;
  11158. }
  11159. // eslint-disable-next-line prefer-template
  11160. return importee.startsWith(pattern + '/');
  11161. }
  11162. function getEntries({ entries, customResolver }) {
  11163. if (!entries) {
  11164. return [];
  11165. }
  11166. const resolverFunctionFromOptions = resolveCustomResolver(customResolver);
  11167. if (Array.isArray(entries)) {
  11168. return entries.map((entry) => {
  11169. return {
  11170. find: entry.find,
  11171. replacement: entry.replacement,
  11172. resolverFunction: resolveCustomResolver(entry.customResolver) || resolverFunctionFromOptions
  11173. };
  11174. });
  11175. }
  11176. return Object.entries(entries).map(([key, value]) => {
  11177. return { find: key, replacement: value, resolverFunction: resolverFunctionFromOptions };
  11178. });
  11179. }
  11180. function getHookFunction(hook) {
  11181. if (typeof hook === 'function') {
  11182. return hook;
  11183. }
  11184. if (hook && 'handler' in hook && typeof hook.handler === 'function') {
  11185. return hook.handler;
  11186. }
  11187. return null;
  11188. }
  11189. function resolveCustomResolver(customResolver) {
  11190. if (typeof customResolver === 'function') {
  11191. return customResolver;
  11192. }
  11193. if (customResolver) {
  11194. return getHookFunction(customResolver.resolveId);
  11195. }
  11196. return null;
  11197. }
  11198. function alias$1(options = {}) {
  11199. const entries = getEntries(options);
  11200. if (entries.length === 0) {
  11201. return {
  11202. name: 'alias',
  11203. resolveId: () => null
  11204. };
  11205. }
  11206. return {
  11207. name: 'alias',
  11208. async buildStart(inputOptions) {
  11209. await Promise.all([...(Array.isArray(options.entries) ? options.entries : []), options].map(({ customResolver }) => { var _a; return customResolver && ((_a = getHookFunction(customResolver.buildStart)) === null || _a === void 0 ? void 0 : _a.call(this, inputOptions)); }));
  11210. },
  11211. resolveId(importee, importer, resolveOptions) {
  11212. // First match is supposed to be the correct one
  11213. const matchedEntry = entries.find((entry) => matches$1(entry.find, importee));
  11214. if (!matchedEntry) {
  11215. return null;
  11216. }
  11217. const updatedId = importee.replace(matchedEntry.find, matchedEntry.replacement);
  11218. if (matchedEntry.resolverFunction) {
  11219. return matchedEntry.resolverFunction.call(this, updatedId, importer, resolveOptions);
  11220. }
  11221. return this.resolve(updatedId, importer, Object.assign({ skipSelf: true }, resolveOptions)).then((resolved) => {
  11222. if (resolved)
  11223. return resolved;
  11224. if (!require$$0$2.isAbsolute(updatedId)) {
  11225. this.warn(`rewrote ${importee} to ${updatedId} but was not an abolute path and was not handled by other plugins. ` +
  11226. `This will lead to duplicated modules for the same path. ` +
  11227. `To avoid duplicating modules, you should resolve to an absolute path.`);
  11228. }
  11229. return { id: updatedId };
  11230. });
  11231. }
  11232. };
  11233. }
  11234. const jsonExtRE = /\.json(?:$|\?)(?!commonjs-(?:proxy|external))/;
  11235. const jsonObjRE = /^\s*\{/;
  11236. const jsonLangs = `\\.(?:json|json5)(?:$|\\?)`;
  11237. const jsonLangRE = new RegExp(jsonLangs);
  11238. const isJSONRequest = (request) => jsonLangRE.test(request);
  11239. function jsonPlugin(options, isBuild) {
  11240. const plugin = {
  11241. name: "vite:json",
  11242. transform: {
  11243. handler(json, id) {
  11244. if (!jsonExtRE.test(id)) return null;
  11245. if (SPECIAL_QUERY_RE.test(id)) return null;
  11246. if (inlineRE$3.test(id) || noInlineRE.test(id)) {
  11247. this.warn(
  11248. `
  11249. Using ?inline or ?no-inline for JSON imports will have no effect.
  11250. Please use ?url&inline or ?url&no-inline to control JSON file inlining behavior.
  11251. `
  11252. );
  11253. }
  11254. json = stripBomTag(json);
  11255. try {
  11256. if (options.stringify !== false) {
  11257. if (options.namedExports && jsonObjRE.test(json)) {
  11258. const parsed = JSON.parse(json);
  11259. const keys = Object.keys(parsed);
  11260. let code = "";
  11261. let defaultObjectCode = "{\n";
  11262. for (const key of keys) {
  11263. if (key === makeLegalIdentifier(key)) {
  11264. code += `export const ${key} = ${serializeValue(parsed[key])};
  11265. `;
  11266. defaultObjectCode += ` ${key},
  11267. `;
  11268. } else {
  11269. defaultObjectCode += ` ${JSON.stringify(key)}: ${serializeValue(parsed[key])},
  11270. `;
  11271. }
  11272. }
  11273. defaultObjectCode += "}";
  11274. code += `export default ${defaultObjectCode};
  11275. `;
  11276. return {
  11277. code,
  11278. map: { mappings: "" }
  11279. };
  11280. }
  11281. if (options.stringify === true || // use 10kB as a threshold for 'auto'
  11282. // https://v8.dev/blog/cost-of-javascript-2019#:~:text=A%20good%20rule%20of%20thumb%20is%20to%20apply%20this%20technique%20for%20objects%20of%2010%20kB%20or%20larger
  11283. json.length > 10 * 1e3) {
  11284. if (isBuild) {
  11285. json = JSON.stringify(JSON.parse(json));
  11286. }
  11287. return {
  11288. code: `export default /* #__PURE__ */ JSON.parse(${JSON.stringify(json)})`,
  11289. map: { mappings: "" }
  11290. };
  11291. }
  11292. }
  11293. return {
  11294. code: dataToEsm(JSON.parse(json), {
  11295. preferConst: true,
  11296. namedExports: options.namedExports
  11297. }),
  11298. map: { mappings: "" }
  11299. };
  11300. } catch (e) {
  11301. const position = extractJsonErrorPosition(e.message, json.length);
  11302. const msg = position ? `, invalid JSON syntax found at position ${position}` : `.`;
  11303. this.error(`Failed to parse JSON file` + msg, position);
  11304. }
  11305. }
  11306. }
  11307. };
  11308. const handler = plugin.transform.handler;
  11309. plugin.transform = handler;
  11310. plugin.transform.handler = handler;
  11311. return plugin;
  11312. }
  11313. function serializeValue(value) {
  11314. const valueAsString = JSON.stringify(value);
  11315. if (typeof value === "object" && value != null && valueAsString.length > 10 * 1e3) {
  11316. return `/* #__PURE__ */ JSON.parse(${JSON.stringify(valueAsString)})`;
  11317. }
  11318. return valueAsString;
  11319. }
  11320. function extractJsonErrorPosition(errorMessage, inputLength) {
  11321. if (errorMessage.startsWith("Unexpected end of JSON input")) {
  11322. return inputLength - 1;
  11323. }
  11324. const errorMessageList = /at position (\d+)/.exec(errorMessage);
  11325. return errorMessageList ? Math.max(parseInt(errorMessageList[1], 10) - 1, 0) : void 0;
  11326. }
  11327. function e(e,n,r){throw new Error(r?`No known conditions for "${n}" specifier in "${e}" package`:`Missing "${n}" specifier in "${e}" package`)}function n(n,i,o,f){let s,u,l=r(n,o),c=function(e){let n=new Set(["default",...e.conditions||[]]);return e.unsafe||n.add(e.require?"require":"import"),e.unsafe||n.add(e.browser?"browser":"node"),n}(f||{}),a=i[l];if(void 0===a){let e,n,r,t;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))));a=i[n];}return a||e(n,l),s=t(a,c),s||e(n,l,1),u&&function(e,n){let r,t=0,i=e.length,o=/[*]/g,f=/[/]$/;for(;t<i;t++)e[t]=o.test(r=e[t])?r.replace(o,n):f.test(r)?r+n:r;}(s,u),s}function r(e,n,r){if(e===n||"."===n)return ".";let t=e+"/",i=t.length,o=n.slice(0,i)===t,f=o?n.slice(i):n;return "#"===f[0]?f:"./"===f.slice(0,2)?f:"./"+f}function t(e,n,r){if(e){if("string"==typeof e)return r&&r.add(e),[e];let i,o;if(Array.isArray(e)){for(o=r||new Set,i=0;i<e.length;i++)t(e[i],n,o);if(!r&&o.size)return [...o]}else for(i in e)if(n.has(i))return t(e[i],n,r)}}function o(e,r,t){let i,o=e.exports;if(o){if("string"==typeof o)o={".":o};else for(i in o){"."!==i[0]&&(o={".":o});break}return n(e.name,o,r||".",t)}}function f(e,r,t){if(e.imports)return n(e.name,e.imports,r,t)}
  11328. const HASH_RE = /#/g;
  11329. const AMPERSAND_RE = /&/g;
  11330. const SLASH_RE = /\//g;
  11331. const EQUAL_RE = /=/g;
  11332. const PLUS_RE = /\+/g;
  11333. const ENC_CARET_RE = /%5e/gi;
  11334. const ENC_BACKTICK_RE = /%60/gi;
  11335. const ENC_PIPE_RE = /%7c/gi;
  11336. const ENC_SPACE_RE = /%20/gi;
  11337. function encode(text) {
  11338. return encodeURI("" + text).replace(ENC_PIPE_RE, "|");
  11339. }
  11340. function encodeQueryValue(input) {
  11341. 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");
  11342. }
  11343. function encodeQueryKey(text) {
  11344. return encodeQueryValue(text).replace(EQUAL_RE, "%3D");
  11345. }
  11346. function encodeQueryItem(key, value) {
  11347. if (typeof value === "number" || typeof value === "boolean") {
  11348. value = String(value);
  11349. }
  11350. if (!value) {
  11351. return encodeQueryKey(key);
  11352. }
  11353. if (Array.isArray(value)) {
  11354. return value.map(
  11355. (_value) => `${encodeQueryKey(key)}=${encodeQueryValue(_value)}`
  11356. ).join("&");
  11357. }
  11358. return `${encodeQueryKey(key)}=${encodeQueryValue(value)}`;
  11359. }
  11360. function stringifyQuery(query) {
  11361. return Object.keys(query).filter((k) => query[k] !== void 0).map((k) => encodeQueryItem(k, query[k])).filter(Boolean).join("&");
  11362. }
  11363. new Set(builtinModules);
  11364. function clearImports(imports) {
  11365. return (imports || "").replace(/(\/\/[^\n]*\n|\/\*.*\*\/)/g, "").replace(/\s+/g, " ");
  11366. }
  11367. function getImportNames(cleanedImports) {
  11368. const topLevelImports = cleanedImports.replace(/{([^}]*)}/, "");
  11369. const namespacedImport = topLevelImports.match(/\* as \s*(\S*)/)?.[1];
  11370. const defaultImport = topLevelImports.split(",").find((index) => !/[*{}]/.test(index))?.trim() || undefined;
  11371. return {
  11372. namespacedImport,
  11373. defaultImport
  11374. };
  11375. }
  11376. /**
  11377. * @typedef ErrnoExceptionFields
  11378. * @property {number | undefined} [errnode]
  11379. * @property {string | undefined} [code]
  11380. * @property {string | undefined} [path]
  11381. * @property {string | undefined} [syscall]
  11382. * @property {string | undefined} [url]
  11383. *
  11384. * @typedef {Error & ErrnoExceptionFields} ErrnoException
  11385. */
  11386. const own$1 = {}.hasOwnProperty;
  11387. const classRegExp = /^([A-Z][a-z\d]*)+$/;
  11388. // Sorted by a rough estimate on most frequently used entries.
  11389. const kTypes = new Set([
  11390. 'string',
  11391. 'function',
  11392. 'number',
  11393. 'object',
  11394. // Accept 'Function' and 'Object' as alternative to the lower cased version.
  11395. 'Function',
  11396. 'Object',
  11397. 'boolean',
  11398. 'bigint',
  11399. 'symbol'
  11400. ]);
  11401. /**
  11402. * Create a list string in the form like 'A and B' or 'A, B, ..., and Z'.
  11403. * We cannot use Intl.ListFormat because it's not available in
  11404. * --without-intl builds.
  11405. *
  11406. * @param {Array<string>} array
  11407. * An array of strings.
  11408. * @param {string} [type]
  11409. * The list type to be inserted before the last element.
  11410. * @returns {string}
  11411. */
  11412. function formatList(array, type = 'and') {
  11413. return array.length < 3
  11414. ? array.join(` ${type} `)
  11415. : `${array.slice(0, -1).join(', ')}, ${type} ${array[array.length - 1]}`
  11416. }
  11417. /** @type {Map<string, MessageFunction | string>} */
  11418. const messages = new Map();
  11419. const nodeInternalPrefix = '__node_internal_';
  11420. /** @type {number} */
  11421. let userStackTraceLimit;
  11422. createError(
  11423. 'ERR_INVALID_ARG_TYPE',
  11424. /**
  11425. * @param {string} name
  11426. * @param {Array<string> | string} expected
  11427. * @param {unknown} actual
  11428. */
  11429. (name, expected, actual) => {
  11430. assert$1(typeof name === 'string', "'name' must be a string");
  11431. if (!Array.isArray(expected)) {
  11432. expected = [expected];
  11433. }
  11434. let message = 'The ';
  11435. if (name.endsWith(' argument')) {
  11436. // For cases like 'first argument'
  11437. message += `${name} `;
  11438. } else {
  11439. const type = name.includes('.') ? 'property' : 'argument';
  11440. message += `"${name}" ${type} `;
  11441. }
  11442. message += 'must be ';
  11443. /** @type {Array<string>} */
  11444. const types = [];
  11445. /** @type {Array<string>} */
  11446. const instances = [];
  11447. /** @type {Array<string>} */
  11448. const other = [];
  11449. for (const value of expected) {
  11450. assert$1(
  11451. typeof value === 'string',
  11452. 'All expected entries have to be of type string'
  11453. );
  11454. if (kTypes.has(value)) {
  11455. types.push(value.toLowerCase());
  11456. } else if (classRegExp.exec(value) === null) {
  11457. assert$1(
  11458. value !== 'object',
  11459. 'The value "object" should be written as "Object"'
  11460. );
  11461. other.push(value);
  11462. } else {
  11463. instances.push(value);
  11464. }
  11465. }
  11466. // Special handle `object` in case other instances are allowed to outline
  11467. // the differences between each other.
  11468. if (instances.length > 0) {
  11469. const pos = types.indexOf('object');
  11470. if (pos !== -1) {
  11471. types.slice(pos, 1);
  11472. instances.push('Object');
  11473. }
  11474. }
  11475. if (types.length > 0) {
  11476. message += `${types.length > 1 ? 'one of type' : 'of type'} ${formatList(
  11477. types,
  11478. 'or'
  11479. )}`;
  11480. if (instances.length > 0 || other.length > 0) message += ' or ';
  11481. }
  11482. if (instances.length > 0) {
  11483. message += `an instance of ${formatList(instances, 'or')}`;
  11484. if (other.length > 0) message += ' or ';
  11485. }
  11486. if (other.length > 0) {
  11487. if (other.length > 1) {
  11488. message += `one of ${formatList(other, 'or')}`;
  11489. } else {
  11490. if (other[0].toLowerCase() !== other[0]) message += 'an ';
  11491. message += `${other[0]}`;
  11492. }
  11493. }
  11494. message += `. Received ${determineSpecificType(actual)}`;
  11495. return message
  11496. },
  11497. TypeError
  11498. );
  11499. createError(
  11500. 'ERR_INVALID_MODULE_SPECIFIER',
  11501. /**
  11502. * @param {string} request
  11503. * @param {string} reason
  11504. * @param {string} [base]
  11505. */
  11506. (request, reason, base = undefined) => {
  11507. return `Invalid module "${request}" ${reason}${
  11508. base ? ` imported from ${base}` : ''
  11509. }`
  11510. },
  11511. TypeError
  11512. );
  11513. createError(
  11514. 'ERR_INVALID_PACKAGE_CONFIG',
  11515. /**
  11516. * @param {string} path
  11517. * @param {string} [base]
  11518. * @param {string} [message]
  11519. */
  11520. (path, base, message) => {
  11521. return `Invalid package config ${path}${
  11522. base ? ` while importing ${base}` : ''
  11523. }${message ? `. ${message}` : ''}`
  11524. },
  11525. Error
  11526. );
  11527. createError(
  11528. 'ERR_INVALID_PACKAGE_TARGET',
  11529. /**
  11530. * @param {string} packagePath
  11531. * @param {string} key
  11532. * @param {unknown} target
  11533. * @param {boolean} [isImport=false]
  11534. * @param {string} [base]
  11535. */
  11536. (packagePath, key, target, isImport = false, base = undefined) => {
  11537. const relatedError =
  11538. typeof target === 'string' &&
  11539. !isImport &&
  11540. target.length > 0 &&
  11541. !target.startsWith('./');
  11542. if (key === '.') {
  11543. assert$1(isImport === false);
  11544. return (
  11545. `Invalid "exports" main target ${JSON.stringify(target)} defined ` +
  11546. `in the package config ${packagePath}package.json${
  11547. base ? ` imported from ${base}` : ''
  11548. }${relatedError ? '; targets must start with "./"' : ''}`
  11549. )
  11550. }
  11551. return `Invalid "${
  11552. isImport ? 'imports' : 'exports'
  11553. }" target ${JSON.stringify(
  11554. target
  11555. )} defined for '${key}' in the package config ${packagePath}package.json${
  11556. base ? ` imported from ${base}` : ''
  11557. }${relatedError ? '; targets must start with "./"' : ''}`
  11558. },
  11559. Error
  11560. );
  11561. createError(
  11562. 'ERR_MODULE_NOT_FOUND',
  11563. /**
  11564. * @param {string} path
  11565. * @param {string} base
  11566. * @param {boolean} [exactUrl]
  11567. */
  11568. (path, base, exactUrl = false) => {
  11569. return `Cannot find ${
  11570. exactUrl ? 'module' : 'package'
  11571. } '${path}' imported from ${base}`
  11572. },
  11573. Error
  11574. );
  11575. createError(
  11576. 'ERR_NETWORK_IMPORT_DISALLOWED',
  11577. "import of '%s' by %s is not supported: %s",
  11578. Error
  11579. );
  11580. createError(
  11581. 'ERR_PACKAGE_IMPORT_NOT_DEFINED',
  11582. /**
  11583. * @param {string} specifier
  11584. * @param {string} packagePath
  11585. * @param {string} base
  11586. */
  11587. (specifier, packagePath, base) => {
  11588. return `Package import specifier "${specifier}" is not defined${
  11589. packagePath ? ` in package ${packagePath}package.json` : ''
  11590. } imported from ${base}`
  11591. },
  11592. TypeError
  11593. );
  11594. createError(
  11595. 'ERR_PACKAGE_PATH_NOT_EXPORTED',
  11596. /**
  11597. * @param {string} packagePath
  11598. * @param {string} subpath
  11599. * @param {string} [base]
  11600. */
  11601. (packagePath, subpath, base = undefined) => {
  11602. if (subpath === '.')
  11603. return `No "exports" main defined in ${packagePath}package.json${
  11604. base ? ` imported from ${base}` : ''
  11605. }`
  11606. return `Package subpath '${subpath}' is not defined by "exports" in ${packagePath}package.json${
  11607. base ? ` imported from ${base}` : ''
  11608. }`
  11609. },
  11610. Error
  11611. );
  11612. createError(
  11613. 'ERR_UNSUPPORTED_DIR_IMPORT',
  11614. "Directory import '%s' is not supported " +
  11615. 'resolving ES modules imported from %s',
  11616. Error
  11617. );
  11618. createError(
  11619. 'ERR_UNSUPPORTED_RESOLVE_REQUEST',
  11620. 'Failed to resolve module specifier "%s" from "%s": Invalid relative URL or base scheme is not hierarchical.',
  11621. TypeError
  11622. );
  11623. createError(
  11624. 'ERR_UNKNOWN_FILE_EXTENSION',
  11625. /**
  11626. * @param {string} extension
  11627. * @param {string} path
  11628. */
  11629. (extension, path) => {
  11630. return `Unknown file extension "${extension}" for ${path}`
  11631. },
  11632. TypeError
  11633. );
  11634. createError(
  11635. 'ERR_INVALID_ARG_VALUE',
  11636. /**
  11637. * @param {string} name
  11638. * @param {unknown} value
  11639. * @param {string} [reason='is invalid']
  11640. */
  11641. (name, value, reason = 'is invalid') => {
  11642. let inspected = inspect(value);
  11643. if (inspected.length > 128) {
  11644. inspected = `${inspected.slice(0, 128)}...`;
  11645. }
  11646. const type = name.includes('.') ? 'property' : 'argument';
  11647. return `The ${type} '${name}' ${reason}. Received ${inspected}`
  11648. },
  11649. TypeError
  11650. // Note: extra classes have been shaken out.
  11651. // , RangeError
  11652. );
  11653. /**
  11654. * Utility function for registering the error codes. Only used here. Exported
  11655. * *only* to allow for testing.
  11656. * @param {string} sym
  11657. * @param {MessageFunction | string} value
  11658. * @param {ErrorConstructor} constructor
  11659. * @returns {new (...parameters: Array<any>) => Error}
  11660. */
  11661. function createError(sym, value, constructor) {
  11662. // Special case for SystemError that formats the error message differently
  11663. // The SystemErrors only have SystemError as their base classes.
  11664. messages.set(sym, value);
  11665. return makeNodeErrorWithCode(constructor, sym)
  11666. }
  11667. /**
  11668. * @param {ErrorConstructor} Base
  11669. * @param {string} key
  11670. * @returns {ErrorConstructor}
  11671. */
  11672. function makeNodeErrorWithCode(Base, key) {
  11673. // @ts-expect-error It’s a Node error.
  11674. return NodeError
  11675. /**
  11676. * @param {Array<unknown>} parameters
  11677. */
  11678. function NodeError(...parameters) {
  11679. const limit = Error.stackTraceLimit;
  11680. if (isErrorStackTraceLimitWritable()) Error.stackTraceLimit = 0;
  11681. const error = new Base();
  11682. // Reset the limit and setting the name property.
  11683. if (isErrorStackTraceLimitWritable()) Error.stackTraceLimit = limit;
  11684. const message = getMessage(key, parameters, error);
  11685. Object.defineProperties(error, {
  11686. // Note: no need to implement `kIsNodeError` symbol, would be hard,
  11687. // probably.
  11688. message: {
  11689. value: message,
  11690. enumerable: false,
  11691. writable: true,
  11692. configurable: true
  11693. },
  11694. toString: {
  11695. /** @this {Error} */
  11696. value() {
  11697. return `${this.name} [${key}]: ${this.message}`
  11698. },
  11699. enumerable: false,
  11700. writable: true,
  11701. configurable: true
  11702. }
  11703. });
  11704. captureLargerStackTrace(error);
  11705. // @ts-expect-error It’s a Node error.
  11706. error.code = key;
  11707. return error
  11708. }
  11709. }
  11710. /**
  11711. * @returns {boolean}
  11712. */
  11713. function isErrorStackTraceLimitWritable() {
  11714. // Do no touch Error.stackTraceLimit as V8 would attempt to install
  11715. // it again during deserialization.
  11716. try {
  11717. if (v8.startupSnapshot.isBuildingSnapshot()) {
  11718. return false
  11719. }
  11720. } catch {}
  11721. const desc = Object.getOwnPropertyDescriptor(Error, 'stackTraceLimit');
  11722. if (desc === undefined) {
  11723. return Object.isExtensible(Error)
  11724. }
  11725. return own$1.call(desc, 'writable') && desc.writable !== undefined
  11726. ? desc.writable
  11727. : desc.set !== undefined
  11728. }
  11729. /**
  11730. * This function removes unnecessary frames from Node.js core errors.
  11731. * @template {(...parameters: unknown[]) => unknown} T
  11732. * @param {T} wrappedFunction
  11733. * @returns {T}
  11734. */
  11735. function hideStackFrames(wrappedFunction) {
  11736. // We rename the functions that will be hidden to cut off the stacktrace
  11737. // at the outermost one
  11738. const hidden = nodeInternalPrefix + wrappedFunction.name;
  11739. Object.defineProperty(wrappedFunction, 'name', {value: hidden});
  11740. return wrappedFunction
  11741. }
  11742. const captureLargerStackTrace = hideStackFrames(
  11743. /**
  11744. * @param {Error} error
  11745. * @returns {Error}
  11746. */
  11747. // @ts-expect-error: fine
  11748. function (error) {
  11749. const stackTraceLimitIsWritable = isErrorStackTraceLimitWritable();
  11750. if (stackTraceLimitIsWritable) {
  11751. userStackTraceLimit = Error.stackTraceLimit;
  11752. Error.stackTraceLimit = Number.POSITIVE_INFINITY;
  11753. }
  11754. Error.captureStackTrace(error);
  11755. // Reset the limit
  11756. if (stackTraceLimitIsWritable) Error.stackTraceLimit = userStackTraceLimit;
  11757. return error
  11758. }
  11759. );
  11760. /**
  11761. * @param {string} key
  11762. * @param {Array<unknown>} parameters
  11763. * @param {Error} self
  11764. * @returns {string}
  11765. */
  11766. function getMessage(key, parameters, self) {
  11767. const message = messages.get(key);
  11768. assert$1(message !== undefined, 'expected `message` to be found');
  11769. if (typeof message === 'function') {
  11770. assert$1(
  11771. message.length <= parameters.length, // Default options do not count.
  11772. `Code: ${key}; The provided arguments length (${parameters.length}) does not ` +
  11773. `match the required ones (${message.length}).`
  11774. );
  11775. return Reflect.apply(message, self, parameters)
  11776. }
  11777. const regex = /%[dfijoOs]/g;
  11778. let expectedLength = 0;
  11779. while (regex.exec(message) !== null) expectedLength++;
  11780. assert$1(
  11781. expectedLength === parameters.length,
  11782. `Code: ${key}; The provided arguments length (${parameters.length}) does not ` +
  11783. `match the required ones (${expectedLength}).`
  11784. );
  11785. if (parameters.length === 0) return message
  11786. parameters.unshift(message);
  11787. return Reflect.apply(format$2, null, parameters)
  11788. }
  11789. /**
  11790. * Determine the specific type of a value for type-mismatch errors.
  11791. * @param {unknown} value
  11792. * @returns {string}
  11793. */
  11794. function determineSpecificType(value) {
  11795. if (value === null || value === undefined) {
  11796. return String(value)
  11797. }
  11798. if (typeof value === 'function' && value.name) {
  11799. return `function ${value.name}`
  11800. }
  11801. if (typeof value === 'object') {
  11802. if (value.constructor && value.constructor.name) {
  11803. return `an instance of ${value.constructor.name}`
  11804. }
  11805. return `${inspect(value, {depth: -1})}`
  11806. }
  11807. let inspected = inspect(value, {colors: false});
  11808. if (inspected.length > 28) {
  11809. inspected = `${inspected.slice(0, 25)}...`;
  11810. }
  11811. return `type ${typeof value} (${inspected})`
  11812. }
  11813. 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;
  11814. const TYPE_RE = /^\s*?type\s/;
  11815. function parseStaticImport(matched) {
  11816. const cleanedImports = clearImports(matched.imports);
  11817. const namedImports = {};
  11818. const _matches = cleanedImports.match(/{([^}]*)}/)?.[1]?.split(",") || [];
  11819. for (const namedImport of _matches) {
  11820. const _match = namedImport.match(/^\s*(\S*) as (\S*)\s*$/);
  11821. const source = _match?.[1] || namedImport.trim();
  11822. const importName = _match?.[2] || source;
  11823. if (source && !TYPE_RE.test(source)) {
  11824. namedImports[source] = importName;
  11825. }
  11826. }
  11827. const { namespacedImport, defaultImport } = getImportNames(cleanedImports);
  11828. return {
  11829. ...matched,
  11830. defaultImport,
  11831. namespacedImport,
  11832. namedImports
  11833. };
  11834. }
  11835. 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;
  11836. const COMMENT_RE = /\/\*.+?\*\/|\/\/.*(?=[nr])/g;
  11837. function hasESMSyntax(code, opts = {}) {
  11838. if (opts.stripComments) {
  11839. code = code.replace(COMMENT_RE, "");
  11840. }
  11841. return ESM_RE.test(code);
  11842. }
  11843. const externalWithConversionNamespace = "vite:dep-pre-bundle:external-conversion";
  11844. const convertedExternalPrefix = "vite-dep-pre-bundle-external:";
  11845. const cjsExternalFacadeNamespace = "vite:cjs-external-facade";
  11846. const nonFacadePrefix = "vite-cjs-external-facade:";
  11847. const externalTypes = [
  11848. "css",
  11849. // supported pre-processor types
  11850. "less",
  11851. "sass",
  11852. "scss",
  11853. "styl",
  11854. "stylus",
  11855. "pcss",
  11856. "postcss",
  11857. // wasm
  11858. "wasm",
  11859. // known SFC types
  11860. "vue",
  11861. "svelte",
  11862. "marko",
  11863. "astro",
  11864. "imba",
  11865. // JSX/TSX may be configured to be compiled differently from how esbuild
  11866. // handles it by default, so exclude them as well
  11867. "jsx",
  11868. "tsx",
  11869. ...KNOWN_ASSET_TYPES
  11870. ];
  11871. function esbuildDepPlugin(environment, qualified, external) {
  11872. const { isProduction } = environment.config;
  11873. const { extensions } = environment.config.optimizeDeps;
  11874. const allExternalTypes = extensions ? externalTypes.filter((type) => !extensions.includes("." + type)) : externalTypes;
  11875. const esmPackageCache = /* @__PURE__ */ new Map();
  11876. const cjsPackageCache = /* @__PURE__ */ new Map();
  11877. const _resolve = createBackCompatIdResolver(environment.getTopLevelConfig(), {
  11878. asSrc: false,
  11879. scan: true,
  11880. packageCache: esmPackageCache
  11881. });
  11882. const _resolveRequire = createBackCompatIdResolver(
  11883. environment.getTopLevelConfig(),
  11884. {
  11885. asSrc: false,
  11886. isRequire: true,
  11887. scan: true,
  11888. packageCache: cjsPackageCache
  11889. }
  11890. );
  11891. const resolve = (id, importer, kind, resolveDir) => {
  11892. let _importer;
  11893. {
  11894. _importer = importer in qualified ? qualified[importer] : importer;
  11895. }
  11896. const resolver = kind.startsWith("require") ? _resolveRequire : _resolve;
  11897. return resolver(environment, id, _importer);
  11898. };
  11899. const resolveResult = (id, resolved) => {
  11900. if (resolved.startsWith(browserExternalId)) {
  11901. return {
  11902. path: id,
  11903. namespace: "browser-external"
  11904. };
  11905. }
  11906. if (resolved.startsWith(optionalPeerDepId)) {
  11907. return {
  11908. path: resolved,
  11909. namespace: "optional-peer-dep"
  11910. };
  11911. }
  11912. if (isBuiltin(environment.config.resolve.builtins, resolved)) {
  11913. return;
  11914. }
  11915. if (isExternalUrl(resolved)) {
  11916. return {
  11917. path: resolved,
  11918. external: true
  11919. };
  11920. }
  11921. return {
  11922. path: path$b.resolve(resolved)
  11923. };
  11924. };
  11925. return {
  11926. name: "vite:dep-pre-bundle",
  11927. setup(build) {
  11928. build.onEnd(() => {
  11929. esmPackageCache.clear();
  11930. cjsPackageCache.clear();
  11931. });
  11932. build.onResolve(
  11933. {
  11934. filter: new RegExp(
  11935. `\\.(` + allExternalTypes.join("|") + `)(\\?.*)?$`
  11936. )
  11937. },
  11938. async ({ path: id, importer, kind }) => {
  11939. if (id.startsWith(convertedExternalPrefix)) {
  11940. return {
  11941. path: id.slice(convertedExternalPrefix.length),
  11942. external: true
  11943. };
  11944. }
  11945. const resolved = await resolve(id, importer, kind);
  11946. if (resolved) {
  11947. if (JS_TYPES_RE.test(resolved)) {
  11948. return {
  11949. path: resolved,
  11950. external: false
  11951. };
  11952. }
  11953. if (kind === "require-call") {
  11954. return {
  11955. path: resolved,
  11956. namespace: externalWithConversionNamespace
  11957. };
  11958. }
  11959. return {
  11960. path: resolved,
  11961. external: true
  11962. };
  11963. }
  11964. }
  11965. );
  11966. build.onLoad(
  11967. { filter: /./, namespace: externalWithConversionNamespace },
  11968. (args) => {
  11969. const modulePath = `"${convertedExternalPrefix}${args.path}"`;
  11970. return {
  11971. contents: isCSSRequest(args.path) && !isModuleCSSRequest(args.path) ? `import ${modulePath};` : `export { default } from ${modulePath};export * from ${modulePath};`,
  11972. loader: "js"
  11973. };
  11974. }
  11975. );
  11976. function resolveEntry(id) {
  11977. const flatId = flattenId(id);
  11978. if (flatId in qualified) {
  11979. return {
  11980. path: qualified[flatId]
  11981. };
  11982. }
  11983. }
  11984. build.onResolve(
  11985. { filter: /^[\w@][^:]/ },
  11986. async ({ path: id, importer, kind }) => {
  11987. if (moduleListContains(external, id)) {
  11988. return {
  11989. path: id,
  11990. external: true
  11991. };
  11992. }
  11993. let entry;
  11994. if (!importer) {
  11995. if (entry = resolveEntry(id)) return entry;
  11996. const aliased = await _resolve(environment, id, void 0, true);
  11997. if (aliased && (entry = resolveEntry(aliased))) {
  11998. return entry;
  11999. }
  12000. }
  12001. const resolved = await resolve(id, importer, kind);
  12002. if (resolved) {
  12003. return resolveResult(id, resolved);
  12004. }
  12005. }
  12006. );
  12007. build.onLoad(
  12008. { filter: /.*/, namespace: "browser-external" },
  12009. ({ path: path2 }) => {
  12010. if (isProduction) {
  12011. return {
  12012. contents: "module.exports = {}"
  12013. };
  12014. } else {
  12015. return {
  12016. // Return in CJS to intercept named imports. Use `Object.create` to
  12017. // create the Proxy in the prototype to workaround esbuild issue. Why?
  12018. //
  12019. // In short, esbuild cjs->esm flow:
  12020. // 1. Create empty object using `Object.create(Object.getPrototypeOf(module.exports))`.
  12021. // 2. Assign props of `module.exports` to the object.
  12022. // 3. Return object for ESM use.
  12023. //
  12024. // If we do `module.exports = new Proxy({}, {})`, step 1 returns empty object,
  12025. // step 2 does nothing as there's no props for `module.exports`. The final object
  12026. // is just an empty object.
  12027. //
  12028. // Creating the Proxy in the prototype satisfies step 1 immediately, which means
  12029. // the returned object is a Proxy that we can intercept.
  12030. //
  12031. // Note: Skip keys that are accessed by esbuild and browser devtools.
  12032. contents: `module.exports = Object.create(new Proxy({}, {
  12033. get(_, key) {
  12034. if (
  12035. key !== '__esModule' &&
  12036. key !== '__proto__' &&
  12037. key !== 'constructor' &&
  12038. key !== 'splice'
  12039. ) {
  12040. console.warn(\`Module "${path2}" has been externalized for browser compatibility. Cannot access "${path2}.\${key}" in client code. See https://vite.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.\`)
  12041. }
  12042. }
  12043. }))`
  12044. };
  12045. }
  12046. }
  12047. );
  12048. build.onLoad(
  12049. { filter: /.*/, namespace: "optional-peer-dep" },
  12050. ({ path: path2 }) => {
  12051. if (isProduction) {
  12052. return {
  12053. contents: "module.exports = {}"
  12054. };
  12055. } else {
  12056. const [, peerDep, parentDep] = path2.split(":");
  12057. return {
  12058. contents: `throw new Error(\`Could not resolve "${peerDep}" imported by "${parentDep}". Is it installed?\`)`
  12059. };
  12060. }
  12061. }
  12062. );
  12063. }
  12064. };
  12065. }
  12066. const matchesEntireLine = (text) => `^${escapeRegex(text)}$`;
  12067. function esbuildCjsExternalPlugin(externals, platform) {
  12068. return {
  12069. name: "cjs-external",
  12070. setup(build) {
  12071. const filter = new RegExp(externals.map(matchesEntireLine).join("|"));
  12072. build.onResolve({ filter: new RegExp(`^${nonFacadePrefix}`) }, (args) => {
  12073. return {
  12074. path: args.path.slice(nonFacadePrefix.length),
  12075. external: true
  12076. };
  12077. });
  12078. build.onResolve({ filter }, (args) => {
  12079. if (args.kind === "require-call" && platform !== "node") {
  12080. return {
  12081. path: args.path,
  12082. namespace: cjsExternalFacadeNamespace
  12083. };
  12084. }
  12085. return {
  12086. path: args.path,
  12087. external: true
  12088. };
  12089. });
  12090. build.onLoad(
  12091. { filter: /.*/, namespace: cjsExternalFacadeNamespace },
  12092. (args) => ({
  12093. contents: `import * as m from ${JSON.stringify(
  12094. nonFacadePrefix + args.path
  12095. )};module.exports = { ...m };`
  12096. })
  12097. );
  12098. }
  12099. };
  12100. }
  12101. const environmentColors = [
  12102. colors$1.blue,
  12103. colors$1.magenta,
  12104. colors$1.green,
  12105. colors$1.gray
  12106. ];
  12107. function getDefaultResolvedEnvironmentOptions(config) {
  12108. return {
  12109. define: config.define,
  12110. resolve: config.resolve,
  12111. consumer: "server",
  12112. optimizeDeps: config.optimizeDeps,
  12113. dev: config.dev,
  12114. build: config.build
  12115. };
  12116. }
  12117. class PartialEnvironment {
  12118. name;
  12119. getTopLevelConfig() {
  12120. return this._topLevelConfig;
  12121. }
  12122. config;
  12123. /**
  12124. * @deprecated use environment.config instead
  12125. **/
  12126. get options() {
  12127. return this._options;
  12128. }
  12129. logger;
  12130. /**
  12131. * @internal
  12132. */
  12133. _options;
  12134. /**
  12135. * @internal
  12136. */
  12137. _topLevelConfig;
  12138. constructor(name, topLevelConfig, options = topLevelConfig.environments[name]) {
  12139. if (!/^[\w$]+$/.test(name)) {
  12140. throw new Error(
  12141. `Invalid environment name "${name}". Environment names must only contain alphanumeric characters and "$", "_".`
  12142. );
  12143. }
  12144. this.name = name;
  12145. this._topLevelConfig = topLevelConfig;
  12146. this._options = options;
  12147. this.config = new Proxy(
  12148. options,
  12149. {
  12150. get: (target, prop) => {
  12151. if (prop === "logger") {
  12152. return this.logger;
  12153. }
  12154. if (prop in target) {
  12155. return this._options[prop];
  12156. }
  12157. return this._topLevelConfig[prop];
  12158. }
  12159. }
  12160. );
  12161. const environment = colors$1.dim(`(${this.name})`);
  12162. const colorIndex = [...this.name].reduce((acc, c) => acc + c.charCodeAt(0), 0) % environmentColors.length;
  12163. const infoColor = environmentColors[colorIndex || 0];
  12164. this.logger = {
  12165. get hasWarned() {
  12166. return topLevelConfig.logger.hasWarned;
  12167. },
  12168. info(msg, opts) {
  12169. return topLevelConfig.logger.info(msg, {
  12170. ...opts,
  12171. environment: infoColor(environment)
  12172. });
  12173. },
  12174. warn(msg, opts) {
  12175. return topLevelConfig.logger.warn(msg, {
  12176. ...opts,
  12177. environment: colors$1.yellow(environment)
  12178. });
  12179. },
  12180. warnOnce(msg, opts) {
  12181. return topLevelConfig.logger.warnOnce(msg, {
  12182. ...opts,
  12183. environment: colors$1.yellow(environment)
  12184. });
  12185. },
  12186. error(msg, opts) {
  12187. return topLevelConfig.logger.error(msg, {
  12188. ...opts,
  12189. environment: colors$1.red(environment)
  12190. });
  12191. },
  12192. clearScreen(type) {
  12193. return topLevelConfig.logger.clearScreen(type);
  12194. },
  12195. hasErrorLogged(error) {
  12196. return topLevelConfig.logger.hasErrorLogged(error);
  12197. }
  12198. };
  12199. }
  12200. }
  12201. class BaseEnvironment extends PartialEnvironment {
  12202. get plugins() {
  12203. if (!this._plugins)
  12204. throw new Error(
  12205. `${this.name} environment.plugins called before initialized`
  12206. );
  12207. return this._plugins;
  12208. }
  12209. /**
  12210. * @internal
  12211. */
  12212. _plugins;
  12213. /**
  12214. * @internal
  12215. */
  12216. _initiated = false;
  12217. constructor(name, config, options = config.environments[name]) {
  12218. super(name, config, options);
  12219. }
  12220. }
  12221. // Copyright 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022, 2023 Simon Lydell
  12222. // License: MIT.
  12223. var HashbangComment, Identifier, JSXIdentifier, JSXPunctuator, JSXString, JSXText, KeywordsWithExpressionAfter, KeywordsWithNoLineTerminatorAfter, LineTerminatorSequence, MultiLineComment, Newline, NumericLiteral, Punctuator, RegularExpressionLiteral, SingleLineComment, StringLiteral, Template, TokensNotPrecedingObjectLiteral, TokensPrecedingExpression, WhiteSpace;
  12224. RegularExpressionLiteral = /\/(?![*\/])(?:\[(?:[^\]\\\n\r\u2028\u2029]+|\\.)*\]?|[^\/[\\\n\r\u2028\u2029]+|\\.)*(\/[$_\u200C\u200D\p{ID_Continue}]*|\\)?/yu;
  12225. Punctuator = /--|\+\+|=>|\.{3}|\??\.(?!\d)|(?:&&|\|\||\?\?|[+\-%&|^]|\*{1,2}|<{1,2}|>{1,3}|!=?|={1,2}|\/(?![\/*]))=?|[?~,:;[\](){}]/y;
  12226. Identifier = /(\x23?)(?=[$_\p{ID_Start}\\])(?:[$_\u200C\u200D\p{ID_Continue}]+|\\u[\da-fA-F]{4}|\\u\{[\da-fA-F]+\})+/yu;
  12227. StringLiteral = /(['"])(?:[^'"\\\n\r]+|(?!\1)['"]|\\(?:\r\n|[^]))*(\1)?/y;
  12228. 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;
  12229. Template = /[`}](?:[^`\\$]+|\\[^]|\$(?!\{))*(`|\$\{)?/y;
  12230. WhiteSpace = /[\t\v\f\ufeff\p{Zs}]+/yu;
  12231. LineTerminatorSequence = /\r?\n|[\r\u2028\u2029]/y;
  12232. MultiLineComment = /\/\*(?:[^*]+|\*(?!\/))*(\*\/)?/y;
  12233. SingleLineComment = /\/\/.*/y;
  12234. HashbangComment = /^#!.*/;
  12235. JSXPunctuator = /[<>.:={}]|\/(?![\/*])/y;
  12236. JSXIdentifier = /[$_\p{ID_Start}][$_\u200C\u200D\p{ID_Continue}-]*/yu;
  12237. JSXString = /(['"])(?:[^'"]+|(?!\1)['"])*(\1)?/y;
  12238. JSXText = /[^<>{}]+/y;
  12239. TokensPrecedingExpression = /^(?:[\/+-]|\.{3}|\?(?:InterpolationIn(?:JSX|Template)|NoLineTerminatorHere|NonExpressionParenEnd|UnaryIncDec))?$|[{}([,;<>=*%&|^!~?:]$/;
  12240. TokensNotPrecedingObjectLiteral = /^(?:=>|[;\]){}]|else|\?(?:NoLineTerminatorHere|NonExpressionParenEnd))?$/;
  12241. KeywordsWithExpressionAfter = /^(?:await|case|default|delete|do|else|instanceof|new|return|throw|typeof|void|yield)$/;
  12242. KeywordsWithNoLineTerminatorAfter = /^(?:return|throw|yield)$/;
  12243. Newline = RegExp(LineTerminatorSequence.source);
  12244. var jsTokens_1 = function*(input, {jsx = false} = {}) {
  12245. var braces, firstCodePoint, isExpression, lastIndex, lastSignificantToken, length, match, mode, nextLastIndex, nextLastSignificantToken, parenNesting, postfixIncDec, punctuator, stack;
  12246. ({length} = input);
  12247. lastIndex = 0;
  12248. lastSignificantToken = "";
  12249. stack = [
  12250. {tag: "JS"}
  12251. ];
  12252. braces = [];
  12253. parenNesting = 0;
  12254. postfixIncDec = false;
  12255. if (match = HashbangComment.exec(input)) {
  12256. yield ({
  12257. type: "HashbangComment",
  12258. value: match[0]
  12259. });
  12260. lastIndex = match[0].length;
  12261. }
  12262. while (lastIndex < length) {
  12263. mode = stack[stack.length - 1];
  12264. switch (mode.tag) {
  12265. case "JS":
  12266. case "JSNonExpressionParen":
  12267. case "InterpolationInTemplate":
  12268. case "InterpolationInJSX":
  12269. if (input[lastIndex] === "/" && (TokensPrecedingExpression.test(lastSignificantToken) || KeywordsWithExpressionAfter.test(lastSignificantToken))) {
  12270. RegularExpressionLiteral.lastIndex = lastIndex;
  12271. if (match = RegularExpressionLiteral.exec(input)) {
  12272. lastIndex = RegularExpressionLiteral.lastIndex;
  12273. lastSignificantToken = match[0];
  12274. postfixIncDec = true;
  12275. yield ({
  12276. type: "RegularExpressionLiteral",
  12277. value: match[0],
  12278. closed: match[1] !== void 0 && match[1] !== "\\"
  12279. });
  12280. continue;
  12281. }
  12282. }
  12283. Punctuator.lastIndex = lastIndex;
  12284. if (match = Punctuator.exec(input)) {
  12285. punctuator = match[0];
  12286. nextLastIndex = Punctuator.lastIndex;
  12287. nextLastSignificantToken = punctuator;
  12288. switch (punctuator) {
  12289. case "(":
  12290. if (lastSignificantToken === "?NonExpressionParenKeyword") {
  12291. stack.push({
  12292. tag: "JSNonExpressionParen",
  12293. nesting: parenNesting
  12294. });
  12295. }
  12296. parenNesting++;
  12297. postfixIncDec = false;
  12298. break;
  12299. case ")":
  12300. parenNesting--;
  12301. postfixIncDec = true;
  12302. if (mode.tag === "JSNonExpressionParen" && parenNesting === mode.nesting) {
  12303. stack.pop();
  12304. nextLastSignificantToken = "?NonExpressionParenEnd";
  12305. postfixIncDec = false;
  12306. }
  12307. break;
  12308. case "{":
  12309. Punctuator.lastIndex = 0;
  12310. isExpression = !TokensNotPrecedingObjectLiteral.test(lastSignificantToken) && (TokensPrecedingExpression.test(lastSignificantToken) || KeywordsWithExpressionAfter.test(lastSignificantToken));
  12311. braces.push(isExpression);
  12312. postfixIncDec = false;
  12313. break;
  12314. case "}":
  12315. switch (mode.tag) {
  12316. case "InterpolationInTemplate":
  12317. if (braces.length === mode.nesting) {
  12318. Template.lastIndex = lastIndex;
  12319. match = Template.exec(input);
  12320. lastIndex = Template.lastIndex;
  12321. lastSignificantToken = match[0];
  12322. if (match[1] === "${") {
  12323. lastSignificantToken = "?InterpolationInTemplate";
  12324. postfixIncDec = false;
  12325. yield ({
  12326. type: "TemplateMiddle",
  12327. value: match[0]
  12328. });
  12329. } else {
  12330. stack.pop();
  12331. postfixIncDec = true;
  12332. yield ({
  12333. type: "TemplateTail",
  12334. value: match[0],
  12335. closed: match[1] === "`"
  12336. });
  12337. }
  12338. continue;
  12339. }
  12340. break;
  12341. case "InterpolationInJSX":
  12342. if (braces.length === mode.nesting) {
  12343. stack.pop();
  12344. lastIndex += 1;
  12345. lastSignificantToken = "}";
  12346. yield ({
  12347. type: "JSXPunctuator",
  12348. value: "}"
  12349. });
  12350. continue;
  12351. }
  12352. }
  12353. postfixIncDec = braces.pop();
  12354. nextLastSignificantToken = postfixIncDec ? "?ExpressionBraceEnd" : "}";
  12355. break;
  12356. case "]":
  12357. postfixIncDec = true;
  12358. break;
  12359. case "++":
  12360. case "--":
  12361. nextLastSignificantToken = postfixIncDec ? "?PostfixIncDec" : "?UnaryIncDec";
  12362. break;
  12363. case "<":
  12364. if (jsx && (TokensPrecedingExpression.test(lastSignificantToken) || KeywordsWithExpressionAfter.test(lastSignificantToken))) {
  12365. stack.push({tag: "JSXTag"});
  12366. lastIndex += 1;
  12367. lastSignificantToken = "<";
  12368. yield ({
  12369. type: "JSXPunctuator",
  12370. value: punctuator
  12371. });
  12372. continue;
  12373. }
  12374. postfixIncDec = false;
  12375. break;
  12376. default:
  12377. postfixIncDec = false;
  12378. }
  12379. lastIndex = nextLastIndex;
  12380. lastSignificantToken = nextLastSignificantToken;
  12381. yield ({
  12382. type: "Punctuator",
  12383. value: punctuator
  12384. });
  12385. continue;
  12386. }
  12387. Identifier.lastIndex = lastIndex;
  12388. if (match = Identifier.exec(input)) {
  12389. lastIndex = Identifier.lastIndex;
  12390. nextLastSignificantToken = match[0];
  12391. switch (match[0]) {
  12392. case "for":
  12393. case "if":
  12394. case "while":
  12395. case "with":
  12396. if (lastSignificantToken !== "." && lastSignificantToken !== "?.") {
  12397. nextLastSignificantToken = "?NonExpressionParenKeyword";
  12398. }
  12399. }
  12400. lastSignificantToken = nextLastSignificantToken;
  12401. postfixIncDec = !KeywordsWithExpressionAfter.test(match[0]);
  12402. yield ({
  12403. type: match[1] === "#" ? "PrivateIdentifier" : "IdentifierName",
  12404. value: match[0]
  12405. });
  12406. continue;
  12407. }
  12408. StringLiteral.lastIndex = lastIndex;
  12409. if (match = StringLiteral.exec(input)) {
  12410. lastIndex = StringLiteral.lastIndex;
  12411. lastSignificantToken = match[0];
  12412. postfixIncDec = true;
  12413. yield ({
  12414. type: "StringLiteral",
  12415. value: match[0],
  12416. closed: match[2] !== void 0
  12417. });
  12418. continue;
  12419. }
  12420. NumericLiteral.lastIndex = lastIndex;
  12421. if (match = NumericLiteral.exec(input)) {
  12422. lastIndex = NumericLiteral.lastIndex;
  12423. lastSignificantToken = match[0];
  12424. postfixIncDec = true;
  12425. yield ({
  12426. type: "NumericLiteral",
  12427. value: match[0]
  12428. });
  12429. continue;
  12430. }
  12431. Template.lastIndex = lastIndex;
  12432. if (match = Template.exec(input)) {
  12433. lastIndex = Template.lastIndex;
  12434. lastSignificantToken = match[0];
  12435. if (match[1] === "${") {
  12436. lastSignificantToken = "?InterpolationInTemplate";
  12437. stack.push({
  12438. tag: "InterpolationInTemplate",
  12439. nesting: braces.length
  12440. });
  12441. postfixIncDec = false;
  12442. yield ({
  12443. type: "TemplateHead",
  12444. value: match[0]
  12445. });
  12446. } else {
  12447. postfixIncDec = true;
  12448. yield ({
  12449. type: "NoSubstitutionTemplate",
  12450. value: match[0],
  12451. closed: match[1] === "`"
  12452. });
  12453. }
  12454. continue;
  12455. }
  12456. break;
  12457. case "JSXTag":
  12458. case "JSXTagEnd":
  12459. JSXPunctuator.lastIndex = lastIndex;
  12460. if (match = JSXPunctuator.exec(input)) {
  12461. lastIndex = JSXPunctuator.lastIndex;
  12462. nextLastSignificantToken = match[0];
  12463. switch (match[0]) {
  12464. case "<":
  12465. stack.push({tag: "JSXTag"});
  12466. break;
  12467. case ">":
  12468. stack.pop();
  12469. if (lastSignificantToken === "/" || mode.tag === "JSXTagEnd") {
  12470. nextLastSignificantToken = "?JSX";
  12471. postfixIncDec = true;
  12472. } else {
  12473. stack.push({tag: "JSXChildren"});
  12474. }
  12475. break;
  12476. case "{":
  12477. stack.push({
  12478. tag: "InterpolationInJSX",
  12479. nesting: braces.length
  12480. });
  12481. nextLastSignificantToken = "?InterpolationInJSX";
  12482. postfixIncDec = false;
  12483. break;
  12484. case "/":
  12485. if (lastSignificantToken === "<") {
  12486. stack.pop();
  12487. if (stack[stack.length - 1].tag === "JSXChildren") {
  12488. stack.pop();
  12489. }
  12490. stack.push({tag: "JSXTagEnd"});
  12491. }
  12492. }
  12493. lastSignificantToken = nextLastSignificantToken;
  12494. yield ({
  12495. type: "JSXPunctuator",
  12496. value: match[0]
  12497. });
  12498. continue;
  12499. }
  12500. JSXIdentifier.lastIndex = lastIndex;
  12501. if (match = JSXIdentifier.exec(input)) {
  12502. lastIndex = JSXIdentifier.lastIndex;
  12503. lastSignificantToken = match[0];
  12504. yield ({
  12505. type: "JSXIdentifier",
  12506. value: match[0]
  12507. });
  12508. continue;
  12509. }
  12510. JSXString.lastIndex = lastIndex;
  12511. if (match = JSXString.exec(input)) {
  12512. lastIndex = JSXString.lastIndex;
  12513. lastSignificantToken = match[0];
  12514. yield ({
  12515. type: "JSXString",
  12516. value: match[0],
  12517. closed: match[2] !== void 0
  12518. });
  12519. continue;
  12520. }
  12521. break;
  12522. case "JSXChildren":
  12523. JSXText.lastIndex = lastIndex;
  12524. if (match = JSXText.exec(input)) {
  12525. lastIndex = JSXText.lastIndex;
  12526. lastSignificantToken = match[0];
  12527. yield ({
  12528. type: "JSXText",
  12529. value: match[0]
  12530. });
  12531. continue;
  12532. }
  12533. switch (input[lastIndex]) {
  12534. case "<":
  12535. stack.push({tag: "JSXTag"});
  12536. lastIndex++;
  12537. lastSignificantToken = "<";
  12538. yield ({
  12539. type: "JSXPunctuator",
  12540. value: "<"
  12541. });
  12542. continue;
  12543. case "{":
  12544. stack.push({
  12545. tag: "InterpolationInJSX",
  12546. nesting: braces.length
  12547. });
  12548. lastIndex++;
  12549. lastSignificantToken = "?InterpolationInJSX";
  12550. postfixIncDec = false;
  12551. yield ({
  12552. type: "JSXPunctuator",
  12553. value: "{"
  12554. });
  12555. continue;
  12556. }
  12557. }
  12558. WhiteSpace.lastIndex = lastIndex;
  12559. if (match = WhiteSpace.exec(input)) {
  12560. lastIndex = WhiteSpace.lastIndex;
  12561. yield ({
  12562. type: "WhiteSpace",
  12563. value: match[0]
  12564. });
  12565. continue;
  12566. }
  12567. LineTerminatorSequence.lastIndex = lastIndex;
  12568. if (match = LineTerminatorSequence.exec(input)) {
  12569. lastIndex = LineTerminatorSequence.lastIndex;
  12570. postfixIncDec = false;
  12571. if (KeywordsWithNoLineTerminatorAfter.test(lastSignificantToken)) {
  12572. lastSignificantToken = "?NoLineTerminatorHere";
  12573. }
  12574. yield ({
  12575. type: "LineTerminatorSequence",
  12576. value: match[0]
  12577. });
  12578. continue;
  12579. }
  12580. MultiLineComment.lastIndex = lastIndex;
  12581. if (match = MultiLineComment.exec(input)) {
  12582. lastIndex = MultiLineComment.lastIndex;
  12583. if (Newline.test(match[0])) {
  12584. postfixIncDec = false;
  12585. if (KeywordsWithNoLineTerminatorAfter.test(lastSignificantToken)) {
  12586. lastSignificantToken = "?NoLineTerminatorHere";
  12587. }
  12588. }
  12589. yield ({
  12590. type: "MultiLineComment",
  12591. value: match[0],
  12592. closed: match[1] !== void 0
  12593. });
  12594. continue;
  12595. }
  12596. SingleLineComment.lastIndex = lastIndex;
  12597. if (match = SingleLineComment.exec(input)) {
  12598. lastIndex = SingleLineComment.lastIndex;
  12599. postfixIncDec = false;
  12600. yield ({
  12601. type: "SingleLineComment",
  12602. value: match[0]
  12603. });
  12604. continue;
  12605. }
  12606. firstCodePoint = String.fromCodePoint(input.codePointAt(lastIndex));
  12607. lastIndex += firstCodePoint.length;
  12608. lastSignificantToken = firstCodePoint;
  12609. postfixIncDec = false;
  12610. yield ({
  12611. type: mode.tag.startsWith("JSX") ? "JSXInvalid" : "Invalid",
  12612. value: firstCodePoint
  12613. });
  12614. }
  12615. return void 0;
  12616. };
  12617. var jsTokens = /*@__PURE__*/getDefaultExportFromCjs(jsTokens_1);
  12618. function stripLiteralJsTokens(code, options) {
  12619. const FILL = " ";
  12620. const FILL_COMMENT = " ";
  12621. let result = "";
  12622. const tokens = [];
  12623. for (const token of jsTokens(code, { jsx: false })) {
  12624. tokens.push(token);
  12625. if (token.type === "SingleLineComment") {
  12626. result += FILL_COMMENT.repeat(token.value.length);
  12627. continue;
  12628. }
  12629. if (token.type === "MultiLineComment") {
  12630. result += token.value.replace(/[^\n]/g, FILL_COMMENT);
  12631. continue;
  12632. }
  12633. if (token.type === "StringLiteral") {
  12634. if (!token.closed) {
  12635. result += token.value;
  12636. continue;
  12637. }
  12638. const body = token.value.slice(1, -1);
  12639. {
  12640. result += token.value[0] + FILL.repeat(body.length) + token.value[token.value.length - 1];
  12641. continue;
  12642. }
  12643. }
  12644. if (token.type === "NoSubstitutionTemplate") {
  12645. const body = token.value.slice(1, -1);
  12646. {
  12647. result += `\`${body.replace(/[^\n]/g, FILL)}\``;
  12648. continue;
  12649. }
  12650. }
  12651. if (token.type === "RegularExpressionLiteral") {
  12652. const body = token.value;
  12653. {
  12654. result += body.replace(/\/(.*)\/(\w?)$/g, (_, $1, $2) => `/${FILL.repeat($1.length)}/${$2}`);
  12655. continue;
  12656. }
  12657. }
  12658. if (token.type === "TemplateHead") {
  12659. const body = token.value.slice(1, -2);
  12660. {
  12661. result += `\`${body.replace(/[^\n]/g, FILL)}\${`;
  12662. continue;
  12663. }
  12664. }
  12665. if (token.type === "TemplateTail") {
  12666. const body = token.value.slice(0, -2);
  12667. {
  12668. result += `}${body.replace(/[^\n]/g, FILL)}\``;
  12669. continue;
  12670. }
  12671. }
  12672. if (token.type === "TemplateMiddle") {
  12673. const body = token.value.slice(1, -2);
  12674. {
  12675. result += `}${body.replace(/[^\n]/g, FILL)}\${`;
  12676. continue;
  12677. }
  12678. }
  12679. result += token.value;
  12680. }
  12681. return {
  12682. result,
  12683. tokens
  12684. };
  12685. }
  12686. function stripLiteral(code, options) {
  12687. return stripLiteralDetailed(code).result;
  12688. }
  12689. function stripLiteralDetailed(code, options) {
  12690. return stripLiteralJsTokens(code);
  12691. }
  12692. function importGlobPlugin(config) {
  12693. const importGlobMaps = /* @__PURE__ */ new Map();
  12694. return {
  12695. name: "vite:import-glob",
  12696. buildStart() {
  12697. importGlobMaps.clear();
  12698. },
  12699. transform: {
  12700. async handler(code, id) {
  12701. if (!code.includes("import.meta.glob")) return;
  12702. const result = await transformGlobImport(
  12703. code,
  12704. id,
  12705. config.root,
  12706. (im, _, options) => this.resolve(im, id, options).then((i) => i?.id || im),
  12707. config.experimental.importGlobRestoreExtension,
  12708. config.logger
  12709. );
  12710. if (result) {
  12711. const allGlobs = result.matches.map((i) => i.globsResolved);
  12712. if (!importGlobMaps.has(this.environment)) {
  12713. importGlobMaps.set(this.environment, /* @__PURE__ */ new Map());
  12714. }
  12715. const globMatchers = allGlobs.map((globs) => {
  12716. const affirmed = [];
  12717. const negated = [];
  12718. for (const glob2 of globs) {
  12719. (glob2[0] === "!" ? negated : affirmed).push(glob2);
  12720. }
  12721. const affirmedMatcher = picomatch$2(affirmed);
  12722. const negatedMatcher = picomatch$2(negated);
  12723. return (file) => {
  12724. return (affirmed.length === 0 || affirmedMatcher(file)) && !(negated.length > 0 && negatedMatcher(file));
  12725. };
  12726. });
  12727. importGlobMaps.get(this.environment).set(id, globMatchers);
  12728. return transformStableResult(result.s, id, config);
  12729. }
  12730. }
  12731. },
  12732. hotUpdate({ type, file, modules: oldModules }) {
  12733. if (type === "update") return;
  12734. const importGlobMap = importGlobMaps.get(this.environment);
  12735. if (!importGlobMap) return;
  12736. const modules = [];
  12737. for (const [id, globMatchers] of importGlobMap) {
  12738. if (globMatchers.some((matcher) => matcher(file))) {
  12739. const mod = this.environment.moduleGraph.getModuleById(id);
  12740. if (mod) modules.push(mod);
  12741. }
  12742. }
  12743. return modules.length > 0 ? [...oldModules, ...modules] : void 0;
  12744. }
  12745. };
  12746. }
  12747. const importGlobRE = /\bimport\.meta\.glob(?:<\w+>)?\s*\(/g;
  12748. const objectKeysRE = /\bObject\.keys\(\s*$/;
  12749. const objectValuesRE = /\bObject\.values\(\s*$/;
  12750. const knownOptions = {
  12751. as: ["string"],
  12752. eager: ["boolean"],
  12753. import: ["string"],
  12754. exhaustive: ["boolean"],
  12755. query: ["object", "string"]
  12756. };
  12757. const forceDefaultAs = ["raw", "url"];
  12758. function err$1(e, pos) {
  12759. const error = new Error(e);
  12760. error.pos = pos;
  12761. return error;
  12762. }
  12763. function parseGlobOptions(rawOpts, optsStartIndex, logger) {
  12764. let opts = {};
  12765. try {
  12766. opts = evalValue(rawOpts);
  12767. } catch {
  12768. throw err$1(
  12769. "Vite is unable to parse the glob options as the value is not static",
  12770. optsStartIndex
  12771. );
  12772. }
  12773. if (opts == null) {
  12774. return {};
  12775. }
  12776. for (const key in opts) {
  12777. if (!(key in knownOptions)) {
  12778. throw err$1(`Unknown glob option "${key}"`, optsStartIndex);
  12779. }
  12780. const allowedTypes = knownOptions[key];
  12781. const valueType = typeof opts[key];
  12782. if (!allowedTypes.includes(valueType)) {
  12783. throw err$1(
  12784. `Expected glob option "${key}" to be of type ${allowedTypes.join(
  12785. " or "
  12786. )}, but got ${valueType}`,
  12787. optsStartIndex
  12788. );
  12789. }
  12790. }
  12791. if (typeof opts.query === "object") {
  12792. for (const key in opts.query) {
  12793. const value = opts.query[key];
  12794. if (!["string", "number", "boolean"].includes(typeof value)) {
  12795. throw err$1(
  12796. `Expected glob option "query.${key}" to be of type string, number, or boolean, but got ${typeof value}`,
  12797. optsStartIndex
  12798. );
  12799. }
  12800. }
  12801. opts.query = stringifyQuery(opts.query);
  12802. }
  12803. if (opts.as && logger) {
  12804. const importSuggestion = forceDefaultAs.includes(opts.as) ? `, import: 'default'` : "";
  12805. logger.warn(
  12806. colors$1.yellow(
  12807. `The glob option "as" has been deprecated in favour of "query". Please update \`as: '${opts.as}'\` to \`query: '?${opts.as}'${importSuggestion}\`.`
  12808. )
  12809. );
  12810. }
  12811. if (opts.as && forceDefaultAs.includes(opts.as)) {
  12812. if (opts.import && opts.import !== "default" && opts.import !== "*")
  12813. throw err$1(
  12814. `Option "import" can only be "default" or "*" when "as" is "${opts.as}", but got "${opts.import}"`,
  12815. optsStartIndex
  12816. );
  12817. opts.import = opts.import || "default";
  12818. }
  12819. if (opts.as && opts.query)
  12820. throw err$1(
  12821. 'Options "as" and "query" cannot be used together',
  12822. optsStartIndex
  12823. );
  12824. if (opts.as) opts.query = opts.as;
  12825. if (opts.query && opts.query[0] !== "?") opts.query = `?${opts.query}`;
  12826. return opts;
  12827. }
  12828. async function parseImportGlob(code, importer, root, resolveId, logger) {
  12829. let cleanCode;
  12830. try {
  12831. cleanCode = stripLiteral(code);
  12832. } catch {
  12833. return [];
  12834. }
  12835. const matches = Array.from(cleanCode.matchAll(importGlobRE));
  12836. const tasks = matches.map(async (match, index) => {
  12837. const start = match.index;
  12838. const err2 = (msg) => {
  12839. const e = new Error(`Invalid glob import syntax: ${msg}`);
  12840. e.pos = start;
  12841. return e;
  12842. };
  12843. const end = findCorrespondingCloseParenthesisPosition(
  12844. cleanCode,
  12845. start + match[0].length
  12846. ) + 1;
  12847. if (end <= 0) {
  12848. throw err2("Close parenthesis not found");
  12849. }
  12850. const statementCode = code.slice(start, end);
  12851. const rootAst = (await parseAstAsync(statementCode)).body[0];
  12852. if (rootAst.type !== "ExpressionStatement") {
  12853. throw err2(`Expect CallExpression, got ${rootAst.type}`);
  12854. }
  12855. const ast = rootAst.expression;
  12856. if (ast.type !== "CallExpression") {
  12857. throw err2(`Expect CallExpression, got ${ast.type}`);
  12858. }
  12859. if (ast.arguments.length < 1 || ast.arguments.length > 2)
  12860. throw err2(`Expected 1-2 arguments, but got ${ast.arguments.length}`);
  12861. const arg1 = ast.arguments[0];
  12862. const arg2 = ast.arguments[1];
  12863. const globs = [];
  12864. const validateLiteral = (element) => {
  12865. if (!element) return;
  12866. if (element.type === "Literal") {
  12867. if (typeof element.value !== "string")
  12868. throw err2(
  12869. `Expected glob to be a string, but got "${typeof element.value}"`
  12870. );
  12871. globs.push(element.value);
  12872. } else if (element.type === "TemplateLiteral") {
  12873. if (element.expressions.length !== 0) {
  12874. throw err2(
  12875. `Expected glob to be a string, but got dynamic template literal`
  12876. );
  12877. }
  12878. globs.push(element.quasis[0].value.raw);
  12879. } else {
  12880. throw err2("Could only use literals");
  12881. }
  12882. };
  12883. if (arg1.type === "ArrayExpression") {
  12884. for (const element of arg1.elements) {
  12885. validateLiteral(element);
  12886. }
  12887. } else {
  12888. validateLiteral(arg1);
  12889. }
  12890. let options = {};
  12891. if (arg2) {
  12892. if (arg2.type !== "ObjectExpression")
  12893. throw err2(
  12894. `Expected the second argument to be an object literal, but got "${arg2.type}"`
  12895. );
  12896. options = parseGlobOptions(
  12897. code.slice(start + arg2.start, start + arg2.end),
  12898. start + arg2.start,
  12899. logger
  12900. );
  12901. }
  12902. const globsResolved = await Promise.all(
  12903. globs.map((glob2) => toAbsoluteGlob(glob2, root, importer, resolveId))
  12904. );
  12905. const isRelative = globs.every((i) => ".!".includes(i[0]));
  12906. const sliceCode = cleanCode.slice(0, start);
  12907. const onlyKeys = objectKeysRE.test(sliceCode);
  12908. let onlyValues = false;
  12909. if (!onlyKeys) {
  12910. onlyValues = objectValuesRE.test(sliceCode);
  12911. }
  12912. return {
  12913. index,
  12914. globs,
  12915. globsResolved,
  12916. isRelative,
  12917. options,
  12918. start,
  12919. end,
  12920. onlyKeys,
  12921. onlyValues
  12922. };
  12923. });
  12924. return (await Promise.all(tasks)).filter(Boolean);
  12925. }
  12926. function findCorrespondingCloseParenthesisPosition(cleanCode, openPos) {
  12927. const closePos = cleanCode.indexOf(")", openPos);
  12928. if (closePos < 0) return -1;
  12929. if (!cleanCode.slice(openPos, closePos).includes("(")) return closePos;
  12930. let remainingParenthesisCount = 0;
  12931. const cleanCodeLen = cleanCode.length;
  12932. for (let pos = openPos; pos < cleanCodeLen; pos++) {
  12933. switch (cleanCode[pos]) {
  12934. case "(": {
  12935. remainingParenthesisCount++;
  12936. break;
  12937. }
  12938. case ")": {
  12939. remainingParenthesisCount--;
  12940. if (remainingParenthesisCount <= 0) {
  12941. return pos;
  12942. }
  12943. }
  12944. }
  12945. }
  12946. return -1;
  12947. }
  12948. const importPrefix = "__vite_glob_";
  12949. const { basename, dirname, relative } = posix$1;
  12950. async function transformGlobImport(code, id, root, resolveId, restoreQueryExtension = false, logger) {
  12951. id = slash$1(id);
  12952. root = slash$1(root);
  12953. const isVirtual = isVirtualModule(id);
  12954. const dir = isVirtual ? void 0 : dirname(id);
  12955. const matches = await parseImportGlob(
  12956. code,
  12957. isVirtual ? void 0 : id,
  12958. root,
  12959. resolveId,
  12960. logger
  12961. );
  12962. const matchedFiles = /* @__PURE__ */ new Set();
  12963. if (!matches.length) return null;
  12964. const s = new MagicString(code);
  12965. const staticImports = (await Promise.all(
  12966. matches.map(
  12967. async ({
  12968. globsResolved,
  12969. isRelative,
  12970. options,
  12971. index,
  12972. start,
  12973. end,
  12974. onlyKeys,
  12975. onlyValues
  12976. }) => {
  12977. const cwd = getCommonBase(globsResolved) ?? root;
  12978. const files = (await glob(globsResolved, {
  12979. absolute: true,
  12980. cwd,
  12981. dot: !!options.exhaustive,
  12982. expandDirectories: false,
  12983. ignore: options.exhaustive ? [] : ["**/node_modules/**"]
  12984. })).filter((file) => file !== id).sort();
  12985. const objectProps = [];
  12986. const staticImports2 = [];
  12987. const resolvePaths = (file) => {
  12988. if (!dir) {
  12989. if (isRelative)
  12990. throw new Error(
  12991. "In virtual modules, all globs must start with '/'"
  12992. );
  12993. const filePath2 = `/${relative(root, file)}`;
  12994. return { filePath: filePath2, importPath: filePath2 };
  12995. }
  12996. let importPath = relative(dir, file);
  12997. if (importPath[0] !== ".") importPath = `./${importPath}`;
  12998. let filePath;
  12999. if (isRelative) {
  13000. filePath = importPath;
  13001. } else {
  13002. filePath = relative(root, file);
  13003. if (filePath[0] !== ".") filePath = `/${filePath}`;
  13004. }
  13005. return { filePath, importPath };
  13006. };
  13007. files.forEach((file, i) => {
  13008. const paths = resolvePaths(file);
  13009. const filePath = paths.filePath;
  13010. let importPath = paths.importPath;
  13011. let importQuery = options.query ?? "";
  13012. if (onlyKeys) {
  13013. objectProps.push(`${JSON.stringify(filePath)}: 0`);
  13014. return;
  13015. }
  13016. if (importQuery && importQuery !== "?raw") {
  13017. const fileExtension = basename(file).split(".").slice(-1)[0];
  13018. if (fileExtension && restoreQueryExtension)
  13019. importQuery = `${importQuery}&lang.${fileExtension}`;
  13020. }
  13021. importPath = `${importPath}${importQuery}`;
  13022. const importKey = options.import && options.import !== "*" ? options.import : void 0;
  13023. if (options.eager) {
  13024. const variableName = `${importPrefix}${index}_${i}`;
  13025. const expression = importKey ? `{ ${importKey} as ${variableName} }` : `* as ${variableName}`;
  13026. staticImports2.push(
  13027. `import ${expression} from ${JSON.stringify(importPath)}`
  13028. );
  13029. objectProps.push(
  13030. onlyValues ? `${variableName}` : `${JSON.stringify(filePath)}: ${variableName}`
  13031. );
  13032. } else {
  13033. let importStatement = `import(${JSON.stringify(importPath)})`;
  13034. if (importKey)
  13035. importStatement += `.then(m => m[${JSON.stringify(importKey)}])`;
  13036. objectProps.push(
  13037. onlyValues ? `() => ${importStatement}` : `${JSON.stringify(filePath)}: () => ${importStatement}`
  13038. );
  13039. }
  13040. });
  13041. files.forEach((i) => matchedFiles.add(i));
  13042. const originalLineBreakCount = code.slice(start, end).match(/\n/g)?.length ?? 0;
  13043. const lineBreaks = originalLineBreakCount > 0 ? "\n".repeat(originalLineBreakCount) : "";
  13044. let replacement = "";
  13045. if (onlyKeys) {
  13046. replacement = `{${objectProps.join(",")}${lineBreaks}}`;
  13047. } else if (onlyValues) {
  13048. replacement = `[${objectProps.join(",")}${lineBreaks}]`;
  13049. } else {
  13050. replacement = `/* #__PURE__ */ Object.assign({${objectProps.join(
  13051. ","
  13052. )}${lineBreaks}})`;
  13053. }
  13054. s.overwrite(start, end, replacement);
  13055. return staticImports2;
  13056. }
  13057. )
  13058. )).flat();
  13059. if (staticImports.length) s.prepend(`${staticImports.join(";")};`);
  13060. return {
  13061. s,
  13062. matches,
  13063. files: matchedFiles
  13064. };
  13065. }
  13066. function globSafePath(path) {
  13067. return escapePath(normalizePath$3(path));
  13068. }
  13069. function lastNthChar(str, n) {
  13070. return str.charAt(str.length - 1 - n);
  13071. }
  13072. function globSafeResolvedPath(resolved, glob2) {
  13073. let numEqual = 0;
  13074. const maxEqual = Math.min(resolved.length, glob2.length);
  13075. while (numEqual < maxEqual && lastNthChar(resolved, numEqual) === lastNthChar(glob2, numEqual)) {
  13076. numEqual += 1;
  13077. }
  13078. const staticPartEnd = resolved.length - numEqual;
  13079. const staticPart = resolved.slice(0, staticPartEnd);
  13080. const dynamicPart = resolved.slice(staticPartEnd);
  13081. return globSafePath(staticPart) + dynamicPart;
  13082. }
  13083. async function toAbsoluteGlob(glob2, root, importer, resolveId) {
  13084. let pre = "";
  13085. if (glob2[0] === "!") {
  13086. pre = "!";
  13087. glob2 = glob2.slice(1);
  13088. }
  13089. root = globSafePath(root);
  13090. const dir = importer ? globSafePath(dirname(importer)) : root;
  13091. if (glob2[0] === "/") return pre + posix$1.join(root, glob2.slice(1));
  13092. if (glob2.startsWith("./")) return pre + posix$1.join(dir, glob2.slice(2));
  13093. if (glob2.startsWith("../")) return pre + posix$1.join(dir, glob2);
  13094. if (glob2.startsWith("**")) return pre + glob2;
  13095. const isSubImportsPattern = glob2[0] === "#" && glob2.includes("*");
  13096. const resolved = normalizePath$3(
  13097. await resolveId(glob2, importer, {
  13098. custom: { "vite:import-glob": { isSubImportsPattern } }
  13099. }) || glob2
  13100. );
  13101. if (isAbsolute$1(resolved)) {
  13102. return pre + globSafeResolvedPath(resolved, glob2);
  13103. }
  13104. throw new Error(
  13105. `Invalid glob: "${glob2}" (resolved: "${resolved}"). It must start with '/' or './'`
  13106. );
  13107. }
  13108. function getCommonBase(globsResolved) {
  13109. const bases = globsResolved.filter((g) => g[0] !== "!").map((glob2) => {
  13110. let { base } = picomatch$2.scan(glob2);
  13111. if (posix$1.basename(base).includes(".")) base = posix$1.dirname(base);
  13112. return base;
  13113. });
  13114. if (!bases.length) return null;
  13115. let commonAncestor = "";
  13116. const dirS = bases[0].split("/");
  13117. for (let i = 0; i < dirS.length; i++) {
  13118. const candidate = dirS.slice(0, i + 1).join("/");
  13119. if (bases.every((base) => base.startsWith(candidate)))
  13120. commonAncestor = candidate;
  13121. else break;
  13122. }
  13123. if (!commonAncestor) commonAncestor = "/";
  13124. return commonAncestor;
  13125. }
  13126. function isVirtualModule(id) {
  13127. return id.startsWith("virtual:") || id[0] === "\0" || !id.includes("/");
  13128. }
  13129. class ScanEnvironment extends BaseEnvironment {
  13130. mode = "scan";
  13131. get pluginContainer() {
  13132. if (!this._pluginContainer)
  13133. throw new Error(
  13134. `${this.name} environment.pluginContainer called before initialized`
  13135. );
  13136. return this._pluginContainer;
  13137. }
  13138. /**
  13139. * @internal
  13140. */
  13141. _pluginContainer;
  13142. async init() {
  13143. if (this._initiated) {
  13144. return;
  13145. }
  13146. this._initiated = true;
  13147. this._plugins = await resolveEnvironmentPlugins(this);
  13148. this._pluginContainer = await createEnvironmentPluginContainer(
  13149. this,
  13150. this.plugins,
  13151. void 0,
  13152. false
  13153. );
  13154. }
  13155. }
  13156. function devToScanEnvironment(environment) {
  13157. return {
  13158. mode: "scan",
  13159. get name() {
  13160. return environment.name;
  13161. },
  13162. getTopLevelConfig() {
  13163. return environment.getTopLevelConfig();
  13164. },
  13165. /**
  13166. * @deprecated use environment.config instead
  13167. **/
  13168. get options() {
  13169. return environment.options;
  13170. },
  13171. get config() {
  13172. return environment.config;
  13173. },
  13174. get logger() {
  13175. return environment.logger;
  13176. },
  13177. get pluginContainer() {
  13178. return environment.pluginContainer;
  13179. },
  13180. get plugins() {
  13181. return environment.plugins;
  13182. }
  13183. };
  13184. }
  13185. const debug$g = createDebugger("vite:deps");
  13186. const htmlTypesRE = /\.(html|vue|svelte|astro|imba)$/;
  13187. const importsRE = /(?<!\/\/.*)(?<=^|;|\*\/)\s*import(?!\s+type)(?:[\w*{}\n\r\t, ]+from)?\s*("[^"]+"|'[^']+')\s*(?=$|;|\/\/|\/\*)/gm;
  13188. function scanImports(environment) {
  13189. const start = performance$1.now();
  13190. const deps = {};
  13191. const missing = {};
  13192. let entries;
  13193. const { config } = environment;
  13194. const scanContext = { cancelled: false };
  13195. const esbuildContext = computeEntries(
  13196. environment
  13197. ).then((computedEntries) => {
  13198. entries = computedEntries;
  13199. if (!entries.length) {
  13200. if (!config.optimizeDeps.entries && !config.optimizeDeps.include) {
  13201. environment.logger.warn(
  13202. colors$1.yellow(
  13203. "(!) Could not auto-determine entry point from rollupOptions or html files and there are no explicit optimizeDeps.include patterns. Skipping dependency pre-bundling."
  13204. )
  13205. );
  13206. }
  13207. return;
  13208. }
  13209. if (scanContext.cancelled) return;
  13210. debug$g?.(
  13211. `Crawling dependencies using entries: ${entries.map((entry) => `
  13212. ${colors$1.dim(entry)}`).join("")}`
  13213. );
  13214. return prepareEsbuildScanner(
  13215. environment,
  13216. entries,
  13217. deps,
  13218. missing,
  13219. scanContext
  13220. );
  13221. });
  13222. const result = esbuildContext.then((context) => {
  13223. function disposeContext() {
  13224. return context?.dispose().catch((e) => {
  13225. environment.logger.error("Failed to dispose esbuild context", {
  13226. error: e
  13227. });
  13228. });
  13229. }
  13230. if (!context || scanContext.cancelled) {
  13231. disposeContext();
  13232. return { deps: {}, missing: {} };
  13233. }
  13234. return context.rebuild().then(() => {
  13235. return {
  13236. // Ensure a fixed order so hashes are stable and improve logs
  13237. deps: orderedDependencies(deps),
  13238. missing
  13239. };
  13240. }).finally(() => {
  13241. return disposeContext();
  13242. });
  13243. }).catch(async (e) => {
  13244. if (e.errors && e.message.includes("The build was canceled")) {
  13245. return { deps: {}, missing: {} };
  13246. }
  13247. const prependMessage = colors$1.red(` Failed to scan for dependencies from entries:
  13248. ${entries.join("\n")}
  13249. `);
  13250. if (e.errors) {
  13251. const msgs = await formatMessages(e.errors, {
  13252. kind: "error",
  13253. color: true
  13254. });
  13255. e.message = prependMessage + msgs.join("\n");
  13256. } else {
  13257. e.message = prependMessage + e.message;
  13258. }
  13259. throw e;
  13260. }).finally(() => {
  13261. if (debug$g) {
  13262. const duration = (performance$1.now() - start).toFixed(2);
  13263. const depsStr = Object.keys(orderedDependencies(deps)).sort().map((id) => `
  13264. ${colors$1.cyan(id)} -> ${colors$1.dim(deps[id])}`).join("") || colors$1.dim("no dependencies found");
  13265. debug$g(`Scan completed in ${duration}ms: ${depsStr}`);
  13266. }
  13267. });
  13268. return {
  13269. cancel: async () => {
  13270. scanContext.cancelled = true;
  13271. return esbuildContext.then((context) => context?.cancel());
  13272. },
  13273. result
  13274. };
  13275. }
  13276. async function computeEntries(environment) {
  13277. let entries = [];
  13278. const explicitEntryPatterns = environment.config.optimizeDeps.entries;
  13279. const buildInput = environment.config.build.rollupOptions.input;
  13280. if (explicitEntryPatterns) {
  13281. entries = await globEntries(explicitEntryPatterns, environment);
  13282. } else if (buildInput) {
  13283. const resolvePath = async (p) => {
  13284. const id = (await environment.pluginContainer.resolveId(p, void 0, {
  13285. scan: true
  13286. }))?.id;
  13287. if (id === void 0) {
  13288. throw new Error(
  13289. `failed to resolve rollupOptions.input value: ${JSON.stringify(p)}.`
  13290. );
  13291. }
  13292. return id;
  13293. };
  13294. if (typeof buildInput === "string") {
  13295. entries = [await resolvePath(buildInput)];
  13296. } else if (Array.isArray(buildInput)) {
  13297. entries = await Promise.all(buildInput.map(resolvePath));
  13298. } else if (isObject$1(buildInput)) {
  13299. entries = await Promise.all(Object.values(buildInput).map(resolvePath));
  13300. } else {
  13301. throw new Error("invalid rollupOptions.input value.");
  13302. }
  13303. } else {
  13304. entries = await globEntries("**/*.html", environment);
  13305. }
  13306. entries = entries.filter(
  13307. (entry) => isScannable(entry, environment.config.optimizeDeps.extensions) && fs__default.existsSync(entry)
  13308. );
  13309. return entries;
  13310. }
  13311. async function prepareEsbuildScanner(environment, entries, deps, missing, scanContext) {
  13312. if (scanContext.cancelled) return;
  13313. const plugin = esbuildScanPlugin(environment, deps, missing, entries);
  13314. const { plugins = [], ...esbuildOptions } = environment.config.optimizeDeps.esbuildOptions ?? {};
  13315. let tsconfigRaw = esbuildOptions.tsconfigRaw;
  13316. if (!tsconfigRaw && !esbuildOptions.tsconfig) {
  13317. const { tsconfig } = await loadTsconfigJsonForFile(
  13318. path$b.join(environment.config.root, "_dummy.js")
  13319. );
  13320. if (tsconfig.compilerOptions?.experimentalDecorators) {
  13321. tsconfigRaw = { compilerOptions: { experimentalDecorators: true } };
  13322. }
  13323. }
  13324. return await esbuild.context({
  13325. absWorkingDir: process.cwd(),
  13326. write: false,
  13327. stdin: {
  13328. contents: entries.map((e) => `import ${JSON.stringify(e)}`).join("\n"),
  13329. loader: "js"
  13330. },
  13331. bundle: true,
  13332. format: "esm",
  13333. logLevel: "silent",
  13334. plugins: [...plugins, plugin],
  13335. ...esbuildOptions,
  13336. tsconfigRaw
  13337. });
  13338. }
  13339. function orderedDependencies(deps) {
  13340. const depsList = Object.entries(deps);
  13341. depsList.sort((a, b) => a[0].localeCompare(b[0]));
  13342. return Object.fromEntries(depsList);
  13343. }
  13344. function globEntries(pattern, environment) {
  13345. const resolvedPatterns = arraify(pattern);
  13346. if (resolvedPatterns.every((str) => !isDynamicPattern(str))) {
  13347. return resolvedPatterns.map(
  13348. (p) => normalizePath$3(path$b.resolve(environment.config.root, p))
  13349. );
  13350. }
  13351. return glob(pattern, {
  13352. absolute: true,
  13353. cwd: environment.config.root,
  13354. ignore: [
  13355. "**/node_modules/**",
  13356. `**/${environment.config.build.outDir}/**`,
  13357. // if there aren't explicit entries, also ignore other common folders
  13358. ...environment.config.optimizeDeps.entries ? [] : [`**/__tests__/**`, `**/coverage/**`]
  13359. ]
  13360. });
  13361. }
  13362. const scriptRE = /(<script(?:\s+[a-z_:][-\w:]*(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^"'<>=\s]+))?)*\s*>)(.*?)<\/script>/gis;
  13363. const commentRE$1 = /<!--.*?-->/gs;
  13364. const srcRE = /\bsrc\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s'">]+))/i;
  13365. const typeRE = /\btype\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s'">]+))/i;
  13366. const langRE = /\blang\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s'">]+))/i;
  13367. const svelteScriptModuleRE = /\bcontext\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s'">]+))/i;
  13368. const svelteModuleRE = /\smodule\b/i;
  13369. function esbuildScanPlugin(environment, depImports, missing, entries) {
  13370. const seen = /* @__PURE__ */ new Map();
  13371. async function resolveId(id, importer) {
  13372. return environment.pluginContainer.resolveId(
  13373. id,
  13374. importer && normalizePath$3(importer),
  13375. { scan: true }
  13376. );
  13377. }
  13378. const resolve = async (id, importer) => {
  13379. const key = id + (importer && path$b.dirname(importer));
  13380. if (seen.has(key)) {
  13381. return seen.get(key);
  13382. }
  13383. const resolved = await resolveId(id, importer);
  13384. const res = resolved?.id;
  13385. seen.set(key, res);
  13386. return res;
  13387. };
  13388. const optimizeDepsOptions = environment.config.optimizeDeps;
  13389. const include = optimizeDepsOptions.include;
  13390. const exclude = [
  13391. ...optimizeDepsOptions.exclude ?? [],
  13392. "@vite/client",
  13393. "@vite/env"
  13394. ];
  13395. const isUnlessEntry = (path2) => !entries.includes(path2);
  13396. const externalUnlessEntry = ({ path: path2 }) => ({
  13397. path: path2,
  13398. external: isUnlessEntry(path2)
  13399. });
  13400. const doTransformGlobImport = async (contents, id, loader) => {
  13401. let transpiledContents;
  13402. if (loader !== "js") {
  13403. transpiledContents = (await transform$1(contents, { loader })).code;
  13404. } else {
  13405. transpiledContents = contents;
  13406. }
  13407. const result = await transformGlobImport(
  13408. transpiledContents,
  13409. id,
  13410. environment.config.root,
  13411. resolve
  13412. );
  13413. return result?.s.toString() || transpiledContents;
  13414. };
  13415. return {
  13416. name: "vite:dep-scan",
  13417. setup(build) {
  13418. const scripts = {};
  13419. build.onResolve({ filter: externalRE }, ({ path: path2 }) => ({
  13420. path: path2,
  13421. external: true
  13422. }));
  13423. build.onResolve({ filter: dataUrlRE }, ({ path: path2 }) => ({
  13424. path: path2,
  13425. external: true
  13426. }));
  13427. build.onResolve({ filter: virtualModuleRE }, ({ path: path2 }) => {
  13428. return {
  13429. // strip prefix to get valid filesystem path so esbuild can resolve imports in the file
  13430. path: path2.replace(virtualModulePrefix, ""),
  13431. namespace: "script"
  13432. };
  13433. });
  13434. build.onLoad({ filter: /.*/, namespace: "script" }, ({ path: path2 }) => {
  13435. return scripts[path2];
  13436. });
  13437. build.onResolve({ filter: htmlTypesRE }, async ({ path: path2, importer }) => {
  13438. const resolved = await resolve(path2, importer);
  13439. if (!resolved) return;
  13440. if (isInNodeModules$1(resolved) && isOptimizable(resolved, optimizeDepsOptions))
  13441. return;
  13442. return {
  13443. path: resolved,
  13444. namespace: "html"
  13445. };
  13446. });
  13447. const htmlTypeOnLoadCallback = async ({ path: p }) => {
  13448. let raw = await fsp.readFile(p, "utf-8");
  13449. raw = raw.replace(commentRE$1, "<!---->");
  13450. const isHtml = p.endsWith(".html");
  13451. let js = "";
  13452. let scriptId = 0;
  13453. const matches = raw.matchAll(scriptRE);
  13454. for (const [, openTag, content] of matches) {
  13455. const typeMatch = typeRE.exec(openTag);
  13456. const type = typeMatch && (typeMatch[1] || typeMatch[2] || typeMatch[3]);
  13457. const langMatch = langRE.exec(openTag);
  13458. const lang = langMatch && (langMatch[1] || langMatch[2] || langMatch[3]);
  13459. if (isHtml && type !== "module") {
  13460. continue;
  13461. }
  13462. if (type && !(type.includes("javascript") || type.includes("ecmascript") || type === "module")) {
  13463. continue;
  13464. }
  13465. let loader = "js";
  13466. if (lang === "ts" || lang === "tsx" || lang === "jsx") {
  13467. loader = lang;
  13468. } else if (p.endsWith(".astro")) {
  13469. loader = "ts";
  13470. }
  13471. const srcMatch = srcRE.exec(openTag);
  13472. if (srcMatch) {
  13473. const src = srcMatch[1] || srcMatch[2] || srcMatch[3];
  13474. js += `import ${JSON.stringify(src)}
  13475. `;
  13476. } else if (content.trim()) {
  13477. const contents = content + (loader.startsWith("ts") ? extractImportPaths(content) : "");
  13478. const key = `${p}?id=${scriptId++}`;
  13479. if (contents.includes("import.meta.glob")) {
  13480. scripts[key] = {
  13481. loader: "js",
  13482. // since it is transpiled
  13483. contents: await doTransformGlobImport(contents, p, loader),
  13484. resolveDir: normalizePath$3(path$b.dirname(p)),
  13485. pluginData: {
  13486. htmlType: { loader }
  13487. }
  13488. };
  13489. } else {
  13490. scripts[key] = {
  13491. loader,
  13492. contents,
  13493. resolveDir: normalizePath$3(path$b.dirname(p)),
  13494. pluginData: {
  13495. htmlType: { loader }
  13496. }
  13497. };
  13498. }
  13499. const virtualModulePath = JSON.stringify(virtualModulePrefix + key);
  13500. let addedImport = false;
  13501. if (p.endsWith(".svelte")) {
  13502. let isModule = svelteModuleRE.test(openTag);
  13503. if (!isModule) {
  13504. const contextMatch = svelteScriptModuleRE.exec(openTag);
  13505. const context = contextMatch && (contextMatch[1] || contextMatch[2] || contextMatch[3]);
  13506. isModule = context === "module";
  13507. }
  13508. if (!isModule) {
  13509. addedImport = true;
  13510. js += `import ${virtualModulePath}
  13511. `;
  13512. }
  13513. }
  13514. if (!addedImport) {
  13515. js += `export * from ${virtualModulePath}
  13516. `;
  13517. }
  13518. }
  13519. }
  13520. if (!p.endsWith(".vue") || !js.includes("export default")) {
  13521. js += "\nexport default {}";
  13522. }
  13523. return {
  13524. loader: "js",
  13525. contents: js
  13526. };
  13527. };
  13528. build.onLoad(
  13529. { filter: htmlTypesRE, namespace: "html" },
  13530. htmlTypeOnLoadCallback
  13531. );
  13532. build.onLoad(
  13533. { filter: htmlTypesRE, namespace: "file" },
  13534. htmlTypeOnLoadCallback
  13535. );
  13536. build.onResolve(
  13537. {
  13538. // avoid matching windows volume
  13539. filter: /^[\w@][^:]/
  13540. },
  13541. async ({ path: id, importer }) => {
  13542. if (moduleListContains(exclude, id)) {
  13543. return externalUnlessEntry({ path: id });
  13544. }
  13545. if (depImports[id]) {
  13546. return externalUnlessEntry({ path: id });
  13547. }
  13548. const resolved = await resolve(id, importer);
  13549. if (resolved) {
  13550. if (shouldExternalizeDep(resolved, id)) {
  13551. return externalUnlessEntry({ path: id });
  13552. }
  13553. if (isInNodeModules$1(resolved) || include?.includes(id)) {
  13554. if (isOptimizable(resolved, optimizeDepsOptions)) {
  13555. depImports[id] = resolved;
  13556. }
  13557. return externalUnlessEntry({ path: id });
  13558. } else if (isScannable(resolved, optimizeDepsOptions.extensions)) {
  13559. const namespace = htmlTypesRE.test(resolved) ? "html" : void 0;
  13560. return {
  13561. path: path$b.resolve(resolved),
  13562. namespace
  13563. };
  13564. } else {
  13565. return externalUnlessEntry({ path: id });
  13566. }
  13567. } else {
  13568. missing[id] = normalizePath$3(importer);
  13569. }
  13570. }
  13571. );
  13572. const setupExternalize = (filter, doExternalize) => {
  13573. build.onResolve({ filter }, ({ path: path2 }) => {
  13574. return {
  13575. path: path2,
  13576. external: doExternalize(path2)
  13577. };
  13578. });
  13579. };
  13580. setupExternalize(CSS_LANGS_RE, isUnlessEntry);
  13581. setupExternalize(/\.(json|json5|wasm)$/, isUnlessEntry);
  13582. setupExternalize(
  13583. new RegExp(`\\.(${KNOWN_ASSET_TYPES.join("|")})$`),
  13584. isUnlessEntry
  13585. );
  13586. setupExternalize(SPECIAL_QUERY_RE, () => true);
  13587. build.onResolve(
  13588. {
  13589. filter: /.*/
  13590. },
  13591. async ({ path: id, importer }) => {
  13592. const resolved = await resolve(id, importer);
  13593. if (resolved) {
  13594. if (shouldExternalizeDep(resolved, id) || !isScannable(resolved, optimizeDepsOptions.extensions)) {
  13595. return externalUnlessEntry({ path: id });
  13596. }
  13597. const namespace = htmlTypesRE.test(resolved) ? "html" : void 0;
  13598. return {
  13599. path: path$b.resolve(cleanUrl(resolved)),
  13600. namespace
  13601. };
  13602. } else {
  13603. return externalUnlessEntry({ path: id });
  13604. }
  13605. }
  13606. );
  13607. build.onLoad({ filter: JS_TYPES_RE }, async ({ path: id }) => {
  13608. let ext = path$b.extname(id).slice(1);
  13609. if (ext === "mjs") ext = "js";
  13610. const esbuildConfig = environment.config.esbuild;
  13611. let contents = await fsp.readFile(id, "utf-8");
  13612. if (ext.endsWith("x") && esbuildConfig && esbuildConfig.jsxInject) {
  13613. contents = esbuildConfig.jsxInject + `
  13614. ` + contents;
  13615. }
  13616. const loader = optimizeDepsOptions.esbuildOptions?.loader?.[`.${ext}`] ?? ext;
  13617. if (contents.includes("import.meta.glob")) {
  13618. return {
  13619. loader: "js",
  13620. // since it is transpiled,
  13621. contents: await doTransformGlobImport(contents, id, loader)
  13622. };
  13623. }
  13624. return {
  13625. loader,
  13626. contents
  13627. };
  13628. });
  13629. build.onLoad({ filter: /.*/, namespace: "file" }, () => {
  13630. return {
  13631. loader: "js",
  13632. contents: "export default {}"
  13633. };
  13634. });
  13635. }
  13636. };
  13637. }
  13638. function extractImportPaths(code) {
  13639. code = code.replace(multilineCommentsRE, "/* */").replace(singlelineCommentsRE, "");
  13640. let js = "";
  13641. let m;
  13642. importsRE.lastIndex = 0;
  13643. while ((m = importsRE.exec(code)) != null) {
  13644. js += `
  13645. import ${m[1]}`;
  13646. }
  13647. return js;
  13648. }
  13649. function shouldExternalizeDep(resolvedId, rawId) {
  13650. if (!path$b.isAbsolute(resolvedId)) {
  13651. return true;
  13652. }
  13653. if (resolvedId === rawId || resolvedId.includes("\0")) {
  13654. return true;
  13655. }
  13656. return false;
  13657. }
  13658. function isScannable(id, extensions) {
  13659. return JS_TYPES_RE.test(id) || htmlTypesRE.test(id) || extensions?.includes(path$b.extname(id)) || false;
  13660. }
  13661. function createOptimizeDepsIncludeResolver(environment) {
  13662. const topLevelConfig = environment.getTopLevelConfig();
  13663. const resolve = createBackCompatIdResolver(topLevelConfig, {
  13664. asSrc: false,
  13665. scan: true,
  13666. packageCache: /* @__PURE__ */ new Map()
  13667. });
  13668. return async (id) => {
  13669. const lastArrowIndex = id.lastIndexOf(">");
  13670. if (lastArrowIndex === -1) {
  13671. return await resolve(environment, id, void 0);
  13672. }
  13673. const nestedRoot = id.substring(0, lastArrowIndex).trim();
  13674. const nestedPath = id.substring(lastArrowIndex + 1).trim();
  13675. const basedir = nestedResolveBasedir(
  13676. nestedRoot,
  13677. topLevelConfig.root,
  13678. topLevelConfig.resolve.preserveSymlinks
  13679. );
  13680. return await resolve(
  13681. environment,
  13682. nestedPath,
  13683. path$b.resolve(basedir, "package.json")
  13684. );
  13685. };
  13686. }
  13687. function expandGlobIds(id, config) {
  13688. const pkgName = getNpmPackageName(id);
  13689. if (!pkgName) return [];
  13690. const pkgData = resolvePackageData(
  13691. pkgName,
  13692. config.root,
  13693. config.resolve.preserveSymlinks,
  13694. config.packageCache
  13695. );
  13696. if (!pkgData) return [];
  13697. const pattern = "." + id.slice(pkgName.length);
  13698. const exports = pkgData.data.exports;
  13699. if (exports) {
  13700. if (typeof exports === "string" || Array.isArray(exports)) {
  13701. return [pkgName];
  13702. }
  13703. const possibleExportPaths = [];
  13704. for (const key in exports) {
  13705. if (key[0] === ".") {
  13706. if (key.includes("*")) {
  13707. const exportsValue = getFirstExportStringValue(exports[key]);
  13708. if (!exportsValue) continue;
  13709. const exportValuePattern = exportsValue.replace(/\*/g, "**/*");
  13710. const exportsValueGlobRe = new RegExp(
  13711. exportsValue.split("*").map(escapeRegex).join("(.*)")
  13712. );
  13713. possibleExportPaths.push(
  13714. ...globSync(exportValuePattern, {
  13715. cwd: pkgData.dir,
  13716. expandDirectories: false,
  13717. ignore: ["node_modules"]
  13718. }).map((filePath) => {
  13719. if (exportsValue.startsWith("./")) {
  13720. filePath = "./" + filePath;
  13721. }
  13722. const matched2 = exportsValueGlobRe.exec(slash$1(filePath));
  13723. if (matched2) {
  13724. let allGlobSame = matched2.length === 2;
  13725. if (!allGlobSame) {
  13726. allGlobSame = true;
  13727. for (let i = 2; i < matched2.length; i++) {
  13728. if (matched2[i] !== matched2[i - 1]) {
  13729. allGlobSame = false;
  13730. break;
  13731. }
  13732. }
  13733. }
  13734. if (allGlobSame) {
  13735. return key.replace("*", matched2[1]).slice(2);
  13736. }
  13737. }
  13738. return "";
  13739. }).filter(Boolean)
  13740. );
  13741. } else {
  13742. possibleExportPaths.push(key.slice(2));
  13743. }
  13744. }
  13745. }
  13746. const isMatch = picomatch$2(pattern);
  13747. const matched = possibleExportPaths.filter((p) => isMatch(p)).map((match) => path$b.posix.join(pkgName, match));
  13748. matched.unshift(pkgName);
  13749. return matched;
  13750. } else {
  13751. const matched = globSync(pattern, {
  13752. cwd: pkgData.dir,
  13753. expandDirectories: false,
  13754. ignore: ["node_modules"]
  13755. }).map((match) => path$b.posix.join(pkgName, slash$1(match)));
  13756. matched.unshift(pkgName);
  13757. return matched;
  13758. }
  13759. }
  13760. function getFirstExportStringValue(obj) {
  13761. if (typeof obj === "string") {
  13762. return obj;
  13763. } else if (Array.isArray(obj)) {
  13764. return obj[0];
  13765. } else {
  13766. for (const key in obj) {
  13767. return getFirstExportStringValue(obj[key]);
  13768. }
  13769. }
  13770. }
  13771. function nestedResolveBasedir(id, basedir, preserveSymlinks = false) {
  13772. const pkgs = id.split(">").map((pkg) => pkg.trim());
  13773. for (const pkg of pkgs) {
  13774. basedir = resolvePackageData(pkg, basedir, preserveSymlinks)?.dir || basedir;
  13775. }
  13776. return basedir;
  13777. }
  13778. const debug$f = createDebugger("vite:deps");
  13779. const jsExtensionRE = /\.js$/i;
  13780. const jsMapExtensionRE = /\.js\.map$/i;
  13781. function isDepOptimizationDisabled(optimizeDeps2) {
  13782. return optimizeDeps2.disabled === true || optimizeDeps2.disabled === "dev" || !!optimizeDeps2.noDiscovery && !optimizeDeps2.include?.length;
  13783. }
  13784. async function optimizeDeps(config, force = config.optimizeDeps.force, asCommand = false) {
  13785. const log = asCommand ? config.logger.info : debug$f;
  13786. config.logger.warn(
  13787. colors$1.yellow(
  13788. "manually calling optimizeDeps is deprecated. This is done automatically and does not need to be called manually."
  13789. )
  13790. );
  13791. const environment = new ScanEnvironment("client", config);
  13792. await environment.init();
  13793. const cachedMetadata = await loadCachedDepOptimizationMetadata(
  13794. environment,
  13795. force,
  13796. asCommand
  13797. );
  13798. if (cachedMetadata) {
  13799. return cachedMetadata;
  13800. }
  13801. const deps = await discoverProjectDependencies(environment).result;
  13802. await addManuallyIncludedOptimizeDeps(environment, deps);
  13803. const depsString = depsLogString(Object.keys(deps));
  13804. log?.(colors$1.green(`Optimizing dependencies:
  13805. ${depsString}`));
  13806. const depsInfo = toDiscoveredDependencies(environment, deps);
  13807. const result = await runOptimizeDeps(environment, depsInfo).result;
  13808. await result.commit();
  13809. return result.metadata;
  13810. }
  13811. async function optimizeExplicitEnvironmentDeps(environment) {
  13812. const cachedMetadata = await loadCachedDepOptimizationMetadata(
  13813. environment,
  13814. environment.config.optimizeDeps.force ?? false,
  13815. false
  13816. );
  13817. if (cachedMetadata) {
  13818. return cachedMetadata;
  13819. }
  13820. const deps = {};
  13821. await addManuallyIncludedOptimizeDeps(environment, deps);
  13822. const depsInfo = toDiscoveredDependencies(environment, deps);
  13823. const result = await runOptimizeDeps(environment, depsInfo).result;
  13824. await result.commit();
  13825. return result.metadata;
  13826. }
  13827. function initDepsOptimizerMetadata(environment, timestamp) {
  13828. const { lockfileHash, configHash, hash } = getDepHash(environment);
  13829. return {
  13830. hash,
  13831. lockfileHash,
  13832. configHash,
  13833. browserHash: getOptimizedBrowserHash(hash, {}, timestamp),
  13834. optimized: {},
  13835. chunks: {},
  13836. discovered: {},
  13837. depInfoList: []
  13838. };
  13839. }
  13840. function addOptimizedDepInfo(metadata, type, depInfo) {
  13841. metadata[type][depInfo.id] = depInfo;
  13842. metadata.depInfoList.push(depInfo);
  13843. return depInfo;
  13844. }
  13845. let firstLoadCachedDepOptimizationMetadata = true;
  13846. async function loadCachedDepOptimizationMetadata(environment, force = environment.config.optimizeDeps.force ?? false, asCommand = false) {
  13847. const log = asCommand ? environment.logger.info : debug$f;
  13848. if (firstLoadCachedDepOptimizationMetadata) {
  13849. firstLoadCachedDepOptimizationMetadata = false;
  13850. setTimeout(
  13851. () => cleanupDepsCacheStaleDirs(environment.getTopLevelConfig()),
  13852. 0
  13853. );
  13854. }
  13855. const depsCacheDir = getDepsCacheDir(environment);
  13856. if (!force) {
  13857. let cachedMetadata;
  13858. try {
  13859. const cachedMetadataPath = path$b.join(depsCacheDir, METADATA_FILENAME);
  13860. cachedMetadata = parseDepsOptimizerMetadata(
  13861. await fsp.readFile(cachedMetadataPath, "utf-8"),
  13862. depsCacheDir
  13863. );
  13864. } catch {
  13865. }
  13866. if (cachedMetadata) {
  13867. if (cachedMetadata.lockfileHash !== getLockfileHash(environment)) {
  13868. environment.logger.info(
  13869. "Re-optimizing dependencies because lockfile has changed",
  13870. {
  13871. timestamp: true
  13872. }
  13873. );
  13874. } else if (cachedMetadata.configHash !== getConfigHash(environment)) {
  13875. environment.logger.info(
  13876. "Re-optimizing dependencies because vite config has changed",
  13877. {
  13878. timestamp: true
  13879. }
  13880. );
  13881. } else {
  13882. log?.(
  13883. `(${environment.name}) Hash is consistent. Skipping. Use --force to override.`
  13884. );
  13885. return cachedMetadata;
  13886. }
  13887. }
  13888. } else {
  13889. environment.logger.info("Forced re-optimization of dependencies", {
  13890. timestamp: true
  13891. });
  13892. }
  13893. debug$f?.(
  13894. `(${environment.name}) ${colors$1.green(`removing old cache dir ${depsCacheDir}`)}`
  13895. );
  13896. await fsp.rm(depsCacheDir, { recursive: true, force: true });
  13897. }
  13898. function discoverProjectDependencies(environment) {
  13899. const { cancel, result } = scanImports(environment);
  13900. return {
  13901. cancel,
  13902. result: result.then(({ deps, missing }) => {
  13903. const missingIds = Object.keys(missing);
  13904. if (missingIds.length) {
  13905. throw new Error(
  13906. `The following dependencies are imported but could not be resolved:
  13907. ${missingIds.map(
  13908. (id) => `${colors$1.cyan(id)} ${colors$1.white(
  13909. colors$1.dim(`(imported by ${missing[id]})`)
  13910. )}`
  13911. ).join(`
  13912. `)}
  13913. Are they installed?`
  13914. );
  13915. }
  13916. return deps;
  13917. })
  13918. };
  13919. }
  13920. function toDiscoveredDependencies(environment, deps, timestamp) {
  13921. const browserHash = getOptimizedBrowserHash(
  13922. getDepHash(environment).hash,
  13923. deps,
  13924. timestamp
  13925. );
  13926. const discovered = {};
  13927. for (const id in deps) {
  13928. const src = deps[id];
  13929. discovered[id] = {
  13930. id,
  13931. file: getOptimizedDepPath(environment, id),
  13932. src,
  13933. browserHash,
  13934. exportsData: extractExportsData(environment, src)
  13935. };
  13936. }
  13937. return discovered;
  13938. }
  13939. function depsLogString(qualifiedIds) {
  13940. return colors$1.yellow(qualifiedIds.join(`, `));
  13941. }
  13942. function runOptimizeDeps(environment, depsInfo) {
  13943. const optimizerContext = { cancelled: false };
  13944. const depsCacheDir = getDepsCacheDir(environment);
  13945. const processingCacheDir = getProcessingDepsCacheDir(environment);
  13946. fs__default.mkdirSync(processingCacheDir, { recursive: true });
  13947. debug$f?.(colors$1.green(`creating package.json in ${processingCacheDir}`));
  13948. fs__default.writeFileSync(
  13949. path$b.resolve(processingCacheDir, "package.json"),
  13950. `{
  13951. "type": "module"
  13952. }
  13953. `
  13954. );
  13955. const metadata = initDepsOptimizerMetadata(environment);
  13956. metadata.browserHash = getOptimizedBrowserHash(
  13957. metadata.hash,
  13958. depsFromOptimizedDepInfo(depsInfo)
  13959. );
  13960. const qualifiedIds = Object.keys(depsInfo);
  13961. let cleaned = false;
  13962. let committed = false;
  13963. const cleanUp = () => {
  13964. if (!cleaned && !committed) {
  13965. cleaned = true;
  13966. debug$f?.(colors$1.green(`removing cache dir ${processingCacheDir}`));
  13967. try {
  13968. fs__default.rmSync(processingCacheDir, { recursive: true, force: true });
  13969. } catch {
  13970. }
  13971. }
  13972. };
  13973. const successfulResult = {
  13974. metadata,
  13975. cancel: cleanUp,
  13976. commit: async () => {
  13977. if (cleaned) {
  13978. throw new Error(
  13979. "Can not commit a Deps Optimization run as it was cancelled"
  13980. );
  13981. }
  13982. committed = true;
  13983. const dataPath = path$b.join(processingCacheDir, METADATA_FILENAME);
  13984. debug$f?.(
  13985. colors$1.green(`creating ${METADATA_FILENAME} in ${processingCacheDir}`)
  13986. );
  13987. fs__default.writeFileSync(
  13988. dataPath,
  13989. stringifyDepsOptimizerMetadata(metadata, depsCacheDir)
  13990. );
  13991. const temporaryPath = depsCacheDir + getTempSuffix();
  13992. const depsCacheDirPresent = fs__default.existsSync(depsCacheDir);
  13993. if (isWindows$3) {
  13994. if (depsCacheDirPresent) {
  13995. debug$f?.(colors$1.green(`renaming ${depsCacheDir} to ${temporaryPath}`));
  13996. await safeRename(depsCacheDir, temporaryPath);
  13997. }
  13998. debug$f?.(
  13999. colors$1.green(`renaming ${processingCacheDir} to ${depsCacheDir}`)
  14000. );
  14001. await safeRename(processingCacheDir, depsCacheDir);
  14002. } else {
  14003. if (depsCacheDirPresent) {
  14004. debug$f?.(colors$1.green(`renaming ${depsCacheDir} to ${temporaryPath}`));
  14005. fs__default.renameSync(depsCacheDir, temporaryPath);
  14006. }
  14007. debug$f?.(
  14008. colors$1.green(`renaming ${processingCacheDir} to ${depsCacheDir}`)
  14009. );
  14010. fs__default.renameSync(processingCacheDir, depsCacheDir);
  14011. }
  14012. if (depsCacheDirPresent) {
  14013. debug$f?.(colors$1.green(`removing cache temp dir ${temporaryPath}`));
  14014. fsp.rm(temporaryPath, { recursive: true, force: true });
  14015. }
  14016. }
  14017. };
  14018. if (!qualifiedIds.length) {
  14019. return {
  14020. cancel: async () => cleanUp(),
  14021. result: Promise.resolve(successfulResult)
  14022. };
  14023. }
  14024. const cancelledResult = {
  14025. metadata,
  14026. commit: async () => cleanUp(),
  14027. cancel: cleanUp
  14028. };
  14029. const start = performance$1.now();
  14030. const preparedRun = prepareEsbuildOptimizerRun(
  14031. environment,
  14032. depsInfo,
  14033. processingCacheDir,
  14034. optimizerContext
  14035. );
  14036. const runResult = preparedRun.then(({ context, idToExports }) => {
  14037. function disposeContext() {
  14038. return context?.dispose().catch((e) => {
  14039. environment.logger.error("Failed to dispose esbuild context", {
  14040. error: e
  14041. });
  14042. });
  14043. }
  14044. if (!context || optimizerContext.cancelled) {
  14045. disposeContext();
  14046. return cancelledResult;
  14047. }
  14048. return context.rebuild().then((result) => {
  14049. const meta = result.metafile;
  14050. const processingCacheDirOutputPath = path$b.relative(
  14051. process.cwd(),
  14052. processingCacheDir
  14053. );
  14054. for (const id in depsInfo) {
  14055. const output = esbuildOutputFromId(
  14056. meta.outputs,
  14057. id,
  14058. processingCacheDir
  14059. );
  14060. const { exportsData, ...info } = depsInfo[id];
  14061. addOptimizedDepInfo(metadata, "optimized", {
  14062. ...info,
  14063. // We only need to hash the output.imports in to check for stability, but adding the hash
  14064. // and file path gives us a unique hash that may be useful for other things in the future
  14065. fileHash: getHash(
  14066. metadata.hash + depsInfo[id].file + JSON.stringify(output.imports)
  14067. ),
  14068. browserHash: metadata.browserHash,
  14069. // After bundling we have more information and can warn the user about legacy packages
  14070. // that require manual configuration
  14071. needsInterop: needsInterop(
  14072. environment,
  14073. id,
  14074. idToExports[id],
  14075. output
  14076. )
  14077. });
  14078. }
  14079. for (const o of Object.keys(meta.outputs)) {
  14080. if (!jsMapExtensionRE.test(o)) {
  14081. const id = path$b.relative(processingCacheDirOutputPath, o).replace(jsExtensionRE, "");
  14082. const file = getOptimizedDepPath(environment, id);
  14083. if (!findOptimizedDepInfoInRecord(
  14084. metadata.optimized,
  14085. (depInfo) => depInfo.file === file
  14086. )) {
  14087. addOptimizedDepInfo(metadata, "chunks", {
  14088. id,
  14089. file,
  14090. needsInterop: false,
  14091. browserHash: metadata.browserHash
  14092. });
  14093. }
  14094. } else {
  14095. const output = meta.outputs[o];
  14096. if (output.bytes === 93) {
  14097. const jsMapPath = path$b.resolve(o);
  14098. const jsPath = jsMapPath.slice(0, -4);
  14099. if (fs__default.existsSync(jsPath) && fs__default.existsSync(jsMapPath)) {
  14100. const map = JSON.parse(fs__default.readFileSync(jsMapPath, "utf-8"));
  14101. if (map.sources.length === 0) {
  14102. const js = fs__default.readFileSync(jsPath, "utf-8");
  14103. fs__default.writeFileSync(
  14104. jsPath,
  14105. js.slice(0, js.lastIndexOf("//# sourceMappingURL="))
  14106. );
  14107. }
  14108. }
  14109. }
  14110. }
  14111. }
  14112. debug$f?.(
  14113. `Dependencies bundled in ${(performance$1.now() - start).toFixed(2)}ms`
  14114. );
  14115. return successfulResult;
  14116. }).catch((e) => {
  14117. if (e.errors && e.message.includes("The build was canceled")) {
  14118. return cancelledResult;
  14119. }
  14120. throw e;
  14121. }).finally(() => {
  14122. return disposeContext();
  14123. });
  14124. });
  14125. runResult.catch(() => {
  14126. cleanUp();
  14127. });
  14128. return {
  14129. async cancel() {
  14130. optimizerContext.cancelled = true;
  14131. const { context } = await preparedRun;
  14132. await context?.cancel();
  14133. cleanUp();
  14134. },
  14135. result: runResult
  14136. };
  14137. }
  14138. async function prepareEsbuildOptimizerRun(environment, depsInfo, processingCacheDir, optimizerContext) {
  14139. const flatIdDeps = {};
  14140. const idToExports = {};
  14141. const { optimizeDeps: optimizeDeps2 } = environment.config;
  14142. const { plugins: pluginsFromConfig = [], ...esbuildOptions } = optimizeDeps2.esbuildOptions ?? {};
  14143. await Promise.all(
  14144. Object.keys(depsInfo).map(async (id) => {
  14145. const src = depsInfo[id].src;
  14146. const exportsData = await (depsInfo[id].exportsData ?? extractExportsData(environment, src));
  14147. if (exportsData.jsxLoader && !esbuildOptions.loader?.[".js"]) {
  14148. esbuildOptions.loader = {
  14149. ".js": "jsx",
  14150. ...esbuildOptions.loader
  14151. };
  14152. }
  14153. const flatId = flattenId(id);
  14154. flatIdDeps[flatId] = src;
  14155. idToExports[id] = exportsData;
  14156. })
  14157. );
  14158. if (optimizerContext.cancelled) return { context: void 0, idToExports };
  14159. const define = {
  14160. "process.env.NODE_ENV": environment.config.keepProcessEnv ? (
  14161. // define process.env.NODE_ENV even for keepProcessEnv === true
  14162. // as esbuild will replace it automatically when `platform` is `'browser'`
  14163. "process.env.NODE_ENV"
  14164. ) : JSON.stringify(process.env.NODE_ENV || environment.config.mode)
  14165. };
  14166. const platform = optimizeDeps2.esbuildOptions?.platform ?? // We generally don't want to use platform 'neutral', as esbuild has custom handling
  14167. // when the platform is 'node' or 'browser' that can't be emulated by using mainFields
  14168. // and conditions
  14169. (environment.config.consumer === "client" || environment.config.ssr.target === "webworker" ? "browser" : "node");
  14170. const external = [...optimizeDeps2.exclude ?? []];
  14171. const plugins = [...pluginsFromConfig];
  14172. if (external.length) {
  14173. plugins.push(esbuildCjsExternalPlugin(external, platform));
  14174. }
  14175. plugins.push(esbuildDepPlugin(environment, flatIdDeps, external));
  14176. const context = await esbuild.context({
  14177. absWorkingDir: process.cwd(),
  14178. entryPoints: Object.keys(flatIdDeps),
  14179. bundle: true,
  14180. platform,
  14181. define,
  14182. format: "esm",
  14183. // See https://github.com/evanw/esbuild/issues/1921#issuecomment-1152991694
  14184. banner: platform === "node" ? {
  14185. js: `import { createRequire } from 'module';const require = createRequire(import.meta.url);`
  14186. } : void 0,
  14187. target: ESBUILD_MODULES_TARGET,
  14188. external,
  14189. logLevel: "error",
  14190. splitting: true,
  14191. sourcemap: true,
  14192. outdir: processingCacheDir,
  14193. ignoreAnnotations: true,
  14194. metafile: true,
  14195. plugins,
  14196. charset: "utf8",
  14197. ...esbuildOptions,
  14198. supported: {
  14199. ...defaultEsbuildSupported,
  14200. ...esbuildOptions.supported
  14201. }
  14202. });
  14203. return { context, idToExports };
  14204. }
  14205. async function addManuallyIncludedOptimizeDeps(environment, deps) {
  14206. const { logger } = environment;
  14207. const { optimizeDeps: optimizeDeps2 } = environment.config;
  14208. const optimizeDepsInclude = optimizeDeps2.include ?? [];
  14209. if (optimizeDepsInclude.length) {
  14210. const unableToOptimize = (id, msg) => {
  14211. if (optimizeDepsInclude.includes(id)) {
  14212. logger.warn(
  14213. `${msg}: ${colors$1.cyan(id)}, present in ${environment.name} 'optimizeDeps.include'`
  14214. );
  14215. }
  14216. };
  14217. const includes = [...optimizeDepsInclude];
  14218. for (let i = 0; i < includes.length; i++) {
  14219. const id = includes[i];
  14220. if (isDynamicPattern(id)) {
  14221. const globIds = expandGlobIds(id, environment.getTopLevelConfig());
  14222. includes.splice(i, 1, ...globIds);
  14223. i += globIds.length - 1;
  14224. }
  14225. }
  14226. const resolve = createOptimizeDepsIncludeResolver(environment);
  14227. for (const id of includes) {
  14228. const normalizedId = normalizeId(id);
  14229. if (!deps[normalizedId]) {
  14230. const entry = await resolve(id);
  14231. if (entry) {
  14232. if (isOptimizable(entry, optimizeDeps2)) {
  14233. deps[normalizedId] = entry;
  14234. } else {
  14235. unableToOptimize(id, "Cannot optimize dependency");
  14236. }
  14237. } else {
  14238. unableToOptimize(id, "Failed to resolve dependency");
  14239. }
  14240. }
  14241. }
  14242. }
  14243. }
  14244. function depsFromOptimizedDepInfo(depsInfo) {
  14245. const obj = {};
  14246. for (const key in depsInfo) {
  14247. obj[key] = depsInfo[key].src;
  14248. }
  14249. return obj;
  14250. }
  14251. function getOptimizedDepPath(environment, id) {
  14252. return normalizePath$3(
  14253. path$b.resolve(getDepsCacheDir(environment), flattenId(id) + ".js")
  14254. );
  14255. }
  14256. function getDepsCacheSuffix(environment) {
  14257. return environment.name === "client" ? "" : `_${environment.name}`;
  14258. }
  14259. function getDepsCacheDir(environment) {
  14260. return getDepsCacheDirPrefix(environment) + getDepsCacheSuffix(environment);
  14261. }
  14262. function getProcessingDepsCacheDir(environment) {
  14263. return getDepsCacheDirPrefix(environment) + getDepsCacheSuffix(environment) + getTempSuffix();
  14264. }
  14265. function getTempSuffix() {
  14266. return "_temp_" + getHash(
  14267. `${process.pid}:${Date.now().toString()}:${Math.random().toString(16).slice(2)}`
  14268. );
  14269. }
  14270. function getDepsCacheDirPrefix(environment) {
  14271. return normalizePath$3(path$b.resolve(environment.config.cacheDir, "deps"));
  14272. }
  14273. function createIsOptimizedDepFile(environment) {
  14274. const depsCacheDirPrefix = getDepsCacheDirPrefix(environment);
  14275. return (id) => id.startsWith(depsCacheDirPrefix);
  14276. }
  14277. function createIsOptimizedDepUrl(environment) {
  14278. const { root } = environment.config;
  14279. const depsCacheDir = getDepsCacheDirPrefix(environment);
  14280. const depsCacheDirRelative = normalizePath$3(path$b.relative(root, depsCacheDir));
  14281. const depsCacheDirPrefix = depsCacheDirRelative.startsWith("../") ? (
  14282. // if the cache directory is outside root, the url prefix would be something
  14283. // like '/@fs/absolute/path/to/node_modules/.vite'
  14284. `/@fs/${removeLeadingSlash(normalizePath$3(depsCacheDir))}`
  14285. ) : (
  14286. // if the cache directory is inside root, the url prefix would be something
  14287. // like '/node_modules/.vite'
  14288. `/${depsCacheDirRelative}`
  14289. );
  14290. return function isOptimizedDepUrl(url) {
  14291. return url.startsWith(depsCacheDirPrefix);
  14292. };
  14293. }
  14294. function parseDepsOptimizerMetadata(jsonMetadata, depsCacheDir) {
  14295. const { hash, lockfileHash, configHash, browserHash, optimized, chunks } = JSON.parse(jsonMetadata, (key, value) => {
  14296. if (key === "file" || key === "src") {
  14297. return normalizePath$3(path$b.resolve(depsCacheDir, value));
  14298. }
  14299. return value;
  14300. });
  14301. if (!chunks || Object.values(optimized).some((depInfo) => !depInfo.fileHash)) {
  14302. return;
  14303. }
  14304. const metadata = {
  14305. hash,
  14306. lockfileHash,
  14307. configHash,
  14308. browserHash,
  14309. optimized: {},
  14310. discovered: {},
  14311. chunks: {},
  14312. depInfoList: []
  14313. };
  14314. for (const id of Object.keys(optimized)) {
  14315. addOptimizedDepInfo(metadata, "optimized", {
  14316. ...optimized[id],
  14317. id,
  14318. browserHash
  14319. });
  14320. }
  14321. for (const id of Object.keys(chunks)) {
  14322. addOptimizedDepInfo(metadata, "chunks", {
  14323. ...chunks[id],
  14324. id,
  14325. browserHash,
  14326. needsInterop: false
  14327. });
  14328. }
  14329. return metadata;
  14330. }
  14331. function stringifyDepsOptimizerMetadata(metadata, depsCacheDir) {
  14332. const { hash, configHash, lockfileHash, browserHash, optimized, chunks } = metadata;
  14333. return JSON.stringify(
  14334. {
  14335. hash,
  14336. configHash,
  14337. lockfileHash,
  14338. browserHash,
  14339. optimized: Object.fromEntries(
  14340. Object.values(optimized).map(
  14341. ({ id, src, file, fileHash, needsInterop: needsInterop2 }) => [
  14342. id,
  14343. {
  14344. src,
  14345. file,
  14346. fileHash,
  14347. needsInterop: needsInterop2
  14348. }
  14349. ]
  14350. )
  14351. ),
  14352. chunks: Object.fromEntries(
  14353. Object.values(chunks).map(({ id, file }) => [id, { file }])
  14354. )
  14355. },
  14356. (key, value) => {
  14357. if (key === "file" || key === "src") {
  14358. return normalizePath$3(path$b.relative(depsCacheDir, value));
  14359. }
  14360. return value;
  14361. },
  14362. 2
  14363. );
  14364. }
  14365. function esbuildOutputFromId(outputs, id, cacheDirOutputPath) {
  14366. const cwd = process.cwd();
  14367. const flatId = flattenId(id) + ".js";
  14368. const normalizedOutputPath = normalizePath$3(
  14369. path$b.relative(cwd, path$b.join(cacheDirOutputPath, flatId))
  14370. );
  14371. const output = outputs[normalizedOutputPath];
  14372. if (output) {
  14373. return output;
  14374. }
  14375. for (const [key, value] of Object.entries(outputs)) {
  14376. if (normalizePath$3(path$b.relative(cwd, key)) === normalizedOutputPath) {
  14377. return value;
  14378. }
  14379. }
  14380. }
  14381. async function extractExportsData(environment, filePath) {
  14382. await init;
  14383. const { optimizeDeps: optimizeDeps2 } = environment.config;
  14384. const esbuildOptions = optimizeDeps2.esbuildOptions ?? {};
  14385. if (optimizeDeps2.extensions?.some((ext) => filePath.endsWith(ext))) {
  14386. const result = await build$3({
  14387. ...esbuildOptions,
  14388. entryPoints: [filePath],
  14389. write: false,
  14390. format: "esm"
  14391. });
  14392. const [, exports2, , hasModuleSyntax2] = parse$d(result.outputFiles[0].text);
  14393. return {
  14394. hasModuleSyntax: hasModuleSyntax2,
  14395. exports: exports2.map((e) => e.n)
  14396. };
  14397. }
  14398. let parseResult;
  14399. let usedJsxLoader = false;
  14400. const entryContent = await fsp.readFile(filePath, "utf-8");
  14401. try {
  14402. parseResult = parse$d(entryContent);
  14403. } catch {
  14404. const loader = esbuildOptions.loader?.[path$b.extname(filePath)] || "jsx";
  14405. debug$f?.(
  14406. `Unable to parse: ${filePath}.
  14407. Trying again with a ${loader} transform.`
  14408. );
  14409. const transformed = await transformWithEsbuild(
  14410. entryContent,
  14411. filePath,
  14412. { loader },
  14413. void 0,
  14414. environment.config
  14415. );
  14416. parseResult = parse$d(transformed.code);
  14417. usedJsxLoader = true;
  14418. }
  14419. const [, exports, , hasModuleSyntax] = parseResult;
  14420. const exportsData = {
  14421. hasModuleSyntax,
  14422. exports: exports.map((e) => e.n),
  14423. jsxLoader: usedJsxLoader
  14424. };
  14425. return exportsData;
  14426. }
  14427. function needsInterop(environment, id, exportsData, output) {
  14428. if (environment.config.optimizeDeps.needsInterop?.includes(id)) {
  14429. return true;
  14430. }
  14431. const { hasModuleSyntax, exports } = exportsData;
  14432. if (!hasModuleSyntax) {
  14433. return true;
  14434. }
  14435. if (output) {
  14436. const generatedExports = output.exports;
  14437. if (isSingleDefaultExport(generatedExports) && !isSingleDefaultExport(exports)) {
  14438. return true;
  14439. }
  14440. }
  14441. return false;
  14442. }
  14443. function isSingleDefaultExport(exports) {
  14444. return exports.length === 1 && exports[0] === "default";
  14445. }
  14446. const lockfileFormats = [
  14447. {
  14448. path: "node_modules/.package-lock.json",
  14449. checkPatchesDir: "patches",
  14450. manager: "npm"
  14451. },
  14452. {
  14453. // Yarn non-PnP
  14454. path: "node_modules/.yarn-state.yml",
  14455. checkPatchesDir: false,
  14456. manager: "yarn"
  14457. },
  14458. {
  14459. // Yarn v3+ PnP
  14460. path: ".pnp.cjs",
  14461. checkPatchesDir: ".yarn/patches",
  14462. manager: "yarn"
  14463. },
  14464. {
  14465. // Yarn v2 PnP
  14466. path: ".pnp.js",
  14467. checkPatchesDir: ".yarn/patches",
  14468. manager: "yarn"
  14469. },
  14470. {
  14471. // yarn 1
  14472. path: "node_modules/.yarn-integrity",
  14473. checkPatchesDir: "patches",
  14474. manager: "yarn"
  14475. },
  14476. {
  14477. path: "node_modules/.pnpm/lock.yaml",
  14478. // Included in lockfile
  14479. checkPatchesDir: false,
  14480. manager: "pnpm"
  14481. },
  14482. {
  14483. path: "bun.lock",
  14484. checkPatchesDir: "patches",
  14485. manager: "bun"
  14486. },
  14487. {
  14488. path: "bun.lockb",
  14489. checkPatchesDir: "patches",
  14490. manager: "bun"
  14491. }
  14492. ].sort((_, { manager }) => {
  14493. return process.env.npm_config_user_agent?.startsWith(manager) ? 1 : -1;
  14494. });
  14495. const lockfilePaths = lockfileFormats.map((l) => l.path);
  14496. function getConfigHash(environment) {
  14497. const { config } = environment;
  14498. const { optimizeDeps: optimizeDeps2 } = config;
  14499. const content = JSON.stringify(
  14500. {
  14501. define: !config.keepProcessEnv ? process.env.NODE_ENV || config.mode : null,
  14502. root: config.root,
  14503. resolve: config.resolve,
  14504. assetsInclude: config.assetsInclude,
  14505. plugins: config.plugins.map((p) => p.name),
  14506. optimizeDeps: {
  14507. include: optimizeDeps2.include ? unique(optimizeDeps2.include).sort() : void 0,
  14508. exclude: optimizeDeps2.exclude ? unique(optimizeDeps2.exclude).sort() : void 0,
  14509. esbuildOptions: {
  14510. ...optimizeDeps2.esbuildOptions,
  14511. plugins: optimizeDeps2.esbuildOptions?.plugins?.map((p) => p.name)
  14512. }
  14513. }
  14514. },
  14515. (_, value) => {
  14516. if (typeof value === "function" || value instanceof RegExp) {
  14517. return value.toString();
  14518. }
  14519. return value;
  14520. }
  14521. );
  14522. return getHash(content);
  14523. }
  14524. function getLockfileHash(environment) {
  14525. const lockfilePath = lookupFile(environment.config.root, lockfilePaths);
  14526. let content = lockfilePath ? fs__default.readFileSync(lockfilePath, "utf-8") : "";
  14527. if (lockfilePath) {
  14528. const normalizedLockfilePath = lockfilePath.replaceAll("\\", "/");
  14529. const lockfileFormat = lockfileFormats.find(
  14530. (f) => normalizedLockfilePath.endsWith(f.path)
  14531. );
  14532. if (lockfileFormat.checkPatchesDir) {
  14533. const baseDir = lockfilePath.slice(0, -lockfileFormat.path.length);
  14534. const fullPath = path$b.join(
  14535. baseDir,
  14536. lockfileFormat.checkPatchesDir
  14537. );
  14538. const stat = tryStatSync(fullPath);
  14539. if (stat?.isDirectory()) {
  14540. content += stat.mtimeMs.toString();
  14541. }
  14542. }
  14543. }
  14544. return getHash(content);
  14545. }
  14546. function getDepHash(environment) {
  14547. const lockfileHash = getLockfileHash(environment);
  14548. const configHash = getConfigHash(environment);
  14549. const hash = getHash(lockfileHash + configHash);
  14550. return {
  14551. hash,
  14552. lockfileHash,
  14553. configHash
  14554. };
  14555. }
  14556. function getOptimizedBrowserHash(hash, deps, timestamp = "") {
  14557. return getHash(hash + JSON.stringify(deps) + timestamp);
  14558. }
  14559. function optimizedDepInfoFromId(metadata, id) {
  14560. return metadata.optimized[id] || metadata.discovered[id] || metadata.chunks[id];
  14561. }
  14562. function optimizedDepInfoFromFile(metadata, file) {
  14563. return metadata.depInfoList.find((depInfo) => depInfo.file === file);
  14564. }
  14565. function findOptimizedDepInfoInRecord(dependenciesInfo, callbackFn) {
  14566. for (const o of Object.keys(dependenciesInfo)) {
  14567. const info = dependenciesInfo[o];
  14568. if (callbackFn(info, o)) {
  14569. return info;
  14570. }
  14571. }
  14572. }
  14573. async function optimizedDepNeedsInterop(environment, metadata, file) {
  14574. const depInfo = optimizedDepInfoFromFile(metadata, file);
  14575. if (depInfo?.src && depInfo.needsInterop === void 0) {
  14576. depInfo.exportsData ??= extractExportsData(environment, depInfo.src);
  14577. depInfo.needsInterop = needsInterop(
  14578. environment,
  14579. depInfo.id,
  14580. await depInfo.exportsData
  14581. );
  14582. }
  14583. return depInfo?.needsInterop;
  14584. }
  14585. const MAX_TEMP_DIR_AGE_MS = 24 * 60 * 60 * 1e3;
  14586. async function cleanupDepsCacheStaleDirs(config) {
  14587. try {
  14588. const cacheDir = path$b.resolve(config.cacheDir);
  14589. if (fs__default.existsSync(cacheDir)) {
  14590. const dirents = await fsp.readdir(cacheDir, { withFileTypes: true });
  14591. for (const dirent of dirents) {
  14592. if (dirent.isDirectory() && dirent.name.includes("_temp_")) {
  14593. const tempDirPath = path$b.resolve(config.cacheDir, dirent.name);
  14594. const stats = await fsp.stat(tempDirPath).catch(() => null);
  14595. if (stats?.mtime && Date.now() - stats.mtime.getTime() > MAX_TEMP_DIR_AGE_MS) {
  14596. debug$f?.(`removing stale cache temp dir ${tempDirPath}`);
  14597. await fsp.rm(tempDirPath, { recursive: true, force: true });
  14598. }
  14599. }
  14600. }
  14601. }
  14602. } catch (err) {
  14603. config.logger.error(err);
  14604. }
  14605. }
  14606. const GRACEFUL_RENAME_TIMEOUT = 5e3;
  14607. const safeRename = promisify$4(function gracefulRename(from, to, cb) {
  14608. const start = Date.now();
  14609. let backoff = 0;
  14610. fs__default.rename(from, to, function CB(er) {
  14611. if (er && (er.code === "EACCES" || er.code === "EPERM") && Date.now() - start < GRACEFUL_RENAME_TIMEOUT) {
  14612. setTimeout(function() {
  14613. fs__default.stat(to, function(stater, _st) {
  14614. if (stater && stater.code === "ENOENT") fs__default.rename(from, to, CB);
  14615. else CB(er);
  14616. });
  14617. }, backoff);
  14618. if (backoff < 100) backoff += 10;
  14619. return;
  14620. }
  14621. cb(er);
  14622. });
  14623. });
  14624. var index$1 = {
  14625. __proto__: null,
  14626. addManuallyIncludedOptimizeDeps: addManuallyIncludedOptimizeDeps,
  14627. addOptimizedDepInfo: addOptimizedDepInfo,
  14628. cleanupDepsCacheStaleDirs: cleanupDepsCacheStaleDirs,
  14629. createIsOptimizedDepFile: createIsOptimizedDepFile,
  14630. createIsOptimizedDepUrl: createIsOptimizedDepUrl,
  14631. depsFromOptimizedDepInfo: depsFromOptimizedDepInfo,
  14632. depsLogString: depsLogString,
  14633. discoverProjectDependencies: discoverProjectDependencies,
  14634. extractExportsData: extractExportsData,
  14635. getDepsCacheDir: getDepsCacheDir,
  14636. getOptimizedDepPath: getOptimizedDepPath,
  14637. initDepsOptimizerMetadata: initDepsOptimizerMetadata,
  14638. isDepOptimizationDisabled: isDepOptimizationDisabled,
  14639. loadCachedDepOptimizationMetadata: loadCachedDepOptimizationMetadata,
  14640. optimizeDeps: optimizeDeps,
  14641. optimizeExplicitEnvironmentDeps: optimizeExplicitEnvironmentDeps,
  14642. optimizedDepInfoFromFile: optimizedDepInfoFromFile,
  14643. optimizedDepInfoFromId: optimizedDepInfoFromId,
  14644. optimizedDepNeedsInterop: optimizedDepNeedsInterop,
  14645. runOptimizeDeps: runOptimizeDeps,
  14646. toDiscoveredDependencies: toDiscoveredDependencies
  14647. };
  14648. const debug$e = createDebugger("vite:external");
  14649. const isExternalCache = /* @__PURE__ */ new WeakMap();
  14650. function shouldExternalize(environment, id, importer) {
  14651. let isExternal = isExternalCache.get(environment);
  14652. if (!isExternal) {
  14653. isExternal = createIsExternal(environment);
  14654. isExternalCache.set(environment, isExternal);
  14655. }
  14656. return isExternal(id, importer);
  14657. }
  14658. function createIsConfiguredAsExternal(environment) {
  14659. const { config } = environment;
  14660. const { root, resolve } = config;
  14661. const { external, noExternal } = resolve;
  14662. const noExternalFilter = typeof noExternal !== "boolean" && !(Array.isArray(noExternal) && noExternal.length === 0) && createFilter$1(void 0, noExternal, { resolve: false });
  14663. const targetConditions = resolve.externalConditions;
  14664. const resolveOptions = {
  14665. ...resolve,
  14666. root,
  14667. isProduction: false,
  14668. isBuild: true,
  14669. conditions: targetConditions
  14670. };
  14671. const isExternalizable = (id, importer, configuredAsExternal) => {
  14672. if (!bareImportRE.test(id) || id.includes("\0")) {
  14673. return false;
  14674. }
  14675. try {
  14676. const resolved = tryNodeResolve(
  14677. id,
  14678. // Skip passing importer in build to avoid externalizing non-hoisted dependencies
  14679. // unresolvable from root (which would be unresolvable from output bundles also)
  14680. config.command === "build" ? void 0 : importer,
  14681. resolveOptions,
  14682. void 0,
  14683. false
  14684. );
  14685. if (!resolved) {
  14686. return false;
  14687. }
  14688. if (!configuredAsExternal && !isInNodeModules$1(resolved.id)) {
  14689. return false;
  14690. }
  14691. return canExternalizeFile(resolved.id);
  14692. } catch {
  14693. debug$e?.(
  14694. `Failed to node resolve "${id}". Skipping externalizing it by default.`
  14695. );
  14696. return false;
  14697. }
  14698. };
  14699. return (id, importer) => {
  14700. if (
  14701. // If this id is defined as external, force it as external
  14702. // Note that individual package entries are allowed in `external`
  14703. external !== true && external.includes(id)
  14704. ) {
  14705. return true;
  14706. }
  14707. const pkgName = getNpmPackageName(id);
  14708. if (!pkgName) {
  14709. return isExternalizable(id, importer, false);
  14710. }
  14711. if (
  14712. // A package name in ssr.external externalizes every
  14713. // externalizable package entry
  14714. external !== true && external.includes(pkgName)
  14715. ) {
  14716. return isExternalizable(id, importer, true);
  14717. }
  14718. if (typeof noExternal === "boolean") {
  14719. return !noExternal;
  14720. }
  14721. if (noExternalFilter && !noExternalFilter(pkgName)) {
  14722. return false;
  14723. }
  14724. return isExternalizable(id, importer, external === true);
  14725. };
  14726. }
  14727. function createIsExternal(environment) {
  14728. const processedIds = /* @__PURE__ */ new Map();
  14729. const isConfiguredAsExternal = createIsConfiguredAsExternal(environment);
  14730. return (id, importer) => {
  14731. if (processedIds.has(id)) {
  14732. return processedIds.get(id);
  14733. }
  14734. let isExternal = false;
  14735. if (id[0] !== "." && !path$b.isAbsolute(id)) {
  14736. isExternal = isBuiltin(environment.config.resolve.builtins, id) || isConfiguredAsExternal(id, importer);
  14737. }
  14738. processedIds.set(id, isExternal);
  14739. return isExternal;
  14740. };
  14741. }
  14742. function canExternalizeFile(filePath) {
  14743. const ext = path$b.extname(filePath);
  14744. return !ext || ext === ".js" || ext === ".mjs" || ext === ".cjs";
  14745. }
  14746. const normalizedClientEntry$1 = normalizePath$3(CLIENT_ENTRY);
  14747. const normalizedEnvEntry$1 = normalizePath$3(ENV_ENTRY);
  14748. const ERR_RESOLVE_PACKAGE_ENTRY_FAIL = "ERR_RESOLVE_PACKAGE_ENTRY_FAIL";
  14749. const browserExternalId = "__vite-browser-external";
  14750. const optionalPeerDepId = "__vite-optional-peer-dep";
  14751. const subpathImportsPrefix = "#";
  14752. const startsWithWordCharRE = /^\w/;
  14753. const debug$d = createDebugger("vite:resolve-details", {
  14754. onlyWhenFocused: true
  14755. });
  14756. function resolvePlugin(resolveOptions) {
  14757. const { root, isProduction, asSrc, preferRelative = false } = resolveOptions;
  14758. const rootInRoot = tryStatSync(path$b.join(root, root))?.isDirectory() ?? false;
  14759. return {
  14760. name: "vite:resolve",
  14761. async resolveId(id, importer, resolveOpts) {
  14762. if (id[0] === "\0" || id.startsWith("virtual:") || // When injected directly in html/client code
  14763. id.startsWith("/virtual:")) {
  14764. return;
  14765. }
  14766. const depsOptimizer = resolveOptions.optimizeDeps && this.environment.mode === "dev" ? this.environment.depsOptimizer : void 0;
  14767. if (id.startsWith(browserExternalId)) {
  14768. return id;
  14769. }
  14770. const isRequire = resolveOpts.custom?.["node-resolve"]?.isRequire ?? false;
  14771. const currentEnvironmentOptions = this.environment.config;
  14772. const options = {
  14773. isRequire,
  14774. ...currentEnvironmentOptions.resolve,
  14775. ...resolveOptions,
  14776. // plugin options + resolve options overrides
  14777. scan: resolveOpts.scan ?? resolveOptions.scan
  14778. };
  14779. const resolvedImports = resolveSubpathImports(id, importer, options);
  14780. if (resolvedImports) {
  14781. id = resolvedImports;
  14782. if (resolveOpts.custom?.["vite:import-glob"]?.isSubImportsPattern) {
  14783. return normalizePath$3(path$b.join(root, id));
  14784. }
  14785. }
  14786. let res;
  14787. if (asSrc && depsOptimizer?.isOptimizedDepUrl(id)) {
  14788. const optimizedPath = id.startsWith(FS_PREFIX) ? fsPathFromId(id) : normalizePath$3(path$b.resolve(root, id.slice(1)));
  14789. return optimizedPath;
  14790. }
  14791. if (asSrc && id.startsWith(FS_PREFIX)) {
  14792. res = fsPathFromId(id);
  14793. debug$d?.(`[@fs] ${colors$1.cyan(id)} -> ${colors$1.dim(res)}`);
  14794. return ensureVersionQuery(res, id, options, depsOptimizer);
  14795. }
  14796. if (asSrc && id[0] === "/" && (rootInRoot || !id.startsWith(withTrailingSlash(root)))) {
  14797. const fsPath = path$b.resolve(root, id.slice(1));
  14798. if (res = tryFsResolve(fsPath, options)) {
  14799. debug$d?.(`[url] ${colors$1.cyan(id)} -> ${colors$1.dim(res)}`);
  14800. return ensureVersionQuery(res, id, options, depsOptimizer);
  14801. }
  14802. }
  14803. if (id[0] === "." || (preferRelative || importer?.endsWith(".html")) && startsWithWordCharRE.test(id)) {
  14804. const basedir = importer ? path$b.dirname(importer) : process.cwd();
  14805. const fsPath = path$b.resolve(basedir, id);
  14806. const normalizedFsPath = normalizePath$3(fsPath);
  14807. if (depsOptimizer?.isOptimizedDepFile(normalizedFsPath)) {
  14808. if (!options.isBuild && !DEP_VERSION_RE.test(normalizedFsPath)) {
  14809. const browserHash = optimizedDepInfoFromFile(
  14810. depsOptimizer.metadata,
  14811. normalizedFsPath
  14812. )?.browserHash;
  14813. if (browserHash) {
  14814. return injectQuery(normalizedFsPath, `v=${browserHash}`);
  14815. }
  14816. }
  14817. return normalizedFsPath;
  14818. }
  14819. if (options.mainFields.includes("browser") && (res = tryResolveBrowserMapping(fsPath, importer, options, true))) {
  14820. return res;
  14821. }
  14822. if (res = tryFsResolve(fsPath, options)) {
  14823. res = ensureVersionQuery(res, id, options, depsOptimizer);
  14824. debug$d?.(`[relative] ${colors$1.cyan(id)} -> ${colors$1.dim(res)}`);
  14825. if (!options.idOnly && !options.scan && options.isBuild) {
  14826. const resPkg = findNearestPackageData(
  14827. path$b.dirname(res),
  14828. options.packageCache
  14829. );
  14830. if (resPkg) {
  14831. return {
  14832. id: res,
  14833. moduleSideEffects: resPkg.hasSideEffects(res)
  14834. };
  14835. }
  14836. }
  14837. return res;
  14838. }
  14839. }
  14840. if (id.startsWith("file://")) {
  14841. const { file, postfix } = splitFileAndPostfix(id);
  14842. id = fileURLToPath$1(file) + postfix;
  14843. }
  14844. if (isWindows$3 && id[0] === "/") {
  14845. const basedir = importer ? path$b.dirname(importer) : process.cwd();
  14846. const fsPath = path$b.resolve(basedir, id);
  14847. if (res = tryFsResolve(fsPath, options)) {
  14848. debug$d?.(`[drive-relative] ${colors$1.cyan(id)} -> ${colors$1.dim(res)}`);
  14849. return ensureVersionQuery(res, id, options, depsOptimizer);
  14850. }
  14851. }
  14852. if (isNonDriveRelativeAbsolutePath(id) && (res = tryFsResolve(id, options))) {
  14853. debug$d?.(`[fs] ${colors$1.cyan(id)} -> ${colors$1.dim(res)}`);
  14854. return ensureVersionQuery(res, id, options, depsOptimizer);
  14855. }
  14856. if (isExternalUrl(id)) {
  14857. return options.idOnly ? id : { id, external: true };
  14858. }
  14859. if (isDataUrl(id)) {
  14860. return null;
  14861. }
  14862. if (bareImportRE.test(id)) {
  14863. const external = options.externalize && options.isBuild && currentEnvironmentOptions.consumer === "server" && shouldExternalize(this.environment, id, importer);
  14864. if (!external && asSrc && depsOptimizer && !options.scan && (res = await tryOptimizedResolve(
  14865. depsOptimizer,
  14866. id,
  14867. importer,
  14868. options.preserveSymlinks,
  14869. options.packageCache
  14870. ))) {
  14871. return res;
  14872. }
  14873. if (options.mainFields.includes("browser") && (res = tryResolveBrowserMapping(
  14874. id,
  14875. importer,
  14876. options,
  14877. false,
  14878. external
  14879. ))) {
  14880. return res;
  14881. }
  14882. if (res = tryNodeResolve(id, importer, options, depsOptimizer, external)) {
  14883. return res;
  14884. }
  14885. if (currentEnvironmentOptions.consumer === "server" && isBuiltin(options.builtins, id)) {
  14886. return options.idOnly ? id : { id, external: true, moduleSideEffects: false };
  14887. } else if (currentEnvironmentOptions.consumer === "server" && isNodeLikeBuiltin(id)) {
  14888. if (!(options.external === true || options.external.includes(id))) {
  14889. let message = `Automatically externalized node built-in module "${id}"`;
  14890. if (importer) {
  14891. message += ` imported from "${path$b.relative(
  14892. process.cwd(),
  14893. importer
  14894. )}"`;
  14895. }
  14896. message += `. Consider adding it to environments.${this.environment.name}.external if it is intended.`;
  14897. this.warn(message);
  14898. }
  14899. return options.idOnly ? id : { id, external: true, moduleSideEffects: false };
  14900. } else if (currentEnvironmentOptions.consumer === "client" && isNodeLikeBuiltin(id)) {
  14901. if (options.noExternal === true && // if both noExternal and external are true, noExternal will take the higher priority and bundle it.
  14902. // only if the id is explicitly listed in external, we will externalize it and skip this error.
  14903. (options.external === true || !options.external.includes(id))) {
  14904. let message = `Cannot bundle built-in module "${id}"`;
  14905. if (importer) {
  14906. message += ` imported from "${path$b.relative(
  14907. process.cwd(),
  14908. importer
  14909. )}"`;
  14910. }
  14911. message += `. Consider disabling environments.${this.environment.name}.noExternal or remove the built-in dependency.`;
  14912. this.error(message);
  14913. }
  14914. if (!asSrc) {
  14915. debug$d?.(
  14916. `externalized node built-in "${id}" to empty module. (imported by: ${colors$1.white(colors$1.dim(importer))})`
  14917. );
  14918. } else if (isProduction) {
  14919. this.warn(
  14920. `Module "${id}" has been externalized for browser compatibility, imported by "${importer}". See https://vite.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.`
  14921. );
  14922. }
  14923. return isProduction ? browserExternalId : `${browserExternalId}:${id}`;
  14924. }
  14925. }
  14926. debug$d?.(`[fallthrough] ${colors$1.dim(id)}`);
  14927. },
  14928. load: {
  14929. handler(id) {
  14930. if (id.startsWith(browserExternalId)) {
  14931. if (isProduction) {
  14932. return `export default {}`;
  14933. } else {
  14934. id = id.slice(browserExternalId.length + 1);
  14935. return ` export default new Proxy({}, {
  14936. get(_, key) {
  14937. throw new Error(\`Module "${id}" has been externalized for browser compatibility. Cannot access "${id}.\${key}" in client code. See https://vite.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.\`)
  14938. }
  14939. })`;
  14940. }
  14941. }
  14942. if (id.startsWith(optionalPeerDepId)) {
  14943. if (isProduction) {
  14944. return `export default {}`;
  14945. } else {
  14946. const [, peerDep, parentDep] = id.split(":");
  14947. return `throw new Error(\`Could not resolve "${peerDep}" imported by "${parentDep}". Is it installed?\`)`;
  14948. }
  14949. }
  14950. }
  14951. }
  14952. };
  14953. }
  14954. function resolveSubpathImports(id, importer, options) {
  14955. if (!importer || !id.startsWith(subpathImportsPrefix)) return;
  14956. const basedir = path$b.dirname(importer);
  14957. const pkgData = findNearestPackageData(basedir, options.packageCache);
  14958. if (!pkgData) return;
  14959. let { file: idWithoutPostfix, postfix } = splitFileAndPostfix(id.slice(1));
  14960. idWithoutPostfix = "#" + idWithoutPostfix;
  14961. let importsPath = resolveExportsOrImports(
  14962. pkgData.data,
  14963. idWithoutPostfix,
  14964. options,
  14965. "imports"
  14966. );
  14967. if (importsPath?.[0] === ".") {
  14968. importsPath = path$b.relative(basedir, path$b.join(pkgData.dir, importsPath));
  14969. if (importsPath[0] !== ".") {
  14970. importsPath = `./${importsPath}`;
  14971. }
  14972. }
  14973. return importsPath + postfix;
  14974. }
  14975. function ensureVersionQuery(resolved, id, options, depsOptimizer) {
  14976. if (!options.isBuild && !options.scan && depsOptimizer && !(resolved === normalizedClientEntry$1 || resolved === normalizedEnvEntry$1)) {
  14977. const isNodeModule = isInNodeModules$1(id) || isInNodeModules$1(resolved);
  14978. if (isNodeModule && !DEP_VERSION_RE.test(resolved)) {
  14979. const versionHash = depsOptimizer.metadata.browserHash;
  14980. if (versionHash && isOptimizable(resolved, depsOptimizer.options)) {
  14981. resolved = injectQuery(resolved, `v=${versionHash}`);
  14982. }
  14983. }
  14984. }
  14985. return resolved;
  14986. }
  14987. function tryFsResolve(fsPath, options, tryIndex = true, skipPackageJson = false) {
  14988. const hashIndex = fsPath.indexOf("#");
  14989. if (hashIndex >= 0 && isInNodeModules$1(fsPath)) {
  14990. const queryIndex = fsPath.indexOf("?");
  14991. if (queryIndex < 0 || queryIndex > hashIndex) {
  14992. const file2 = queryIndex > hashIndex ? fsPath.slice(0, queryIndex) : fsPath;
  14993. const res2 = tryCleanFsResolve(file2, options, tryIndex, skipPackageJson);
  14994. if (res2) return res2 + fsPath.slice(file2.length);
  14995. }
  14996. }
  14997. const { file, postfix } = splitFileAndPostfix(fsPath);
  14998. const res = tryCleanFsResolve(file, options, tryIndex, skipPackageJson);
  14999. if (res) return res + postfix;
  15000. }
  15001. const knownTsOutputRE = /\.(?:js|mjs|cjs|jsx)$/;
  15002. const isPossibleTsOutput = (url) => knownTsOutputRE.test(url);
  15003. function tryCleanFsResolve(file, options, tryIndex = true, skipPackageJson = false) {
  15004. const { tryPrefix, extensions, preserveSymlinks } = options;
  15005. const fileResult = tryResolveRealFileOrType(file, options.preserveSymlinks);
  15006. if (fileResult?.path) return fileResult.path;
  15007. let res;
  15008. const possibleJsToTs = isPossibleTsOutput(file);
  15009. if (possibleJsToTs || options.extensions.length || tryPrefix) {
  15010. const dirPath = path$b.dirname(file);
  15011. if (isDirectory(dirPath)) {
  15012. if (possibleJsToTs) {
  15013. const fileExt = path$b.extname(file);
  15014. const fileName = file.slice(0, -fileExt.length);
  15015. if (res = tryResolveRealFile(
  15016. fileName + fileExt.replace("js", "ts"),
  15017. preserveSymlinks
  15018. ))
  15019. return res;
  15020. if (fileExt === ".js" && (res = tryResolveRealFile(fileName + ".tsx", preserveSymlinks)))
  15021. return res;
  15022. }
  15023. if (res = tryResolveRealFileWithExtensions(
  15024. file,
  15025. extensions,
  15026. preserveSymlinks
  15027. ))
  15028. return res;
  15029. if (tryPrefix) {
  15030. const prefixed = `${dirPath}/${options.tryPrefix}${path$b.basename(file)}`;
  15031. if (res = tryResolveRealFile(prefixed, preserveSymlinks)) return res;
  15032. if (res = tryResolveRealFileWithExtensions(
  15033. prefixed,
  15034. extensions,
  15035. preserveSymlinks
  15036. ))
  15037. return res;
  15038. }
  15039. }
  15040. }
  15041. if (tryIndex && fileResult?.type === "directory") {
  15042. const dirPath = file;
  15043. if (!skipPackageJson) {
  15044. let pkgPath = `${dirPath}/package.json`;
  15045. try {
  15046. if (fs__default.existsSync(pkgPath)) {
  15047. if (!options.preserveSymlinks) {
  15048. pkgPath = safeRealpathSync(pkgPath);
  15049. }
  15050. const pkg = loadPackageData(pkgPath);
  15051. return resolvePackageEntry(dirPath, pkg, options);
  15052. }
  15053. } catch (e) {
  15054. if (e.code !== ERR_RESOLVE_PACKAGE_ENTRY_FAIL && e.code !== "ENOENT")
  15055. throw e;
  15056. }
  15057. }
  15058. if (res = tryResolveRealFileWithExtensions(
  15059. `${dirPath}/index`,
  15060. extensions,
  15061. preserveSymlinks
  15062. ))
  15063. return res;
  15064. if (tryPrefix) {
  15065. if (res = tryResolveRealFileWithExtensions(
  15066. `${dirPath}/${options.tryPrefix}index`,
  15067. extensions,
  15068. preserveSymlinks
  15069. ))
  15070. return res;
  15071. }
  15072. }
  15073. }
  15074. function tryNodeResolve(id, importer, options, depsOptimizer, externalize) {
  15075. const { root, dedupe, isBuild, preserveSymlinks, packageCache } = options;
  15076. const deepMatch = deepImportRE.exec(id);
  15077. const pkgId = deepMatch ? deepMatch[1] || deepMatch[2] : cleanUrl(id);
  15078. let basedir;
  15079. if (dedupe.includes(pkgId)) {
  15080. basedir = root;
  15081. } else if (importer && path$b.isAbsolute(importer) && // css processing appends `*` for importer
  15082. (importer.endsWith("*") || fs__default.existsSync(cleanUrl(importer)))) {
  15083. basedir = path$b.dirname(importer);
  15084. } else {
  15085. basedir = root;
  15086. }
  15087. const isModuleBuiltin = (id2) => isBuiltin(options.builtins, id2);
  15088. let selfPkg = null;
  15089. if (!isModuleBuiltin(id) && !id.includes("\0") && bareImportRE.test(id)) {
  15090. const selfPackageData = findNearestPackageData(basedir, packageCache);
  15091. selfPkg = selfPackageData?.data.exports && selfPackageData.data.name === pkgId ? selfPackageData : null;
  15092. }
  15093. const pkg = selfPkg || resolvePackageData(pkgId, basedir, preserveSymlinks, packageCache);
  15094. if (!pkg) {
  15095. if (basedir !== root && // root has no peer dep
  15096. !isModuleBuiltin(id) && !id.includes("\0") && bareImportRE.test(id)) {
  15097. const mainPkg = findNearestMainPackageData(basedir, packageCache)?.data;
  15098. if (mainPkg) {
  15099. const pkgName = getNpmPackageName(id);
  15100. if (pkgName != null && mainPkg.peerDependencies?.[pkgName] && mainPkg.peerDependenciesMeta?.[pkgName]?.optional) {
  15101. return {
  15102. id: `${optionalPeerDepId}:${id}:${mainPkg.name}`
  15103. };
  15104. }
  15105. }
  15106. }
  15107. return;
  15108. }
  15109. const resolveId = deepMatch ? resolveDeepImport : resolvePackageEntry;
  15110. const unresolvedId = deepMatch ? "." + id.slice(pkgId.length) : id;
  15111. let resolved = resolveId(unresolvedId, pkg, options);
  15112. if (!resolved) {
  15113. return;
  15114. }
  15115. const processResult = (resolved2) => {
  15116. if (!externalize) {
  15117. return resolved2;
  15118. }
  15119. if (!canExternalizeFile(resolved2.id)) {
  15120. return resolved2;
  15121. }
  15122. let resolvedId = id;
  15123. if (deepMatch && !pkg.data.exports && path$b.extname(id) !== path$b.extname(resolved2.id)) {
  15124. const index = resolved2.id.indexOf(id);
  15125. if (index > -1) {
  15126. resolvedId = resolved2.id.slice(index);
  15127. debug$d?.(
  15128. `[processResult] ${colors$1.cyan(id)} -> ${colors$1.dim(resolvedId)}`
  15129. );
  15130. }
  15131. }
  15132. return { ...resolved2, id: resolvedId, external: true };
  15133. };
  15134. if (!options.idOnly && (!options.scan && isBuild || externalize)) {
  15135. return processResult({
  15136. id: resolved,
  15137. moduleSideEffects: pkg.hasSideEffects(resolved)
  15138. });
  15139. }
  15140. if (!isInNodeModules$1(resolved) || // linked
  15141. !depsOptimizer || // resolving before listening to the server
  15142. options.scan) {
  15143. return { id: resolved };
  15144. }
  15145. const isJsType = isOptimizable(resolved, depsOptimizer.options);
  15146. const exclude = depsOptimizer.options.exclude;
  15147. const skipOptimization = depsOptimizer.options.noDiscovery || !isJsType || importer && isInNodeModules$1(importer) || exclude?.includes(pkgId) || exclude?.includes(id) || SPECIAL_QUERY_RE.test(resolved);
  15148. if (skipOptimization) {
  15149. const versionHash = depsOptimizer.metadata.browserHash;
  15150. if (versionHash && isJsType) {
  15151. resolved = injectQuery(resolved, `v=${versionHash}`);
  15152. }
  15153. } else {
  15154. const optimizedInfo = depsOptimizer.registerMissingImport(id, resolved);
  15155. resolved = depsOptimizer.getOptimizedDepId(optimizedInfo);
  15156. }
  15157. return { id: resolved };
  15158. }
  15159. async function tryOptimizedResolve(depsOptimizer, id, importer, preserveSymlinks, packageCache) {
  15160. await depsOptimizer.scanProcessing;
  15161. const metadata = depsOptimizer.metadata;
  15162. const depInfo = optimizedDepInfoFromId(metadata, id);
  15163. if (depInfo) {
  15164. return depsOptimizer.getOptimizedDepId(depInfo);
  15165. }
  15166. if (!importer) return;
  15167. let idPkgDir;
  15168. const nestedIdMatch = `> ${id}`;
  15169. for (const optimizedData of metadata.depInfoList) {
  15170. if (!optimizedData.src) continue;
  15171. if (!optimizedData.id.endsWith(nestedIdMatch)) continue;
  15172. if (idPkgDir == null) {
  15173. const pkgName = getNpmPackageName(id);
  15174. if (!pkgName) break;
  15175. idPkgDir = resolvePackageData(
  15176. pkgName,
  15177. importer,
  15178. preserveSymlinks,
  15179. packageCache
  15180. )?.dir;
  15181. if (idPkgDir == null) break;
  15182. idPkgDir = normalizePath$3(idPkgDir);
  15183. }
  15184. if (optimizedData.src.startsWith(withTrailingSlash(idPkgDir))) {
  15185. return depsOptimizer.getOptimizedDepId(optimizedData);
  15186. }
  15187. }
  15188. }
  15189. function resolvePackageEntry(id, { dir, data, setResolvedCache, getResolvedCache }, options) {
  15190. const { file: idWithoutPostfix, postfix } = splitFileAndPostfix(id);
  15191. const cached = getResolvedCache(".", options);
  15192. if (cached) {
  15193. return cached + postfix;
  15194. }
  15195. try {
  15196. let entryPoint;
  15197. if (data.exports) {
  15198. entryPoint = resolveExportsOrImports(data, ".", options, "exports");
  15199. }
  15200. if (!entryPoint) {
  15201. for (const field of options.mainFields) {
  15202. if (field === "browser") {
  15203. entryPoint = tryResolveBrowserEntry(dir, data, options);
  15204. if (entryPoint) {
  15205. break;
  15206. }
  15207. } else if (typeof data[field] === "string") {
  15208. entryPoint = data[field];
  15209. break;
  15210. }
  15211. }
  15212. }
  15213. entryPoint ||= data.main;
  15214. const entryPoints = entryPoint ? [entryPoint] : ["index.js", "index.json", "index.node"];
  15215. for (let entry of entryPoints) {
  15216. let skipPackageJson = false;
  15217. if (options.mainFields[0] === "sass" && !options.extensions.includes(path$b.extname(entry))) {
  15218. entry = "";
  15219. skipPackageJson = true;
  15220. } else {
  15221. const { browser: browserField } = data;
  15222. if (options.mainFields.includes("browser") && isObject$1(browserField)) {
  15223. entry = mapWithBrowserField(entry, browserField) || entry;
  15224. }
  15225. }
  15226. const entryPointPath = path$b.join(dir, entry);
  15227. const resolvedEntryPoint = tryFsResolve(
  15228. entryPointPath,
  15229. options,
  15230. true,
  15231. skipPackageJson
  15232. );
  15233. if (resolvedEntryPoint) {
  15234. debug$d?.(
  15235. `[package entry] ${colors$1.cyan(idWithoutPostfix)} -> ${colors$1.dim(
  15236. resolvedEntryPoint
  15237. )}${postfix !== "" ? ` (postfix: ${postfix})` : ""}`
  15238. );
  15239. setResolvedCache(".", resolvedEntryPoint, options);
  15240. return resolvedEntryPoint + postfix;
  15241. }
  15242. }
  15243. } catch (e) {
  15244. packageEntryFailure(id, e.message);
  15245. }
  15246. packageEntryFailure(id);
  15247. }
  15248. function packageEntryFailure(id, details) {
  15249. const err = new Error(
  15250. `Failed to resolve entry for package "${id}". The package may have incorrect main/module/exports specified in its package.json` + (details ? ": " + details : ".")
  15251. );
  15252. err.code = ERR_RESOLVE_PACKAGE_ENTRY_FAIL;
  15253. throw err;
  15254. }
  15255. function resolveExportsOrImports(pkg, key, options, type) {
  15256. const conditions = options.conditions.map((condition) => {
  15257. if (condition === DEV_PROD_CONDITION) {
  15258. return options.isProduction ? "production" : "development";
  15259. }
  15260. return condition;
  15261. });
  15262. if (options.isRequire) {
  15263. conditions.push("require");
  15264. } else {
  15265. conditions.push("import");
  15266. }
  15267. const fn = type === "imports" ? f : o;
  15268. const result = fn(pkg, key, { conditions, unsafe: true });
  15269. return result ? result[0] : void 0;
  15270. }
  15271. function resolveDeepImport(id, { setResolvedCache, getResolvedCache, dir, data }, options) {
  15272. const cache = getResolvedCache(id, options);
  15273. if (cache) {
  15274. return cache;
  15275. }
  15276. let relativeId = id;
  15277. const { exports: exportsField, browser: browserField } = data;
  15278. if (exportsField) {
  15279. if (isObject$1(exportsField) && !Array.isArray(exportsField)) {
  15280. const { file, postfix } = splitFileAndPostfix(relativeId);
  15281. const exportsId = resolveExportsOrImports(data, file, options, "exports");
  15282. if (exportsId !== void 0) {
  15283. relativeId = exportsId + postfix;
  15284. } else {
  15285. relativeId = void 0;
  15286. }
  15287. } else {
  15288. relativeId = void 0;
  15289. }
  15290. if (!relativeId) {
  15291. throw new Error(
  15292. `Package subpath '${relativeId}' is not defined by "exports" in ${path$b.join(dir, "package.json")}.`
  15293. );
  15294. }
  15295. } else if (options.mainFields.includes("browser") && isObject$1(browserField)) {
  15296. const { file, postfix } = splitFileAndPostfix(relativeId);
  15297. const mapped = mapWithBrowserField(file, browserField);
  15298. if (mapped) {
  15299. relativeId = mapped + postfix;
  15300. } else if (mapped === false) {
  15301. setResolvedCache(id, browserExternalId, options);
  15302. return browserExternalId;
  15303. }
  15304. }
  15305. if (relativeId) {
  15306. const resolved = tryFsResolve(
  15307. path$b.join(dir, relativeId),
  15308. options,
  15309. !exportsField
  15310. // try index only if no exports field
  15311. );
  15312. if (resolved) {
  15313. debug$d?.(
  15314. `[node/deep-import] ${colors$1.cyan(id)} -> ${colors$1.dim(resolved)}`
  15315. );
  15316. setResolvedCache(id, resolved, options);
  15317. return resolved;
  15318. }
  15319. }
  15320. }
  15321. function tryResolveBrowserMapping(id, importer, options, isFilePath, externalize) {
  15322. let res;
  15323. const pkg = importer && findNearestPackageData(path$b.dirname(importer), options.packageCache);
  15324. if (pkg && isObject$1(pkg.data.browser)) {
  15325. const mapId = isFilePath ? "./" + slash$1(path$b.relative(pkg.dir, id)) : id;
  15326. const browserMappedPath = mapWithBrowserField(mapId, pkg.data.browser);
  15327. if (browserMappedPath) {
  15328. if (res = bareImportRE.test(browserMappedPath) ? tryNodeResolve(
  15329. browserMappedPath,
  15330. importer,
  15331. options,
  15332. void 0,
  15333. void 0
  15334. )?.id : tryFsResolve(path$b.join(pkg.dir, browserMappedPath), options)) {
  15335. debug$d?.(`[browser mapped] ${colors$1.cyan(id)} -> ${colors$1.dim(res)}`);
  15336. let result = { id: res };
  15337. if (options.idOnly) {
  15338. return result;
  15339. }
  15340. if (!options.scan && options.isBuild) {
  15341. const resPkg = findNearestPackageData(
  15342. path$b.dirname(res),
  15343. options.packageCache
  15344. );
  15345. if (resPkg) {
  15346. result = {
  15347. id: res,
  15348. moduleSideEffects: resPkg.hasSideEffects(res)
  15349. };
  15350. }
  15351. }
  15352. return externalize ? { ...result, external: true } : result;
  15353. }
  15354. } else if (browserMappedPath === false) {
  15355. return browserExternalId;
  15356. }
  15357. }
  15358. }
  15359. function tryResolveBrowserEntry(dir, data, options) {
  15360. const browserEntry = typeof data.browser === "string" ? data.browser : isObject$1(data.browser) && data.browser["."];
  15361. if (browserEntry) {
  15362. if (!options.isRequire && options.mainFields.includes("module") && typeof data.module === "string" && data.module !== browserEntry) {
  15363. const resolvedBrowserEntry = tryFsResolve(
  15364. path$b.join(dir, browserEntry),
  15365. options
  15366. );
  15367. if (resolvedBrowserEntry) {
  15368. const content = fs__default.readFileSync(resolvedBrowserEntry, "utf-8");
  15369. if (hasESMSyntax(content)) {
  15370. return browserEntry;
  15371. } else {
  15372. return data.module;
  15373. }
  15374. }
  15375. } else {
  15376. return browserEntry;
  15377. }
  15378. }
  15379. }
  15380. function mapWithBrowserField(relativePathInPkgDir, map) {
  15381. const normalizedPath = path$b.posix.normalize(relativePathInPkgDir);
  15382. for (const key in map) {
  15383. const normalizedKey = path$b.posix.normalize(key);
  15384. if (normalizedPath === normalizedKey || equalWithoutSuffix(normalizedPath, normalizedKey, ".js") || equalWithoutSuffix(normalizedPath, normalizedKey, "/index.js")) {
  15385. return map[key];
  15386. }
  15387. }
  15388. }
  15389. function equalWithoutSuffix(path2, key, suffix) {
  15390. return key.endsWith(suffix) && key.slice(0, -suffix.length) === path2;
  15391. }
  15392. function tryResolveRealFile(file, preserveSymlinks) {
  15393. const stat = tryStatSync(file);
  15394. if (stat?.isFile()) return getRealPath(file, preserveSymlinks);
  15395. }
  15396. function tryResolveRealFileWithExtensions(filePath, extensions, preserveSymlinks) {
  15397. for (const ext of extensions) {
  15398. const res = tryResolveRealFile(filePath + ext, preserveSymlinks);
  15399. if (res) return res;
  15400. }
  15401. }
  15402. function tryResolveRealFileOrType(file, preserveSymlinks) {
  15403. const fileStat = tryStatSync(file);
  15404. if (fileStat?.isFile()) {
  15405. return { path: getRealPath(file, preserveSymlinks), type: "file" };
  15406. }
  15407. if (fileStat?.isDirectory()) {
  15408. return { type: "directory" };
  15409. }
  15410. return;
  15411. }
  15412. function getRealPath(resolved, preserveSymlinks) {
  15413. if (!preserveSymlinks) {
  15414. resolved = safeRealpathSync(resolved);
  15415. }
  15416. return normalizePath$3(resolved);
  15417. }
  15418. function isDirectory(path2) {
  15419. const stat = tryStatSync(path2);
  15420. return stat?.isDirectory() ?? false;
  15421. }
  15422. const debug$c = createDebugger("vite:optimize-deps");
  15423. function optimizedDepsPlugin() {
  15424. return {
  15425. name: "vite:optimized-deps",
  15426. applyToEnvironment(environment) {
  15427. return !isDepOptimizationDisabled(environment.config.optimizeDeps);
  15428. },
  15429. resolveId(id) {
  15430. const environment = this.environment;
  15431. if (environment.depsOptimizer?.isOptimizedDepFile(id)) {
  15432. return id;
  15433. }
  15434. },
  15435. // this.load({ id }) isn't implemented in PluginContainer
  15436. // The logic to register an id to wait until it is processed
  15437. // is in importAnalysis, see call to delayDepsOptimizerUntil
  15438. async load(id) {
  15439. const environment = this.environment;
  15440. const depsOptimizer = environment.depsOptimizer;
  15441. if (depsOptimizer?.isOptimizedDepFile(id)) {
  15442. const metadata = depsOptimizer.metadata;
  15443. const file = cleanUrl(id);
  15444. const versionMatch = DEP_VERSION_RE.exec(file);
  15445. const browserHash = versionMatch ? versionMatch[1].split("=")[1] : void 0;
  15446. const info = optimizedDepInfoFromFile(metadata, file);
  15447. if (info) {
  15448. if (browserHash && info.browserHash !== browserHash) {
  15449. throwOutdatedRequest(id);
  15450. }
  15451. try {
  15452. await info.processing;
  15453. } catch {
  15454. throwProcessingError(id);
  15455. }
  15456. const newMetadata = depsOptimizer.metadata;
  15457. if (metadata !== newMetadata) {
  15458. const currentInfo = optimizedDepInfoFromFile(newMetadata, file);
  15459. if (info.browserHash !== currentInfo?.browserHash) {
  15460. throwOutdatedRequest(id);
  15461. }
  15462. }
  15463. }
  15464. debug$c?.(`load ${colors$1.cyan(file)}`);
  15465. try {
  15466. return await fsp.readFile(file, "utf-8");
  15467. } catch {
  15468. const newMetadata = depsOptimizer.metadata;
  15469. if (optimizedDepInfoFromFile(newMetadata, file)) {
  15470. throwOutdatedRequest(id);
  15471. }
  15472. throwFileNotFoundInOptimizedDep(id);
  15473. }
  15474. }
  15475. }
  15476. };
  15477. }
  15478. function throwProcessingError(id) {
  15479. const err = new Error(
  15480. `Something unexpected happened while optimizing "${id}". The current page should have reloaded by now`
  15481. );
  15482. err.code = ERR_OPTIMIZE_DEPS_PROCESSING_ERROR;
  15483. throw err;
  15484. }
  15485. function throwOutdatedRequest(id) {
  15486. const err = new Error(
  15487. `There is a new version of the pre-bundle for "${id}", a page reload is going to ask for it.`
  15488. );
  15489. err.code = ERR_OUTDATED_OPTIMIZED_DEP;
  15490. throw err;
  15491. }
  15492. function throwFileNotFoundInOptimizedDep(id) {
  15493. const err = new Error(
  15494. `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\`.`
  15495. );
  15496. err.code = ERR_FILE_NOT_FOUND_IN_OPTIMIZED_DEP_DIR;
  15497. throw err;
  15498. }
  15499. var main = {exports: {}};
  15500. var version$1 = "16.5.0";
  15501. var require$$4 = {
  15502. version: version$1};
  15503. const fs$6 = require$$0$4;
  15504. const path$8 = require$$0$2;
  15505. const os$1 = require$$2;
  15506. const crypto$1 = require$$3;
  15507. const packageJson = require$$4;
  15508. const version = packageJson.version;
  15509. const LINE = /(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg;
  15510. // Parse src into an Object
  15511. function parse$c (src) {
  15512. const obj = {};
  15513. // Convert buffer to string
  15514. let lines = src.toString();
  15515. // Convert line breaks to same format
  15516. lines = lines.replace(/\r\n?/mg, '\n');
  15517. let match;
  15518. while ((match = LINE.exec(lines)) != null) {
  15519. const key = match[1];
  15520. // Default undefined or null to empty string
  15521. let value = (match[2] || '');
  15522. // Remove whitespace
  15523. value = value.trim();
  15524. // Check if double quoted
  15525. const maybeQuote = value[0];
  15526. // Remove surrounding quotes
  15527. value = value.replace(/^(['"`])([\s\S]*)\1$/mg, '$2');
  15528. // Expand newlines if double quoted
  15529. if (maybeQuote === '"') {
  15530. value = value.replace(/\\n/g, '\n');
  15531. value = value.replace(/\\r/g, '\r');
  15532. }
  15533. // Add to object
  15534. obj[key] = value;
  15535. }
  15536. return obj
  15537. }
  15538. function _parseVault (options) {
  15539. const vaultPath = _vaultPath(options);
  15540. // Parse .env.vault
  15541. const result = DotenvModule.configDotenv({ path: vaultPath });
  15542. if (!result.parsed) {
  15543. const err = new Error(`MISSING_DATA: Cannot parse ${vaultPath} for an unknown reason`);
  15544. err.code = 'MISSING_DATA';
  15545. throw err
  15546. }
  15547. // handle scenario for comma separated keys - for use with key rotation
  15548. // example: DOTENV_KEY="dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=prod,dotenv://:key_7890@dotenvx.com/vault/.env.vault?environment=prod"
  15549. const keys = _dotenvKey(options).split(',');
  15550. const length = keys.length;
  15551. let decrypted;
  15552. for (let i = 0; i < length; i++) {
  15553. try {
  15554. // Get full key
  15555. const key = keys[i].trim();
  15556. // Get instructions for decrypt
  15557. const attrs = _instructions(result, key);
  15558. // Decrypt
  15559. decrypted = DotenvModule.decrypt(attrs.ciphertext, attrs.key);
  15560. break
  15561. } catch (error) {
  15562. // last key
  15563. if (i + 1 >= length) {
  15564. throw error
  15565. }
  15566. // try next key
  15567. }
  15568. }
  15569. // Parse decrypted .env string
  15570. return DotenvModule.parse(decrypted)
  15571. }
  15572. function _warn (message) {
  15573. console.log(`[dotenv@${version}][WARN] ${message}`);
  15574. }
  15575. function _debug (message) {
  15576. console.log(`[dotenv@${version}][DEBUG] ${message}`);
  15577. }
  15578. function _dotenvKey (options) {
  15579. // prioritize developer directly setting options.DOTENV_KEY
  15580. if (options && options.DOTENV_KEY && options.DOTENV_KEY.length > 0) {
  15581. return options.DOTENV_KEY
  15582. }
  15583. // secondary infra already contains a DOTENV_KEY environment variable
  15584. if (process.env.DOTENV_KEY && process.env.DOTENV_KEY.length > 0) {
  15585. return process.env.DOTENV_KEY
  15586. }
  15587. // fallback to empty string
  15588. return ''
  15589. }
  15590. function _instructions (result, dotenvKey) {
  15591. // Parse DOTENV_KEY. Format is a URI
  15592. let uri;
  15593. try {
  15594. uri = new URL(dotenvKey);
  15595. } catch (error) {
  15596. if (error.code === 'ERR_INVALID_URL') {
  15597. const err = new Error('INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development');
  15598. err.code = 'INVALID_DOTENV_KEY';
  15599. throw err
  15600. }
  15601. throw error
  15602. }
  15603. // Get decrypt key
  15604. const key = uri.password;
  15605. if (!key) {
  15606. const err = new Error('INVALID_DOTENV_KEY: Missing key part');
  15607. err.code = 'INVALID_DOTENV_KEY';
  15608. throw err
  15609. }
  15610. // Get environment
  15611. const environment = uri.searchParams.get('environment');
  15612. if (!environment) {
  15613. const err = new Error('INVALID_DOTENV_KEY: Missing environment part');
  15614. err.code = 'INVALID_DOTENV_KEY';
  15615. throw err
  15616. }
  15617. // Get ciphertext payload
  15618. const environmentKey = `DOTENV_VAULT_${environment.toUpperCase()}`;
  15619. const ciphertext = result.parsed[environmentKey]; // DOTENV_VAULT_PRODUCTION
  15620. if (!ciphertext) {
  15621. const err = new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${environmentKey} in your .env.vault file.`);
  15622. err.code = 'NOT_FOUND_DOTENV_ENVIRONMENT';
  15623. throw err
  15624. }
  15625. return { ciphertext, key }
  15626. }
  15627. function _vaultPath (options) {
  15628. let possibleVaultPath = null;
  15629. if (options && options.path && options.path.length > 0) {
  15630. if (Array.isArray(options.path)) {
  15631. for (const filepath of options.path) {
  15632. if (fs$6.existsSync(filepath)) {
  15633. possibleVaultPath = filepath.endsWith('.vault') ? filepath : `${filepath}.vault`;
  15634. }
  15635. }
  15636. } else {
  15637. possibleVaultPath = options.path.endsWith('.vault') ? options.path : `${options.path}.vault`;
  15638. }
  15639. } else {
  15640. possibleVaultPath = path$8.resolve(process.cwd(), '.env.vault');
  15641. }
  15642. if (fs$6.existsSync(possibleVaultPath)) {
  15643. return possibleVaultPath
  15644. }
  15645. return null
  15646. }
  15647. function _resolveHome (envPath) {
  15648. return envPath[0] === '~' ? path$8.join(os$1.homedir(), envPath.slice(1)) : envPath
  15649. }
  15650. function _configVault (options) {
  15651. const debug = Boolean(options && options.debug);
  15652. if (debug) {
  15653. _debug('Loading env from encrypted .env.vault');
  15654. }
  15655. const parsed = DotenvModule._parseVault(options);
  15656. let processEnv = process.env;
  15657. if (options && options.processEnv != null) {
  15658. processEnv = options.processEnv;
  15659. }
  15660. DotenvModule.populate(processEnv, parsed, options);
  15661. return { parsed }
  15662. }
  15663. function configDotenv (options) {
  15664. const dotenvPath = path$8.resolve(process.cwd(), '.env');
  15665. let encoding = 'utf8';
  15666. const debug = Boolean(options && options.debug);
  15667. if (options && options.encoding) {
  15668. encoding = options.encoding;
  15669. } else {
  15670. if (debug) {
  15671. _debug('No encoding is specified. UTF-8 is used by default');
  15672. }
  15673. }
  15674. let optionPaths = [dotenvPath]; // default, look for .env
  15675. if (options && options.path) {
  15676. if (!Array.isArray(options.path)) {
  15677. optionPaths = [_resolveHome(options.path)];
  15678. } else {
  15679. optionPaths = []; // reset default
  15680. for (const filepath of options.path) {
  15681. optionPaths.push(_resolveHome(filepath));
  15682. }
  15683. }
  15684. }
  15685. // Build the parsed data in a temporary object (because we need to return it). Once we have the final
  15686. // parsed data, we will combine it with process.env (or options.processEnv if provided).
  15687. let lastError;
  15688. const parsedAll = {};
  15689. for (const path of optionPaths) {
  15690. try {
  15691. // Specifying an encoding returns a string instead of a buffer
  15692. const parsed = DotenvModule.parse(fs$6.readFileSync(path, { encoding }));
  15693. DotenvModule.populate(parsedAll, parsed, options);
  15694. } catch (e) {
  15695. if (debug) {
  15696. _debug(`Failed to load ${path} ${e.message}`);
  15697. }
  15698. lastError = e;
  15699. }
  15700. }
  15701. let processEnv = process.env;
  15702. if (options && options.processEnv != null) {
  15703. processEnv = options.processEnv;
  15704. }
  15705. DotenvModule.populate(processEnv, parsedAll, options);
  15706. if (lastError) {
  15707. return { parsed: parsedAll, error: lastError }
  15708. } else {
  15709. return { parsed: parsedAll }
  15710. }
  15711. }
  15712. // Populates process.env from .env file
  15713. function config (options) {
  15714. // fallback to original dotenv if DOTENV_KEY is not set
  15715. if (_dotenvKey(options).length === 0) {
  15716. return DotenvModule.configDotenv(options)
  15717. }
  15718. const vaultPath = _vaultPath(options);
  15719. // dotenvKey exists but .env.vault file does not exist
  15720. if (!vaultPath) {
  15721. _warn(`You set DOTENV_KEY but you are missing a .env.vault file at ${vaultPath}. Did you forget to build it?`);
  15722. return DotenvModule.configDotenv(options)
  15723. }
  15724. return DotenvModule._configVault(options)
  15725. }
  15726. function decrypt (encrypted, keyStr) {
  15727. const key = Buffer.from(keyStr.slice(-64), 'hex');
  15728. let ciphertext = Buffer.from(encrypted, 'base64');
  15729. const nonce = ciphertext.subarray(0, 12);
  15730. const authTag = ciphertext.subarray(-16);
  15731. ciphertext = ciphertext.subarray(12, -16);
  15732. try {
  15733. const aesgcm = crypto$1.createDecipheriv('aes-256-gcm', key, nonce);
  15734. aesgcm.setAuthTag(authTag);
  15735. return `${aesgcm.update(ciphertext)}${aesgcm.final()}`
  15736. } catch (error) {
  15737. const isRange = error instanceof RangeError;
  15738. const invalidKeyLength = error.message === 'Invalid key length';
  15739. const decryptionFailed = error.message === 'Unsupported state or unable to authenticate data';
  15740. if (isRange || invalidKeyLength) {
  15741. const err = new Error('INVALID_DOTENV_KEY: It must be 64 characters long (or more)');
  15742. err.code = 'INVALID_DOTENV_KEY';
  15743. throw err
  15744. } else if (decryptionFailed) {
  15745. const err = new Error('DECRYPTION_FAILED: Please check your DOTENV_KEY');
  15746. err.code = 'DECRYPTION_FAILED';
  15747. throw err
  15748. } else {
  15749. throw error
  15750. }
  15751. }
  15752. }
  15753. // Populate process.env with parsed values
  15754. function populate (processEnv, parsed, options = {}) {
  15755. const debug = Boolean(options && options.debug);
  15756. const override = Boolean(options && options.override);
  15757. if (typeof parsed !== 'object') {
  15758. const err = new Error('OBJECT_REQUIRED: Please check the processEnv argument being passed to populate');
  15759. err.code = 'OBJECT_REQUIRED';
  15760. throw err
  15761. }
  15762. // Set process.env
  15763. for (const key of Object.keys(parsed)) {
  15764. if (Object.prototype.hasOwnProperty.call(processEnv, key)) {
  15765. if (override === true) {
  15766. processEnv[key] = parsed[key];
  15767. }
  15768. if (debug) {
  15769. if (override === true) {
  15770. _debug(`"${key}" is already defined and WAS overwritten`);
  15771. } else {
  15772. _debug(`"${key}" is already defined and was NOT overwritten`);
  15773. }
  15774. }
  15775. } else {
  15776. processEnv[key] = parsed[key];
  15777. }
  15778. }
  15779. }
  15780. const DotenvModule = {
  15781. configDotenv,
  15782. _configVault,
  15783. _parseVault,
  15784. config,
  15785. decrypt,
  15786. parse: parse$c,
  15787. populate
  15788. };
  15789. main.exports.configDotenv = DotenvModule.configDotenv;
  15790. main.exports._configVault = DotenvModule._configVault;
  15791. main.exports._parseVault = DotenvModule._parseVault;
  15792. main.exports.config = DotenvModule.config;
  15793. main.exports.decrypt = DotenvModule.decrypt;
  15794. var parse_1$2 = main.exports.parse = DotenvModule.parse;
  15795. main.exports.populate = DotenvModule.populate;
  15796. main.exports = DotenvModule;
  15797. function _resolveEscapeSequences (value) {
  15798. return value.replace(/\\\$/g, '$')
  15799. }
  15800. function expandValue (value, processEnv, runningParsed) {
  15801. const env = { ...runningParsed, ...processEnv }; // process.env wins
  15802. const regex = /(?<!\\)\${([^{}]+)}|(?<!\\)\$([A-Za-z_][A-Za-z0-9_]*)/g;
  15803. let result = value;
  15804. let match;
  15805. const seen = new Set(); // self-referential checker
  15806. while ((match = regex.exec(result)) !== null) {
  15807. seen.add(result);
  15808. const [template, bracedExpression, unbracedExpression] = match;
  15809. const expression = bracedExpression || unbracedExpression;
  15810. // match the operators `:+`, `+`, `:-`, and `-`
  15811. const opRegex = /(:\+|\+|:-|-)/;
  15812. // find first match
  15813. const opMatch = expression.match(opRegex);
  15814. const splitter = opMatch ? opMatch[0] : null;
  15815. const r = expression.split(splitter);
  15816. let defaultValue;
  15817. let value;
  15818. const key = r.shift();
  15819. if ([':+', '+'].includes(splitter)) {
  15820. defaultValue = env[key] ? r.join(splitter) : '';
  15821. value = null;
  15822. } else {
  15823. defaultValue = r.join(splitter);
  15824. value = env[key];
  15825. }
  15826. if (value) {
  15827. // self-referential check
  15828. if (seen.has(value)) {
  15829. result = result.replace(template, defaultValue);
  15830. } else {
  15831. result = result.replace(template, value);
  15832. }
  15833. } else {
  15834. result = result.replace(template, defaultValue);
  15835. }
  15836. // if the result equaled what was in process.env and runningParsed then stop expanding
  15837. if (result === runningParsed[key]) {
  15838. break
  15839. }
  15840. regex.lastIndex = 0; // reset regex search position to re-evaluate after each replacement
  15841. }
  15842. return result
  15843. }
  15844. function expand$2 (options) {
  15845. // for use with progressive expansion
  15846. // const runningParsed = {}
  15847. let processEnv = process.env;
  15848. if (options && options.processEnv != null) {
  15849. processEnv = options.processEnv;
  15850. }
  15851. // dotenv.config() ran before this so the assumption is process.env has already been set
  15852. for (const key in options.parsed) {
  15853. let value = options.parsed[key];
  15854. // short-circuit scenario: process.env was already set prior to the file value
  15855. if (processEnv[key] && processEnv[key] !== value) {
  15856. value = processEnv[key];
  15857. } else {
  15858. // PATCH: we pass options.parsed instead of runningParsed
  15859. // to allow variables declared in other files to be used
  15860. value = expandValue(value, processEnv, options.parsed);
  15861. }
  15862. options.parsed[key] = _resolveEscapeSequences(value);
  15863. // for use with progressive expansion
  15864. // runningParsed[key] = _resolveEscapeSequences(value)
  15865. }
  15866. for (const processKey in options.parsed) {
  15867. processEnv[processKey] = options.parsed[processKey];
  15868. }
  15869. return options
  15870. }
  15871. var expand_1$1 = expand$2;
  15872. const debug$b = createDebugger("vite:env");
  15873. function getEnvFilesForMode(mode, envDir) {
  15874. if (envDir !== false) {
  15875. return [
  15876. /** default file */
  15877. `.env`,
  15878. /** local file */
  15879. `.env.local`,
  15880. /** mode file */
  15881. `.env.${mode}`,
  15882. /** mode local file */
  15883. `.env.${mode}.local`
  15884. ].map((file) => normalizePath$3(path$b.join(envDir, file)));
  15885. }
  15886. return [];
  15887. }
  15888. function loadEnv(mode, envDir, prefixes = "VITE_") {
  15889. const start = performance.now();
  15890. const getTime = () => `${(performance.now() - start).toFixed(2)}ms`;
  15891. if (mode === "local") {
  15892. throw new Error(
  15893. `"local" cannot be used as a mode name because it conflicts with the .local postfix for .env files.`
  15894. );
  15895. }
  15896. prefixes = arraify(prefixes);
  15897. const env = {};
  15898. const envFiles = getEnvFilesForMode(mode, envDir);
  15899. debug$b?.(`loading env files: %O`, envFiles);
  15900. const parsed = Object.fromEntries(
  15901. envFiles.flatMap((filePath) => {
  15902. if (!tryStatSync(filePath)?.isFile()) return [];
  15903. return Object.entries(parse_1$2(fs__default.readFileSync(filePath)));
  15904. })
  15905. );
  15906. debug$b?.(`env files loaded in ${getTime()}`);
  15907. if (parsed.NODE_ENV && process.env.VITE_USER_NODE_ENV === void 0) {
  15908. process.env.VITE_USER_NODE_ENV = parsed.NODE_ENV;
  15909. }
  15910. if (parsed.BROWSER && process.env.BROWSER === void 0) {
  15911. process.env.BROWSER = parsed.BROWSER;
  15912. }
  15913. if (parsed.BROWSER_ARGS && process.env.BROWSER_ARGS === void 0) {
  15914. process.env.BROWSER_ARGS = parsed.BROWSER_ARGS;
  15915. }
  15916. const processEnv = { ...process.env };
  15917. expand_1$1({ parsed, processEnv });
  15918. for (const [key, value] of Object.entries(parsed)) {
  15919. if (prefixes.some((prefix) => key.startsWith(prefix))) {
  15920. env[key] = value;
  15921. }
  15922. }
  15923. for (const key in process.env) {
  15924. if (prefixes.some((prefix) => key.startsWith(prefix))) {
  15925. env[key] = process.env[key];
  15926. }
  15927. }
  15928. debug$b?.(`using resolved env: %O`, env);
  15929. return env;
  15930. }
  15931. function resolveEnvPrefix({
  15932. envPrefix = "VITE_"
  15933. }) {
  15934. envPrefix = arraify(envPrefix);
  15935. if (envPrefix.includes("")) {
  15936. throw new Error(
  15937. `envPrefix option contains value '', which could lead unexpected exposure of sensitive information.`
  15938. );
  15939. }
  15940. return envPrefix;
  15941. }
  15942. const docsURL = "https://vite.dev";
  15943. const deprecationCode = {
  15944. removePluginHookSsrArgument: "changes/this-environment-in-hooks",
  15945. removePluginHookHandleHotUpdate: "changes/hotupdate-hook",
  15946. removeServerModuleGraph: "changes/per-environment-apis",
  15947. removeServerHot: "changes/per-environment-apis",
  15948. removeServerTransformRequest: "changes/per-environment-apis",
  15949. removeSsrLoadModule: "changes/ssr-using-modulerunner"
  15950. };
  15951. const deprecationMessages = {
  15952. removePluginHookSsrArgument: "Plugin hook `options.ssr` is replaced with `this.environment.config.consumer === 'server'`.",
  15953. removePluginHookHandleHotUpdate: "Plugin hook `handleHotUpdate()` is replaced with `hotUpdate()`.",
  15954. removeServerModuleGraph: "The `server.moduleGraph` is replaced with `this.environment.moduleGraph`.",
  15955. removeServerHot: "The `server.hot` is replaced with `this.environment.hot`.",
  15956. removeServerTransformRequest: "The `server.transformRequest` is replaced with `this.environment.transformRequest`.",
  15957. removeSsrLoadModule: "The `server.ssrLoadModule` is replaced with Environment Runner."
  15958. };
  15959. let _ignoreDeprecationWarnings = false;
  15960. function warnFutureDeprecation(config, type, extraMessage, stacktrace = true) {
  15961. if (_ignoreDeprecationWarnings || !config.future || config.future[type] !== "warn")
  15962. return;
  15963. let msg = `[vite future] ${deprecationMessages[type]}`;
  15964. if (extraMessage) {
  15965. msg += ` ${extraMessage}`;
  15966. }
  15967. msg = colors$1.yellow(msg);
  15968. const docs = `${docsURL}/changes/${deprecationCode[type].toLowerCase()}`;
  15969. msg += colors$1.gray(`
  15970. ${stacktrace ? "\u251C" : "\u2514"}\u2500\u2500\u2500 `) + colors$1.underline(docs) + "\n";
  15971. if (stacktrace) {
  15972. const stack = new Error().stack;
  15973. if (stack) {
  15974. let stacks = stack.split("\n").slice(3).filter((i) => !i.includes("/node_modules/vite/dist/"));
  15975. if (stacks.length === 0) {
  15976. stacks.push("No stack trace found.");
  15977. }
  15978. stacks = stacks.map(
  15979. (i, idx) => ` ${idx === stacks.length - 1 ? "\u2514" : "\u2502"} ${i.trim()}`
  15980. );
  15981. msg += colors$1.dim(stacks.join("\n")) + "\n";
  15982. }
  15983. }
  15984. config.logger.warnOnce(msg);
  15985. }
  15986. function ignoreDeprecationWarnings(fn) {
  15987. const before = _ignoreDeprecationWarnings;
  15988. _ignoreDeprecationWarnings = true;
  15989. const ret = fn();
  15990. _ignoreDeprecationWarnings = before;
  15991. return ret;
  15992. }
  15993. function prepareError(err) {
  15994. return {
  15995. message: stripVTControlCharacters(err.message),
  15996. stack: stripVTControlCharacters(cleanStack(err.stack || "")),
  15997. id: err.id,
  15998. frame: stripVTControlCharacters(err.frame || ""),
  15999. plugin: err.plugin,
  16000. pluginCode: err.pluginCode?.toString(),
  16001. loc: err.loc
  16002. };
  16003. }
  16004. function buildErrorMessage(err, args = [], includeStack = true) {
  16005. if (err.plugin) args.push(` Plugin: ${colors$1.magenta(err.plugin)}`);
  16006. const loc = err.loc ? `:${err.loc.line}:${err.loc.column}` : "";
  16007. if (err.id) args.push(` File: ${colors$1.cyan(err.id)}${loc}`);
  16008. if (err.frame) args.push(colors$1.yellow(pad$1(err.frame)));
  16009. if (includeStack && err.stack) args.push(pad$1(cleanStack(err.stack)));
  16010. return args.join("\n");
  16011. }
  16012. function cleanStack(stack) {
  16013. return stack.split(/\n/).filter((l) => /^\s*at/.test(l)).join("\n");
  16014. }
  16015. function logError(server, err) {
  16016. const msg = buildErrorMessage(err, [
  16017. colors$1.red(`Internal server error: ${err.message}`)
  16018. ]);
  16019. server.config.logger.error(msg, {
  16020. clear: true,
  16021. timestamp: true,
  16022. error: err
  16023. });
  16024. server.environments.client.hot.send({
  16025. type: "error",
  16026. err: prepareError(err)
  16027. });
  16028. }
  16029. function errorMiddleware(server, allowNext = false) {
  16030. return function viteErrorMiddleware(err, _req, res, next) {
  16031. logError(server, err);
  16032. if (allowNext) {
  16033. next();
  16034. } else {
  16035. res.statusCode = 500;
  16036. res.end(`
  16037. <!DOCTYPE html>
  16038. <html lang="en">
  16039. <head>
  16040. <meta charset="UTF-8" />
  16041. <title>Error</title>
  16042. <script type="module">
  16043. const error = ${JSON.stringify(prepareError(err)).replace(
  16044. /</g,
  16045. "\\u003c"
  16046. )}
  16047. try {
  16048. const { ErrorOverlay } = await import(${JSON.stringify(path$b.posix.join(server.config.base, CLIENT_PUBLIC_PATH))})
  16049. document.body.appendChild(new ErrorOverlay(error))
  16050. } catch {
  16051. const h = (tag, text) => {
  16052. const el = document.createElement(tag)
  16053. el.textContent = text
  16054. return el
  16055. }
  16056. document.body.appendChild(h('h1', 'Internal Server Error'))
  16057. document.body.appendChild(h('h2', error.message))
  16058. document.body.appendChild(h('pre', error.stack))
  16059. document.body.appendChild(h('p', '(Error overlay failed to load)'))
  16060. }
  16061. <\/script>
  16062. </head>
  16063. <body>
  16064. </body>
  16065. </html>
  16066. `);
  16067. }
  16068. };
  16069. }
  16070. var node = {exports: {}};
  16071. var debug$a = {exports: {}};
  16072. /**
  16073. * Helpers.
  16074. */
  16075. var s = 1000;
  16076. var m = s * 60;
  16077. var h = m * 60;
  16078. var d = h * 24;
  16079. var y = d * 365.25;
  16080. /**
  16081. * Parse or format the given `val`.
  16082. *
  16083. * Options:
  16084. *
  16085. * - `long` verbose formatting [false]
  16086. *
  16087. * @param {String|Number} val
  16088. * @param {Object} [options]
  16089. * @throws {Error} throw an error if val is not a non-empty string or a number
  16090. * @return {String|Number}
  16091. * @api public
  16092. */
  16093. var ms = function(val, options) {
  16094. options = options || {};
  16095. var type = typeof val;
  16096. if (type === 'string' && val.length > 0) {
  16097. return parse$b(val);
  16098. } else if (type === 'number' && isNaN(val) === false) {
  16099. return options.long ? fmtLong(val) : fmtShort(val);
  16100. }
  16101. throw new Error(
  16102. 'val is not a non-empty string or a valid number. val=' +
  16103. JSON.stringify(val)
  16104. );
  16105. };
  16106. /**
  16107. * Parse the given `str` and return milliseconds.
  16108. *
  16109. * @param {String} str
  16110. * @return {Number}
  16111. * @api private
  16112. */
  16113. function parse$b(str) {
  16114. str = String(str);
  16115. if (str.length > 100) {
  16116. return;
  16117. }
  16118. var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(
  16119. str
  16120. );
  16121. if (!match) {
  16122. return;
  16123. }
  16124. var n = parseFloat(match[1]);
  16125. var type = (match[2] || 'ms').toLowerCase();
  16126. switch (type) {
  16127. case 'years':
  16128. case 'year':
  16129. case 'yrs':
  16130. case 'yr':
  16131. case 'y':
  16132. return n * y;
  16133. case 'days':
  16134. case 'day':
  16135. case 'd':
  16136. return n * d;
  16137. case 'hours':
  16138. case 'hour':
  16139. case 'hrs':
  16140. case 'hr':
  16141. case 'h':
  16142. return n * h;
  16143. case 'minutes':
  16144. case 'minute':
  16145. case 'mins':
  16146. case 'min':
  16147. case 'm':
  16148. return n * m;
  16149. case 'seconds':
  16150. case 'second':
  16151. case 'secs':
  16152. case 'sec':
  16153. case 's':
  16154. return n * s;
  16155. case 'milliseconds':
  16156. case 'millisecond':
  16157. case 'msecs':
  16158. case 'msec':
  16159. case 'ms':
  16160. return n;
  16161. default:
  16162. return undefined;
  16163. }
  16164. }
  16165. /**
  16166. * Short format for `ms`.
  16167. *
  16168. * @param {Number} ms
  16169. * @return {String}
  16170. * @api private
  16171. */
  16172. function fmtShort(ms) {
  16173. if (ms >= d) {
  16174. return Math.round(ms / d) + 'd';
  16175. }
  16176. if (ms >= h) {
  16177. return Math.round(ms / h) + 'h';
  16178. }
  16179. if (ms >= m) {
  16180. return Math.round(ms / m) + 'm';
  16181. }
  16182. if (ms >= s) {
  16183. return Math.round(ms / s) + 's';
  16184. }
  16185. return ms + 'ms';
  16186. }
  16187. /**
  16188. * Long format for `ms`.
  16189. *
  16190. * @param {Number} ms
  16191. * @return {String}
  16192. * @api private
  16193. */
  16194. function fmtLong(ms) {
  16195. return plural(ms, d, 'day') ||
  16196. plural(ms, h, 'hour') ||
  16197. plural(ms, m, 'minute') ||
  16198. plural(ms, s, 'second') ||
  16199. ms + ' ms';
  16200. }
  16201. /**
  16202. * Pluralization helper.
  16203. */
  16204. function plural(ms, n, name) {
  16205. if (ms < n) {
  16206. return;
  16207. }
  16208. if (ms < n * 1.5) {
  16209. return Math.floor(ms / n) + ' ' + name;
  16210. }
  16211. return Math.ceil(ms / n) + ' ' + name + 's';
  16212. }
  16213. (function (module, exports) {
  16214. /**
  16215. * This is the common logic for both the Node.js and web browser
  16216. * implementations of `debug()`.
  16217. *
  16218. * Expose `debug()` as the module.
  16219. */
  16220. exports = module.exports = createDebug.debug = createDebug['default'] = createDebug;
  16221. exports.coerce = coerce;
  16222. exports.disable = disable;
  16223. exports.enable = enable;
  16224. exports.enabled = enabled;
  16225. exports.humanize = ms;
  16226. /**
  16227. * The currently active debug mode names, and names to skip.
  16228. */
  16229. exports.names = [];
  16230. exports.skips = [];
  16231. /**
  16232. * Map of special "%n" handling functions, for the debug "format" argument.
  16233. *
  16234. * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
  16235. */
  16236. exports.formatters = {};
  16237. /**
  16238. * Previous log timestamp.
  16239. */
  16240. var prevTime;
  16241. /**
  16242. * Select a color.
  16243. * @param {String} namespace
  16244. * @return {Number}
  16245. * @api private
  16246. */
  16247. function selectColor(namespace) {
  16248. var hash = 0, i;
  16249. for (i in namespace) {
  16250. hash = ((hash << 5) - hash) + namespace.charCodeAt(i);
  16251. hash |= 0; // Convert to 32bit integer
  16252. }
  16253. return exports.colors[Math.abs(hash) % exports.colors.length];
  16254. }
  16255. /**
  16256. * Create a debugger with the given `namespace`.
  16257. *
  16258. * @param {String} namespace
  16259. * @return {Function}
  16260. * @api public
  16261. */
  16262. function createDebug(namespace) {
  16263. function debug() {
  16264. // disabled?
  16265. if (!debug.enabled) return;
  16266. var self = debug;
  16267. // set `diff` timestamp
  16268. var curr = +new Date();
  16269. var ms = curr - (prevTime || curr);
  16270. self.diff = ms;
  16271. self.prev = prevTime;
  16272. self.curr = curr;
  16273. prevTime = curr;
  16274. // turn the `arguments` into a proper Array
  16275. var args = new Array(arguments.length);
  16276. for (var i = 0; i < args.length; i++) {
  16277. args[i] = arguments[i];
  16278. }
  16279. args[0] = exports.coerce(args[0]);
  16280. if ('string' !== typeof args[0]) {
  16281. // anything else let's inspect with %O
  16282. args.unshift('%O');
  16283. }
  16284. // apply any `formatters` transformations
  16285. var index = 0;
  16286. args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) {
  16287. // if we encounter an escaped % then don't increase the array index
  16288. if (match === '%%') return match;
  16289. index++;
  16290. var formatter = exports.formatters[format];
  16291. if ('function' === typeof formatter) {
  16292. var val = args[index];
  16293. match = formatter.call(self, val);
  16294. // now we need to remove `args[index]` since it's inlined in the `format`
  16295. args.splice(index, 1);
  16296. index--;
  16297. }
  16298. return match;
  16299. });
  16300. // apply env-specific formatting (colors, etc.)
  16301. exports.formatArgs.call(self, args);
  16302. var logFn = debug.log || exports.log || console.log.bind(console);
  16303. logFn.apply(self, args);
  16304. }
  16305. debug.namespace = namespace;
  16306. debug.enabled = exports.enabled(namespace);
  16307. debug.useColors = exports.useColors();
  16308. debug.color = selectColor(namespace);
  16309. // env-specific initialization logic for debug instances
  16310. if ('function' === typeof exports.init) {
  16311. exports.init(debug);
  16312. }
  16313. return debug;
  16314. }
  16315. /**
  16316. * Enables a debug mode by namespaces. This can include modes
  16317. * separated by a colon and wildcards.
  16318. *
  16319. * @param {String} namespaces
  16320. * @api public
  16321. */
  16322. function enable(namespaces) {
  16323. exports.save(namespaces);
  16324. exports.names = [];
  16325. exports.skips = [];
  16326. var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
  16327. var len = split.length;
  16328. for (var i = 0; i < len; i++) {
  16329. if (!split[i]) continue; // ignore empty strings
  16330. namespaces = split[i].replace(/\*/g, '.*?');
  16331. if (namespaces[0] === '-') {
  16332. exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
  16333. } else {
  16334. exports.names.push(new RegExp('^' + namespaces + '$'));
  16335. }
  16336. }
  16337. }
  16338. /**
  16339. * Disable debug output.
  16340. *
  16341. * @api public
  16342. */
  16343. function disable() {
  16344. exports.enable('');
  16345. }
  16346. /**
  16347. * Returns true if the given mode name is enabled, false otherwise.
  16348. *
  16349. * @param {String} name
  16350. * @return {Boolean}
  16351. * @api public
  16352. */
  16353. function enabled(name) {
  16354. var i, len;
  16355. for (i = 0, len = exports.skips.length; i < len; i++) {
  16356. if (exports.skips[i].test(name)) {
  16357. return false;
  16358. }
  16359. }
  16360. for (i = 0, len = exports.names.length; i < len; i++) {
  16361. if (exports.names[i].test(name)) {
  16362. return true;
  16363. }
  16364. }
  16365. return false;
  16366. }
  16367. /**
  16368. * Coerce `val`.
  16369. *
  16370. * @param {Mixed} val
  16371. * @return {Mixed}
  16372. * @api private
  16373. */
  16374. function coerce(val) {
  16375. if (val instanceof Error) return val.stack || val.message;
  16376. return val;
  16377. }
  16378. } (debug$a, debug$a.exports));
  16379. var debugExports = debug$a.exports;
  16380. /**
  16381. * Module dependencies.
  16382. */
  16383. (function (module, exports) {
  16384. var tty = require$$0$3;
  16385. var util = require$$1;
  16386. /**
  16387. * This is the Node.js implementation of `debug()`.
  16388. *
  16389. * Expose `debug()` as the module.
  16390. */
  16391. exports = module.exports = debugExports;
  16392. exports.init = init;
  16393. exports.log = log;
  16394. exports.formatArgs = formatArgs;
  16395. exports.save = save;
  16396. exports.load = load;
  16397. exports.useColors = useColors;
  16398. /**
  16399. * Colors.
  16400. */
  16401. exports.colors = [6, 2, 3, 4, 5, 1];
  16402. /**
  16403. * Build up the default `inspectOpts` object from the environment variables.
  16404. *
  16405. * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js
  16406. */
  16407. exports.inspectOpts = Object.keys(process.env).filter(function (key) {
  16408. return /^debug_/i.test(key);
  16409. }).reduce(function (obj, key) {
  16410. // camel-case
  16411. var prop = key
  16412. .substring(6)
  16413. .toLowerCase()
  16414. .replace(/_([a-z])/g, function (_, k) { return k.toUpperCase() });
  16415. // coerce string value into JS value
  16416. var val = process.env[key];
  16417. if (/^(yes|on|true|enabled)$/i.test(val)) val = true;
  16418. else if (/^(no|off|false|disabled)$/i.test(val)) val = false;
  16419. else if (val === 'null') val = null;
  16420. else val = Number(val);
  16421. obj[prop] = val;
  16422. return obj;
  16423. }, {});
  16424. /**
  16425. * The file descriptor to write the `debug()` calls to.
  16426. * Set the `DEBUG_FD` env variable to override with another value. i.e.:
  16427. *
  16428. * $ DEBUG_FD=3 node script.js 3>debug.log
  16429. */
  16430. var fd = parseInt(process.env.DEBUG_FD, 10) || 2;
  16431. if (1 !== fd && 2 !== fd) {
  16432. util.deprecate(function(){}, 'except for stderr(2) and stdout(1), any other usage of DEBUG_FD is deprecated. Override debug.log if you want to use a different log function (https://git.io/debug_fd)')();
  16433. }
  16434. var stream = 1 === fd ? process.stdout :
  16435. 2 === fd ? process.stderr :
  16436. createWritableStdioStream(fd);
  16437. /**
  16438. * Is stdout a TTY? Colored output is enabled when `true`.
  16439. */
  16440. function useColors() {
  16441. return 'colors' in exports.inspectOpts
  16442. ? Boolean(exports.inspectOpts.colors)
  16443. : tty.isatty(fd);
  16444. }
  16445. /**
  16446. * Map %o to `util.inspect()`, all on a single line.
  16447. */
  16448. exports.formatters.o = function(v) {
  16449. this.inspectOpts.colors = this.useColors;
  16450. return util.inspect(v, this.inspectOpts)
  16451. .split('\n').map(function(str) {
  16452. return str.trim()
  16453. }).join(' ');
  16454. };
  16455. /**
  16456. * Map %o to `util.inspect()`, allowing multiple lines if needed.
  16457. */
  16458. exports.formatters.O = function(v) {
  16459. this.inspectOpts.colors = this.useColors;
  16460. return util.inspect(v, this.inspectOpts);
  16461. };
  16462. /**
  16463. * Adds ANSI color escape codes if enabled.
  16464. *
  16465. * @api public
  16466. */
  16467. function formatArgs(args) {
  16468. var name = this.namespace;
  16469. var useColors = this.useColors;
  16470. if (useColors) {
  16471. var c = this.color;
  16472. var prefix = ' \u001b[3' + c + ';1m' + name + ' ' + '\u001b[0m';
  16473. args[0] = prefix + args[0].split('\n').join('\n' + prefix);
  16474. args.push('\u001b[3' + c + 'm+' + exports.humanize(this.diff) + '\u001b[0m');
  16475. } else {
  16476. args[0] = new Date().toUTCString()
  16477. + ' ' + name + ' ' + args[0];
  16478. }
  16479. }
  16480. /**
  16481. * Invokes `util.format()` with the specified arguments and writes to `stream`.
  16482. */
  16483. function log() {
  16484. return stream.write(util.format.apply(util, arguments) + '\n');
  16485. }
  16486. /**
  16487. * Save `namespaces`.
  16488. *
  16489. * @param {String} namespaces
  16490. * @api private
  16491. */
  16492. function save(namespaces) {
  16493. if (null == namespaces) {
  16494. // If you set a process.env field to null or undefined, it gets cast to the
  16495. // string 'null' or 'undefined'. Just delete instead.
  16496. delete process.env.DEBUG;
  16497. } else {
  16498. process.env.DEBUG = namespaces;
  16499. }
  16500. }
  16501. /**
  16502. * Load `namespaces`.
  16503. *
  16504. * @return {String} returns the previously persisted debug modes
  16505. * @api private
  16506. */
  16507. function load() {
  16508. return process.env.DEBUG;
  16509. }
  16510. /**
  16511. * Copied from `node/src/node.js`.
  16512. *
  16513. * XXX: It's lame that node doesn't expose this API out-of-the-box. It also
  16514. * relies on the undocumented `tty_wrap.guessHandleType()` which is also lame.
  16515. */
  16516. function createWritableStdioStream (fd) {
  16517. var stream;
  16518. var tty_wrap = process.binding('tty_wrap');
  16519. // Note stream._type is used for test-module-load-list.js
  16520. switch (tty_wrap.guessHandleType(fd)) {
  16521. case 'TTY':
  16522. stream = new tty.WriteStream(fd);
  16523. stream._type = 'tty';
  16524. // Hack to have stream not keep the event loop alive.
  16525. // See https://github.com/joyent/node/issues/1726
  16526. if (stream._handle && stream._handle.unref) {
  16527. stream._handle.unref();
  16528. }
  16529. break;
  16530. case 'FILE':
  16531. var fs = require$$0$4;
  16532. stream = new fs.SyncWriteStream(fd, { autoClose: false });
  16533. stream._type = 'fs';
  16534. break;
  16535. case 'PIPE':
  16536. case 'TCP':
  16537. var net = require$$4$1;
  16538. stream = new net.Socket({
  16539. fd: fd,
  16540. readable: false,
  16541. writable: true
  16542. });
  16543. // FIXME Should probably have an option in net.Socket to create a
  16544. // stream from an existing fd which is writable only. But for now
  16545. // we'll just add this hack and set the `readable` member to false.
  16546. // Test: ./node test/fixtures/echo.js < /etc/passwd
  16547. stream.readable = false;
  16548. stream.read = null;
  16549. stream._type = 'pipe';
  16550. // FIXME Hack to have stream not keep the event loop alive.
  16551. // See https://github.com/joyent/node/issues/1726
  16552. if (stream._handle && stream._handle.unref) {
  16553. stream._handle.unref();
  16554. }
  16555. break;
  16556. default:
  16557. // Probably an error on in uv_guess_handle()
  16558. throw new Error('Implement me. Unknown stream file type!');
  16559. }
  16560. // For supporting legacy API we put the FD here.
  16561. stream.fd = fd;
  16562. stream._isStdio = true;
  16563. return stream;
  16564. }
  16565. /**
  16566. * Init logic for `debug` instances.
  16567. *
  16568. * Create a new `inspectOpts` object in case `useColors` is set
  16569. * differently for a particular `debug` instance.
  16570. */
  16571. function init (debug) {
  16572. debug.inspectOpts = {};
  16573. var keys = Object.keys(exports.inspectOpts);
  16574. for (var i = 0; i < keys.length; i++) {
  16575. debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]];
  16576. }
  16577. }
  16578. /**
  16579. * Enable namespaces listed in `process.env.DEBUG` initially.
  16580. */
  16581. exports.enable(load());
  16582. } (node, node.exports));
  16583. var nodeExports = node.exports;
  16584. /*!
  16585. * encodeurl
  16586. * Copyright(c) 2016 Douglas Christopher Wilson
  16587. * MIT Licensed
  16588. */
  16589. /**
  16590. * Module exports.
  16591. * @public
  16592. */
  16593. var encodeurl = encodeUrl$1;
  16594. /**
  16595. * RegExp to match non-URL code points, *after* encoding (i.e. not including "%")
  16596. * and including invalid escape sequences.
  16597. * @private
  16598. */
  16599. 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;
  16600. /**
  16601. * RegExp to match unmatched surrogate pair.
  16602. * @private
  16603. */
  16604. var UNMATCHED_SURROGATE_PAIR_REGEXP = /(^|[^\uD800-\uDBFF])[\uDC00-\uDFFF]|[\uD800-\uDBFF]([^\uDC00-\uDFFF]|$)/g;
  16605. /**
  16606. * String to replace unmatched surrogate pair with.
  16607. * @private
  16608. */
  16609. var UNMATCHED_SURROGATE_PAIR_REPLACE = '$1\uFFFD$2';
  16610. /**
  16611. * Encode a URL to a percent-encoded form, excluding already-encoded sequences.
  16612. *
  16613. * This function will take an already-encoded URL and encode all the non-URL
  16614. * code points. This function will not encode the "%" character unless it is
  16615. * not part of a valid sequence (`%20` will be left as-is, but `%foo` will
  16616. * be encoded as `%25foo`).
  16617. *
  16618. * This encode is meant to be "safe" and does not throw errors. It will try as
  16619. * hard as it can to properly encode the given URL, including replacing any raw,
  16620. * unpaired surrogate pairs with the Unicode replacement character prior to
  16621. * encoding.
  16622. *
  16623. * @param {string} url
  16624. * @return {string}
  16625. * @public
  16626. */
  16627. function encodeUrl$1 (url) {
  16628. return String(url)
  16629. .replace(UNMATCHED_SURROGATE_PAIR_REGEXP, UNMATCHED_SURROGATE_PAIR_REPLACE)
  16630. .replace(ENCODE_CHARS_REGEXP, encodeURI)
  16631. }
  16632. /*!
  16633. * escape-html
  16634. * Copyright(c) 2012-2013 TJ Holowaychuk
  16635. * Copyright(c) 2015 Andreas Lubbe
  16636. * Copyright(c) 2015 Tiancheng "Timothy" Gu
  16637. * MIT Licensed
  16638. */
  16639. /**
  16640. * Module variables.
  16641. * @private
  16642. */
  16643. var matchHtmlRegExp = /["'&<>]/;
  16644. /**
  16645. * Module exports.
  16646. * @public
  16647. */
  16648. var escapeHtml_1 = escapeHtml$1;
  16649. /**
  16650. * Escape special characters in the given string of html.
  16651. *
  16652. * @param {string} string The string to escape for inserting into HTML
  16653. * @return {string}
  16654. * @public
  16655. */
  16656. function escapeHtml$1(string) {
  16657. var str = '' + string;
  16658. var match = matchHtmlRegExp.exec(str);
  16659. if (!match) {
  16660. return str;
  16661. }
  16662. var escape;
  16663. var html = '';
  16664. var index = 0;
  16665. var lastIndex = 0;
  16666. for (index = match.index; index < str.length; index++) {
  16667. switch (str.charCodeAt(index)) {
  16668. case 34: // "
  16669. escape = '&quot;';
  16670. break;
  16671. case 38: // &
  16672. escape = '&amp;';
  16673. break;
  16674. case 39: // '
  16675. escape = '&#39;';
  16676. break;
  16677. case 60: // <
  16678. escape = '&lt;';
  16679. break;
  16680. case 62: // >
  16681. escape = '&gt;';
  16682. break;
  16683. default:
  16684. continue;
  16685. }
  16686. if (lastIndex !== index) {
  16687. html += str.substring(lastIndex, index);
  16688. }
  16689. lastIndex = index + 1;
  16690. html += escape;
  16691. }
  16692. return lastIndex !== index
  16693. ? html + str.substring(lastIndex, index)
  16694. : html;
  16695. }
  16696. var escapeHtml$2 = /*@__PURE__*/getDefaultExportFromCjs(escapeHtml_1);
  16697. var onFinished$2 = {exports: {}};
  16698. /*!
  16699. * ee-first
  16700. * Copyright(c) 2014 Jonathan Ong
  16701. * MIT Licensed
  16702. */
  16703. /**
  16704. * Module exports.
  16705. * @public
  16706. */
  16707. var eeFirst = first$1;
  16708. /**
  16709. * Get the first event in a set of event emitters and event pairs.
  16710. *
  16711. * @param {array} stuff
  16712. * @param {function} done
  16713. * @public
  16714. */
  16715. function first$1(stuff, done) {
  16716. if (!Array.isArray(stuff))
  16717. throw new TypeError('arg must be an array of [ee, events...] arrays')
  16718. var cleanups = [];
  16719. for (var i = 0; i < stuff.length; i++) {
  16720. var arr = stuff[i];
  16721. if (!Array.isArray(arr) || arr.length < 2)
  16722. throw new TypeError('each array member must be [ee, events...]')
  16723. var ee = arr[0];
  16724. for (var j = 1; j < arr.length; j++) {
  16725. var event = arr[j];
  16726. var fn = listener(event, callback);
  16727. // listen to the event
  16728. ee.on(event, fn);
  16729. // push this listener to the list of cleanups
  16730. cleanups.push({
  16731. ee: ee,
  16732. event: event,
  16733. fn: fn,
  16734. });
  16735. }
  16736. }
  16737. function callback() {
  16738. cleanup();
  16739. done.apply(null, arguments);
  16740. }
  16741. function cleanup() {
  16742. var x;
  16743. for (var i = 0; i < cleanups.length; i++) {
  16744. x = cleanups[i];
  16745. x.ee.removeListener(x.event, x.fn);
  16746. }
  16747. }
  16748. function thunk(fn) {
  16749. done = fn;
  16750. }
  16751. thunk.cancel = cleanup;
  16752. return thunk
  16753. }
  16754. /**
  16755. * Create the event listener.
  16756. * @private
  16757. */
  16758. function listener(event, done) {
  16759. return function onevent(arg1) {
  16760. var args = new Array(arguments.length);
  16761. var ee = this;
  16762. var err = event === 'error'
  16763. ? arg1
  16764. : null;
  16765. // copy args to prevent arguments escaping scope
  16766. for (var i = 0; i < args.length; i++) {
  16767. args[i] = arguments[i];
  16768. }
  16769. done(err, ee, event, args);
  16770. }
  16771. }
  16772. /*!
  16773. * on-finished
  16774. * Copyright(c) 2013 Jonathan Ong
  16775. * Copyright(c) 2014 Douglas Christopher Wilson
  16776. * MIT Licensed
  16777. */
  16778. /**
  16779. * Module exports.
  16780. * @public
  16781. */
  16782. onFinished$2.exports = onFinished$1;
  16783. onFinished$2.exports.isFinished = isFinished$1;
  16784. /**
  16785. * Module dependencies.
  16786. * @private
  16787. */
  16788. var first = eeFirst;
  16789. /**
  16790. * Variables.
  16791. * @private
  16792. */
  16793. /* istanbul ignore next */
  16794. var defer$2 = typeof setImmediate === 'function'
  16795. ? setImmediate
  16796. : function(fn){ process.nextTick(fn.bind.apply(fn, arguments)); };
  16797. /**
  16798. * Invoke callback when the response has finished, useful for
  16799. * cleaning up resources afterwards.
  16800. *
  16801. * @param {object} msg
  16802. * @param {function} listener
  16803. * @return {object}
  16804. * @public
  16805. */
  16806. function onFinished$1(msg, listener) {
  16807. if (isFinished$1(msg) !== false) {
  16808. defer$2(listener, null, msg);
  16809. return msg
  16810. }
  16811. // attach the listener to the message
  16812. attachListener(msg, listener);
  16813. return msg
  16814. }
  16815. /**
  16816. * Determine if message is already finished.
  16817. *
  16818. * @param {object} msg
  16819. * @return {boolean}
  16820. * @public
  16821. */
  16822. function isFinished$1(msg) {
  16823. var socket = msg.socket;
  16824. if (typeof msg.finished === 'boolean') {
  16825. // OutgoingMessage
  16826. return Boolean(msg.finished || (socket && !socket.writable))
  16827. }
  16828. if (typeof msg.complete === 'boolean') {
  16829. // IncomingMessage
  16830. return Boolean(msg.upgrade || !socket || !socket.readable || (msg.complete && !msg.readable))
  16831. }
  16832. // don't know
  16833. return undefined
  16834. }
  16835. /**
  16836. * Attach a finished listener to the message.
  16837. *
  16838. * @param {object} msg
  16839. * @param {function} callback
  16840. * @private
  16841. */
  16842. function attachFinishedListener(msg, callback) {
  16843. var eeMsg;
  16844. var eeSocket;
  16845. var finished = false;
  16846. function onFinish(error) {
  16847. eeMsg.cancel();
  16848. eeSocket.cancel();
  16849. finished = true;
  16850. callback(error);
  16851. }
  16852. // finished on first message event
  16853. eeMsg = eeSocket = first([[msg, 'end', 'finish']], onFinish);
  16854. function onSocket(socket) {
  16855. // remove listener
  16856. msg.removeListener('socket', onSocket);
  16857. if (finished) return
  16858. if (eeMsg !== eeSocket) return
  16859. // finished on first socket event
  16860. eeSocket = first([[socket, 'error', 'close']], onFinish);
  16861. }
  16862. if (msg.socket) {
  16863. // socket already assigned
  16864. onSocket(msg.socket);
  16865. return
  16866. }
  16867. // wait for socket to be assigned
  16868. msg.on('socket', onSocket);
  16869. if (msg.socket === undefined) {
  16870. // node.js 0.8 patch
  16871. patchAssignSocket(msg, onSocket);
  16872. }
  16873. }
  16874. /**
  16875. * Attach the listener to the message.
  16876. *
  16877. * @param {object} msg
  16878. * @return {function}
  16879. * @private
  16880. */
  16881. function attachListener(msg, listener) {
  16882. var attached = msg.__onFinished;
  16883. // create a private single listener with queue
  16884. if (!attached || !attached.queue) {
  16885. attached = msg.__onFinished = createListener(msg);
  16886. attachFinishedListener(msg, attached);
  16887. }
  16888. attached.queue.push(listener);
  16889. }
  16890. /**
  16891. * Create listener on message.
  16892. *
  16893. * @param {object} msg
  16894. * @return {function}
  16895. * @private
  16896. */
  16897. function createListener(msg) {
  16898. function listener(err) {
  16899. if (msg.__onFinished === listener) msg.__onFinished = null;
  16900. if (!listener.queue) return
  16901. var queue = listener.queue;
  16902. listener.queue = null;
  16903. for (var i = 0; i < queue.length; i++) {
  16904. queue[i](err, msg);
  16905. }
  16906. }
  16907. listener.queue = [];
  16908. return listener
  16909. }
  16910. /**
  16911. * Patch ServerResponse.prototype.assignSocket for node.js 0.8.
  16912. *
  16913. * @param {ServerResponse} res
  16914. * @param {function} callback
  16915. * @private
  16916. */
  16917. function patchAssignSocket(res, callback) {
  16918. var assignSocket = res.assignSocket;
  16919. if (typeof assignSocket !== 'function') return
  16920. // res.on('socket', callback) is broken in 0.8
  16921. res.assignSocket = function _assignSocket(socket) {
  16922. assignSocket.call(this, socket);
  16923. callback(socket);
  16924. };
  16925. }
  16926. var onFinishedExports = onFinished$2.exports;
  16927. var parseurl$1 = {exports: {}};
  16928. /*!
  16929. * parseurl
  16930. * Copyright(c) 2014 Jonathan Ong
  16931. * Copyright(c) 2014-2017 Douglas Christopher Wilson
  16932. * MIT Licensed
  16933. */
  16934. /**
  16935. * Module dependencies.
  16936. * @private
  16937. */
  16938. var url$3 = require$$0$5;
  16939. var parse$a = url$3.parse;
  16940. var Url = url$3.Url;
  16941. /**
  16942. * Module exports.
  16943. * @public
  16944. */
  16945. parseurl$1.exports = parseurl;
  16946. parseurl$1.exports.original = originalurl;
  16947. /**
  16948. * Parse the `req` url with memoization.
  16949. *
  16950. * @param {ServerRequest} req
  16951. * @return {Object}
  16952. * @public
  16953. */
  16954. function parseurl (req) {
  16955. var url = req.url;
  16956. if (url === undefined) {
  16957. // URL is undefined
  16958. return undefined
  16959. }
  16960. var parsed = req._parsedUrl;
  16961. if (fresh(url, parsed)) {
  16962. // Return cached URL parse
  16963. return parsed
  16964. }
  16965. // Parse the URL
  16966. parsed = fastparse(url);
  16967. parsed._raw = url;
  16968. return (req._parsedUrl = parsed)
  16969. }
  16970. /**
  16971. * Parse the `req` original url with fallback and memoization.
  16972. *
  16973. * @param {ServerRequest} req
  16974. * @return {Object}
  16975. * @public
  16976. */
  16977. function originalurl (req) {
  16978. var url = req.originalUrl;
  16979. if (typeof url !== 'string') {
  16980. // Fallback
  16981. return parseurl(req)
  16982. }
  16983. var parsed = req._parsedOriginalUrl;
  16984. if (fresh(url, parsed)) {
  16985. // Return cached URL parse
  16986. return parsed
  16987. }
  16988. // Parse the URL
  16989. parsed = fastparse(url);
  16990. parsed._raw = url;
  16991. return (req._parsedOriginalUrl = parsed)
  16992. }
  16993. /**
  16994. * Parse the `str` url with fast-path short-cut.
  16995. *
  16996. * @param {string} str
  16997. * @return {Object}
  16998. * @private
  16999. */
  17000. function fastparse (str) {
  17001. if (typeof str !== 'string' || str.charCodeAt(0) !== 0x2f /* / */) {
  17002. return parse$a(str)
  17003. }
  17004. var pathname = str;
  17005. var query = null;
  17006. var search = null;
  17007. // This takes the regexp from https://github.com/joyent/node/pull/7878
  17008. // Which is /^(\/[^?#\s]*)(\?[^#\s]*)?$/
  17009. // And unrolls it into a for loop
  17010. for (var i = 1; i < str.length; i++) {
  17011. switch (str.charCodeAt(i)) {
  17012. case 0x3f: /* ? */
  17013. if (search === null) {
  17014. pathname = str.substring(0, i);
  17015. query = str.substring(i + 1);
  17016. search = str.substring(i);
  17017. }
  17018. break
  17019. case 0x09: /* \t */
  17020. case 0x0a: /* \n */
  17021. case 0x0c: /* \f */
  17022. case 0x0d: /* \r */
  17023. case 0x20: /* */
  17024. case 0x23: /* # */
  17025. case 0xa0:
  17026. case 0xfeff:
  17027. return parse$a(str)
  17028. }
  17029. }
  17030. var url = Url !== undefined
  17031. ? new Url()
  17032. : {};
  17033. url.path = str;
  17034. url.href = str;
  17035. url.pathname = pathname;
  17036. if (search !== null) {
  17037. url.query = query;
  17038. url.search = search;
  17039. }
  17040. return url
  17041. }
  17042. /**
  17043. * Determine if parsed is still fresh for url.
  17044. *
  17045. * @param {string} url
  17046. * @param {object} parsedUrl
  17047. * @return {boolean}
  17048. * @private
  17049. */
  17050. function fresh (url, parsedUrl) {
  17051. return typeof parsedUrl === 'object' &&
  17052. parsedUrl !== null &&
  17053. (Url === undefined || parsedUrl instanceof Url) &&
  17054. parsedUrl._raw === url
  17055. }
  17056. var parseurlExports = parseurl$1.exports;
  17057. var require$$0$1 = {
  17058. "100": "Continue",
  17059. "101": "Switching Protocols",
  17060. "102": "Processing",
  17061. "103": "Early Hints",
  17062. "200": "OK",
  17063. "201": "Created",
  17064. "202": "Accepted",
  17065. "203": "Non-Authoritative Information",
  17066. "204": "No Content",
  17067. "205": "Reset Content",
  17068. "206": "Partial Content",
  17069. "207": "Multi-Status",
  17070. "208": "Already Reported",
  17071. "226": "IM Used",
  17072. "300": "Multiple Choices",
  17073. "301": "Moved Permanently",
  17074. "302": "Found",
  17075. "303": "See Other",
  17076. "304": "Not Modified",
  17077. "305": "Use Proxy",
  17078. "306": "(Unused)",
  17079. "307": "Temporary Redirect",
  17080. "308": "Permanent Redirect",
  17081. "400": "Bad Request",
  17082. "401": "Unauthorized",
  17083. "402": "Payment Required",
  17084. "403": "Forbidden",
  17085. "404": "Not Found",
  17086. "405": "Method Not Allowed",
  17087. "406": "Not Acceptable",
  17088. "407": "Proxy Authentication Required",
  17089. "408": "Request Timeout",
  17090. "409": "Conflict",
  17091. "410": "Gone",
  17092. "411": "Length Required",
  17093. "412": "Precondition Failed",
  17094. "413": "Payload Too Large",
  17095. "414": "URI Too Long",
  17096. "415": "Unsupported Media Type",
  17097. "416": "Range Not Satisfiable",
  17098. "417": "Expectation Failed",
  17099. "418": "I'm a teapot",
  17100. "421": "Misdirected Request",
  17101. "422": "Unprocessable Entity",
  17102. "423": "Locked",
  17103. "424": "Failed Dependency",
  17104. "425": "Unordered Collection",
  17105. "426": "Upgrade Required",
  17106. "428": "Precondition Required",
  17107. "429": "Too Many Requests",
  17108. "431": "Request Header Fields Too Large",
  17109. "451": "Unavailable For Legal Reasons",
  17110. "500": "Internal Server Error",
  17111. "501": "Not Implemented",
  17112. "502": "Bad Gateway",
  17113. "503": "Service Unavailable",
  17114. "504": "Gateway Timeout",
  17115. "505": "HTTP Version Not Supported",
  17116. "506": "Variant Also Negotiates",
  17117. "507": "Insufficient Storage",
  17118. "508": "Loop Detected",
  17119. "509": "Bandwidth Limit Exceeded",
  17120. "510": "Not Extended",
  17121. "511": "Network Authentication Required"
  17122. };
  17123. /*!
  17124. * statuses
  17125. * Copyright(c) 2014 Jonathan Ong
  17126. * Copyright(c) 2016 Douglas Christopher Wilson
  17127. * MIT Licensed
  17128. */
  17129. /**
  17130. * Module dependencies.
  17131. * @private
  17132. */
  17133. var codes = require$$0$1;
  17134. /**
  17135. * Module exports.
  17136. * @public
  17137. */
  17138. var statuses$1 = status;
  17139. // status code to message map
  17140. status.STATUS_CODES = codes;
  17141. // array of status codes
  17142. status.codes = populateStatusesMap(status, codes);
  17143. // status codes for redirects
  17144. status.redirect = {
  17145. 300: true,
  17146. 301: true,
  17147. 302: true,
  17148. 303: true,
  17149. 305: true,
  17150. 307: true,
  17151. 308: true
  17152. };
  17153. // status codes for empty bodies
  17154. status.empty = {
  17155. 204: true,
  17156. 205: true,
  17157. 304: true
  17158. };
  17159. // status codes for when you should retry the request
  17160. status.retry = {
  17161. 502: true,
  17162. 503: true,
  17163. 504: true
  17164. };
  17165. /**
  17166. * Populate the statuses map for given codes.
  17167. * @private
  17168. */
  17169. function populateStatusesMap (statuses, codes) {
  17170. var arr = [];
  17171. Object.keys(codes).forEach(function forEachCode (code) {
  17172. var message = codes[code];
  17173. var status = Number(code);
  17174. // Populate properties
  17175. statuses[status] = message;
  17176. statuses[message] = status;
  17177. statuses[message.toLowerCase()] = status;
  17178. // Add to array
  17179. arr.push(status);
  17180. });
  17181. return arr
  17182. }
  17183. /**
  17184. * Get the status code.
  17185. *
  17186. * Given a number, this will throw if it is not a known status
  17187. * code, otherwise the code will be returned. Given a string,
  17188. * the string will be parsed for a number and return the code
  17189. * if valid, otherwise will lookup the code assuming this is
  17190. * the status message.
  17191. *
  17192. * @param {string|number} code
  17193. * @returns {number}
  17194. * @public
  17195. */
  17196. function status (code) {
  17197. if (typeof code === 'number') {
  17198. if (!status[code]) throw new Error('invalid status code: ' + code)
  17199. return code
  17200. }
  17201. if (typeof code !== 'string') {
  17202. throw new TypeError('code must be a number or string')
  17203. }
  17204. // '403'
  17205. var n = parseInt(code, 10);
  17206. if (!isNaN(n)) {
  17207. if (!status[n]) throw new Error('invalid status code: ' + n)
  17208. return n
  17209. }
  17210. n = status[code.toLowerCase()];
  17211. if (!n) throw new Error('invalid status message: "' + code + '"')
  17212. return n
  17213. }
  17214. /*!
  17215. * unpipe
  17216. * Copyright(c) 2015 Douglas Christopher Wilson
  17217. * MIT Licensed
  17218. */
  17219. /**
  17220. * Module exports.
  17221. * @public
  17222. */
  17223. var unpipe_1 = unpipe$1;
  17224. /**
  17225. * Determine if there are Node.js pipe-like data listeners.
  17226. * @private
  17227. */
  17228. function hasPipeDataListeners(stream) {
  17229. var listeners = stream.listeners('data');
  17230. for (var i = 0; i < listeners.length; i++) {
  17231. if (listeners[i].name === 'ondata') {
  17232. return true
  17233. }
  17234. }
  17235. return false
  17236. }
  17237. /**
  17238. * Unpipe a stream from all destinations.
  17239. *
  17240. * @param {object} stream
  17241. * @public
  17242. */
  17243. function unpipe$1(stream) {
  17244. if (!stream) {
  17245. throw new TypeError('argument stream is required')
  17246. }
  17247. if (typeof stream.unpipe === 'function') {
  17248. // new-style
  17249. stream.unpipe();
  17250. return
  17251. }
  17252. // Node.js 0.8 hack
  17253. if (!hasPipeDataListeners(stream)) {
  17254. return
  17255. }
  17256. var listener;
  17257. var listeners = stream.listeners('close');
  17258. for (var i = 0; i < listeners.length; i++) {
  17259. listener = listeners[i];
  17260. if (listener.name !== 'cleanup' && listener.name !== 'onclose') {
  17261. continue
  17262. }
  17263. // invoke the listener
  17264. listener.call(stream);
  17265. }
  17266. }
  17267. /*!
  17268. * finalhandler
  17269. * Copyright(c) 2014-2017 Douglas Christopher Wilson
  17270. * MIT Licensed
  17271. */
  17272. /**
  17273. * Module dependencies.
  17274. * @private
  17275. */
  17276. var debug$9 = nodeExports('finalhandler');
  17277. var encodeUrl = encodeurl;
  17278. var escapeHtml = escapeHtml_1;
  17279. var onFinished = onFinishedExports;
  17280. var parseUrl$2 = parseurlExports;
  17281. var statuses = statuses$1;
  17282. var unpipe = unpipe_1;
  17283. /**
  17284. * Module variables.
  17285. * @private
  17286. */
  17287. var DOUBLE_SPACE_REGEXP = /\x20{2}/g;
  17288. var NEWLINE_REGEXP = /\n/g;
  17289. /* istanbul ignore next */
  17290. var defer$1 = typeof setImmediate === 'function'
  17291. ? setImmediate
  17292. : function (fn) { process.nextTick(fn.bind.apply(fn, arguments)); };
  17293. var isFinished = onFinished.isFinished;
  17294. /**
  17295. * Create a minimal HTML document.
  17296. *
  17297. * @param {string} message
  17298. * @private
  17299. */
  17300. function createHtmlDocument (message) {
  17301. var body = escapeHtml(message)
  17302. .replace(NEWLINE_REGEXP, '<br>')
  17303. .replace(DOUBLE_SPACE_REGEXP, ' &nbsp;');
  17304. return '<!DOCTYPE html>\n' +
  17305. '<html lang="en">\n' +
  17306. '<head>\n' +
  17307. '<meta charset="utf-8">\n' +
  17308. '<title>Error</title>\n' +
  17309. '</head>\n' +
  17310. '<body>\n' +
  17311. '<pre>' + body + '</pre>\n' +
  17312. '</body>\n' +
  17313. '</html>\n'
  17314. }
  17315. /**
  17316. * Module exports.
  17317. * @public
  17318. */
  17319. var finalhandler_1 = finalhandler$1;
  17320. /**
  17321. * Create a function to handle the final response.
  17322. *
  17323. * @param {Request} req
  17324. * @param {Response} res
  17325. * @param {Object} [options]
  17326. * @return {Function}
  17327. * @public
  17328. */
  17329. function finalhandler$1 (req, res, options) {
  17330. var opts = options || {};
  17331. // get environment
  17332. var env = opts.env || process.env.NODE_ENV || 'development';
  17333. // get error callback
  17334. var onerror = opts.onerror;
  17335. return function (err) {
  17336. var headers;
  17337. var msg;
  17338. var status;
  17339. // ignore 404 on in-flight response
  17340. if (!err && headersSent(res)) {
  17341. debug$9('cannot 404 after headers sent');
  17342. return
  17343. }
  17344. // unhandled error
  17345. if (err) {
  17346. // respect status code from error
  17347. status = getErrorStatusCode(err);
  17348. if (status === undefined) {
  17349. // fallback to status code on response
  17350. status = getResponseStatusCode(res);
  17351. } else {
  17352. // respect headers from error
  17353. headers = getErrorHeaders(err);
  17354. }
  17355. // get error message
  17356. msg = getErrorMessage(err, status, env);
  17357. } else {
  17358. // not found
  17359. status = 404;
  17360. msg = 'Cannot ' + req.method + ' ' + encodeUrl(getResourceName(req));
  17361. }
  17362. debug$9('default %s', status);
  17363. // schedule onerror callback
  17364. if (err && onerror) {
  17365. defer$1(onerror, err, req, res);
  17366. }
  17367. // cannot actually respond
  17368. if (headersSent(res)) {
  17369. debug$9('cannot %d after headers sent', status);
  17370. req.socket.destroy();
  17371. return
  17372. }
  17373. // send response
  17374. send$2(req, res, status, headers, msg);
  17375. }
  17376. }
  17377. /**
  17378. * Get headers from Error object.
  17379. *
  17380. * @param {Error} err
  17381. * @return {object}
  17382. * @private
  17383. */
  17384. function getErrorHeaders (err) {
  17385. if (!err.headers || typeof err.headers !== 'object') {
  17386. return undefined
  17387. }
  17388. var headers = Object.create(null);
  17389. var keys = Object.keys(err.headers);
  17390. for (var i = 0; i < keys.length; i++) {
  17391. var key = keys[i];
  17392. headers[key] = err.headers[key];
  17393. }
  17394. return headers
  17395. }
  17396. /**
  17397. * Get message from Error object, fallback to status message.
  17398. *
  17399. * @param {Error} err
  17400. * @param {number} status
  17401. * @param {string} env
  17402. * @return {string}
  17403. * @private
  17404. */
  17405. function getErrorMessage (err, status, env) {
  17406. var msg;
  17407. if (env !== 'production') {
  17408. // use err.stack, which typically includes err.message
  17409. msg = err.stack;
  17410. // fallback to err.toString() when possible
  17411. if (!msg && typeof err.toString === 'function') {
  17412. msg = err.toString();
  17413. }
  17414. }
  17415. return msg || statuses[status]
  17416. }
  17417. /**
  17418. * Get status code from Error object.
  17419. *
  17420. * @param {Error} err
  17421. * @return {number}
  17422. * @private
  17423. */
  17424. function getErrorStatusCode (err) {
  17425. // check err.status
  17426. if (typeof err.status === 'number' && err.status >= 400 && err.status < 600) {
  17427. return err.status
  17428. }
  17429. // check err.statusCode
  17430. if (typeof err.statusCode === 'number' && err.statusCode >= 400 && err.statusCode < 600) {
  17431. return err.statusCode
  17432. }
  17433. return undefined
  17434. }
  17435. /**
  17436. * Get resource name for the request.
  17437. *
  17438. * This is typically just the original pathname of the request
  17439. * but will fallback to "resource" is that cannot be determined.
  17440. *
  17441. * @param {IncomingMessage} req
  17442. * @return {string}
  17443. * @private
  17444. */
  17445. function getResourceName (req) {
  17446. try {
  17447. return parseUrl$2.original(req).pathname
  17448. } catch (e) {
  17449. return 'resource'
  17450. }
  17451. }
  17452. /**
  17453. * Get status code from response.
  17454. *
  17455. * @param {OutgoingMessage} res
  17456. * @return {number}
  17457. * @private
  17458. */
  17459. function getResponseStatusCode (res) {
  17460. var status = res.statusCode;
  17461. // default status code to 500 if outside valid range
  17462. if (typeof status !== 'number' || status < 400 || status > 599) {
  17463. status = 500;
  17464. }
  17465. return status
  17466. }
  17467. /**
  17468. * Determine if the response headers have been sent.
  17469. *
  17470. * @param {object} res
  17471. * @returns {boolean}
  17472. * @private
  17473. */
  17474. function headersSent (res) {
  17475. return typeof res.headersSent !== 'boolean'
  17476. ? Boolean(res._header)
  17477. : res.headersSent
  17478. }
  17479. /**
  17480. * Send response.
  17481. *
  17482. * @param {IncomingMessage} req
  17483. * @param {OutgoingMessage} res
  17484. * @param {number} status
  17485. * @param {object} headers
  17486. * @param {string} message
  17487. * @private
  17488. */
  17489. function send$2 (req, res, status, headers, message) {
  17490. function write () {
  17491. // response body
  17492. var body = createHtmlDocument(message);
  17493. // response status
  17494. res.statusCode = status;
  17495. res.statusMessage = statuses[status];
  17496. // response headers
  17497. setHeaders(res, headers);
  17498. // security headers
  17499. res.setHeader('Content-Security-Policy', "default-src 'none'");
  17500. res.setHeader('X-Content-Type-Options', 'nosniff');
  17501. // standard headers
  17502. res.setHeader('Content-Type', 'text/html; charset=utf-8');
  17503. res.setHeader('Content-Length', Buffer.byteLength(body, 'utf8'));
  17504. if (req.method === 'HEAD') {
  17505. res.end();
  17506. return
  17507. }
  17508. res.end(body, 'utf8');
  17509. }
  17510. if (isFinished(req)) {
  17511. write();
  17512. return
  17513. }
  17514. // unpipe everything from the request
  17515. unpipe(req);
  17516. // flush the request
  17517. onFinished(req, write);
  17518. req.resume();
  17519. }
  17520. /**
  17521. * Set response headers from an object.
  17522. *
  17523. * @param {OutgoingMessage} res
  17524. * @param {object} headers
  17525. * @private
  17526. */
  17527. function setHeaders (res, headers) {
  17528. if (!headers) {
  17529. return
  17530. }
  17531. var keys = Object.keys(headers);
  17532. for (var i = 0; i < keys.length; i++) {
  17533. var key = keys[i];
  17534. res.setHeader(key, headers[key]);
  17535. }
  17536. }
  17537. var utilsMerge = {exports: {}};
  17538. /**
  17539. * Merge object b with object a.
  17540. *
  17541. * var a = { foo: 'bar' }
  17542. * , b = { bar: 'baz' };
  17543. *
  17544. * merge(a, b);
  17545. * // => { foo: 'bar', bar: 'baz' }
  17546. *
  17547. * @param {Object} a
  17548. * @param {Object} b
  17549. * @return {Object}
  17550. * @api public
  17551. */
  17552. (function (module, exports) {
  17553. module.exports = function(a, b){
  17554. if (a && b) {
  17555. for (var key in b) {
  17556. a[key] = b[key];
  17557. }
  17558. }
  17559. return a;
  17560. };
  17561. } (utilsMerge));
  17562. var utilsMergeExports = utilsMerge.exports;
  17563. /*!
  17564. * connect
  17565. * Copyright(c) 2010 Sencha Inc.
  17566. * Copyright(c) 2011 TJ Holowaychuk
  17567. * Copyright(c) 2015 Douglas Christopher Wilson
  17568. * MIT Licensed
  17569. */
  17570. /**
  17571. * Module dependencies.
  17572. * @private
  17573. */
  17574. var debug$8 = nodeExports('connect:dispatcher');
  17575. var EventEmitter$3 = require$$0$7.EventEmitter;
  17576. var finalhandler = finalhandler_1;
  17577. var http$4 = require$$1$2;
  17578. var merge = utilsMergeExports;
  17579. var parseUrl$1 = parseurlExports;
  17580. /**
  17581. * Module exports.
  17582. * @public
  17583. */
  17584. var connect = createServer$1;
  17585. /**
  17586. * Module variables.
  17587. * @private
  17588. */
  17589. var env = process.env.NODE_ENV || 'development';
  17590. var proto = {};
  17591. /* istanbul ignore next */
  17592. var defer = typeof setImmediate === 'function'
  17593. ? setImmediate
  17594. : function(fn){ process.nextTick(fn.bind.apply(fn, arguments)); };
  17595. /**
  17596. * Create a new connect server.
  17597. *
  17598. * @return {function}
  17599. * @public
  17600. */
  17601. function createServer$1() {
  17602. function app(req, res, next){ app.handle(req, res, next); }
  17603. merge(app, proto);
  17604. merge(app, EventEmitter$3.prototype);
  17605. app.route = '/';
  17606. app.stack = [];
  17607. return app;
  17608. }
  17609. /**
  17610. * Utilize the given middleware `handle` to the given `route`,
  17611. * defaulting to _/_. This "route" is the mount-point for the
  17612. * middleware, when given a value other than _/_ the middleware
  17613. * is only effective when that segment is present in the request's
  17614. * pathname.
  17615. *
  17616. * For example if we were to mount a function at _/admin_, it would
  17617. * be invoked on _/admin_, and _/admin/settings_, however it would
  17618. * not be invoked for _/_, or _/posts_.
  17619. *
  17620. * @param {String|Function|Server} route, callback or server
  17621. * @param {Function|Server} callback or server
  17622. * @return {Server} for chaining
  17623. * @public
  17624. */
  17625. proto.use = function use(route, fn) {
  17626. var handle = fn;
  17627. var path = route;
  17628. // default route to '/'
  17629. if (typeof route !== 'string') {
  17630. handle = route;
  17631. path = '/';
  17632. }
  17633. // wrap sub-apps
  17634. if (typeof handle.handle === 'function') {
  17635. var server = handle;
  17636. server.route = path;
  17637. handle = function (req, res, next) {
  17638. server.handle(req, res, next);
  17639. };
  17640. }
  17641. // wrap vanilla http.Servers
  17642. if (handle instanceof http$4.Server) {
  17643. handle = handle.listeners('request')[0];
  17644. }
  17645. // strip trailing slash
  17646. if (path[path.length - 1] === '/') {
  17647. path = path.slice(0, -1);
  17648. }
  17649. // add the middleware
  17650. debug$8('use %s %s', path || '/', handle.name || 'anonymous');
  17651. this.stack.push({ route: path, handle: handle });
  17652. return this;
  17653. };
  17654. /**
  17655. * Handle server requests, punting them down
  17656. * the middleware stack.
  17657. *
  17658. * @private
  17659. */
  17660. proto.handle = function handle(req, res, out) {
  17661. var index = 0;
  17662. var protohost = getProtohost(req.url) || '';
  17663. var removed = '';
  17664. var slashAdded = false;
  17665. var stack = this.stack;
  17666. // final function handler
  17667. var done = out || finalhandler(req, res, {
  17668. env: env,
  17669. onerror: logerror
  17670. });
  17671. // store the original URL
  17672. req.originalUrl = req.originalUrl || req.url;
  17673. function next(err) {
  17674. if (slashAdded) {
  17675. req.url = req.url.substr(1);
  17676. slashAdded = false;
  17677. }
  17678. if (removed.length !== 0) {
  17679. req.url = protohost + removed + req.url.substr(protohost.length);
  17680. removed = '';
  17681. }
  17682. // next callback
  17683. var layer = stack[index++];
  17684. // all done
  17685. if (!layer) {
  17686. defer(done, err);
  17687. return;
  17688. }
  17689. // route data
  17690. var path = parseUrl$1(req).pathname || '/';
  17691. var route = layer.route;
  17692. // skip this layer if the route doesn't match
  17693. if (path.toLowerCase().substr(0, route.length) !== route.toLowerCase()) {
  17694. return next(err);
  17695. }
  17696. // skip if route match does not border "/", ".", or end
  17697. var c = path.length > route.length && path[route.length];
  17698. if (c && c !== '/' && c !== '.') {
  17699. return next(err);
  17700. }
  17701. // trim off the part of the url that matches the route
  17702. if (route.length !== 0 && route !== '/') {
  17703. removed = route;
  17704. req.url = protohost + req.url.substr(protohost.length + removed.length);
  17705. // ensure leading slash
  17706. if (!protohost && req.url[0] !== '/') {
  17707. req.url = '/' + req.url;
  17708. slashAdded = true;
  17709. }
  17710. }
  17711. // call the layer handle
  17712. call(layer.handle, route, err, req, res, next);
  17713. }
  17714. next();
  17715. };
  17716. /**
  17717. * Listen for connections.
  17718. *
  17719. * This method takes the same arguments
  17720. * as node's `http.Server#listen()`.
  17721. *
  17722. * HTTP and HTTPS:
  17723. *
  17724. * If you run your application both as HTTP
  17725. * and HTTPS you may wrap them individually,
  17726. * since your Connect "server" is really just
  17727. * a JavaScript `Function`.
  17728. *
  17729. * var connect = require('connect')
  17730. * , http = require('http')
  17731. * , https = require('https');
  17732. *
  17733. * var app = connect();
  17734. *
  17735. * http.createServer(app).listen(80);
  17736. * https.createServer(options, app).listen(443);
  17737. *
  17738. * @return {http.Server}
  17739. * @api public
  17740. */
  17741. proto.listen = function listen() {
  17742. var server = http$4.createServer(this);
  17743. return server.listen.apply(server, arguments);
  17744. };
  17745. /**
  17746. * Invoke a route handle.
  17747. * @private
  17748. */
  17749. function call(handle, route, err, req, res, next) {
  17750. var arity = handle.length;
  17751. var error = err;
  17752. var hasError = Boolean(err);
  17753. debug$8('%s %s : %s', handle.name || '<anonymous>', route, req.originalUrl);
  17754. try {
  17755. if (hasError && arity === 4) {
  17756. // error-handling middleware
  17757. handle(err, req, res, next);
  17758. return;
  17759. } else if (!hasError && arity < 4) {
  17760. // request-handling middleware
  17761. handle(req, res, next);
  17762. return;
  17763. }
  17764. } catch (e) {
  17765. // replace the error
  17766. error = e;
  17767. }
  17768. // continue
  17769. next(error);
  17770. }
  17771. /**
  17772. * Log error using console.error.
  17773. *
  17774. * @param {Error} err
  17775. * @private
  17776. */
  17777. function logerror(err) {
  17778. if (env !== 'test') console.error(err.stack || err.toString());
  17779. }
  17780. /**
  17781. * Get get protocol + host for a URL.
  17782. *
  17783. * @param {string} url
  17784. * @private
  17785. */
  17786. function getProtohost(url) {
  17787. if (url.length === 0 || url[0] === '/') {
  17788. return undefined;
  17789. }
  17790. var fqdnIndex = url.indexOf('://');
  17791. return fqdnIndex !== -1 && url.lastIndexOf('?', fqdnIndex) === -1
  17792. ? url.substr(0, url.indexOf('/', 3 + fqdnIndex))
  17793. : undefined;
  17794. }
  17795. var connect$1 = /*@__PURE__*/getDefaultExportFromCjs(connect);
  17796. var lib = {exports: {}};
  17797. /*
  17798. object-assign
  17799. (c) Sindre Sorhus
  17800. @license MIT
  17801. */
  17802. /* eslint-disable no-unused-vars */
  17803. var getOwnPropertySymbols = Object.getOwnPropertySymbols;
  17804. var hasOwnProperty = Object.prototype.hasOwnProperty;
  17805. var propIsEnumerable = Object.prototype.propertyIsEnumerable;
  17806. function toObject(val) {
  17807. if (val === null || val === undefined) {
  17808. throw new TypeError('Object.assign cannot be called with null or undefined');
  17809. }
  17810. return Object(val);
  17811. }
  17812. function shouldUseNative() {
  17813. try {
  17814. if (!Object.assign) {
  17815. return false;
  17816. }
  17817. // Detect buggy property enumeration order in older V8 versions.
  17818. // https://bugs.chromium.org/p/v8/issues/detail?id=4118
  17819. var test1 = new String('abc'); // eslint-disable-line no-new-wrappers
  17820. test1[5] = 'de';
  17821. if (Object.getOwnPropertyNames(test1)[0] === '5') {
  17822. return false;
  17823. }
  17824. // https://bugs.chromium.org/p/v8/issues/detail?id=3056
  17825. var test2 = {};
  17826. for (var i = 0; i < 10; i++) {
  17827. test2['_' + String.fromCharCode(i)] = i;
  17828. }
  17829. var order2 = Object.getOwnPropertyNames(test2).map(function (n) {
  17830. return test2[n];
  17831. });
  17832. if (order2.join('') !== '0123456789') {
  17833. return false;
  17834. }
  17835. // https://bugs.chromium.org/p/v8/issues/detail?id=3056
  17836. var test3 = {};
  17837. 'abcdefghijklmnopqrst'.split('').forEach(function (letter) {
  17838. test3[letter] = letter;
  17839. });
  17840. if (Object.keys(Object.assign({}, test3)).join('') !==
  17841. 'abcdefghijklmnopqrst') {
  17842. return false;
  17843. }
  17844. return true;
  17845. } catch (err) {
  17846. // We don't expect any of the above to throw, but better to be safe.
  17847. return false;
  17848. }
  17849. }
  17850. var objectAssign = shouldUseNative() ? Object.assign : function (target, source) {
  17851. var from;
  17852. var to = toObject(target);
  17853. var symbols;
  17854. for (var s = 1; s < arguments.length; s++) {
  17855. from = Object(arguments[s]);
  17856. for (var key in from) {
  17857. if (hasOwnProperty.call(from, key)) {
  17858. to[key] = from[key];
  17859. }
  17860. }
  17861. if (getOwnPropertySymbols) {
  17862. symbols = getOwnPropertySymbols(from);
  17863. for (var i = 0; i < symbols.length; i++) {
  17864. if (propIsEnumerable.call(from, symbols[i])) {
  17865. to[symbols[i]] = from[symbols[i]];
  17866. }
  17867. }
  17868. }
  17869. }
  17870. return to;
  17871. };
  17872. var vary$1 = {exports: {}};
  17873. /*!
  17874. * vary
  17875. * Copyright(c) 2014-2017 Douglas Christopher Wilson
  17876. * MIT Licensed
  17877. */
  17878. /**
  17879. * Module exports.
  17880. */
  17881. vary$1.exports = vary;
  17882. vary$1.exports.append = append$1;
  17883. /**
  17884. * RegExp to match field-name in RFC 7230 sec 3.2
  17885. *
  17886. * field-name = token
  17887. * token = 1*tchar
  17888. * tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*"
  17889. * / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~"
  17890. * / DIGIT / ALPHA
  17891. * ; any VCHAR, except delimiters
  17892. */
  17893. var FIELD_NAME_REGEXP = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
  17894. /**
  17895. * Append a field to a vary header.
  17896. *
  17897. * @param {String} header
  17898. * @param {String|Array} field
  17899. * @return {String}
  17900. * @public
  17901. */
  17902. function append$1 (header, field) {
  17903. if (typeof header !== 'string') {
  17904. throw new TypeError('header argument is required')
  17905. }
  17906. if (!field) {
  17907. throw new TypeError('field argument is required')
  17908. }
  17909. // get fields array
  17910. var fields = !Array.isArray(field)
  17911. ? parse$9(String(field))
  17912. : field;
  17913. // assert on invalid field names
  17914. for (var j = 0; j < fields.length; j++) {
  17915. if (!FIELD_NAME_REGEXP.test(fields[j])) {
  17916. throw new TypeError('field argument contains an invalid header name')
  17917. }
  17918. }
  17919. // existing, unspecified vary
  17920. if (header === '*') {
  17921. return header
  17922. }
  17923. // enumerate current values
  17924. var val = header;
  17925. var vals = parse$9(header.toLowerCase());
  17926. // unspecified vary
  17927. if (fields.indexOf('*') !== -1 || vals.indexOf('*') !== -1) {
  17928. return '*'
  17929. }
  17930. for (var i = 0; i < fields.length; i++) {
  17931. var fld = fields[i].toLowerCase();
  17932. // append value (case-preserving)
  17933. if (vals.indexOf(fld) === -1) {
  17934. vals.push(fld);
  17935. val = val
  17936. ? val + ', ' + fields[i]
  17937. : fields[i];
  17938. }
  17939. }
  17940. return val
  17941. }
  17942. /**
  17943. * Parse a vary header into an array.
  17944. *
  17945. * @param {String} header
  17946. * @return {Array}
  17947. * @private
  17948. */
  17949. function parse$9 (header) {
  17950. var end = 0;
  17951. var list = [];
  17952. var start = 0;
  17953. // gather tokens
  17954. for (var i = 0, len = header.length; i < len; i++) {
  17955. switch (header.charCodeAt(i)) {
  17956. case 0x20: /* */
  17957. if (start === end) {
  17958. start = end = i + 1;
  17959. }
  17960. break
  17961. case 0x2c: /* , */
  17962. list.push(header.substring(start, end));
  17963. start = end = i + 1;
  17964. break
  17965. default:
  17966. end = i + 1;
  17967. break
  17968. }
  17969. }
  17970. // final token
  17971. list.push(header.substring(start, end));
  17972. return list
  17973. }
  17974. /**
  17975. * Mark that a request is varied on a header field.
  17976. *
  17977. * @param {Object} res
  17978. * @param {String|Array} field
  17979. * @public
  17980. */
  17981. function vary (res, field) {
  17982. if (!res || !res.getHeader || !res.setHeader) {
  17983. // quack quack
  17984. throw new TypeError('res argument is required')
  17985. }
  17986. // get existing header
  17987. var val = res.getHeader('Vary') || '';
  17988. var header = Array.isArray(val)
  17989. ? val.join(', ')
  17990. : String(val);
  17991. // set new header
  17992. if ((val = append$1(header, field))) {
  17993. res.setHeader('Vary', val);
  17994. }
  17995. }
  17996. var varyExports = vary$1.exports;
  17997. (function () {
  17998. var assign = objectAssign;
  17999. var vary = varyExports;
  18000. var defaults = {
  18001. origin: '*',
  18002. methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',
  18003. preflightContinue: false,
  18004. optionsSuccessStatus: 204
  18005. };
  18006. function isString(s) {
  18007. return typeof s === 'string' || s instanceof String;
  18008. }
  18009. function isOriginAllowed(origin, allowedOrigin) {
  18010. if (Array.isArray(allowedOrigin)) {
  18011. for (var i = 0; i < allowedOrigin.length; ++i) {
  18012. if (isOriginAllowed(origin, allowedOrigin[i])) {
  18013. return true;
  18014. }
  18015. }
  18016. return false;
  18017. } else if (isString(allowedOrigin)) {
  18018. return origin === allowedOrigin;
  18019. } else if (allowedOrigin instanceof RegExp) {
  18020. return allowedOrigin.test(origin);
  18021. } else {
  18022. return !!allowedOrigin;
  18023. }
  18024. }
  18025. function configureOrigin(options, req) {
  18026. var requestOrigin = req.headers.origin,
  18027. headers = [],
  18028. isAllowed;
  18029. if (!options.origin || options.origin === '*') {
  18030. // allow any origin
  18031. headers.push([{
  18032. key: 'Access-Control-Allow-Origin',
  18033. value: '*'
  18034. }]);
  18035. } else if (isString(options.origin)) {
  18036. // fixed origin
  18037. headers.push([{
  18038. key: 'Access-Control-Allow-Origin',
  18039. value: options.origin
  18040. }]);
  18041. headers.push([{
  18042. key: 'Vary',
  18043. value: 'Origin'
  18044. }]);
  18045. } else {
  18046. isAllowed = isOriginAllowed(requestOrigin, options.origin);
  18047. // reflect origin
  18048. headers.push([{
  18049. key: 'Access-Control-Allow-Origin',
  18050. value: isAllowed ? requestOrigin : false
  18051. }]);
  18052. headers.push([{
  18053. key: 'Vary',
  18054. value: 'Origin'
  18055. }]);
  18056. }
  18057. return headers;
  18058. }
  18059. function configureMethods(options) {
  18060. var methods = options.methods;
  18061. if (methods.join) {
  18062. methods = options.methods.join(','); // .methods is an array, so turn it into a string
  18063. }
  18064. return {
  18065. key: 'Access-Control-Allow-Methods',
  18066. value: methods
  18067. };
  18068. }
  18069. function configureCredentials(options) {
  18070. if (options.credentials === true) {
  18071. return {
  18072. key: 'Access-Control-Allow-Credentials',
  18073. value: 'true'
  18074. };
  18075. }
  18076. return null;
  18077. }
  18078. function configureAllowedHeaders(options, req) {
  18079. var allowedHeaders = options.allowedHeaders || options.headers;
  18080. var headers = [];
  18081. if (!allowedHeaders) {
  18082. allowedHeaders = req.headers['access-control-request-headers']; // .headers wasn't specified, so reflect the request headers
  18083. headers.push([{
  18084. key: 'Vary',
  18085. value: 'Access-Control-Request-Headers'
  18086. }]);
  18087. } else if (allowedHeaders.join) {
  18088. allowedHeaders = allowedHeaders.join(','); // .headers is an array, so turn it into a string
  18089. }
  18090. if (allowedHeaders && allowedHeaders.length) {
  18091. headers.push([{
  18092. key: 'Access-Control-Allow-Headers',
  18093. value: allowedHeaders
  18094. }]);
  18095. }
  18096. return headers;
  18097. }
  18098. function configureExposedHeaders(options) {
  18099. var headers = options.exposedHeaders;
  18100. if (!headers) {
  18101. return null;
  18102. } else if (headers.join) {
  18103. headers = headers.join(','); // .headers is an array, so turn it into a string
  18104. }
  18105. if (headers && headers.length) {
  18106. return {
  18107. key: 'Access-Control-Expose-Headers',
  18108. value: headers
  18109. };
  18110. }
  18111. return null;
  18112. }
  18113. function configureMaxAge(options) {
  18114. var maxAge = (typeof options.maxAge === 'number' || options.maxAge) && options.maxAge.toString();
  18115. if (maxAge && maxAge.length) {
  18116. return {
  18117. key: 'Access-Control-Max-Age',
  18118. value: maxAge
  18119. };
  18120. }
  18121. return null;
  18122. }
  18123. function applyHeaders(headers, res) {
  18124. for (var i = 0, n = headers.length; i < n; i++) {
  18125. var header = headers[i];
  18126. if (header) {
  18127. if (Array.isArray(header)) {
  18128. applyHeaders(header, res);
  18129. } else if (header.key === 'Vary' && header.value) {
  18130. vary(res, header.value);
  18131. } else if (header.value) {
  18132. res.setHeader(header.key, header.value);
  18133. }
  18134. }
  18135. }
  18136. }
  18137. function cors(options, req, res, next) {
  18138. var headers = [],
  18139. method = req.method && req.method.toUpperCase && req.method.toUpperCase();
  18140. if (method === 'OPTIONS') {
  18141. // preflight
  18142. headers.push(configureOrigin(options, req));
  18143. headers.push(configureCredentials(options));
  18144. headers.push(configureMethods(options));
  18145. headers.push(configureAllowedHeaders(options, req));
  18146. headers.push(configureMaxAge(options));
  18147. headers.push(configureExposedHeaders(options));
  18148. applyHeaders(headers, res);
  18149. if (options.preflightContinue) {
  18150. next();
  18151. } else {
  18152. // Safari (and potentially other browsers) need content-length 0,
  18153. // for 204 or they just hang waiting for a body
  18154. res.statusCode = options.optionsSuccessStatus;
  18155. res.setHeader('Content-Length', '0');
  18156. res.end();
  18157. }
  18158. } else {
  18159. // actual response
  18160. headers.push(configureOrigin(options, req));
  18161. headers.push(configureCredentials(options));
  18162. headers.push(configureExposedHeaders(options));
  18163. applyHeaders(headers, res);
  18164. next();
  18165. }
  18166. }
  18167. function middlewareWrapper(o) {
  18168. // if options are static (either via defaults or custom options passed in), wrap in a function
  18169. var optionsCallback = null;
  18170. if (typeof o === 'function') {
  18171. optionsCallback = o;
  18172. } else {
  18173. optionsCallback = function (req, cb) {
  18174. cb(null, o);
  18175. };
  18176. }
  18177. return function corsMiddleware(req, res, next) {
  18178. optionsCallback(req, function (err, options) {
  18179. if (err) {
  18180. next(err);
  18181. } else {
  18182. var corsOptions = assign({}, defaults, options);
  18183. var originCallback = null;
  18184. if (corsOptions.origin && typeof corsOptions.origin === 'function') {
  18185. originCallback = corsOptions.origin;
  18186. } else if (corsOptions.origin) {
  18187. originCallback = function (origin, cb) {
  18188. cb(null, corsOptions.origin);
  18189. };
  18190. }
  18191. if (originCallback) {
  18192. originCallback(req.headers.origin, function (err2, origin) {
  18193. if (err2 || !origin) {
  18194. next(err2);
  18195. } else {
  18196. corsOptions.origin = origin;
  18197. cors(corsOptions, req, res, next);
  18198. }
  18199. });
  18200. } else {
  18201. next();
  18202. }
  18203. }
  18204. });
  18205. };
  18206. }
  18207. // can pass either an options hash, an options delegate, or nothing
  18208. lib.exports = middlewareWrapper;
  18209. }());
  18210. var libExports = lib.exports;
  18211. var corsMiddleware = /*@__PURE__*/getDefaultExportFromCjs(libExports);
  18212. var chokidar = {};
  18213. const fs$5 = require$$0$4;
  18214. const { Readable } = require$$0$8;
  18215. const sysPath$3 = require$$0$2;
  18216. const { promisify: promisify$3 } = require$$1;
  18217. const picomatch$1 = picomatch$2;
  18218. const readdir$1 = promisify$3(fs$5.readdir);
  18219. const stat$3 = promisify$3(fs$5.stat);
  18220. const lstat$2 = promisify$3(fs$5.lstat);
  18221. const realpath$1 = promisify$3(fs$5.realpath);
  18222. /**
  18223. * @typedef {Object} EntryInfo
  18224. * @property {String} path
  18225. * @property {String} fullPath
  18226. * @property {fs.Stats=} stats
  18227. * @property {fs.Dirent=} dirent
  18228. * @property {String} basename
  18229. */
  18230. const BANG$2 = '!';
  18231. const RECURSIVE_ERROR_CODE = 'READDIRP_RECURSIVE_ERROR';
  18232. const NORMAL_FLOW_ERRORS = new Set(['ENOENT', 'EPERM', 'EACCES', 'ELOOP', RECURSIVE_ERROR_CODE]);
  18233. const FILE_TYPE = 'files';
  18234. const DIR_TYPE = 'directories';
  18235. const FILE_DIR_TYPE = 'files_directories';
  18236. const EVERYTHING_TYPE = 'all';
  18237. const ALL_TYPES = [FILE_TYPE, DIR_TYPE, FILE_DIR_TYPE, EVERYTHING_TYPE];
  18238. const isNormalFlowError = error => NORMAL_FLOW_ERRORS.has(error.code);
  18239. const [maj, min] = process.versions.node.split('.').slice(0, 2).map(n => Number.parseInt(n, 10));
  18240. const wantBigintFsStats = process.platform === 'win32' && (maj > 10 || (maj === 10 && min >= 5));
  18241. const normalizeFilter$1 = filter => {
  18242. if (filter === undefined) return;
  18243. if (typeof filter === 'function') return filter;
  18244. if (typeof filter === 'string') {
  18245. const glob = picomatch$1(filter.trim());
  18246. return entry => glob(entry.basename);
  18247. }
  18248. if (Array.isArray(filter)) {
  18249. const positive = [];
  18250. const negative = [];
  18251. for (const item of filter) {
  18252. const trimmed = item.trim();
  18253. if (trimmed.charAt(0) === BANG$2) {
  18254. negative.push(picomatch$1(trimmed.slice(1)));
  18255. } else {
  18256. positive.push(picomatch$1(trimmed));
  18257. }
  18258. }
  18259. if (negative.length > 0) {
  18260. if (positive.length > 0) {
  18261. return entry =>
  18262. positive.some(f => f(entry.basename)) && !negative.some(f => f(entry.basename));
  18263. }
  18264. return entry => !negative.some(f => f(entry.basename));
  18265. }
  18266. return entry => positive.some(f => f(entry.basename));
  18267. }
  18268. };
  18269. class ReaddirpStream extends Readable {
  18270. static get defaultOptions() {
  18271. return {
  18272. root: '.',
  18273. /* eslint-disable no-unused-vars */
  18274. fileFilter: (path) => true,
  18275. directoryFilter: (path) => true,
  18276. /* eslint-enable no-unused-vars */
  18277. type: FILE_TYPE,
  18278. lstat: false,
  18279. depth: 2147483648,
  18280. alwaysStat: false
  18281. };
  18282. }
  18283. constructor(options = {}) {
  18284. super({
  18285. objectMode: true,
  18286. autoDestroy: true,
  18287. highWaterMark: options.highWaterMark || 4096
  18288. });
  18289. const opts = { ...ReaddirpStream.defaultOptions, ...options };
  18290. const { root, type } = opts;
  18291. this._fileFilter = normalizeFilter$1(opts.fileFilter);
  18292. this._directoryFilter = normalizeFilter$1(opts.directoryFilter);
  18293. const statMethod = opts.lstat ? lstat$2 : stat$3;
  18294. // Use bigint stats if it's windows and stat() supports options (node 10+).
  18295. if (wantBigintFsStats) {
  18296. this._stat = path => statMethod(path, { bigint: true });
  18297. } else {
  18298. this._stat = statMethod;
  18299. }
  18300. this._maxDepth = opts.depth;
  18301. this._wantsDir = [DIR_TYPE, FILE_DIR_TYPE, EVERYTHING_TYPE].includes(type);
  18302. this._wantsFile = [FILE_TYPE, FILE_DIR_TYPE, EVERYTHING_TYPE].includes(type);
  18303. this._wantsEverything = type === EVERYTHING_TYPE;
  18304. this._root = sysPath$3.resolve(root);
  18305. this._isDirent = ('Dirent' in fs$5) && !opts.alwaysStat;
  18306. this._statsProp = this._isDirent ? 'dirent' : 'stats';
  18307. this._rdOptions = { encoding: 'utf8', withFileTypes: this._isDirent };
  18308. // Launch stream with one parent, the root dir.
  18309. this.parents = [this._exploreDir(root, 1)];
  18310. this.reading = false;
  18311. this.parent = undefined;
  18312. }
  18313. async _read(batch) {
  18314. if (this.reading) return;
  18315. this.reading = true;
  18316. try {
  18317. while (!this.destroyed && batch > 0) {
  18318. const { path, depth, files = [] } = this.parent || {};
  18319. if (files.length > 0) {
  18320. const slice = files.splice(0, batch).map(dirent => this._formatEntry(dirent, path));
  18321. for (const entry of await Promise.all(slice)) {
  18322. if (this.destroyed) return;
  18323. const entryType = await this._getEntryType(entry);
  18324. if (entryType === 'directory' && this._directoryFilter(entry)) {
  18325. if (depth <= this._maxDepth) {
  18326. this.parents.push(this._exploreDir(entry.fullPath, depth + 1));
  18327. }
  18328. if (this._wantsDir) {
  18329. this.push(entry);
  18330. batch--;
  18331. }
  18332. } else if ((entryType === 'file' || this._includeAsFile(entry)) && this._fileFilter(entry)) {
  18333. if (this._wantsFile) {
  18334. this.push(entry);
  18335. batch--;
  18336. }
  18337. }
  18338. }
  18339. } else {
  18340. const parent = this.parents.pop();
  18341. if (!parent) {
  18342. this.push(null);
  18343. break;
  18344. }
  18345. this.parent = await parent;
  18346. if (this.destroyed) return;
  18347. }
  18348. }
  18349. } catch (error) {
  18350. this.destroy(error);
  18351. } finally {
  18352. this.reading = false;
  18353. }
  18354. }
  18355. async _exploreDir(path, depth) {
  18356. let files;
  18357. try {
  18358. files = await readdir$1(path, this._rdOptions);
  18359. } catch (error) {
  18360. this._onError(error);
  18361. }
  18362. return { files, depth, path };
  18363. }
  18364. async _formatEntry(dirent, path) {
  18365. let entry;
  18366. try {
  18367. const basename = this._isDirent ? dirent.name : dirent;
  18368. const fullPath = sysPath$3.resolve(sysPath$3.join(path, basename));
  18369. entry = { path: sysPath$3.relative(this._root, fullPath), fullPath, basename };
  18370. entry[this._statsProp] = this._isDirent ? dirent : await this._stat(fullPath);
  18371. } catch (err) {
  18372. this._onError(err);
  18373. }
  18374. return entry;
  18375. }
  18376. _onError(err) {
  18377. if (isNormalFlowError(err) && !this.destroyed) {
  18378. this.emit('warn', err);
  18379. } else {
  18380. this.destroy(err);
  18381. }
  18382. }
  18383. async _getEntryType(entry) {
  18384. // entry may be undefined, because a warning or an error were emitted
  18385. // and the statsProp is undefined
  18386. const stats = entry && entry[this._statsProp];
  18387. if (!stats) {
  18388. return;
  18389. }
  18390. if (stats.isFile()) {
  18391. return 'file';
  18392. }
  18393. if (stats.isDirectory()) {
  18394. return 'directory';
  18395. }
  18396. if (stats && stats.isSymbolicLink()) {
  18397. const full = entry.fullPath;
  18398. try {
  18399. const entryRealPath = await realpath$1(full);
  18400. const entryRealPathStats = await lstat$2(entryRealPath);
  18401. if (entryRealPathStats.isFile()) {
  18402. return 'file';
  18403. }
  18404. if (entryRealPathStats.isDirectory()) {
  18405. const len = entryRealPath.length;
  18406. if (full.startsWith(entryRealPath) && full.substr(len, 1) === sysPath$3.sep) {
  18407. const recursiveError = new Error(
  18408. `Circular symlink detected: "${full}" points to "${entryRealPath}"`
  18409. );
  18410. recursiveError.code = RECURSIVE_ERROR_CODE;
  18411. return this._onError(recursiveError);
  18412. }
  18413. return 'directory';
  18414. }
  18415. } catch (error) {
  18416. this._onError(error);
  18417. }
  18418. }
  18419. }
  18420. _includeAsFile(entry) {
  18421. const stats = entry && entry[this._statsProp];
  18422. return stats && this._wantsEverything && !stats.isDirectory();
  18423. }
  18424. }
  18425. /**
  18426. * @typedef {Object} ReaddirpArguments
  18427. * @property {Function=} fileFilter
  18428. * @property {Function=} directoryFilter
  18429. * @property {String=} type
  18430. * @property {Number=} depth
  18431. * @property {String=} root
  18432. * @property {Boolean=} lstat
  18433. * @property {Boolean=} bigint
  18434. */
  18435. /**
  18436. * Main function which ends up calling readdirRec and reads all files and directories in given root recursively.
  18437. * @param {String} root Root directory
  18438. * @param {ReaddirpArguments=} options Options to specify root (start directory), filters and recursion depth
  18439. */
  18440. const readdirp$1 = (root, options = {}) => {
  18441. let type = options.entryType || options.type;
  18442. if (type === 'both') type = FILE_DIR_TYPE; // backwards-compatibility
  18443. if (type) options.type = type;
  18444. if (!root) {
  18445. throw new Error('readdirp: root argument is required. Usage: readdirp(root, options)');
  18446. } else if (typeof root !== 'string') {
  18447. throw new TypeError('readdirp: root argument must be a string. Usage: readdirp(root, options)');
  18448. } else if (type && !ALL_TYPES.includes(type)) {
  18449. throw new Error(`readdirp: Invalid type passed. Use one of ${ALL_TYPES.join(', ')}`);
  18450. }
  18451. options.root = root;
  18452. return new ReaddirpStream(options);
  18453. };
  18454. const readdirpPromise = (root, options = {}) => {
  18455. return new Promise((resolve, reject) => {
  18456. const files = [];
  18457. readdirp$1(root, options)
  18458. .on('data', entry => files.push(entry))
  18459. .on('end', () => resolve(files))
  18460. .on('error', error => reject(error));
  18461. });
  18462. };
  18463. readdirp$1.promise = readdirpPromise;
  18464. readdirp$1.ReaddirpStream = ReaddirpStream;
  18465. readdirp$1.default = readdirp$1;
  18466. var readdirp_1 = readdirp$1;
  18467. var anymatch$2 = {exports: {}};
  18468. /*!
  18469. * normalize-path <https://github.com/jonschlinkert/normalize-path>
  18470. *
  18471. * Copyright (c) 2014-2018, Jon Schlinkert.
  18472. * Released under the MIT License.
  18473. */
  18474. var normalizePath$2 = function(path, stripTrailing) {
  18475. if (typeof path !== 'string') {
  18476. throw new TypeError('expected path to be a string');
  18477. }
  18478. if (path === '\\' || path === '/') return '/';
  18479. var len = path.length;
  18480. if (len <= 1) return path;
  18481. // ensure that win32 namespaces has two leading slashes, so that the path is
  18482. // handled properly by the win32 version of path.parse() after being normalized
  18483. // https://msdn.microsoft.com/library/windows/desktop/aa365247(v=vs.85).aspx#namespaces
  18484. var prefix = '';
  18485. if (len > 4 && path[3] === '\\') {
  18486. var ch = path[2];
  18487. if ((ch === '?' || ch === '.') && path.slice(0, 2) === '\\\\') {
  18488. path = path.slice(2);
  18489. prefix = '//';
  18490. }
  18491. }
  18492. var segs = path.split(/[/\\]+/);
  18493. if (stripTrailing !== false && segs[segs.length - 1] === '') {
  18494. segs.pop();
  18495. }
  18496. return prefix + segs.join('/');
  18497. };
  18498. var anymatch_1 = anymatch$2.exports;
  18499. Object.defineProperty(anymatch_1, "__esModule", { value: true });
  18500. const picomatch = picomatch$2;
  18501. const normalizePath$1 = normalizePath$2;
  18502. /**
  18503. * @typedef {(testString: string) => boolean} AnymatchFn
  18504. * @typedef {string|RegExp|AnymatchFn} AnymatchPattern
  18505. * @typedef {AnymatchPattern|AnymatchPattern[]} AnymatchMatcher
  18506. */
  18507. const BANG$1 = '!';
  18508. const DEFAULT_OPTIONS = {returnIndex: false};
  18509. const arrify$1 = (item) => Array.isArray(item) ? item : [item];
  18510. /**
  18511. * @param {AnymatchPattern} matcher
  18512. * @param {object} options
  18513. * @returns {AnymatchFn}
  18514. */
  18515. const createPattern = (matcher, options) => {
  18516. if (typeof matcher === 'function') {
  18517. return matcher;
  18518. }
  18519. if (typeof matcher === 'string') {
  18520. const glob = picomatch(matcher, options);
  18521. return (string) => matcher === string || glob(string);
  18522. }
  18523. if (matcher instanceof RegExp) {
  18524. return (string) => matcher.test(string);
  18525. }
  18526. return (string) => false;
  18527. };
  18528. /**
  18529. * @param {Array<Function>} patterns
  18530. * @param {Array<Function>} negPatterns
  18531. * @param {String|Array} args
  18532. * @param {Boolean} returnIndex
  18533. * @returns {boolean|number}
  18534. */
  18535. const matchPatterns = (patterns, negPatterns, args, returnIndex) => {
  18536. const isList = Array.isArray(args);
  18537. const _path = isList ? args[0] : args;
  18538. if (!isList && typeof _path !== 'string') {
  18539. throw new TypeError('anymatch: second argument must be a string: got ' +
  18540. Object.prototype.toString.call(_path))
  18541. }
  18542. const path = normalizePath$1(_path, false);
  18543. for (let index = 0; index < negPatterns.length; index++) {
  18544. const nglob = negPatterns[index];
  18545. if (nglob(path)) {
  18546. return returnIndex ? -1 : false;
  18547. }
  18548. }
  18549. const applied = isList && [path].concat(args.slice(1));
  18550. for (let index = 0; index < patterns.length; index++) {
  18551. const pattern = patterns[index];
  18552. if (isList ? pattern(...applied) : pattern(path)) {
  18553. return returnIndex ? index : true;
  18554. }
  18555. }
  18556. return returnIndex ? -1 : false;
  18557. };
  18558. /**
  18559. * @param {AnymatchMatcher} matchers
  18560. * @param {Array|string} testString
  18561. * @param {object} options
  18562. * @returns {boolean|number|Function}
  18563. */
  18564. const anymatch$1 = (matchers, testString, options = DEFAULT_OPTIONS) => {
  18565. if (matchers == null) {
  18566. throw new TypeError('anymatch: specify first argument');
  18567. }
  18568. const opts = typeof options === 'boolean' ? {returnIndex: options} : options;
  18569. const returnIndex = opts.returnIndex || false;
  18570. // Early cache for matchers.
  18571. const mtchers = arrify$1(matchers);
  18572. const negatedGlobs = mtchers
  18573. .filter(item => typeof item === 'string' && item.charAt(0) === BANG$1)
  18574. .map(item => item.slice(1))
  18575. .map(item => picomatch(item, opts));
  18576. const patterns = mtchers
  18577. .filter(item => typeof item !== 'string' || (typeof item === 'string' && item.charAt(0) !== BANG$1))
  18578. .map(matcher => createPattern(matcher, opts));
  18579. if (testString == null) {
  18580. return (testString, ri = false) => {
  18581. const returnIndex = typeof ri === 'boolean' ? ri : false;
  18582. return matchPatterns(patterns, negatedGlobs, testString, returnIndex);
  18583. }
  18584. }
  18585. return matchPatterns(patterns, negatedGlobs, testString, returnIndex);
  18586. };
  18587. anymatch$1.default = anymatch$1;
  18588. anymatch$2.exports = anymatch$1;
  18589. var anymatchExports = anymatch$2.exports;
  18590. /*!
  18591. * is-extglob <https://github.com/jonschlinkert/is-extglob>
  18592. *
  18593. * Copyright (c) 2014-2016, Jon Schlinkert.
  18594. * Licensed under the MIT License.
  18595. */
  18596. var isExtglob$1 = function isExtglob(str) {
  18597. if (typeof str !== 'string' || str === '') {
  18598. return false;
  18599. }
  18600. var match;
  18601. while ((match = /(\\).|([@?!+*]\(.*\))/g.exec(str))) {
  18602. if (match[2]) return true;
  18603. str = str.slice(match.index + match[0].length);
  18604. }
  18605. return false;
  18606. };
  18607. /*!
  18608. * is-glob <https://github.com/jonschlinkert/is-glob>
  18609. *
  18610. * Copyright (c) 2014-2017, Jon Schlinkert.
  18611. * Released under the MIT License.
  18612. */
  18613. var isExtglob = isExtglob$1;
  18614. var chars = { '{': '}', '(': ')', '[': ']'};
  18615. var strictCheck = function(str) {
  18616. if (str[0] === '!') {
  18617. return true;
  18618. }
  18619. var index = 0;
  18620. var pipeIndex = -2;
  18621. var closeSquareIndex = -2;
  18622. var closeCurlyIndex = -2;
  18623. var closeParenIndex = -2;
  18624. var backSlashIndex = -2;
  18625. while (index < str.length) {
  18626. if (str[index] === '*') {
  18627. return true;
  18628. }
  18629. if (str[index + 1] === '?' && /[\].+)]/.test(str[index])) {
  18630. return true;
  18631. }
  18632. if (closeSquareIndex !== -1 && str[index] === '[' && str[index + 1] !== ']') {
  18633. if (closeSquareIndex < index) {
  18634. closeSquareIndex = str.indexOf(']', index);
  18635. }
  18636. if (closeSquareIndex > index) {
  18637. if (backSlashIndex === -1 || backSlashIndex > closeSquareIndex) {
  18638. return true;
  18639. }
  18640. backSlashIndex = str.indexOf('\\', index);
  18641. if (backSlashIndex === -1 || backSlashIndex > closeSquareIndex) {
  18642. return true;
  18643. }
  18644. }
  18645. }
  18646. if (closeCurlyIndex !== -1 && str[index] === '{' && str[index + 1] !== '}') {
  18647. closeCurlyIndex = str.indexOf('}', index);
  18648. if (closeCurlyIndex > index) {
  18649. backSlashIndex = str.indexOf('\\', index);
  18650. if (backSlashIndex === -1 || backSlashIndex > closeCurlyIndex) {
  18651. return true;
  18652. }
  18653. }
  18654. }
  18655. if (closeParenIndex !== -1 && str[index] === '(' && str[index + 1] === '?' && /[:!=]/.test(str[index + 2]) && str[index + 3] !== ')') {
  18656. closeParenIndex = str.indexOf(')', index);
  18657. if (closeParenIndex > index) {
  18658. backSlashIndex = str.indexOf('\\', index);
  18659. if (backSlashIndex === -1 || backSlashIndex > closeParenIndex) {
  18660. return true;
  18661. }
  18662. }
  18663. }
  18664. if (pipeIndex !== -1 && str[index] === '(' && str[index + 1] !== '|') {
  18665. if (pipeIndex < index) {
  18666. pipeIndex = str.indexOf('|', index);
  18667. }
  18668. if (pipeIndex !== -1 && str[pipeIndex + 1] !== ')') {
  18669. closeParenIndex = str.indexOf(')', pipeIndex);
  18670. if (closeParenIndex > pipeIndex) {
  18671. backSlashIndex = str.indexOf('\\', pipeIndex);
  18672. if (backSlashIndex === -1 || backSlashIndex > closeParenIndex) {
  18673. return true;
  18674. }
  18675. }
  18676. }
  18677. }
  18678. if (str[index] === '\\') {
  18679. var open = str[index + 1];
  18680. index += 2;
  18681. var close = chars[open];
  18682. if (close) {
  18683. var n = str.indexOf(close, index);
  18684. if (n !== -1) {
  18685. index = n + 1;
  18686. }
  18687. }
  18688. if (str[index] === '!') {
  18689. return true;
  18690. }
  18691. } else {
  18692. index++;
  18693. }
  18694. }
  18695. return false;
  18696. };
  18697. var relaxedCheck = function(str) {
  18698. if (str[0] === '!') {
  18699. return true;
  18700. }
  18701. var index = 0;
  18702. while (index < str.length) {
  18703. if (/[*?{}()[\]]/.test(str[index])) {
  18704. return true;
  18705. }
  18706. if (str[index] === '\\') {
  18707. var open = str[index + 1];
  18708. index += 2;
  18709. var close = chars[open];
  18710. if (close) {
  18711. var n = str.indexOf(close, index);
  18712. if (n !== -1) {
  18713. index = n + 1;
  18714. }
  18715. }
  18716. if (str[index] === '!') {
  18717. return true;
  18718. }
  18719. } else {
  18720. index++;
  18721. }
  18722. }
  18723. return false;
  18724. };
  18725. var isGlob$2 = function isGlob(str, options) {
  18726. if (typeof str !== 'string' || str === '') {
  18727. return false;
  18728. }
  18729. if (isExtglob(str)) {
  18730. return true;
  18731. }
  18732. var check = strictCheck;
  18733. // optionally relax check
  18734. if (options && options.strict === false) {
  18735. check = relaxedCheck;
  18736. }
  18737. return check(str);
  18738. };
  18739. var isGlob$1 = isGlob$2;
  18740. var pathPosixDirname = require$$0$2.posix.dirname;
  18741. var isWin32 = require$$2.platform() === 'win32';
  18742. var slash = '/';
  18743. var backslash = /\\/g;
  18744. var enclosure = /[\{\[].*[\}\]]$/;
  18745. var globby = /(^|[^\\])([\{\[]|\([^\)]+$)/;
  18746. var escaped = /\\([\!\*\?\|\[\]\(\)\{\}])/g;
  18747. /**
  18748. * @param {string} str
  18749. * @param {Object} opts
  18750. * @param {boolean} [opts.flipBackslashes=true]
  18751. * @returns {string}
  18752. */
  18753. var globParent$1 = function globParent(str, opts) {
  18754. var options = Object.assign({ flipBackslashes: true }, opts);
  18755. // flip windows path separators
  18756. if (options.flipBackslashes && isWin32 && str.indexOf(slash) < 0) {
  18757. str = str.replace(backslash, slash);
  18758. }
  18759. // special case for strings ending in enclosure containing path separator
  18760. if (enclosure.test(str)) {
  18761. str += slash;
  18762. }
  18763. // preserves full path in case of trailing path separator
  18764. str += 'a';
  18765. // remove path parts that are globby
  18766. do {
  18767. str = pathPosixDirname(str);
  18768. } while (isGlob$1(str) || globby.test(str));
  18769. // remove escape chars and return result
  18770. return str.replace(escaped, '$1');
  18771. };
  18772. var utils$3 = {};
  18773. (function (exports) {
  18774. exports.isInteger = num => {
  18775. if (typeof num === 'number') {
  18776. return Number.isInteger(num);
  18777. }
  18778. if (typeof num === 'string' && num.trim() !== '') {
  18779. return Number.isInteger(Number(num));
  18780. }
  18781. return false;
  18782. };
  18783. /**
  18784. * Find a node of the given type
  18785. */
  18786. exports.find = (node, type) => node.nodes.find(node => node.type === type);
  18787. /**
  18788. * Find a node of the given type
  18789. */
  18790. exports.exceedsLimit = (min, max, step = 1, limit) => {
  18791. if (limit === false) return false;
  18792. if (!exports.isInteger(min) || !exports.isInteger(max)) return false;
  18793. return ((Number(max) - Number(min)) / Number(step)) >= limit;
  18794. };
  18795. /**
  18796. * Escape the given node with '\\' before node.value
  18797. */
  18798. exports.escapeNode = (block, n = 0, type) => {
  18799. const node = block.nodes[n];
  18800. if (!node) return;
  18801. if ((type && node.type === type) || node.type === 'open' || node.type === 'close') {
  18802. if (node.escaped !== true) {
  18803. node.value = '\\' + node.value;
  18804. node.escaped = true;
  18805. }
  18806. }
  18807. };
  18808. /**
  18809. * Returns true if the given brace node should be enclosed in literal braces
  18810. */
  18811. exports.encloseBrace = node => {
  18812. if (node.type !== 'brace') return false;
  18813. if ((node.commas >> 0 + node.ranges >> 0) === 0) {
  18814. node.invalid = true;
  18815. return true;
  18816. }
  18817. return false;
  18818. };
  18819. /**
  18820. * Returns true if a brace node is invalid.
  18821. */
  18822. exports.isInvalidBrace = block => {
  18823. if (block.type !== 'brace') return false;
  18824. if (block.invalid === true || block.dollar) return true;
  18825. if ((block.commas >> 0 + block.ranges >> 0) === 0) {
  18826. block.invalid = true;
  18827. return true;
  18828. }
  18829. if (block.open !== true || block.close !== true) {
  18830. block.invalid = true;
  18831. return true;
  18832. }
  18833. return false;
  18834. };
  18835. /**
  18836. * Returns true if a node is an open or close node
  18837. */
  18838. exports.isOpenOrClose = node => {
  18839. if (node.type === 'open' || node.type === 'close') {
  18840. return true;
  18841. }
  18842. return node.open === true || node.close === true;
  18843. };
  18844. /**
  18845. * Reduce an array of text nodes.
  18846. */
  18847. exports.reduce = nodes => nodes.reduce((acc, node) => {
  18848. if (node.type === 'text') acc.push(node.value);
  18849. if (node.type === 'range') node.type = 'text';
  18850. return acc;
  18851. }, []);
  18852. /**
  18853. * Flatten an array
  18854. */
  18855. exports.flatten = (...args) => {
  18856. const result = [];
  18857. const flat = arr => {
  18858. for (let i = 0; i < arr.length; i++) {
  18859. const ele = arr[i];
  18860. if (Array.isArray(ele)) {
  18861. flat(ele);
  18862. continue;
  18863. }
  18864. if (ele !== undefined) {
  18865. result.push(ele);
  18866. }
  18867. }
  18868. return result;
  18869. };
  18870. flat(args);
  18871. return result;
  18872. };
  18873. } (utils$3));
  18874. const utils$2 = utils$3;
  18875. var stringify$4 = (ast, options = {}) => {
  18876. const stringify = (node, parent = {}) => {
  18877. const invalidBlock = options.escapeInvalid && utils$2.isInvalidBrace(parent);
  18878. const invalidNode = node.invalid === true && options.escapeInvalid === true;
  18879. let output = '';
  18880. if (node.value) {
  18881. if ((invalidBlock || invalidNode) && utils$2.isOpenOrClose(node)) {
  18882. return '\\' + node.value;
  18883. }
  18884. return node.value;
  18885. }
  18886. if (node.value) {
  18887. return node.value;
  18888. }
  18889. if (node.nodes) {
  18890. for (const child of node.nodes) {
  18891. output += stringify(child);
  18892. }
  18893. }
  18894. return output;
  18895. };
  18896. return stringify(ast);
  18897. };
  18898. /*!
  18899. * is-number <https://github.com/jonschlinkert/is-number>
  18900. *
  18901. * Copyright (c) 2014-present, Jon Schlinkert.
  18902. * Released under the MIT License.
  18903. */
  18904. var isNumber$2 = function(num) {
  18905. if (typeof num === 'number') {
  18906. return num - num === 0;
  18907. }
  18908. if (typeof num === 'string' && num.trim() !== '') {
  18909. return Number.isFinite ? Number.isFinite(+num) : isFinite(+num);
  18910. }
  18911. return false;
  18912. };
  18913. /*!
  18914. * to-regex-range <https://github.com/micromatch/to-regex-range>
  18915. *
  18916. * Copyright (c) 2015-present, Jon Schlinkert.
  18917. * Released under the MIT License.
  18918. */
  18919. const isNumber$1 = isNumber$2;
  18920. const toRegexRange$1 = (min, max, options) => {
  18921. if (isNumber$1(min) === false) {
  18922. throw new TypeError('toRegexRange: expected the first argument to be a number');
  18923. }
  18924. if (max === void 0 || min === max) {
  18925. return String(min);
  18926. }
  18927. if (isNumber$1(max) === false) {
  18928. throw new TypeError('toRegexRange: expected the second argument to be a number.');
  18929. }
  18930. let opts = { relaxZeros: true, ...options };
  18931. if (typeof opts.strictZeros === 'boolean') {
  18932. opts.relaxZeros = opts.strictZeros === false;
  18933. }
  18934. let relax = String(opts.relaxZeros);
  18935. let shorthand = String(opts.shorthand);
  18936. let capture = String(opts.capture);
  18937. let wrap = String(opts.wrap);
  18938. let cacheKey = min + ':' + max + '=' + relax + shorthand + capture + wrap;
  18939. if (toRegexRange$1.cache.hasOwnProperty(cacheKey)) {
  18940. return toRegexRange$1.cache[cacheKey].result;
  18941. }
  18942. let a = Math.min(min, max);
  18943. let b = Math.max(min, max);
  18944. if (Math.abs(a - b) === 1) {
  18945. let result = min + '|' + max;
  18946. if (opts.capture) {
  18947. return `(${result})`;
  18948. }
  18949. if (opts.wrap === false) {
  18950. return result;
  18951. }
  18952. return `(?:${result})`;
  18953. }
  18954. let isPadded = hasPadding(min) || hasPadding(max);
  18955. let state = { min, max, a, b };
  18956. let positives = [];
  18957. let negatives = [];
  18958. if (isPadded) {
  18959. state.isPadded = isPadded;
  18960. state.maxLen = String(state.max).length;
  18961. }
  18962. if (a < 0) {
  18963. let newMin = b < 0 ? Math.abs(b) : 1;
  18964. negatives = splitToPatterns(newMin, Math.abs(a), state, opts);
  18965. a = state.a = 0;
  18966. }
  18967. if (b >= 0) {
  18968. positives = splitToPatterns(a, b, state, opts);
  18969. }
  18970. state.negatives = negatives;
  18971. state.positives = positives;
  18972. state.result = collatePatterns(negatives, positives);
  18973. if (opts.capture === true) {
  18974. state.result = `(${state.result})`;
  18975. } else if (opts.wrap !== false && (positives.length + negatives.length) > 1) {
  18976. state.result = `(?:${state.result})`;
  18977. }
  18978. toRegexRange$1.cache[cacheKey] = state;
  18979. return state.result;
  18980. };
  18981. function collatePatterns(neg, pos, options) {
  18982. let onlyNegative = filterPatterns(neg, pos, '-', false) || [];
  18983. let onlyPositive = filterPatterns(pos, neg, '', false) || [];
  18984. let intersected = filterPatterns(neg, pos, '-?', true) || [];
  18985. let subpatterns = onlyNegative.concat(intersected).concat(onlyPositive);
  18986. return subpatterns.join('|');
  18987. }
  18988. function splitToRanges(min, max) {
  18989. let nines = 1;
  18990. let zeros = 1;
  18991. let stop = countNines(min, nines);
  18992. let stops = new Set([max]);
  18993. while (min <= stop && stop <= max) {
  18994. stops.add(stop);
  18995. nines += 1;
  18996. stop = countNines(min, nines);
  18997. }
  18998. stop = countZeros(max + 1, zeros) - 1;
  18999. while (min < stop && stop <= max) {
  19000. stops.add(stop);
  19001. zeros += 1;
  19002. stop = countZeros(max + 1, zeros) - 1;
  19003. }
  19004. stops = [...stops];
  19005. stops.sort(compare);
  19006. return stops;
  19007. }
  19008. /**
  19009. * Convert a range to a regex pattern
  19010. * @param {Number} `start`
  19011. * @param {Number} `stop`
  19012. * @return {String}
  19013. */
  19014. function rangeToPattern(start, stop, options) {
  19015. if (start === stop) {
  19016. return { pattern: start, count: [], digits: 0 };
  19017. }
  19018. let zipped = zip(start, stop);
  19019. let digits = zipped.length;
  19020. let pattern = '';
  19021. let count = 0;
  19022. for (let i = 0; i < digits; i++) {
  19023. let [startDigit, stopDigit] = zipped[i];
  19024. if (startDigit === stopDigit) {
  19025. pattern += startDigit;
  19026. } else if (startDigit !== '0' || stopDigit !== '9') {
  19027. pattern += toCharacterClass(startDigit, stopDigit);
  19028. } else {
  19029. count++;
  19030. }
  19031. }
  19032. if (count) {
  19033. pattern += options.shorthand === true ? '\\d' : '[0-9]';
  19034. }
  19035. return { pattern, count: [count], digits };
  19036. }
  19037. function splitToPatterns(min, max, tok, options) {
  19038. let ranges = splitToRanges(min, max);
  19039. let tokens = [];
  19040. let start = min;
  19041. let prev;
  19042. for (let i = 0; i < ranges.length; i++) {
  19043. let max = ranges[i];
  19044. let obj = rangeToPattern(String(start), String(max), options);
  19045. let zeros = '';
  19046. if (!tok.isPadded && prev && prev.pattern === obj.pattern) {
  19047. if (prev.count.length > 1) {
  19048. prev.count.pop();
  19049. }
  19050. prev.count.push(obj.count[0]);
  19051. prev.string = prev.pattern + toQuantifier(prev.count);
  19052. start = max + 1;
  19053. continue;
  19054. }
  19055. if (tok.isPadded) {
  19056. zeros = padZeros(max, tok, options);
  19057. }
  19058. obj.string = zeros + obj.pattern + toQuantifier(obj.count);
  19059. tokens.push(obj);
  19060. start = max + 1;
  19061. prev = obj;
  19062. }
  19063. return tokens;
  19064. }
  19065. function filterPatterns(arr, comparison, prefix, intersection, options) {
  19066. let result = [];
  19067. for (let ele of arr) {
  19068. let { string } = ele;
  19069. // only push if _both_ are negative...
  19070. if (!intersection && !contains(comparison, 'string', string)) {
  19071. result.push(prefix + string);
  19072. }
  19073. // or _both_ are positive
  19074. if (intersection && contains(comparison, 'string', string)) {
  19075. result.push(prefix + string);
  19076. }
  19077. }
  19078. return result;
  19079. }
  19080. /**
  19081. * Zip strings
  19082. */
  19083. function zip(a, b) {
  19084. let arr = [];
  19085. for (let i = 0; i < a.length; i++) arr.push([a[i], b[i]]);
  19086. return arr;
  19087. }
  19088. function compare(a, b) {
  19089. return a > b ? 1 : b > a ? -1 : 0;
  19090. }
  19091. function contains(arr, key, val) {
  19092. return arr.some(ele => ele[key] === val);
  19093. }
  19094. function countNines(min, len) {
  19095. return Number(String(min).slice(0, -len) + '9'.repeat(len));
  19096. }
  19097. function countZeros(integer, zeros) {
  19098. return integer - (integer % Math.pow(10, zeros));
  19099. }
  19100. function toQuantifier(digits) {
  19101. let [start = 0, stop = ''] = digits;
  19102. if (stop || start > 1) {
  19103. return `{${start + (stop ? ',' + stop : '')}}`;
  19104. }
  19105. return '';
  19106. }
  19107. function toCharacterClass(a, b, options) {
  19108. return `[${a}${(b - a === 1) ? '' : '-'}${b}]`;
  19109. }
  19110. function hasPadding(str) {
  19111. return /^-?(0+)\d/.test(str);
  19112. }
  19113. function padZeros(value, tok, options) {
  19114. if (!tok.isPadded) {
  19115. return value;
  19116. }
  19117. let diff = Math.abs(tok.maxLen - String(value).length);
  19118. let relax = options.relaxZeros !== false;
  19119. switch (diff) {
  19120. case 0:
  19121. return '';
  19122. case 1:
  19123. return relax ? '0?' : '0';
  19124. case 2:
  19125. return relax ? '0{0,2}' : '00';
  19126. default: {
  19127. return relax ? `0{0,${diff}}` : `0{${diff}}`;
  19128. }
  19129. }
  19130. }
  19131. /**
  19132. * Cache
  19133. */
  19134. toRegexRange$1.cache = {};
  19135. toRegexRange$1.clearCache = () => (toRegexRange$1.cache = {});
  19136. /**
  19137. * Expose `toRegexRange`
  19138. */
  19139. var toRegexRange_1 = toRegexRange$1;
  19140. /*!
  19141. * fill-range <https://github.com/jonschlinkert/fill-range>
  19142. *
  19143. * Copyright (c) 2014-present, Jon Schlinkert.
  19144. * Licensed under the MIT License.
  19145. */
  19146. const util = require$$1;
  19147. const toRegexRange = toRegexRange_1;
  19148. const isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val);
  19149. const transform = toNumber => {
  19150. return value => toNumber === true ? Number(value) : String(value);
  19151. };
  19152. const isValidValue = value => {
  19153. return typeof value === 'number' || (typeof value === 'string' && value !== '');
  19154. };
  19155. const isNumber = num => Number.isInteger(+num);
  19156. const zeros = input => {
  19157. let value = `${input}`;
  19158. let index = -1;
  19159. if (value[0] === '-') value = value.slice(1);
  19160. if (value === '0') return false;
  19161. while (value[++index] === '0');
  19162. return index > 0;
  19163. };
  19164. const stringify$3 = (start, end, options) => {
  19165. if (typeof start === 'string' || typeof end === 'string') {
  19166. return true;
  19167. }
  19168. return options.stringify === true;
  19169. };
  19170. const pad = (input, maxLength, toNumber) => {
  19171. if (maxLength > 0) {
  19172. let dash = input[0] === '-' ? '-' : '';
  19173. if (dash) input = input.slice(1);
  19174. input = (dash + input.padStart(dash ? maxLength - 1 : maxLength, '0'));
  19175. }
  19176. if (toNumber === false) {
  19177. return String(input);
  19178. }
  19179. return input;
  19180. };
  19181. const toMaxLen = (input, maxLength) => {
  19182. let negative = input[0] === '-' ? '-' : '';
  19183. if (negative) {
  19184. input = input.slice(1);
  19185. maxLength--;
  19186. }
  19187. while (input.length < maxLength) input = '0' + input;
  19188. return negative ? ('-' + input) : input;
  19189. };
  19190. const toSequence = (parts, options, maxLen) => {
  19191. parts.negatives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
  19192. parts.positives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
  19193. let prefix = options.capture ? '' : '?:';
  19194. let positives = '';
  19195. let negatives = '';
  19196. let result;
  19197. if (parts.positives.length) {
  19198. positives = parts.positives.map(v => toMaxLen(String(v), maxLen)).join('|');
  19199. }
  19200. if (parts.negatives.length) {
  19201. negatives = `-(${prefix}${parts.negatives.map(v => toMaxLen(String(v), maxLen)).join('|')})`;
  19202. }
  19203. if (positives && negatives) {
  19204. result = `${positives}|${negatives}`;
  19205. } else {
  19206. result = positives || negatives;
  19207. }
  19208. if (options.wrap) {
  19209. return `(${prefix}${result})`;
  19210. }
  19211. return result;
  19212. };
  19213. const toRange = (a, b, isNumbers, options) => {
  19214. if (isNumbers) {
  19215. return toRegexRange(a, b, { wrap: false, ...options });
  19216. }
  19217. let start = String.fromCharCode(a);
  19218. if (a === b) return start;
  19219. let stop = String.fromCharCode(b);
  19220. return `[${start}-${stop}]`;
  19221. };
  19222. const toRegex = (start, end, options) => {
  19223. if (Array.isArray(start)) {
  19224. let wrap = options.wrap === true;
  19225. let prefix = options.capture ? '' : '?:';
  19226. return wrap ? `(${prefix}${start.join('|')})` : start.join('|');
  19227. }
  19228. return toRegexRange(start, end, options);
  19229. };
  19230. const rangeError = (...args) => {
  19231. return new RangeError('Invalid range arguments: ' + util.inspect(...args));
  19232. };
  19233. const invalidRange = (start, end, options) => {
  19234. if (options.strictRanges === true) throw rangeError([start, end]);
  19235. return [];
  19236. };
  19237. const invalidStep = (step, options) => {
  19238. if (options.strictRanges === true) {
  19239. throw new TypeError(`Expected step "${step}" to be a number`);
  19240. }
  19241. return [];
  19242. };
  19243. const fillNumbers = (start, end, step = 1, options = {}) => {
  19244. let a = Number(start);
  19245. let b = Number(end);
  19246. if (!Number.isInteger(a) || !Number.isInteger(b)) {
  19247. if (options.strictRanges === true) throw rangeError([start, end]);
  19248. return [];
  19249. }
  19250. // fix negative zero
  19251. if (a === 0) a = 0;
  19252. if (b === 0) b = 0;
  19253. let descending = a > b;
  19254. let startString = String(start);
  19255. let endString = String(end);
  19256. let stepString = String(step);
  19257. step = Math.max(Math.abs(step), 1);
  19258. let padded = zeros(startString) || zeros(endString) || zeros(stepString);
  19259. let maxLen = padded ? Math.max(startString.length, endString.length, stepString.length) : 0;
  19260. let toNumber = padded === false && stringify$3(start, end, options) === false;
  19261. let format = options.transform || transform(toNumber);
  19262. if (options.toRegex && step === 1) {
  19263. return toRange(toMaxLen(start, maxLen), toMaxLen(end, maxLen), true, options);
  19264. }
  19265. let parts = { negatives: [], positives: [] };
  19266. let push = num => parts[num < 0 ? 'negatives' : 'positives'].push(Math.abs(num));
  19267. let range = [];
  19268. let index = 0;
  19269. while (descending ? a >= b : a <= b) {
  19270. if (options.toRegex === true && step > 1) {
  19271. push(a);
  19272. } else {
  19273. range.push(pad(format(a, index), maxLen, toNumber));
  19274. }
  19275. a = descending ? a - step : a + step;
  19276. index++;
  19277. }
  19278. if (options.toRegex === true) {
  19279. return step > 1
  19280. ? toSequence(parts, options, maxLen)
  19281. : toRegex(range, null, { wrap: false, ...options });
  19282. }
  19283. return range;
  19284. };
  19285. const fillLetters = (start, end, step = 1, options = {}) => {
  19286. if ((!isNumber(start) && start.length > 1) || (!isNumber(end) && end.length > 1)) {
  19287. return invalidRange(start, end, options);
  19288. }
  19289. let format = options.transform || (val => String.fromCharCode(val));
  19290. let a = `${start}`.charCodeAt(0);
  19291. let b = `${end}`.charCodeAt(0);
  19292. let descending = a > b;
  19293. let min = Math.min(a, b);
  19294. let max = Math.max(a, b);
  19295. if (options.toRegex && step === 1) {
  19296. return toRange(min, max, false, options);
  19297. }
  19298. let range = [];
  19299. let index = 0;
  19300. while (descending ? a >= b : a <= b) {
  19301. range.push(format(a, index));
  19302. a = descending ? a - step : a + step;
  19303. index++;
  19304. }
  19305. if (options.toRegex === true) {
  19306. return toRegex(range, null, { wrap: false, options });
  19307. }
  19308. return range;
  19309. };
  19310. const fill$2 = (start, end, step, options = {}) => {
  19311. if (end == null && isValidValue(start)) {
  19312. return [start];
  19313. }
  19314. if (!isValidValue(start) || !isValidValue(end)) {
  19315. return invalidRange(start, end, options);
  19316. }
  19317. if (typeof step === 'function') {
  19318. return fill$2(start, end, 1, { transform: step });
  19319. }
  19320. if (isObject(step)) {
  19321. return fill$2(start, end, 0, step);
  19322. }
  19323. let opts = { ...options };
  19324. if (opts.capture === true) opts.wrap = true;
  19325. step = step || opts.step || 1;
  19326. if (!isNumber(step)) {
  19327. if (step != null && !isObject(step)) return invalidStep(step, opts);
  19328. return fill$2(start, end, 1, step);
  19329. }
  19330. if (isNumber(start) && isNumber(end)) {
  19331. return fillNumbers(start, end, step, opts);
  19332. }
  19333. return fillLetters(start, end, Math.max(Math.abs(step), 1), opts);
  19334. };
  19335. var fillRange = fill$2;
  19336. const fill$1 = fillRange;
  19337. const utils$1 = utils$3;
  19338. const compile$1 = (ast, options = {}) => {
  19339. const walk = (node, parent = {}) => {
  19340. const invalidBlock = utils$1.isInvalidBrace(parent);
  19341. const invalidNode = node.invalid === true && options.escapeInvalid === true;
  19342. const invalid = invalidBlock === true || invalidNode === true;
  19343. const prefix = options.escapeInvalid === true ? '\\' : '';
  19344. let output = '';
  19345. if (node.isOpen === true) {
  19346. return prefix + node.value;
  19347. }
  19348. if (node.isClose === true) {
  19349. console.log('node.isClose', prefix, node.value);
  19350. return prefix + node.value;
  19351. }
  19352. if (node.type === 'open') {
  19353. return invalid ? prefix + node.value : '(';
  19354. }
  19355. if (node.type === 'close') {
  19356. return invalid ? prefix + node.value : ')';
  19357. }
  19358. if (node.type === 'comma') {
  19359. return node.prev.type === 'comma' ? '' : invalid ? node.value : '|';
  19360. }
  19361. if (node.value) {
  19362. return node.value;
  19363. }
  19364. if (node.nodes && node.ranges > 0) {
  19365. const args = utils$1.reduce(node.nodes);
  19366. const range = fill$1(...args, { ...options, wrap: false, toRegex: true, strictZeros: true });
  19367. if (range.length !== 0) {
  19368. return args.length > 1 && range.length > 1 ? `(${range})` : range;
  19369. }
  19370. }
  19371. if (node.nodes) {
  19372. for (const child of node.nodes) {
  19373. output += walk(child, node);
  19374. }
  19375. }
  19376. return output;
  19377. };
  19378. return walk(ast);
  19379. };
  19380. var compile_1 = compile$1;
  19381. const fill = fillRange;
  19382. const stringify$2 = stringify$4;
  19383. const utils = utils$3;
  19384. const append = (queue = '', stash = '', enclose = false) => {
  19385. const result = [];
  19386. queue = [].concat(queue);
  19387. stash = [].concat(stash);
  19388. if (!stash.length) return queue;
  19389. if (!queue.length) {
  19390. return enclose ? utils.flatten(stash).map(ele => `{${ele}}`) : stash;
  19391. }
  19392. for (const item of queue) {
  19393. if (Array.isArray(item)) {
  19394. for (const value of item) {
  19395. result.push(append(value, stash, enclose));
  19396. }
  19397. } else {
  19398. for (let ele of stash) {
  19399. if (enclose === true && typeof ele === 'string') ele = `{${ele}}`;
  19400. result.push(Array.isArray(ele) ? append(item, ele, enclose) : item + ele);
  19401. }
  19402. }
  19403. }
  19404. return utils.flatten(result);
  19405. };
  19406. const expand$1 = (ast, options = {}) => {
  19407. const rangeLimit = options.rangeLimit === undefined ? 1000 : options.rangeLimit;
  19408. const walk = (node, parent = {}) => {
  19409. node.queue = [];
  19410. let p = parent;
  19411. let q = parent.queue;
  19412. while (p.type !== 'brace' && p.type !== 'root' && p.parent) {
  19413. p = p.parent;
  19414. q = p.queue;
  19415. }
  19416. if (node.invalid || node.dollar) {
  19417. q.push(append(q.pop(), stringify$2(node, options)));
  19418. return;
  19419. }
  19420. if (node.type === 'brace' && node.invalid !== true && node.nodes.length === 2) {
  19421. q.push(append(q.pop(), ['{}']));
  19422. return;
  19423. }
  19424. if (node.nodes && node.ranges > 0) {
  19425. const args = utils.reduce(node.nodes);
  19426. if (utils.exceedsLimit(...args, options.step, rangeLimit)) {
  19427. throw new RangeError('expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.');
  19428. }
  19429. let range = fill(...args, options);
  19430. if (range.length === 0) {
  19431. range = stringify$2(node, options);
  19432. }
  19433. q.push(append(q.pop(), range));
  19434. node.nodes = [];
  19435. return;
  19436. }
  19437. const enclose = utils.encloseBrace(node);
  19438. let queue = node.queue;
  19439. let block = node;
  19440. while (block.type !== 'brace' && block.type !== 'root' && block.parent) {
  19441. block = block.parent;
  19442. queue = block.queue;
  19443. }
  19444. for (let i = 0; i < node.nodes.length; i++) {
  19445. const child = node.nodes[i];
  19446. if (child.type === 'comma' && node.type === 'brace') {
  19447. if (i === 1) queue.push('');
  19448. queue.push('');
  19449. continue;
  19450. }
  19451. if (child.type === 'close') {
  19452. q.push(append(q.pop(), queue, enclose));
  19453. continue;
  19454. }
  19455. if (child.value && child.type !== 'open') {
  19456. queue.push(append(queue.pop(), child.value));
  19457. continue;
  19458. }
  19459. if (child.nodes) {
  19460. walk(child, node);
  19461. }
  19462. }
  19463. return queue;
  19464. };
  19465. return utils.flatten(walk(ast));
  19466. };
  19467. var expand_1 = expand$1;
  19468. var constants$2 = {
  19469. MAX_LENGTH: 10000,
  19470. CHAR_LEFT_PARENTHESES: '(', /* ( */
  19471. CHAR_RIGHT_PARENTHESES: ')', /* ) */
  19472. CHAR_BACKSLASH: '\\', /* \ */
  19473. CHAR_BACKTICK: '`', /* ` */
  19474. CHAR_COMMA: ',', /* , */
  19475. CHAR_DOT: '.', /* . */
  19476. CHAR_DOUBLE_QUOTE: '"', /* " */
  19477. CHAR_LEFT_CURLY_BRACE: '{', /* { */
  19478. CHAR_LEFT_SQUARE_BRACKET: '[', /* [ */
  19479. CHAR_NO_BREAK_SPACE: '\u00A0', /* \u00A0 */
  19480. CHAR_RIGHT_CURLY_BRACE: '}', /* } */
  19481. CHAR_RIGHT_SQUARE_BRACKET: ']', /* ] */
  19482. CHAR_SINGLE_QUOTE: '\'', /* ' */
  19483. CHAR_ZERO_WIDTH_NOBREAK_SPACE: '\uFEFF' /* \uFEFF */
  19484. };
  19485. const stringify$1 = stringify$4;
  19486. /**
  19487. * Constants
  19488. */
  19489. const {
  19490. MAX_LENGTH,
  19491. CHAR_BACKSLASH, /* \ */
  19492. CHAR_BACKTICK, /* ` */
  19493. CHAR_COMMA, /* , */
  19494. CHAR_DOT, /* . */
  19495. CHAR_LEFT_PARENTHESES, /* ( */
  19496. CHAR_RIGHT_PARENTHESES, /* ) */
  19497. CHAR_LEFT_CURLY_BRACE, /* { */
  19498. CHAR_RIGHT_CURLY_BRACE, /* } */
  19499. CHAR_LEFT_SQUARE_BRACKET, /* [ */
  19500. CHAR_RIGHT_SQUARE_BRACKET, /* ] */
  19501. CHAR_DOUBLE_QUOTE, /* " */
  19502. CHAR_SINGLE_QUOTE, /* ' */
  19503. CHAR_NO_BREAK_SPACE,
  19504. CHAR_ZERO_WIDTH_NOBREAK_SPACE
  19505. } = constants$2;
  19506. /**
  19507. * parse
  19508. */
  19509. const parse$8 = (input, options = {}) => {
  19510. if (typeof input !== 'string') {
  19511. throw new TypeError('Expected a string');
  19512. }
  19513. const opts = options || {};
  19514. const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
  19515. if (input.length > max) {
  19516. throw new SyntaxError(`Input length (${input.length}), exceeds max characters (${max})`);
  19517. }
  19518. const ast = { type: 'root', input, nodes: [] };
  19519. const stack = [ast];
  19520. let block = ast;
  19521. let prev = ast;
  19522. let brackets = 0;
  19523. const length = input.length;
  19524. let index = 0;
  19525. let depth = 0;
  19526. let value;
  19527. /**
  19528. * Helpers
  19529. */
  19530. const advance = () => input[index++];
  19531. const push = node => {
  19532. if (node.type === 'text' && prev.type === 'dot') {
  19533. prev.type = 'text';
  19534. }
  19535. if (prev && prev.type === 'text' && node.type === 'text') {
  19536. prev.value += node.value;
  19537. return;
  19538. }
  19539. block.nodes.push(node);
  19540. node.parent = block;
  19541. node.prev = prev;
  19542. prev = node;
  19543. return node;
  19544. };
  19545. push({ type: 'bos' });
  19546. while (index < length) {
  19547. block = stack[stack.length - 1];
  19548. value = advance();
  19549. /**
  19550. * Invalid chars
  19551. */
  19552. if (value === CHAR_ZERO_WIDTH_NOBREAK_SPACE || value === CHAR_NO_BREAK_SPACE) {
  19553. continue;
  19554. }
  19555. /**
  19556. * Escaped chars
  19557. */
  19558. if (value === CHAR_BACKSLASH) {
  19559. push({ type: 'text', value: (options.keepEscaping ? value : '') + advance() });
  19560. continue;
  19561. }
  19562. /**
  19563. * Right square bracket (literal): ']'
  19564. */
  19565. if (value === CHAR_RIGHT_SQUARE_BRACKET) {
  19566. push({ type: 'text', value: '\\' + value });
  19567. continue;
  19568. }
  19569. /**
  19570. * Left square bracket: '['
  19571. */
  19572. if (value === CHAR_LEFT_SQUARE_BRACKET) {
  19573. brackets++;
  19574. let next;
  19575. while (index < length && (next = advance())) {
  19576. value += next;
  19577. if (next === CHAR_LEFT_SQUARE_BRACKET) {
  19578. brackets++;
  19579. continue;
  19580. }
  19581. if (next === CHAR_BACKSLASH) {
  19582. value += advance();
  19583. continue;
  19584. }
  19585. if (next === CHAR_RIGHT_SQUARE_BRACKET) {
  19586. brackets--;
  19587. if (brackets === 0) {
  19588. break;
  19589. }
  19590. }
  19591. }
  19592. push({ type: 'text', value });
  19593. continue;
  19594. }
  19595. /**
  19596. * Parentheses
  19597. */
  19598. if (value === CHAR_LEFT_PARENTHESES) {
  19599. block = push({ type: 'paren', nodes: [] });
  19600. stack.push(block);
  19601. push({ type: 'text', value });
  19602. continue;
  19603. }
  19604. if (value === CHAR_RIGHT_PARENTHESES) {
  19605. if (block.type !== 'paren') {
  19606. push({ type: 'text', value });
  19607. continue;
  19608. }
  19609. block = stack.pop();
  19610. push({ type: 'text', value });
  19611. block = stack[stack.length - 1];
  19612. continue;
  19613. }
  19614. /**
  19615. * Quotes: '|"|`
  19616. */
  19617. if (value === CHAR_DOUBLE_QUOTE || value === CHAR_SINGLE_QUOTE || value === CHAR_BACKTICK) {
  19618. const open = value;
  19619. let next;
  19620. if (options.keepQuotes !== true) {
  19621. value = '';
  19622. }
  19623. while (index < length && (next = advance())) {
  19624. if (next === CHAR_BACKSLASH) {
  19625. value += next + advance();
  19626. continue;
  19627. }
  19628. if (next === open) {
  19629. if (options.keepQuotes === true) value += next;
  19630. break;
  19631. }
  19632. value += next;
  19633. }
  19634. push({ type: 'text', value });
  19635. continue;
  19636. }
  19637. /**
  19638. * Left curly brace: '{'
  19639. */
  19640. if (value === CHAR_LEFT_CURLY_BRACE) {
  19641. depth++;
  19642. const dollar = prev.value && prev.value.slice(-1) === '$' || block.dollar === true;
  19643. const brace = {
  19644. type: 'brace',
  19645. open: true,
  19646. close: false,
  19647. dollar,
  19648. depth,
  19649. commas: 0,
  19650. ranges: 0,
  19651. nodes: []
  19652. };
  19653. block = push(brace);
  19654. stack.push(block);
  19655. push({ type: 'open', value });
  19656. continue;
  19657. }
  19658. /**
  19659. * Right curly brace: '}'
  19660. */
  19661. if (value === CHAR_RIGHT_CURLY_BRACE) {
  19662. if (block.type !== 'brace') {
  19663. push({ type: 'text', value });
  19664. continue;
  19665. }
  19666. const type = 'close';
  19667. block = stack.pop();
  19668. block.close = true;
  19669. push({ type, value });
  19670. depth--;
  19671. block = stack[stack.length - 1];
  19672. continue;
  19673. }
  19674. /**
  19675. * Comma: ','
  19676. */
  19677. if (value === CHAR_COMMA && depth > 0) {
  19678. if (block.ranges > 0) {
  19679. block.ranges = 0;
  19680. const open = block.nodes.shift();
  19681. block.nodes = [open, { type: 'text', value: stringify$1(block) }];
  19682. }
  19683. push({ type: 'comma', value });
  19684. block.commas++;
  19685. continue;
  19686. }
  19687. /**
  19688. * Dot: '.'
  19689. */
  19690. if (value === CHAR_DOT && depth > 0 && block.commas === 0) {
  19691. const siblings = block.nodes;
  19692. if (depth === 0 || siblings.length === 0) {
  19693. push({ type: 'text', value });
  19694. continue;
  19695. }
  19696. if (prev.type === 'dot') {
  19697. block.range = [];
  19698. prev.value += value;
  19699. prev.type = 'range';
  19700. if (block.nodes.length !== 3 && block.nodes.length !== 5) {
  19701. block.invalid = true;
  19702. block.ranges = 0;
  19703. prev.type = 'text';
  19704. continue;
  19705. }
  19706. block.ranges++;
  19707. block.args = [];
  19708. continue;
  19709. }
  19710. if (prev.type === 'range') {
  19711. siblings.pop();
  19712. const before = siblings[siblings.length - 1];
  19713. before.value += prev.value + value;
  19714. prev = before;
  19715. block.ranges--;
  19716. continue;
  19717. }
  19718. push({ type: 'dot', value });
  19719. continue;
  19720. }
  19721. /**
  19722. * Text
  19723. */
  19724. push({ type: 'text', value });
  19725. }
  19726. // Mark imbalanced braces and brackets as invalid
  19727. do {
  19728. block = stack.pop();
  19729. if (block.type !== 'root') {
  19730. block.nodes.forEach(node => {
  19731. if (!node.nodes) {
  19732. if (node.type === 'open') node.isOpen = true;
  19733. if (node.type === 'close') node.isClose = true;
  19734. if (!node.nodes) node.type = 'text';
  19735. node.invalid = true;
  19736. }
  19737. });
  19738. // get the location of the block on parent.nodes (block's siblings)
  19739. const parent = stack[stack.length - 1];
  19740. const index = parent.nodes.indexOf(block);
  19741. // replace the (invalid) block with it's nodes
  19742. parent.nodes.splice(index, 1, ...block.nodes);
  19743. }
  19744. } while (stack.length > 0);
  19745. push({ type: 'eos' });
  19746. return ast;
  19747. };
  19748. var parse_1$1 = parse$8;
  19749. const stringify = stringify$4;
  19750. const compile = compile_1;
  19751. const expand = expand_1;
  19752. const parse$7 = parse_1$1;
  19753. /**
  19754. * Expand the given pattern or create a regex-compatible string.
  19755. *
  19756. * ```js
  19757. * const braces = require('braces');
  19758. * console.log(braces('{a,b,c}', { compile: true })); //=> ['(a|b|c)']
  19759. * console.log(braces('{a,b,c}')); //=> ['a', 'b', 'c']
  19760. * ```
  19761. * @param {String} `str`
  19762. * @param {Object} `options`
  19763. * @return {String}
  19764. * @api public
  19765. */
  19766. const braces$1 = (input, options = {}) => {
  19767. let output = [];
  19768. if (Array.isArray(input)) {
  19769. for (const pattern of input) {
  19770. const result = braces$1.create(pattern, options);
  19771. if (Array.isArray(result)) {
  19772. output.push(...result);
  19773. } else {
  19774. output.push(result);
  19775. }
  19776. }
  19777. } else {
  19778. output = [].concat(braces$1.create(input, options));
  19779. }
  19780. if (options && options.expand === true && options.nodupes === true) {
  19781. output = [...new Set(output)];
  19782. }
  19783. return output;
  19784. };
  19785. /**
  19786. * Parse the given `str` with the given `options`.
  19787. *
  19788. * ```js
  19789. * // braces.parse(pattern, [, options]);
  19790. * const ast = braces.parse('a/{b,c}/d');
  19791. * console.log(ast);
  19792. * ```
  19793. * @param {String} pattern Brace pattern to parse
  19794. * @param {Object} options
  19795. * @return {Object} Returns an AST
  19796. * @api public
  19797. */
  19798. braces$1.parse = (input, options = {}) => parse$7(input, options);
  19799. /**
  19800. * Creates a braces string from an AST, or an AST node.
  19801. *
  19802. * ```js
  19803. * const braces = require('braces');
  19804. * let ast = braces.parse('foo/{a,b}/bar');
  19805. * console.log(stringify(ast.nodes[2])); //=> '{a,b}'
  19806. * ```
  19807. * @param {String} `input` Brace pattern or AST.
  19808. * @param {Object} `options`
  19809. * @return {Array} Returns an array of expanded values.
  19810. * @api public
  19811. */
  19812. braces$1.stringify = (input, options = {}) => {
  19813. if (typeof input === 'string') {
  19814. return stringify(braces$1.parse(input, options), options);
  19815. }
  19816. return stringify(input, options);
  19817. };
  19818. /**
  19819. * Compiles a brace pattern into a regex-compatible, optimized string.
  19820. * This method is called by the main [braces](#braces) function by default.
  19821. *
  19822. * ```js
  19823. * const braces = require('braces');
  19824. * console.log(braces.compile('a/{b,c}/d'));
  19825. * //=> ['a/(b|c)/d']
  19826. * ```
  19827. * @param {String} `input` Brace pattern or AST.
  19828. * @param {Object} `options`
  19829. * @return {Array} Returns an array of expanded values.
  19830. * @api public
  19831. */
  19832. braces$1.compile = (input, options = {}) => {
  19833. if (typeof input === 'string') {
  19834. input = braces$1.parse(input, options);
  19835. }
  19836. return compile(input, options);
  19837. };
  19838. /**
  19839. * Expands a brace pattern into an array. This method is called by the
  19840. * main [braces](#braces) function when `options.expand` is true. Before
  19841. * using this method it's recommended that you read the [performance notes](#performance))
  19842. * and advantages of using [.compile](#compile) instead.
  19843. *
  19844. * ```js
  19845. * const braces = require('braces');
  19846. * console.log(braces.expand('a/{b,c}/d'));
  19847. * //=> ['a/b/d', 'a/c/d'];
  19848. * ```
  19849. * @param {String} `pattern` Brace pattern
  19850. * @param {Object} `options`
  19851. * @return {Array} Returns an array of expanded values.
  19852. * @api public
  19853. */
  19854. braces$1.expand = (input, options = {}) => {
  19855. if (typeof input === 'string') {
  19856. input = braces$1.parse(input, options);
  19857. }
  19858. let result = expand(input, options);
  19859. // filter out empty strings if specified
  19860. if (options.noempty === true) {
  19861. result = result.filter(Boolean);
  19862. }
  19863. // filter out duplicates if specified
  19864. if (options.nodupes === true) {
  19865. result = [...new Set(result)];
  19866. }
  19867. return result;
  19868. };
  19869. /**
  19870. * Processes a brace pattern and returns either an expanded array
  19871. * (if `options.expand` is true), a highly optimized regex-compatible string.
  19872. * This method is called by the main [braces](#braces) function.
  19873. *
  19874. * ```js
  19875. * const braces = require('braces');
  19876. * console.log(braces.create('user-{200..300}/project-{a,b,c}-{1..10}'))
  19877. * //=> 'user-(20[0-9]|2[1-9][0-9]|300)/project-(a|b|c)-([1-9]|10)'
  19878. * ```
  19879. * @param {String} `pattern` Brace pattern
  19880. * @param {Object} `options`
  19881. * @return {Array} Returns an array of expanded values.
  19882. * @api public
  19883. */
  19884. braces$1.create = (input, options = {}) => {
  19885. if (input === '' || input.length < 3) {
  19886. return [input];
  19887. }
  19888. return options.expand !== true
  19889. ? braces$1.compile(input, options)
  19890. : braces$1.expand(input, options);
  19891. };
  19892. /**
  19893. * Expose "braces"
  19894. */
  19895. var braces_1 = braces$1;
  19896. var require$$0 = [
  19897. "3dm",
  19898. "3ds",
  19899. "3g2",
  19900. "3gp",
  19901. "7z",
  19902. "a",
  19903. "aac",
  19904. "adp",
  19905. "afdesign",
  19906. "afphoto",
  19907. "afpub",
  19908. "ai",
  19909. "aif",
  19910. "aiff",
  19911. "alz",
  19912. "ape",
  19913. "apk",
  19914. "appimage",
  19915. "ar",
  19916. "arj",
  19917. "asf",
  19918. "au",
  19919. "avi",
  19920. "bak",
  19921. "baml",
  19922. "bh",
  19923. "bin",
  19924. "bk",
  19925. "bmp",
  19926. "btif",
  19927. "bz2",
  19928. "bzip2",
  19929. "cab",
  19930. "caf",
  19931. "cgm",
  19932. "class",
  19933. "cmx",
  19934. "cpio",
  19935. "cr2",
  19936. "cur",
  19937. "dat",
  19938. "dcm",
  19939. "deb",
  19940. "dex",
  19941. "djvu",
  19942. "dll",
  19943. "dmg",
  19944. "dng",
  19945. "doc",
  19946. "docm",
  19947. "docx",
  19948. "dot",
  19949. "dotm",
  19950. "dra",
  19951. "DS_Store",
  19952. "dsk",
  19953. "dts",
  19954. "dtshd",
  19955. "dvb",
  19956. "dwg",
  19957. "dxf",
  19958. "ecelp4800",
  19959. "ecelp7470",
  19960. "ecelp9600",
  19961. "egg",
  19962. "eol",
  19963. "eot",
  19964. "epub",
  19965. "exe",
  19966. "f4v",
  19967. "fbs",
  19968. "fh",
  19969. "fla",
  19970. "flac",
  19971. "flatpak",
  19972. "fli",
  19973. "flv",
  19974. "fpx",
  19975. "fst",
  19976. "fvt",
  19977. "g3",
  19978. "gh",
  19979. "gif",
  19980. "graffle",
  19981. "gz",
  19982. "gzip",
  19983. "h261",
  19984. "h263",
  19985. "h264",
  19986. "icns",
  19987. "ico",
  19988. "ief",
  19989. "img",
  19990. "ipa",
  19991. "iso",
  19992. "jar",
  19993. "jpeg",
  19994. "jpg",
  19995. "jpgv",
  19996. "jpm",
  19997. "jxr",
  19998. "key",
  19999. "ktx",
  20000. "lha",
  20001. "lib",
  20002. "lvp",
  20003. "lz",
  20004. "lzh",
  20005. "lzma",
  20006. "lzo",
  20007. "m3u",
  20008. "m4a",
  20009. "m4v",
  20010. "mar",
  20011. "mdi",
  20012. "mht",
  20013. "mid",
  20014. "midi",
  20015. "mj2",
  20016. "mka",
  20017. "mkv",
  20018. "mmr",
  20019. "mng",
  20020. "mobi",
  20021. "mov",
  20022. "movie",
  20023. "mp3",
  20024. "mp4",
  20025. "mp4a",
  20026. "mpeg",
  20027. "mpg",
  20028. "mpga",
  20029. "mxu",
  20030. "nef",
  20031. "npx",
  20032. "numbers",
  20033. "nupkg",
  20034. "o",
  20035. "odp",
  20036. "ods",
  20037. "odt",
  20038. "oga",
  20039. "ogg",
  20040. "ogv",
  20041. "otf",
  20042. "ott",
  20043. "pages",
  20044. "pbm",
  20045. "pcx",
  20046. "pdb",
  20047. "pdf",
  20048. "pea",
  20049. "pgm",
  20050. "pic",
  20051. "png",
  20052. "pnm",
  20053. "pot",
  20054. "potm",
  20055. "potx",
  20056. "ppa",
  20057. "ppam",
  20058. "ppm",
  20059. "pps",
  20060. "ppsm",
  20061. "ppsx",
  20062. "ppt",
  20063. "pptm",
  20064. "pptx",
  20065. "psd",
  20066. "pya",
  20067. "pyc",
  20068. "pyo",
  20069. "pyv",
  20070. "qt",
  20071. "rar",
  20072. "ras",
  20073. "raw",
  20074. "resources",
  20075. "rgb",
  20076. "rip",
  20077. "rlc",
  20078. "rmf",
  20079. "rmvb",
  20080. "rpm",
  20081. "rtf",
  20082. "rz",
  20083. "s3m",
  20084. "s7z",
  20085. "scpt",
  20086. "sgi",
  20087. "shar",
  20088. "snap",
  20089. "sil",
  20090. "sketch",
  20091. "slk",
  20092. "smv",
  20093. "snk",
  20094. "so",
  20095. "stl",
  20096. "suo",
  20097. "sub",
  20098. "swf",
  20099. "tar",
  20100. "tbz",
  20101. "tbz2",
  20102. "tga",
  20103. "tgz",
  20104. "thmx",
  20105. "tif",
  20106. "tiff",
  20107. "tlz",
  20108. "ttc",
  20109. "ttf",
  20110. "txz",
  20111. "udf",
  20112. "uvh",
  20113. "uvi",
  20114. "uvm",
  20115. "uvp",
  20116. "uvs",
  20117. "uvu",
  20118. "viv",
  20119. "vob",
  20120. "war",
  20121. "wav",
  20122. "wax",
  20123. "wbmp",
  20124. "wdp",
  20125. "weba",
  20126. "webm",
  20127. "webp",
  20128. "whl",
  20129. "wim",
  20130. "wm",
  20131. "wma",
  20132. "wmv",
  20133. "wmx",
  20134. "woff",
  20135. "woff2",
  20136. "wrm",
  20137. "wvx",
  20138. "xbm",
  20139. "xif",
  20140. "xla",
  20141. "xlam",
  20142. "xls",
  20143. "xlsb",
  20144. "xlsm",
  20145. "xlsx",
  20146. "xlt",
  20147. "xltm",
  20148. "xltx",
  20149. "xm",
  20150. "xmind",
  20151. "xpi",
  20152. "xpm",
  20153. "xwd",
  20154. "xz",
  20155. "z",
  20156. "zip",
  20157. "zipx"
  20158. ];
  20159. var binaryExtensions$1 = require$$0;
  20160. const path$7 = require$$0$2;
  20161. const binaryExtensions = binaryExtensions$1;
  20162. const extensions = new Set(binaryExtensions);
  20163. var isBinaryPath$1 = filePath => extensions.has(path$7.extname(filePath).slice(1).toLowerCase());
  20164. var constants$1 = {};
  20165. (function (exports) {
  20166. const {sep} = require$$0$2;
  20167. const {platform} = process;
  20168. const os = require$$2;
  20169. exports.EV_ALL = 'all';
  20170. exports.EV_READY = 'ready';
  20171. exports.EV_ADD = 'add';
  20172. exports.EV_CHANGE = 'change';
  20173. exports.EV_ADD_DIR = 'addDir';
  20174. exports.EV_UNLINK = 'unlink';
  20175. exports.EV_UNLINK_DIR = 'unlinkDir';
  20176. exports.EV_RAW = 'raw';
  20177. exports.EV_ERROR = 'error';
  20178. exports.STR_DATA = 'data';
  20179. exports.STR_END = 'end';
  20180. exports.STR_CLOSE = 'close';
  20181. exports.FSEVENT_CREATED = 'created';
  20182. exports.FSEVENT_MODIFIED = 'modified';
  20183. exports.FSEVENT_DELETED = 'deleted';
  20184. exports.FSEVENT_MOVED = 'moved';
  20185. exports.FSEVENT_CLONED = 'cloned';
  20186. exports.FSEVENT_UNKNOWN = 'unknown';
  20187. exports.FSEVENT_FLAG_MUST_SCAN_SUBDIRS = 1;
  20188. exports.FSEVENT_TYPE_FILE = 'file';
  20189. exports.FSEVENT_TYPE_DIRECTORY = 'directory';
  20190. exports.FSEVENT_TYPE_SYMLINK = 'symlink';
  20191. exports.KEY_LISTENERS = 'listeners';
  20192. exports.KEY_ERR = 'errHandlers';
  20193. exports.KEY_RAW = 'rawEmitters';
  20194. exports.HANDLER_KEYS = [exports.KEY_LISTENERS, exports.KEY_ERR, exports.KEY_RAW];
  20195. exports.DOT_SLASH = `.${sep}`;
  20196. exports.BACK_SLASH_RE = /\\/g;
  20197. exports.DOUBLE_SLASH_RE = /\/\//;
  20198. exports.SLASH_OR_BACK_SLASH_RE = /[/\\]/;
  20199. exports.DOT_RE = /\..*\.(sw[px])$|~$|\.subl.*\.tmp/;
  20200. exports.REPLACER_RE = /^\.[/\\]/;
  20201. exports.SLASH = '/';
  20202. exports.SLASH_SLASH = '//';
  20203. exports.BRACE_START = '{';
  20204. exports.BANG = '!';
  20205. exports.ONE_DOT = '.';
  20206. exports.TWO_DOTS = '..';
  20207. exports.STAR = '*';
  20208. exports.GLOBSTAR = '**';
  20209. exports.ROOT_GLOBSTAR = '/**/*';
  20210. exports.SLASH_GLOBSTAR = '/**';
  20211. exports.DIR_SUFFIX = 'Dir';
  20212. exports.ANYMATCH_OPTS = {dot: true};
  20213. exports.STRING_TYPE = 'string';
  20214. exports.FUNCTION_TYPE = 'function';
  20215. exports.EMPTY_STR = '';
  20216. exports.EMPTY_FN = () => {};
  20217. exports.IDENTITY_FN = val => val;
  20218. exports.isWindows = platform === 'win32';
  20219. exports.isMacos = platform === 'darwin';
  20220. exports.isLinux = platform === 'linux';
  20221. exports.isIBMi = os.type() === 'OS400';
  20222. } (constants$1));
  20223. const fs$4 = require$$0$4;
  20224. const sysPath$2 = require$$0$2;
  20225. const { promisify: promisify$2 } = require$$1;
  20226. const isBinaryPath = isBinaryPath$1;
  20227. const {
  20228. isWindows: isWindows$2,
  20229. isLinux,
  20230. EMPTY_FN: EMPTY_FN$2,
  20231. EMPTY_STR: EMPTY_STR$1,
  20232. KEY_LISTENERS,
  20233. KEY_ERR,
  20234. KEY_RAW,
  20235. HANDLER_KEYS,
  20236. EV_CHANGE: EV_CHANGE$2,
  20237. EV_ADD: EV_ADD$2,
  20238. EV_ADD_DIR: EV_ADD_DIR$2,
  20239. EV_ERROR: EV_ERROR$2,
  20240. STR_DATA: STR_DATA$1,
  20241. STR_END: STR_END$2,
  20242. BRACE_START: BRACE_START$1,
  20243. STAR
  20244. } = constants$1;
  20245. const THROTTLE_MODE_WATCH = 'watch';
  20246. const open$1 = promisify$2(fs$4.open);
  20247. const stat$2 = promisify$2(fs$4.stat);
  20248. const lstat$1 = promisify$2(fs$4.lstat);
  20249. const close = promisify$2(fs$4.close);
  20250. const fsrealpath = promisify$2(fs$4.realpath);
  20251. const statMethods$1 = { lstat: lstat$1, stat: stat$2 };
  20252. // TODO: emit errors properly. Example: EMFILE on Macos.
  20253. const foreach = (val, fn) => {
  20254. if (val instanceof Set) {
  20255. val.forEach(fn);
  20256. } else {
  20257. fn(val);
  20258. }
  20259. };
  20260. const addAndConvert = (main, prop, item) => {
  20261. let container = main[prop];
  20262. if (!(container instanceof Set)) {
  20263. main[prop] = container = new Set([container]);
  20264. }
  20265. container.add(item);
  20266. };
  20267. const clearItem = cont => key => {
  20268. const set = cont[key];
  20269. if (set instanceof Set) {
  20270. set.clear();
  20271. } else {
  20272. delete cont[key];
  20273. }
  20274. };
  20275. const delFromSet = (main, prop, item) => {
  20276. const container = main[prop];
  20277. if (container instanceof Set) {
  20278. container.delete(item);
  20279. } else if (container === item) {
  20280. delete main[prop];
  20281. }
  20282. };
  20283. const isEmptySet = (val) => val instanceof Set ? val.size === 0 : !val;
  20284. /**
  20285. * @typedef {String} Path
  20286. */
  20287. // fs_watch helpers
  20288. // object to hold per-process fs_watch instances
  20289. // (may be shared across chokidar FSWatcher instances)
  20290. /**
  20291. * @typedef {Object} FsWatchContainer
  20292. * @property {Set} listeners
  20293. * @property {Set} errHandlers
  20294. * @property {Set} rawEmitters
  20295. * @property {fs.FSWatcher=} watcher
  20296. * @property {Boolean=} watcherUnusable
  20297. */
  20298. /**
  20299. * @type {Map<String,FsWatchContainer>}
  20300. */
  20301. const FsWatchInstances = new Map();
  20302. /**
  20303. * Instantiates the fs_watch interface
  20304. * @param {String} path to be watched
  20305. * @param {Object} options to be passed to fs_watch
  20306. * @param {Function} listener main event handler
  20307. * @param {Function} errHandler emits info about errors
  20308. * @param {Function} emitRaw emits raw event data
  20309. * @returns {fs.FSWatcher} new fsevents instance
  20310. */
  20311. function createFsWatchInstance(path, options, listener, errHandler, emitRaw) {
  20312. const handleEvent = (rawEvent, evPath) => {
  20313. listener(path);
  20314. emitRaw(rawEvent, evPath, {watchedPath: path});
  20315. // emit based on events occurring for files from a directory's watcher in
  20316. // case the file's watcher misses it (and rely on throttling to de-dupe)
  20317. if (evPath && path !== evPath) {
  20318. fsWatchBroadcast(
  20319. sysPath$2.resolve(path, evPath), KEY_LISTENERS, sysPath$2.join(path, evPath)
  20320. );
  20321. }
  20322. };
  20323. try {
  20324. return fs$4.watch(path, options, handleEvent);
  20325. } catch (error) {
  20326. errHandler(error);
  20327. }
  20328. }
  20329. /**
  20330. * Helper for passing fs_watch event data to a collection of listeners
  20331. * @param {Path} fullPath absolute path bound to fs_watch instance
  20332. * @param {String} type listener type
  20333. * @param {*=} val1 arguments to be passed to listeners
  20334. * @param {*=} val2
  20335. * @param {*=} val3
  20336. */
  20337. const fsWatchBroadcast = (fullPath, type, val1, val2, val3) => {
  20338. const cont = FsWatchInstances.get(fullPath);
  20339. if (!cont) return;
  20340. foreach(cont[type], (listener) => {
  20341. listener(val1, val2, val3);
  20342. });
  20343. };
  20344. /**
  20345. * Instantiates the fs_watch interface or binds listeners
  20346. * to an existing one covering the same file system entry
  20347. * @param {String} path
  20348. * @param {String} fullPath absolute path
  20349. * @param {Object} options to be passed to fs_watch
  20350. * @param {Object} handlers container for event listener functions
  20351. */
  20352. const setFsWatchListener = (path, fullPath, options, handlers) => {
  20353. const {listener, errHandler, rawEmitter} = handlers;
  20354. let cont = FsWatchInstances.get(fullPath);
  20355. /** @type {fs.FSWatcher=} */
  20356. let watcher;
  20357. if (!options.persistent) {
  20358. watcher = createFsWatchInstance(
  20359. path, options, listener, errHandler, rawEmitter
  20360. );
  20361. return watcher.close.bind(watcher);
  20362. }
  20363. if (cont) {
  20364. addAndConvert(cont, KEY_LISTENERS, listener);
  20365. addAndConvert(cont, KEY_ERR, errHandler);
  20366. addAndConvert(cont, KEY_RAW, rawEmitter);
  20367. } else {
  20368. watcher = createFsWatchInstance(
  20369. path,
  20370. options,
  20371. fsWatchBroadcast.bind(null, fullPath, KEY_LISTENERS),
  20372. errHandler, // no need to use broadcast here
  20373. fsWatchBroadcast.bind(null, fullPath, KEY_RAW)
  20374. );
  20375. if (!watcher) return;
  20376. watcher.on(EV_ERROR$2, async (error) => {
  20377. const broadcastErr = fsWatchBroadcast.bind(null, fullPath, KEY_ERR);
  20378. cont.watcherUnusable = true; // documented since Node 10.4.1
  20379. // Workaround for https://github.com/joyent/node/issues/4337
  20380. if (isWindows$2 && error.code === 'EPERM') {
  20381. try {
  20382. const fd = await open$1(path, 'r');
  20383. await close(fd);
  20384. broadcastErr(error);
  20385. } catch (err) {}
  20386. } else {
  20387. broadcastErr(error);
  20388. }
  20389. });
  20390. cont = {
  20391. listeners: listener,
  20392. errHandlers: errHandler,
  20393. rawEmitters: rawEmitter,
  20394. watcher
  20395. };
  20396. FsWatchInstances.set(fullPath, cont);
  20397. }
  20398. // const index = cont.listeners.indexOf(listener);
  20399. // removes this instance's listeners and closes the underlying fs_watch
  20400. // instance if there are no more listeners left
  20401. return () => {
  20402. delFromSet(cont, KEY_LISTENERS, listener);
  20403. delFromSet(cont, KEY_ERR, errHandler);
  20404. delFromSet(cont, KEY_RAW, rawEmitter);
  20405. if (isEmptySet(cont.listeners)) {
  20406. // Check to protect against issue gh-730.
  20407. // if (cont.watcherUnusable) {
  20408. cont.watcher.close();
  20409. // }
  20410. FsWatchInstances.delete(fullPath);
  20411. HANDLER_KEYS.forEach(clearItem(cont));
  20412. cont.watcher = undefined;
  20413. Object.freeze(cont);
  20414. }
  20415. };
  20416. };
  20417. // fs_watchFile helpers
  20418. // object to hold per-process fs_watchFile instances
  20419. // (may be shared across chokidar FSWatcher instances)
  20420. const FsWatchFileInstances = new Map();
  20421. /**
  20422. * Instantiates the fs_watchFile interface or binds listeners
  20423. * to an existing one covering the same file system entry
  20424. * @param {String} path to be watched
  20425. * @param {String} fullPath absolute path
  20426. * @param {Object} options options to be passed to fs_watchFile
  20427. * @param {Object} handlers container for event listener functions
  20428. * @returns {Function} closer
  20429. */
  20430. const setFsWatchFileListener = (path, fullPath, options, handlers) => {
  20431. const {listener, rawEmitter} = handlers;
  20432. let cont = FsWatchFileInstances.get(fullPath);
  20433. const copts = cont && cont.options;
  20434. if (copts && (copts.persistent < options.persistent || copts.interval > options.interval)) {
  20435. fs$4.unwatchFile(fullPath);
  20436. cont = undefined;
  20437. }
  20438. /* eslint-enable no-unused-vars, prefer-destructuring */
  20439. if (cont) {
  20440. addAndConvert(cont, KEY_LISTENERS, listener);
  20441. addAndConvert(cont, KEY_RAW, rawEmitter);
  20442. } else {
  20443. // TODO
  20444. // listeners.add(listener);
  20445. // rawEmitters.add(rawEmitter);
  20446. cont = {
  20447. listeners: listener,
  20448. rawEmitters: rawEmitter,
  20449. options,
  20450. watcher: fs$4.watchFile(fullPath, options, (curr, prev) => {
  20451. foreach(cont.rawEmitters, (rawEmitter) => {
  20452. rawEmitter(EV_CHANGE$2, fullPath, {curr, prev});
  20453. });
  20454. const currmtime = curr.mtimeMs;
  20455. if (curr.size !== prev.size || currmtime > prev.mtimeMs || currmtime === 0) {
  20456. foreach(cont.listeners, (listener) => listener(path, curr));
  20457. }
  20458. })
  20459. };
  20460. FsWatchFileInstances.set(fullPath, cont);
  20461. }
  20462. // const index = cont.listeners.indexOf(listener);
  20463. // Removes this instance's listeners and closes the underlying fs_watchFile
  20464. // instance if there are no more listeners left.
  20465. return () => {
  20466. delFromSet(cont, KEY_LISTENERS, listener);
  20467. delFromSet(cont, KEY_RAW, rawEmitter);
  20468. if (isEmptySet(cont.listeners)) {
  20469. FsWatchFileInstances.delete(fullPath);
  20470. fs$4.unwatchFile(fullPath);
  20471. cont.options = cont.watcher = undefined;
  20472. Object.freeze(cont);
  20473. }
  20474. };
  20475. };
  20476. /**
  20477. * @mixin
  20478. */
  20479. let NodeFsHandler$1 = class NodeFsHandler {
  20480. /**
  20481. * @param {import("../index").FSWatcher} fsW
  20482. */
  20483. constructor(fsW) {
  20484. this.fsw = fsW;
  20485. this._boundHandleError = (error) => fsW._handleError(error);
  20486. }
  20487. /**
  20488. * Watch file for changes with fs_watchFile or fs_watch.
  20489. * @param {String} path to file or dir
  20490. * @param {Function} listener on fs change
  20491. * @returns {Function} closer for the watcher instance
  20492. */
  20493. _watchWithNodeFs(path, listener) {
  20494. const opts = this.fsw.options;
  20495. const directory = sysPath$2.dirname(path);
  20496. const basename = sysPath$2.basename(path);
  20497. const parent = this.fsw._getWatchedDir(directory);
  20498. parent.add(basename);
  20499. const absolutePath = sysPath$2.resolve(path);
  20500. const options = {persistent: opts.persistent};
  20501. if (!listener) listener = EMPTY_FN$2;
  20502. let closer;
  20503. if (opts.usePolling) {
  20504. options.interval = opts.enableBinaryInterval && isBinaryPath(basename) ?
  20505. opts.binaryInterval : opts.interval;
  20506. closer = setFsWatchFileListener(path, absolutePath, options, {
  20507. listener,
  20508. rawEmitter: this.fsw._emitRaw
  20509. });
  20510. } else {
  20511. closer = setFsWatchListener(path, absolutePath, options, {
  20512. listener,
  20513. errHandler: this._boundHandleError,
  20514. rawEmitter: this.fsw._emitRaw
  20515. });
  20516. }
  20517. return closer;
  20518. }
  20519. /**
  20520. * Watch a file and emit add event if warranted.
  20521. * @param {Path} file Path
  20522. * @param {fs.Stats} stats result of fs_stat
  20523. * @param {Boolean} initialAdd was the file added at watch instantiation?
  20524. * @returns {Function} closer for the watcher instance
  20525. */
  20526. _handleFile(file, stats, initialAdd) {
  20527. if (this.fsw.closed) {
  20528. return;
  20529. }
  20530. const dirname = sysPath$2.dirname(file);
  20531. const basename = sysPath$2.basename(file);
  20532. const parent = this.fsw._getWatchedDir(dirname);
  20533. // stats is always present
  20534. let prevStats = stats;
  20535. // if the file is already being watched, do nothing
  20536. if (parent.has(basename)) return;
  20537. const listener = async (path, newStats) => {
  20538. if (!this.fsw._throttle(THROTTLE_MODE_WATCH, file, 5)) return;
  20539. if (!newStats || newStats.mtimeMs === 0) {
  20540. try {
  20541. const newStats = await stat$2(file);
  20542. if (this.fsw.closed) return;
  20543. // Check that change event was not fired because of changed only accessTime.
  20544. const at = newStats.atimeMs;
  20545. const mt = newStats.mtimeMs;
  20546. if (!at || at <= mt || mt !== prevStats.mtimeMs) {
  20547. this.fsw._emit(EV_CHANGE$2, file, newStats);
  20548. }
  20549. if (isLinux && prevStats.ino !== newStats.ino) {
  20550. this.fsw._closeFile(path);
  20551. prevStats = newStats;
  20552. this.fsw._addPathCloser(path, this._watchWithNodeFs(file, listener));
  20553. } else {
  20554. prevStats = newStats;
  20555. }
  20556. } catch (error) {
  20557. // Fix issues where mtime is null but file is still present
  20558. this.fsw._remove(dirname, basename);
  20559. }
  20560. // add is about to be emitted if file not already tracked in parent
  20561. } else if (parent.has(basename)) {
  20562. // Check that change event was not fired because of changed only accessTime.
  20563. const at = newStats.atimeMs;
  20564. const mt = newStats.mtimeMs;
  20565. if (!at || at <= mt || mt !== prevStats.mtimeMs) {
  20566. this.fsw._emit(EV_CHANGE$2, file, newStats);
  20567. }
  20568. prevStats = newStats;
  20569. }
  20570. };
  20571. // kick off the watcher
  20572. const closer = this._watchWithNodeFs(file, listener);
  20573. // emit an add event if we're supposed to
  20574. if (!(initialAdd && this.fsw.options.ignoreInitial) && this.fsw._isntIgnored(file)) {
  20575. if (!this.fsw._throttle(EV_ADD$2, file, 0)) return;
  20576. this.fsw._emit(EV_ADD$2, file, stats);
  20577. }
  20578. return closer;
  20579. }
  20580. /**
  20581. * Handle symlinks encountered while reading a dir.
  20582. * @param {Object} entry returned by readdirp
  20583. * @param {String} directory path of dir being read
  20584. * @param {String} path of this item
  20585. * @param {String} item basename of this item
  20586. * @returns {Promise<Boolean>} true if no more processing is needed for this entry.
  20587. */
  20588. async _handleSymlink(entry, directory, path, item) {
  20589. if (this.fsw.closed) {
  20590. return;
  20591. }
  20592. const full = entry.fullPath;
  20593. const dir = this.fsw._getWatchedDir(directory);
  20594. if (!this.fsw.options.followSymlinks) {
  20595. // watch symlink directly (don't follow) and detect changes
  20596. this.fsw._incrReadyCount();
  20597. let linkPath;
  20598. try {
  20599. linkPath = await fsrealpath(path);
  20600. } catch (e) {
  20601. this.fsw._emitReady();
  20602. return true;
  20603. }
  20604. if (this.fsw.closed) return;
  20605. if (dir.has(item)) {
  20606. if (this.fsw._symlinkPaths.get(full) !== linkPath) {
  20607. this.fsw._symlinkPaths.set(full, linkPath);
  20608. this.fsw._emit(EV_CHANGE$2, path, entry.stats);
  20609. }
  20610. } else {
  20611. dir.add(item);
  20612. this.fsw._symlinkPaths.set(full, linkPath);
  20613. this.fsw._emit(EV_ADD$2, path, entry.stats);
  20614. }
  20615. this.fsw._emitReady();
  20616. return true;
  20617. }
  20618. // don't follow the same symlink more than once
  20619. if (this.fsw._symlinkPaths.has(full)) {
  20620. return true;
  20621. }
  20622. this.fsw._symlinkPaths.set(full, true);
  20623. }
  20624. _handleRead(directory, initialAdd, wh, target, dir, depth, throttler) {
  20625. // Normalize the directory name on Windows
  20626. directory = sysPath$2.join(directory, EMPTY_STR$1);
  20627. if (!wh.hasGlob) {
  20628. throttler = this.fsw._throttle('readdir', directory, 1000);
  20629. if (!throttler) return;
  20630. }
  20631. const previous = this.fsw._getWatchedDir(wh.path);
  20632. const current = new Set();
  20633. let stream = this.fsw._readdirp(directory, {
  20634. fileFilter: entry => wh.filterPath(entry),
  20635. directoryFilter: entry => wh.filterDir(entry),
  20636. depth: 0
  20637. }).on(STR_DATA$1, async (entry) => {
  20638. if (this.fsw.closed) {
  20639. stream = undefined;
  20640. return;
  20641. }
  20642. const item = entry.path;
  20643. let path = sysPath$2.join(directory, item);
  20644. current.add(item);
  20645. if (entry.stats.isSymbolicLink() && await this._handleSymlink(entry, directory, path, item)) {
  20646. return;
  20647. }
  20648. if (this.fsw.closed) {
  20649. stream = undefined;
  20650. return;
  20651. }
  20652. // Files that present in current directory snapshot
  20653. // but absent in previous are added to watch list and
  20654. // emit `add` event.
  20655. if (item === target || !target && !previous.has(item)) {
  20656. this.fsw._incrReadyCount();
  20657. // ensure relativeness of path is preserved in case of watcher reuse
  20658. path = sysPath$2.join(dir, sysPath$2.relative(dir, path));
  20659. this._addToNodeFs(path, initialAdd, wh, depth + 1);
  20660. }
  20661. }).on(EV_ERROR$2, this._boundHandleError);
  20662. return new Promise(resolve =>
  20663. stream.once(STR_END$2, () => {
  20664. if (this.fsw.closed) {
  20665. stream = undefined;
  20666. return;
  20667. }
  20668. const wasThrottled = throttler ? throttler.clear() : false;
  20669. resolve();
  20670. // Files that absent in current directory snapshot
  20671. // but present in previous emit `remove` event
  20672. // and are removed from @watched[directory].
  20673. previous.getChildren().filter((item) => {
  20674. return item !== directory &&
  20675. !current.has(item) &&
  20676. // in case of intersecting globs;
  20677. // a path may have been filtered out of this readdir, but
  20678. // shouldn't be removed because it matches a different glob
  20679. (!wh.hasGlob || wh.filterPath({
  20680. fullPath: sysPath$2.resolve(directory, item)
  20681. }));
  20682. }).forEach((item) => {
  20683. this.fsw._remove(directory, item);
  20684. });
  20685. stream = undefined;
  20686. // one more time for any missed in case changes came in extremely quickly
  20687. if (wasThrottled) this._handleRead(directory, false, wh, target, dir, depth, throttler);
  20688. })
  20689. );
  20690. }
  20691. /**
  20692. * Read directory to add / remove files from `@watched` list and re-read it on change.
  20693. * @param {String} dir fs path
  20694. * @param {fs.Stats} stats
  20695. * @param {Boolean} initialAdd
  20696. * @param {Number} depth relative to user-supplied path
  20697. * @param {String} target child path targeted for watch
  20698. * @param {Object} wh Common watch helpers for this path
  20699. * @param {String} realpath
  20700. * @returns {Promise<Function>} closer for the watcher instance.
  20701. */
  20702. async _handleDir(dir, stats, initialAdd, depth, target, wh, realpath) {
  20703. const parentDir = this.fsw._getWatchedDir(sysPath$2.dirname(dir));
  20704. const tracked = parentDir.has(sysPath$2.basename(dir));
  20705. if (!(initialAdd && this.fsw.options.ignoreInitial) && !target && !tracked) {
  20706. if (!wh.hasGlob || wh.globFilter(dir)) this.fsw._emit(EV_ADD_DIR$2, dir, stats);
  20707. }
  20708. // ensure dir is tracked (harmless if redundant)
  20709. parentDir.add(sysPath$2.basename(dir));
  20710. this.fsw._getWatchedDir(dir);
  20711. let throttler;
  20712. let closer;
  20713. const oDepth = this.fsw.options.depth;
  20714. if ((oDepth == null || depth <= oDepth) && !this.fsw._symlinkPaths.has(realpath)) {
  20715. if (!target) {
  20716. await this._handleRead(dir, initialAdd, wh, target, dir, depth, throttler);
  20717. if (this.fsw.closed) return;
  20718. }
  20719. closer = this._watchWithNodeFs(dir, (dirPath, stats) => {
  20720. // if current directory is removed, do nothing
  20721. if (stats && stats.mtimeMs === 0) return;
  20722. this._handleRead(dirPath, false, wh, target, dir, depth, throttler);
  20723. });
  20724. }
  20725. return closer;
  20726. }
  20727. /**
  20728. * Handle added file, directory, or glob pattern.
  20729. * Delegates call to _handleFile / _handleDir after checks.
  20730. * @param {String} path to file or ir
  20731. * @param {Boolean} initialAdd was the file added at watch instantiation?
  20732. * @param {Object} priorWh depth relative to user-supplied path
  20733. * @param {Number} depth Child path actually targeted for watch
  20734. * @param {String=} target Child path actually targeted for watch
  20735. * @returns {Promise}
  20736. */
  20737. async _addToNodeFs(path, initialAdd, priorWh, depth, target) {
  20738. const ready = this.fsw._emitReady;
  20739. if (this.fsw._isIgnored(path) || this.fsw.closed) {
  20740. ready();
  20741. return false;
  20742. }
  20743. const wh = this.fsw._getWatchHelpers(path, depth);
  20744. if (!wh.hasGlob && priorWh) {
  20745. wh.hasGlob = priorWh.hasGlob;
  20746. wh.globFilter = priorWh.globFilter;
  20747. wh.filterPath = entry => priorWh.filterPath(entry);
  20748. wh.filterDir = entry => priorWh.filterDir(entry);
  20749. }
  20750. // evaluate what is at the path we're being asked to watch
  20751. try {
  20752. const stats = await statMethods$1[wh.statMethod](wh.watchPath);
  20753. if (this.fsw.closed) return;
  20754. if (this.fsw._isIgnored(wh.watchPath, stats)) {
  20755. ready();
  20756. return false;
  20757. }
  20758. const follow = this.fsw.options.followSymlinks && !path.includes(STAR) && !path.includes(BRACE_START$1);
  20759. let closer;
  20760. if (stats.isDirectory()) {
  20761. const absPath = sysPath$2.resolve(path);
  20762. const targetPath = follow ? await fsrealpath(path) : path;
  20763. if (this.fsw.closed) return;
  20764. closer = await this._handleDir(wh.watchPath, stats, initialAdd, depth, target, wh, targetPath);
  20765. if (this.fsw.closed) return;
  20766. // preserve this symlink's target path
  20767. if (absPath !== targetPath && targetPath !== undefined) {
  20768. this.fsw._symlinkPaths.set(absPath, targetPath);
  20769. }
  20770. } else if (stats.isSymbolicLink()) {
  20771. const targetPath = follow ? await fsrealpath(path) : path;
  20772. if (this.fsw.closed) return;
  20773. const parent = sysPath$2.dirname(wh.watchPath);
  20774. this.fsw._getWatchedDir(parent).add(wh.watchPath);
  20775. this.fsw._emit(EV_ADD$2, wh.watchPath, stats);
  20776. closer = await this._handleDir(parent, stats, initialAdd, depth, path, wh, targetPath);
  20777. if (this.fsw.closed) return;
  20778. // preserve this symlink's target path
  20779. if (targetPath !== undefined) {
  20780. this.fsw._symlinkPaths.set(sysPath$2.resolve(path), targetPath);
  20781. }
  20782. } else {
  20783. closer = this._handleFile(wh.watchPath, stats, initialAdd);
  20784. }
  20785. ready();
  20786. this.fsw._addPathCloser(path, closer);
  20787. return false;
  20788. } catch (error) {
  20789. if (this.fsw._handleError(error)) {
  20790. ready();
  20791. return path;
  20792. }
  20793. }
  20794. }
  20795. };
  20796. var nodefsHandler = NodeFsHandler$1;
  20797. var fseventsHandler = {exports: {}};
  20798. const fs$3 = require$$0$4;
  20799. const sysPath$1 = require$$0$2;
  20800. const { promisify: promisify$1 } = require$$1;
  20801. let fsevents;
  20802. try {
  20803. fsevents = __require('fsevents');
  20804. } catch (error) {
  20805. if (process.env.CHOKIDAR_PRINT_FSEVENTS_REQUIRE_ERROR) console.error(error);
  20806. }
  20807. if (fsevents) {
  20808. // TODO: real check
  20809. const mtch = process.version.match(/v(\d+)\.(\d+)/);
  20810. if (mtch && mtch[1] && mtch[2]) {
  20811. const maj = Number.parseInt(mtch[1], 10);
  20812. const min = Number.parseInt(mtch[2], 10);
  20813. if (maj === 8 && min < 16) {
  20814. fsevents = undefined;
  20815. }
  20816. }
  20817. }
  20818. const {
  20819. EV_ADD: EV_ADD$1,
  20820. EV_CHANGE: EV_CHANGE$1,
  20821. EV_ADD_DIR: EV_ADD_DIR$1,
  20822. EV_UNLINK: EV_UNLINK$1,
  20823. EV_ERROR: EV_ERROR$1,
  20824. STR_DATA,
  20825. STR_END: STR_END$1,
  20826. FSEVENT_CREATED,
  20827. FSEVENT_MODIFIED,
  20828. FSEVENT_DELETED,
  20829. FSEVENT_MOVED,
  20830. // FSEVENT_CLONED,
  20831. FSEVENT_UNKNOWN,
  20832. FSEVENT_FLAG_MUST_SCAN_SUBDIRS,
  20833. FSEVENT_TYPE_FILE,
  20834. FSEVENT_TYPE_DIRECTORY,
  20835. FSEVENT_TYPE_SYMLINK,
  20836. ROOT_GLOBSTAR,
  20837. DIR_SUFFIX,
  20838. DOT_SLASH,
  20839. FUNCTION_TYPE: FUNCTION_TYPE$1,
  20840. EMPTY_FN: EMPTY_FN$1,
  20841. IDENTITY_FN
  20842. } = constants$1;
  20843. const Depth = (value) => isNaN(value) ? {} : {depth: value};
  20844. const stat$1 = promisify$1(fs$3.stat);
  20845. const lstat = promisify$1(fs$3.lstat);
  20846. const realpath = promisify$1(fs$3.realpath);
  20847. const statMethods = { stat: stat$1, lstat };
  20848. /**
  20849. * @typedef {String} Path
  20850. */
  20851. /**
  20852. * @typedef {Object} FsEventsWatchContainer
  20853. * @property {Set<Function>} listeners
  20854. * @property {Function} rawEmitter
  20855. * @property {{stop: Function}} watcher
  20856. */
  20857. // fsevents instance helper functions
  20858. /**
  20859. * Object to hold per-process fsevents instances (may be shared across chokidar FSWatcher instances)
  20860. * @type {Map<Path,FsEventsWatchContainer>}
  20861. */
  20862. const FSEventsWatchers = new Map();
  20863. // Threshold of duplicate path prefixes at which to start
  20864. // consolidating going forward
  20865. const consolidateThreshhold = 10;
  20866. const wrongEventFlags = new Set([
  20867. 69888, 70400, 71424, 72704, 73472, 131328, 131840, 262912
  20868. ]);
  20869. /**
  20870. * Instantiates the fsevents interface
  20871. * @param {Path} path path to be watched
  20872. * @param {Function} callback called when fsevents is bound and ready
  20873. * @returns {{stop: Function}} new fsevents instance
  20874. */
  20875. const createFSEventsInstance = (path, callback) => {
  20876. const stop = fsevents.watch(path, callback);
  20877. return {stop};
  20878. };
  20879. /**
  20880. * Instantiates the fsevents interface or binds listeners to an existing one covering
  20881. * the same file tree.
  20882. * @param {Path} path - to be watched
  20883. * @param {Path} realPath - real path for symlinks
  20884. * @param {Function} listener - called when fsevents emits events
  20885. * @param {Function} rawEmitter - passes data to listeners of the 'raw' event
  20886. * @returns {Function} closer
  20887. */
  20888. function setFSEventsListener(path, realPath, listener, rawEmitter) {
  20889. let watchPath = sysPath$1.extname(realPath) ? sysPath$1.dirname(realPath) : realPath;
  20890. const parentPath = sysPath$1.dirname(watchPath);
  20891. let cont = FSEventsWatchers.get(watchPath);
  20892. // If we've accumulated a substantial number of paths that
  20893. // could have been consolidated by watching one directory
  20894. // above the current one, create a watcher on the parent
  20895. // path instead, so that we do consolidate going forward.
  20896. if (couldConsolidate(parentPath)) {
  20897. watchPath = parentPath;
  20898. }
  20899. const resolvedPath = sysPath$1.resolve(path);
  20900. const hasSymlink = resolvedPath !== realPath;
  20901. const filteredListener = (fullPath, flags, info) => {
  20902. if (hasSymlink) fullPath = fullPath.replace(realPath, resolvedPath);
  20903. if (
  20904. fullPath === resolvedPath ||
  20905. !fullPath.indexOf(resolvedPath + sysPath$1.sep)
  20906. ) listener(fullPath, flags, info);
  20907. };
  20908. // check if there is already a watcher on a parent path
  20909. // modifies `watchPath` to the parent path when it finds a match
  20910. let watchedParent = false;
  20911. for (const watchedPath of FSEventsWatchers.keys()) {
  20912. if (realPath.indexOf(sysPath$1.resolve(watchedPath) + sysPath$1.sep) === 0) {
  20913. watchPath = watchedPath;
  20914. cont = FSEventsWatchers.get(watchPath);
  20915. watchedParent = true;
  20916. break;
  20917. }
  20918. }
  20919. if (cont || watchedParent) {
  20920. cont.listeners.add(filteredListener);
  20921. } else {
  20922. cont = {
  20923. listeners: new Set([filteredListener]),
  20924. rawEmitter,
  20925. watcher: createFSEventsInstance(watchPath, (fullPath, flags) => {
  20926. if (!cont.listeners.size) return;
  20927. if (flags & FSEVENT_FLAG_MUST_SCAN_SUBDIRS) return;
  20928. const info = fsevents.getInfo(fullPath, flags);
  20929. cont.listeners.forEach(list => {
  20930. list(fullPath, flags, info);
  20931. });
  20932. cont.rawEmitter(info.event, fullPath, info);
  20933. })
  20934. };
  20935. FSEventsWatchers.set(watchPath, cont);
  20936. }
  20937. // removes this instance's listeners and closes the underlying fsevents
  20938. // instance if there are no more listeners left
  20939. return () => {
  20940. const lst = cont.listeners;
  20941. lst.delete(filteredListener);
  20942. if (!lst.size) {
  20943. FSEventsWatchers.delete(watchPath);
  20944. if (cont.watcher) return cont.watcher.stop().then(() => {
  20945. cont.rawEmitter = cont.watcher = undefined;
  20946. Object.freeze(cont);
  20947. });
  20948. }
  20949. };
  20950. }
  20951. // Decide whether or not we should start a new higher-level
  20952. // parent watcher
  20953. const couldConsolidate = (path) => {
  20954. let count = 0;
  20955. for (const watchPath of FSEventsWatchers.keys()) {
  20956. if (watchPath.indexOf(path) === 0) {
  20957. count++;
  20958. if (count >= consolidateThreshhold) {
  20959. return true;
  20960. }
  20961. }
  20962. }
  20963. return false;
  20964. };
  20965. // returns boolean indicating whether fsevents can be used
  20966. const canUse = () => fsevents && FSEventsWatchers.size < 128;
  20967. // determines subdirectory traversal levels from root to path
  20968. const calcDepth = (path, root) => {
  20969. let i = 0;
  20970. while (!path.indexOf(root) && (path = sysPath$1.dirname(path)) !== root) i++;
  20971. return i;
  20972. };
  20973. // returns boolean indicating whether the fsevents' event info has the same type
  20974. // as the one returned by fs.stat
  20975. const sameTypes = (info, stats) => (
  20976. info.type === FSEVENT_TYPE_DIRECTORY && stats.isDirectory() ||
  20977. info.type === FSEVENT_TYPE_SYMLINK && stats.isSymbolicLink() ||
  20978. info.type === FSEVENT_TYPE_FILE && stats.isFile()
  20979. );
  20980. /**
  20981. * @mixin
  20982. */
  20983. let FsEventsHandler$1 = class FsEventsHandler {
  20984. /**
  20985. * @param {import('../index').FSWatcher} fsw
  20986. */
  20987. constructor(fsw) {
  20988. this.fsw = fsw;
  20989. }
  20990. checkIgnored(path, stats) {
  20991. const ipaths = this.fsw._ignoredPaths;
  20992. if (this.fsw._isIgnored(path, stats)) {
  20993. ipaths.add(path);
  20994. if (stats && stats.isDirectory()) {
  20995. ipaths.add(path + ROOT_GLOBSTAR);
  20996. }
  20997. return true;
  20998. }
  20999. ipaths.delete(path);
  21000. ipaths.delete(path + ROOT_GLOBSTAR);
  21001. }
  21002. addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts) {
  21003. const event = watchedDir.has(item) ? EV_CHANGE$1 : EV_ADD$1;
  21004. this.handleEvent(event, path, fullPath, realPath, parent, watchedDir, item, info, opts);
  21005. }
  21006. async checkExists(path, fullPath, realPath, parent, watchedDir, item, info, opts) {
  21007. try {
  21008. const stats = await stat$1(path);
  21009. if (this.fsw.closed) return;
  21010. if (sameTypes(info, stats)) {
  21011. this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts);
  21012. } else {
  21013. this.handleEvent(EV_UNLINK$1, path, fullPath, realPath, parent, watchedDir, item, info, opts);
  21014. }
  21015. } catch (error) {
  21016. if (error.code === 'EACCES') {
  21017. this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts);
  21018. } else {
  21019. this.handleEvent(EV_UNLINK$1, path, fullPath, realPath, parent, watchedDir, item, info, opts);
  21020. }
  21021. }
  21022. }
  21023. handleEvent(event, path, fullPath, realPath, parent, watchedDir, item, info, opts) {
  21024. if (this.fsw.closed || this.checkIgnored(path)) return;
  21025. if (event === EV_UNLINK$1) {
  21026. const isDirectory = info.type === FSEVENT_TYPE_DIRECTORY;
  21027. // suppress unlink events on never before seen files
  21028. if (isDirectory || watchedDir.has(item)) {
  21029. this.fsw._remove(parent, item, isDirectory);
  21030. }
  21031. } else {
  21032. if (event === EV_ADD$1) {
  21033. // track new directories
  21034. if (info.type === FSEVENT_TYPE_DIRECTORY) this.fsw._getWatchedDir(path);
  21035. if (info.type === FSEVENT_TYPE_SYMLINK && opts.followSymlinks) {
  21036. // push symlinks back to the top of the stack to get handled
  21037. const curDepth = opts.depth === undefined ?
  21038. undefined : calcDepth(fullPath, realPath) + 1;
  21039. return this._addToFsEvents(path, false, true, curDepth);
  21040. }
  21041. // track new paths
  21042. // (other than symlinks being followed, which will be tracked soon)
  21043. this.fsw._getWatchedDir(parent).add(item);
  21044. }
  21045. /**
  21046. * @type {'add'|'addDir'|'unlink'|'unlinkDir'}
  21047. */
  21048. const eventName = info.type === FSEVENT_TYPE_DIRECTORY ? event + DIR_SUFFIX : event;
  21049. this.fsw._emit(eventName, path);
  21050. if (eventName === EV_ADD_DIR$1) this._addToFsEvents(path, false, true);
  21051. }
  21052. }
  21053. /**
  21054. * Handle symlinks encountered during directory scan
  21055. * @param {String} watchPath - file/dir path to be watched with fsevents
  21056. * @param {String} realPath - real path (in case of symlinks)
  21057. * @param {Function} transform - path transformer
  21058. * @param {Function} globFilter - path filter in case a glob pattern was provided
  21059. * @returns {Function} closer for the watcher instance
  21060. */
  21061. _watchWithFsEvents(watchPath, realPath, transform, globFilter) {
  21062. if (this.fsw.closed || this.fsw._isIgnored(watchPath)) return;
  21063. const opts = this.fsw.options;
  21064. const watchCallback = async (fullPath, flags, info) => {
  21065. // PATCH: bypass the callback for better perf when fullPath hit the ignored file list
  21066. if (this.fsw.closed || this.fsw._isIgnored(fullPath)) return;
  21067. if (
  21068. opts.depth !== undefined &&
  21069. calcDepth(fullPath, realPath) > opts.depth
  21070. ) return;
  21071. const path = transform(sysPath$1.join(
  21072. watchPath, sysPath$1.relative(watchPath, fullPath)
  21073. ));
  21074. if (globFilter && !globFilter(path)) return;
  21075. // ensure directories are tracked
  21076. const parent = sysPath$1.dirname(path);
  21077. const item = sysPath$1.basename(path);
  21078. const watchedDir = this.fsw._getWatchedDir(
  21079. info.type === FSEVENT_TYPE_DIRECTORY ? path : parent
  21080. );
  21081. // correct for wrong events emitted
  21082. if (wrongEventFlags.has(flags) || info.event === FSEVENT_UNKNOWN) {
  21083. if (typeof opts.ignored === FUNCTION_TYPE$1) {
  21084. let stats;
  21085. try {
  21086. stats = await stat$1(path);
  21087. } catch (error) {}
  21088. if (this.fsw.closed) return;
  21089. if (this.checkIgnored(path, stats)) return;
  21090. if (sameTypes(info, stats)) {
  21091. this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts);
  21092. } else {
  21093. this.handleEvent(EV_UNLINK$1, path, fullPath, realPath, parent, watchedDir, item, info, opts);
  21094. }
  21095. } else {
  21096. this.checkExists(path, fullPath, realPath, parent, watchedDir, item, info, opts);
  21097. }
  21098. } else {
  21099. switch (info.event) {
  21100. case FSEVENT_CREATED:
  21101. case FSEVENT_MODIFIED:
  21102. return this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts);
  21103. case FSEVENT_DELETED:
  21104. case FSEVENT_MOVED:
  21105. return this.checkExists(path, fullPath, realPath, parent, watchedDir, item, info, opts);
  21106. }
  21107. }
  21108. };
  21109. const closer = setFSEventsListener(
  21110. watchPath,
  21111. realPath,
  21112. watchCallback,
  21113. this.fsw._emitRaw
  21114. );
  21115. this.fsw._emitReady();
  21116. return closer;
  21117. }
  21118. /**
  21119. * Handle symlinks encountered during directory scan
  21120. * @param {String} linkPath path to symlink
  21121. * @param {String} fullPath absolute path to the symlink
  21122. * @param {Function} transform pre-existing path transformer
  21123. * @param {Number} curDepth level of subdirectories traversed to where symlink is
  21124. * @returns {Promise<void>}
  21125. */
  21126. async _handleFsEventsSymlink(linkPath, fullPath, transform, curDepth) {
  21127. // don't follow the same symlink more than once
  21128. if (this.fsw.closed || this.fsw._symlinkPaths.has(fullPath)) return;
  21129. this.fsw._symlinkPaths.set(fullPath, true);
  21130. this.fsw._incrReadyCount();
  21131. try {
  21132. const linkTarget = await realpath(linkPath);
  21133. if (this.fsw.closed) return;
  21134. if (this.fsw._isIgnored(linkTarget)) {
  21135. return this.fsw._emitReady();
  21136. }
  21137. this.fsw._incrReadyCount();
  21138. // add the linkTarget for watching with a wrapper for transform
  21139. // that causes emitted paths to incorporate the link's path
  21140. this._addToFsEvents(linkTarget || linkPath, (path) => {
  21141. let aliasedPath = linkPath;
  21142. if (linkTarget && linkTarget !== DOT_SLASH) {
  21143. aliasedPath = path.replace(linkTarget, linkPath);
  21144. } else if (path !== DOT_SLASH) {
  21145. aliasedPath = sysPath$1.join(linkPath, path);
  21146. }
  21147. return transform(aliasedPath);
  21148. }, false, curDepth);
  21149. } catch(error) {
  21150. if (this.fsw._handleError(error)) {
  21151. return this.fsw._emitReady();
  21152. }
  21153. }
  21154. }
  21155. /**
  21156. *
  21157. * @param {Path} newPath
  21158. * @param {fs.Stats} stats
  21159. */
  21160. emitAdd(newPath, stats, processPath, opts, forceAdd) {
  21161. const pp = processPath(newPath);
  21162. const isDir = stats.isDirectory();
  21163. const dirObj = this.fsw._getWatchedDir(sysPath$1.dirname(pp));
  21164. const base = sysPath$1.basename(pp);
  21165. // ensure empty dirs get tracked
  21166. if (isDir) this.fsw._getWatchedDir(pp);
  21167. if (dirObj.has(base)) return;
  21168. dirObj.add(base);
  21169. if (!opts.ignoreInitial || forceAdd === true) {
  21170. this.fsw._emit(isDir ? EV_ADD_DIR$1 : EV_ADD$1, pp, stats);
  21171. }
  21172. }
  21173. initWatch(realPath, path, wh, processPath) {
  21174. if (this.fsw.closed) return;
  21175. const closer = this._watchWithFsEvents(
  21176. wh.watchPath,
  21177. sysPath$1.resolve(realPath || wh.watchPath),
  21178. processPath,
  21179. wh.globFilter
  21180. );
  21181. this.fsw._addPathCloser(path, closer);
  21182. }
  21183. /**
  21184. * Handle added path with fsevents
  21185. * @param {String} path file/dir path or glob pattern
  21186. * @param {Function|Boolean=} transform converts working path to what the user expects
  21187. * @param {Boolean=} forceAdd ensure add is emitted
  21188. * @param {Number=} priorDepth Level of subdirectories already traversed.
  21189. * @returns {Promise<void>}
  21190. */
  21191. async _addToFsEvents(path, transform, forceAdd, priorDepth) {
  21192. if (this.fsw.closed) {
  21193. return;
  21194. }
  21195. const opts = this.fsw.options;
  21196. const processPath = typeof transform === FUNCTION_TYPE$1 ? transform : IDENTITY_FN;
  21197. const wh = this.fsw._getWatchHelpers(path);
  21198. // evaluate what is at the path we're being asked to watch
  21199. try {
  21200. const stats = await statMethods[wh.statMethod](wh.watchPath);
  21201. if (this.fsw.closed) return;
  21202. if (this.fsw._isIgnored(wh.watchPath, stats)) {
  21203. throw null;
  21204. }
  21205. if (stats.isDirectory()) {
  21206. // emit addDir unless this is a glob parent
  21207. if (!wh.globFilter) this.emitAdd(processPath(path), stats, processPath, opts, forceAdd);
  21208. // don't recurse further if it would exceed depth setting
  21209. if (priorDepth && priorDepth > opts.depth) return;
  21210. // scan the contents of the dir
  21211. this.fsw._readdirp(wh.watchPath, {
  21212. fileFilter: entry => wh.filterPath(entry),
  21213. directoryFilter: entry => wh.filterDir(entry),
  21214. ...Depth(opts.depth - (priorDepth || 0))
  21215. }).on(STR_DATA, (entry) => {
  21216. // need to check filterPath on dirs b/c filterDir is less restrictive
  21217. if (this.fsw.closed) {
  21218. return;
  21219. }
  21220. if (entry.stats.isDirectory() && !wh.filterPath(entry)) return;
  21221. const joinedPath = sysPath$1.join(wh.watchPath, entry.path);
  21222. const {fullPath} = entry;
  21223. if (wh.followSymlinks && entry.stats.isSymbolicLink()) {
  21224. // preserve the current depth here since it can't be derived from
  21225. // real paths past the symlink
  21226. const curDepth = opts.depth === undefined ?
  21227. undefined : calcDepth(joinedPath, sysPath$1.resolve(wh.watchPath)) + 1;
  21228. this._handleFsEventsSymlink(joinedPath, fullPath, processPath, curDepth);
  21229. } else {
  21230. this.emitAdd(joinedPath, entry.stats, processPath, opts, forceAdd);
  21231. }
  21232. }).on(EV_ERROR$1, EMPTY_FN$1).on(STR_END$1, () => {
  21233. this.fsw._emitReady();
  21234. });
  21235. } else {
  21236. this.emitAdd(wh.watchPath, stats, processPath, opts, forceAdd);
  21237. this.fsw._emitReady();
  21238. }
  21239. } catch (error) {
  21240. if (!error || this.fsw._handleError(error)) {
  21241. // TODO: Strange thing: "should not choke on an ignored watch path" will be failed without 2 ready calls -__-
  21242. this.fsw._emitReady();
  21243. this.fsw._emitReady();
  21244. }
  21245. }
  21246. if (opts.persistent && forceAdd !== true) {
  21247. if (typeof transform === FUNCTION_TYPE$1) {
  21248. // realpath has already been resolved
  21249. this.initWatch(undefined, path, wh, processPath);
  21250. } else {
  21251. let realPath;
  21252. try {
  21253. realPath = await realpath(wh.watchPath);
  21254. } catch (e) {}
  21255. this.initWatch(realPath, path, wh, processPath);
  21256. }
  21257. }
  21258. }
  21259. };
  21260. fseventsHandler.exports = FsEventsHandler$1;
  21261. fseventsHandler.exports.canUse = canUse;
  21262. var fseventsHandlerExports = fseventsHandler.exports;
  21263. const { EventEmitter: EventEmitter$2 } = require$$0$7;
  21264. const fs$2 = require$$0$4;
  21265. const sysPath = require$$0$2;
  21266. const { promisify } = require$$1;
  21267. const readdirp = readdirp_1;
  21268. const anymatch = anymatchExports.default;
  21269. const globParent = globParent$1;
  21270. const isGlob = isGlob$2;
  21271. const braces = braces_1;
  21272. const normalizePath = normalizePath$2;
  21273. const NodeFsHandler = nodefsHandler;
  21274. const FsEventsHandler = fseventsHandlerExports;
  21275. const {
  21276. EV_ALL,
  21277. EV_READY,
  21278. EV_ADD,
  21279. EV_CHANGE,
  21280. EV_UNLINK,
  21281. EV_ADD_DIR,
  21282. EV_UNLINK_DIR,
  21283. EV_RAW,
  21284. EV_ERROR,
  21285. STR_CLOSE,
  21286. STR_END,
  21287. BACK_SLASH_RE,
  21288. DOUBLE_SLASH_RE,
  21289. SLASH_OR_BACK_SLASH_RE,
  21290. DOT_RE,
  21291. REPLACER_RE,
  21292. SLASH,
  21293. SLASH_SLASH,
  21294. BRACE_START,
  21295. BANG,
  21296. ONE_DOT,
  21297. TWO_DOTS,
  21298. GLOBSTAR,
  21299. SLASH_GLOBSTAR,
  21300. ANYMATCH_OPTS,
  21301. STRING_TYPE,
  21302. FUNCTION_TYPE,
  21303. EMPTY_STR,
  21304. EMPTY_FN,
  21305. isWindows: isWindows$1,
  21306. isMacos,
  21307. isIBMi
  21308. } = constants$1;
  21309. const stat = promisify(fs$2.stat);
  21310. const readdir = promisify(fs$2.readdir);
  21311. /**
  21312. * @typedef {String} Path
  21313. * @typedef {'all'|'add'|'addDir'|'change'|'unlink'|'unlinkDir'|'raw'|'error'|'ready'} EventName
  21314. * @typedef {'readdir'|'watch'|'add'|'remove'|'change'} ThrottleType
  21315. */
  21316. /**
  21317. *
  21318. * @typedef {Object} WatchHelpers
  21319. * @property {Boolean} followSymlinks
  21320. * @property {'stat'|'lstat'} statMethod
  21321. * @property {Path} path
  21322. * @property {Path} watchPath
  21323. * @property {Function} entryPath
  21324. * @property {Boolean} hasGlob
  21325. * @property {Object} globFilter
  21326. * @property {Function} filterPath
  21327. * @property {Function} filterDir
  21328. */
  21329. const arrify = (value = []) => Array.isArray(value) ? value : [value];
  21330. const flatten = (list, result = []) => {
  21331. list.forEach(item => {
  21332. if (Array.isArray(item)) {
  21333. flatten(item, result);
  21334. } else {
  21335. result.push(item);
  21336. }
  21337. });
  21338. return result;
  21339. };
  21340. const unifyPaths = (paths_) => {
  21341. /**
  21342. * @type {Array<String>}
  21343. */
  21344. const paths = flatten(arrify(paths_));
  21345. if (!paths.every(p => typeof p === STRING_TYPE)) {
  21346. throw new TypeError(`Non-string provided as watch path: ${paths}`);
  21347. }
  21348. return paths.map(normalizePathToUnix);
  21349. };
  21350. // If SLASH_SLASH occurs at the beginning of path, it is not replaced
  21351. // because "//StoragePC/DrivePool/Movies" is a valid network path
  21352. const toUnix = (string) => {
  21353. let str = string.replace(BACK_SLASH_RE, SLASH);
  21354. let prepend = false;
  21355. if (str.startsWith(SLASH_SLASH)) {
  21356. prepend = true;
  21357. }
  21358. while (str.match(DOUBLE_SLASH_RE)) {
  21359. str = str.replace(DOUBLE_SLASH_RE, SLASH);
  21360. }
  21361. if (prepend) {
  21362. str = SLASH + str;
  21363. }
  21364. return str;
  21365. };
  21366. // Our version of upath.normalize
  21367. // TODO: this is not equal to path-normalize module - investigate why
  21368. const normalizePathToUnix = (path) => toUnix(sysPath.normalize(toUnix(path)));
  21369. const normalizeIgnored = (cwd = EMPTY_STR) => (path) => {
  21370. if (typeof path !== STRING_TYPE) return path;
  21371. return normalizePathToUnix(sysPath.isAbsolute(path) ? path : sysPath.join(cwd, path));
  21372. };
  21373. const getAbsolutePath = (path, cwd) => {
  21374. if (sysPath.isAbsolute(path)) {
  21375. return path;
  21376. }
  21377. if (path.startsWith(BANG)) {
  21378. return BANG + sysPath.join(cwd, path.slice(1));
  21379. }
  21380. return sysPath.join(cwd, path);
  21381. };
  21382. const undef = (opts, key) => opts[key] === undefined;
  21383. /**
  21384. * Directory entry.
  21385. * @property {Path} path
  21386. * @property {Set<Path>} items
  21387. */
  21388. class DirEntry {
  21389. /**
  21390. * @param {Path} dir
  21391. * @param {Function} removeWatcher
  21392. */
  21393. constructor(dir, removeWatcher) {
  21394. this.path = dir;
  21395. this._removeWatcher = removeWatcher;
  21396. /** @type {Set<Path>} */
  21397. this.items = new Set();
  21398. }
  21399. add(item) {
  21400. const {items} = this;
  21401. if (!items) return;
  21402. if (item !== ONE_DOT && item !== TWO_DOTS) items.add(item);
  21403. }
  21404. async remove(item) {
  21405. const {items} = this;
  21406. if (!items) return;
  21407. items.delete(item);
  21408. if (items.size > 0) return;
  21409. const dir = this.path;
  21410. try {
  21411. await readdir(dir);
  21412. } catch (err) {
  21413. if (this._removeWatcher) {
  21414. this._removeWatcher(sysPath.dirname(dir), sysPath.basename(dir));
  21415. }
  21416. }
  21417. }
  21418. has(item) {
  21419. const {items} = this;
  21420. if (!items) return;
  21421. return items.has(item);
  21422. }
  21423. /**
  21424. * @returns {Array<String>}
  21425. */
  21426. getChildren() {
  21427. const {items} = this;
  21428. if (!items) return;
  21429. return [...items.values()];
  21430. }
  21431. dispose() {
  21432. this.items.clear();
  21433. delete this.path;
  21434. delete this._removeWatcher;
  21435. delete this.items;
  21436. Object.freeze(this);
  21437. }
  21438. }
  21439. const STAT_METHOD_F = 'stat';
  21440. const STAT_METHOD_L = 'lstat';
  21441. class WatchHelper {
  21442. constructor(path, watchPath, follow, fsw) {
  21443. this.fsw = fsw;
  21444. this.path = path = path.replace(REPLACER_RE, EMPTY_STR);
  21445. this.watchPath = watchPath;
  21446. this.fullWatchPath = sysPath.resolve(watchPath);
  21447. this.hasGlob = watchPath !== path;
  21448. /** @type {object|boolean} */
  21449. if (path === EMPTY_STR) this.hasGlob = false;
  21450. this.globSymlink = this.hasGlob && follow ? undefined : false;
  21451. this.globFilter = this.hasGlob ? anymatch(path, undefined, ANYMATCH_OPTS) : false;
  21452. this.dirParts = this.getDirParts(path);
  21453. this.dirParts.forEach((parts) => {
  21454. if (parts.length > 1) parts.pop();
  21455. });
  21456. this.followSymlinks = follow;
  21457. this.statMethod = follow ? STAT_METHOD_F : STAT_METHOD_L;
  21458. }
  21459. checkGlobSymlink(entry) {
  21460. // only need to resolve once
  21461. // first entry should always have entry.parentDir === EMPTY_STR
  21462. if (this.globSymlink === undefined) {
  21463. this.globSymlink = entry.fullParentDir === this.fullWatchPath ?
  21464. false : {realPath: entry.fullParentDir, linkPath: this.fullWatchPath};
  21465. }
  21466. if (this.globSymlink) {
  21467. return entry.fullPath.replace(this.globSymlink.realPath, this.globSymlink.linkPath);
  21468. }
  21469. return entry.fullPath;
  21470. }
  21471. entryPath(entry) {
  21472. return sysPath.join(this.watchPath,
  21473. sysPath.relative(this.watchPath, this.checkGlobSymlink(entry))
  21474. );
  21475. }
  21476. filterPath(entry) {
  21477. const {stats} = entry;
  21478. if (stats && stats.isSymbolicLink()) return this.filterDir(entry);
  21479. const resolvedPath = this.entryPath(entry);
  21480. const matchesGlob = this.hasGlob && typeof this.globFilter === FUNCTION_TYPE ?
  21481. this.globFilter(resolvedPath) : true;
  21482. return matchesGlob &&
  21483. this.fsw._isntIgnored(resolvedPath, stats) &&
  21484. this.fsw._hasReadPermissions(stats);
  21485. }
  21486. getDirParts(path) {
  21487. if (!this.hasGlob) return [];
  21488. const parts = [];
  21489. const expandedPath = path.includes(BRACE_START) ? braces.expand(path) : [path];
  21490. expandedPath.forEach((path) => {
  21491. parts.push(sysPath.relative(this.watchPath, path).split(SLASH_OR_BACK_SLASH_RE));
  21492. });
  21493. return parts;
  21494. }
  21495. filterDir(entry) {
  21496. if (this.hasGlob) {
  21497. const entryParts = this.getDirParts(this.checkGlobSymlink(entry));
  21498. let globstar = false;
  21499. this.unmatchedGlob = !this.dirParts.some((parts) => {
  21500. return parts.every((part, i) => {
  21501. if (part === GLOBSTAR) globstar = true;
  21502. return globstar || !entryParts[0][i] || anymatch(part, entryParts[0][i], ANYMATCH_OPTS);
  21503. });
  21504. });
  21505. }
  21506. return !this.unmatchedGlob && this.fsw._isntIgnored(this.entryPath(entry), entry.stats);
  21507. }
  21508. }
  21509. /**
  21510. * Watches files & directories for changes. Emitted events:
  21511. * `add`, `addDir`, `change`, `unlink`, `unlinkDir`, `all`, `error`
  21512. *
  21513. * new FSWatcher()
  21514. * .add(directories)
  21515. * .on('add', path => log('File', path, 'was added'))
  21516. */
  21517. class FSWatcher extends EventEmitter$2 {
  21518. // Not indenting methods for history sake; for now.
  21519. constructor(_opts) {
  21520. super();
  21521. const opts = {};
  21522. if (_opts) Object.assign(opts, _opts); // for frozen objects
  21523. /** @type {Map<String, DirEntry>} */
  21524. this._watched = new Map();
  21525. /** @type {Map<String, Array>} */
  21526. this._closers = new Map();
  21527. /** @type {Set<String>} */
  21528. this._ignoredPaths = new Set();
  21529. /** @type {Map<ThrottleType, Map>} */
  21530. this._throttled = new Map();
  21531. /** @type {Map<Path, String|Boolean>} */
  21532. this._symlinkPaths = new Map();
  21533. this._streams = new Set();
  21534. this.closed = false;
  21535. // Set up default options.
  21536. if (undef(opts, 'persistent')) opts.persistent = true;
  21537. if (undef(opts, 'ignoreInitial')) opts.ignoreInitial = false;
  21538. if (undef(opts, 'ignorePermissionErrors')) opts.ignorePermissionErrors = false;
  21539. if (undef(opts, 'interval')) opts.interval = 100;
  21540. if (undef(opts, 'binaryInterval')) opts.binaryInterval = 300;
  21541. if (undef(opts, 'disableGlobbing')) opts.disableGlobbing = false;
  21542. opts.enableBinaryInterval = opts.binaryInterval !== opts.interval;
  21543. // Enable fsevents on OS X when polling isn't explicitly enabled.
  21544. if (undef(opts, 'useFsEvents')) opts.useFsEvents = !opts.usePolling;
  21545. // If we can't use fsevents, ensure the options reflect it's disabled.
  21546. const canUseFsEvents = FsEventsHandler.canUse();
  21547. if (!canUseFsEvents) opts.useFsEvents = false;
  21548. // Use polling on Mac if not using fsevents.
  21549. // Other platforms use non-polling fs_watch.
  21550. if (undef(opts, 'usePolling') && !opts.useFsEvents) {
  21551. opts.usePolling = isMacos;
  21552. }
  21553. // Always default to polling on IBM i because fs.watch() is not available on IBM i.
  21554. if(isIBMi) {
  21555. opts.usePolling = true;
  21556. }
  21557. // Global override (useful for end-developers that need to force polling for all
  21558. // instances of chokidar, regardless of usage/dependency depth)
  21559. const envPoll = process.env.CHOKIDAR_USEPOLLING;
  21560. if (envPoll !== undefined) {
  21561. const envLower = envPoll.toLowerCase();
  21562. if (envLower === 'false' || envLower === '0') {
  21563. opts.usePolling = false;
  21564. } else if (envLower === 'true' || envLower === '1') {
  21565. opts.usePolling = true;
  21566. } else {
  21567. opts.usePolling = !!envLower;
  21568. }
  21569. }
  21570. const envInterval = process.env.CHOKIDAR_INTERVAL;
  21571. if (envInterval) {
  21572. opts.interval = Number.parseInt(envInterval, 10);
  21573. }
  21574. // Editor atomic write normalization enabled by default with fs.watch
  21575. if (undef(opts, 'atomic')) opts.atomic = !opts.usePolling && !opts.useFsEvents;
  21576. if (opts.atomic) this._pendingUnlinks = new Map();
  21577. if (undef(opts, 'followSymlinks')) opts.followSymlinks = true;
  21578. if (undef(opts, 'awaitWriteFinish')) opts.awaitWriteFinish = false;
  21579. if (opts.awaitWriteFinish === true) opts.awaitWriteFinish = {};
  21580. const awf = opts.awaitWriteFinish;
  21581. if (awf) {
  21582. if (!awf.stabilityThreshold) awf.stabilityThreshold = 2000;
  21583. if (!awf.pollInterval) awf.pollInterval = 100;
  21584. this._pendingWrites = new Map();
  21585. }
  21586. if (opts.ignored) opts.ignored = arrify(opts.ignored);
  21587. let readyCalls = 0;
  21588. this._emitReady = () => {
  21589. readyCalls++;
  21590. if (readyCalls >= this._readyCount) {
  21591. this._emitReady = EMPTY_FN;
  21592. this._readyEmitted = true;
  21593. // use process.nextTick to allow time for listener to be bound
  21594. process.nextTick(() => this.emit(EV_READY));
  21595. }
  21596. };
  21597. this._emitRaw = (...args) => this.emit(EV_RAW, ...args);
  21598. this._readyEmitted = false;
  21599. this.options = opts;
  21600. // Initialize with proper watcher.
  21601. if (opts.useFsEvents) {
  21602. this._fsEventsHandler = new FsEventsHandler(this);
  21603. } else {
  21604. this._nodeFsHandler = new NodeFsHandler(this);
  21605. }
  21606. // You’re frozen when your heart’s not open.
  21607. Object.freeze(opts);
  21608. }
  21609. // Public methods
  21610. /**
  21611. * Adds paths to be watched on an existing FSWatcher instance
  21612. * @param {Path|Array<Path>} paths_
  21613. * @param {String=} _origAdd private; for handling non-existent paths to be watched
  21614. * @param {Boolean=} _internal private; indicates a non-user add
  21615. * @returns {FSWatcher} for chaining
  21616. */
  21617. add(paths_, _origAdd, _internal) {
  21618. const {cwd, disableGlobbing} = this.options;
  21619. this.closed = false;
  21620. let paths = unifyPaths(paths_);
  21621. if (cwd) {
  21622. paths = paths.map((path) => {
  21623. const absPath = getAbsolutePath(path, cwd);
  21624. // Check `path` instead of `absPath` because the cwd portion can't be a glob
  21625. if (disableGlobbing || !isGlob(path)) {
  21626. return absPath;
  21627. }
  21628. return normalizePath(absPath);
  21629. });
  21630. }
  21631. // set aside negated glob strings
  21632. paths = paths.filter((path) => {
  21633. if (path.startsWith(BANG)) {
  21634. this._ignoredPaths.add(path.slice(1));
  21635. return false;
  21636. }
  21637. // if a path is being added that was previously ignored, stop ignoring it
  21638. this._ignoredPaths.delete(path);
  21639. this._ignoredPaths.delete(path + SLASH_GLOBSTAR);
  21640. // reset the cached userIgnored anymatch fn
  21641. // to make ignoredPaths changes effective
  21642. this._userIgnored = undefined;
  21643. return true;
  21644. });
  21645. if (this.options.useFsEvents && this._fsEventsHandler) {
  21646. if (!this._readyCount) this._readyCount = paths.length;
  21647. if (this.options.persistent) this._readyCount += paths.length;
  21648. paths.forEach((path) => this._fsEventsHandler._addToFsEvents(path));
  21649. } else {
  21650. if (!this._readyCount) this._readyCount = 0;
  21651. this._readyCount += paths.length;
  21652. Promise.all(
  21653. paths.map(async path => {
  21654. const res = await this._nodeFsHandler._addToNodeFs(path, !_internal, 0, 0, _origAdd);
  21655. if (res) this._emitReady();
  21656. return res;
  21657. })
  21658. ).then(results => {
  21659. if (this.closed) return;
  21660. results.filter(item => item).forEach(item => {
  21661. this.add(sysPath.dirname(item), sysPath.basename(_origAdd || item));
  21662. });
  21663. });
  21664. }
  21665. return this;
  21666. }
  21667. /**
  21668. * Close watchers or start ignoring events from specified paths.
  21669. * @param {Path|Array<Path>} paths_ - string or array of strings, file/directory paths and/or globs
  21670. * @returns {FSWatcher} for chaining
  21671. */
  21672. unwatch(paths_) {
  21673. if (this.closed) return this;
  21674. const paths = unifyPaths(paths_);
  21675. const {cwd} = this.options;
  21676. paths.forEach((path) => {
  21677. // convert to absolute path unless relative path already matches
  21678. if (!sysPath.isAbsolute(path) && !this._closers.has(path)) {
  21679. if (cwd) path = sysPath.join(cwd, path);
  21680. path = sysPath.resolve(path);
  21681. }
  21682. this._closePath(path);
  21683. this._ignoredPaths.add(path);
  21684. if (this._watched.has(path)) {
  21685. this._ignoredPaths.add(path + SLASH_GLOBSTAR);
  21686. }
  21687. // reset the cached userIgnored anymatch fn
  21688. // to make ignoredPaths changes effective
  21689. this._userIgnored = undefined;
  21690. });
  21691. return this;
  21692. }
  21693. /**
  21694. * Close watchers and remove all listeners from watched paths.
  21695. * @returns {Promise<void>}.
  21696. */
  21697. close() {
  21698. if (this.closed) return this._closePromise;
  21699. this.closed = true;
  21700. // Memory management.
  21701. this.removeAllListeners();
  21702. const closers = [];
  21703. this._closers.forEach(closerList => closerList.forEach(closer => {
  21704. const promise = closer();
  21705. if (promise instanceof Promise) closers.push(promise);
  21706. }));
  21707. this._streams.forEach(stream => stream.destroy());
  21708. this._userIgnored = undefined;
  21709. this._readyCount = 0;
  21710. this._readyEmitted = false;
  21711. this._watched.forEach(dirent => dirent.dispose());
  21712. ['closers', 'watched', 'streams', 'symlinkPaths', 'throttled'].forEach(key => {
  21713. this[`_${key}`].clear();
  21714. });
  21715. this._closePromise = closers.length ? Promise.all(closers).then(() => undefined) : Promise.resolve();
  21716. return this._closePromise;
  21717. }
  21718. /**
  21719. * Expose list of watched paths
  21720. * @returns {Object} for chaining
  21721. */
  21722. getWatched() {
  21723. const watchList = {};
  21724. this._watched.forEach((entry, dir) => {
  21725. const key = this.options.cwd ? sysPath.relative(this.options.cwd, dir) : dir;
  21726. watchList[key || ONE_DOT] = entry.getChildren().sort();
  21727. });
  21728. return watchList;
  21729. }
  21730. emitWithAll(event, args) {
  21731. this.emit(...args);
  21732. if (event !== EV_ERROR) this.emit(EV_ALL, ...args);
  21733. }
  21734. // Common helpers
  21735. // --------------
  21736. /**
  21737. * Normalize and emit events.
  21738. * Calling _emit DOES NOT MEAN emit() would be called!
  21739. * @param {EventName} event Type of event
  21740. * @param {Path} path File or directory path
  21741. * @param {*=} val1 arguments to be passed with event
  21742. * @param {*=} val2
  21743. * @param {*=} val3
  21744. * @returns the error if defined, otherwise the value of the FSWatcher instance's `closed` flag
  21745. */
  21746. async _emit(event, path, val1, val2, val3) {
  21747. if (this.closed) return;
  21748. const opts = this.options;
  21749. if (isWindows$1) path = sysPath.normalize(path);
  21750. if (opts.cwd) path = sysPath.relative(opts.cwd, path);
  21751. /** @type Array<any> */
  21752. const args = [event, path];
  21753. if (val3 !== undefined) args.push(val1, val2, val3);
  21754. else if (val2 !== undefined) args.push(val1, val2);
  21755. else if (val1 !== undefined) args.push(val1);
  21756. const awf = opts.awaitWriteFinish;
  21757. let pw;
  21758. if (awf && (pw = this._pendingWrites.get(path))) {
  21759. pw.lastChange = new Date();
  21760. return this;
  21761. }
  21762. if (opts.atomic) {
  21763. if (event === EV_UNLINK) {
  21764. this._pendingUnlinks.set(path, args);
  21765. setTimeout(() => {
  21766. this._pendingUnlinks.forEach((entry, path) => {
  21767. this.emit(...entry);
  21768. this.emit(EV_ALL, ...entry);
  21769. this._pendingUnlinks.delete(path);
  21770. });
  21771. }, typeof opts.atomic === 'number' ? opts.atomic : 100);
  21772. return this;
  21773. }
  21774. if (event === EV_ADD && this._pendingUnlinks.has(path)) {
  21775. event = args[0] = EV_CHANGE;
  21776. this._pendingUnlinks.delete(path);
  21777. }
  21778. }
  21779. if (awf && (event === EV_ADD || event === EV_CHANGE) && this._readyEmitted) {
  21780. const awfEmit = (err, stats) => {
  21781. if (err) {
  21782. event = args[0] = EV_ERROR;
  21783. args[1] = err;
  21784. this.emitWithAll(event, args);
  21785. } else if (stats) {
  21786. // if stats doesn't exist the file must have been deleted
  21787. if (args.length > 2) {
  21788. args[2] = stats;
  21789. } else {
  21790. args.push(stats);
  21791. }
  21792. this.emitWithAll(event, args);
  21793. }
  21794. };
  21795. this._awaitWriteFinish(path, awf.stabilityThreshold, event, awfEmit);
  21796. return this;
  21797. }
  21798. if (event === EV_CHANGE) {
  21799. const isThrottled = !this._throttle(EV_CHANGE, path, 50);
  21800. if (isThrottled) return this;
  21801. }
  21802. if (opts.alwaysStat && val1 === undefined &&
  21803. (event === EV_ADD || event === EV_ADD_DIR || event === EV_CHANGE)
  21804. ) {
  21805. const fullPath = opts.cwd ? sysPath.join(opts.cwd, path) : path;
  21806. let stats;
  21807. try {
  21808. stats = await stat(fullPath);
  21809. } catch (err) {}
  21810. // Suppress event when fs_stat fails, to avoid sending undefined 'stat'
  21811. if (!stats || this.closed) return;
  21812. args.push(stats);
  21813. }
  21814. this.emitWithAll(event, args);
  21815. return this;
  21816. }
  21817. /**
  21818. * Common handler for errors
  21819. * @param {Error} error
  21820. * @returns {Error|Boolean} The error if defined, otherwise the value of the FSWatcher instance's `closed` flag
  21821. */
  21822. _handleError(error) {
  21823. const code = error && error.code;
  21824. if (error && code !== 'ENOENT' && code !== 'ENOTDIR' &&
  21825. (!this.options.ignorePermissionErrors || (code !== 'EPERM' && code !== 'EACCES'))
  21826. ) {
  21827. this.emit(EV_ERROR, error);
  21828. }
  21829. return error || this.closed;
  21830. }
  21831. /**
  21832. * Helper utility for throttling
  21833. * @param {ThrottleType} actionType type being throttled
  21834. * @param {Path} path being acted upon
  21835. * @param {Number} timeout duration of time to suppress duplicate actions
  21836. * @returns {Object|false} tracking object or false if action should be suppressed
  21837. */
  21838. _throttle(actionType, path, timeout) {
  21839. if (!this._throttled.has(actionType)) {
  21840. this._throttled.set(actionType, new Map());
  21841. }
  21842. /** @type {Map<Path, Object>} */
  21843. const action = this._throttled.get(actionType);
  21844. /** @type {Object} */
  21845. const actionPath = action.get(path);
  21846. if (actionPath) {
  21847. actionPath.count++;
  21848. return false;
  21849. }
  21850. let timeoutObject;
  21851. const clear = () => {
  21852. const item = action.get(path);
  21853. const count = item ? item.count : 0;
  21854. action.delete(path);
  21855. clearTimeout(timeoutObject);
  21856. if (item) clearTimeout(item.timeoutObject);
  21857. return count;
  21858. };
  21859. timeoutObject = setTimeout(clear, timeout);
  21860. const thr = {timeoutObject, clear, count: 0};
  21861. action.set(path, thr);
  21862. return thr;
  21863. }
  21864. _incrReadyCount() {
  21865. return this._readyCount++;
  21866. }
  21867. /**
  21868. * Awaits write operation to finish.
  21869. * Polls a newly created file for size variations. When files size does not change for 'threshold' milliseconds calls callback.
  21870. * @param {Path} path being acted upon
  21871. * @param {Number} threshold Time in milliseconds a file size must be fixed before acknowledging write OP is finished
  21872. * @param {EventName} event
  21873. * @param {Function} awfEmit Callback to be called when ready for event to be emitted.
  21874. */
  21875. _awaitWriteFinish(path, threshold, event, awfEmit) {
  21876. let timeoutHandler;
  21877. let fullPath = path;
  21878. if (this.options.cwd && !sysPath.isAbsolute(path)) {
  21879. fullPath = sysPath.join(this.options.cwd, path);
  21880. }
  21881. const now = new Date();
  21882. const awaitWriteFinish = (prevStat) => {
  21883. fs$2.stat(fullPath, (err, curStat) => {
  21884. if (err || !this._pendingWrites.has(path)) {
  21885. if (err && err.code !== 'ENOENT') awfEmit(err);
  21886. return;
  21887. }
  21888. const now = Number(new Date());
  21889. if (prevStat && curStat.size !== prevStat.size) {
  21890. this._pendingWrites.get(path).lastChange = now;
  21891. }
  21892. const pw = this._pendingWrites.get(path);
  21893. const df = now - pw.lastChange;
  21894. if (df >= threshold) {
  21895. this._pendingWrites.delete(path);
  21896. awfEmit(undefined, curStat);
  21897. } else {
  21898. timeoutHandler = setTimeout(
  21899. awaitWriteFinish,
  21900. this.options.awaitWriteFinish.pollInterval,
  21901. curStat
  21902. );
  21903. }
  21904. });
  21905. };
  21906. if (!this._pendingWrites.has(path)) {
  21907. this._pendingWrites.set(path, {
  21908. lastChange: now,
  21909. cancelWait: () => {
  21910. this._pendingWrites.delete(path);
  21911. clearTimeout(timeoutHandler);
  21912. return event;
  21913. }
  21914. });
  21915. timeoutHandler = setTimeout(
  21916. awaitWriteFinish,
  21917. this.options.awaitWriteFinish.pollInterval
  21918. );
  21919. }
  21920. }
  21921. _getGlobIgnored() {
  21922. return [...this._ignoredPaths.values()];
  21923. }
  21924. /**
  21925. * Determines whether user has asked to ignore this path.
  21926. * @param {Path} path filepath or dir
  21927. * @param {fs.Stats=} stats result of fs.stat
  21928. * @returns {Boolean}
  21929. */
  21930. _isIgnored(path, stats) {
  21931. if (this.options.atomic && DOT_RE.test(path)) return true;
  21932. if (!this._userIgnored) {
  21933. const {cwd} = this.options;
  21934. const ign = this.options.ignored;
  21935. const ignored = ign && ign.map(normalizeIgnored(cwd));
  21936. const paths = arrify(ignored)
  21937. .filter((path) => typeof path === STRING_TYPE && !isGlob(path))
  21938. .map((path) => path + SLASH_GLOBSTAR);
  21939. const list = this._getGlobIgnored().map(normalizeIgnored(cwd)).concat(ignored, paths);
  21940. this._userIgnored = anymatch(list, undefined, ANYMATCH_OPTS);
  21941. }
  21942. return this._userIgnored([path, stats]);
  21943. }
  21944. _isntIgnored(path, stat) {
  21945. return !this._isIgnored(path, stat);
  21946. }
  21947. /**
  21948. * Provides a set of common helpers and properties relating to symlink and glob handling.
  21949. * @param {Path} path file, directory, or glob pattern being watched
  21950. * @param {Number=} depth at any depth > 0, this isn't a glob
  21951. * @returns {WatchHelper} object containing helpers for this path
  21952. */
  21953. _getWatchHelpers(path, depth) {
  21954. const watchPath = depth || this.options.disableGlobbing || !isGlob(path) ? path : globParent(path);
  21955. const follow = this.options.followSymlinks;
  21956. return new WatchHelper(path, watchPath, follow, this);
  21957. }
  21958. // Directory helpers
  21959. // -----------------
  21960. /**
  21961. * Provides directory tracking objects
  21962. * @param {String} directory path of the directory
  21963. * @returns {DirEntry} the directory's tracking object
  21964. */
  21965. _getWatchedDir(directory) {
  21966. if (!this._boundRemove) this._boundRemove = this._remove.bind(this);
  21967. const dir = sysPath.resolve(directory);
  21968. if (!this._watched.has(dir)) this._watched.set(dir, new DirEntry(dir, this._boundRemove));
  21969. return this._watched.get(dir);
  21970. }
  21971. // File helpers
  21972. // ------------
  21973. /**
  21974. * Check for read permissions.
  21975. * Based on this answer on SO: https://stackoverflow.com/a/11781404/1358405
  21976. * @param {fs.Stats} stats - object, result of fs_stat
  21977. * @returns {Boolean} indicates whether the file can be read
  21978. */
  21979. _hasReadPermissions(stats) {
  21980. if (this.options.ignorePermissionErrors) return true;
  21981. // stats.mode may be bigint
  21982. const md = stats && Number.parseInt(stats.mode, 10);
  21983. const st = md & 0o777;
  21984. const it = Number.parseInt(st.toString(8)[0], 10);
  21985. return Boolean(4 & it);
  21986. }
  21987. /**
  21988. * Handles emitting unlink events for
  21989. * files and directories, and via recursion, for
  21990. * files and directories within directories that are unlinked
  21991. * @param {String} directory within which the following item is located
  21992. * @param {String} item base path of item/directory
  21993. * @returns {void}
  21994. */
  21995. _remove(directory, item, isDirectory) {
  21996. // if what is being deleted is a directory, get that directory's paths
  21997. // for recursive deleting and cleaning of watched object
  21998. // if it is not a directory, nestedDirectoryChildren will be empty array
  21999. const path = sysPath.join(directory, item);
  22000. const fullPath = sysPath.resolve(path);
  22001. isDirectory = isDirectory != null
  22002. ? isDirectory
  22003. : this._watched.has(path) || this._watched.has(fullPath);
  22004. // prevent duplicate handling in case of arriving here nearly simultaneously
  22005. // via multiple paths (such as _handleFile and _handleDir)
  22006. if (!this._throttle('remove', path, 100)) return;
  22007. // if the only watched file is removed, watch for its return
  22008. if (!isDirectory && !this.options.useFsEvents && this._watched.size === 1) {
  22009. this.add(directory, item, true);
  22010. }
  22011. // This will create a new entry in the watched object in either case
  22012. // so we got to do the directory check beforehand
  22013. const wp = this._getWatchedDir(path);
  22014. const nestedDirectoryChildren = wp.getChildren();
  22015. // Recursively remove children directories / files.
  22016. nestedDirectoryChildren.forEach(nested => this._remove(path, nested));
  22017. // Check if item was on the watched list and remove it
  22018. const parent = this._getWatchedDir(directory);
  22019. const wasTracked = parent.has(item);
  22020. parent.remove(item);
  22021. // Fixes issue #1042 -> Relative paths were detected and added as symlinks
  22022. // (https://github.com/paulmillr/chokidar/blob/e1753ddbc9571bdc33b4a4af172d52cb6e611c10/lib/nodefs-handler.js#L612),
  22023. // but never removed from the map in case the path was deleted.
  22024. // This leads to an incorrect state if the path was recreated:
  22025. // https://github.com/paulmillr/chokidar/blob/e1753ddbc9571bdc33b4a4af172d52cb6e611c10/lib/nodefs-handler.js#L553
  22026. if (this._symlinkPaths.has(fullPath)) {
  22027. this._symlinkPaths.delete(fullPath);
  22028. }
  22029. // If we wait for this file to be fully written, cancel the wait.
  22030. let relPath = path;
  22031. if (this.options.cwd) relPath = sysPath.relative(this.options.cwd, path);
  22032. if (this.options.awaitWriteFinish && this._pendingWrites.has(relPath)) {
  22033. const event = this._pendingWrites.get(relPath).cancelWait();
  22034. if (event === EV_ADD) return;
  22035. }
  22036. // The Entry will either be a directory that just got removed
  22037. // or a bogus entry to a file, in either case we have to remove it
  22038. this._watched.delete(path);
  22039. this._watched.delete(fullPath);
  22040. const eventName = isDirectory ? EV_UNLINK_DIR : EV_UNLINK;
  22041. if (wasTracked && !this._isIgnored(path)) this._emit(eventName, path);
  22042. // Avoid conflicts if we later create another file with the same name
  22043. if (!this.options.useFsEvents) {
  22044. this._closePath(path);
  22045. }
  22046. }
  22047. /**
  22048. * Closes all watchers for a path
  22049. * @param {Path} path
  22050. */
  22051. _closePath(path) {
  22052. this._closeFile(path);
  22053. const dir = sysPath.dirname(path);
  22054. this._getWatchedDir(dir).remove(sysPath.basename(path));
  22055. }
  22056. /**
  22057. * Closes only file-specific watchers
  22058. * @param {Path} path
  22059. */
  22060. _closeFile(path) {
  22061. const closers = this._closers.get(path);
  22062. if (!closers) return;
  22063. closers.forEach(closer => closer());
  22064. this._closers.delete(path);
  22065. }
  22066. /**
  22067. *
  22068. * @param {Path} path
  22069. * @param {Function} closer
  22070. */
  22071. _addPathCloser(path, closer) {
  22072. if (!closer) return;
  22073. let list = this._closers.get(path);
  22074. if (!list) {
  22075. list = [];
  22076. this._closers.set(path, list);
  22077. }
  22078. list.push(closer);
  22079. }
  22080. _readdirp(root, opts) {
  22081. if (this.closed) return;
  22082. const options = {type: EV_ALL, alwaysStat: true, lstat: true, ...opts};
  22083. let stream = readdirp(root, options);
  22084. this._streams.add(stream);
  22085. stream.once(STR_CLOSE, () => {
  22086. stream = undefined;
  22087. });
  22088. stream.once(STR_END, () => {
  22089. if (stream) {
  22090. this._streams.delete(stream);
  22091. stream = undefined;
  22092. }
  22093. });
  22094. return stream;
  22095. }
  22096. }
  22097. // Export FSWatcher class
  22098. chokidar.FSWatcher = FSWatcher;
  22099. /**
  22100. * Instantiates watcher with paths to be tracked.
  22101. * @param {String|Array<String>} paths file/directory paths and/or globs
  22102. * @param {Object=} options chokidar opts
  22103. * @returns an instance of FSWatcher for chaining.
  22104. */
  22105. const watch = (paths, options) => {
  22106. const watcher = new FSWatcher(options);
  22107. watcher.add(paths);
  22108. return watcher;
  22109. };
  22110. chokidar.watch = watch;
  22111. var shellQuote$1 = {};
  22112. var quote = function quote(xs) {
  22113. return xs.map(function (s) {
  22114. if (s === '') {
  22115. return '\'\'';
  22116. }
  22117. if (s && typeof s === 'object') {
  22118. return s.op.replace(/(.)/g, '\\$1');
  22119. }
  22120. if ((/["\s]/).test(s) && !(/'/).test(s)) {
  22121. return "'" + s.replace(/(['\\])/g, '\\$1') + "'";
  22122. }
  22123. if ((/["'\s]/).test(s)) {
  22124. return '"' + s.replace(/(["\\$`!])/g, '\\$1') + '"';
  22125. }
  22126. return String(s).replace(/([A-Za-z]:)?([#!"$&'()*,:;<=>?@[\\\]^`{|}])/g, '$1\\$2');
  22127. }).join(' ');
  22128. };
  22129. // '<(' is process substitution operator and
  22130. // can be parsed the same as control operator
  22131. var CONTROL = '(?:' + [
  22132. '\\|\\|',
  22133. '\\&\\&',
  22134. ';;',
  22135. '\\|\\&',
  22136. '\\<\\(',
  22137. '\\<\\<\\<',
  22138. '>>',
  22139. '>\\&',
  22140. '<\\&',
  22141. '[&;()|<>]'
  22142. ].join('|') + ')';
  22143. var controlRE = new RegExp('^' + CONTROL + '$');
  22144. var META = '|&;()<> \\t';
  22145. var SINGLE_QUOTE = '"((\\\\"|[^"])*?)"';
  22146. var DOUBLE_QUOTE = '\'((\\\\\'|[^\'])*?)\'';
  22147. var hash = /^#$/;
  22148. var SQ = "'";
  22149. var DQ = '"';
  22150. var DS = '$';
  22151. var TOKEN = '';
  22152. var mult = 0x100000000; // Math.pow(16, 8);
  22153. for (var i = 0; i < 4; i++) {
  22154. TOKEN += (mult * Math.random()).toString(16);
  22155. }
  22156. var startsWithToken = new RegExp('^' + TOKEN);
  22157. function matchAll(s, r) {
  22158. var origIndex = r.lastIndex;
  22159. var matches = [];
  22160. var matchObj;
  22161. while ((matchObj = r.exec(s))) {
  22162. matches.push(matchObj);
  22163. if (r.lastIndex === matchObj.index) {
  22164. r.lastIndex += 1;
  22165. }
  22166. }
  22167. r.lastIndex = origIndex;
  22168. return matches;
  22169. }
  22170. function getVar(env, pre, key) {
  22171. var r = typeof env === 'function' ? env(key) : env[key];
  22172. if (typeof r === 'undefined' && key != '') {
  22173. r = '';
  22174. } else if (typeof r === 'undefined') {
  22175. r = '$';
  22176. }
  22177. if (typeof r === 'object') {
  22178. return pre + TOKEN + JSON.stringify(r) + TOKEN;
  22179. }
  22180. return pre + r;
  22181. }
  22182. function parseInternal(string, env, opts) {
  22183. if (!opts) {
  22184. opts = {};
  22185. }
  22186. var BS = opts.escape || '\\';
  22187. var BAREWORD = '(\\' + BS + '[\'"' + META + ']|[^\\s\'"' + META + '])+';
  22188. var chunker = new RegExp([
  22189. '(' + CONTROL + ')', // control chars
  22190. '(' + BAREWORD + '|' + SINGLE_QUOTE + '|' + DOUBLE_QUOTE + ')+'
  22191. ].join('|'), 'g');
  22192. var matches = matchAll(string, chunker);
  22193. if (matches.length === 0) {
  22194. return [];
  22195. }
  22196. if (!env) {
  22197. env = {};
  22198. }
  22199. var commented = false;
  22200. return matches.map(function (match) {
  22201. var s = match[0];
  22202. if (!s || commented) {
  22203. return void 0;
  22204. }
  22205. if (controlRE.test(s)) {
  22206. return { op: s };
  22207. }
  22208. // Hand-written scanner/parser for Bash quoting rules:
  22209. //
  22210. // 1. inside single quotes, all characters are printed literally.
  22211. // 2. inside double quotes, all characters are printed literally
  22212. // except variables prefixed by '$' and backslashes followed by
  22213. // either a double quote or another backslash.
  22214. // 3. outside of any quotes, backslashes are treated as escape
  22215. // characters and not printed (unless they are themselves escaped)
  22216. // 4. quote context can switch mid-token if there is no whitespace
  22217. // between the two quote contexts (e.g. all'one'"token" parses as
  22218. // "allonetoken")
  22219. var quote = false;
  22220. var esc = false;
  22221. var out = '';
  22222. var isGlob = false;
  22223. var i;
  22224. function parseEnvVar() {
  22225. i += 1;
  22226. var varend;
  22227. var varname;
  22228. var char = s.charAt(i);
  22229. if (char === '{') {
  22230. i += 1;
  22231. if (s.charAt(i) === '}') {
  22232. throw new Error('Bad substitution: ' + s.slice(i - 2, i + 1));
  22233. }
  22234. varend = s.indexOf('}', i);
  22235. if (varend < 0) {
  22236. throw new Error('Bad substitution: ' + s.slice(i));
  22237. }
  22238. varname = s.slice(i, varend);
  22239. i = varend;
  22240. } else if ((/[*@#?$!_-]/).test(char)) {
  22241. varname = char;
  22242. i += 1;
  22243. } else {
  22244. var slicedFromI = s.slice(i);
  22245. varend = slicedFromI.match(/[^\w\d_]/);
  22246. if (!varend) {
  22247. varname = slicedFromI;
  22248. i = s.length;
  22249. } else {
  22250. varname = slicedFromI.slice(0, varend.index);
  22251. i += varend.index - 1;
  22252. }
  22253. }
  22254. return getVar(env, '', varname);
  22255. }
  22256. for (i = 0; i < s.length; i++) {
  22257. var c = s.charAt(i);
  22258. isGlob = isGlob || (!quote && (c === '*' || c === '?'));
  22259. if (esc) {
  22260. out += c;
  22261. esc = false;
  22262. } else if (quote) {
  22263. if (c === quote) {
  22264. quote = false;
  22265. } else if (quote == SQ) {
  22266. out += c;
  22267. } else { // Double quote
  22268. if (c === BS) {
  22269. i += 1;
  22270. c = s.charAt(i);
  22271. if (c === DQ || c === BS || c === DS) {
  22272. out += c;
  22273. } else {
  22274. out += BS + c;
  22275. }
  22276. } else if (c === DS) {
  22277. out += parseEnvVar();
  22278. } else {
  22279. out += c;
  22280. }
  22281. }
  22282. } else if (c === DQ || c === SQ) {
  22283. quote = c;
  22284. } else if (controlRE.test(c)) {
  22285. return { op: s };
  22286. } else if (hash.test(c)) {
  22287. commented = true;
  22288. var commentObj = { comment: string.slice(match.index + i + 1) };
  22289. if (out.length) {
  22290. return [out, commentObj];
  22291. }
  22292. return [commentObj];
  22293. } else if (c === BS) {
  22294. esc = true;
  22295. } else if (c === DS) {
  22296. out += parseEnvVar();
  22297. } else {
  22298. out += c;
  22299. }
  22300. }
  22301. if (isGlob) {
  22302. return { op: 'glob', pattern: out };
  22303. }
  22304. return out;
  22305. }).reduce(function (prev, arg) { // finalize parsed arguments
  22306. // TODO: replace this whole reduce with a concat
  22307. return typeof arg === 'undefined' ? prev : prev.concat(arg);
  22308. }, []);
  22309. }
  22310. var parse$6 = function parse(s, env, opts) {
  22311. var mapped = parseInternal(s, env, opts);
  22312. if (typeof env !== 'function') {
  22313. return mapped;
  22314. }
  22315. return mapped.reduce(function (acc, s) {
  22316. if (typeof s === 'object') {
  22317. return acc.concat(s);
  22318. }
  22319. var xs = s.split(RegExp('(' + TOKEN + '.*?' + TOKEN + ')', 'g'));
  22320. if (xs.length === 1) {
  22321. return acc.concat(xs[0]);
  22322. }
  22323. return acc.concat(xs.filter(Boolean).map(function (x) {
  22324. if (startsWithToken.test(x)) {
  22325. return JSON.parse(x.split(TOKEN)[1]);
  22326. }
  22327. return x;
  22328. }));
  22329. }, []);
  22330. };
  22331. shellQuote$1.quote = quote;
  22332. shellQuote$1.parse = parse$6;
  22333. var macos = {
  22334. '/Applications/Atom.app/Contents/MacOS/Atom': 'atom',
  22335. '/Applications/Atom Beta.app/Contents/MacOS/Atom Beta':
  22336. '/Applications/Atom Beta.app/Contents/MacOS/Atom Beta',
  22337. '/Applications/Brackets.app/Contents/MacOS/Brackets': 'brackets',
  22338. '/Applications/Sublime Text.app/Contents/MacOS/Sublime Text':
  22339. '/Applications/Sublime Text.app/Contents/SharedSupport/bin/subl',
  22340. '/Applications/Sublime Text.app/Contents/MacOS/sublime_text':
  22341. '/Applications/Sublime Text.app/Contents/SharedSupport/bin/subl',
  22342. '/Applications/Sublime Text 2.app/Contents/MacOS/Sublime Text 2':
  22343. '/Applications/Sublime Text 2.app/Contents/SharedSupport/bin/subl',
  22344. '/Applications/Sublime Text Dev.app/Contents/MacOS/Sublime Text':
  22345. '/Applications/Sublime Text Dev.app/Contents/SharedSupport/bin/subl',
  22346. '/Applications/Visual Studio Code.app/Contents/MacOS/Electron': 'code',
  22347. '/Applications/Visual Studio Code - Insiders.app/Contents/MacOS/Electron':
  22348. 'code-insiders',
  22349. '/Applications/VSCodium.app/Contents/MacOS/Electron': 'codium',
  22350. '/Applications/Cursor.app/Contents/MacOS/Cursor': 'cursor',
  22351. '/Applications/AppCode.app/Contents/MacOS/appcode':
  22352. '/Applications/AppCode.app/Contents/MacOS/appcode',
  22353. '/Applications/CLion.app/Contents/MacOS/clion':
  22354. '/Applications/CLion.app/Contents/MacOS/clion',
  22355. '/Applications/IntelliJ IDEA.app/Contents/MacOS/idea':
  22356. '/Applications/IntelliJ IDEA.app/Contents/MacOS/idea',
  22357. '/Applications/IntelliJ IDEA Ultimate.app/Contents/MacOS/idea':
  22358. '/Applications/IntelliJ IDEA Ultimate.app/Contents/MacOS/idea',
  22359. '/Applications/IntelliJ IDEA Community Edition.app/Contents/MacOS/idea':
  22360. '/Applications/IntelliJ IDEA Community Edition.app/Contents/MacOS/idea',
  22361. '/Applications/PhpStorm.app/Contents/MacOS/phpstorm':
  22362. '/Applications/PhpStorm.app/Contents/MacOS/phpstorm',
  22363. '/Applications/PyCharm.app/Contents/MacOS/pycharm':
  22364. '/Applications/PyCharm.app/Contents/MacOS/pycharm',
  22365. '/Applications/PyCharm CE.app/Contents/MacOS/pycharm':
  22366. '/Applications/PyCharm CE.app/Contents/MacOS/pycharm',
  22367. '/Applications/RubyMine.app/Contents/MacOS/rubymine':
  22368. '/Applications/RubyMine.app/Contents/MacOS/rubymine',
  22369. '/Applications/WebStorm.app/Contents/MacOS/webstorm':
  22370. '/Applications/WebStorm.app/Contents/MacOS/webstorm',
  22371. '/Applications/MacVim.app/Contents/MacOS/MacVim': 'mvim',
  22372. '/Applications/GoLand.app/Contents/MacOS/goland':
  22373. '/Applications/GoLand.app/Contents/MacOS/goland',
  22374. '/Applications/Rider.app/Contents/MacOS/rider':
  22375. '/Applications/Rider.app/Contents/MacOS/rider',
  22376. '/Applications/Zed.app/Contents/MacOS/zed': 'zed'
  22377. };
  22378. var linux = {
  22379. atom: 'atom',
  22380. Brackets: 'brackets',
  22381. 'code-insiders': 'code-insiders',
  22382. code: 'code',
  22383. vscodium: 'vscodium',
  22384. codium: 'codium',
  22385. emacs: 'emacs',
  22386. gvim: 'gvim',
  22387. idea: 'idea',
  22388. 'idea.sh': 'idea',
  22389. phpstorm: 'phpstorm',
  22390. 'phpstorm.sh': 'phpstorm',
  22391. pycharm: 'pycharm',
  22392. 'pycharm.sh': 'pycharm',
  22393. rubymine: 'rubymine',
  22394. 'rubymine.sh': 'rubymine',
  22395. sublime_text: 'subl',
  22396. vim: 'vim',
  22397. webstorm: 'webstorm',
  22398. 'webstorm.sh': 'webstorm',
  22399. goland: 'goland',
  22400. 'goland.sh': 'goland',
  22401. rider: 'rider',
  22402. 'rider.sh': 'rider'
  22403. };
  22404. var windows$1 = [
  22405. 'Brackets.exe',
  22406. 'Code.exe',
  22407. 'Code - Insiders.exe',
  22408. 'VSCodium.exe',
  22409. 'Cursor.exe',
  22410. 'atom.exe',
  22411. 'sublime_text.exe',
  22412. 'notepad++.exe',
  22413. 'clion.exe',
  22414. 'clion64.exe',
  22415. 'idea.exe',
  22416. 'idea64.exe',
  22417. 'phpstorm.exe',
  22418. 'phpstorm64.exe',
  22419. 'pycharm.exe',
  22420. 'pycharm64.exe',
  22421. 'rubymine.exe',
  22422. 'rubymine64.exe',
  22423. 'webstorm.exe',
  22424. 'webstorm64.exe',
  22425. 'goland.exe',
  22426. 'goland64.exe',
  22427. 'rider.exe',
  22428. 'rider64.exe'
  22429. ];
  22430. const path$6 = require$$0$2;
  22431. const shellQuote = shellQuote$1;
  22432. const childProcess$1 = require$$2$1;
  22433. // Map from full process name to binary that starts the process
  22434. // We can't just re-use full process name, because it will spawn a new instance
  22435. // of the app every time
  22436. const COMMON_EDITORS_MACOS = macos;
  22437. const COMMON_EDITORS_LINUX = linux;
  22438. const COMMON_EDITORS_WIN = windows$1;
  22439. var guess = function guessEditor (specifiedEditor) {
  22440. if (specifiedEditor) {
  22441. return shellQuote.parse(specifiedEditor)
  22442. }
  22443. if (process.env.LAUNCH_EDITOR) {
  22444. return [process.env.LAUNCH_EDITOR]
  22445. }
  22446. if (process.versions.webcontainer) {
  22447. return [process.env.EDITOR || 'code']
  22448. }
  22449. // We can find out which editor is currently running by:
  22450. // `ps x` on macOS and Linux
  22451. // `Get-Process` on Windows
  22452. try {
  22453. if (process.platform === 'darwin') {
  22454. const output = childProcess$1
  22455. .execSync('ps x -o comm=', {
  22456. stdio: ['pipe', 'pipe', 'ignore']
  22457. })
  22458. .toString();
  22459. const processNames = Object.keys(COMMON_EDITORS_MACOS);
  22460. const processList = output.split('\n');
  22461. for (let i = 0; i < processNames.length; i++) {
  22462. const processName = processNames[i];
  22463. // Find editor by exact match.
  22464. if (processList.includes(processName)) {
  22465. return [COMMON_EDITORS_MACOS[processName]]
  22466. }
  22467. const processNameWithoutApplications = processName.replace('/Applications', '');
  22468. // Find editor installation not in /Applications.
  22469. if (output.indexOf(processNameWithoutApplications) !== -1) {
  22470. // Use the CLI command if one is specified
  22471. if (processName !== COMMON_EDITORS_MACOS[processName]) {
  22472. return [COMMON_EDITORS_MACOS[processName]]
  22473. }
  22474. // Use a partial match to find the running process path. If one is found, use the
  22475. // existing path since it can be running from anywhere.
  22476. const runningProcess = processList.find((procName) => procName.endsWith(processNameWithoutApplications));
  22477. if (runningProcess !== undefined) {
  22478. return [runningProcess]
  22479. }
  22480. }
  22481. }
  22482. } else if (process.platform === 'win32') {
  22483. const output = childProcess$1
  22484. .execSync(
  22485. 'powershell -NoProfile -Command "' +
  22486. '[Console]::OutputEncoding=[Text.Encoding]::UTF8;' +
  22487. 'Get-CimInstance -Query \\"select executablepath from win32_process where executablepath is not null\\" | % { $_.ExecutablePath }' +
  22488. '"',
  22489. {
  22490. stdio: ['pipe', 'pipe', 'ignore']
  22491. }
  22492. )
  22493. .toString();
  22494. const runningProcesses = output.split('\r\n');
  22495. for (let i = 0; i < runningProcesses.length; i++) {
  22496. const fullProcessPath = runningProcesses[i].trim();
  22497. const shortProcessName = path$6.basename(fullProcessPath);
  22498. if (COMMON_EDITORS_WIN.indexOf(shortProcessName) !== -1) {
  22499. return [fullProcessPath]
  22500. }
  22501. }
  22502. } else if (process.platform === 'linux') {
  22503. // --no-heading No header line
  22504. // x List all processes owned by you
  22505. // -o comm Need only names column
  22506. const output = childProcess$1
  22507. .execSync('ps x --no-heading -o comm --sort=comm', {
  22508. stdio: ['pipe', 'pipe', 'ignore']
  22509. })
  22510. .toString();
  22511. const processNames = Object.keys(COMMON_EDITORS_LINUX);
  22512. for (let i = 0; i < processNames.length; i++) {
  22513. const processName = processNames[i];
  22514. if (output.indexOf(processName) !== -1) {
  22515. return [COMMON_EDITORS_LINUX[processName]]
  22516. }
  22517. }
  22518. }
  22519. } catch (ignoreError) {
  22520. // Ignore...
  22521. }
  22522. // Last resort, use old skool env vars
  22523. if (process.env.VISUAL) {
  22524. return [process.env.VISUAL]
  22525. } else if (process.env.EDITOR) {
  22526. return [process.env.EDITOR]
  22527. }
  22528. return [null]
  22529. };
  22530. const path$5 = require$$0$2;
  22531. // normalize file/line numbers into command line args for specific editors
  22532. var getArgs = function getArgumentsForPosition (
  22533. editor,
  22534. fileName,
  22535. lineNumber,
  22536. columnNumber = 1
  22537. ) {
  22538. const editorBasename = path$5.basename(editor).replace(/\.(exe|cmd|bat)$/i, '');
  22539. switch (editorBasename) {
  22540. case 'atom':
  22541. case 'Atom':
  22542. case 'Atom Beta':
  22543. case 'subl':
  22544. case 'sublime':
  22545. case 'sublime_text':
  22546. case 'wstorm':
  22547. case 'charm':
  22548. case 'zed':
  22549. return [`${fileName}:${lineNumber}:${columnNumber}`]
  22550. case 'notepad++':
  22551. return ['-n' + lineNumber, '-c' + columnNumber, fileName]
  22552. case 'vim':
  22553. case 'mvim':
  22554. return [`+call cursor(${lineNumber}, ${columnNumber})`, fileName]
  22555. case 'joe':
  22556. case 'gvim':
  22557. return ['+' + `${lineNumber}`, fileName]
  22558. case 'emacs':
  22559. case 'emacsclient':
  22560. return [`+${lineNumber}:${columnNumber}`, fileName]
  22561. case 'rmate':
  22562. case 'mate':
  22563. case 'mine':
  22564. return ['--line', lineNumber, fileName]
  22565. case 'code':
  22566. case 'Code':
  22567. case 'code-insiders':
  22568. case 'Code - Insiders':
  22569. case 'codium':
  22570. case 'cursor':
  22571. case 'vscodium':
  22572. case 'VSCodium':
  22573. return ['-r', '-g', `${fileName}:${lineNumber}:${columnNumber}`]
  22574. case 'appcode':
  22575. case 'clion':
  22576. case 'clion64':
  22577. case 'idea':
  22578. case 'idea64':
  22579. case 'phpstorm':
  22580. case 'phpstorm64':
  22581. case 'pycharm':
  22582. case 'pycharm64':
  22583. case 'rubymine':
  22584. case 'rubymine64':
  22585. case 'webstorm':
  22586. case 'webstorm64':
  22587. case 'goland':
  22588. case 'goland64':
  22589. case 'rider':
  22590. case 'rider64':
  22591. return ['--line', lineNumber, '--column', columnNumber, fileName]
  22592. }
  22593. if (process.env.LAUNCH_EDITOR) {
  22594. return [fileName, lineNumber, columnNumber]
  22595. }
  22596. // For all others, drop the lineNumber until we have
  22597. // a mapping above, since providing the lineNumber incorrectly
  22598. // can result in errors or confusing behavior.
  22599. return [fileName]
  22600. };
  22601. /**
  22602. * Copyright (c) 2015-present, Facebook, Inc.
  22603. *
  22604. * This source code is licensed under the MIT license found in the
  22605. * LICENSE file at
  22606. * https://github.com/facebookincubator/create-react-app/blob/master/LICENSE
  22607. *
  22608. * Modified by Yuxi Evan You
  22609. */
  22610. const fs$1 = require$$0$4;
  22611. const os = require$$2;
  22612. const path$4 = require$$0$2;
  22613. const colors = picocolorsExports;
  22614. const childProcess = require$$2$1;
  22615. const guessEditor = guess;
  22616. const getArgumentsForPosition = getArgs;
  22617. function wrapErrorCallback (cb) {
  22618. return (fileName, errorMessage) => {
  22619. console.log();
  22620. console.log(
  22621. colors.red('Could not open ' + path$4.basename(fileName) + ' in the editor.')
  22622. );
  22623. if (errorMessage) {
  22624. if (errorMessage[errorMessage.length - 1] !== '.') {
  22625. errorMessage += '.';
  22626. }
  22627. console.log(
  22628. colors.red('The editor process exited with an error: ' + errorMessage)
  22629. );
  22630. }
  22631. console.log();
  22632. if (cb) cb(fileName, errorMessage);
  22633. }
  22634. }
  22635. function isTerminalEditor (editor) {
  22636. switch (editor) {
  22637. case 'vim':
  22638. case 'emacs':
  22639. case 'nano':
  22640. return true
  22641. }
  22642. return false
  22643. }
  22644. const positionRE = /:(\d+)(:(\d+))?$/;
  22645. function parseFile (file) {
  22646. // support `file://` protocol
  22647. if (file.startsWith('file://')) {
  22648. file = require$$0$5.fileURLToPath(file);
  22649. }
  22650. const fileName = file.replace(positionRE, '');
  22651. const match = file.match(positionRE);
  22652. const lineNumber = match && match[1];
  22653. const columnNumber = match && match[3];
  22654. return {
  22655. fileName,
  22656. lineNumber,
  22657. columnNumber
  22658. }
  22659. }
  22660. let _childProcess = null;
  22661. function launchEditor (file, specifiedEditor, onErrorCallback) {
  22662. const parsed = parseFile(file);
  22663. let { fileName } = parsed;
  22664. const { lineNumber, columnNumber } = parsed;
  22665. if (!fs$1.existsSync(fileName)) {
  22666. return
  22667. }
  22668. if (typeof specifiedEditor === 'function') {
  22669. onErrorCallback = specifiedEditor;
  22670. specifiedEditor = undefined;
  22671. }
  22672. onErrorCallback = wrapErrorCallback(onErrorCallback);
  22673. const [editor, ...args] = guessEditor(specifiedEditor);
  22674. if (!editor) {
  22675. onErrorCallback(fileName, null);
  22676. return
  22677. }
  22678. if (
  22679. process.platform === 'linux' &&
  22680. fileName.startsWith('/mnt/') &&
  22681. /Microsoft/i.test(os.release())
  22682. ) {
  22683. // Assume WSL / "Bash on Ubuntu on Windows" is being used, and
  22684. // that the file exists on the Windows file system.
  22685. // `os.release()` is "4.4.0-43-Microsoft" in the current release
  22686. // build of WSL, see: https://github.com/Microsoft/BashOnWindows/issues/423#issuecomment-221627364
  22687. // When a Windows editor is specified, interop functionality can
  22688. // handle the path translation, but only if a relative path is used.
  22689. fileName = path$4.relative('', fileName);
  22690. }
  22691. if (lineNumber) {
  22692. const extraArgs = getArgumentsForPosition(editor, fileName, lineNumber, columnNumber);
  22693. args.push.apply(args, extraArgs);
  22694. } else {
  22695. args.push(fileName);
  22696. }
  22697. if (_childProcess && isTerminalEditor(editor)) {
  22698. // There's an existing editor process already and it's attached
  22699. // to the terminal, so go kill it. Otherwise two separate editor
  22700. // instances attach to the stdin/stdout which gets confusing.
  22701. _childProcess.kill('SIGKILL');
  22702. }
  22703. if (process.platform === 'win32') {
  22704. // On Windows, we need to use `exec` with the `shell: true` option,
  22705. // and some more sanitization is required.
  22706. // However, CMD.exe on Windows is vulnerable to RCE attacks given a file name of the
  22707. // form "C:\Users\myusername\Downloads\& curl 172.21.93.52".
  22708. // `create-react-app` used a safe file name pattern to validate user-provided file names:
  22709. // - https://github.com/facebook/create-react-app/pull/4866
  22710. // - https://github.com/facebook/create-react-app/pull/5431
  22711. // But that's not a viable solution for this package because
  22712. // it's depended on by so many meta frameworks that heavily rely on
  22713. // special characters in file names for filesystem-based routing.
  22714. // We need to at least:
  22715. // - Support `+` because it's used in SvelteKit and Vike
  22716. // - Support `$` because it's used in Remix
  22717. // - Support `(` and `)` because they are used in Analog, SolidStart, and Vike
  22718. // - Support `@` because it's used in Vike
  22719. // - Support `[` and `]` because they are widely used for [slug]
  22720. // So here we choose to use `^` to escape special characters instead.
  22721. // According to https://ss64.com/nt/syntax-esc.html,
  22722. // we can use `^` to escape `&`, `<`, `>`, `|`, `%`, and `^`
  22723. // I'm not sure if we have to escape all of these, but let's do it anyway
  22724. function escapeCmdArgs (cmdArgs) {
  22725. return cmdArgs.replace(/([&|<>,;=^])/g, '^$1')
  22726. }
  22727. // Need to double quote the editor path in case it contains spaces;
  22728. // If the fileName contains spaces, we also need to double quote it in the arguments
  22729. // However, there's a case that it's concatenated with line number and column number
  22730. // which is separated by `:`. We need to double quote the whole string in this case.
  22731. // Also, if the string contains the escape character `^`, it needs to be quoted, too.
  22732. function doubleQuoteIfNeeded(str) {
  22733. if (str.includes('^')) {
  22734. // If a string includes an escaped character, not only does it need to be quoted,
  22735. // but the quotes need to be escaped too.
  22736. return `^"${str}^"`
  22737. } else if (str.includes(' ')) {
  22738. return `"${str}"`
  22739. }
  22740. return str
  22741. }
  22742. const launchCommand = [editor, ...args.map(escapeCmdArgs)]
  22743. .map(doubleQuoteIfNeeded)
  22744. .join(' ');
  22745. _childProcess = childProcess.exec(launchCommand, {
  22746. stdio: 'inherit',
  22747. shell: true
  22748. });
  22749. } else {
  22750. _childProcess = childProcess.spawn(editor, args, { stdio: 'inherit' });
  22751. }
  22752. _childProcess.on('exit', function (errorCode) {
  22753. _childProcess = null;
  22754. if (errorCode) {
  22755. onErrorCallback(fileName, '(code ' + errorCode + ')');
  22756. }
  22757. });
  22758. _childProcess.on('error', function (error) {
  22759. let { code, message } = error;
  22760. if ('ENOENT' === code) {
  22761. message = `${message} ('${editor}' command does not exist in 'PATH')`;
  22762. }
  22763. onErrorCallback(fileName, message);
  22764. });
  22765. }
  22766. var launchEditor_1 = launchEditor;
  22767. const url$2 = require$$0$5;
  22768. const path$3 = require$$0$2;
  22769. const launch = launchEditor_1;
  22770. var launchEditorMiddleware = (specifiedEditor, srcRoot, onErrorCallback) => {
  22771. if (typeof specifiedEditor === 'function') {
  22772. onErrorCallback = specifiedEditor;
  22773. specifiedEditor = undefined;
  22774. }
  22775. if (typeof srcRoot === 'function') {
  22776. onErrorCallback = srcRoot;
  22777. srcRoot = undefined;
  22778. }
  22779. srcRoot = srcRoot || process.cwd();
  22780. return function launchEditorMiddleware (req, res) {
  22781. const { file } = url$2.parse(req.url, true).query || {};
  22782. if (!file) {
  22783. res.statusCode = 500;
  22784. res.end(`launch-editor-middleware: required query param "file" is missing.`);
  22785. } else {
  22786. launch(path$3.resolve(srcRoot, file), specifiedEditor, onErrorCallback);
  22787. res.end();
  22788. }
  22789. }
  22790. };
  22791. var launchEditorMiddleware$1 = /*@__PURE__*/getDefaultExportFromCjs(launchEditorMiddleware);
  22792. async function resolveHttpServer({ proxy }, app, httpsOptions) {
  22793. if (!httpsOptions) {
  22794. const { createServer } = await import('node:http');
  22795. return createServer(app);
  22796. }
  22797. if (proxy) {
  22798. const { createServer } = await import('node:https');
  22799. return createServer(httpsOptions, app);
  22800. } else {
  22801. const { createSecureServer } = await import('node:http2');
  22802. return createSecureServer(
  22803. {
  22804. // Manually increase the session memory to prevent 502 ENHANCE_YOUR_CALM
  22805. // errors on large numbers of requests
  22806. maxSessionMemory: 1e3,
  22807. ...httpsOptions,
  22808. allowHTTP1: true
  22809. },
  22810. // @ts-expect-error TODO: is this correct?
  22811. app
  22812. );
  22813. }
  22814. }
  22815. async function resolveHttpsConfig(https) {
  22816. if (!https) return void 0;
  22817. const [ca, cert, key, pfx] = await Promise.all([
  22818. readFileIfExists(https.ca),
  22819. readFileIfExists(https.cert),
  22820. readFileIfExists(https.key),
  22821. readFileIfExists(https.pfx)
  22822. ]);
  22823. return { ...https, ca, cert, key, pfx };
  22824. }
  22825. async function readFileIfExists(value) {
  22826. if (typeof value === "string") {
  22827. return fsp.readFile(path$b.resolve(value)).catch(() => value);
  22828. }
  22829. return value;
  22830. }
  22831. async function httpServerStart(httpServer, serverOptions) {
  22832. let { port, strictPort, host, logger } = serverOptions;
  22833. return new Promise((resolve, reject) => {
  22834. const onError = (e) => {
  22835. if (e.code === "EADDRINUSE") {
  22836. if (strictPort) {
  22837. httpServer.removeListener("error", onError);
  22838. reject(new Error(`Port ${port} is already in use`));
  22839. } else {
  22840. logger.info(`Port ${port} is in use, trying another one...`);
  22841. httpServer.listen(++port, host);
  22842. }
  22843. } else {
  22844. httpServer.removeListener("error", onError);
  22845. reject(e);
  22846. }
  22847. };
  22848. httpServer.on("error", onError);
  22849. httpServer.listen(port, host, () => {
  22850. httpServer.removeListener("error", onError);
  22851. resolve(port);
  22852. });
  22853. });
  22854. }
  22855. function setClientErrorHandler(server, logger) {
  22856. server.on("clientError", (err, socket) => {
  22857. let msg = "400 Bad Request";
  22858. if (err.code === "HPE_HEADER_OVERFLOW") {
  22859. msg = "431 Request Header Fields Too Large";
  22860. logger.warn(
  22861. colors$1.yellow(
  22862. "Server responded with status code 431. See https://vite.dev/guide/troubleshooting.html#_431-request-header-fields-too-large."
  22863. )
  22864. );
  22865. }
  22866. if (err.code === "ECONNRESET" || !socket.writable) {
  22867. return;
  22868. }
  22869. socket.end(`HTTP/1.1 ${msg}\r
  22870. \r
  22871. `);
  22872. });
  22873. }
  22874. let offset;
  22875. function calculateOffsetOnce() {
  22876. if (offset !== void 0) {
  22877. return;
  22878. }
  22879. try {
  22880. new Function("throw new Error(1)")();
  22881. } catch (e) {
  22882. const match = /:(\d+):\d+\)$/.exec(e.stack.split("\n")[1]);
  22883. offset = match ? +match[1] - 1 : 0;
  22884. }
  22885. }
  22886. function ssrRewriteStacktrace(stack, moduleGraph) {
  22887. calculateOffsetOnce();
  22888. return stack.split("\n").map((line) => {
  22889. return line.replace(
  22890. /^ {4}at (?:(\S.*?)\s\()?(.+?):(\d+)(?::(\d+))?\)?/,
  22891. (input, varName, id, line2, column) => {
  22892. if (!id) return input;
  22893. const mod = moduleGraph.getModuleById(id);
  22894. const rawSourceMap = mod?.transformResult?.map;
  22895. if (!rawSourceMap) {
  22896. return input;
  22897. }
  22898. const traced = new TraceMap(rawSourceMap);
  22899. const pos = originalPositionFor$1(traced, {
  22900. line: Number(line2) - offset,
  22901. // stacktrace's column is 1-indexed, but sourcemap's one is 0-indexed
  22902. column: Number(column) - 1
  22903. });
  22904. if (!pos.source) {
  22905. return input;
  22906. }
  22907. const trimmedVarName = varName?.trim();
  22908. const sourceFile = path$b.resolve(path$b.dirname(id), pos.source);
  22909. const source = `${sourceFile}:${pos.line}:${pos.column + 1}`;
  22910. if (!trimmedVarName || trimmedVarName === "eval") {
  22911. return ` at ${source}`;
  22912. } else {
  22913. return ` at ${trimmedVarName} (${source})`;
  22914. }
  22915. }
  22916. );
  22917. }).join("\n");
  22918. }
  22919. function rebindErrorStacktrace(e, stacktrace) {
  22920. const { configurable, writable } = Object.getOwnPropertyDescriptor(
  22921. e,
  22922. "stack"
  22923. );
  22924. if (configurable) {
  22925. Object.defineProperty(e, "stack", {
  22926. value: stacktrace,
  22927. enumerable: true,
  22928. configurable: true,
  22929. writable: true
  22930. });
  22931. } else if (writable) {
  22932. e.stack = stacktrace;
  22933. }
  22934. }
  22935. const rewroteStacktraces = /* @__PURE__ */ new WeakSet();
  22936. function ssrFixStacktrace(e, moduleGraph) {
  22937. if (!e.stack) return;
  22938. if (rewroteStacktraces.has(e)) return;
  22939. const stacktrace = ssrRewriteStacktrace(e.stack, moduleGraph);
  22940. rebindErrorStacktrace(e, stacktrace);
  22941. rewroteStacktraces.add(e);
  22942. }
  22943. function createHMROptions(environment, options) {
  22944. if (environment.config.server.hmr === false || options.hmr === false) {
  22945. return false;
  22946. }
  22947. if (!("api" in environment.hot)) return false;
  22948. return {
  22949. logger: options.hmr?.logger
  22950. };
  22951. }
  22952. const prepareStackTrace = {
  22953. retrieveFile(id) {
  22954. if (existsSync$1(id)) {
  22955. return readFileSync$1(id, "utf-8");
  22956. }
  22957. }
  22958. };
  22959. function resolveSourceMapOptions(options) {
  22960. if (options.sourcemapInterceptor != null) {
  22961. if (options.sourcemapInterceptor === "prepareStackTrace") {
  22962. return prepareStackTrace;
  22963. }
  22964. if (typeof options.sourcemapInterceptor === "object") {
  22965. return { ...prepareStackTrace, ...options.sourcemapInterceptor };
  22966. }
  22967. return options.sourcemapInterceptor;
  22968. }
  22969. if (typeof process !== "undefined" && "setSourceMapsEnabled" in process) {
  22970. return "node";
  22971. }
  22972. return prepareStackTrace;
  22973. }
  22974. const createServerModuleRunnerTransport = (options) => {
  22975. const hmrClient = {
  22976. send: (payload) => {
  22977. if (payload.type !== "custom") {
  22978. throw new Error(
  22979. "Cannot send non-custom events from the client to the server."
  22980. );
  22981. }
  22982. options.channel.send(payload);
  22983. }
  22984. };
  22985. let handler;
  22986. return {
  22987. connect({ onMessage }) {
  22988. options.channel.api.outsideEmitter.on("send", onMessage);
  22989. onMessage({ type: "connected" });
  22990. handler = onMessage;
  22991. },
  22992. disconnect() {
  22993. if (handler) {
  22994. options.channel.api.outsideEmitter.off("send", handler);
  22995. }
  22996. },
  22997. send(payload) {
  22998. if (payload.type !== "custom") {
  22999. throw new Error(
  23000. "Cannot send non-custom events from the server to the client."
  23001. );
  23002. }
  23003. options.channel.api.innerEmitter.emit(
  23004. payload.event,
  23005. payload.data,
  23006. hmrClient
  23007. );
  23008. }
  23009. };
  23010. };
  23011. function createServerModuleRunner(environment, options = {}) {
  23012. const hmr = createHMROptions(environment, options);
  23013. return new ModuleRunner(
  23014. {
  23015. ...options,
  23016. root: environment.config.root,
  23017. transport: createServerModuleRunnerTransport({
  23018. channel: environment.hot
  23019. }),
  23020. hmr,
  23021. sourcemapInterceptor: resolveSourceMapOptions(options)
  23022. },
  23023. options.evaluator
  23024. );
  23025. }
  23026. async function ssrLoadModule(url, server, fixStacktrace) {
  23027. const environment = server.environments.ssr;
  23028. server._ssrCompatModuleRunner ||= new SSRCompatModuleRunner(environment);
  23029. url = unwrapId$1(url);
  23030. return instantiateModule(
  23031. url,
  23032. server._ssrCompatModuleRunner,
  23033. environment,
  23034. fixStacktrace
  23035. );
  23036. }
  23037. async function instantiateModule(url, runner, environment, fixStacktrace) {
  23038. const mod = await environment.moduleGraph.ensureEntryFromUrl(url);
  23039. if (mod.ssrError) {
  23040. throw mod.ssrError;
  23041. }
  23042. try {
  23043. return await runner.import(url);
  23044. } catch (e) {
  23045. if (e.stack && fixStacktrace) {
  23046. ssrFixStacktrace(e, environment.moduleGraph);
  23047. }
  23048. environment.logger.error(
  23049. buildErrorMessage(e, [
  23050. colors$1.red(`Error when evaluating SSR module ${url}: ${e.message}`)
  23051. ]),
  23052. {
  23053. timestamp: true,
  23054. clear: environment.config.clearScreen,
  23055. error: e
  23056. }
  23057. );
  23058. throw e;
  23059. }
  23060. }
  23061. class SSRCompatModuleRunner extends ModuleRunner {
  23062. constructor(environment) {
  23063. super(
  23064. {
  23065. root: environment.config.root,
  23066. transport: createServerModuleRunnerTransport({
  23067. channel: environment.hot
  23068. }),
  23069. sourcemapInterceptor: false,
  23070. hmr: false
  23071. },
  23072. new ESModulesEvaluator()
  23073. );
  23074. this.environment = environment;
  23075. }
  23076. async directRequest(url, mod, callstack) {
  23077. const id = mod.meta && "id" in mod.meta && mod.meta.id;
  23078. if (!id) {
  23079. return super.directRequest(url, mod, callstack);
  23080. }
  23081. const viteMod = this.environment.moduleGraph.getModuleById(id);
  23082. if (!viteMod) {
  23083. return super.directRequest(id, mod, callstack);
  23084. }
  23085. try {
  23086. const exports = await super.directRequest(id, mod, callstack);
  23087. viteMod.ssrModule = exports;
  23088. return exports;
  23089. } catch (err) {
  23090. viteMod.ssrError = err;
  23091. throw err;
  23092. }
  23093. }
  23094. }
  23095. /**
  23096. * @param {import('estree').Node} param
  23097. * @returns {string[]}
  23098. */
  23099. function extract_names(param) {
  23100. return extract_identifiers(param).map((node) => node.name);
  23101. }
  23102. /**
  23103. * @param {import('estree').Node} param
  23104. * @param {import('estree').Identifier[]} nodes
  23105. * @returns {import('estree').Identifier[]}
  23106. */
  23107. function extract_identifiers(param, nodes = []) {
  23108. switch (param.type) {
  23109. case 'Identifier':
  23110. nodes.push(param);
  23111. break;
  23112. case 'MemberExpression':
  23113. let object = param;
  23114. while (object.type === 'MemberExpression') {
  23115. object = /** @type {any} */ (object.object);
  23116. }
  23117. nodes.push(/** @type {any} */ (object));
  23118. break;
  23119. case 'ObjectPattern':
  23120. for (const prop of param.properties) {
  23121. if (prop.type === 'RestElement') {
  23122. extract_identifiers(prop.argument, nodes);
  23123. } else {
  23124. extract_identifiers(prop.value, nodes);
  23125. }
  23126. }
  23127. break;
  23128. case 'ArrayPattern':
  23129. for (const element of param.elements) {
  23130. if (element) extract_identifiers(element, nodes);
  23131. }
  23132. break;
  23133. case 'RestElement':
  23134. extract_identifiers(param.argument, nodes);
  23135. break;
  23136. case 'AssignmentPattern':
  23137. extract_identifiers(param.left, nodes);
  23138. break;
  23139. }
  23140. return nodes;
  23141. }
  23142. /**
  23143. * @typedef { import('estree').Node} Node
  23144. * @typedef {{
  23145. * skip: () => void;
  23146. * remove: () => void;
  23147. * replace: (node: Node) => void;
  23148. * }} WalkerContext
  23149. */
  23150. class WalkerBase {
  23151. constructor() {
  23152. /** @type {boolean} */
  23153. this.should_skip = false;
  23154. /** @type {boolean} */
  23155. this.should_remove = false;
  23156. /** @type {Node | null} */
  23157. this.replacement = null;
  23158. /** @type {WalkerContext} */
  23159. this.context = {
  23160. skip: () => (this.should_skip = true),
  23161. remove: () => (this.should_remove = true),
  23162. replace: (node) => (this.replacement = node)
  23163. };
  23164. }
  23165. /**
  23166. * @template {Node} Parent
  23167. * @param {Parent | null | undefined} parent
  23168. * @param {keyof Parent | null | undefined} prop
  23169. * @param {number | null | undefined} index
  23170. * @param {Node} node
  23171. */
  23172. replace(parent, prop, index, node) {
  23173. if (parent && prop) {
  23174. if (index != null) {
  23175. /** @type {Array<Node>} */ (parent[prop])[index] = node;
  23176. } else {
  23177. /** @type {Node} */ (parent[prop]) = node;
  23178. }
  23179. }
  23180. }
  23181. /**
  23182. * @template {Node} Parent
  23183. * @param {Parent | null | undefined} parent
  23184. * @param {keyof Parent | null | undefined} prop
  23185. * @param {number | null | undefined} index
  23186. */
  23187. remove(parent, prop, index) {
  23188. if (parent && prop) {
  23189. if (index !== null && index !== undefined) {
  23190. /** @type {Array<Node>} */ (parent[prop]).splice(index, 1);
  23191. } else {
  23192. delete parent[prop];
  23193. }
  23194. }
  23195. }
  23196. }
  23197. /**
  23198. * @typedef { import('estree').Node} Node
  23199. * @typedef { import('./walker.js').WalkerContext} WalkerContext
  23200. * @typedef {(
  23201. * this: WalkerContext,
  23202. * node: Node,
  23203. * parent: Node | null,
  23204. * key: string | number | symbol | null | undefined,
  23205. * index: number | null | undefined
  23206. * ) => void} SyncHandler
  23207. */
  23208. class SyncWalker extends WalkerBase {
  23209. /**
  23210. *
  23211. * @param {SyncHandler} [enter]
  23212. * @param {SyncHandler} [leave]
  23213. */
  23214. constructor(enter, leave) {
  23215. super();
  23216. /** @type {boolean} */
  23217. this.should_skip = false;
  23218. /** @type {boolean} */
  23219. this.should_remove = false;
  23220. /** @type {Node | null} */
  23221. this.replacement = null;
  23222. /** @type {WalkerContext} */
  23223. this.context = {
  23224. skip: () => (this.should_skip = true),
  23225. remove: () => (this.should_remove = true),
  23226. replace: (node) => (this.replacement = node)
  23227. };
  23228. /** @type {SyncHandler | undefined} */
  23229. this.enter = enter;
  23230. /** @type {SyncHandler | undefined} */
  23231. this.leave = leave;
  23232. }
  23233. /**
  23234. * @template {Node} Parent
  23235. * @param {Node} node
  23236. * @param {Parent | null} parent
  23237. * @param {keyof Parent} [prop]
  23238. * @param {number | null} [index]
  23239. * @returns {Node | null}
  23240. */
  23241. visit(node, parent, prop, index) {
  23242. if (node) {
  23243. if (this.enter) {
  23244. const _should_skip = this.should_skip;
  23245. const _should_remove = this.should_remove;
  23246. const _replacement = this.replacement;
  23247. this.should_skip = false;
  23248. this.should_remove = false;
  23249. this.replacement = null;
  23250. this.enter.call(this.context, node, parent, prop, index);
  23251. if (this.replacement) {
  23252. node = this.replacement;
  23253. this.replace(parent, prop, index, node);
  23254. }
  23255. if (this.should_remove) {
  23256. this.remove(parent, prop, index);
  23257. }
  23258. const skipped = this.should_skip;
  23259. const removed = this.should_remove;
  23260. this.should_skip = _should_skip;
  23261. this.should_remove = _should_remove;
  23262. this.replacement = _replacement;
  23263. if (skipped) return node;
  23264. if (removed) return null;
  23265. }
  23266. /** @type {keyof Node} */
  23267. let key;
  23268. for (key in node) {
  23269. /** @type {unknown} */
  23270. const value = node[key];
  23271. if (value && typeof value === 'object') {
  23272. if (Array.isArray(value)) {
  23273. const nodes = /** @type {Array<unknown>} */ (value);
  23274. for (let i = 0; i < nodes.length; i += 1) {
  23275. const item = nodes[i];
  23276. if (isNode(item)) {
  23277. if (!this.visit(item, node, key, i)) {
  23278. // removed
  23279. i--;
  23280. }
  23281. }
  23282. }
  23283. } else if (isNode(value)) {
  23284. this.visit(value, node, key, null);
  23285. }
  23286. }
  23287. }
  23288. if (this.leave) {
  23289. const _replacement = this.replacement;
  23290. const _should_remove = this.should_remove;
  23291. this.replacement = null;
  23292. this.should_remove = false;
  23293. this.leave.call(this.context, node, parent, prop, index);
  23294. if (this.replacement) {
  23295. node = this.replacement;
  23296. this.replace(parent, prop, index, node);
  23297. }
  23298. if (this.should_remove) {
  23299. this.remove(parent, prop, index);
  23300. }
  23301. const removed = this.should_remove;
  23302. this.replacement = _replacement;
  23303. this.should_remove = _should_remove;
  23304. if (removed) return null;
  23305. }
  23306. }
  23307. return node;
  23308. }
  23309. }
  23310. /**
  23311. * Ducktype a node.
  23312. *
  23313. * @param {unknown} value
  23314. * @returns {value is Node}
  23315. */
  23316. function isNode(value) {
  23317. return (
  23318. value !== null && typeof value === 'object' && 'type' in value && typeof value.type === 'string'
  23319. );
  23320. }
  23321. /**
  23322. * @typedef {import('estree').Node} Node
  23323. * @typedef {import('./sync.js').SyncHandler} SyncHandler
  23324. * @typedef {import('./async.js').AsyncHandler} AsyncHandler
  23325. */
  23326. /**
  23327. * @param {Node} ast
  23328. * @param {{
  23329. * enter?: SyncHandler
  23330. * leave?: SyncHandler
  23331. * }} walker
  23332. * @returns {Node | null}
  23333. */
  23334. function walk$1(ast, { enter, leave }) {
  23335. const instance = new SyncWalker(enter, leave);
  23336. return instance.visit(ast, null);
  23337. }
  23338. const ssrModuleExportsKey = `__vite_ssr_exports__`;
  23339. const ssrImportKey = `__vite_ssr_import__`;
  23340. const ssrDynamicImportKey = `__vite_ssr_dynamic_import__`;
  23341. const ssrExportAllKey = `__vite_ssr_exportAll__`;
  23342. const ssrImportMetaKey = `__vite_ssr_import_meta__`;
  23343. const hashbangRE = /^#!.*\n/;
  23344. async function ssrTransform(code, inMap, url, originalCode, options) {
  23345. if (options?.json?.stringify && isJSONRequest(url)) {
  23346. return ssrTransformJSON(code, inMap);
  23347. }
  23348. return ssrTransformScript(code, inMap, url, originalCode);
  23349. }
  23350. async function ssrTransformJSON(code, inMap) {
  23351. return {
  23352. code: code.replace("export default", `${ssrModuleExportsKey}.default =`),
  23353. map: inMap,
  23354. deps: [],
  23355. dynamicDeps: [],
  23356. ssr: true
  23357. };
  23358. }
  23359. async function ssrTransformScript(code, inMap, url, originalCode) {
  23360. const s = new MagicString(code);
  23361. let ast;
  23362. try {
  23363. ast = await parseAstAsync(code);
  23364. } catch (err) {
  23365. if (err.code === "PARSE_ERROR") {
  23366. err.message = `Parse failure: ${err.message}
  23367. `;
  23368. err.id = url;
  23369. if (typeof err.pos === "number") {
  23370. err.loc = numberToPos(code, err.pos);
  23371. err.loc.file = url;
  23372. err.frame = generateCodeFrame(code, err.pos);
  23373. err.message += `At file: ${url}:${err.loc.line}:${err.loc.column}`;
  23374. } else {
  23375. err.message += `At file: ${url}`;
  23376. }
  23377. }
  23378. throw err;
  23379. }
  23380. let uid = 0;
  23381. const deps = /* @__PURE__ */ new Set();
  23382. const dynamicDeps = /* @__PURE__ */ new Set();
  23383. const idToImportMap = /* @__PURE__ */ new Map();
  23384. const declaredConst = /* @__PURE__ */ new Set();
  23385. const fileStartIndex = hashbangRE.exec(code)?.[0].length ?? 0;
  23386. let hoistIndex = fileStartIndex;
  23387. function defineImport(index, importNode, metadata) {
  23388. const source = importNode.source.value;
  23389. deps.add(source);
  23390. const metadataArg = (metadata?.importedNames?.length ?? 0) > 0 ? `, ${JSON.stringify(metadata)}` : "";
  23391. const importId = `__vite_ssr_import_${uid++}__`;
  23392. const transformedImport = `const ${importId} = await ${ssrImportKey}(${JSON.stringify(
  23393. source
  23394. )}${metadataArg});`;
  23395. s.update(importNode.start, importNode.end, transformedImport);
  23396. const nonWhitespaceRegex = /\S/g;
  23397. nonWhitespaceRegex.lastIndex = index;
  23398. nonWhitespaceRegex.exec(code);
  23399. if (importNode.start > nonWhitespaceRegex.lastIndex) {
  23400. s.move(importNode.start, importNode.end, index);
  23401. } else {
  23402. hoistIndex = importNode.end;
  23403. }
  23404. let linesSpanned = 1;
  23405. for (let i = importNode.start; i < importNode.end; i++) {
  23406. if (code[i] === "\n") {
  23407. linesSpanned++;
  23408. }
  23409. }
  23410. if (linesSpanned > 1) {
  23411. s.prependRight(importNode.end, "\n".repeat(linesSpanned - 1));
  23412. }
  23413. return importId;
  23414. }
  23415. function defineExport(name, local = name) {
  23416. s.appendLeft(
  23417. fileStartIndex,
  23418. `Object.defineProperty(${ssrModuleExportsKey}, ${JSON.stringify(name)}, { enumerable: true, configurable: true, get(){ try { return ${local} } catch {} }});
  23419. `
  23420. );
  23421. }
  23422. const imports = [];
  23423. const exports = [];
  23424. const reExportImportIdMap = /* @__PURE__ */ new Map();
  23425. for (const node of ast.body) {
  23426. if (node.type === "ImportDeclaration") {
  23427. imports.push(node);
  23428. } else if (node.type === "ExportDefaultDeclaration") {
  23429. exports.push(node);
  23430. } else if (node.type === "ExportNamedDeclaration" || node.type === "ExportAllDeclaration") {
  23431. imports.push(node);
  23432. exports.push(node);
  23433. }
  23434. }
  23435. for (const node of imports) {
  23436. if (node.type === "ExportNamedDeclaration") {
  23437. if (node.source) {
  23438. const importId2 = defineImport(
  23439. hoistIndex,
  23440. node,
  23441. {
  23442. importedNames: node.specifiers.map(
  23443. (s2) => getIdentifierNameOrLiteralValue$1(s2.local)
  23444. )
  23445. }
  23446. );
  23447. reExportImportIdMap.set(node, importId2);
  23448. }
  23449. continue;
  23450. }
  23451. if (node.type === "ExportAllDeclaration") {
  23452. if (node.source) {
  23453. const importId2 = defineImport(hoistIndex, node);
  23454. reExportImportIdMap.set(node, importId2);
  23455. }
  23456. continue;
  23457. }
  23458. const importId = defineImport(hoistIndex, node, {
  23459. importedNames: node.specifiers.map((s2) => {
  23460. if (s2.type === "ImportSpecifier")
  23461. return getIdentifierNameOrLiteralValue$1(s2.imported);
  23462. else if (s2.type === "ImportDefaultSpecifier") return "default";
  23463. }).filter(isDefined)
  23464. });
  23465. for (const spec of node.specifiers) {
  23466. if (spec.type === "ImportSpecifier") {
  23467. if (spec.imported.type === "Identifier") {
  23468. idToImportMap.set(
  23469. spec.local.name,
  23470. `${importId}.${spec.imported.name}`
  23471. );
  23472. } else {
  23473. idToImportMap.set(
  23474. spec.local.name,
  23475. `${importId}[${JSON.stringify(spec.imported.value)}]`
  23476. );
  23477. }
  23478. } else if (spec.type === "ImportDefaultSpecifier") {
  23479. idToImportMap.set(spec.local.name, `${importId}.default`);
  23480. } else {
  23481. idToImportMap.set(spec.local.name, importId);
  23482. }
  23483. }
  23484. }
  23485. for (const node of exports) {
  23486. if (node.type === "ExportNamedDeclaration") {
  23487. if (node.declaration) {
  23488. if (node.declaration.type === "FunctionDeclaration" || node.declaration.type === "ClassDeclaration") {
  23489. defineExport(node.declaration.id.name);
  23490. } else {
  23491. for (const declaration of node.declaration.declarations) {
  23492. const names = extract_names(declaration.id);
  23493. for (const name of names) {
  23494. defineExport(name);
  23495. }
  23496. }
  23497. }
  23498. s.remove(node.start, node.declaration.start);
  23499. } else {
  23500. if (node.source) {
  23501. const importId = reExportImportIdMap.get(node);
  23502. for (const spec of node.specifiers) {
  23503. const exportedAs = getIdentifierNameOrLiteralValue$1(
  23504. spec.exported
  23505. );
  23506. if (spec.local.type === "Identifier") {
  23507. defineExport(exportedAs, `${importId}.${spec.local.name}`);
  23508. } else {
  23509. defineExport(
  23510. exportedAs,
  23511. `${importId}[${JSON.stringify(spec.local.value)}]`
  23512. );
  23513. }
  23514. }
  23515. } else {
  23516. s.remove(node.start, node.end);
  23517. for (const spec of node.specifiers) {
  23518. const local = spec.local.name;
  23519. const binding = idToImportMap.get(local);
  23520. const exportedAs = getIdentifierNameOrLiteralValue$1(
  23521. spec.exported
  23522. );
  23523. defineExport(exportedAs, binding || local);
  23524. }
  23525. }
  23526. }
  23527. }
  23528. if (node.type === "ExportDefaultDeclaration") {
  23529. const expressionTypes = ["FunctionExpression", "ClassExpression"];
  23530. if ("id" in node.declaration && node.declaration.id && !expressionTypes.includes(node.declaration.type)) {
  23531. const { name } = node.declaration.id;
  23532. s.remove(
  23533. node.start,
  23534. node.start + 15
  23535. /* 'export default '.length */
  23536. );
  23537. defineExport("default", name);
  23538. } else {
  23539. const name = `__vite_ssr_export_default__`;
  23540. s.update(
  23541. node.start,
  23542. node.start + 14,
  23543. `const ${name} =`
  23544. );
  23545. defineExport("default", name);
  23546. }
  23547. }
  23548. if (node.type === "ExportAllDeclaration") {
  23549. const importId = reExportImportIdMap.get(node);
  23550. if (node.exported) {
  23551. const exportedAs = getIdentifierNameOrLiteralValue$1(
  23552. node.exported
  23553. );
  23554. defineExport(exportedAs, `${importId}`);
  23555. } else {
  23556. s.appendLeft(node.end, `${ssrExportAllKey}(${importId});
  23557. `);
  23558. }
  23559. }
  23560. }
  23561. walk(ast, {
  23562. onStatements(statements) {
  23563. for (let i = 0; i < statements.length - 1; i++) {
  23564. const stmt = statements[i];
  23565. if (code[stmt.end - 1] !== ";" && stmt.type !== "FunctionDeclaration" && stmt.type !== "ClassDeclaration" && stmt.type !== "BlockStatement" && stmt.type !== "ImportDeclaration") {
  23566. s.appendLeft(stmt.end, ";");
  23567. }
  23568. }
  23569. },
  23570. onIdentifier(id, parent, parentStack) {
  23571. const grandparent = parentStack[1];
  23572. const binding = idToImportMap.get(id.name);
  23573. if (!binding) {
  23574. return;
  23575. }
  23576. if (isStaticProperty(parent) && parent.shorthand) {
  23577. if (!isNodeInPattern(parent) || isInDestructuringAssignment(parent, parentStack)) {
  23578. s.appendLeft(id.end, `: ${binding}`);
  23579. }
  23580. } else if (parent.type === "PropertyDefinition" && grandparent?.type === "ClassBody" || parent.type === "ClassDeclaration" && id === parent.superClass) {
  23581. if (!declaredConst.has(id.name)) {
  23582. declaredConst.add(id.name);
  23583. const topNode = parentStack[parentStack.length - 2];
  23584. s.prependRight(topNode.start, `const ${id.name} = ${binding};
  23585. `);
  23586. }
  23587. } else if (parent.type === "CallExpression") {
  23588. s.update(id.start, id.end, binding);
  23589. s.prependRight(id.start, `(0,`);
  23590. s.appendLeft(id.end, `)`);
  23591. } else if (
  23592. // don't transform class name identifier
  23593. !(parent.type === "ClassExpression" && id === parent.id)
  23594. ) {
  23595. s.update(id.start, id.end, binding);
  23596. }
  23597. },
  23598. onImportMeta(node) {
  23599. s.update(node.start, node.end, ssrImportMetaKey);
  23600. },
  23601. onDynamicImport(node) {
  23602. s.update(node.start, node.start + 6, ssrDynamicImportKey);
  23603. if (node.type === "ImportExpression" && node.source.type === "Literal") {
  23604. dynamicDeps.add(node.source.value);
  23605. }
  23606. }
  23607. });
  23608. let map;
  23609. if (inMap?.mappings === "") {
  23610. map = inMap;
  23611. } else {
  23612. map = s.generateMap({ hires: "boundary" });
  23613. map.sources = [path$b.basename(url)];
  23614. map.sourcesContent = [originalCode];
  23615. if (inMap && inMap.mappings && "sources" in inMap && inMap.sources.length > 0) {
  23616. map = combineSourcemaps(url, [
  23617. map,
  23618. inMap
  23619. ]);
  23620. }
  23621. }
  23622. return {
  23623. code: s.toString(),
  23624. map,
  23625. ssr: true,
  23626. deps: [...deps],
  23627. dynamicDeps: [...dynamicDeps]
  23628. };
  23629. }
  23630. function getIdentifierNameOrLiteralValue$1(node) {
  23631. return node.type === "Identifier" ? node.name : node.value;
  23632. }
  23633. const isNodeInPatternWeakSet = /* @__PURE__ */ new WeakSet();
  23634. const setIsNodeInPattern = (node) => isNodeInPatternWeakSet.add(node);
  23635. const isNodeInPattern = (node) => isNodeInPatternWeakSet.has(node);
  23636. function walk(root, { onIdentifier, onImportMeta, onDynamicImport, onStatements }) {
  23637. const parentStack = [];
  23638. const varKindStack = [];
  23639. const scopeMap = /* @__PURE__ */ new WeakMap();
  23640. const identifiers = [];
  23641. const setScope = (node, name) => {
  23642. let scopeIds = scopeMap.get(node);
  23643. if (scopeIds && scopeIds.has(name)) {
  23644. return;
  23645. }
  23646. if (!scopeIds) {
  23647. scopeIds = /* @__PURE__ */ new Set();
  23648. scopeMap.set(node, scopeIds);
  23649. }
  23650. scopeIds.add(name);
  23651. };
  23652. function isInScope(name, parents) {
  23653. return parents.some((node) => scopeMap.get(node)?.has(name));
  23654. }
  23655. function handlePattern(p, parentScope) {
  23656. if (p.type === "Identifier") {
  23657. setScope(parentScope, p.name);
  23658. } else if (p.type === "RestElement") {
  23659. handlePattern(p.argument, parentScope);
  23660. } else if (p.type === "ObjectPattern") {
  23661. p.properties.forEach((property) => {
  23662. if (property.type === "RestElement") {
  23663. setScope(parentScope, property.argument.name);
  23664. } else {
  23665. handlePattern(property.value, parentScope);
  23666. }
  23667. });
  23668. } else if (p.type === "ArrayPattern") {
  23669. p.elements.forEach((element) => {
  23670. if (element) {
  23671. handlePattern(element, parentScope);
  23672. }
  23673. });
  23674. } else if (p.type === "AssignmentPattern") {
  23675. handlePattern(p.left, parentScope);
  23676. } else {
  23677. setScope(parentScope, p.name);
  23678. }
  23679. }
  23680. walk$1(root, {
  23681. enter(node, parent) {
  23682. if (node.type === "ImportDeclaration") {
  23683. return this.skip();
  23684. }
  23685. if (node.type === "Program" || node.type === "BlockStatement" || node.type === "StaticBlock") {
  23686. onStatements(node.body);
  23687. } else if (node.type === "SwitchCase") {
  23688. onStatements(node.consequent);
  23689. }
  23690. if (parent && !(parent.type === "IfStatement" && node === parent.alternate)) {
  23691. parentStack.unshift(parent);
  23692. }
  23693. if (node.type === "VariableDeclaration") {
  23694. varKindStack.unshift(node.kind);
  23695. }
  23696. if (node.type === "MetaProperty" && node.meta.name === "import") {
  23697. onImportMeta(node);
  23698. } else if (node.type === "ImportExpression") {
  23699. onDynamicImport(node);
  23700. }
  23701. if (node.type === "Identifier") {
  23702. if (!isInScope(node.name, parentStack) && isRefIdentifier(node, parent, parentStack)) {
  23703. identifiers.push([node, parentStack.slice(0)]);
  23704. }
  23705. } else if (isFunction$1(node)) {
  23706. if (node.type === "FunctionDeclaration") {
  23707. const parentScope = findParentScope(parentStack);
  23708. if (parentScope) {
  23709. setScope(parentScope, node.id.name);
  23710. }
  23711. }
  23712. if (node.type === "FunctionExpression" && node.id) {
  23713. setScope(node, node.id.name);
  23714. }
  23715. node.params.forEach((p) => {
  23716. if (p.type === "ObjectPattern" || p.type === "ArrayPattern") {
  23717. handlePattern(p, node);
  23718. return;
  23719. }
  23720. walk$1(p.type === "AssignmentPattern" ? p.left : p, {
  23721. enter(child, parent2) {
  23722. if (parent2?.type === "AssignmentPattern" && parent2.right === child) {
  23723. return this.skip();
  23724. }
  23725. if (child.type !== "Identifier") return;
  23726. if (isStaticPropertyKey(child, parent2)) return;
  23727. if (parent2?.type === "TemplateLiteral" && parent2.expressions.includes(child) || parent2?.type === "CallExpression" && parent2.callee === child) {
  23728. return;
  23729. }
  23730. setScope(node, child.name);
  23731. }
  23732. });
  23733. });
  23734. } else if (node.type === "ClassDeclaration") {
  23735. const parentScope = findParentScope(parentStack);
  23736. if (parentScope) {
  23737. setScope(parentScope, node.id.name);
  23738. }
  23739. } else if (node.type === "ClassExpression" && node.id) {
  23740. setScope(node, node.id.name);
  23741. } else if (node.type === "Property" && parent.type === "ObjectPattern") {
  23742. setIsNodeInPattern(node);
  23743. } else if (node.type === "VariableDeclarator") {
  23744. const parentFunction = findParentScope(
  23745. parentStack,
  23746. varKindStack[0] === "var"
  23747. );
  23748. if (parentFunction) {
  23749. handlePattern(node.id, parentFunction);
  23750. }
  23751. } else if (node.type === "CatchClause" && node.param) {
  23752. handlePattern(node.param, node);
  23753. }
  23754. },
  23755. leave(node, parent) {
  23756. if (parent && !(parent.type === "IfStatement" && node === parent.alternate)) {
  23757. parentStack.shift();
  23758. }
  23759. if (node.type === "VariableDeclaration") {
  23760. varKindStack.shift();
  23761. }
  23762. }
  23763. });
  23764. identifiers.forEach(([node, stack]) => {
  23765. if (!isInScope(node.name, stack)) onIdentifier(node, stack[0], stack);
  23766. });
  23767. }
  23768. function isRefIdentifier(id, parent, parentStack) {
  23769. if (parent.type === "CatchClause" || (parent.type === "VariableDeclarator" || parent.type === "ClassDeclaration") && parent.id === id) {
  23770. return false;
  23771. }
  23772. if (isFunction$1(parent)) {
  23773. if (parent.id === id) {
  23774. return false;
  23775. }
  23776. if (parent.params.includes(id)) {
  23777. return false;
  23778. }
  23779. }
  23780. if (parent.type === "MethodDefinition" && !parent.computed) {
  23781. return false;
  23782. }
  23783. if (isStaticPropertyKey(id, parent)) {
  23784. return false;
  23785. }
  23786. if (isNodeInPattern(parent) && parent.value === id) {
  23787. return false;
  23788. }
  23789. if (parent.type === "ArrayPattern" && !isInDestructuringAssignment(parent, parentStack)) {
  23790. return false;
  23791. }
  23792. if (parent.type === "MemberExpression" && parent.property === id && !parent.computed) {
  23793. return false;
  23794. }
  23795. if (parent.type === "ExportSpecifier" || parent.type === "ExportAllDeclaration") {
  23796. return false;
  23797. }
  23798. if (id.name === "arguments") {
  23799. return false;
  23800. }
  23801. return true;
  23802. }
  23803. const isStaticProperty = (node) => node.type === "Property" && !node.computed;
  23804. const isStaticPropertyKey = (node, parent) => parent && isStaticProperty(parent) && parent.key === node;
  23805. const functionNodeTypeRE = /Function(?:Expression|Declaration)$|Method$/;
  23806. function isFunction$1(node) {
  23807. return functionNodeTypeRE.test(node.type);
  23808. }
  23809. const blockNodeTypeRE = /^BlockStatement$|^For(?:In|Of)?Statement$/;
  23810. function isBlock(node) {
  23811. return blockNodeTypeRE.test(node.type);
  23812. }
  23813. function findParentScope(parentStack, isVar = false) {
  23814. return parentStack.find(isVar ? isFunction$1 : isBlock);
  23815. }
  23816. function isInDestructuringAssignment(parent, parentStack) {
  23817. if (parent.type === "Property" || parent.type === "ArrayPattern") {
  23818. return parentStack.some((i) => i.type === "AssignmentExpression");
  23819. }
  23820. return false;
  23821. }
  23822. let isDockerCached;
  23823. function hasDockerEnv() {
  23824. try {
  23825. fs__default.statSync('/.dockerenv');
  23826. return true;
  23827. } catch {
  23828. return false;
  23829. }
  23830. }
  23831. function hasDockerCGroup() {
  23832. try {
  23833. return fs__default.readFileSync('/proc/self/cgroup', 'utf8').includes('docker');
  23834. } catch {
  23835. return false;
  23836. }
  23837. }
  23838. function isDocker() {
  23839. // TODO: Use `??=` when targeting Node.js 16.
  23840. if (isDockerCached === undefined) {
  23841. isDockerCached = hasDockerEnv() || hasDockerCGroup();
  23842. }
  23843. return isDockerCached;
  23844. }
  23845. let cachedResult;
  23846. // Podman detection
  23847. const hasContainerEnv = () => {
  23848. try {
  23849. fs__default.statSync('/run/.containerenv');
  23850. return true;
  23851. } catch {
  23852. return false;
  23853. }
  23854. };
  23855. function isInsideContainer() {
  23856. // TODO: Use `??=` when targeting Node.js 16.
  23857. if (cachedResult === undefined) {
  23858. cachedResult = hasContainerEnv() || isDocker();
  23859. }
  23860. return cachedResult;
  23861. }
  23862. const isWsl = () => {
  23863. if (process$1.platform !== 'linux') {
  23864. return false;
  23865. }
  23866. if (os$3.release().toLowerCase().includes('microsoft')) {
  23867. if (isInsideContainer()) {
  23868. return false;
  23869. }
  23870. return true;
  23871. }
  23872. try {
  23873. return fs__default.readFileSync('/proc/version', 'utf8').toLowerCase().includes('microsoft')
  23874. ? !isInsideContainer() : false;
  23875. } catch {
  23876. return false;
  23877. }
  23878. };
  23879. var isWsl$1 = process$1.env.__IS_WSL_TEST__ ? isWsl : isWsl();
  23880. function defineLazyProperty(object, propertyName, valueGetter) {
  23881. const define = value => Object.defineProperty(object, propertyName, {value, enumerable: true, writable: true});
  23882. Object.defineProperty(object, propertyName, {
  23883. configurable: true,
  23884. enumerable: true,
  23885. get() {
  23886. const result = valueGetter();
  23887. define(result);
  23888. return result;
  23889. },
  23890. set(value) {
  23891. define(value);
  23892. }
  23893. });
  23894. return object;
  23895. }
  23896. const execFileAsync$3 = promisify$4(execFile);
  23897. async function defaultBrowserId() {
  23898. if (process$1.platform !== 'darwin') {
  23899. throw new Error('macOS only');
  23900. }
  23901. const {stdout} = await execFileAsync$3('defaults', ['read', 'com.apple.LaunchServices/com.apple.launchservices.secure', 'LSHandlers']);
  23902. // `(?!-)` is to prevent matching `LSHandlerRoleAll = "-";`.
  23903. const match = /LSHandlerRoleAll = "(?!-)(?<id>[^"]+?)";\s+?LSHandlerURLScheme = (?:http|https);/.exec(stdout);
  23904. return match?.groups.id ?? 'com.apple.Safari';
  23905. }
  23906. const execFileAsync$2 = promisify$4(execFile);
  23907. async function runAppleScript(script, {humanReadableOutput = true} = {}) {
  23908. if (process$1.platform !== 'darwin') {
  23909. throw new Error('macOS only');
  23910. }
  23911. const outputArguments = humanReadableOutput ? [] : ['-ss'];
  23912. const {stdout} = await execFileAsync$2('osascript', ['-e', script, outputArguments]);
  23913. return stdout.trim();
  23914. }
  23915. async function bundleName(bundleId) {
  23916. 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")`);
  23917. }
  23918. const execFileAsync$1 = promisify$4(execFile);
  23919. // Windows doesn't have browser IDs in the same way macOS/Linux does so we give fake
  23920. // ones that look real and match the macOS/Linux versions for cross-platform apps.
  23921. const windowsBrowserProgIds = {
  23922. AppXq0fevzme2pys62n3e0fbqa7peapykr8v: {name: 'Edge', id: 'com.microsoft.edge.old'},
  23923. MSEdgeDHTML: {name: 'Edge', id: 'com.microsoft.edge'}, // On macOS, it's "com.microsoft.edgemac"
  23924. MSEdgeHTM: {name: 'Edge', id: 'com.microsoft.edge'}, // Newer Edge/Win10 releases
  23925. 'IE.HTTP': {name: 'Internet Explorer', id: 'com.microsoft.ie'},
  23926. FirefoxURL: {name: 'Firefox', id: 'org.mozilla.firefox'},
  23927. ChromeHTML: {name: 'Chrome', id: 'com.google.chrome'},
  23928. BraveHTML: {name: 'Brave', id: 'com.brave.Browser'},
  23929. BraveBHTML: {name: 'Brave Beta', id: 'com.brave.Browser.beta'},
  23930. BraveSSHTM: {name: 'Brave Nightly', id: 'com.brave.Browser.nightly'},
  23931. };
  23932. class UnknownBrowserError extends Error {}
  23933. async function defaultBrowser$1(_execFileAsync = execFileAsync$1) {
  23934. const {stdout} = await _execFileAsync('reg', [
  23935. 'QUERY',
  23936. ' HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http\\UserChoice',
  23937. '/v',
  23938. 'ProgId',
  23939. ]);
  23940. const match = /ProgId\s*REG_SZ\s*(?<id>\S+)/.exec(stdout);
  23941. if (!match) {
  23942. throw new UnknownBrowserError(`Cannot find Windows browser in stdout: ${JSON.stringify(stdout)}`);
  23943. }
  23944. const {id} = match.groups;
  23945. const browser = windowsBrowserProgIds[id];
  23946. if (!browser) {
  23947. throw new UnknownBrowserError(`Unknown browser ID: ${id}`);
  23948. }
  23949. return browser;
  23950. }
  23951. const execFileAsync = promisify$4(execFile);
  23952. // Inlined: https://github.com/sindresorhus/titleize/blob/main/index.js
  23953. const titleize = string => string.toLowerCase().replaceAll(/(?:^|\s|-)\S/g, x => x.toUpperCase());
  23954. async function defaultBrowser() {
  23955. if (process$1.platform === 'darwin') {
  23956. const id = await defaultBrowserId();
  23957. const name = await bundleName(id);
  23958. return {name, id};
  23959. }
  23960. if (process$1.platform === 'linux') {
  23961. const {stdout} = await execFileAsync('xdg-mime', ['query', 'default', 'x-scheme-handler/http']);
  23962. const id = stdout.trim();
  23963. const name = titleize(id.replace(/.desktop$/, '').replace('-', ' '));
  23964. return {name, id};
  23965. }
  23966. if (process$1.platform === 'win32') {
  23967. return defaultBrowser$1();
  23968. }
  23969. throw new Error('Only macOS, Linux, and Windows are supported');
  23970. }
  23971. // Path to included `xdg-open`.
  23972. const __dirname = path$b.dirname(fileURLToPath$1(import.meta.url));
  23973. const localXdgOpenPath = path$b.join(__dirname, 'xdg-open');
  23974. const {platform, arch} = process$1;
  23975. /**
  23976. Get the mount point for fixed drives in WSL.
  23977. @inner
  23978. @returns {string} The mount point.
  23979. */
  23980. const getWslDrivesMountPoint = (() => {
  23981. // Default value for "root" param
  23982. // according to https://docs.microsoft.com/en-us/windows/wsl/wsl-config
  23983. const defaultMountPoint = '/mnt/';
  23984. let mountPoint;
  23985. return async function () {
  23986. if (mountPoint) {
  23987. // Return memoized mount point value
  23988. return mountPoint;
  23989. }
  23990. const configFilePath = '/etc/wsl.conf';
  23991. let isConfigFileExists = false;
  23992. try {
  23993. await fsp.access(configFilePath, constants$3.F_OK);
  23994. isConfigFileExists = true;
  23995. } catch {}
  23996. if (!isConfigFileExists) {
  23997. return defaultMountPoint;
  23998. }
  23999. const configContent = await fsp.readFile(configFilePath, {encoding: 'utf8'});
  24000. const configMountPoint = /(?<!#.*)root\s*=\s*(?<mountPoint>.*)/g.exec(configContent);
  24001. if (!configMountPoint) {
  24002. return defaultMountPoint;
  24003. }
  24004. mountPoint = configMountPoint.groups.mountPoint.trim();
  24005. mountPoint = mountPoint.endsWith('/') ? mountPoint : `${mountPoint}/`;
  24006. return mountPoint;
  24007. };
  24008. })();
  24009. const pTryEach = async (array, mapper) => {
  24010. let latestError;
  24011. for (const item of array) {
  24012. try {
  24013. return await mapper(item); // eslint-disable-line no-await-in-loop
  24014. } catch (error) {
  24015. latestError = error;
  24016. }
  24017. }
  24018. throw latestError;
  24019. };
  24020. const baseOpen = async options => {
  24021. options = {
  24022. wait: false,
  24023. background: false,
  24024. newInstance: false,
  24025. allowNonzeroExitCode: false,
  24026. ...options,
  24027. };
  24028. if (Array.isArray(options.app)) {
  24029. return pTryEach(options.app, singleApp => baseOpen({
  24030. ...options,
  24031. app: singleApp,
  24032. }));
  24033. }
  24034. let {name: app, arguments: appArguments = []} = options.app ?? {};
  24035. appArguments = [...appArguments];
  24036. if (Array.isArray(app)) {
  24037. return pTryEach(app, appName => baseOpen({
  24038. ...options,
  24039. app: {
  24040. name: appName,
  24041. arguments: appArguments,
  24042. },
  24043. }));
  24044. }
  24045. if (app === 'browser' || app === 'browserPrivate') {
  24046. // IDs from default-browser for macOS and windows are the same
  24047. const ids = {
  24048. 'com.google.chrome': 'chrome',
  24049. 'google-chrome.desktop': 'chrome',
  24050. 'org.mozilla.firefox': 'firefox',
  24051. 'firefox.desktop': 'firefox',
  24052. 'com.microsoft.msedge': 'edge',
  24053. 'com.microsoft.edge': 'edge',
  24054. 'com.microsoft.edgemac': 'edge',
  24055. 'microsoft-edge.desktop': 'edge',
  24056. };
  24057. // Incognito flags for each browser in `apps`.
  24058. const flags = {
  24059. chrome: '--incognito',
  24060. firefox: '--private-window',
  24061. edge: '--inPrivate',
  24062. };
  24063. const browser = await defaultBrowser();
  24064. if (browser.id in ids) {
  24065. const browserName = ids[browser.id];
  24066. if (app === 'browserPrivate') {
  24067. appArguments.push(flags[browserName]);
  24068. }
  24069. return baseOpen({
  24070. ...options,
  24071. app: {
  24072. name: apps[browserName],
  24073. arguments: appArguments,
  24074. },
  24075. });
  24076. }
  24077. throw new Error(`${browser.name} is not supported as a default browser`);
  24078. }
  24079. let command;
  24080. const cliArguments = [];
  24081. const childProcessOptions = {};
  24082. if (platform === 'darwin') {
  24083. command = 'open';
  24084. if (options.wait) {
  24085. cliArguments.push('--wait-apps');
  24086. }
  24087. if (options.background) {
  24088. cliArguments.push('--background');
  24089. }
  24090. if (options.newInstance) {
  24091. cliArguments.push('--new');
  24092. }
  24093. if (app) {
  24094. cliArguments.push('-a', app);
  24095. }
  24096. } else if (platform === 'win32' || (isWsl$1 && !isInsideContainer() && !app)) {
  24097. const mountPoint = await getWslDrivesMountPoint();
  24098. command = isWsl$1
  24099. ? `${mountPoint}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`
  24100. : `${process$1.env.SYSTEMROOT || process$1.env.windir || 'C:\\Windows'}\\System32\\WindowsPowerShell\\v1.0\\powershell`;
  24101. cliArguments.push(
  24102. '-NoProfile',
  24103. '-NonInteractive',
  24104. '-ExecutionPolicy',
  24105. 'Bypass',
  24106. '-EncodedCommand',
  24107. );
  24108. if (!isWsl$1) {
  24109. childProcessOptions.windowsVerbatimArguments = true;
  24110. }
  24111. const encodedArguments = ['Start'];
  24112. if (options.wait) {
  24113. encodedArguments.push('-Wait');
  24114. }
  24115. if (app) {
  24116. // Double quote with double quotes to ensure the inner quotes are passed through.
  24117. // Inner quotes are delimited for PowerShell interpretation with backticks.
  24118. encodedArguments.push(`"\`"${app}\`""`);
  24119. if (options.target) {
  24120. appArguments.push(options.target);
  24121. }
  24122. } else if (options.target) {
  24123. encodedArguments.push(`"${options.target}"`);
  24124. }
  24125. if (appArguments.length > 0) {
  24126. appArguments = appArguments.map(argument => `"\`"${argument}\`""`);
  24127. encodedArguments.push('-ArgumentList', appArguments.join(','));
  24128. }
  24129. // Using Base64-encoded command, accepted by PowerShell, to allow special characters.
  24130. options.target = Buffer$1.from(encodedArguments.join(' '), 'utf16le').toString('base64');
  24131. } else {
  24132. if (app) {
  24133. command = app;
  24134. } else {
  24135. // When bundled by Webpack, there's no actual package file path and no local `xdg-open`.
  24136. const isBundled = !__dirname || __dirname === '/';
  24137. // Check if local `xdg-open` exists and is executable.
  24138. let exeLocalXdgOpen = false;
  24139. try {
  24140. await fsp.access(localXdgOpenPath, constants$3.X_OK);
  24141. exeLocalXdgOpen = true;
  24142. } catch {}
  24143. const useSystemXdgOpen = process$1.versions.electron
  24144. ?? (platform === 'android' || isBundled || !exeLocalXdgOpen);
  24145. command = useSystemXdgOpen ? 'xdg-open' : localXdgOpenPath;
  24146. }
  24147. if (appArguments.length > 0) {
  24148. cliArguments.push(...appArguments);
  24149. }
  24150. if (!options.wait) {
  24151. // `xdg-open` will block the process unless stdio is ignored
  24152. // and it's detached from the parent even if it's unref'd.
  24153. childProcessOptions.stdio = 'ignore';
  24154. childProcessOptions.detached = true;
  24155. }
  24156. }
  24157. if (platform === 'darwin' && appArguments.length > 0) {
  24158. cliArguments.push('--args', ...appArguments);
  24159. }
  24160. // This has to come after `--args`.
  24161. if (options.target) {
  24162. cliArguments.push(options.target);
  24163. }
  24164. const subprocess = childProcess$2.spawn(command, cliArguments, childProcessOptions);
  24165. if (options.wait) {
  24166. return new Promise((resolve, reject) => {
  24167. subprocess.once('error', reject);
  24168. subprocess.once('close', exitCode => {
  24169. if (!options.allowNonzeroExitCode && exitCode > 0) {
  24170. reject(new Error(`Exited with code ${exitCode}`));
  24171. return;
  24172. }
  24173. resolve(subprocess);
  24174. });
  24175. });
  24176. }
  24177. subprocess.unref();
  24178. return subprocess;
  24179. };
  24180. const open = (target, options) => {
  24181. if (typeof target !== 'string') {
  24182. throw new TypeError('Expected a `target`');
  24183. }
  24184. return baseOpen({
  24185. ...options,
  24186. target,
  24187. });
  24188. };
  24189. function detectArchBinary(binary) {
  24190. if (typeof binary === 'string' || Array.isArray(binary)) {
  24191. return binary;
  24192. }
  24193. const {[arch]: archBinary} = binary;
  24194. if (!archBinary) {
  24195. throw new Error(`${arch} is not supported`);
  24196. }
  24197. return archBinary;
  24198. }
  24199. function detectPlatformBinary({[platform]: platformBinary}, {wsl}) {
  24200. if (wsl && isWsl$1) {
  24201. return detectArchBinary(wsl);
  24202. }
  24203. if (!platformBinary) {
  24204. throw new Error(`${platform} is not supported`);
  24205. }
  24206. return detectArchBinary(platformBinary);
  24207. }
  24208. const apps = {};
  24209. defineLazyProperty(apps, 'chrome', () => detectPlatformBinary({
  24210. darwin: 'google chrome',
  24211. win32: 'chrome',
  24212. linux: ['google-chrome', 'google-chrome-stable', 'chromium'],
  24213. }, {
  24214. wsl: {
  24215. ia32: '/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe',
  24216. x64: ['/mnt/c/Program Files/Google/Chrome/Application/chrome.exe', '/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe'],
  24217. },
  24218. }));
  24219. defineLazyProperty(apps, 'firefox', () => detectPlatformBinary({
  24220. darwin: 'firefox',
  24221. win32: 'C:\\Program Files\\Mozilla Firefox\\firefox.exe',
  24222. linux: 'firefox',
  24223. }, {
  24224. wsl: '/mnt/c/Program Files/Mozilla Firefox/firefox.exe',
  24225. }));
  24226. defineLazyProperty(apps, 'edge', () => detectPlatformBinary({
  24227. darwin: 'microsoft edge',
  24228. win32: 'msedge',
  24229. linux: ['microsoft-edge', 'microsoft-edge-dev'],
  24230. }, {
  24231. wsl: '/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe',
  24232. }));
  24233. defineLazyProperty(apps, 'browser', () => 'browser');
  24234. defineLazyProperty(apps, 'browserPrivate', () => 'browserPrivate');
  24235. var crossSpawn = {exports: {}};
  24236. var windows;
  24237. var hasRequiredWindows;
  24238. function requireWindows () {
  24239. if (hasRequiredWindows) return windows;
  24240. hasRequiredWindows = 1;
  24241. windows = isexe;
  24242. isexe.sync = sync;
  24243. var fs = require$$0$4;
  24244. function checkPathExt (path, options) {
  24245. var pathext = options.pathExt !== undefined ?
  24246. options.pathExt : process.env.PATHEXT;
  24247. if (!pathext) {
  24248. return true
  24249. }
  24250. pathext = pathext.split(';');
  24251. if (pathext.indexOf('') !== -1) {
  24252. return true
  24253. }
  24254. for (var i = 0; i < pathext.length; i++) {
  24255. var p = pathext[i].toLowerCase();
  24256. if (p && path.substr(-p.length).toLowerCase() === p) {
  24257. return true
  24258. }
  24259. }
  24260. return false
  24261. }
  24262. function checkStat (stat, path, options) {
  24263. if (!stat.isSymbolicLink() && !stat.isFile()) {
  24264. return false
  24265. }
  24266. return checkPathExt(path, options)
  24267. }
  24268. function isexe (path, options, cb) {
  24269. fs.stat(path, function (er, stat) {
  24270. cb(er, er ? false : checkStat(stat, path, options));
  24271. });
  24272. }
  24273. function sync (path, options) {
  24274. return checkStat(fs.statSync(path), path, options)
  24275. }
  24276. return windows;
  24277. }
  24278. var mode;
  24279. var hasRequiredMode;
  24280. function requireMode () {
  24281. if (hasRequiredMode) return mode;
  24282. hasRequiredMode = 1;
  24283. mode = isexe;
  24284. isexe.sync = sync;
  24285. var fs = require$$0$4;
  24286. function isexe (path, options, cb) {
  24287. fs.stat(path, function (er, stat) {
  24288. cb(er, er ? false : checkStat(stat, options));
  24289. });
  24290. }
  24291. function sync (path, options) {
  24292. return checkStat(fs.statSync(path), options)
  24293. }
  24294. function checkStat (stat, options) {
  24295. return stat.isFile() && checkMode(stat, options)
  24296. }
  24297. function checkMode (stat, options) {
  24298. var mod = stat.mode;
  24299. var uid = stat.uid;
  24300. var gid = stat.gid;
  24301. var myUid = options.uid !== undefined ?
  24302. options.uid : process.getuid && process.getuid();
  24303. var myGid = options.gid !== undefined ?
  24304. options.gid : process.getgid && process.getgid();
  24305. var u = parseInt('100', 8);
  24306. var g = parseInt('010', 8);
  24307. var o = parseInt('001', 8);
  24308. var ug = u | g;
  24309. var ret = (mod & o) ||
  24310. (mod & g) && gid === myGid ||
  24311. (mod & u) && uid === myUid ||
  24312. (mod & ug) && myUid === 0;
  24313. return ret
  24314. }
  24315. return mode;
  24316. }
  24317. var core;
  24318. if (process.platform === 'win32' || commonjsGlobal.TESTING_WINDOWS) {
  24319. core = requireWindows();
  24320. } else {
  24321. core = requireMode();
  24322. }
  24323. var isexe_1 = isexe$1;
  24324. isexe$1.sync = sync;
  24325. function isexe$1 (path, options, cb) {
  24326. if (typeof options === 'function') {
  24327. cb = options;
  24328. options = {};
  24329. }
  24330. if (!cb) {
  24331. if (typeof Promise !== 'function') {
  24332. throw new TypeError('callback not provided')
  24333. }
  24334. return new Promise(function (resolve, reject) {
  24335. isexe$1(path, options || {}, function (er, is) {
  24336. if (er) {
  24337. reject(er);
  24338. } else {
  24339. resolve(is);
  24340. }
  24341. });
  24342. })
  24343. }
  24344. core(path, options || {}, function (er, is) {
  24345. // ignore EACCES because that just means we aren't allowed to run it
  24346. if (er) {
  24347. if (er.code === 'EACCES' || options && options.ignoreErrors) {
  24348. er = null;
  24349. is = false;
  24350. }
  24351. }
  24352. cb(er, is);
  24353. });
  24354. }
  24355. function sync (path, options) {
  24356. // my kingdom for a filtered catch
  24357. try {
  24358. return core.sync(path, options || {})
  24359. } catch (er) {
  24360. if (options && options.ignoreErrors || er.code === 'EACCES') {
  24361. return false
  24362. } else {
  24363. throw er
  24364. }
  24365. }
  24366. }
  24367. const isWindows = process.platform === 'win32' ||
  24368. process.env.OSTYPE === 'cygwin' ||
  24369. process.env.OSTYPE === 'msys';
  24370. const path$2 = require$$0$2;
  24371. const COLON = isWindows ? ';' : ':';
  24372. const isexe = isexe_1;
  24373. const getNotFoundError = (cmd) =>
  24374. Object.assign(new Error(`not found: ${cmd}`), { code: 'ENOENT' });
  24375. const getPathInfo = (cmd, opt) => {
  24376. const colon = opt.colon || COLON;
  24377. // If it has a slash, then we don't bother searching the pathenv.
  24378. // just check the file itself, and that's it.
  24379. const pathEnv = cmd.match(/\//) || isWindows && cmd.match(/\\/) ? ['']
  24380. : (
  24381. [
  24382. // windows always checks the cwd first
  24383. ...(isWindows ? [process.cwd()] : []),
  24384. ...(opt.path || process.env.PATH ||
  24385. /* istanbul ignore next: very unusual */ '').split(colon),
  24386. ]
  24387. );
  24388. const pathExtExe = isWindows
  24389. ? opt.pathExt || process.env.PATHEXT || '.EXE;.CMD;.BAT;.COM'
  24390. : '';
  24391. const pathExt = isWindows ? pathExtExe.split(colon) : [''];
  24392. if (isWindows) {
  24393. if (cmd.indexOf('.') !== -1 && pathExt[0] !== '')
  24394. pathExt.unshift('');
  24395. }
  24396. return {
  24397. pathEnv,
  24398. pathExt,
  24399. pathExtExe,
  24400. }
  24401. };
  24402. const which$1 = (cmd, opt, cb) => {
  24403. if (typeof opt === 'function') {
  24404. cb = opt;
  24405. opt = {};
  24406. }
  24407. if (!opt)
  24408. opt = {};
  24409. const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt);
  24410. const found = [];
  24411. const step = i => new Promise((resolve, reject) => {
  24412. if (i === pathEnv.length)
  24413. return opt.all && found.length ? resolve(found)
  24414. : reject(getNotFoundError(cmd))
  24415. const ppRaw = pathEnv[i];
  24416. const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw;
  24417. const pCmd = path$2.join(pathPart, cmd);
  24418. const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd
  24419. : pCmd;
  24420. resolve(subStep(p, i, 0));
  24421. });
  24422. const subStep = (p, i, ii) => new Promise((resolve, reject) => {
  24423. if (ii === pathExt.length)
  24424. return resolve(step(i + 1))
  24425. const ext = pathExt[ii];
  24426. isexe(p + ext, { pathExt: pathExtExe }, (er, is) => {
  24427. if (!er && is) {
  24428. if (opt.all)
  24429. found.push(p + ext);
  24430. else
  24431. return resolve(p + ext)
  24432. }
  24433. return resolve(subStep(p, i, ii + 1))
  24434. });
  24435. });
  24436. return cb ? step(0).then(res => cb(null, res), cb) : step(0)
  24437. };
  24438. const whichSync = (cmd, opt) => {
  24439. opt = opt || {};
  24440. const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt);
  24441. const found = [];
  24442. for (let i = 0; i < pathEnv.length; i ++) {
  24443. const ppRaw = pathEnv[i];
  24444. const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw;
  24445. const pCmd = path$2.join(pathPart, cmd);
  24446. const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd
  24447. : pCmd;
  24448. for (let j = 0; j < pathExt.length; j ++) {
  24449. const cur = p + pathExt[j];
  24450. try {
  24451. const is = isexe.sync(cur, { pathExt: pathExtExe });
  24452. if (is) {
  24453. if (opt.all)
  24454. found.push(cur);
  24455. else
  24456. return cur
  24457. }
  24458. } catch (ex) {}
  24459. }
  24460. }
  24461. if (opt.all && found.length)
  24462. return found
  24463. if (opt.nothrow)
  24464. return null
  24465. throw getNotFoundError(cmd)
  24466. };
  24467. var which_1 = which$1;
  24468. which$1.sync = whichSync;
  24469. var pathKey$1 = {exports: {}};
  24470. const pathKey = (options = {}) => {
  24471. const environment = options.env || process.env;
  24472. const platform = options.platform || process.platform;
  24473. if (platform !== 'win32') {
  24474. return 'PATH';
  24475. }
  24476. return Object.keys(environment).reverse().find(key => key.toUpperCase() === 'PATH') || 'Path';
  24477. };
  24478. pathKey$1.exports = pathKey;
  24479. // TODO: Remove this for the next major release
  24480. pathKey$1.exports.default = pathKey;
  24481. var pathKeyExports = pathKey$1.exports;
  24482. const path$1 = require$$0$2;
  24483. const which = which_1;
  24484. const getPathKey = pathKeyExports;
  24485. function resolveCommandAttempt(parsed, withoutPathExt) {
  24486. const env = parsed.options.env || process.env;
  24487. const cwd = process.cwd();
  24488. const hasCustomCwd = parsed.options.cwd != null;
  24489. // Worker threads do not have process.chdir()
  24490. const shouldSwitchCwd = hasCustomCwd && process.chdir !== undefined && !process.chdir.disabled;
  24491. // If a custom `cwd` was specified, we need to change the process cwd
  24492. // because `which` will do stat calls but does not support a custom cwd
  24493. if (shouldSwitchCwd) {
  24494. try {
  24495. process.chdir(parsed.options.cwd);
  24496. } catch (err) {
  24497. /* Empty */
  24498. }
  24499. }
  24500. let resolved;
  24501. try {
  24502. resolved = which.sync(parsed.command, {
  24503. path: env[getPathKey({ env })],
  24504. pathExt: withoutPathExt ? path$1.delimiter : undefined,
  24505. });
  24506. } catch (e) {
  24507. /* Empty */
  24508. } finally {
  24509. if (shouldSwitchCwd) {
  24510. process.chdir(cwd);
  24511. }
  24512. }
  24513. // If we successfully resolved, ensure that an absolute path is returned
  24514. // Note that when a custom `cwd` was used, we need to resolve to an absolute path based on it
  24515. if (resolved) {
  24516. resolved = path$1.resolve(hasCustomCwd ? parsed.options.cwd : '', resolved);
  24517. }
  24518. return resolved;
  24519. }
  24520. function resolveCommand$1(parsed) {
  24521. return resolveCommandAttempt(parsed) || resolveCommandAttempt(parsed, true);
  24522. }
  24523. var resolveCommand_1 = resolveCommand$1;
  24524. var _escape = {};
  24525. // See http://www.robvanderwoude.com/escapechars.php
  24526. const metaCharsRegExp = /([()\][%!^"`<>&|;, *?])/g;
  24527. function escapeCommand(arg) {
  24528. // Escape meta chars
  24529. arg = arg.replace(metaCharsRegExp, '^$1');
  24530. return arg;
  24531. }
  24532. function escapeArgument(arg, doubleEscapeMetaChars) {
  24533. // Convert to string
  24534. arg = `${arg}`;
  24535. // Algorithm below is based on https://qntm.org/cmd
  24536. // It's slightly altered to disable JS backtracking to avoid hanging on specially crafted input
  24537. // Please see https://github.com/moxystudio/node-cross-spawn/pull/160 for more information
  24538. // Sequence of backslashes followed by a double quote:
  24539. // double up all the backslashes and escape the double quote
  24540. arg = arg.replace(/(?=(\\+?)?)\1"/g, '$1$1\\"');
  24541. // Sequence of backslashes followed by the end of the string
  24542. // (which will become a double quote later):
  24543. // double up all the backslashes
  24544. arg = arg.replace(/(?=(\\+?)?)\1$/, '$1$1');
  24545. // All other backslashes occur literally
  24546. // Quote the whole thing:
  24547. arg = `"${arg}"`;
  24548. // Escape meta chars
  24549. arg = arg.replace(metaCharsRegExp, '^$1');
  24550. // Double escape meta chars if necessary
  24551. if (doubleEscapeMetaChars) {
  24552. arg = arg.replace(metaCharsRegExp, '^$1');
  24553. }
  24554. return arg;
  24555. }
  24556. _escape.command = escapeCommand;
  24557. _escape.argument = escapeArgument;
  24558. var shebangRegex$1 = /^#!(.*)/;
  24559. const shebangRegex = shebangRegex$1;
  24560. var shebangCommand$1 = (string = '') => {
  24561. const match = string.match(shebangRegex);
  24562. if (!match) {
  24563. return null;
  24564. }
  24565. const [path, argument] = match[0].replace(/#! ?/, '').split(' ');
  24566. const binary = path.split('/').pop();
  24567. if (binary === 'env') {
  24568. return argument;
  24569. }
  24570. return argument ? `${binary} ${argument}` : binary;
  24571. };
  24572. const fs = require$$0$4;
  24573. const shebangCommand = shebangCommand$1;
  24574. function readShebang$1(command) {
  24575. // Read the first 150 bytes from the file
  24576. const size = 150;
  24577. const buffer = Buffer.alloc(size);
  24578. let fd;
  24579. try {
  24580. fd = fs.openSync(command, 'r');
  24581. fs.readSync(fd, buffer, 0, size, 0);
  24582. fs.closeSync(fd);
  24583. } catch (e) { /* Empty */ }
  24584. // Attempt to extract shebang (null is returned if not a shebang)
  24585. return shebangCommand(buffer.toString());
  24586. }
  24587. var readShebang_1 = readShebang$1;
  24588. const path = require$$0$2;
  24589. const resolveCommand = resolveCommand_1;
  24590. const escape$1 = _escape;
  24591. const readShebang = readShebang_1;
  24592. const isWin$1 = process.platform === 'win32';
  24593. const isExecutableRegExp = /\.(?:com|exe)$/i;
  24594. const isCmdShimRegExp = /node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;
  24595. function detectShebang(parsed) {
  24596. parsed.file = resolveCommand(parsed);
  24597. const shebang = parsed.file && readShebang(parsed.file);
  24598. if (shebang) {
  24599. parsed.args.unshift(parsed.file);
  24600. parsed.command = shebang;
  24601. return resolveCommand(parsed);
  24602. }
  24603. return parsed.file;
  24604. }
  24605. function parseNonShell(parsed) {
  24606. if (!isWin$1) {
  24607. return parsed;
  24608. }
  24609. // Detect & add support for shebangs
  24610. const commandFile = detectShebang(parsed);
  24611. // We don't need a shell if the command filename is an executable
  24612. const needsShell = !isExecutableRegExp.test(commandFile);
  24613. // If a shell is required, use cmd.exe and take care of escaping everything correctly
  24614. // Note that `forceShell` is an hidden option used only in tests
  24615. if (parsed.options.forceShell || needsShell) {
  24616. // Need to double escape meta chars if the command is a cmd-shim located in `node_modules/.bin/`
  24617. // The cmd-shim simply calls execute the package bin file with NodeJS, proxying any argument
  24618. // Because the escape of metachars with ^ gets interpreted when the cmd.exe is first called,
  24619. // we need to double escape them
  24620. const needsDoubleEscapeMetaChars = isCmdShimRegExp.test(commandFile);
  24621. // Normalize posix paths into OS compatible paths (e.g.: foo/bar -> foo\bar)
  24622. // This is necessary otherwise it will always fail with ENOENT in those cases
  24623. parsed.command = path.normalize(parsed.command);
  24624. // Escape command & arguments
  24625. parsed.command = escape$1.command(parsed.command);
  24626. parsed.args = parsed.args.map((arg) => escape$1.argument(arg, needsDoubleEscapeMetaChars));
  24627. const shellCommand = [parsed.command].concat(parsed.args).join(' ');
  24628. parsed.args = ['/d', '/s', '/c', `"${shellCommand}"`];
  24629. parsed.command = process.env.comspec || 'cmd.exe';
  24630. parsed.options.windowsVerbatimArguments = true; // Tell node's spawn that the arguments are already escaped
  24631. }
  24632. return parsed;
  24633. }
  24634. function parse$5(command, args, options) {
  24635. // Normalize arguments, similar to nodejs
  24636. if (args && !Array.isArray(args)) {
  24637. options = args;
  24638. args = null;
  24639. }
  24640. args = args ? args.slice(0) : []; // Clone array to avoid changing the original
  24641. options = Object.assign({}, options); // Clone object to avoid changing the original
  24642. // Build our parsed object
  24643. const parsed = {
  24644. command,
  24645. args,
  24646. options,
  24647. file: undefined,
  24648. original: {
  24649. command,
  24650. args,
  24651. },
  24652. };
  24653. // Delegate further parsing to shell or non-shell
  24654. return options.shell ? parsed : parseNonShell(parsed);
  24655. }
  24656. var parse_1 = parse$5;
  24657. const isWin = process.platform === 'win32';
  24658. function notFoundError(original, syscall) {
  24659. return Object.assign(new Error(`${syscall} ${original.command} ENOENT`), {
  24660. code: 'ENOENT',
  24661. errno: 'ENOENT',
  24662. syscall: `${syscall} ${original.command}`,
  24663. path: original.command,
  24664. spawnargs: original.args,
  24665. });
  24666. }
  24667. function hookChildProcess(cp, parsed) {
  24668. if (!isWin) {
  24669. return;
  24670. }
  24671. const originalEmit = cp.emit;
  24672. cp.emit = function (name, arg1) {
  24673. // If emitting "exit" event and exit code is 1, we need to check if
  24674. // the command exists and emit an "error" instead
  24675. // See https://github.com/IndigoUnited/node-cross-spawn/issues/16
  24676. if (name === 'exit') {
  24677. const err = verifyENOENT(arg1, parsed);
  24678. if (err) {
  24679. return originalEmit.call(cp, 'error', err);
  24680. }
  24681. }
  24682. return originalEmit.apply(cp, arguments); // eslint-disable-line prefer-rest-params
  24683. };
  24684. }
  24685. function verifyENOENT(status, parsed) {
  24686. if (isWin && status === 1 && !parsed.file) {
  24687. return notFoundError(parsed.original, 'spawn');
  24688. }
  24689. return null;
  24690. }
  24691. function verifyENOENTSync(status, parsed) {
  24692. if (isWin && status === 1 && !parsed.file) {
  24693. return notFoundError(parsed.original, 'spawnSync');
  24694. }
  24695. return null;
  24696. }
  24697. var enoent$1 = {
  24698. hookChildProcess,
  24699. verifyENOENT,
  24700. verifyENOENTSync,
  24701. notFoundError,
  24702. };
  24703. const cp = require$$2$1;
  24704. const parse$4 = parse_1;
  24705. const enoent = enoent$1;
  24706. function spawn(command, args, options) {
  24707. // Parse the arguments
  24708. const parsed = parse$4(command, args, options);
  24709. // Spawn the child process
  24710. const spawned = cp.spawn(parsed.command, parsed.args, parsed.options);
  24711. // Hook into child process "exit" event to emit an error if the command
  24712. // does not exists, see: https://github.com/IndigoUnited/node-cross-spawn/issues/16
  24713. enoent.hookChildProcess(spawned, parsed);
  24714. return spawned;
  24715. }
  24716. function spawnSync(command, args, options) {
  24717. // Parse the arguments
  24718. const parsed = parse$4(command, args, options);
  24719. // Spawn the child process
  24720. const result = cp.spawnSync(parsed.command, parsed.args, parsed.options);
  24721. // Analyze if the command does not exist, see: https://github.com/IndigoUnited/node-cross-spawn/issues/16
  24722. result.error = result.error || enoent.verifyENOENTSync(result.status, parsed);
  24723. return result;
  24724. }
  24725. crossSpawn.exports = spawn;
  24726. crossSpawn.exports.spawn = spawn;
  24727. crossSpawn.exports.sync = spawnSync;
  24728. crossSpawn.exports._parse = parse$4;
  24729. crossSpawn.exports._enoent = enoent;
  24730. var crossSpawnExports = crossSpawn.exports;
  24731. var spawn$1 = /*@__PURE__*/getDefaultExportFromCjs(crossSpawnExports);
  24732. function openBrowser(url, opt, logger) {
  24733. const browser = process.env.BROWSER || "";
  24734. if (browser.toLowerCase().endsWith(".js")) {
  24735. executeNodeScript(browser, url, logger);
  24736. } else if (browser.toLowerCase() !== "none") {
  24737. const browserArgs = process.env.BROWSER_ARGS ? process.env.BROWSER_ARGS.split(" ") : [];
  24738. startBrowserProcess(browser, browserArgs, url, logger);
  24739. }
  24740. }
  24741. function executeNodeScript(scriptPath, url, logger) {
  24742. const extraArgs = process.argv.slice(2);
  24743. const child = spawn$1(process.execPath, [scriptPath, ...extraArgs, url], {
  24744. stdio: "inherit"
  24745. });
  24746. child.on("close", (code) => {
  24747. if (code !== 0) {
  24748. logger.error(
  24749. colors$1.red(
  24750. `
  24751. The script specified as BROWSER environment variable failed.
  24752. ${colors$1.cyan(
  24753. scriptPath
  24754. )} exited with code ${code}.`
  24755. ),
  24756. { error: null }
  24757. );
  24758. }
  24759. });
  24760. }
  24761. const supportedChromiumBrowsers = [
  24762. "Google Chrome Canary",
  24763. "Google Chrome Dev",
  24764. "Google Chrome Beta",
  24765. "Google Chrome",
  24766. "Microsoft Edge",
  24767. "Brave Browser",
  24768. "Vivaldi",
  24769. "Chromium"
  24770. ];
  24771. async function startBrowserProcess(browser, browserArgs, url, logger) {
  24772. const preferredOSXBrowser = browser === "google chrome" ? "Google Chrome" : browser;
  24773. const shouldTryOpenChromeWithAppleScript = process.platform === "darwin" && (!preferredOSXBrowser || supportedChromiumBrowsers.includes(preferredOSXBrowser));
  24774. if (shouldTryOpenChromeWithAppleScript) {
  24775. try {
  24776. const ps = await execAsync("ps cax");
  24777. const openedBrowser = preferredOSXBrowser && ps.includes(preferredOSXBrowser) ? preferredOSXBrowser : supportedChromiumBrowsers.find((b) => ps.includes(b));
  24778. if (openedBrowser) {
  24779. await execAsync(
  24780. `osascript openChrome.applescript "${url}" "${openedBrowser}"`,
  24781. {
  24782. cwd: join$1(VITE_PACKAGE_DIR, "bin")
  24783. }
  24784. );
  24785. return true;
  24786. }
  24787. } catch {
  24788. }
  24789. }
  24790. if (process.platform === "darwin" && browser === "open") {
  24791. browser = void 0;
  24792. }
  24793. try {
  24794. const options = browser ? { app: { name: browser, arguments: browserArgs } } : {};
  24795. new Promise((_, reject) => {
  24796. open(url, options).then((subprocess) => {
  24797. subprocess.on("error", reject);
  24798. }).catch(reject);
  24799. }).catch((err) => {
  24800. logger.error(err.stack || err.message);
  24801. });
  24802. return true;
  24803. } catch {
  24804. return false;
  24805. }
  24806. }
  24807. function execAsync(command, options) {
  24808. return new Promise((resolve, reject) => {
  24809. exec(command, options, (error, stdout) => {
  24810. if (error) {
  24811. reject(error);
  24812. } else {
  24813. resolve(stdout.toString());
  24814. }
  24815. });
  24816. });
  24817. }
  24818. function bindCLIShortcuts(server, opts) {
  24819. if (!server.httpServer || !process.stdin.isTTY || process.env.CI) {
  24820. return;
  24821. }
  24822. const isDev = isDevServer(server);
  24823. if (isDev) {
  24824. server._shortcutsOptions = opts;
  24825. }
  24826. if (opts?.print) {
  24827. server.config.logger.info(
  24828. colors$1.dim(colors$1.green(" \u279C")) + colors$1.dim(" press ") + colors$1.bold("h + enter") + colors$1.dim(" to show help")
  24829. );
  24830. }
  24831. const shortcuts = (opts?.customShortcuts ?? []).concat(
  24832. isDev ? BASE_DEV_SHORTCUTS : BASE_PREVIEW_SHORTCUTS
  24833. );
  24834. let actionRunning = false;
  24835. const onInput = async (input) => {
  24836. if (actionRunning) return;
  24837. if (input === "h") {
  24838. const loggedKeys = /* @__PURE__ */ new Set();
  24839. server.config.logger.info("\n Shortcuts");
  24840. for (const shortcut2 of shortcuts) {
  24841. if (loggedKeys.has(shortcut2.key)) continue;
  24842. loggedKeys.add(shortcut2.key);
  24843. if (shortcut2.action == null) continue;
  24844. server.config.logger.info(
  24845. colors$1.dim(" press ") + colors$1.bold(`${shortcut2.key} + enter`) + colors$1.dim(` to ${shortcut2.description}`)
  24846. );
  24847. }
  24848. return;
  24849. }
  24850. const shortcut = shortcuts.find((shortcut2) => shortcut2.key === input);
  24851. if (!shortcut || shortcut.action == null) return;
  24852. actionRunning = true;
  24853. await shortcut.action(server);
  24854. actionRunning = false;
  24855. };
  24856. const rl = readline.createInterface({ input: process.stdin });
  24857. rl.on("line", onInput);
  24858. server.httpServer.on("close", () => rl.close());
  24859. }
  24860. const BASE_DEV_SHORTCUTS = [
  24861. {
  24862. key: "r",
  24863. description: "restart the server",
  24864. async action(server) {
  24865. await restartServerWithUrls(server);
  24866. }
  24867. },
  24868. {
  24869. key: "u",
  24870. description: "show server url",
  24871. action(server) {
  24872. server.config.logger.info("");
  24873. server.printUrls();
  24874. }
  24875. },
  24876. {
  24877. key: "o",
  24878. description: "open in browser",
  24879. action(server) {
  24880. server.openBrowser();
  24881. }
  24882. },
  24883. {
  24884. key: "c",
  24885. description: "clear console",
  24886. action(server) {
  24887. server.config.logger.clearScreen("error");
  24888. }
  24889. },
  24890. {
  24891. key: "q",
  24892. description: "quit",
  24893. async action(server) {
  24894. try {
  24895. await server.close();
  24896. } finally {
  24897. process.exit();
  24898. }
  24899. }
  24900. }
  24901. ];
  24902. const BASE_PREVIEW_SHORTCUTS = [
  24903. {
  24904. key: "o",
  24905. description: "open in browser",
  24906. action(server) {
  24907. const url = server.resolvedUrls?.local[0] ?? server.resolvedUrls?.network[0];
  24908. if (url) {
  24909. openBrowser(url, true, server.config.logger);
  24910. } else {
  24911. server.config.logger.warn("No URL available to open in browser");
  24912. }
  24913. }
  24914. },
  24915. {
  24916. key: "q",
  24917. description: "quit",
  24918. async action(server) {
  24919. try {
  24920. await server.close();
  24921. } finally {
  24922. process.exit();
  24923. }
  24924. }
  24925. }
  24926. ];
  24927. function getResolvedOutDirs(root, outDir, outputOptions) {
  24928. const resolvedOutDir = path$b.resolve(root, outDir);
  24929. if (!outputOptions) return /* @__PURE__ */ new Set([resolvedOutDir]);
  24930. return new Set(
  24931. arraify(outputOptions).map(
  24932. ({ dir }) => dir ? path$b.resolve(root, dir) : resolvedOutDir
  24933. )
  24934. );
  24935. }
  24936. function resolveEmptyOutDir(emptyOutDir, root, outDirs, logger) {
  24937. if (emptyOutDir != null) return emptyOutDir;
  24938. for (const outDir of outDirs) {
  24939. if (!normalizePath$3(outDir).startsWith(withTrailingSlash(root))) {
  24940. logger?.warn(
  24941. colors$1.yellow(
  24942. `
  24943. ${colors$1.bold(`(!)`)} outDir ${colors$1.white(
  24944. colors$1.dim(outDir)
  24945. )} is not inside project root and will not be emptied.
  24946. Use --emptyOutDir to override.
  24947. `
  24948. )
  24949. );
  24950. return false;
  24951. }
  24952. }
  24953. return true;
  24954. }
  24955. function resolveChokidarOptions(options, resolvedOutDirs, emptyOutDir, cacheDir) {
  24956. const { ignored: ignoredList, ...otherOptions } = options ?? {};
  24957. const ignored = [
  24958. "**/.git/**",
  24959. "**/node_modules/**",
  24960. "**/test-results/**",
  24961. // Playwright
  24962. escapePath(cacheDir) + "/**",
  24963. ...arraify(ignoredList || [])
  24964. ];
  24965. if (emptyOutDir) {
  24966. ignored.push(
  24967. ...[...resolvedOutDirs].map((outDir) => escapePath(outDir) + "/**")
  24968. );
  24969. }
  24970. const resolvedWatchOptions = {
  24971. ignored,
  24972. ignoreInitial: true,
  24973. ignorePermissionErrors: true,
  24974. ...otherOptions
  24975. };
  24976. return resolvedWatchOptions;
  24977. }
  24978. class NoopWatcher extends EventEmitter$4 {
  24979. constructor(options) {
  24980. super();
  24981. this.options = options;
  24982. }
  24983. add() {
  24984. return this;
  24985. }
  24986. unwatch() {
  24987. return this;
  24988. }
  24989. getWatched() {
  24990. return {};
  24991. }
  24992. ref() {
  24993. return this;
  24994. }
  24995. unref() {
  24996. return this;
  24997. }
  24998. async close() {
  24999. }
  25000. }
  25001. function createNoopWatcher(options) {
  25002. return new NoopWatcher(options);
  25003. }
  25004. var bufferUtil$1 = {exports: {}};
  25005. const BINARY_TYPES$2 = ['nodebuffer', 'arraybuffer', 'fragments'];
  25006. const hasBlob$1 = typeof Blob !== 'undefined';
  25007. if (hasBlob$1) BINARY_TYPES$2.push('blob');
  25008. var constants = {
  25009. BINARY_TYPES: BINARY_TYPES$2,
  25010. EMPTY_BUFFER: Buffer.alloc(0),
  25011. GUID: '258EAFA5-E914-47DA-95CA-C5AB0DC85B11',
  25012. hasBlob: hasBlob$1,
  25013. kForOnEventAttribute: Symbol('kIsForOnEventAttribute'),
  25014. kListener: Symbol('kListener'),
  25015. kStatusCode: Symbol('status-code'),
  25016. kWebSocket: Symbol('websocket'),
  25017. NOOP: () => {}
  25018. };
  25019. const { EMPTY_BUFFER: EMPTY_BUFFER$3 } = constants;
  25020. const FastBuffer$2 = Buffer[Symbol.species];
  25021. /**
  25022. * Merges an array of buffers into a new buffer.
  25023. *
  25024. * @param {Buffer[]} list The array of buffers to concat
  25025. * @param {Number} totalLength The total length of buffers in the list
  25026. * @return {Buffer} The resulting buffer
  25027. * @public
  25028. */
  25029. function concat$1(list, totalLength) {
  25030. if (list.length === 0) return EMPTY_BUFFER$3;
  25031. if (list.length === 1) return list[0];
  25032. const target = Buffer.allocUnsafe(totalLength);
  25033. let offset = 0;
  25034. for (let i = 0; i < list.length; i++) {
  25035. const buf = list[i];
  25036. target.set(buf, offset);
  25037. offset += buf.length;
  25038. }
  25039. if (offset < totalLength) {
  25040. return new FastBuffer$2(target.buffer, target.byteOffset, offset);
  25041. }
  25042. return target;
  25043. }
  25044. /**
  25045. * Masks a buffer using the given mask.
  25046. *
  25047. * @param {Buffer} source The buffer to mask
  25048. * @param {Buffer} mask The mask to use
  25049. * @param {Buffer} output The buffer where to store the result
  25050. * @param {Number} offset The offset at which to start writing
  25051. * @param {Number} length The number of bytes to mask.
  25052. * @public
  25053. */
  25054. function _mask(source, mask, output, offset, length) {
  25055. for (let i = 0; i < length; i++) {
  25056. output[offset + i] = source[i] ^ mask[i & 3];
  25057. }
  25058. }
  25059. /**
  25060. * Unmasks a buffer using the given mask.
  25061. *
  25062. * @param {Buffer} buffer The buffer to unmask
  25063. * @param {Buffer} mask The mask to use
  25064. * @public
  25065. */
  25066. function _unmask(buffer, mask) {
  25067. for (let i = 0; i < buffer.length; i++) {
  25068. buffer[i] ^= mask[i & 3];
  25069. }
  25070. }
  25071. /**
  25072. * Converts a buffer to an `ArrayBuffer`.
  25073. *
  25074. * @param {Buffer} buf The buffer to convert
  25075. * @return {ArrayBuffer} Converted buffer
  25076. * @public
  25077. */
  25078. function toArrayBuffer$1(buf) {
  25079. if (buf.length === buf.buffer.byteLength) {
  25080. return buf.buffer;
  25081. }
  25082. return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.length);
  25083. }
  25084. /**
  25085. * Converts `data` to a `Buffer`.
  25086. *
  25087. * @param {*} data The data to convert
  25088. * @return {Buffer} The buffer
  25089. * @throws {TypeError}
  25090. * @public
  25091. */
  25092. function toBuffer$2(data) {
  25093. toBuffer$2.readOnly = true;
  25094. if (Buffer.isBuffer(data)) return data;
  25095. let buf;
  25096. if (data instanceof ArrayBuffer) {
  25097. buf = new FastBuffer$2(data);
  25098. } else if (ArrayBuffer.isView(data)) {
  25099. buf = new FastBuffer$2(data.buffer, data.byteOffset, data.byteLength);
  25100. } else {
  25101. buf = Buffer.from(data);
  25102. toBuffer$2.readOnly = false;
  25103. }
  25104. return buf;
  25105. }
  25106. bufferUtil$1.exports = {
  25107. concat: concat$1,
  25108. mask: _mask,
  25109. toArrayBuffer: toArrayBuffer$1,
  25110. toBuffer: toBuffer$2,
  25111. unmask: _unmask
  25112. };
  25113. /* istanbul ignore else */
  25114. if (!process.env.WS_NO_BUFFER_UTIL) {
  25115. try {
  25116. const bufferUtil = require('bufferutil');
  25117. bufferUtil$1.exports.mask = function (source, mask, output, offset, length) {
  25118. if (length < 48) _mask(source, mask, output, offset, length);
  25119. else bufferUtil.mask(source, mask, output, offset, length);
  25120. };
  25121. bufferUtil$1.exports.unmask = function (buffer, mask) {
  25122. if (buffer.length < 32) _unmask(buffer, mask);
  25123. else bufferUtil.unmask(buffer, mask);
  25124. };
  25125. } catch (e) {
  25126. // Continue regardless of the error.
  25127. }
  25128. }
  25129. var bufferUtilExports = bufferUtil$1.exports;
  25130. const kDone = Symbol('kDone');
  25131. const kRun = Symbol('kRun');
  25132. /**
  25133. * A very simple job queue with adjustable concurrency. Adapted from
  25134. * https://github.com/STRML/async-limiter
  25135. */
  25136. let Limiter$1 = class Limiter {
  25137. /**
  25138. * Creates a new `Limiter`.
  25139. *
  25140. * @param {Number} [concurrency=Infinity] The maximum number of jobs allowed
  25141. * to run concurrently
  25142. */
  25143. constructor(concurrency) {
  25144. this[kDone] = () => {
  25145. this.pending--;
  25146. this[kRun]();
  25147. };
  25148. this.concurrency = concurrency || Infinity;
  25149. this.jobs = [];
  25150. this.pending = 0;
  25151. }
  25152. /**
  25153. * Adds a job to the queue.
  25154. *
  25155. * @param {Function} job The job to run
  25156. * @public
  25157. */
  25158. add(job) {
  25159. this.jobs.push(job);
  25160. this[kRun]();
  25161. }
  25162. /**
  25163. * Removes a job from the queue and runs it if possible.
  25164. *
  25165. * @private
  25166. */
  25167. [kRun]() {
  25168. if (this.pending === this.concurrency) return;
  25169. if (this.jobs.length) {
  25170. const job = this.jobs.shift();
  25171. this.pending++;
  25172. job(this[kDone]);
  25173. }
  25174. }
  25175. };
  25176. var limiter = Limiter$1;
  25177. const zlib = zlib$1;
  25178. const bufferUtil = bufferUtilExports;
  25179. const Limiter = limiter;
  25180. const { kStatusCode: kStatusCode$2 } = constants;
  25181. const FastBuffer$1 = Buffer[Symbol.species];
  25182. const TRAILER = Buffer.from([0x00, 0x00, 0xff, 0xff]);
  25183. const kPerMessageDeflate = Symbol('permessage-deflate');
  25184. const kTotalLength = Symbol('total-length');
  25185. const kCallback = Symbol('callback');
  25186. const kBuffers = Symbol('buffers');
  25187. const kError$1 = Symbol('error');
  25188. //
  25189. // We limit zlib concurrency, which prevents severe memory fragmentation
  25190. // as documented in https://github.com/nodejs/node/issues/8871#issuecomment-250915913
  25191. // and https://github.com/websockets/ws/issues/1202
  25192. //
  25193. // Intentionally global; it's the global thread pool that's an issue.
  25194. //
  25195. let zlibLimiter;
  25196. /**
  25197. * permessage-deflate implementation.
  25198. */
  25199. let PerMessageDeflate$4 = class PerMessageDeflate {
  25200. /**
  25201. * Creates a PerMessageDeflate instance.
  25202. *
  25203. * @param {Object} [options] Configuration options
  25204. * @param {(Boolean|Number)} [options.clientMaxWindowBits] Advertise support
  25205. * for, or request, a custom client window size
  25206. * @param {Boolean} [options.clientNoContextTakeover=false] Advertise/
  25207. * acknowledge disabling of client context takeover
  25208. * @param {Number} [options.concurrencyLimit=10] The number of concurrent
  25209. * calls to zlib
  25210. * @param {(Boolean|Number)} [options.serverMaxWindowBits] Request/confirm the
  25211. * use of a custom server window size
  25212. * @param {Boolean} [options.serverNoContextTakeover=false] Request/accept
  25213. * disabling of server context takeover
  25214. * @param {Number} [options.threshold=1024] Size (in bytes) below which
  25215. * messages should not be compressed if context takeover is disabled
  25216. * @param {Object} [options.zlibDeflateOptions] Options to pass to zlib on
  25217. * deflate
  25218. * @param {Object} [options.zlibInflateOptions] Options to pass to zlib on
  25219. * inflate
  25220. * @param {Boolean} [isServer=false] Create the instance in either server or
  25221. * client mode
  25222. * @param {Number} [maxPayload=0] The maximum allowed message length
  25223. */
  25224. constructor(options, isServer, maxPayload) {
  25225. this._maxPayload = maxPayload | 0;
  25226. this._options = options || {};
  25227. this._threshold =
  25228. this._options.threshold !== undefined ? this._options.threshold : 1024;
  25229. this._isServer = !!isServer;
  25230. this._deflate = null;
  25231. this._inflate = null;
  25232. this.params = null;
  25233. if (!zlibLimiter) {
  25234. const concurrency =
  25235. this._options.concurrencyLimit !== undefined
  25236. ? this._options.concurrencyLimit
  25237. : 10;
  25238. zlibLimiter = new Limiter(concurrency);
  25239. }
  25240. }
  25241. /**
  25242. * @type {String}
  25243. */
  25244. static get extensionName() {
  25245. return 'permessage-deflate';
  25246. }
  25247. /**
  25248. * Create an extension negotiation offer.
  25249. *
  25250. * @return {Object} Extension parameters
  25251. * @public
  25252. */
  25253. offer() {
  25254. const params = {};
  25255. if (this._options.serverNoContextTakeover) {
  25256. params.server_no_context_takeover = true;
  25257. }
  25258. if (this._options.clientNoContextTakeover) {
  25259. params.client_no_context_takeover = true;
  25260. }
  25261. if (this._options.serverMaxWindowBits) {
  25262. params.server_max_window_bits = this._options.serverMaxWindowBits;
  25263. }
  25264. if (this._options.clientMaxWindowBits) {
  25265. params.client_max_window_bits = this._options.clientMaxWindowBits;
  25266. } else if (this._options.clientMaxWindowBits == null) {
  25267. params.client_max_window_bits = true;
  25268. }
  25269. return params;
  25270. }
  25271. /**
  25272. * Accept an extension negotiation offer/response.
  25273. *
  25274. * @param {Array} configurations The extension negotiation offers/reponse
  25275. * @return {Object} Accepted configuration
  25276. * @public
  25277. */
  25278. accept(configurations) {
  25279. configurations = this.normalizeParams(configurations);
  25280. this.params = this._isServer
  25281. ? this.acceptAsServer(configurations)
  25282. : this.acceptAsClient(configurations);
  25283. return this.params;
  25284. }
  25285. /**
  25286. * Releases all resources used by the extension.
  25287. *
  25288. * @public
  25289. */
  25290. cleanup() {
  25291. if (this._inflate) {
  25292. this._inflate.close();
  25293. this._inflate = null;
  25294. }
  25295. if (this._deflate) {
  25296. const callback = this._deflate[kCallback];
  25297. this._deflate.close();
  25298. this._deflate = null;
  25299. if (callback) {
  25300. callback(
  25301. new Error(
  25302. 'The deflate stream was closed while data was being processed'
  25303. )
  25304. );
  25305. }
  25306. }
  25307. }
  25308. /**
  25309. * Accept an extension negotiation offer.
  25310. *
  25311. * @param {Array} offers The extension negotiation offers
  25312. * @return {Object} Accepted configuration
  25313. * @private
  25314. */
  25315. acceptAsServer(offers) {
  25316. const opts = this._options;
  25317. const accepted = offers.find((params) => {
  25318. if (
  25319. (opts.serverNoContextTakeover === false &&
  25320. params.server_no_context_takeover) ||
  25321. (params.server_max_window_bits &&
  25322. (opts.serverMaxWindowBits === false ||
  25323. (typeof opts.serverMaxWindowBits === 'number' &&
  25324. opts.serverMaxWindowBits > params.server_max_window_bits))) ||
  25325. (typeof opts.clientMaxWindowBits === 'number' &&
  25326. !params.client_max_window_bits)
  25327. ) {
  25328. return false;
  25329. }
  25330. return true;
  25331. });
  25332. if (!accepted) {
  25333. throw new Error('None of the extension offers can be accepted');
  25334. }
  25335. if (opts.serverNoContextTakeover) {
  25336. accepted.server_no_context_takeover = true;
  25337. }
  25338. if (opts.clientNoContextTakeover) {
  25339. accepted.client_no_context_takeover = true;
  25340. }
  25341. if (typeof opts.serverMaxWindowBits === 'number') {
  25342. accepted.server_max_window_bits = opts.serverMaxWindowBits;
  25343. }
  25344. if (typeof opts.clientMaxWindowBits === 'number') {
  25345. accepted.client_max_window_bits = opts.clientMaxWindowBits;
  25346. } else if (
  25347. accepted.client_max_window_bits === true ||
  25348. opts.clientMaxWindowBits === false
  25349. ) {
  25350. delete accepted.client_max_window_bits;
  25351. }
  25352. return accepted;
  25353. }
  25354. /**
  25355. * Accept the extension negotiation response.
  25356. *
  25357. * @param {Array} response The extension negotiation response
  25358. * @return {Object} Accepted configuration
  25359. * @private
  25360. */
  25361. acceptAsClient(response) {
  25362. const params = response[0];
  25363. if (
  25364. this._options.clientNoContextTakeover === false &&
  25365. params.client_no_context_takeover
  25366. ) {
  25367. throw new Error('Unexpected parameter "client_no_context_takeover"');
  25368. }
  25369. if (!params.client_max_window_bits) {
  25370. if (typeof this._options.clientMaxWindowBits === 'number') {
  25371. params.client_max_window_bits = this._options.clientMaxWindowBits;
  25372. }
  25373. } else if (
  25374. this._options.clientMaxWindowBits === false ||
  25375. (typeof this._options.clientMaxWindowBits === 'number' &&
  25376. params.client_max_window_bits > this._options.clientMaxWindowBits)
  25377. ) {
  25378. throw new Error(
  25379. 'Unexpected or invalid parameter "client_max_window_bits"'
  25380. );
  25381. }
  25382. return params;
  25383. }
  25384. /**
  25385. * Normalize parameters.
  25386. *
  25387. * @param {Array} configurations The extension negotiation offers/reponse
  25388. * @return {Array} The offers/response with normalized parameters
  25389. * @private
  25390. */
  25391. normalizeParams(configurations) {
  25392. configurations.forEach((params) => {
  25393. Object.keys(params).forEach((key) => {
  25394. let value = params[key];
  25395. if (value.length > 1) {
  25396. throw new Error(`Parameter "${key}" must have only a single value`);
  25397. }
  25398. value = value[0];
  25399. if (key === 'client_max_window_bits') {
  25400. if (value !== true) {
  25401. const num = +value;
  25402. if (!Number.isInteger(num) || num < 8 || num > 15) {
  25403. throw new TypeError(
  25404. `Invalid value for parameter "${key}": ${value}`
  25405. );
  25406. }
  25407. value = num;
  25408. } else if (!this._isServer) {
  25409. throw new TypeError(
  25410. `Invalid value for parameter "${key}": ${value}`
  25411. );
  25412. }
  25413. } else if (key === 'server_max_window_bits') {
  25414. const num = +value;
  25415. if (!Number.isInteger(num) || num < 8 || num > 15) {
  25416. throw new TypeError(
  25417. `Invalid value for parameter "${key}": ${value}`
  25418. );
  25419. }
  25420. value = num;
  25421. } else if (
  25422. key === 'client_no_context_takeover' ||
  25423. key === 'server_no_context_takeover'
  25424. ) {
  25425. if (value !== true) {
  25426. throw new TypeError(
  25427. `Invalid value for parameter "${key}": ${value}`
  25428. );
  25429. }
  25430. } else {
  25431. throw new Error(`Unknown parameter "${key}"`);
  25432. }
  25433. params[key] = value;
  25434. });
  25435. });
  25436. return configurations;
  25437. }
  25438. /**
  25439. * Decompress data. Concurrency limited.
  25440. *
  25441. * @param {Buffer} data Compressed data
  25442. * @param {Boolean} fin Specifies whether or not this is the last fragment
  25443. * @param {Function} callback Callback
  25444. * @public
  25445. */
  25446. decompress(data, fin, callback) {
  25447. zlibLimiter.add((done) => {
  25448. this._decompress(data, fin, (err, result) => {
  25449. done();
  25450. callback(err, result);
  25451. });
  25452. });
  25453. }
  25454. /**
  25455. * Compress data. Concurrency limited.
  25456. *
  25457. * @param {(Buffer|String)} data Data to compress
  25458. * @param {Boolean} fin Specifies whether or not this is the last fragment
  25459. * @param {Function} callback Callback
  25460. * @public
  25461. */
  25462. compress(data, fin, callback) {
  25463. zlibLimiter.add((done) => {
  25464. this._compress(data, fin, (err, result) => {
  25465. done();
  25466. callback(err, result);
  25467. });
  25468. });
  25469. }
  25470. /**
  25471. * Decompress data.
  25472. *
  25473. * @param {Buffer} data Compressed data
  25474. * @param {Boolean} fin Specifies whether or not this is the last fragment
  25475. * @param {Function} callback Callback
  25476. * @private
  25477. */
  25478. _decompress(data, fin, callback) {
  25479. const endpoint = this._isServer ? 'client' : 'server';
  25480. if (!this._inflate) {
  25481. const key = `${endpoint}_max_window_bits`;
  25482. const windowBits =
  25483. typeof this.params[key] !== 'number'
  25484. ? zlib.Z_DEFAULT_WINDOWBITS
  25485. : this.params[key];
  25486. this._inflate = zlib.createInflateRaw({
  25487. ...this._options.zlibInflateOptions,
  25488. windowBits
  25489. });
  25490. this._inflate[kPerMessageDeflate] = this;
  25491. this._inflate[kTotalLength] = 0;
  25492. this._inflate[kBuffers] = [];
  25493. this._inflate.on('error', inflateOnError);
  25494. this._inflate.on('data', inflateOnData);
  25495. }
  25496. this._inflate[kCallback] = callback;
  25497. this._inflate.write(data);
  25498. if (fin) this._inflate.write(TRAILER);
  25499. this._inflate.flush(() => {
  25500. const err = this._inflate[kError$1];
  25501. if (err) {
  25502. this._inflate.close();
  25503. this._inflate = null;
  25504. callback(err);
  25505. return;
  25506. }
  25507. const data = bufferUtil.concat(
  25508. this._inflate[kBuffers],
  25509. this._inflate[kTotalLength]
  25510. );
  25511. if (this._inflate._readableState.endEmitted) {
  25512. this._inflate.close();
  25513. this._inflate = null;
  25514. } else {
  25515. this._inflate[kTotalLength] = 0;
  25516. this._inflate[kBuffers] = [];
  25517. if (fin && this.params[`${endpoint}_no_context_takeover`]) {
  25518. this._inflate.reset();
  25519. }
  25520. }
  25521. callback(null, data);
  25522. });
  25523. }
  25524. /**
  25525. * Compress data.
  25526. *
  25527. * @param {(Buffer|String)} data Data to compress
  25528. * @param {Boolean} fin Specifies whether or not this is the last fragment
  25529. * @param {Function} callback Callback
  25530. * @private
  25531. */
  25532. _compress(data, fin, callback) {
  25533. const endpoint = this._isServer ? 'server' : 'client';
  25534. if (!this._deflate) {
  25535. const key = `${endpoint}_max_window_bits`;
  25536. const windowBits =
  25537. typeof this.params[key] !== 'number'
  25538. ? zlib.Z_DEFAULT_WINDOWBITS
  25539. : this.params[key];
  25540. this._deflate = zlib.createDeflateRaw({
  25541. ...this._options.zlibDeflateOptions,
  25542. windowBits
  25543. });
  25544. this._deflate[kTotalLength] = 0;
  25545. this._deflate[kBuffers] = [];
  25546. this._deflate.on('data', deflateOnData);
  25547. }
  25548. this._deflate[kCallback] = callback;
  25549. this._deflate.write(data);
  25550. this._deflate.flush(zlib.Z_SYNC_FLUSH, () => {
  25551. if (!this._deflate) {
  25552. //
  25553. // The deflate stream was closed while data was being processed.
  25554. //
  25555. return;
  25556. }
  25557. let data = bufferUtil.concat(
  25558. this._deflate[kBuffers],
  25559. this._deflate[kTotalLength]
  25560. );
  25561. if (fin) {
  25562. data = new FastBuffer$1(data.buffer, data.byteOffset, data.length - 4);
  25563. }
  25564. //
  25565. // Ensure that the callback will not be called again in
  25566. // `PerMessageDeflate#cleanup()`.
  25567. //
  25568. this._deflate[kCallback] = null;
  25569. this._deflate[kTotalLength] = 0;
  25570. this._deflate[kBuffers] = [];
  25571. if (fin && this.params[`${endpoint}_no_context_takeover`]) {
  25572. this._deflate.reset();
  25573. }
  25574. callback(null, data);
  25575. });
  25576. }
  25577. };
  25578. var permessageDeflate = PerMessageDeflate$4;
  25579. /**
  25580. * The listener of the `zlib.DeflateRaw` stream `'data'` event.
  25581. *
  25582. * @param {Buffer} chunk A chunk of data
  25583. * @private
  25584. */
  25585. function deflateOnData(chunk) {
  25586. this[kBuffers].push(chunk);
  25587. this[kTotalLength] += chunk.length;
  25588. }
  25589. /**
  25590. * The listener of the `zlib.InflateRaw` stream `'data'` event.
  25591. *
  25592. * @param {Buffer} chunk A chunk of data
  25593. * @private
  25594. */
  25595. function inflateOnData(chunk) {
  25596. this[kTotalLength] += chunk.length;
  25597. if (
  25598. this[kPerMessageDeflate]._maxPayload < 1 ||
  25599. this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload
  25600. ) {
  25601. this[kBuffers].push(chunk);
  25602. return;
  25603. }
  25604. this[kError$1] = new RangeError('Max payload size exceeded');
  25605. this[kError$1].code = 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH';
  25606. this[kError$1][kStatusCode$2] = 1009;
  25607. this.removeListener('data', inflateOnData);
  25608. this.reset();
  25609. }
  25610. /**
  25611. * The listener of the `zlib.InflateRaw` stream `'error'` event.
  25612. *
  25613. * @param {Error} err The emitted error
  25614. * @private
  25615. */
  25616. function inflateOnError(err) {
  25617. //
  25618. // There is no need to call `Zlib#close()` as the handle is automatically
  25619. // closed when an error is emitted.
  25620. //
  25621. this[kPerMessageDeflate]._inflate = null;
  25622. err[kStatusCode$2] = 1007;
  25623. this[kCallback](err);
  25624. }
  25625. var validation = {exports: {}};
  25626. const { isUtf8 } = require$$0$9;
  25627. const { hasBlob } = constants;
  25628. //
  25629. // Allowed token characters:
  25630. //
  25631. // '!', '#', '$', '%', '&', ''', '*', '+', '-',
  25632. // '.', 0-9, A-Z, '^', '_', '`', a-z, '|', '~'
  25633. //
  25634. // tokenChars[32] === 0 // ' '
  25635. // tokenChars[33] === 1 // '!'
  25636. // tokenChars[34] === 0 // '"'
  25637. // ...
  25638. //
  25639. // prettier-ignore
  25640. const tokenChars$2 = [
  25641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0 - 15
  25642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 16 - 31
  25643. 0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, // 32 - 47
  25644. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, // 48 - 63
  25645. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 64 - 79
  25646. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, // 80 - 95
  25647. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 96 - 111
  25648. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0 // 112 - 127
  25649. ];
  25650. /**
  25651. * Checks if a status code is allowed in a close frame.
  25652. *
  25653. * @param {Number} code The status code
  25654. * @return {Boolean} `true` if the status code is valid, else `false`
  25655. * @public
  25656. */
  25657. function isValidStatusCode$2(code) {
  25658. return (
  25659. (code >= 1000 &&
  25660. code <= 1014 &&
  25661. code !== 1004 &&
  25662. code !== 1005 &&
  25663. code !== 1006) ||
  25664. (code >= 3000 && code <= 4999)
  25665. );
  25666. }
  25667. /**
  25668. * Checks if a given buffer contains only correct UTF-8.
  25669. * Ported from https://www.cl.cam.ac.uk/%7Emgk25/ucs/utf8_check.c by
  25670. * Markus Kuhn.
  25671. *
  25672. * @param {Buffer} buf The buffer to check
  25673. * @return {Boolean} `true` if `buf` contains only correct UTF-8, else `false`
  25674. * @public
  25675. */
  25676. function _isValidUTF8(buf) {
  25677. const len = buf.length;
  25678. let i = 0;
  25679. while (i < len) {
  25680. if ((buf[i] & 0x80) === 0) {
  25681. // 0xxxxxxx
  25682. i++;
  25683. } else if ((buf[i] & 0xe0) === 0xc0) {
  25684. // 110xxxxx 10xxxxxx
  25685. if (
  25686. i + 1 === len ||
  25687. (buf[i + 1] & 0xc0) !== 0x80 ||
  25688. (buf[i] & 0xfe) === 0xc0 // Overlong
  25689. ) {
  25690. return false;
  25691. }
  25692. i += 2;
  25693. } else if ((buf[i] & 0xf0) === 0xe0) {
  25694. // 1110xxxx 10xxxxxx 10xxxxxx
  25695. if (
  25696. i + 2 >= len ||
  25697. (buf[i + 1] & 0xc0) !== 0x80 ||
  25698. (buf[i + 2] & 0xc0) !== 0x80 ||
  25699. (buf[i] === 0xe0 && (buf[i + 1] & 0xe0) === 0x80) || // Overlong
  25700. (buf[i] === 0xed && (buf[i + 1] & 0xe0) === 0xa0) // Surrogate (U+D800 - U+DFFF)
  25701. ) {
  25702. return false;
  25703. }
  25704. i += 3;
  25705. } else if ((buf[i] & 0xf8) === 0xf0) {
  25706. // 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
  25707. if (
  25708. i + 3 >= len ||
  25709. (buf[i + 1] & 0xc0) !== 0x80 ||
  25710. (buf[i + 2] & 0xc0) !== 0x80 ||
  25711. (buf[i + 3] & 0xc0) !== 0x80 ||
  25712. (buf[i] === 0xf0 && (buf[i + 1] & 0xf0) === 0x80) || // Overlong
  25713. (buf[i] === 0xf4 && buf[i + 1] > 0x8f) ||
  25714. buf[i] > 0xf4 // > U+10FFFF
  25715. ) {
  25716. return false;
  25717. }
  25718. i += 4;
  25719. } else {
  25720. return false;
  25721. }
  25722. }
  25723. return true;
  25724. }
  25725. /**
  25726. * Determines whether a value is a `Blob`.
  25727. *
  25728. * @param {*} value The value to be tested
  25729. * @return {Boolean} `true` if `value` is a `Blob`, else `false`
  25730. * @private
  25731. */
  25732. function isBlob$2(value) {
  25733. return (
  25734. hasBlob &&
  25735. typeof value === 'object' &&
  25736. typeof value.arrayBuffer === 'function' &&
  25737. typeof value.type === 'string' &&
  25738. typeof value.stream === 'function' &&
  25739. (value[Symbol.toStringTag] === 'Blob' ||
  25740. value[Symbol.toStringTag] === 'File')
  25741. );
  25742. }
  25743. validation.exports = {
  25744. isBlob: isBlob$2,
  25745. isValidStatusCode: isValidStatusCode$2,
  25746. isValidUTF8: _isValidUTF8,
  25747. tokenChars: tokenChars$2
  25748. };
  25749. if (isUtf8) {
  25750. validation.exports.isValidUTF8 = function (buf) {
  25751. return buf.length < 24 ? _isValidUTF8(buf) : isUtf8(buf);
  25752. };
  25753. } /* istanbul ignore else */ else if (!process.env.WS_NO_UTF_8_VALIDATE) {
  25754. try {
  25755. const isValidUTF8 = require('utf-8-validate');
  25756. validation.exports.isValidUTF8 = function (buf) {
  25757. return buf.length < 32 ? _isValidUTF8(buf) : isValidUTF8(buf);
  25758. };
  25759. } catch (e) {
  25760. // Continue regardless of the error.
  25761. }
  25762. }
  25763. var validationExports = validation.exports;
  25764. const { Writable: Writable$1 } = require$$0$8;
  25765. const PerMessageDeflate$3 = permessageDeflate;
  25766. const {
  25767. BINARY_TYPES: BINARY_TYPES$1,
  25768. EMPTY_BUFFER: EMPTY_BUFFER$2,
  25769. kStatusCode: kStatusCode$1,
  25770. kWebSocket: kWebSocket$3
  25771. } = constants;
  25772. const { concat, toArrayBuffer, unmask } = bufferUtilExports;
  25773. const { isValidStatusCode: isValidStatusCode$1, isValidUTF8 } = validationExports;
  25774. const FastBuffer = Buffer[Symbol.species];
  25775. const GET_INFO = 0;
  25776. const GET_PAYLOAD_LENGTH_16 = 1;
  25777. const GET_PAYLOAD_LENGTH_64 = 2;
  25778. const GET_MASK = 3;
  25779. const GET_DATA = 4;
  25780. const INFLATING = 5;
  25781. const DEFER_EVENT = 6;
  25782. /**
  25783. * HyBi Receiver implementation.
  25784. *
  25785. * @extends Writable
  25786. */
  25787. let Receiver$1 = class Receiver extends Writable$1 {
  25788. /**
  25789. * Creates a Receiver instance.
  25790. *
  25791. * @param {Object} [options] Options object
  25792. * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether
  25793. * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
  25794. * multiple times in the same tick
  25795. * @param {String} [options.binaryType=nodebuffer] The type for binary data
  25796. * @param {Object} [options.extensions] An object containing the negotiated
  25797. * extensions
  25798. * @param {Boolean} [options.isServer=false] Specifies whether to operate in
  25799. * client or server mode
  25800. * @param {Number} [options.maxPayload=0] The maximum allowed message length
  25801. * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
  25802. * not to skip UTF-8 validation for text and close messages
  25803. */
  25804. constructor(options = {}) {
  25805. super();
  25806. this._allowSynchronousEvents =
  25807. options.allowSynchronousEvents !== undefined
  25808. ? options.allowSynchronousEvents
  25809. : true;
  25810. this._binaryType = options.binaryType || BINARY_TYPES$1[0];
  25811. this._extensions = options.extensions || {};
  25812. this._isServer = !!options.isServer;
  25813. this._maxPayload = options.maxPayload | 0;
  25814. this._skipUTF8Validation = !!options.skipUTF8Validation;
  25815. this[kWebSocket$3] = undefined;
  25816. this._bufferedBytes = 0;
  25817. this._buffers = [];
  25818. this._compressed = false;
  25819. this._payloadLength = 0;
  25820. this._mask = undefined;
  25821. this._fragmented = 0;
  25822. this._masked = false;
  25823. this._fin = false;
  25824. this._opcode = 0;
  25825. this._totalPayloadLength = 0;
  25826. this._messageLength = 0;
  25827. this._fragments = [];
  25828. this._errored = false;
  25829. this._loop = false;
  25830. this._state = GET_INFO;
  25831. }
  25832. /**
  25833. * Implements `Writable.prototype._write()`.
  25834. *
  25835. * @param {Buffer} chunk The chunk of data to write
  25836. * @param {String} encoding The character encoding of `chunk`
  25837. * @param {Function} cb Callback
  25838. * @private
  25839. */
  25840. _write(chunk, encoding, cb) {
  25841. if (this._opcode === 0x08 && this._state == GET_INFO) return cb();
  25842. this._bufferedBytes += chunk.length;
  25843. this._buffers.push(chunk);
  25844. this.startLoop(cb);
  25845. }
  25846. /**
  25847. * Consumes `n` bytes from the buffered data.
  25848. *
  25849. * @param {Number} n The number of bytes to consume
  25850. * @return {Buffer} The consumed bytes
  25851. * @private
  25852. */
  25853. consume(n) {
  25854. this._bufferedBytes -= n;
  25855. if (n === this._buffers[0].length) return this._buffers.shift();
  25856. if (n < this._buffers[0].length) {
  25857. const buf = this._buffers[0];
  25858. this._buffers[0] = new FastBuffer(
  25859. buf.buffer,
  25860. buf.byteOffset + n,
  25861. buf.length - n
  25862. );
  25863. return new FastBuffer(buf.buffer, buf.byteOffset, n);
  25864. }
  25865. const dst = Buffer.allocUnsafe(n);
  25866. do {
  25867. const buf = this._buffers[0];
  25868. const offset = dst.length - n;
  25869. if (n >= buf.length) {
  25870. dst.set(this._buffers.shift(), offset);
  25871. } else {
  25872. dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n), offset);
  25873. this._buffers[0] = new FastBuffer(
  25874. buf.buffer,
  25875. buf.byteOffset + n,
  25876. buf.length - n
  25877. );
  25878. }
  25879. n -= buf.length;
  25880. } while (n > 0);
  25881. return dst;
  25882. }
  25883. /**
  25884. * Starts the parsing loop.
  25885. *
  25886. * @param {Function} cb Callback
  25887. * @private
  25888. */
  25889. startLoop(cb) {
  25890. this._loop = true;
  25891. do {
  25892. switch (this._state) {
  25893. case GET_INFO:
  25894. this.getInfo(cb);
  25895. break;
  25896. case GET_PAYLOAD_LENGTH_16:
  25897. this.getPayloadLength16(cb);
  25898. break;
  25899. case GET_PAYLOAD_LENGTH_64:
  25900. this.getPayloadLength64(cb);
  25901. break;
  25902. case GET_MASK:
  25903. this.getMask();
  25904. break;
  25905. case GET_DATA:
  25906. this.getData(cb);
  25907. break;
  25908. case INFLATING:
  25909. case DEFER_EVENT:
  25910. this._loop = false;
  25911. return;
  25912. }
  25913. } while (this._loop);
  25914. if (!this._errored) cb();
  25915. }
  25916. /**
  25917. * Reads the first two bytes of a frame.
  25918. *
  25919. * @param {Function} cb Callback
  25920. * @private
  25921. */
  25922. getInfo(cb) {
  25923. if (this._bufferedBytes < 2) {
  25924. this._loop = false;
  25925. return;
  25926. }
  25927. const buf = this.consume(2);
  25928. if ((buf[0] & 0x30) !== 0x00) {
  25929. const error = this.createError(
  25930. RangeError,
  25931. 'RSV2 and RSV3 must be clear',
  25932. true,
  25933. 1002,
  25934. 'WS_ERR_UNEXPECTED_RSV_2_3'
  25935. );
  25936. cb(error);
  25937. return;
  25938. }
  25939. const compressed = (buf[0] & 0x40) === 0x40;
  25940. if (compressed && !this._extensions[PerMessageDeflate$3.extensionName]) {
  25941. const error = this.createError(
  25942. RangeError,
  25943. 'RSV1 must be clear',
  25944. true,
  25945. 1002,
  25946. 'WS_ERR_UNEXPECTED_RSV_1'
  25947. );
  25948. cb(error);
  25949. return;
  25950. }
  25951. this._fin = (buf[0] & 0x80) === 0x80;
  25952. this._opcode = buf[0] & 0x0f;
  25953. this._payloadLength = buf[1] & 0x7f;
  25954. if (this._opcode === 0x00) {
  25955. if (compressed) {
  25956. const error = this.createError(
  25957. RangeError,
  25958. 'RSV1 must be clear',
  25959. true,
  25960. 1002,
  25961. 'WS_ERR_UNEXPECTED_RSV_1'
  25962. );
  25963. cb(error);
  25964. return;
  25965. }
  25966. if (!this._fragmented) {
  25967. const error = this.createError(
  25968. RangeError,
  25969. 'invalid opcode 0',
  25970. true,
  25971. 1002,
  25972. 'WS_ERR_INVALID_OPCODE'
  25973. );
  25974. cb(error);
  25975. return;
  25976. }
  25977. this._opcode = this._fragmented;
  25978. } else if (this._opcode === 0x01 || this._opcode === 0x02) {
  25979. if (this._fragmented) {
  25980. const error = this.createError(
  25981. RangeError,
  25982. `invalid opcode ${this._opcode}`,
  25983. true,
  25984. 1002,
  25985. 'WS_ERR_INVALID_OPCODE'
  25986. );
  25987. cb(error);
  25988. return;
  25989. }
  25990. this._compressed = compressed;
  25991. } else if (this._opcode > 0x07 && this._opcode < 0x0b) {
  25992. if (!this._fin) {
  25993. const error = this.createError(
  25994. RangeError,
  25995. 'FIN must be set',
  25996. true,
  25997. 1002,
  25998. 'WS_ERR_EXPECTED_FIN'
  25999. );
  26000. cb(error);
  26001. return;
  26002. }
  26003. if (compressed) {
  26004. const error = this.createError(
  26005. RangeError,
  26006. 'RSV1 must be clear',
  26007. true,
  26008. 1002,
  26009. 'WS_ERR_UNEXPECTED_RSV_1'
  26010. );
  26011. cb(error);
  26012. return;
  26013. }
  26014. if (
  26015. this._payloadLength > 0x7d ||
  26016. (this._opcode === 0x08 && this._payloadLength === 1)
  26017. ) {
  26018. const error = this.createError(
  26019. RangeError,
  26020. `invalid payload length ${this._payloadLength}`,
  26021. true,
  26022. 1002,
  26023. 'WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH'
  26024. );
  26025. cb(error);
  26026. return;
  26027. }
  26028. } else {
  26029. const error = this.createError(
  26030. RangeError,
  26031. `invalid opcode ${this._opcode}`,
  26032. true,
  26033. 1002,
  26034. 'WS_ERR_INVALID_OPCODE'
  26035. );
  26036. cb(error);
  26037. return;
  26038. }
  26039. if (!this._fin && !this._fragmented) this._fragmented = this._opcode;
  26040. this._masked = (buf[1] & 0x80) === 0x80;
  26041. if (this._isServer) {
  26042. if (!this._masked) {
  26043. const error = this.createError(
  26044. RangeError,
  26045. 'MASK must be set',
  26046. true,
  26047. 1002,
  26048. 'WS_ERR_EXPECTED_MASK'
  26049. );
  26050. cb(error);
  26051. return;
  26052. }
  26053. } else if (this._masked) {
  26054. const error = this.createError(
  26055. RangeError,
  26056. 'MASK must be clear',
  26057. true,
  26058. 1002,
  26059. 'WS_ERR_UNEXPECTED_MASK'
  26060. );
  26061. cb(error);
  26062. return;
  26063. }
  26064. if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16;
  26065. else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64;
  26066. else this.haveLength(cb);
  26067. }
  26068. /**
  26069. * Gets extended payload length (7+16).
  26070. *
  26071. * @param {Function} cb Callback
  26072. * @private
  26073. */
  26074. getPayloadLength16(cb) {
  26075. if (this._bufferedBytes < 2) {
  26076. this._loop = false;
  26077. return;
  26078. }
  26079. this._payloadLength = this.consume(2).readUInt16BE(0);
  26080. this.haveLength(cb);
  26081. }
  26082. /**
  26083. * Gets extended payload length (7+64).
  26084. *
  26085. * @param {Function} cb Callback
  26086. * @private
  26087. */
  26088. getPayloadLength64(cb) {
  26089. if (this._bufferedBytes < 8) {
  26090. this._loop = false;
  26091. return;
  26092. }
  26093. const buf = this.consume(8);
  26094. const num = buf.readUInt32BE(0);
  26095. //
  26096. // The maximum safe integer in JavaScript is 2^53 - 1. An error is returned
  26097. // if payload length is greater than this number.
  26098. //
  26099. if (num > Math.pow(2, 53 - 32) - 1) {
  26100. const error = this.createError(
  26101. RangeError,
  26102. 'Unsupported WebSocket frame: payload length > 2^53 - 1',
  26103. false,
  26104. 1009,
  26105. 'WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH'
  26106. );
  26107. cb(error);
  26108. return;
  26109. }
  26110. this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4);
  26111. this.haveLength(cb);
  26112. }
  26113. /**
  26114. * Payload length has been read.
  26115. *
  26116. * @param {Function} cb Callback
  26117. * @private
  26118. */
  26119. haveLength(cb) {
  26120. if (this._payloadLength && this._opcode < 0x08) {
  26121. this._totalPayloadLength += this._payloadLength;
  26122. if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) {
  26123. const error = this.createError(
  26124. RangeError,
  26125. 'Max payload size exceeded',
  26126. false,
  26127. 1009,
  26128. 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH'
  26129. );
  26130. cb(error);
  26131. return;
  26132. }
  26133. }
  26134. if (this._masked) this._state = GET_MASK;
  26135. else this._state = GET_DATA;
  26136. }
  26137. /**
  26138. * Reads mask bytes.
  26139. *
  26140. * @private
  26141. */
  26142. getMask() {
  26143. if (this._bufferedBytes < 4) {
  26144. this._loop = false;
  26145. return;
  26146. }
  26147. this._mask = this.consume(4);
  26148. this._state = GET_DATA;
  26149. }
  26150. /**
  26151. * Reads data bytes.
  26152. *
  26153. * @param {Function} cb Callback
  26154. * @private
  26155. */
  26156. getData(cb) {
  26157. let data = EMPTY_BUFFER$2;
  26158. if (this._payloadLength) {
  26159. if (this._bufferedBytes < this._payloadLength) {
  26160. this._loop = false;
  26161. return;
  26162. }
  26163. data = this.consume(this._payloadLength);
  26164. if (
  26165. this._masked &&
  26166. (this._mask[0] | this._mask[1] | this._mask[2] | this._mask[3]) !== 0
  26167. ) {
  26168. unmask(data, this._mask);
  26169. }
  26170. }
  26171. if (this._opcode > 0x07) {
  26172. this.controlMessage(data, cb);
  26173. return;
  26174. }
  26175. if (this._compressed) {
  26176. this._state = INFLATING;
  26177. this.decompress(data, cb);
  26178. return;
  26179. }
  26180. if (data.length) {
  26181. //
  26182. // This message is not compressed so its length is the sum of the payload
  26183. // length of all fragments.
  26184. //
  26185. this._messageLength = this._totalPayloadLength;
  26186. this._fragments.push(data);
  26187. }
  26188. this.dataMessage(cb);
  26189. }
  26190. /**
  26191. * Decompresses data.
  26192. *
  26193. * @param {Buffer} data Compressed data
  26194. * @param {Function} cb Callback
  26195. * @private
  26196. */
  26197. decompress(data, cb) {
  26198. const perMessageDeflate = this._extensions[PerMessageDeflate$3.extensionName];
  26199. perMessageDeflate.decompress(data, this._fin, (err, buf) => {
  26200. if (err) return cb(err);
  26201. if (buf.length) {
  26202. this._messageLength += buf.length;
  26203. if (this._messageLength > this._maxPayload && this._maxPayload > 0) {
  26204. const error = this.createError(
  26205. RangeError,
  26206. 'Max payload size exceeded',
  26207. false,
  26208. 1009,
  26209. 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH'
  26210. );
  26211. cb(error);
  26212. return;
  26213. }
  26214. this._fragments.push(buf);
  26215. }
  26216. this.dataMessage(cb);
  26217. if (this._state === GET_INFO) this.startLoop(cb);
  26218. });
  26219. }
  26220. /**
  26221. * Handles a data message.
  26222. *
  26223. * @param {Function} cb Callback
  26224. * @private
  26225. */
  26226. dataMessage(cb) {
  26227. if (!this._fin) {
  26228. this._state = GET_INFO;
  26229. return;
  26230. }
  26231. const messageLength = this._messageLength;
  26232. const fragments = this._fragments;
  26233. this._totalPayloadLength = 0;
  26234. this._messageLength = 0;
  26235. this._fragmented = 0;
  26236. this._fragments = [];
  26237. if (this._opcode === 2) {
  26238. let data;
  26239. if (this._binaryType === 'nodebuffer') {
  26240. data = concat(fragments, messageLength);
  26241. } else if (this._binaryType === 'arraybuffer') {
  26242. data = toArrayBuffer(concat(fragments, messageLength));
  26243. } else if (this._binaryType === 'blob') {
  26244. data = new Blob(fragments);
  26245. } else {
  26246. data = fragments;
  26247. }
  26248. if (this._allowSynchronousEvents) {
  26249. this.emit('message', data, true);
  26250. this._state = GET_INFO;
  26251. } else {
  26252. this._state = DEFER_EVENT;
  26253. setImmediate(() => {
  26254. this.emit('message', data, true);
  26255. this._state = GET_INFO;
  26256. this.startLoop(cb);
  26257. });
  26258. }
  26259. } else {
  26260. const buf = concat(fragments, messageLength);
  26261. if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
  26262. const error = this.createError(
  26263. Error,
  26264. 'invalid UTF-8 sequence',
  26265. true,
  26266. 1007,
  26267. 'WS_ERR_INVALID_UTF8'
  26268. );
  26269. cb(error);
  26270. return;
  26271. }
  26272. if (this._state === INFLATING || this._allowSynchronousEvents) {
  26273. this.emit('message', buf, false);
  26274. this._state = GET_INFO;
  26275. } else {
  26276. this._state = DEFER_EVENT;
  26277. setImmediate(() => {
  26278. this.emit('message', buf, false);
  26279. this._state = GET_INFO;
  26280. this.startLoop(cb);
  26281. });
  26282. }
  26283. }
  26284. }
  26285. /**
  26286. * Handles a control message.
  26287. *
  26288. * @param {Buffer} data Data to handle
  26289. * @return {(Error|RangeError|undefined)} A possible error
  26290. * @private
  26291. */
  26292. controlMessage(data, cb) {
  26293. if (this._opcode === 0x08) {
  26294. if (data.length === 0) {
  26295. this._loop = false;
  26296. this.emit('conclude', 1005, EMPTY_BUFFER$2);
  26297. this.end();
  26298. } else {
  26299. const code = data.readUInt16BE(0);
  26300. if (!isValidStatusCode$1(code)) {
  26301. const error = this.createError(
  26302. RangeError,
  26303. `invalid status code ${code}`,
  26304. true,
  26305. 1002,
  26306. 'WS_ERR_INVALID_CLOSE_CODE'
  26307. );
  26308. cb(error);
  26309. return;
  26310. }
  26311. const buf = new FastBuffer(
  26312. data.buffer,
  26313. data.byteOffset + 2,
  26314. data.length - 2
  26315. );
  26316. if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
  26317. const error = this.createError(
  26318. Error,
  26319. 'invalid UTF-8 sequence',
  26320. true,
  26321. 1007,
  26322. 'WS_ERR_INVALID_UTF8'
  26323. );
  26324. cb(error);
  26325. return;
  26326. }
  26327. this._loop = false;
  26328. this.emit('conclude', code, buf);
  26329. this.end();
  26330. }
  26331. this._state = GET_INFO;
  26332. return;
  26333. }
  26334. if (this._allowSynchronousEvents) {
  26335. this.emit(this._opcode === 0x09 ? 'ping' : 'pong', data);
  26336. this._state = GET_INFO;
  26337. } else {
  26338. this._state = DEFER_EVENT;
  26339. setImmediate(() => {
  26340. this.emit(this._opcode === 0x09 ? 'ping' : 'pong', data);
  26341. this._state = GET_INFO;
  26342. this.startLoop(cb);
  26343. });
  26344. }
  26345. }
  26346. /**
  26347. * Builds an error object.
  26348. *
  26349. * @param {function(new:Error|RangeError)} ErrorCtor The error constructor
  26350. * @param {String} message The error message
  26351. * @param {Boolean} prefix Specifies whether or not to add a default prefix to
  26352. * `message`
  26353. * @param {Number} statusCode The status code
  26354. * @param {String} errorCode The exposed error code
  26355. * @return {(Error|RangeError)} The error
  26356. * @private
  26357. */
  26358. createError(ErrorCtor, message, prefix, statusCode, errorCode) {
  26359. this._loop = false;
  26360. this._errored = true;
  26361. const err = new ErrorCtor(
  26362. prefix ? `Invalid WebSocket frame: ${message}` : message
  26363. );
  26364. Error.captureStackTrace(err, this.createError);
  26365. err.code = errorCode;
  26366. err[kStatusCode$1] = statusCode;
  26367. return err;
  26368. }
  26369. };
  26370. var receiver = Receiver$1;
  26371. /* eslint no-unused-vars: ["error", { "varsIgnorePattern": "^Duplex" }] */
  26372. const { randomFillSync } = require$$3;
  26373. const PerMessageDeflate$2 = permessageDeflate;
  26374. const { EMPTY_BUFFER: EMPTY_BUFFER$1, kWebSocket: kWebSocket$2, NOOP: NOOP$2 } = constants;
  26375. const { isBlob: isBlob$1, isValidStatusCode } = validationExports;
  26376. const { mask: applyMask, toBuffer: toBuffer$1 } = bufferUtilExports;
  26377. const kByteLength = Symbol('kByteLength');
  26378. const maskBuffer = Buffer.alloc(4);
  26379. const RANDOM_POOL_SIZE = 8 * 1024;
  26380. let randomPool;
  26381. let randomPoolPointer = RANDOM_POOL_SIZE;
  26382. const DEFAULT = 0;
  26383. const DEFLATING = 1;
  26384. const GET_BLOB_DATA = 2;
  26385. /**
  26386. * HyBi Sender implementation.
  26387. */
  26388. let Sender$1 = class Sender {
  26389. /**
  26390. * Creates a Sender instance.
  26391. *
  26392. * @param {Duplex} socket The connection socket
  26393. * @param {Object} [extensions] An object containing the negotiated extensions
  26394. * @param {Function} [generateMask] The function used to generate the masking
  26395. * key
  26396. */
  26397. constructor(socket, extensions, generateMask) {
  26398. this._extensions = extensions || {};
  26399. if (generateMask) {
  26400. this._generateMask = generateMask;
  26401. this._maskBuffer = Buffer.alloc(4);
  26402. }
  26403. this._socket = socket;
  26404. this._firstFragment = true;
  26405. this._compress = false;
  26406. this._bufferedBytes = 0;
  26407. this._queue = [];
  26408. this._state = DEFAULT;
  26409. this.onerror = NOOP$2;
  26410. this[kWebSocket$2] = undefined;
  26411. }
  26412. /**
  26413. * Frames a piece of data according to the HyBi WebSocket protocol.
  26414. *
  26415. * @param {(Buffer|String)} data The data to frame
  26416. * @param {Object} options Options object
  26417. * @param {Boolean} [options.fin=false] Specifies whether or not to set the
  26418. * FIN bit
  26419. * @param {Function} [options.generateMask] The function used to generate the
  26420. * masking key
  26421. * @param {Boolean} [options.mask=false] Specifies whether or not to mask
  26422. * `data`
  26423. * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
  26424. * key
  26425. * @param {Number} options.opcode The opcode
  26426. * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
  26427. * modified
  26428. * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
  26429. * RSV1 bit
  26430. * @return {(Buffer|String)[]} The framed data
  26431. * @public
  26432. */
  26433. static frame(data, options) {
  26434. let mask;
  26435. let merge = false;
  26436. let offset = 2;
  26437. let skipMasking = false;
  26438. if (options.mask) {
  26439. mask = options.maskBuffer || maskBuffer;
  26440. if (options.generateMask) {
  26441. options.generateMask(mask);
  26442. } else {
  26443. if (randomPoolPointer === RANDOM_POOL_SIZE) {
  26444. /* istanbul ignore else */
  26445. if (randomPool === undefined) {
  26446. //
  26447. // This is lazily initialized because server-sent frames must not
  26448. // be masked so it may never be used.
  26449. //
  26450. randomPool = Buffer.alloc(RANDOM_POOL_SIZE);
  26451. }
  26452. randomFillSync(randomPool, 0, RANDOM_POOL_SIZE);
  26453. randomPoolPointer = 0;
  26454. }
  26455. mask[0] = randomPool[randomPoolPointer++];
  26456. mask[1] = randomPool[randomPoolPointer++];
  26457. mask[2] = randomPool[randomPoolPointer++];
  26458. mask[3] = randomPool[randomPoolPointer++];
  26459. }
  26460. skipMasking = (mask[0] | mask[1] | mask[2] | mask[3]) === 0;
  26461. offset = 6;
  26462. }
  26463. let dataLength;
  26464. if (typeof data === 'string') {
  26465. if (
  26466. (!options.mask || skipMasking) &&
  26467. options[kByteLength] !== undefined
  26468. ) {
  26469. dataLength = options[kByteLength];
  26470. } else {
  26471. data = Buffer.from(data);
  26472. dataLength = data.length;
  26473. }
  26474. } else {
  26475. dataLength = data.length;
  26476. merge = options.mask && options.readOnly && !skipMasking;
  26477. }
  26478. let payloadLength = dataLength;
  26479. if (dataLength >= 65536) {
  26480. offset += 8;
  26481. payloadLength = 127;
  26482. } else if (dataLength > 125) {
  26483. offset += 2;
  26484. payloadLength = 126;
  26485. }
  26486. const target = Buffer.allocUnsafe(merge ? dataLength + offset : offset);
  26487. target[0] = options.fin ? options.opcode | 0x80 : options.opcode;
  26488. if (options.rsv1) target[0] |= 0x40;
  26489. target[1] = payloadLength;
  26490. if (payloadLength === 126) {
  26491. target.writeUInt16BE(dataLength, 2);
  26492. } else if (payloadLength === 127) {
  26493. target[2] = target[3] = 0;
  26494. target.writeUIntBE(dataLength, 4, 6);
  26495. }
  26496. if (!options.mask) return [target, data];
  26497. target[1] |= 0x80;
  26498. target[offset - 4] = mask[0];
  26499. target[offset - 3] = mask[1];
  26500. target[offset - 2] = mask[2];
  26501. target[offset - 1] = mask[3];
  26502. if (skipMasking) return [target, data];
  26503. if (merge) {
  26504. applyMask(data, mask, target, offset, dataLength);
  26505. return [target];
  26506. }
  26507. applyMask(data, mask, data, 0, dataLength);
  26508. return [target, data];
  26509. }
  26510. /**
  26511. * Sends a close message to the other peer.
  26512. *
  26513. * @param {Number} [code] The status code component of the body
  26514. * @param {(String|Buffer)} [data] The message component of the body
  26515. * @param {Boolean} [mask=false] Specifies whether or not to mask the message
  26516. * @param {Function} [cb] Callback
  26517. * @public
  26518. */
  26519. close(code, data, mask, cb) {
  26520. let buf;
  26521. if (code === undefined) {
  26522. buf = EMPTY_BUFFER$1;
  26523. } else if (typeof code !== 'number' || !isValidStatusCode(code)) {
  26524. throw new TypeError('First argument must be a valid error code number');
  26525. } else if (data === undefined || !data.length) {
  26526. buf = Buffer.allocUnsafe(2);
  26527. buf.writeUInt16BE(code, 0);
  26528. } else {
  26529. const length = Buffer.byteLength(data);
  26530. if (length > 123) {
  26531. throw new RangeError('The message must not be greater than 123 bytes');
  26532. }
  26533. buf = Buffer.allocUnsafe(2 + length);
  26534. buf.writeUInt16BE(code, 0);
  26535. if (typeof data === 'string') {
  26536. buf.write(data, 2);
  26537. } else {
  26538. buf.set(data, 2);
  26539. }
  26540. }
  26541. const options = {
  26542. [kByteLength]: buf.length,
  26543. fin: true,
  26544. generateMask: this._generateMask,
  26545. mask,
  26546. maskBuffer: this._maskBuffer,
  26547. opcode: 0x08,
  26548. readOnly: false,
  26549. rsv1: false
  26550. };
  26551. if (this._state !== DEFAULT) {
  26552. this.enqueue([this.dispatch, buf, false, options, cb]);
  26553. } else {
  26554. this.sendFrame(Sender.frame(buf, options), cb);
  26555. }
  26556. }
  26557. /**
  26558. * Sends a ping message to the other peer.
  26559. *
  26560. * @param {*} data The message to send
  26561. * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
  26562. * @param {Function} [cb] Callback
  26563. * @public
  26564. */
  26565. ping(data, mask, cb) {
  26566. let byteLength;
  26567. let readOnly;
  26568. if (typeof data === 'string') {
  26569. byteLength = Buffer.byteLength(data);
  26570. readOnly = false;
  26571. } else if (isBlob$1(data)) {
  26572. byteLength = data.size;
  26573. readOnly = false;
  26574. } else {
  26575. data = toBuffer$1(data);
  26576. byteLength = data.length;
  26577. readOnly = toBuffer$1.readOnly;
  26578. }
  26579. if (byteLength > 125) {
  26580. throw new RangeError('The data size must not be greater than 125 bytes');
  26581. }
  26582. const options = {
  26583. [kByteLength]: byteLength,
  26584. fin: true,
  26585. generateMask: this._generateMask,
  26586. mask,
  26587. maskBuffer: this._maskBuffer,
  26588. opcode: 0x09,
  26589. readOnly,
  26590. rsv1: false
  26591. };
  26592. if (isBlob$1(data)) {
  26593. if (this._state !== DEFAULT) {
  26594. this.enqueue([this.getBlobData, data, false, options, cb]);
  26595. } else {
  26596. this.getBlobData(data, false, options, cb);
  26597. }
  26598. } else if (this._state !== DEFAULT) {
  26599. this.enqueue([this.dispatch, data, false, options, cb]);
  26600. } else {
  26601. this.sendFrame(Sender.frame(data, options), cb);
  26602. }
  26603. }
  26604. /**
  26605. * Sends a pong message to the other peer.
  26606. *
  26607. * @param {*} data The message to send
  26608. * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
  26609. * @param {Function} [cb] Callback
  26610. * @public
  26611. */
  26612. pong(data, mask, cb) {
  26613. let byteLength;
  26614. let readOnly;
  26615. if (typeof data === 'string') {
  26616. byteLength = Buffer.byteLength(data);
  26617. readOnly = false;
  26618. } else if (isBlob$1(data)) {
  26619. byteLength = data.size;
  26620. readOnly = false;
  26621. } else {
  26622. data = toBuffer$1(data);
  26623. byteLength = data.length;
  26624. readOnly = toBuffer$1.readOnly;
  26625. }
  26626. if (byteLength > 125) {
  26627. throw new RangeError('The data size must not be greater than 125 bytes');
  26628. }
  26629. const options = {
  26630. [kByteLength]: byteLength,
  26631. fin: true,
  26632. generateMask: this._generateMask,
  26633. mask,
  26634. maskBuffer: this._maskBuffer,
  26635. opcode: 0x0a,
  26636. readOnly,
  26637. rsv1: false
  26638. };
  26639. if (isBlob$1(data)) {
  26640. if (this._state !== DEFAULT) {
  26641. this.enqueue([this.getBlobData, data, false, options, cb]);
  26642. } else {
  26643. this.getBlobData(data, false, options, cb);
  26644. }
  26645. } else if (this._state !== DEFAULT) {
  26646. this.enqueue([this.dispatch, data, false, options, cb]);
  26647. } else {
  26648. this.sendFrame(Sender.frame(data, options), cb);
  26649. }
  26650. }
  26651. /**
  26652. * Sends a data message to the other peer.
  26653. *
  26654. * @param {*} data The message to send
  26655. * @param {Object} options Options object
  26656. * @param {Boolean} [options.binary=false] Specifies whether `data` is binary
  26657. * or text
  26658. * @param {Boolean} [options.compress=false] Specifies whether or not to
  26659. * compress `data`
  26660. * @param {Boolean} [options.fin=false] Specifies whether the fragment is the
  26661. * last one
  26662. * @param {Boolean} [options.mask=false] Specifies whether or not to mask
  26663. * `data`
  26664. * @param {Function} [cb] Callback
  26665. * @public
  26666. */
  26667. send(data, options, cb) {
  26668. const perMessageDeflate = this._extensions[PerMessageDeflate$2.extensionName];
  26669. let opcode = options.binary ? 2 : 1;
  26670. let rsv1 = options.compress;
  26671. let byteLength;
  26672. let readOnly;
  26673. if (typeof data === 'string') {
  26674. byteLength = Buffer.byteLength(data);
  26675. readOnly = false;
  26676. } else if (isBlob$1(data)) {
  26677. byteLength = data.size;
  26678. readOnly = false;
  26679. } else {
  26680. data = toBuffer$1(data);
  26681. byteLength = data.length;
  26682. readOnly = toBuffer$1.readOnly;
  26683. }
  26684. if (this._firstFragment) {
  26685. this._firstFragment = false;
  26686. if (
  26687. rsv1 &&
  26688. perMessageDeflate &&
  26689. perMessageDeflate.params[
  26690. perMessageDeflate._isServer
  26691. ? 'server_no_context_takeover'
  26692. : 'client_no_context_takeover'
  26693. ]
  26694. ) {
  26695. rsv1 = byteLength >= perMessageDeflate._threshold;
  26696. }
  26697. this._compress = rsv1;
  26698. } else {
  26699. rsv1 = false;
  26700. opcode = 0;
  26701. }
  26702. if (options.fin) this._firstFragment = true;
  26703. const opts = {
  26704. [kByteLength]: byteLength,
  26705. fin: options.fin,
  26706. generateMask: this._generateMask,
  26707. mask: options.mask,
  26708. maskBuffer: this._maskBuffer,
  26709. opcode,
  26710. readOnly,
  26711. rsv1
  26712. };
  26713. if (isBlob$1(data)) {
  26714. if (this._state !== DEFAULT) {
  26715. this.enqueue([this.getBlobData, data, this._compress, opts, cb]);
  26716. } else {
  26717. this.getBlobData(data, this._compress, opts, cb);
  26718. }
  26719. } else if (this._state !== DEFAULT) {
  26720. this.enqueue([this.dispatch, data, this._compress, opts, cb]);
  26721. } else {
  26722. this.dispatch(data, this._compress, opts, cb);
  26723. }
  26724. }
  26725. /**
  26726. * Gets the contents of a blob as binary data.
  26727. *
  26728. * @param {Blob} blob The blob
  26729. * @param {Boolean} [compress=false] Specifies whether or not to compress
  26730. * the data
  26731. * @param {Object} options Options object
  26732. * @param {Boolean} [options.fin=false] Specifies whether or not to set the
  26733. * FIN bit
  26734. * @param {Function} [options.generateMask] The function used to generate the
  26735. * masking key
  26736. * @param {Boolean} [options.mask=false] Specifies whether or not to mask
  26737. * `data`
  26738. * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
  26739. * key
  26740. * @param {Number} options.opcode The opcode
  26741. * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
  26742. * modified
  26743. * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
  26744. * RSV1 bit
  26745. * @param {Function} [cb] Callback
  26746. * @private
  26747. */
  26748. getBlobData(blob, compress, options, cb) {
  26749. this._bufferedBytes += options[kByteLength];
  26750. this._state = GET_BLOB_DATA;
  26751. blob
  26752. .arrayBuffer()
  26753. .then((arrayBuffer) => {
  26754. if (this._socket.destroyed) {
  26755. const err = new Error(
  26756. 'The socket was closed while the blob was being read'
  26757. );
  26758. //
  26759. // `callCallbacks` is called in the next tick to ensure that errors
  26760. // that might be thrown in the callbacks behave like errors thrown
  26761. // outside the promise chain.
  26762. //
  26763. process.nextTick(callCallbacks, this, err, cb);
  26764. return;
  26765. }
  26766. this._bufferedBytes -= options[kByteLength];
  26767. const data = toBuffer$1(arrayBuffer);
  26768. if (!compress) {
  26769. this._state = DEFAULT;
  26770. this.sendFrame(Sender.frame(data, options), cb);
  26771. this.dequeue();
  26772. } else {
  26773. this.dispatch(data, compress, options, cb);
  26774. }
  26775. })
  26776. .catch((err) => {
  26777. //
  26778. // `onError` is called in the next tick for the same reason that
  26779. // `callCallbacks` above is.
  26780. //
  26781. process.nextTick(onError, this, err, cb);
  26782. });
  26783. }
  26784. /**
  26785. * Dispatches a message.
  26786. *
  26787. * @param {(Buffer|String)} data The message to send
  26788. * @param {Boolean} [compress=false] Specifies whether or not to compress
  26789. * `data`
  26790. * @param {Object} options Options object
  26791. * @param {Boolean} [options.fin=false] Specifies whether or not to set the
  26792. * FIN bit
  26793. * @param {Function} [options.generateMask] The function used to generate the
  26794. * masking key
  26795. * @param {Boolean} [options.mask=false] Specifies whether or not to mask
  26796. * `data`
  26797. * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
  26798. * key
  26799. * @param {Number} options.opcode The opcode
  26800. * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
  26801. * modified
  26802. * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
  26803. * RSV1 bit
  26804. * @param {Function} [cb] Callback
  26805. * @private
  26806. */
  26807. dispatch(data, compress, options, cb) {
  26808. if (!compress) {
  26809. this.sendFrame(Sender.frame(data, options), cb);
  26810. return;
  26811. }
  26812. const perMessageDeflate = this._extensions[PerMessageDeflate$2.extensionName];
  26813. this._bufferedBytes += options[kByteLength];
  26814. this._state = DEFLATING;
  26815. perMessageDeflate.compress(data, options.fin, (_, buf) => {
  26816. if (this._socket.destroyed) {
  26817. const err = new Error(
  26818. 'The socket was closed while data was being compressed'
  26819. );
  26820. callCallbacks(this, err, cb);
  26821. return;
  26822. }
  26823. this._bufferedBytes -= options[kByteLength];
  26824. this._state = DEFAULT;
  26825. options.readOnly = false;
  26826. this.sendFrame(Sender.frame(buf, options), cb);
  26827. this.dequeue();
  26828. });
  26829. }
  26830. /**
  26831. * Executes queued send operations.
  26832. *
  26833. * @private
  26834. */
  26835. dequeue() {
  26836. while (this._state === DEFAULT && this._queue.length) {
  26837. const params = this._queue.shift();
  26838. this._bufferedBytes -= params[3][kByteLength];
  26839. Reflect.apply(params[0], this, params.slice(1));
  26840. }
  26841. }
  26842. /**
  26843. * Enqueues a send operation.
  26844. *
  26845. * @param {Array} params Send operation parameters.
  26846. * @private
  26847. */
  26848. enqueue(params) {
  26849. this._bufferedBytes += params[3][kByteLength];
  26850. this._queue.push(params);
  26851. }
  26852. /**
  26853. * Sends a frame.
  26854. *
  26855. * @param {(Buffer | String)[]} list The frame to send
  26856. * @param {Function} [cb] Callback
  26857. * @private
  26858. */
  26859. sendFrame(list, cb) {
  26860. if (list.length === 2) {
  26861. this._socket.cork();
  26862. this._socket.write(list[0]);
  26863. this._socket.write(list[1], cb);
  26864. this._socket.uncork();
  26865. } else {
  26866. this._socket.write(list[0], cb);
  26867. }
  26868. }
  26869. };
  26870. var sender = Sender$1;
  26871. /**
  26872. * Calls queued callbacks with an error.
  26873. *
  26874. * @param {Sender} sender The `Sender` instance
  26875. * @param {Error} err The error to call the callbacks with
  26876. * @param {Function} [cb] The first callback
  26877. * @private
  26878. */
  26879. function callCallbacks(sender, err, cb) {
  26880. if (typeof cb === 'function') cb(err);
  26881. for (let i = 0; i < sender._queue.length; i++) {
  26882. const params = sender._queue[i];
  26883. const callback = params[params.length - 1];
  26884. if (typeof callback === 'function') callback(err);
  26885. }
  26886. }
  26887. /**
  26888. * Handles a `Sender` error.
  26889. *
  26890. * @param {Sender} sender The `Sender` instance
  26891. * @param {Error} err The error
  26892. * @param {Function} [cb] The first pending callback
  26893. * @private
  26894. */
  26895. function onError(sender, err, cb) {
  26896. callCallbacks(sender, err, cb);
  26897. sender.onerror(err);
  26898. }
  26899. const { kForOnEventAttribute: kForOnEventAttribute$1, kListener: kListener$1 } = constants;
  26900. const kCode = Symbol('kCode');
  26901. const kData = Symbol('kData');
  26902. const kError = Symbol('kError');
  26903. const kMessage = Symbol('kMessage');
  26904. const kReason = Symbol('kReason');
  26905. const kTarget = Symbol('kTarget');
  26906. const kType = Symbol('kType');
  26907. const kWasClean = Symbol('kWasClean');
  26908. /**
  26909. * Class representing an event.
  26910. */
  26911. let Event$1 = class Event {
  26912. /**
  26913. * Create a new `Event`.
  26914. *
  26915. * @param {String} type The name of the event
  26916. * @throws {TypeError} If the `type` argument is not specified
  26917. */
  26918. constructor(type) {
  26919. this[kTarget] = null;
  26920. this[kType] = type;
  26921. }
  26922. /**
  26923. * @type {*}
  26924. */
  26925. get target() {
  26926. return this[kTarget];
  26927. }
  26928. /**
  26929. * @type {String}
  26930. */
  26931. get type() {
  26932. return this[kType];
  26933. }
  26934. };
  26935. Object.defineProperty(Event$1.prototype, 'target', { enumerable: true });
  26936. Object.defineProperty(Event$1.prototype, 'type', { enumerable: true });
  26937. /**
  26938. * Class representing a close event.
  26939. *
  26940. * @extends Event
  26941. */
  26942. class CloseEvent extends Event$1 {
  26943. /**
  26944. * Create a new `CloseEvent`.
  26945. *
  26946. * @param {String} type The name of the event
  26947. * @param {Object} [options] A dictionary object that allows for setting
  26948. * attributes via object members of the same name
  26949. * @param {Number} [options.code=0] The status code explaining why the
  26950. * connection was closed
  26951. * @param {String} [options.reason=''] A human-readable string explaining why
  26952. * the connection was closed
  26953. * @param {Boolean} [options.wasClean=false] Indicates whether or not the
  26954. * connection was cleanly closed
  26955. */
  26956. constructor(type, options = {}) {
  26957. super(type);
  26958. this[kCode] = options.code === undefined ? 0 : options.code;
  26959. this[kReason] = options.reason === undefined ? '' : options.reason;
  26960. this[kWasClean] = options.wasClean === undefined ? false : options.wasClean;
  26961. }
  26962. /**
  26963. * @type {Number}
  26964. */
  26965. get code() {
  26966. return this[kCode];
  26967. }
  26968. /**
  26969. * @type {String}
  26970. */
  26971. get reason() {
  26972. return this[kReason];
  26973. }
  26974. /**
  26975. * @type {Boolean}
  26976. */
  26977. get wasClean() {
  26978. return this[kWasClean];
  26979. }
  26980. }
  26981. Object.defineProperty(CloseEvent.prototype, 'code', { enumerable: true });
  26982. Object.defineProperty(CloseEvent.prototype, 'reason', { enumerable: true });
  26983. Object.defineProperty(CloseEvent.prototype, 'wasClean', { enumerable: true });
  26984. /**
  26985. * Class representing an error event.
  26986. *
  26987. * @extends Event
  26988. */
  26989. class ErrorEvent extends Event$1 {
  26990. /**
  26991. * Create a new `ErrorEvent`.
  26992. *
  26993. * @param {String} type The name of the event
  26994. * @param {Object} [options] A dictionary object that allows for setting
  26995. * attributes via object members of the same name
  26996. * @param {*} [options.error=null] The error that generated this event
  26997. * @param {String} [options.message=''] The error message
  26998. */
  26999. constructor(type, options = {}) {
  27000. super(type);
  27001. this[kError] = options.error === undefined ? null : options.error;
  27002. this[kMessage] = options.message === undefined ? '' : options.message;
  27003. }
  27004. /**
  27005. * @type {*}
  27006. */
  27007. get error() {
  27008. return this[kError];
  27009. }
  27010. /**
  27011. * @type {String}
  27012. */
  27013. get message() {
  27014. return this[kMessage];
  27015. }
  27016. }
  27017. Object.defineProperty(ErrorEvent.prototype, 'error', { enumerable: true });
  27018. Object.defineProperty(ErrorEvent.prototype, 'message', { enumerable: true });
  27019. /**
  27020. * Class representing a message event.
  27021. *
  27022. * @extends Event
  27023. */
  27024. class MessageEvent extends Event$1 {
  27025. /**
  27026. * Create a new `MessageEvent`.
  27027. *
  27028. * @param {String} type The name of the event
  27029. * @param {Object} [options] A dictionary object that allows for setting
  27030. * attributes via object members of the same name
  27031. * @param {*} [options.data=null] The message content
  27032. */
  27033. constructor(type, options = {}) {
  27034. super(type);
  27035. this[kData] = options.data === undefined ? null : options.data;
  27036. }
  27037. /**
  27038. * @type {*}
  27039. */
  27040. get data() {
  27041. return this[kData];
  27042. }
  27043. }
  27044. Object.defineProperty(MessageEvent.prototype, 'data', { enumerable: true });
  27045. /**
  27046. * This provides methods for emulating the `EventTarget` interface. It's not
  27047. * meant to be used directly.
  27048. *
  27049. * @mixin
  27050. */
  27051. const EventTarget = {
  27052. /**
  27053. * Register an event listener.
  27054. *
  27055. * @param {String} type A string representing the event type to listen for
  27056. * @param {(Function|Object)} handler The listener to add
  27057. * @param {Object} [options] An options object specifies characteristics about
  27058. * the event listener
  27059. * @param {Boolean} [options.once=false] A `Boolean` indicating that the
  27060. * listener should be invoked at most once after being added. If `true`,
  27061. * the listener would be automatically removed when invoked.
  27062. * @public
  27063. */
  27064. addEventListener(type, handler, options = {}) {
  27065. for (const listener of this.listeners(type)) {
  27066. if (
  27067. !options[kForOnEventAttribute$1] &&
  27068. listener[kListener$1] === handler &&
  27069. !listener[kForOnEventAttribute$1]
  27070. ) {
  27071. return;
  27072. }
  27073. }
  27074. let wrapper;
  27075. if (type === 'message') {
  27076. wrapper = function onMessage(data, isBinary) {
  27077. const event = new MessageEvent('message', {
  27078. data: isBinary ? data : data.toString()
  27079. });
  27080. event[kTarget] = this;
  27081. callListener(handler, this, event);
  27082. };
  27083. } else if (type === 'close') {
  27084. wrapper = function onClose(code, message) {
  27085. const event = new CloseEvent('close', {
  27086. code,
  27087. reason: message.toString(),
  27088. wasClean: this._closeFrameReceived && this._closeFrameSent
  27089. });
  27090. event[kTarget] = this;
  27091. callListener(handler, this, event);
  27092. };
  27093. } else if (type === 'error') {
  27094. wrapper = function onError(error) {
  27095. const event = new ErrorEvent('error', {
  27096. error,
  27097. message: error.message
  27098. });
  27099. event[kTarget] = this;
  27100. callListener(handler, this, event);
  27101. };
  27102. } else if (type === 'open') {
  27103. wrapper = function onOpen() {
  27104. const event = new Event$1('open');
  27105. event[kTarget] = this;
  27106. callListener(handler, this, event);
  27107. };
  27108. } else {
  27109. return;
  27110. }
  27111. wrapper[kForOnEventAttribute$1] = !!options[kForOnEventAttribute$1];
  27112. wrapper[kListener$1] = handler;
  27113. if (options.once) {
  27114. this.once(type, wrapper);
  27115. } else {
  27116. this.on(type, wrapper);
  27117. }
  27118. },
  27119. /**
  27120. * Remove an event listener.
  27121. *
  27122. * @param {String} type A string representing the event type to remove
  27123. * @param {(Function|Object)} handler The listener to remove
  27124. * @public
  27125. */
  27126. removeEventListener(type, handler) {
  27127. for (const listener of this.listeners(type)) {
  27128. if (listener[kListener$1] === handler && !listener[kForOnEventAttribute$1]) {
  27129. this.removeListener(type, listener);
  27130. break;
  27131. }
  27132. }
  27133. }
  27134. };
  27135. var eventTarget = {
  27136. EventTarget};
  27137. /**
  27138. * Call an event listener
  27139. *
  27140. * @param {(Function|Object)} listener The listener to call
  27141. * @param {*} thisArg The value to use as `this`` when calling the listener
  27142. * @param {Event} event The event to pass to the listener
  27143. * @private
  27144. */
  27145. function callListener(listener, thisArg, event) {
  27146. if (typeof listener === 'object' && listener.handleEvent) {
  27147. listener.handleEvent.call(listener, event);
  27148. } else {
  27149. listener.call(thisArg, event);
  27150. }
  27151. }
  27152. const { tokenChars: tokenChars$1 } = validationExports;
  27153. /**
  27154. * Adds an offer to the map of extension offers or a parameter to the map of
  27155. * parameters.
  27156. *
  27157. * @param {Object} dest The map of extension offers or parameters
  27158. * @param {String} name The extension or parameter name
  27159. * @param {(Object|Boolean|String)} elem The extension parameters or the
  27160. * parameter value
  27161. * @private
  27162. */
  27163. function push(dest, name, elem) {
  27164. if (dest[name] === undefined) dest[name] = [elem];
  27165. else dest[name].push(elem);
  27166. }
  27167. /**
  27168. * Parses the `Sec-WebSocket-Extensions` header into an object.
  27169. *
  27170. * @param {String} header The field value of the header
  27171. * @return {Object} The parsed object
  27172. * @public
  27173. */
  27174. function parse$3(header) {
  27175. const offers = Object.create(null);
  27176. let params = Object.create(null);
  27177. let mustUnescape = false;
  27178. let isEscaping = false;
  27179. let inQuotes = false;
  27180. let extensionName;
  27181. let paramName;
  27182. let start = -1;
  27183. let code = -1;
  27184. let end = -1;
  27185. let i = 0;
  27186. for (; i < header.length; i++) {
  27187. code = header.charCodeAt(i);
  27188. if (extensionName === undefined) {
  27189. if (end === -1 && tokenChars$1[code] === 1) {
  27190. if (start === -1) start = i;
  27191. } else if (
  27192. i !== 0 &&
  27193. (code === 0x20 /* ' ' */ || code === 0x09) /* '\t' */
  27194. ) {
  27195. if (end === -1 && start !== -1) end = i;
  27196. } else if (code === 0x3b /* ';' */ || code === 0x2c /* ',' */) {
  27197. if (start === -1) {
  27198. throw new SyntaxError(`Unexpected character at index ${i}`);
  27199. }
  27200. if (end === -1) end = i;
  27201. const name = header.slice(start, end);
  27202. if (code === 0x2c) {
  27203. push(offers, name, params);
  27204. params = Object.create(null);
  27205. } else {
  27206. extensionName = name;
  27207. }
  27208. start = end = -1;
  27209. } else {
  27210. throw new SyntaxError(`Unexpected character at index ${i}`);
  27211. }
  27212. } else if (paramName === undefined) {
  27213. if (end === -1 && tokenChars$1[code] === 1) {
  27214. if (start === -1) start = i;
  27215. } else if (code === 0x20 || code === 0x09) {
  27216. if (end === -1 && start !== -1) end = i;
  27217. } else if (code === 0x3b || code === 0x2c) {
  27218. if (start === -1) {
  27219. throw new SyntaxError(`Unexpected character at index ${i}`);
  27220. }
  27221. if (end === -1) end = i;
  27222. push(params, header.slice(start, end), true);
  27223. if (code === 0x2c) {
  27224. push(offers, extensionName, params);
  27225. params = Object.create(null);
  27226. extensionName = undefined;
  27227. }
  27228. start = end = -1;
  27229. } else if (code === 0x3d /* '=' */ && start !== -1 && end === -1) {
  27230. paramName = header.slice(start, i);
  27231. start = end = -1;
  27232. } else {
  27233. throw new SyntaxError(`Unexpected character at index ${i}`);
  27234. }
  27235. } else {
  27236. //
  27237. // The value of a quoted-string after unescaping must conform to the
  27238. // token ABNF, so only token characters are valid.
  27239. // Ref: https://tools.ietf.org/html/rfc6455#section-9.1
  27240. //
  27241. if (isEscaping) {
  27242. if (tokenChars$1[code] !== 1) {
  27243. throw new SyntaxError(`Unexpected character at index ${i}`);
  27244. }
  27245. if (start === -1) start = i;
  27246. else if (!mustUnescape) mustUnescape = true;
  27247. isEscaping = false;
  27248. } else if (inQuotes) {
  27249. if (tokenChars$1[code] === 1) {
  27250. if (start === -1) start = i;
  27251. } else if (code === 0x22 /* '"' */ && start !== -1) {
  27252. inQuotes = false;
  27253. end = i;
  27254. } else if (code === 0x5c /* '\' */) {
  27255. isEscaping = true;
  27256. } else {
  27257. throw new SyntaxError(`Unexpected character at index ${i}`);
  27258. }
  27259. } else if (code === 0x22 && header.charCodeAt(i - 1) === 0x3d) {
  27260. inQuotes = true;
  27261. } else if (end === -1 && tokenChars$1[code] === 1) {
  27262. if (start === -1) start = i;
  27263. } else if (start !== -1 && (code === 0x20 || code === 0x09)) {
  27264. if (end === -1) end = i;
  27265. } else if (code === 0x3b || code === 0x2c) {
  27266. if (start === -1) {
  27267. throw new SyntaxError(`Unexpected character at index ${i}`);
  27268. }
  27269. if (end === -1) end = i;
  27270. let value = header.slice(start, end);
  27271. if (mustUnescape) {
  27272. value = value.replace(/\\/g, '');
  27273. mustUnescape = false;
  27274. }
  27275. push(params, paramName, value);
  27276. if (code === 0x2c) {
  27277. push(offers, extensionName, params);
  27278. params = Object.create(null);
  27279. extensionName = undefined;
  27280. }
  27281. paramName = undefined;
  27282. start = end = -1;
  27283. } else {
  27284. throw new SyntaxError(`Unexpected character at index ${i}`);
  27285. }
  27286. }
  27287. }
  27288. if (start === -1 || inQuotes || code === 0x20 || code === 0x09) {
  27289. throw new SyntaxError('Unexpected end of input');
  27290. }
  27291. if (end === -1) end = i;
  27292. const token = header.slice(start, end);
  27293. if (extensionName === undefined) {
  27294. push(offers, token, params);
  27295. } else {
  27296. if (paramName === undefined) {
  27297. push(params, token, true);
  27298. } else if (mustUnescape) {
  27299. push(params, paramName, token.replace(/\\/g, ''));
  27300. } else {
  27301. push(params, paramName, token);
  27302. }
  27303. push(offers, extensionName, params);
  27304. }
  27305. return offers;
  27306. }
  27307. /**
  27308. * Builds the `Sec-WebSocket-Extensions` header field value.
  27309. *
  27310. * @param {Object} extensions The map of extensions and parameters to format
  27311. * @return {String} A string representing the given object
  27312. * @public
  27313. */
  27314. function format$1(extensions) {
  27315. return Object.keys(extensions)
  27316. .map((extension) => {
  27317. let configurations = extensions[extension];
  27318. if (!Array.isArray(configurations)) configurations = [configurations];
  27319. return configurations
  27320. .map((params) => {
  27321. return [extension]
  27322. .concat(
  27323. Object.keys(params).map((k) => {
  27324. let values = params[k];
  27325. if (!Array.isArray(values)) values = [values];
  27326. return values
  27327. .map((v) => (v === true ? k : `${k}=${v}`))
  27328. .join('; ');
  27329. })
  27330. )
  27331. .join('; ');
  27332. })
  27333. .join(', ');
  27334. })
  27335. .join(', ');
  27336. }
  27337. var extension$1 = { format: format$1, parse: parse$3 };
  27338. /* eslint no-unused-vars: ["error", { "varsIgnorePattern": "^Duplex|Readable$", "caughtErrors": "none" }] */
  27339. const EventEmitter$1 = require$$0$7;
  27340. const https$2 = require$$1$3;
  27341. const http$3 = require$$1$2;
  27342. const net = require$$4$1;
  27343. const tls = require$$4$2;
  27344. const { randomBytes, createHash: createHash$1 } = require$$3;
  27345. const { URL: URL$2 } = require$$0$5;
  27346. const PerMessageDeflate$1 = permessageDeflate;
  27347. const Receiver = receiver;
  27348. const Sender = sender;
  27349. const { isBlob } = validationExports;
  27350. const {
  27351. BINARY_TYPES,
  27352. EMPTY_BUFFER,
  27353. GUID: GUID$1,
  27354. kForOnEventAttribute,
  27355. kListener,
  27356. kStatusCode,
  27357. kWebSocket: kWebSocket$1,
  27358. NOOP: NOOP$1
  27359. } = constants;
  27360. const {
  27361. EventTarget: { addEventListener, removeEventListener }
  27362. } = eventTarget;
  27363. const { format, parse: parse$2 } = extension$1;
  27364. const { toBuffer } = bufferUtilExports;
  27365. const closeTimeout = 30 * 1000;
  27366. const kAborted = Symbol('kAborted');
  27367. const protocolVersions = [8, 13];
  27368. const readyStates = ['CONNECTING', 'OPEN', 'CLOSING', 'CLOSED'];
  27369. const subprotocolRegex = /^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;
  27370. /**
  27371. * Class representing a WebSocket.
  27372. *
  27373. * @extends EventEmitter
  27374. */
  27375. let WebSocket$1 = class WebSocket extends EventEmitter$1 {
  27376. /**
  27377. * Create a new `WebSocket`.
  27378. *
  27379. * @param {(String|URL)} address The URL to which to connect
  27380. * @param {(String|String[])} [protocols] The subprotocols
  27381. * @param {Object} [options] Connection options
  27382. */
  27383. constructor(address, protocols, options) {
  27384. super();
  27385. this._binaryType = BINARY_TYPES[0];
  27386. this._closeCode = 1006;
  27387. this._closeFrameReceived = false;
  27388. this._closeFrameSent = false;
  27389. this._closeMessage = EMPTY_BUFFER;
  27390. this._closeTimer = null;
  27391. this._errorEmitted = false;
  27392. this._extensions = {};
  27393. this._paused = false;
  27394. this._protocol = '';
  27395. this._readyState = WebSocket.CONNECTING;
  27396. this._receiver = null;
  27397. this._sender = null;
  27398. this._socket = null;
  27399. if (address !== null) {
  27400. this._bufferedAmount = 0;
  27401. this._isServer = false;
  27402. this._redirects = 0;
  27403. if (protocols === undefined) {
  27404. protocols = [];
  27405. } else if (!Array.isArray(protocols)) {
  27406. if (typeof protocols === 'object' && protocols !== null) {
  27407. options = protocols;
  27408. protocols = [];
  27409. } else {
  27410. protocols = [protocols];
  27411. }
  27412. }
  27413. initAsClient(this, address, protocols, options);
  27414. } else {
  27415. this._autoPong = options.autoPong;
  27416. this._isServer = true;
  27417. }
  27418. }
  27419. /**
  27420. * For historical reasons, the custom "nodebuffer" type is used by the default
  27421. * instead of "blob".
  27422. *
  27423. * @type {String}
  27424. */
  27425. get binaryType() {
  27426. return this._binaryType;
  27427. }
  27428. set binaryType(type) {
  27429. if (!BINARY_TYPES.includes(type)) return;
  27430. this._binaryType = type;
  27431. //
  27432. // Allow to change `binaryType` on the fly.
  27433. //
  27434. if (this._receiver) this._receiver._binaryType = type;
  27435. }
  27436. /**
  27437. * @type {Number}
  27438. */
  27439. get bufferedAmount() {
  27440. if (!this._socket) return this._bufferedAmount;
  27441. return this._socket._writableState.length + this._sender._bufferedBytes;
  27442. }
  27443. /**
  27444. * @type {String}
  27445. */
  27446. get extensions() {
  27447. return Object.keys(this._extensions).join();
  27448. }
  27449. /**
  27450. * @type {Boolean}
  27451. */
  27452. get isPaused() {
  27453. return this._paused;
  27454. }
  27455. /**
  27456. * @type {Function}
  27457. */
  27458. /* istanbul ignore next */
  27459. get onclose() {
  27460. return null;
  27461. }
  27462. /**
  27463. * @type {Function}
  27464. */
  27465. /* istanbul ignore next */
  27466. get onerror() {
  27467. return null;
  27468. }
  27469. /**
  27470. * @type {Function}
  27471. */
  27472. /* istanbul ignore next */
  27473. get onopen() {
  27474. return null;
  27475. }
  27476. /**
  27477. * @type {Function}
  27478. */
  27479. /* istanbul ignore next */
  27480. get onmessage() {
  27481. return null;
  27482. }
  27483. /**
  27484. * @type {String}
  27485. */
  27486. get protocol() {
  27487. return this._protocol;
  27488. }
  27489. /**
  27490. * @type {Number}
  27491. */
  27492. get readyState() {
  27493. return this._readyState;
  27494. }
  27495. /**
  27496. * @type {String}
  27497. */
  27498. get url() {
  27499. return this._url;
  27500. }
  27501. /**
  27502. * Set up the socket and the internal resources.
  27503. *
  27504. * @param {Duplex} socket The network socket between the server and client
  27505. * @param {Buffer} head The first packet of the upgraded stream
  27506. * @param {Object} options Options object
  27507. * @param {Boolean} [options.allowSynchronousEvents=false] Specifies whether
  27508. * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
  27509. * multiple times in the same tick
  27510. * @param {Function} [options.generateMask] The function used to generate the
  27511. * masking key
  27512. * @param {Number} [options.maxPayload=0] The maximum allowed message size
  27513. * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
  27514. * not to skip UTF-8 validation for text and close messages
  27515. * @private
  27516. */
  27517. setSocket(socket, head, options) {
  27518. const receiver = new Receiver({
  27519. allowSynchronousEvents: options.allowSynchronousEvents,
  27520. binaryType: this.binaryType,
  27521. extensions: this._extensions,
  27522. isServer: this._isServer,
  27523. maxPayload: options.maxPayload,
  27524. skipUTF8Validation: options.skipUTF8Validation
  27525. });
  27526. const sender = new Sender(socket, this._extensions, options.generateMask);
  27527. this._receiver = receiver;
  27528. this._sender = sender;
  27529. this._socket = socket;
  27530. receiver[kWebSocket$1] = this;
  27531. sender[kWebSocket$1] = this;
  27532. socket[kWebSocket$1] = this;
  27533. receiver.on('conclude', receiverOnConclude);
  27534. receiver.on('drain', receiverOnDrain);
  27535. receiver.on('error', receiverOnError);
  27536. receiver.on('message', receiverOnMessage);
  27537. receiver.on('ping', receiverOnPing);
  27538. receiver.on('pong', receiverOnPong);
  27539. sender.onerror = senderOnError;
  27540. //
  27541. // These methods may not be available if `socket` is just a `Duplex`.
  27542. //
  27543. if (socket.setTimeout) socket.setTimeout(0);
  27544. if (socket.setNoDelay) socket.setNoDelay();
  27545. if (head.length > 0) socket.unshift(head);
  27546. socket.on('close', socketOnClose);
  27547. socket.on('data', socketOnData);
  27548. socket.on('end', socketOnEnd);
  27549. socket.on('error', socketOnError$1);
  27550. this._readyState = WebSocket.OPEN;
  27551. this.emit('open');
  27552. }
  27553. /**
  27554. * Emit the `'close'` event.
  27555. *
  27556. * @private
  27557. */
  27558. emitClose() {
  27559. if (!this._socket) {
  27560. this._readyState = WebSocket.CLOSED;
  27561. this.emit('close', this._closeCode, this._closeMessage);
  27562. return;
  27563. }
  27564. if (this._extensions[PerMessageDeflate$1.extensionName]) {
  27565. this._extensions[PerMessageDeflate$1.extensionName].cleanup();
  27566. }
  27567. this._receiver.removeAllListeners();
  27568. this._readyState = WebSocket.CLOSED;
  27569. this.emit('close', this._closeCode, this._closeMessage);
  27570. }
  27571. /**
  27572. * Start a closing handshake.
  27573. *
  27574. * +----------+ +-----------+ +----------+
  27575. * - - -|ws.close()|-->|close frame|-->|ws.close()|- - -
  27576. * | +----------+ +-----------+ +----------+ |
  27577. * +----------+ +-----------+ |
  27578. * CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING
  27579. * +----------+ +-----------+ |
  27580. * | | | +---+ |
  27581. * +------------------------+-->|fin| - - - -
  27582. * | +---+ | +---+
  27583. * - - - - -|fin|<---------------------+
  27584. * +---+
  27585. *
  27586. * @param {Number} [code] Status code explaining why the connection is closing
  27587. * @param {(String|Buffer)} [data] The reason why the connection is
  27588. * closing
  27589. * @public
  27590. */
  27591. close(code, data) {
  27592. if (this.readyState === WebSocket.CLOSED) return;
  27593. if (this.readyState === WebSocket.CONNECTING) {
  27594. const msg = 'WebSocket was closed before the connection was established';
  27595. abortHandshake$1(this, this._req, msg);
  27596. return;
  27597. }
  27598. if (this.readyState === WebSocket.CLOSING) {
  27599. if (
  27600. this._closeFrameSent &&
  27601. (this._closeFrameReceived || this._receiver._writableState.errorEmitted)
  27602. ) {
  27603. this._socket.end();
  27604. }
  27605. return;
  27606. }
  27607. this._readyState = WebSocket.CLOSING;
  27608. this._sender.close(code, data, !this._isServer, (err) => {
  27609. //
  27610. // This error is handled by the `'error'` listener on the socket. We only
  27611. // want to know if the close frame has been sent here.
  27612. //
  27613. if (err) return;
  27614. this._closeFrameSent = true;
  27615. if (
  27616. this._closeFrameReceived ||
  27617. this._receiver._writableState.errorEmitted
  27618. ) {
  27619. this._socket.end();
  27620. }
  27621. });
  27622. setCloseTimer(this);
  27623. }
  27624. /**
  27625. * Pause the socket.
  27626. *
  27627. * @public
  27628. */
  27629. pause() {
  27630. if (
  27631. this.readyState === WebSocket.CONNECTING ||
  27632. this.readyState === WebSocket.CLOSED
  27633. ) {
  27634. return;
  27635. }
  27636. this._paused = true;
  27637. this._socket.pause();
  27638. }
  27639. /**
  27640. * Send a ping.
  27641. *
  27642. * @param {*} [data] The data to send
  27643. * @param {Boolean} [mask] Indicates whether or not to mask `data`
  27644. * @param {Function} [cb] Callback which is executed when the ping is sent
  27645. * @public
  27646. */
  27647. ping(data, mask, cb) {
  27648. if (this.readyState === WebSocket.CONNECTING) {
  27649. throw new Error('WebSocket is not open: readyState 0 (CONNECTING)');
  27650. }
  27651. if (typeof data === 'function') {
  27652. cb = data;
  27653. data = mask = undefined;
  27654. } else if (typeof mask === 'function') {
  27655. cb = mask;
  27656. mask = undefined;
  27657. }
  27658. if (typeof data === 'number') data = data.toString();
  27659. if (this.readyState !== WebSocket.OPEN) {
  27660. sendAfterClose(this, data, cb);
  27661. return;
  27662. }
  27663. if (mask === undefined) mask = !this._isServer;
  27664. this._sender.ping(data || EMPTY_BUFFER, mask, cb);
  27665. }
  27666. /**
  27667. * Send a pong.
  27668. *
  27669. * @param {*} [data] The data to send
  27670. * @param {Boolean} [mask] Indicates whether or not to mask `data`
  27671. * @param {Function} [cb] Callback which is executed when the pong is sent
  27672. * @public
  27673. */
  27674. pong(data, mask, cb) {
  27675. if (this.readyState === WebSocket.CONNECTING) {
  27676. throw new Error('WebSocket is not open: readyState 0 (CONNECTING)');
  27677. }
  27678. if (typeof data === 'function') {
  27679. cb = data;
  27680. data = mask = undefined;
  27681. } else if (typeof mask === 'function') {
  27682. cb = mask;
  27683. mask = undefined;
  27684. }
  27685. if (typeof data === 'number') data = data.toString();
  27686. if (this.readyState !== WebSocket.OPEN) {
  27687. sendAfterClose(this, data, cb);
  27688. return;
  27689. }
  27690. if (mask === undefined) mask = !this._isServer;
  27691. this._sender.pong(data || EMPTY_BUFFER, mask, cb);
  27692. }
  27693. /**
  27694. * Resume the socket.
  27695. *
  27696. * @public
  27697. */
  27698. resume() {
  27699. if (
  27700. this.readyState === WebSocket.CONNECTING ||
  27701. this.readyState === WebSocket.CLOSED
  27702. ) {
  27703. return;
  27704. }
  27705. this._paused = false;
  27706. if (!this._receiver._writableState.needDrain) this._socket.resume();
  27707. }
  27708. /**
  27709. * Send a data message.
  27710. *
  27711. * @param {*} data The message to send
  27712. * @param {Object} [options] Options object
  27713. * @param {Boolean} [options.binary] Specifies whether `data` is binary or
  27714. * text
  27715. * @param {Boolean} [options.compress] Specifies whether or not to compress
  27716. * `data`
  27717. * @param {Boolean} [options.fin=true] Specifies whether the fragment is the
  27718. * last one
  27719. * @param {Boolean} [options.mask] Specifies whether or not to mask `data`
  27720. * @param {Function} [cb] Callback which is executed when data is written out
  27721. * @public
  27722. */
  27723. send(data, options, cb) {
  27724. if (this.readyState === WebSocket.CONNECTING) {
  27725. throw new Error('WebSocket is not open: readyState 0 (CONNECTING)');
  27726. }
  27727. if (typeof options === 'function') {
  27728. cb = options;
  27729. options = {};
  27730. }
  27731. if (typeof data === 'number') data = data.toString();
  27732. if (this.readyState !== WebSocket.OPEN) {
  27733. sendAfterClose(this, data, cb);
  27734. return;
  27735. }
  27736. const opts = {
  27737. binary: typeof data !== 'string',
  27738. mask: !this._isServer,
  27739. compress: true,
  27740. fin: true,
  27741. ...options
  27742. };
  27743. if (!this._extensions[PerMessageDeflate$1.extensionName]) {
  27744. opts.compress = false;
  27745. }
  27746. this._sender.send(data || EMPTY_BUFFER, opts, cb);
  27747. }
  27748. /**
  27749. * Forcibly close the connection.
  27750. *
  27751. * @public
  27752. */
  27753. terminate() {
  27754. if (this.readyState === WebSocket.CLOSED) return;
  27755. if (this.readyState === WebSocket.CONNECTING) {
  27756. const msg = 'WebSocket was closed before the connection was established';
  27757. abortHandshake$1(this, this._req, msg);
  27758. return;
  27759. }
  27760. if (this._socket) {
  27761. this._readyState = WebSocket.CLOSING;
  27762. this._socket.destroy();
  27763. }
  27764. }
  27765. };
  27766. /**
  27767. * @constant {Number} CONNECTING
  27768. * @memberof WebSocket
  27769. */
  27770. Object.defineProperty(WebSocket$1, 'CONNECTING', {
  27771. enumerable: true,
  27772. value: readyStates.indexOf('CONNECTING')
  27773. });
  27774. /**
  27775. * @constant {Number} CONNECTING
  27776. * @memberof WebSocket.prototype
  27777. */
  27778. Object.defineProperty(WebSocket$1.prototype, 'CONNECTING', {
  27779. enumerable: true,
  27780. value: readyStates.indexOf('CONNECTING')
  27781. });
  27782. /**
  27783. * @constant {Number} OPEN
  27784. * @memberof WebSocket
  27785. */
  27786. Object.defineProperty(WebSocket$1, 'OPEN', {
  27787. enumerable: true,
  27788. value: readyStates.indexOf('OPEN')
  27789. });
  27790. /**
  27791. * @constant {Number} OPEN
  27792. * @memberof WebSocket.prototype
  27793. */
  27794. Object.defineProperty(WebSocket$1.prototype, 'OPEN', {
  27795. enumerable: true,
  27796. value: readyStates.indexOf('OPEN')
  27797. });
  27798. /**
  27799. * @constant {Number} CLOSING
  27800. * @memberof WebSocket
  27801. */
  27802. Object.defineProperty(WebSocket$1, 'CLOSING', {
  27803. enumerable: true,
  27804. value: readyStates.indexOf('CLOSING')
  27805. });
  27806. /**
  27807. * @constant {Number} CLOSING
  27808. * @memberof WebSocket.prototype
  27809. */
  27810. Object.defineProperty(WebSocket$1.prototype, 'CLOSING', {
  27811. enumerable: true,
  27812. value: readyStates.indexOf('CLOSING')
  27813. });
  27814. /**
  27815. * @constant {Number} CLOSED
  27816. * @memberof WebSocket
  27817. */
  27818. Object.defineProperty(WebSocket$1, 'CLOSED', {
  27819. enumerable: true,
  27820. value: readyStates.indexOf('CLOSED')
  27821. });
  27822. /**
  27823. * @constant {Number} CLOSED
  27824. * @memberof WebSocket.prototype
  27825. */
  27826. Object.defineProperty(WebSocket$1.prototype, 'CLOSED', {
  27827. enumerable: true,
  27828. value: readyStates.indexOf('CLOSED')
  27829. });
  27830. [
  27831. 'binaryType',
  27832. 'bufferedAmount',
  27833. 'extensions',
  27834. 'isPaused',
  27835. 'protocol',
  27836. 'readyState',
  27837. 'url'
  27838. ].forEach((property) => {
  27839. Object.defineProperty(WebSocket$1.prototype, property, { enumerable: true });
  27840. });
  27841. //
  27842. // Add the `onopen`, `onerror`, `onclose`, and `onmessage` attributes.
  27843. // See https://html.spec.whatwg.org/multipage/comms.html#the-websocket-interface
  27844. //
  27845. ['open', 'error', 'close', 'message'].forEach((method) => {
  27846. Object.defineProperty(WebSocket$1.prototype, `on${method}`, {
  27847. enumerable: true,
  27848. get() {
  27849. for (const listener of this.listeners(method)) {
  27850. if (listener[kForOnEventAttribute]) return listener[kListener];
  27851. }
  27852. return null;
  27853. },
  27854. set(handler) {
  27855. for (const listener of this.listeners(method)) {
  27856. if (listener[kForOnEventAttribute]) {
  27857. this.removeListener(method, listener);
  27858. break;
  27859. }
  27860. }
  27861. if (typeof handler !== 'function') return;
  27862. this.addEventListener(method, handler, {
  27863. [kForOnEventAttribute]: true
  27864. });
  27865. }
  27866. });
  27867. });
  27868. WebSocket$1.prototype.addEventListener = addEventListener;
  27869. WebSocket$1.prototype.removeEventListener = removeEventListener;
  27870. var websocket = WebSocket$1;
  27871. /**
  27872. * Initialize a WebSocket client.
  27873. *
  27874. * @param {WebSocket} websocket The client to initialize
  27875. * @param {(String|URL)} address The URL to which to connect
  27876. * @param {Array} protocols The subprotocols
  27877. * @param {Object} [options] Connection options
  27878. * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether any
  27879. * of the `'message'`, `'ping'`, and `'pong'` events can be emitted multiple
  27880. * times in the same tick
  27881. * @param {Boolean} [options.autoPong=true] Specifies whether or not to
  27882. * automatically send a pong in response to a ping
  27883. * @param {Function} [options.finishRequest] A function which can be used to
  27884. * customize the headers of each http request before it is sent
  27885. * @param {Boolean} [options.followRedirects=false] Whether or not to follow
  27886. * redirects
  27887. * @param {Function} [options.generateMask] The function used to generate the
  27888. * masking key
  27889. * @param {Number} [options.handshakeTimeout] Timeout in milliseconds for the
  27890. * handshake request
  27891. * @param {Number} [options.maxPayload=104857600] The maximum allowed message
  27892. * size
  27893. * @param {Number} [options.maxRedirects=10] The maximum number of redirects
  27894. * allowed
  27895. * @param {String} [options.origin] Value of the `Origin` or
  27896. * `Sec-WebSocket-Origin` header
  27897. * @param {(Boolean|Object)} [options.perMessageDeflate=true] Enable/disable
  27898. * permessage-deflate
  27899. * @param {Number} [options.protocolVersion=13] Value of the
  27900. * `Sec-WebSocket-Version` header
  27901. * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
  27902. * not to skip UTF-8 validation for text and close messages
  27903. * @private
  27904. */
  27905. function initAsClient(websocket, address, protocols, options) {
  27906. const opts = {
  27907. allowSynchronousEvents: true,
  27908. autoPong: true,
  27909. protocolVersion: protocolVersions[1],
  27910. maxPayload: 100 * 1024 * 1024,
  27911. skipUTF8Validation: false,
  27912. perMessageDeflate: true,
  27913. followRedirects: false,
  27914. maxRedirects: 10,
  27915. ...options,
  27916. socketPath: undefined,
  27917. hostname: undefined,
  27918. protocol: undefined,
  27919. timeout: undefined,
  27920. method: 'GET',
  27921. host: undefined,
  27922. path: undefined,
  27923. port: undefined
  27924. };
  27925. websocket._autoPong = opts.autoPong;
  27926. if (!protocolVersions.includes(opts.protocolVersion)) {
  27927. throw new RangeError(
  27928. `Unsupported protocol version: ${opts.protocolVersion} ` +
  27929. `(supported versions: ${protocolVersions.join(', ')})`
  27930. );
  27931. }
  27932. let parsedUrl;
  27933. if (address instanceof URL$2) {
  27934. parsedUrl = address;
  27935. } else {
  27936. try {
  27937. parsedUrl = new URL$2(address);
  27938. } catch (e) {
  27939. throw new SyntaxError(`Invalid URL: ${address}`);
  27940. }
  27941. }
  27942. if (parsedUrl.protocol === 'http:') {
  27943. parsedUrl.protocol = 'ws:';
  27944. } else if (parsedUrl.protocol === 'https:') {
  27945. parsedUrl.protocol = 'wss:';
  27946. }
  27947. websocket._url = parsedUrl.href;
  27948. const isSecure = parsedUrl.protocol === 'wss:';
  27949. const isIpcUrl = parsedUrl.protocol === 'ws+unix:';
  27950. let invalidUrlMessage;
  27951. if (parsedUrl.protocol !== 'ws:' && !isSecure && !isIpcUrl) {
  27952. invalidUrlMessage =
  27953. 'The URL\'s protocol must be one of "ws:", "wss:", ' +
  27954. '"http:", "https", or "ws+unix:"';
  27955. } else if (isIpcUrl && !parsedUrl.pathname) {
  27956. invalidUrlMessage = "The URL's pathname is empty";
  27957. } else if (parsedUrl.hash) {
  27958. invalidUrlMessage = 'The URL contains a fragment identifier';
  27959. }
  27960. if (invalidUrlMessage) {
  27961. const err = new SyntaxError(invalidUrlMessage);
  27962. if (websocket._redirects === 0) {
  27963. throw err;
  27964. } else {
  27965. emitErrorAndClose(websocket, err);
  27966. return;
  27967. }
  27968. }
  27969. const defaultPort = isSecure ? 443 : 80;
  27970. const key = randomBytes(16).toString('base64');
  27971. const request = isSecure ? https$2.request : http$3.request;
  27972. const protocolSet = new Set();
  27973. let perMessageDeflate;
  27974. opts.createConnection =
  27975. opts.createConnection || (isSecure ? tlsConnect : netConnect);
  27976. opts.defaultPort = opts.defaultPort || defaultPort;
  27977. opts.port = parsedUrl.port || defaultPort;
  27978. opts.host = parsedUrl.hostname.startsWith('[')
  27979. ? parsedUrl.hostname.slice(1, -1)
  27980. : parsedUrl.hostname;
  27981. opts.headers = {
  27982. ...opts.headers,
  27983. 'Sec-WebSocket-Version': opts.protocolVersion,
  27984. 'Sec-WebSocket-Key': key,
  27985. Connection: 'Upgrade',
  27986. Upgrade: 'websocket'
  27987. };
  27988. opts.path = parsedUrl.pathname + parsedUrl.search;
  27989. opts.timeout = opts.handshakeTimeout;
  27990. if (opts.perMessageDeflate) {
  27991. perMessageDeflate = new PerMessageDeflate$1(
  27992. opts.perMessageDeflate !== true ? opts.perMessageDeflate : {},
  27993. false,
  27994. opts.maxPayload
  27995. );
  27996. opts.headers['Sec-WebSocket-Extensions'] = format({
  27997. [PerMessageDeflate$1.extensionName]: perMessageDeflate.offer()
  27998. });
  27999. }
  28000. if (protocols.length) {
  28001. for (const protocol of protocols) {
  28002. if (
  28003. typeof protocol !== 'string' ||
  28004. !subprotocolRegex.test(protocol) ||
  28005. protocolSet.has(protocol)
  28006. ) {
  28007. throw new SyntaxError(
  28008. 'An invalid or duplicated subprotocol was specified'
  28009. );
  28010. }
  28011. protocolSet.add(protocol);
  28012. }
  28013. opts.headers['Sec-WebSocket-Protocol'] = protocols.join(',');
  28014. }
  28015. if (opts.origin) {
  28016. if (opts.protocolVersion < 13) {
  28017. opts.headers['Sec-WebSocket-Origin'] = opts.origin;
  28018. } else {
  28019. opts.headers.Origin = opts.origin;
  28020. }
  28021. }
  28022. if (parsedUrl.username || parsedUrl.password) {
  28023. opts.auth = `${parsedUrl.username}:${parsedUrl.password}`;
  28024. }
  28025. if (isIpcUrl) {
  28026. const parts = opts.path.split(':');
  28027. opts.socketPath = parts[0];
  28028. opts.path = parts[1];
  28029. }
  28030. let req;
  28031. if (opts.followRedirects) {
  28032. if (websocket._redirects === 0) {
  28033. websocket._originalIpc = isIpcUrl;
  28034. websocket._originalSecure = isSecure;
  28035. websocket._originalHostOrSocketPath = isIpcUrl
  28036. ? opts.socketPath
  28037. : parsedUrl.host;
  28038. const headers = options && options.headers;
  28039. //
  28040. // Shallow copy the user provided options so that headers can be changed
  28041. // without mutating the original object.
  28042. //
  28043. options = { ...options, headers: {} };
  28044. if (headers) {
  28045. for (const [key, value] of Object.entries(headers)) {
  28046. options.headers[key.toLowerCase()] = value;
  28047. }
  28048. }
  28049. } else if (websocket.listenerCount('redirect') === 0) {
  28050. const isSameHost = isIpcUrl
  28051. ? websocket._originalIpc
  28052. ? opts.socketPath === websocket._originalHostOrSocketPath
  28053. : false
  28054. : websocket._originalIpc
  28055. ? false
  28056. : parsedUrl.host === websocket._originalHostOrSocketPath;
  28057. if (!isSameHost || (websocket._originalSecure && !isSecure)) {
  28058. //
  28059. // Match curl 7.77.0 behavior and drop the following headers. These
  28060. // headers are also dropped when following a redirect to a subdomain.
  28061. //
  28062. delete opts.headers.authorization;
  28063. delete opts.headers.cookie;
  28064. if (!isSameHost) delete opts.headers.host;
  28065. opts.auth = undefined;
  28066. }
  28067. }
  28068. //
  28069. // Match curl 7.77.0 behavior and make the first `Authorization` header win.
  28070. // If the `Authorization` header is set, then there is nothing to do as it
  28071. // will take precedence.
  28072. //
  28073. if (opts.auth && !options.headers.authorization) {
  28074. options.headers.authorization =
  28075. 'Basic ' + Buffer.from(opts.auth).toString('base64');
  28076. }
  28077. req = websocket._req = request(opts);
  28078. if (websocket._redirects) {
  28079. //
  28080. // Unlike what is done for the `'upgrade'` event, no early exit is
  28081. // triggered here if the user calls `websocket.close()` or
  28082. // `websocket.terminate()` from a listener of the `'redirect'` event. This
  28083. // is because the user can also call `request.destroy()` with an error
  28084. // before calling `websocket.close()` or `websocket.terminate()` and this
  28085. // would result in an error being emitted on the `request` object with no
  28086. // `'error'` event listeners attached.
  28087. //
  28088. websocket.emit('redirect', websocket.url, req);
  28089. }
  28090. } else {
  28091. req = websocket._req = request(opts);
  28092. }
  28093. if (opts.timeout) {
  28094. req.on('timeout', () => {
  28095. abortHandshake$1(websocket, req, 'Opening handshake has timed out');
  28096. });
  28097. }
  28098. req.on('error', (err) => {
  28099. if (req === null || req[kAborted]) return;
  28100. req = websocket._req = null;
  28101. emitErrorAndClose(websocket, err);
  28102. });
  28103. req.on('response', (res) => {
  28104. const location = res.headers.location;
  28105. const statusCode = res.statusCode;
  28106. if (
  28107. location &&
  28108. opts.followRedirects &&
  28109. statusCode >= 300 &&
  28110. statusCode < 400
  28111. ) {
  28112. if (++websocket._redirects > opts.maxRedirects) {
  28113. abortHandshake$1(websocket, req, 'Maximum redirects exceeded');
  28114. return;
  28115. }
  28116. req.abort();
  28117. let addr;
  28118. try {
  28119. addr = new URL$2(location, address);
  28120. } catch (e) {
  28121. const err = new SyntaxError(`Invalid URL: ${location}`);
  28122. emitErrorAndClose(websocket, err);
  28123. return;
  28124. }
  28125. initAsClient(websocket, addr, protocols, options);
  28126. } else if (!websocket.emit('unexpected-response', req, res)) {
  28127. abortHandshake$1(
  28128. websocket,
  28129. req,
  28130. `Unexpected server response: ${res.statusCode}`
  28131. );
  28132. }
  28133. });
  28134. req.on('upgrade', (res, socket, head) => {
  28135. websocket.emit('upgrade', res);
  28136. //
  28137. // The user may have closed the connection from a listener of the
  28138. // `'upgrade'` event.
  28139. //
  28140. if (websocket.readyState !== WebSocket$1.CONNECTING) return;
  28141. req = websocket._req = null;
  28142. const upgrade = res.headers.upgrade;
  28143. if (upgrade === undefined || upgrade.toLowerCase() !== 'websocket') {
  28144. abortHandshake$1(websocket, socket, 'Invalid Upgrade header');
  28145. return;
  28146. }
  28147. const digest = createHash$1('sha1')
  28148. .update(key + GUID$1)
  28149. .digest('base64');
  28150. if (res.headers['sec-websocket-accept'] !== digest) {
  28151. abortHandshake$1(websocket, socket, 'Invalid Sec-WebSocket-Accept header');
  28152. return;
  28153. }
  28154. const serverProt = res.headers['sec-websocket-protocol'];
  28155. let protError;
  28156. if (serverProt !== undefined) {
  28157. if (!protocolSet.size) {
  28158. protError = 'Server sent a subprotocol but none was requested';
  28159. } else if (!protocolSet.has(serverProt)) {
  28160. protError = 'Server sent an invalid subprotocol';
  28161. }
  28162. } else if (protocolSet.size) {
  28163. protError = 'Server sent no subprotocol';
  28164. }
  28165. if (protError) {
  28166. abortHandshake$1(websocket, socket, protError);
  28167. return;
  28168. }
  28169. if (serverProt) websocket._protocol = serverProt;
  28170. const secWebSocketExtensions = res.headers['sec-websocket-extensions'];
  28171. if (secWebSocketExtensions !== undefined) {
  28172. if (!perMessageDeflate) {
  28173. const message =
  28174. 'Server sent a Sec-WebSocket-Extensions header but no extension ' +
  28175. 'was requested';
  28176. abortHandshake$1(websocket, socket, message);
  28177. return;
  28178. }
  28179. let extensions;
  28180. try {
  28181. extensions = parse$2(secWebSocketExtensions);
  28182. } catch (err) {
  28183. const message = 'Invalid Sec-WebSocket-Extensions header';
  28184. abortHandshake$1(websocket, socket, message);
  28185. return;
  28186. }
  28187. const extensionNames = Object.keys(extensions);
  28188. if (
  28189. extensionNames.length !== 1 ||
  28190. extensionNames[0] !== PerMessageDeflate$1.extensionName
  28191. ) {
  28192. const message = 'Server indicated an extension that was not requested';
  28193. abortHandshake$1(websocket, socket, message);
  28194. return;
  28195. }
  28196. try {
  28197. perMessageDeflate.accept(extensions[PerMessageDeflate$1.extensionName]);
  28198. } catch (err) {
  28199. const message = 'Invalid Sec-WebSocket-Extensions header';
  28200. abortHandshake$1(websocket, socket, message);
  28201. return;
  28202. }
  28203. websocket._extensions[PerMessageDeflate$1.extensionName] =
  28204. perMessageDeflate;
  28205. }
  28206. websocket.setSocket(socket, head, {
  28207. allowSynchronousEvents: opts.allowSynchronousEvents,
  28208. generateMask: opts.generateMask,
  28209. maxPayload: opts.maxPayload,
  28210. skipUTF8Validation: opts.skipUTF8Validation
  28211. });
  28212. });
  28213. if (opts.finishRequest) {
  28214. opts.finishRequest(req, websocket);
  28215. } else {
  28216. req.end();
  28217. }
  28218. }
  28219. /**
  28220. * Emit the `'error'` and `'close'` events.
  28221. *
  28222. * @param {WebSocket} websocket The WebSocket instance
  28223. * @param {Error} The error to emit
  28224. * @private
  28225. */
  28226. function emitErrorAndClose(websocket, err) {
  28227. websocket._readyState = WebSocket$1.CLOSING;
  28228. //
  28229. // The following assignment is practically useless and is done only for
  28230. // consistency.
  28231. //
  28232. websocket._errorEmitted = true;
  28233. websocket.emit('error', err);
  28234. websocket.emitClose();
  28235. }
  28236. /**
  28237. * Create a `net.Socket` and initiate a connection.
  28238. *
  28239. * @param {Object} options Connection options
  28240. * @return {net.Socket} The newly created socket used to start the connection
  28241. * @private
  28242. */
  28243. function netConnect(options) {
  28244. options.path = options.socketPath;
  28245. return net.connect(options);
  28246. }
  28247. /**
  28248. * Create a `tls.TLSSocket` and initiate a connection.
  28249. *
  28250. * @param {Object} options Connection options
  28251. * @return {tls.TLSSocket} The newly created socket used to start the connection
  28252. * @private
  28253. */
  28254. function tlsConnect(options) {
  28255. options.path = undefined;
  28256. if (!options.servername && options.servername !== '') {
  28257. options.servername = net.isIP(options.host) ? '' : options.host;
  28258. }
  28259. return tls.connect(options);
  28260. }
  28261. /**
  28262. * Abort the handshake and emit an error.
  28263. *
  28264. * @param {WebSocket} websocket The WebSocket instance
  28265. * @param {(http.ClientRequest|net.Socket|tls.Socket)} stream The request to
  28266. * abort or the socket to destroy
  28267. * @param {String} message The error message
  28268. * @private
  28269. */
  28270. function abortHandshake$1(websocket, stream, message) {
  28271. websocket._readyState = WebSocket$1.CLOSING;
  28272. const err = new Error(message);
  28273. Error.captureStackTrace(err, abortHandshake$1);
  28274. if (stream.setHeader) {
  28275. stream[kAborted] = true;
  28276. stream.abort();
  28277. if (stream.socket && !stream.socket.destroyed) {
  28278. //
  28279. // On Node.js >= 14.3.0 `request.abort()` does not destroy the socket if
  28280. // called after the request completed. See
  28281. // https://github.com/websockets/ws/issues/1869.
  28282. //
  28283. stream.socket.destroy();
  28284. }
  28285. process.nextTick(emitErrorAndClose, websocket, err);
  28286. } else {
  28287. stream.destroy(err);
  28288. stream.once('error', websocket.emit.bind(websocket, 'error'));
  28289. stream.once('close', websocket.emitClose.bind(websocket));
  28290. }
  28291. }
  28292. /**
  28293. * Handle cases where the `ping()`, `pong()`, or `send()` methods are called
  28294. * when the `readyState` attribute is `CLOSING` or `CLOSED`.
  28295. *
  28296. * @param {WebSocket} websocket The WebSocket instance
  28297. * @param {*} [data] The data to send
  28298. * @param {Function} [cb] Callback
  28299. * @private
  28300. */
  28301. function sendAfterClose(websocket, data, cb) {
  28302. if (data) {
  28303. const length = isBlob(data) ? data.size : toBuffer(data).length;
  28304. //
  28305. // The `_bufferedAmount` property is used only when the peer is a client and
  28306. // the opening handshake fails. Under these circumstances, in fact, the
  28307. // `setSocket()` method is not called, so the `_socket` and `_sender`
  28308. // properties are set to `null`.
  28309. //
  28310. if (websocket._socket) websocket._sender._bufferedBytes += length;
  28311. else websocket._bufferedAmount += length;
  28312. }
  28313. if (cb) {
  28314. const err = new Error(
  28315. `WebSocket is not open: readyState ${websocket.readyState} ` +
  28316. `(${readyStates[websocket.readyState]})`
  28317. );
  28318. process.nextTick(cb, err);
  28319. }
  28320. }
  28321. /**
  28322. * The listener of the `Receiver` `'conclude'` event.
  28323. *
  28324. * @param {Number} code The status code
  28325. * @param {Buffer} reason The reason for closing
  28326. * @private
  28327. */
  28328. function receiverOnConclude(code, reason) {
  28329. const websocket = this[kWebSocket$1];
  28330. websocket._closeFrameReceived = true;
  28331. websocket._closeMessage = reason;
  28332. websocket._closeCode = code;
  28333. if (websocket._socket[kWebSocket$1] === undefined) return;
  28334. websocket._socket.removeListener('data', socketOnData);
  28335. process.nextTick(resume, websocket._socket);
  28336. if (code === 1005) websocket.close();
  28337. else websocket.close(code, reason);
  28338. }
  28339. /**
  28340. * The listener of the `Receiver` `'drain'` event.
  28341. *
  28342. * @private
  28343. */
  28344. function receiverOnDrain() {
  28345. const websocket = this[kWebSocket$1];
  28346. if (!websocket.isPaused) websocket._socket.resume();
  28347. }
  28348. /**
  28349. * The listener of the `Receiver` `'error'` event.
  28350. *
  28351. * @param {(RangeError|Error)} err The emitted error
  28352. * @private
  28353. */
  28354. function receiverOnError(err) {
  28355. const websocket = this[kWebSocket$1];
  28356. if (websocket._socket[kWebSocket$1] !== undefined) {
  28357. websocket._socket.removeListener('data', socketOnData);
  28358. //
  28359. // On Node.js < 14.0.0 the `'error'` event is emitted synchronously. See
  28360. // https://github.com/websockets/ws/issues/1940.
  28361. //
  28362. process.nextTick(resume, websocket._socket);
  28363. websocket.close(err[kStatusCode]);
  28364. }
  28365. if (!websocket._errorEmitted) {
  28366. websocket._errorEmitted = true;
  28367. websocket.emit('error', err);
  28368. }
  28369. }
  28370. /**
  28371. * The listener of the `Receiver` `'finish'` event.
  28372. *
  28373. * @private
  28374. */
  28375. function receiverOnFinish() {
  28376. this[kWebSocket$1].emitClose();
  28377. }
  28378. /**
  28379. * The listener of the `Receiver` `'message'` event.
  28380. *
  28381. * @param {Buffer|ArrayBuffer|Buffer[])} data The message
  28382. * @param {Boolean} isBinary Specifies whether the message is binary or not
  28383. * @private
  28384. */
  28385. function receiverOnMessage(data, isBinary) {
  28386. this[kWebSocket$1].emit('message', data, isBinary);
  28387. }
  28388. /**
  28389. * The listener of the `Receiver` `'ping'` event.
  28390. *
  28391. * @param {Buffer} data The data included in the ping frame
  28392. * @private
  28393. */
  28394. function receiverOnPing(data) {
  28395. const websocket = this[kWebSocket$1];
  28396. if (websocket._autoPong) websocket.pong(data, !this._isServer, NOOP$1);
  28397. websocket.emit('ping', data);
  28398. }
  28399. /**
  28400. * The listener of the `Receiver` `'pong'` event.
  28401. *
  28402. * @param {Buffer} data The data included in the pong frame
  28403. * @private
  28404. */
  28405. function receiverOnPong(data) {
  28406. this[kWebSocket$1].emit('pong', data);
  28407. }
  28408. /**
  28409. * Resume a readable stream
  28410. *
  28411. * @param {Readable} stream The readable stream
  28412. * @private
  28413. */
  28414. function resume(stream) {
  28415. stream.resume();
  28416. }
  28417. /**
  28418. * The `Sender` error event handler.
  28419. *
  28420. * @param {Error} The error
  28421. * @private
  28422. */
  28423. function senderOnError(err) {
  28424. const websocket = this[kWebSocket$1];
  28425. if (websocket.readyState === WebSocket$1.CLOSED) return;
  28426. if (websocket.readyState === WebSocket$1.OPEN) {
  28427. websocket._readyState = WebSocket$1.CLOSING;
  28428. setCloseTimer(websocket);
  28429. }
  28430. //
  28431. // `socket.end()` is used instead of `socket.destroy()` to allow the other
  28432. // peer to finish sending queued data. There is no need to set a timer here
  28433. // because `CLOSING` means that it is already set or not needed.
  28434. //
  28435. this._socket.end();
  28436. if (!websocket._errorEmitted) {
  28437. websocket._errorEmitted = true;
  28438. websocket.emit('error', err);
  28439. }
  28440. }
  28441. /**
  28442. * Set a timer to destroy the underlying raw socket of a WebSocket.
  28443. *
  28444. * @param {WebSocket} websocket The WebSocket instance
  28445. * @private
  28446. */
  28447. function setCloseTimer(websocket) {
  28448. websocket._closeTimer = setTimeout(
  28449. websocket._socket.destroy.bind(websocket._socket),
  28450. closeTimeout
  28451. );
  28452. }
  28453. /**
  28454. * The listener of the socket `'close'` event.
  28455. *
  28456. * @private
  28457. */
  28458. function socketOnClose() {
  28459. const websocket = this[kWebSocket$1];
  28460. this.removeListener('close', socketOnClose);
  28461. this.removeListener('data', socketOnData);
  28462. this.removeListener('end', socketOnEnd);
  28463. websocket._readyState = WebSocket$1.CLOSING;
  28464. let chunk;
  28465. //
  28466. // The close frame might not have been received or the `'end'` event emitted,
  28467. // for example, if the socket was destroyed due to an error. Ensure that the
  28468. // `receiver` stream is closed after writing any remaining buffered data to
  28469. // it. If the readable side of the socket is in flowing mode then there is no
  28470. // buffered data as everything has been already written and `readable.read()`
  28471. // will return `null`. If instead, the socket is paused, any possible buffered
  28472. // data will be read as a single chunk.
  28473. //
  28474. if (
  28475. !this._readableState.endEmitted &&
  28476. !websocket._closeFrameReceived &&
  28477. !websocket._receiver._writableState.errorEmitted &&
  28478. (chunk = websocket._socket.read()) !== null
  28479. ) {
  28480. websocket._receiver.write(chunk);
  28481. }
  28482. websocket._receiver.end();
  28483. this[kWebSocket$1] = undefined;
  28484. clearTimeout(websocket._closeTimer);
  28485. if (
  28486. websocket._receiver._writableState.finished ||
  28487. websocket._receiver._writableState.errorEmitted
  28488. ) {
  28489. websocket.emitClose();
  28490. } else {
  28491. websocket._receiver.on('error', receiverOnFinish);
  28492. websocket._receiver.on('finish', receiverOnFinish);
  28493. }
  28494. }
  28495. /**
  28496. * The listener of the socket `'data'` event.
  28497. *
  28498. * @param {Buffer} chunk A chunk of data
  28499. * @private
  28500. */
  28501. function socketOnData(chunk) {
  28502. if (!this[kWebSocket$1]._receiver.write(chunk)) {
  28503. this.pause();
  28504. }
  28505. }
  28506. /**
  28507. * The listener of the socket `'end'` event.
  28508. *
  28509. * @private
  28510. */
  28511. function socketOnEnd() {
  28512. const websocket = this[kWebSocket$1];
  28513. websocket._readyState = WebSocket$1.CLOSING;
  28514. websocket._receiver.end();
  28515. this.end();
  28516. }
  28517. /**
  28518. * The listener of the socket `'error'` event.
  28519. *
  28520. * @private
  28521. */
  28522. function socketOnError$1() {
  28523. const websocket = this[kWebSocket$1];
  28524. this.removeListener('error', socketOnError$1);
  28525. this.on('error', NOOP$1);
  28526. if (websocket) {
  28527. websocket._readyState = WebSocket$1.CLOSING;
  28528. this.destroy();
  28529. }
  28530. }
  28531. const { tokenChars } = validationExports;
  28532. /**
  28533. * Parses the `Sec-WebSocket-Protocol` header into a set of subprotocol names.
  28534. *
  28535. * @param {String} header The field value of the header
  28536. * @return {Set} The subprotocol names
  28537. * @public
  28538. */
  28539. function parse$1(header) {
  28540. const protocols = new Set();
  28541. let start = -1;
  28542. let end = -1;
  28543. let i = 0;
  28544. for (i; i < header.length; i++) {
  28545. const code = header.charCodeAt(i);
  28546. if (end === -1 && tokenChars[code] === 1) {
  28547. if (start === -1) start = i;
  28548. } else if (
  28549. i !== 0 &&
  28550. (code === 0x20 /* ' ' */ || code === 0x09) /* '\t' */
  28551. ) {
  28552. if (end === -1 && start !== -1) end = i;
  28553. } else if (code === 0x2c /* ',' */) {
  28554. if (start === -1) {
  28555. throw new SyntaxError(`Unexpected character at index ${i}`);
  28556. }
  28557. if (end === -1) end = i;
  28558. const protocol = header.slice(start, end);
  28559. if (protocols.has(protocol)) {
  28560. throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`);
  28561. }
  28562. protocols.add(protocol);
  28563. start = end = -1;
  28564. } else {
  28565. throw new SyntaxError(`Unexpected character at index ${i}`);
  28566. }
  28567. }
  28568. if (start === -1 || end !== -1) {
  28569. throw new SyntaxError('Unexpected end of input');
  28570. }
  28571. const protocol = header.slice(start, i);
  28572. if (protocols.has(protocol)) {
  28573. throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`);
  28574. }
  28575. protocols.add(protocol);
  28576. return protocols;
  28577. }
  28578. var subprotocol$1 = { parse: parse$1 };
  28579. /* eslint no-unused-vars: ["error", { "varsIgnorePattern": "^Duplex$", "caughtErrors": "none" }] */
  28580. const EventEmitter = require$$0$7;
  28581. const http$2 = require$$1$2;
  28582. const { createHash } = require$$3;
  28583. const extension = extension$1;
  28584. const PerMessageDeflate = permessageDeflate;
  28585. const subprotocol = subprotocol$1;
  28586. const WebSocket = websocket;
  28587. const { GUID, kWebSocket } = constants;
  28588. const keyRegex = /^[+/0-9A-Za-z]{22}==$/;
  28589. const RUNNING = 0;
  28590. const CLOSING = 1;
  28591. const CLOSED = 2;
  28592. /**
  28593. * Class representing a WebSocket server.
  28594. *
  28595. * @extends EventEmitter
  28596. */
  28597. class WebSocketServer extends EventEmitter {
  28598. /**
  28599. * Create a `WebSocketServer` instance.
  28600. *
  28601. * @param {Object} options Configuration options
  28602. * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether
  28603. * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
  28604. * multiple times in the same tick
  28605. * @param {Boolean} [options.autoPong=true] Specifies whether or not to
  28606. * automatically send a pong in response to a ping
  28607. * @param {Number} [options.backlog=511] The maximum length of the queue of
  28608. * pending connections
  28609. * @param {Boolean} [options.clientTracking=true] Specifies whether or not to
  28610. * track clients
  28611. * @param {Function} [options.handleProtocols] A hook to handle protocols
  28612. * @param {String} [options.host] The hostname where to bind the server
  28613. * @param {Number} [options.maxPayload=104857600] The maximum allowed message
  28614. * size
  28615. * @param {Boolean} [options.noServer=false] Enable no server mode
  28616. * @param {String} [options.path] Accept only connections matching this path
  28617. * @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable
  28618. * permessage-deflate
  28619. * @param {Number} [options.port] The port where to bind the server
  28620. * @param {(http.Server|https.Server)} [options.server] A pre-created HTTP/S
  28621. * server to use
  28622. * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
  28623. * not to skip UTF-8 validation for text and close messages
  28624. * @param {Function} [options.verifyClient] A hook to reject connections
  28625. * @param {Function} [options.WebSocket=WebSocket] Specifies the `WebSocket`
  28626. * class to use. It must be the `WebSocket` class or class that extends it
  28627. * @param {Function} [callback] A listener for the `listening` event
  28628. */
  28629. constructor(options, callback) {
  28630. super();
  28631. options = {
  28632. allowSynchronousEvents: true,
  28633. autoPong: true,
  28634. maxPayload: 100 * 1024 * 1024,
  28635. skipUTF8Validation: false,
  28636. perMessageDeflate: false,
  28637. handleProtocols: null,
  28638. clientTracking: true,
  28639. verifyClient: null,
  28640. noServer: false,
  28641. backlog: null, // use default (511 as implemented in net.js)
  28642. server: null,
  28643. host: null,
  28644. path: null,
  28645. port: null,
  28646. WebSocket,
  28647. ...options
  28648. };
  28649. if (
  28650. (options.port == null && !options.server && !options.noServer) ||
  28651. (options.port != null && (options.server || options.noServer)) ||
  28652. (options.server && options.noServer)
  28653. ) {
  28654. throw new TypeError(
  28655. 'One and only one of the "port", "server", or "noServer" options ' +
  28656. 'must be specified'
  28657. );
  28658. }
  28659. if (options.port != null) {
  28660. this._server = http$2.createServer((req, res) => {
  28661. const body = http$2.STATUS_CODES[426];
  28662. res.writeHead(426, {
  28663. 'Content-Length': body.length,
  28664. 'Content-Type': 'text/plain'
  28665. });
  28666. res.end(body);
  28667. });
  28668. this._server.listen(
  28669. options.port,
  28670. options.host,
  28671. options.backlog,
  28672. callback
  28673. );
  28674. } else if (options.server) {
  28675. this._server = options.server;
  28676. }
  28677. if (this._server) {
  28678. const emitConnection = this.emit.bind(this, 'connection');
  28679. this._removeListeners = addListeners(this._server, {
  28680. listening: this.emit.bind(this, 'listening'),
  28681. error: this.emit.bind(this, 'error'),
  28682. upgrade: (req, socket, head) => {
  28683. this.handleUpgrade(req, socket, head, emitConnection);
  28684. }
  28685. });
  28686. }
  28687. if (options.perMessageDeflate === true) options.perMessageDeflate = {};
  28688. if (options.clientTracking) {
  28689. this.clients = new Set();
  28690. this._shouldEmitClose = false;
  28691. }
  28692. this.options = options;
  28693. this._state = RUNNING;
  28694. }
  28695. /**
  28696. * Returns the bound address, the address family name, and port of the server
  28697. * as reported by the operating system if listening on an IP socket.
  28698. * If the server is listening on a pipe or UNIX domain socket, the name is
  28699. * returned as a string.
  28700. *
  28701. * @return {(Object|String|null)} The address of the server
  28702. * @public
  28703. */
  28704. address() {
  28705. if (this.options.noServer) {
  28706. throw new Error('The server is operating in "noServer" mode');
  28707. }
  28708. if (!this._server) return null;
  28709. return this._server.address();
  28710. }
  28711. /**
  28712. * Stop the server from accepting new connections and emit the `'close'` event
  28713. * when all existing connections are closed.
  28714. *
  28715. * @param {Function} [cb] A one-time listener for the `'close'` event
  28716. * @public
  28717. */
  28718. close(cb) {
  28719. if (this._state === CLOSED) {
  28720. if (cb) {
  28721. this.once('close', () => {
  28722. cb(new Error('The server is not running'));
  28723. });
  28724. }
  28725. process.nextTick(emitClose, this);
  28726. return;
  28727. }
  28728. if (cb) this.once('close', cb);
  28729. if (this._state === CLOSING) return;
  28730. this._state = CLOSING;
  28731. if (this.options.noServer || this.options.server) {
  28732. if (this._server) {
  28733. this._removeListeners();
  28734. this._removeListeners = this._server = null;
  28735. }
  28736. if (this.clients) {
  28737. if (!this.clients.size) {
  28738. process.nextTick(emitClose, this);
  28739. } else {
  28740. this._shouldEmitClose = true;
  28741. }
  28742. } else {
  28743. process.nextTick(emitClose, this);
  28744. }
  28745. } else {
  28746. const server = this._server;
  28747. this._removeListeners();
  28748. this._removeListeners = this._server = null;
  28749. //
  28750. // The HTTP/S server was created internally. Close it, and rely on its
  28751. // `'close'` event.
  28752. //
  28753. server.close(() => {
  28754. emitClose(this);
  28755. });
  28756. }
  28757. }
  28758. /**
  28759. * See if a given request should be handled by this server instance.
  28760. *
  28761. * @param {http.IncomingMessage} req Request object to inspect
  28762. * @return {Boolean} `true` if the request is valid, else `false`
  28763. * @public
  28764. */
  28765. shouldHandle(req) {
  28766. if (this.options.path) {
  28767. const index = req.url.indexOf('?');
  28768. const pathname = index !== -1 ? req.url.slice(0, index) : req.url;
  28769. if (pathname !== this.options.path) return false;
  28770. }
  28771. return true;
  28772. }
  28773. /**
  28774. * Handle a HTTP Upgrade request.
  28775. *
  28776. * @param {http.IncomingMessage} req The request object
  28777. * @param {Duplex} socket The network socket between the server and client
  28778. * @param {Buffer} head The first packet of the upgraded stream
  28779. * @param {Function} cb Callback
  28780. * @public
  28781. */
  28782. handleUpgrade(req, socket, head, cb) {
  28783. socket.on('error', socketOnError);
  28784. const key = req.headers['sec-websocket-key'];
  28785. const upgrade = req.headers.upgrade;
  28786. const version = +req.headers['sec-websocket-version'];
  28787. if (req.method !== 'GET') {
  28788. const message = 'Invalid HTTP method';
  28789. abortHandshakeOrEmitwsClientError(this, req, socket, 405, message);
  28790. return;
  28791. }
  28792. if (upgrade === undefined || upgrade.toLowerCase() !== 'websocket') {
  28793. const message = 'Invalid Upgrade header';
  28794. abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
  28795. return;
  28796. }
  28797. if (key === undefined || !keyRegex.test(key)) {
  28798. const message = 'Missing or invalid Sec-WebSocket-Key header';
  28799. abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
  28800. return;
  28801. }
  28802. if (version !== 8 && version !== 13) {
  28803. const message = 'Missing or invalid Sec-WebSocket-Version header';
  28804. abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
  28805. return;
  28806. }
  28807. if (!this.shouldHandle(req)) {
  28808. abortHandshake(socket, 400);
  28809. return;
  28810. }
  28811. const secWebSocketProtocol = req.headers['sec-websocket-protocol'];
  28812. let protocols = new Set();
  28813. if (secWebSocketProtocol !== undefined) {
  28814. try {
  28815. protocols = subprotocol.parse(secWebSocketProtocol);
  28816. } catch (err) {
  28817. const message = 'Invalid Sec-WebSocket-Protocol header';
  28818. abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
  28819. return;
  28820. }
  28821. }
  28822. const secWebSocketExtensions = req.headers['sec-websocket-extensions'];
  28823. const extensions = {};
  28824. if (
  28825. this.options.perMessageDeflate &&
  28826. secWebSocketExtensions !== undefined
  28827. ) {
  28828. const perMessageDeflate = new PerMessageDeflate(
  28829. this.options.perMessageDeflate,
  28830. true,
  28831. this.options.maxPayload
  28832. );
  28833. try {
  28834. const offers = extension.parse(secWebSocketExtensions);
  28835. if (offers[PerMessageDeflate.extensionName]) {
  28836. perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]);
  28837. extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
  28838. }
  28839. } catch (err) {
  28840. const message =
  28841. 'Invalid or unacceptable Sec-WebSocket-Extensions header';
  28842. abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
  28843. return;
  28844. }
  28845. }
  28846. //
  28847. // Optionally call external client verification handler.
  28848. //
  28849. if (this.options.verifyClient) {
  28850. const info = {
  28851. origin:
  28852. req.headers[`${version === 8 ? 'sec-websocket-origin' : 'origin'}`],
  28853. secure: !!(req.socket.authorized || req.socket.encrypted),
  28854. req
  28855. };
  28856. if (this.options.verifyClient.length === 2) {
  28857. this.options.verifyClient(info, (verified, code, message, headers) => {
  28858. if (!verified) {
  28859. return abortHandshake(socket, code || 401, message, headers);
  28860. }
  28861. this.completeUpgrade(
  28862. extensions,
  28863. key,
  28864. protocols,
  28865. req,
  28866. socket,
  28867. head,
  28868. cb
  28869. );
  28870. });
  28871. return;
  28872. }
  28873. if (!this.options.verifyClient(info)) return abortHandshake(socket, 401);
  28874. }
  28875. this.completeUpgrade(extensions, key, protocols, req, socket, head, cb);
  28876. }
  28877. /**
  28878. * Upgrade the connection to WebSocket.
  28879. *
  28880. * @param {Object} extensions The accepted extensions
  28881. * @param {String} key The value of the `Sec-WebSocket-Key` header
  28882. * @param {Set} protocols The subprotocols
  28883. * @param {http.IncomingMessage} req The request object
  28884. * @param {Duplex} socket The network socket between the server and client
  28885. * @param {Buffer} head The first packet of the upgraded stream
  28886. * @param {Function} cb Callback
  28887. * @throws {Error} If called more than once with the same socket
  28888. * @private
  28889. */
  28890. completeUpgrade(extensions, key, protocols, req, socket, head, cb) {
  28891. //
  28892. // Destroy the socket if the client has already sent a FIN packet.
  28893. //
  28894. if (!socket.readable || !socket.writable) return socket.destroy();
  28895. if (socket[kWebSocket]) {
  28896. throw new Error(
  28897. 'server.handleUpgrade() was called more than once with the same ' +
  28898. 'socket, possibly due to a misconfiguration'
  28899. );
  28900. }
  28901. if (this._state > RUNNING) return abortHandshake(socket, 503);
  28902. const digest = createHash('sha1')
  28903. .update(key + GUID)
  28904. .digest('base64');
  28905. const headers = [
  28906. 'HTTP/1.1 101 Switching Protocols',
  28907. 'Upgrade: websocket',
  28908. 'Connection: Upgrade',
  28909. `Sec-WebSocket-Accept: ${digest}`
  28910. ];
  28911. const ws = new this.options.WebSocket(null, undefined, this.options);
  28912. if (protocols.size) {
  28913. //
  28914. // Optionally call external protocol selection handler.
  28915. //
  28916. const protocol = this.options.handleProtocols
  28917. ? this.options.handleProtocols(protocols, req)
  28918. : protocols.values().next().value;
  28919. if (protocol) {
  28920. headers.push(`Sec-WebSocket-Protocol: ${protocol}`);
  28921. ws._protocol = protocol;
  28922. }
  28923. }
  28924. if (extensions[PerMessageDeflate.extensionName]) {
  28925. const params = extensions[PerMessageDeflate.extensionName].params;
  28926. const value = extension.format({
  28927. [PerMessageDeflate.extensionName]: [params]
  28928. });
  28929. headers.push(`Sec-WebSocket-Extensions: ${value}`);
  28930. ws._extensions = extensions;
  28931. }
  28932. //
  28933. // Allow external modification/inspection of handshake headers.
  28934. //
  28935. this.emit('headers', headers, req);
  28936. socket.write(headers.concat('\r\n').join('\r\n'));
  28937. socket.removeListener('error', socketOnError);
  28938. ws.setSocket(socket, head, {
  28939. allowSynchronousEvents: this.options.allowSynchronousEvents,
  28940. maxPayload: this.options.maxPayload,
  28941. skipUTF8Validation: this.options.skipUTF8Validation
  28942. });
  28943. if (this.clients) {
  28944. this.clients.add(ws);
  28945. ws.on('close', () => {
  28946. this.clients.delete(ws);
  28947. if (this._shouldEmitClose && !this.clients.size) {
  28948. process.nextTick(emitClose, this);
  28949. }
  28950. });
  28951. }
  28952. cb(ws, req);
  28953. }
  28954. }
  28955. var websocketServer = WebSocketServer;
  28956. /**
  28957. * Add event listeners on an `EventEmitter` using a map of <event, listener>
  28958. * pairs.
  28959. *
  28960. * @param {EventEmitter} server The event emitter
  28961. * @param {Object.<String, Function>} map The listeners to add
  28962. * @return {Function} A function that will remove the added listeners when
  28963. * called
  28964. * @private
  28965. */
  28966. function addListeners(server, map) {
  28967. for (const event of Object.keys(map)) server.on(event, map[event]);
  28968. return function removeListeners() {
  28969. for (const event of Object.keys(map)) {
  28970. server.removeListener(event, map[event]);
  28971. }
  28972. };
  28973. }
  28974. /**
  28975. * Emit a `'close'` event on an `EventEmitter`.
  28976. *
  28977. * @param {EventEmitter} server The event emitter
  28978. * @private
  28979. */
  28980. function emitClose(server) {
  28981. server._state = CLOSED;
  28982. server.emit('close');
  28983. }
  28984. /**
  28985. * Handle socket errors.
  28986. *
  28987. * @private
  28988. */
  28989. function socketOnError() {
  28990. this.destroy();
  28991. }
  28992. /**
  28993. * Close the connection when preconditions are not fulfilled.
  28994. *
  28995. * @param {Duplex} socket The socket of the upgrade request
  28996. * @param {Number} code The HTTP response status code
  28997. * @param {String} [message] The HTTP response body
  28998. * @param {Object} [headers] Additional HTTP response headers
  28999. * @private
  29000. */
  29001. function abortHandshake(socket, code, message, headers) {
  29002. //
  29003. // The socket is writable unless the user destroyed or ended it before calling
  29004. // `server.handleUpgrade()` or in the `verifyClient` function, which is a user
  29005. // error. Handling this does not make much sense as the worst that can happen
  29006. // is that some of the data written by the user might be discarded due to the
  29007. // call to `socket.end()` below, which triggers an `'error'` event that in
  29008. // turn causes the socket to be destroyed.
  29009. //
  29010. message = message || http$2.STATUS_CODES[code];
  29011. headers = {
  29012. Connection: 'close',
  29013. 'Content-Type': 'text/html',
  29014. 'Content-Length': Buffer.byteLength(message),
  29015. ...headers
  29016. };
  29017. socket.once('finish', socket.destroy);
  29018. socket.end(
  29019. `HTTP/1.1 ${code} ${http$2.STATUS_CODES[code]}\r\n` +
  29020. Object.keys(headers)
  29021. .map((h) => `${h}: ${headers[h]}`)
  29022. .join('\r\n') +
  29023. '\r\n\r\n' +
  29024. message
  29025. );
  29026. }
  29027. /**
  29028. * Emit a `'wsClientError'` event on a `WebSocketServer` if there is at least
  29029. * one listener for it, otherwise call `abortHandshake()`.
  29030. *
  29031. * @param {WebSocketServer} server The WebSocket server
  29032. * @param {http.IncomingMessage} req The request object
  29033. * @param {Duplex} socket The socket of the upgrade request
  29034. * @param {Number} code The HTTP response status code
  29035. * @param {String} message The HTTP response body
  29036. * @private
  29037. */
  29038. function abortHandshakeOrEmitwsClientError(server, req, socket, code, message) {
  29039. if (server.listenerCount('wsClientError')) {
  29040. const err = new Error(message);
  29041. Error.captureStackTrace(err, abortHandshakeOrEmitwsClientError);
  29042. server.emit('wsClientError', err, socket, req);
  29043. } else {
  29044. abortHandshake(socket, code, message);
  29045. }
  29046. }
  29047. var WebSocketServerRaw_ = /*@__PURE__*/getDefaultExportFromCjs(websocketServer);
  29048. const allowedHostsServerCache = /* @__PURE__ */ new WeakMap();
  29049. const allowedHostsPreviewCache = /* @__PURE__ */ new WeakMap();
  29050. const isFileOrExtensionProtocolRE = /^(?:file|.+-extension):/i;
  29051. function getAdditionalAllowedHosts(resolvedServerOptions, resolvedPreviewOptions) {
  29052. const list = [];
  29053. if (typeof resolvedServerOptions.host === "string" && resolvedServerOptions.host) {
  29054. list.push(resolvedServerOptions.host);
  29055. }
  29056. if (typeof resolvedServerOptions.hmr === "object" && resolvedServerOptions.hmr.host) {
  29057. list.push(resolvedServerOptions.hmr.host);
  29058. }
  29059. if (typeof resolvedPreviewOptions.host === "string" && resolvedPreviewOptions.host) {
  29060. list.push(resolvedPreviewOptions.host);
  29061. }
  29062. if (resolvedServerOptions.origin) {
  29063. try {
  29064. const serverOriginUrl = new URL(resolvedServerOptions.origin);
  29065. list.push(serverOriginUrl.hostname);
  29066. } catch {
  29067. }
  29068. }
  29069. return list;
  29070. }
  29071. function isHostAllowedWithoutCache(allowedHosts, additionalAllowedHosts, host) {
  29072. if (isFileOrExtensionProtocolRE.test(host)) {
  29073. return true;
  29074. }
  29075. const trimmedHost = host.trim();
  29076. if (trimmedHost[0] === "[") {
  29077. const endIpv6 = trimmedHost.indexOf("]");
  29078. if (endIpv6 < 0) {
  29079. return false;
  29080. }
  29081. return net$1.isIP(trimmedHost.slice(1, endIpv6)) === 6;
  29082. }
  29083. const colonPos = trimmedHost.indexOf(":");
  29084. const hostname = colonPos === -1 ? trimmedHost : trimmedHost.slice(0, colonPos);
  29085. if (net$1.isIP(hostname) === 4) {
  29086. return true;
  29087. }
  29088. if (hostname === "localhost" || hostname.endsWith(".localhost")) {
  29089. return true;
  29090. }
  29091. for (const additionalAllowedHost of additionalAllowedHosts) {
  29092. if (additionalAllowedHost === hostname) {
  29093. return true;
  29094. }
  29095. }
  29096. for (const allowedHost of allowedHosts) {
  29097. if (allowedHost === hostname) {
  29098. return true;
  29099. }
  29100. if (allowedHost[0] === "." && (allowedHost.slice(1) === hostname || hostname.endsWith(allowedHost))) {
  29101. return true;
  29102. }
  29103. }
  29104. return false;
  29105. }
  29106. function isHostAllowed(config, isPreview, host) {
  29107. const allowedHosts = isPreview ? config.preview.allowedHosts : config.server.allowedHosts;
  29108. if (allowedHosts === true) {
  29109. return true;
  29110. }
  29111. const cache = isPreview ? allowedHostsPreviewCache : allowedHostsServerCache;
  29112. if (!cache.has(config)) {
  29113. cache.set(config, /* @__PURE__ */ new Set());
  29114. }
  29115. const cachedAllowedHosts = cache.get(config);
  29116. if (cachedAllowedHosts.has(host)) {
  29117. return true;
  29118. }
  29119. const result = isHostAllowedWithoutCache(
  29120. allowedHosts,
  29121. config.additionalAllowedHosts,
  29122. host
  29123. );
  29124. if (result) {
  29125. cachedAllowedHosts.add(host);
  29126. }
  29127. return result;
  29128. }
  29129. function hostCheckMiddleware(config, isPreview) {
  29130. return function viteHostCheckMiddleware(req, res, next) {
  29131. const hostHeader = req.headers.host;
  29132. if (!hostHeader || !isHostAllowed(config, isPreview, hostHeader)) {
  29133. const hostname = hostHeader?.replace(/:\d+$/, "");
  29134. const hostnameWithQuotes = JSON.stringify(hostname);
  29135. const optionName = `${isPreview ? "preview" : "server"}.allowedHosts`;
  29136. res.writeHead(403, {
  29137. "Content-Type": "text/plain"
  29138. });
  29139. res.end(
  29140. `Blocked request. This host (${hostnameWithQuotes}) is not allowed.
  29141. To allow this host, add ${hostnameWithQuotes} to \`${optionName}\` in vite.config.js.`
  29142. );
  29143. return;
  29144. }
  29145. return next();
  29146. };
  29147. }
  29148. const WebSocketServerRaw = process.versions.bun ? (
  29149. // @ts-expect-error: Bun defines `import.meta.require`
  29150. import.meta.require("ws").WebSocketServer
  29151. ) : WebSocketServerRaw_;
  29152. const HMR_HEADER = "vite-hmr";
  29153. const isWebSocketServer = Symbol("isWebSocketServer");
  29154. const wsServerEvents = [
  29155. "connection",
  29156. "error",
  29157. "headers",
  29158. "listening",
  29159. "message"
  29160. ];
  29161. function noop$2() {
  29162. }
  29163. function hasValidToken(config, url) {
  29164. const token = url.searchParams.get("token");
  29165. if (!token) return false;
  29166. try {
  29167. const isValidToken = crypto$2.timingSafeEqual(
  29168. Buffer.from(token),
  29169. Buffer.from(config.webSocketToken)
  29170. );
  29171. return isValidToken;
  29172. } catch {
  29173. }
  29174. return false;
  29175. }
  29176. function createWebSocketServer(server, config, httpsOptions) {
  29177. if (config.server.ws === false) {
  29178. return {
  29179. [isWebSocketServer]: true,
  29180. get clients() {
  29181. return /* @__PURE__ */ new Set();
  29182. },
  29183. async close() {
  29184. },
  29185. on: noop$2,
  29186. off: noop$2,
  29187. setInvokeHandler: noop$2,
  29188. handleInvoke: async () => ({
  29189. error: {
  29190. name: "TransportError",
  29191. message: "handleInvoke not implemented",
  29192. stack: new Error().stack
  29193. }
  29194. }),
  29195. listen: noop$2,
  29196. send: noop$2
  29197. };
  29198. }
  29199. let wsHttpServer = void 0;
  29200. const hmr = isObject$1(config.server.hmr) && config.server.hmr;
  29201. const hmrServer = hmr && hmr.server;
  29202. const hmrPort = hmr && hmr.port;
  29203. const portsAreCompatible = !hmrPort || hmrPort === config.server.port;
  29204. const wsServer = hmrServer || portsAreCompatible && server;
  29205. let hmrServerWsListener;
  29206. const customListeners = /* @__PURE__ */ new Map();
  29207. const clientsMap = /* @__PURE__ */ new WeakMap();
  29208. const port = hmrPort || 24678;
  29209. const host = hmr && hmr.host || void 0;
  29210. const shouldHandle = (req) => {
  29211. const protocol = req.headers["sec-websocket-protocol"];
  29212. if (protocol === "vite-ping") return true;
  29213. const hostHeader = req.headers.host;
  29214. if (!hostHeader || !isHostAllowed(config, false, hostHeader)) {
  29215. return false;
  29216. }
  29217. if (config.legacy?.skipWebSocketTokenCheck) {
  29218. return true;
  29219. }
  29220. if (req.headers.origin) {
  29221. const parsedUrl = new URL(`http://example.com${req.url}`);
  29222. return hasValidToken(config, parsedUrl);
  29223. }
  29224. return true;
  29225. };
  29226. const handleUpgrade = (req, socket, head, isPing) => {
  29227. wss.handleUpgrade(req, socket, head, (ws) => {
  29228. if (isPing) {
  29229. ws.close(
  29230. /* Normal Closure */
  29231. 1e3
  29232. );
  29233. return;
  29234. }
  29235. wss.emit("connection", ws, req);
  29236. });
  29237. };
  29238. const wss = new WebSocketServerRaw({ noServer: true });
  29239. wss.shouldHandle = shouldHandle;
  29240. if (wsServer) {
  29241. let hmrBase = config.base;
  29242. const hmrPath = hmr ? hmr.path : void 0;
  29243. if (hmrPath) {
  29244. hmrBase = path$b.posix.join(hmrBase, hmrPath);
  29245. }
  29246. hmrServerWsListener = (req, socket, head) => {
  29247. const protocol = req.headers["sec-websocket-protocol"];
  29248. const parsedUrl = new URL(`http://example.com${req.url}`);
  29249. if ([HMR_HEADER, "vite-ping"].includes(protocol) && parsedUrl.pathname === hmrBase) {
  29250. handleUpgrade(req, socket, head, protocol === "vite-ping");
  29251. }
  29252. };
  29253. wsServer.on("upgrade", hmrServerWsListener);
  29254. } else {
  29255. const route = (_, res) => {
  29256. const statusCode = 426;
  29257. const body = STATUS_CODES[statusCode];
  29258. if (!body)
  29259. throw new Error(`No body text found for the ${statusCode} status code`);
  29260. res.writeHead(statusCode, {
  29261. "Content-Length": body.length,
  29262. "Content-Type": "text/plain"
  29263. });
  29264. res.end(body);
  29265. };
  29266. if (httpsOptions) {
  29267. wsHttpServer = createServer$2(httpsOptions, route);
  29268. } else {
  29269. wsHttpServer = createServer$3(route);
  29270. }
  29271. wsHttpServer.on("upgrade", (req, socket, head) => {
  29272. const protocol = req.headers["sec-websocket-protocol"];
  29273. if (protocol === "vite-ping" && server && !server.listening) {
  29274. req.destroy();
  29275. return;
  29276. }
  29277. handleUpgrade(req, socket, head, protocol === "vite-ping");
  29278. });
  29279. wsHttpServer.on("error", (e) => {
  29280. if (e.code === "EADDRINUSE") {
  29281. config.logger.error(
  29282. colors$1.red(
  29283. `WebSocket server error: Port ${e.port} is already in use`
  29284. ),
  29285. { error: e }
  29286. );
  29287. } else {
  29288. config.logger.error(
  29289. colors$1.red(`WebSocket server error:
  29290. ${e.stack || e.message}`),
  29291. { error: e }
  29292. );
  29293. }
  29294. });
  29295. }
  29296. wss.on("connection", (socket) => {
  29297. socket.on("message", (raw) => {
  29298. if (!customListeners.size) return;
  29299. let parsed;
  29300. try {
  29301. parsed = JSON.parse(String(raw));
  29302. } catch {
  29303. }
  29304. if (!parsed || parsed.type !== "custom" || !parsed.event) return;
  29305. const listeners = customListeners.get(parsed.event);
  29306. if (!listeners?.size) return;
  29307. const client = getSocketClient(socket);
  29308. listeners.forEach(
  29309. (listener) => listener(parsed.data, client, parsed.invoke)
  29310. );
  29311. });
  29312. socket.on("error", (err) => {
  29313. config.logger.error(`${colors$1.red(`ws error:`)}
  29314. ${err.stack}`, {
  29315. timestamp: true,
  29316. error: err
  29317. });
  29318. });
  29319. socket.send(JSON.stringify({ type: "connected" }));
  29320. if (bufferedError) {
  29321. socket.send(JSON.stringify(bufferedError));
  29322. bufferedError = null;
  29323. }
  29324. });
  29325. wss.on("error", (e) => {
  29326. if (e.code === "EADDRINUSE") {
  29327. config.logger.error(
  29328. colors$1.red(`WebSocket server error: Port ${e.port} is already in use`),
  29329. { error: e }
  29330. );
  29331. } else {
  29332. config.logger.error(
  29333. colors$1.red(`WebSocket server error:
  29334. ${e.stack || e.message}`),
  29335. { error: e }
  29336. );
  29337. }
  29338. });
  29339. function getSocketClient(socket) {
  29340. if (!clientsMap.has(socket)) {
  29341. clientsMap.set(socket, {
  29342. send: (...args) => {
  29343. let payload;
  29344. if (typeof args[0] === "string") {
  29345. payload = {
  29346. type: "custom",
  29347. event: args[0],
  29348. data: args[1]
  29349. };
  29350. } else {
  29351. payload = args[0];
  29352. }
  29353. socket.send(JSON.stringify(payload));
  29354. },
  29355. socket
  29356. });
  29357. }
  29358. return clientsMap.get(socket);
  29359. }
  29360. let bufferedError = null;
  29361. const normalizedHotChannel = normalizeHotChannel(
  29362. {
  29363. send(payload) {
  29364. if (payload.type === "error" && !wss.clients.size) {
  29365. bufferedError = payload;
  29366. return;
  29367. }
  29368. const stringified = JSON.stringify(payload);
  29369. wss.clients.forEach((client) => {
  29370. if (client.readyState === 1) {
  29371. client.send(stringified);
  29372. }
  29373. });
  29374. },
  29375. on(event, fn) {
  29376. if (!customListeners.has(event)) {
  29377. customListeners.set(event, /* @__PURE__ */ new Set());
  29378. }
  29379. customListeners.get(event).add(fn);
  29380. },
  29381. off(event, fn) {
  29382. customListeners.get(event)?.delete(fn);
  29383. },
  29384. listen() {
  29385. wsHttpServer?.listen(port, host);
  29386. },
  29387. close() {
  29388. if (hmrServerWsListener && wsServer) {
  29389. wsServer.off("upgrade", hmrServerWsListener);
  29390. }
  29391. return new Promise((resolve, reject) => {
  29392. wss.clients.forEach((client) => {
  29393. client.terminate();
  29394. });
  29395. wss.close((err) => {
  29396. if (err) {
  29397. reject(err);
  29398. } else {
  29399. if (wsHttpServer) {
  29400. wsHttpServer.close((err2) => {
  29401. if (err2) {
  29402. reject(err2);
  29403. } else {
  29404. resolve();
  29405. }
  29406. });
  29407. } else {
  29408. resolve();
  29409. }
  29410. }
  29411. });
  29412. });
  29413. }
  29414. },
  29415. config.server.hmr !== false,
  29416. // Don't normalize client as we already handles the send, and to keep `.socket`
  29417. false
  29418. );
  29419. return {
  29420. ...normalizedHotChannel,
  29421. on: (event, fn) => {
  29422. if (wsServerEvents.includes(event)) {
  29423. wss.on(event, fn);
  29424. return;
  29425. }
  29426. normalizedHotChannel.on(event, fn);
  29427. },
  29428. off: (event, fn) => {
  29429. if (wsServerEvents.includes(event)) {
  29430. wss.off(event, fn);
  29431. return;
  29432. }
  29433. normalizedHotChannel.off(event, fn);
  29434. },
  29435. async close() {
  29436. await normalizedHotChannel.close();
  29437. },
  29438. [isWebSocketServer]: true,
  29439. get clients() {
  29440. return new Set(Array.from(wss.clients).map(getSocketClient));
  29441. }
  29442. };
  29443. }
  29444. function baseMiddleware(rawBase, middlewareMode) {
  29445. return function viteBaseMiddleware(req, res, next) {
  29446. const url = req.url;
  29447. const pathname = cleanUrl(url);
  29448. const base = rawBase;
  29449. if (pathname.startsWith(base)) {
  29450. req.url = stripBase(url, base);
  29451. return next();
  29452. }
  29453. if (middlewareMode) {
  29454. return next();
  29455. }
  29456. if (pathname === "/" || pathname === "/index.html") {
  29457. res.writeHead(302, {
  29458. Location: base + url.slice(pathname.length)
  29459. });
  29460. res.end();
  29461. return;
  29462. }
  29463. const redirectPath = withTrailingSlash(url) !== base ? joinUrlSegments(base, url) : base;
  29464. if (req.headers.accept?.includes("text/html")) {
  29465. res.writeHead(404, {
  29466. "Content-Type": "text/html"
  29467. });
  29468. res.end(
  29469. `The server is configured with a public base URL of ${base} - did you mean to visit <a href="${redirectPath}">${redirectPath}</a> instead?`
  29470. );
  29471. return;
  29472. } else {
  29473. res.writeHead(404, {
  29474. "Content-Type": "text/plain"
  29475. });
  29476. res.end(
  29477. `The server is configured with a public base URL of ${base} - did you mean to visit ${redirectPath} instead?`
  29478. );
  29479. return;
  29480. }
  29481. };
  29482. }
  29483. var httpProxy$3 = {exports: {}};
  29484. var eventemitter3 = {exports: {}};
  29485. (function (module) {
  29486. var has = Object.prototype.hasOwnProperty
  29487. , prefix = '~';
  29488. /**
  29489. * Constructor to create a storage for our `EE` objects.
  29490. * An `Events` instance is a plain object whose properties are event names.
  29491. *
  29492. * @constructor
  29493. * @private
  29494. */
  29495. function Events() {}
  29496. //
  29497. // We try to not inherit from `Object.prototype`. In some engines creating an
  29498. // instance in this way is faster than calling `Object.create(null)` directly.
  29499. // If `Object.create(null)` is not supported we prefix the event names with a
  29500. // character to make sure that the built-in object properties are not
  29501. // overridden or used as an attack vector.
  29502. //
  29503. if (Object.create) {
  29504. Events.prototype = Object.create(null);
  29505. //
  29506. // This hack is needed because the `__proto__` property is still inherited in
  29507. // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5.
  29508. //
  29509. if (!new Events().__proto__) prefix = false;
  29510. }
  29511. /**
  29512. * Representation of a single event listener.
  29513. *
  29514. * @param {Function} fn The listener function.
  29515. * @param {*} context The context to invoke the listener with.
  29516. * @param {Boolean} [once=false] Specify if the listener is a one-time listener.
  29517. * @constructor
  29518. * @private
  29519. */
  29520. function EE(fn, context, once) {
  29521. this.fn = fn;
  29522. this.context = context;
  29523. this.once = once || false;
  29524. }
  29525. /**
  29526. * Add a listener for a given event.
  29527. *
  29528. * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.
  29529. * @param {(String|Symbol)} event The event name.
  29530. * @param {Function} fn The listener function.
  29531. * @param {*} context The context to invoke the listener with.
  29532. * @param {Boolean} once Specify if the listener is a one-time listener.
  29533. * @returns {EventEmitter}
  29534. * @private
  29535. */
  29536. function addListener(emitter, event, fn, context, once) {
  29537. if (typeof fn !== 'function') {
  29538. throw new TypeError('The listener must be a function');
  29539. }
  29540. var listener = new EE(fn, context || emitter, once)
  29541. , evt = prefix ? prefix + event : event;
  29542. if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++;
  29543. else if (!emitter._events[evt].fn) emitter._events[evt].push(listener);
  29544. else emitter._events[evt] = [emitter._events[evt], listener];
  29545. return emitter;
  29546. }
  29547. /**
  29548. * Clear event by name.
  29549. *
  29550. * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.
  29551. * @param {(String|Symbol)} evt The Event name.
  29552. * @private
  29553. */
  29554. function clearEvent(emitter, evt) {
  29555. if (--emitter._eventsCount === 0) emitter._events = new Events();
  29556. else delete emitter._events[evt];
  29557. }
  29558. /**
  29559. * Minimal `EventEmitter` interface that is molded against the Node.js
  29560. * `EventEmitter` interface.
  29561. *
  29562. * @constructor
  29563. * @public
  29564. */
  29565. function EventEmitter() {
  29566. this._events = new Events();
  29567. this._eventsCount = 0;
  29568. }
  29569. /**
  29570. * Return an array listing the events for which the emitter has registered
  29571. * listeners.
  29572. *
  29573. * @returns {Array}
  29574. * @public
  29575. */
  29576. EventEmitter.prototype.eventNames = function eventNames() {
  29577. var names = []
  29578. , events
  29579. , name;
  29580. if (this._eventsCount === 0) return names;
  29581. for (name in (events = this._events)) {
  29582. if (has.call(events, name)) names.push(prefix ? name.slice(1) : name);
  29583. }
  29584. if (Object.getOwnPropertySymbols) {
  29585. return names.concat(Object.getOwnPropertySymbols(events));
  29586. }
  29587. return names;
  29588. };
  29589. /**
  29590. * Return the listeners registered for a given event.
  29591. *
  29592. * @param {(String|Symbol)} event The event name.
  29593. * @returns {Array} The registered listeners.
  29594. * @public
  29595. */
  29596. EventEmitter.prototype.listeners = function listeners(event) {
  29597. var evt = prefix ? prefix + event : event
  29598. , handlers = this._events[evt];
  29599. if (!handlers) return [];
  29600. if (handlers.fn) return [handlers.fn];
  29601. for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {
  29602. ee[i] = handlers[i].fn;
  29603. }
  29604. return ee;
  29605. };
  29606. /**
  29607. * Return the number of listeners listening to a given event.
  29608. *
  29609. * @param {(String|Symbol)} event The event name.
  29610. * @returns {Number} The number of listeners.
  29611. * @public
  29612. */
  29613. EventEmitter.prototype.listenerCount = function listenerCount(event) {
  29614. var evt = prefix ? prefix + event : event
  29615. , listeners = this._events[evt];
  29616. if (!listeners) return 0;
  29617. if (listeners.fn) return 1;
  29618. return listeners.length;
  29619. };
  29620. /**
  29621. * Calls each of the listeners registered for a given event.
  29622. *
  29623. * @param {(String|Symbol)} event The event name.
  29624. * @returns {Boolean} `true` if the event had listeners, else `false`.
  29625. * @public
  29626. */
  29627. EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {
  29628. var evt = prefix ? prefix + event : event;
  29629. if (!this._events[evt]) return false;
  29630. var listeners = this._events[evt]
  29631. , len = arguments.length
  29632. , args
  29633. , i;
  29634. if (listeners.fn) {
  29635. if (listeners.once) this.removeListener(event, listeners.fn, undefined, true);
  29636. switch (len) {
  29637. case 1: return listeners.fn.call(listeners.context), true;
  29638. case 2: return listeners.fn.call(listeners.context, a1), true;
  29639. case 3: return listeners.fn.call(listeners.context, a1, a2), true;
  29640. case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true;
  29641. case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;
  29642. case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;
  29643. }
  29644. for (i = 1, args = new Array(len -1); i < len; i++) {
  29645. args[i - 1] = arguments[i];
  29646. }
  29647. listeners.fn.apply(listeners.context, args);
  29648. } else {
  29649. var length = listeners.length
  29650. , j;
  29651. for (i = 0; i < length; i++) {
  29652. if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true);
  29653. switch (len) {
  29654. case 1: listeners[i].fn.call(listeners[i].context); break;
  29655. case 2: listeners[i].fn.call(listeners[i].context, a1); break;
  29656. case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break;
  29657. case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break;
  29658. default:
  29659. if (!args) for (j = 1, args = new Array(len -1); j < len; j++) {
  29660. args[j - 1] = arguments[j];
  29661. }
  29662. listeners[i].fn.apply(listeners[i].context, args);
  29663. }
  29664. }
  29665. }
  29666. return true;
  29667. };
  29668. /**
  29669. * Add a listener for a given event.
  29670. *
  29671. * @param {(String|Symbol)} event The event name.
  29672. * @param {Function} fn The listener function.
  29673. * @param {*} [context=this] The context to invoke the listener with.
  29674. * @returns {EventEmitter} `this`.
  29675. * @public
  29676. */
  29677. EventEmitter.prototype.on = function on(event, fn, context) {
  29678. return addListener(this, event, fn, context, false);
  29679. };
  29680. /**
  29681. * Add a one-time listener for a given event.
  29682. *
  29683. * @param {(String|Symbol)} event The event name.
  29684. * @param {Function} fn The listener function.
  29685. * @param {*} [context=this] The context to invoke the listener with.
  29686. * @returns {EventEmitter} `this`.
  29687. * @public
  29688. */
  29689. EventEmitter.prototype.once = function once(event, fn, context) {
  29690. return addListener(this, event, fn, context, true);
  29691. };
  29692. /**
  29693. * Remove the listeners of a given event.
  29694. *
  29695. * @param {(String|Symbol)} event The event name.
  29696. * @param {Function} fn Only remove the listeners that match this function.
  29697. * @param {*} context Only remove the listeners that have this context.
  29698. * @param {Boolean} once Only remove one-time listeners.
  29699. * @returns {EventEmitter} `this`.
  29700. * @public
  29701. */
  29702. EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {
  29703. var evt = prefix ? prefix + event : event;
  29704. if (!this._events[evt]) return this;
  29705. if (!fn) {
  29706. clearEvent(this, evt);
  29707. return this;
  29708. }
  29709. var listeners = this._events[evt];
  29710. if (listeners.fn) {
  29711. if (
  29712. listeners.fn === fn &&
  29713. (!once || listeners.once) &&
  29714. (!context || listeners.context === context)
  29715. ) {
  29716. clearEvent(this, evt);
  29717. }
  29718. } else {
  29719. for (var i = 0, events = [], length = listeners.length; i < length; i++) {
  29720. if (
  29721. listeners[i].fn !== fn ||
  29722. (once && !listeners[i].once) ||
  29723. (context && listeners[i].context !== context)
  29724. ) {
  29725. events.push(listeners[i]);
  29726. }
  29727. }
  29728. //
  29729. // Reset the array, or remove it completely if we have no more listeners.
  29730. //
  29731. if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;
  29732. else clearEvent(this, evt);
  29733. }
  29734. return this;
  29735. };
  29736. /**
  29737. * Remove all listeners, or those of the specified event.
  29738. *
  29739. * @param {(String|Symbol)} [event] The event name.
  29740. * @returns {EventEmitter} `this`.
  29741. * @public
  29742. */
  29743. EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {
  29744. var evt;
  29745. if (event) {
  29746. evt = prefix ? prefix + event : event;
  29747. if (this._events[evt]) clearEvent(this, evt);
  29748. } else {
  29749. this._events = new Events();
  29750. this._eventsCount = 0;
  29751. }
  29752. return this;
  29753. };
  29754. //
  29755. // Alias methods names because people roll like that.
  29756. //
  29757. EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
  29758. EventEmitter.prototype.addListener = EventEmitter.prototype.on;
  29759. //
  29760. // Expose the prefix.
  29761. //
  29762. EventEmitter.prefixed = prefix;
  29763. //
  29764. // Allow `EventEmitter` to be imported as module namespace.
  29765. //
  29766. EventEmitter.EventEmitter = EventEmitter;
  29767. //
  29768. // Expose the module.
  29769. //
  29770. {
  29771. module.exports = EventEmitter;
  29772. }
  29773. } (eventemitter3));
  29774. var eventemitter3Exports = eventemitter3.exports;
  29775. var common$3 = {};
  29776. /**
  29777. * Check if we're required to add a port number.
  29778. *
  29779. * @see https://url.spec.whatwg.org/#default-port
  29780. * @param {Number|String} port Port number we need to check
  29781. * @param {String} protocol Protocol we need to check against.
  29782. * @returns {Boolean} Is it a default port for the given protocol
  29783. * @api private
  29784. */
  29785. var requiresPort = function required(port, protocol) {
  29786. protocol = protocol.split(':')[0];
  29787. port = +port;
  29788. if (!port) return false;
  29789. switch (protocol) {
  29790. case 'http':
  29791. case 'ws':
  29792. return port !== 80;
  29793. case 'https':
  29794. case 'wss':
  29795. return port !== 443;
  29796. case 'ftp':
  29797. return port !== 21;
  29798. case 'gopher':
  29799. return port !== 70;
  29800. case 'file':
  29801. return false;
  29802. }
  29803. return port !== 0;
  29804. };
  29805. (function (exports) {
  29806. var common = exports,
  29807. url = require$$0$5,
  29808. required = requiresPort;
  29809. var upgradeHeader = /(^|,)\s*upgrade\s*($|,)/i,
  29810. isSSL = /^https|wss/;
  29811. /**
  29812. * Simple Regex for testing if protocol is https
  29813. */
  29814. common.isSSL = isSSL;
  29815. /**
  29816. * Copies the right headers from `options` and `req` to
  29817. * `outgoing` which is then used to fire the proxied
  29818. * request.
  29819. *
  29820. * Examples:
  29821. *
  29822. * common.setupOutgoing(outgoing, options, req)
  29823. * // => { host: ..., hostname: ...}
  29824. *
  29825. * @param {Object} Outgoing Base object to be filled with required properties
  29826. * @param {Object} Options Config object passed to the proxy
  29827. * @param {ClientRequest} Req Request Object
  29828. * @param {String} Forward String to select forward or target
  29829. * @return {Object} Outgoing Object with all required properties set
  29830. *
  29831. * @api private
  29832. */
  29833. common.setupOutgoing = function(outgoing, options, req, forward) {
  29834. outgoing.port = options[forward || 'target'].port ||
  29835. (isSSL.test(options[forward || 'target'].protocol) ? 443 : 80);
  29836. ['host', 'hostname', 'socketPath', 'pfx', 'key',
  29837. 'passphrase', 'cert', 'ca', 'ciphers', 'secureProtocol'].forEach(
  29838. function(e) { outgoing[e] = options[forward || 'target'][e]; }
  29839. );
  29840. outgoing.method = options.method || req.method;
  29841. outgoing.headers = Object.assign({}, req.headers);
  29842. if (options.headers){
  29843. Object.assign(outgoing.headers, options.headers);
  29844. }
  29845. if (options.auth) {
  29846. outgoing.auth = options.auth;
  29847. }
  29848. if (options.ca) {
  29849. outgoing.ca = options.ca;
  29850. }
  29851. if (isSSL.test(options[forward || 'target'].protocol)) {
  29852. outgoing.rejectUnauthorized = (typeof options.secure === "undefined") ? true : options.secure;
  29853. }
  29854. outgoing.agent = options.agent || false;
  29855. outgoing.localAddress = options.localAddress;
  29856. //
  29857. // Remark: If we are false and not upgrading, set the connection: close. This is the right thing to do
  29858. // as node core doesn't handle this COMPLETELY properly yet.
  29859. //
  29860. if (!outgoing.agent) {
  29861. outgoing.headers = outgoing.headers || {};
  29862. if (typeof outgoing.headers.connection !== 'string'
  29863. || !upgradeHeader.test(outgoing.headers.connection)
  29864. ) { outgoing.headers.connection = 'close'; }
  29865. }
  29866. // the final path is target path + relative path requested by user:
  29867. var target = options[forward || 'target'];
  29868. var targetPath = target && options.prependPath !== false
  29869. ? (target.path || '')
  29870. : '';
  29871. //
  29872. // Remark: Can we somehow not use url.parse as a perf optimization?
  29873. //
  29874. var outgoingPath = !options.toProxy
  29875. ? (url.parse(req.url).path || '')
  29876. : req.url;
  29877. //
  29878. // Remark: ignorePath will just straight up ignore whatever the request's
  29879. // path is. This can be labeled as FOOT-GUN material if you do not know what
  29880. // you are doing and are using conflicting options.
  29881. //
  29882. outgoingPath = !options.ignorePath ? outgoingPath : '';
  29883. outgoing.path = common.urlJoin(targetPath, outgoingPath);
  29884. if (options.changeOrigin) {
  29885. outgoing.headers.host =
  29886. required(outgoing.port, options[forward || 'target'].protocol) && !hasPort(outgoing.host)
  29887. ? outgoing.host + ':' + outgoing.port
  29888. : outgoing.host;
  29889. }
  29890. return outgoing;
  29891. };
  29892. /**
  29893. * Set the proper configuration for sockets,
  29894. * set no delay and set keep alive, also set
  29895. * the timeout to 0.
  29896. *
  29897. * Examples:
  29898. *
  29899. * common.setupSocket(socket)
  29900. * // => Socket
  29901. *
  29902. * @param {Socket} Socket instance to setup
  29903. * @return {Socket} Return the configured socket.
  29904. *
  29905. * @api private
  29906. */
  29907. common.setupSocket = function(socket) {
  29908. socket.setTimeout(0);
  29909. socket.setNoDelay(true);
  29910. socket.setKeepAlive(true, 0);
  29911. return socket;
  29912. };
  29913. /**
  29914. * Get the port number from the host. Or guess it based on the connection type.
  29915. *
  29916. * @param {Request} req Incoming HTTP request.
  29917. *
  29918. * @return {String} The port number.
  29919. *
  29920. * @api private
  29921. */
  29922. common.getPort = function(req) {
  29923. var res = req.headers.host ? req.headers.host.match(/:(\d+)/) : '';
  29924. return res ?
  29925. res[1] :
  29926. common.hasEncryptedConnection(req) ? '443' : '80';
  29927. };
  29928. /**
  29929. * Check if the request has an encrypted connection.
  29930. *
  29931. * @param {Request} req Incoming HTTP request.
  29932. *
  29933. * @return {Boolean} Whether the connection is encrypted or not.
  29934. *
  29935. * @api private
  29936. */
  29937. common.hasEncryptedConnection = function(req) {
  29938. return Boolean(req.connection.encrypted || req.connection.pair);
  29939. };
  29940. /**
  29941. * OS-agnostic join (doesn't break on URLs like path.join does on Windows)>
  29942. *
  29943. * @return {String} The generated path.
  29944. *
  29945. * @api private
  29946. */
  29947. common.urlJoin = function() {
  29948. //
  29949. // We do not want to mess with the query string. All we want to touch is the path.
  29950. //
  29951. var args = Array.prototype.slice.call(arguments),
  29952. lastIndex = args.length - 1,
  29953. last = args[lastIndex],
  29954. lastSegs = last.split('?'),
  29955. retSegs;
  29956. args[lastIndex] = lastSegs.shift();
  29957. //
  29958. // Join all strings, but remove empty strings so we don't get extra slashes from
  29959. // joining e.g. ['', 'am']
  29960. //
  29961. retSegs = [
  29962. args.filter(Boolean).join('/')
  29963. .replace(/\/+/g, '/')
  29964. .replace('http:/', 'http://')
  29965. .replace('https:/', 'https://')
  29966. ];
  29967. // Only join the query string if it exists so we don't have trailing a '?'
  29968. // on every request
  29969. // Handle case where there could be multiple ? in the URL.
  29970. retSegs.push.apply(retSegs, lastSegs);
  29971. return retSegs.join('?')
  29972. };
  29973. /**
  29974. * Rewrites or removes the domain of a cookie header
  29975. *
  29976. * @param {String|Array} Header
  29977. * @param {Object} Config, mapping of domain to rewritten domain.
  29978. * '*' key to match any domain, null value to remove the domain.
  29979. *
  29980. * @api private
  29981. */
  29982. common.rewriteCookieProperty = function rewriteCookieProperty(header, config, property) {
  29983. if (Array.isArray(header)) {
  29984. return header.map(function (headerElement) {
  29985. return rewriteCookieProperty(headerElement, config, property);
  29986. });
  29987. }
  29988. return header.replace(new RegExp("(;\\s*" + property + "=)([^;]+)", 'i'), function(match, prefix, previousValue) {
  29989. var newValue;
  29990. if (previousValue in config) {
  29991. newValue = config[previousValue];
  29992. } else if ('*' in config) {
  29993. newValue = config['*'];
  29994. } else {
  29995. //no match, return previous value
  29996. return match;
  29997. }
  29998. if (newValue) {
  29999. //replace value
  30000. return prefix + newValue;
  30001. } else {
  30002. //remove value
  30003. return '';
  30004. }
  30005. });
  30006. };
  30007. /**
  30008. * Check the host and see if it potentially has a port in it (keep it simple)
  30009. *
  30010. * @returns {Boolean} Whether we have one or not
  30011. *
  30012. * @api private
  30013. */
  30014. function hasPort(host) {
  30015. return !!~host.indexOf(':');
  30016. }} (common$3));
  30017. var url$1 = require$$0$5,
  30018. common$2 = common$3;
  30019. var redirectRegex = /^201|30(1|2|7|8)$/;
  30020. /*!
  30021. * Array of passes.
  30022. *
  30023. * A `pass` is just a function that is executed on `req, res, options`
  30024. * so that you can easily add new checks while still keeping the base
  30025. * flexible.
  30026. */
  30027. var webOutgoing = { // <--
  30028. /**
  30029. * If is a HTTP 1.0 request, remove chunk headers
  30030. *
  30031. * @param {ClientRequest} Req Request object
  30032. * @param {IncomingMessage} Res Response object
  30033. * @param {proxyResponse} Res Response object from the proxy request
  30034. *
  30035. * @api private
  30036. */
  30037. removeChunked: function removeChunked(req, res, proxyRes) {
  30038. if (req.httpVersion === '1.0') {
  30039. delete proxyRes.headers['transfer-encoding'];
  30040. }
  30041. },
  30042. /**
  30043. * If is a HTTP 1.0 request, set the correct connection header
  30044. * or if connection header not present, then use `keep-alive`
  30045. *
  30046. * @param {ClientRequest} Req Request object
  30047. * @param {IncomingMessage} Res Response object
  30048. * @param {proxyResponse} Res Response object from the proxy request
  30049. *
  30050. * @api private
  30051. */
  30052. setConnection: function setConnection(req, res, proxyRes) {
  30053. if (req.httpVersion === '1.0') {
  30054. proxyRes.headers.connection = req.headers.connection || 'close';
  30055. } else if (req.httpVersion !== '2.0' && !proxyRes.headers.connection) {
  30056. proxyRes.headers.connection = req.headers.connection || 'keep-alive';
  30057. }
  30058. },
  30059. setRedirectHostRewrite: function setRedirectHostRewrite(req, res, proxyRes, options) {
  30060. if ((options.hostRewrite || options.autoRewrite || options.protocolRewrite)
  30061. && proxyRes.headers['location']
  30062. && redirectRegex.test(proxyRes.statusCode)) {
  30063. var target = url$1.parse(options.target);
  30064. var u = url$1.parse(proxyRes.headers['location']);
  30065. // make sure the redirected host matches the target host before rewriting
  30066. if (target.host != u.host) {
  30067. return;
  30068. }
  30069. if (options.hostRewrite) {
  30070. u.host = options.hostRewrite;
  30071. } else if (options.autoRewrite) {
  30072. u.host = req.headers['host'];
  30073. }
  30074. if (options.protocolRewrite) {
  30075. u.protocol = options.protocolRewrite;
  30076. }
  30077. proxyRes.headers['location'] = u.format();
  30078. }
  30079. },
  30080. /**
  30081. * Copy headers from proxyResponse to response
  30082. * set each header in response object.
  30083. *
  30084. * @param {ClientRequest} Req Request object
  30085. * @param {IncomingMessage} Res Response object
  30086. * @param {proxyResponse} Res Response object from the proxy request
  30087. * @param {Object} Options options.cookieDomainRewrite: Config to rewrite cookie domain
  30088. *
  30089. * @api private
  30090. */
  30091. writeHeaders: function writeHeaders(req, res, proxyRes, options) {
  30092. var rewriteCookieDomainConfig = options.cookieDomainRewrite,
  30093. rewriteCookiePathConfig = options.cookiePathRewrite,
  30094. preserveHeaderKeyCase = options.preserveHeaderKeyCase,
  30095. rawHeaderKeyMap,
  30096. setHeader = function(key, header) {
  30097. if (header == undefined) return;
  30098. if (rewriteCookieDomainConfig && key.toLowerCase() === 'set-cookie') {
  30099. header = common$2.rewriteCookieProperty(header, rewriteCookieDomainConfig, 'domain');
  30100. }
  30101. if (rewriteCookiePathConfig && key.toLowerCase() === 'set-cookie') {
  30102. header = common$2.rewriteCookieProperty(header, rewriteCookiePathConfig, 'path');
  30103. }
  30104. res.setHeader(String(key).trim(), header);
  30105. };
  30106. if (typeof rewriteCookieDomainConfig === 'string') { //also test for ''
  30107. rewriteCookieDomainConfig = { '*': rewriteCookieDomainConfig };
  30108. }
  30109. if (typeof rewriteCookiePathConfig === 'string') { //also test for ''
  30110. rewriteCookiePathConfig = { '*': rewriteCookiePathConfig };
  30111. }
  30112. // message.rawHeaders is added in: v0.11.6
  30113. // https://nodejs.org/api/http.html#http_message_rawheaders
  30114. if (preserveHeaderKeyCase && proxyRes.rawHeaders != undefined) {
  30115. rawHeaderKeyMap = {};
  30116. for (var i = 0; i < proxyRes.rawHeaders.length; i += 2) {
  30117. var key = proxyRes.rawHeaders[i];
  30118. rawHeaderKeyMap[key.toLowerCase()] = key;
  30119. }
  30120. }
  30121. Object.keys(proxyRes.headers).forEach(function(key) {
  30122. var header = proxyRes.headers[key];
  30123. if (preserveHeaderKeyCase && rawHeaderKeyMap) {
  30124. key = rawHeaderKeyMap[key] || key;
  30125. }
  30126. setHeader(key, header);
  30127. });
  30128. },
  30129. /**
  30130. * Set the statusCode from the proxyResponse
  30131. *
  30132. * @param {ClientRequest} Req Request object
  30133. * @param {IncomingMessage} Res Response object
  30134. * @param {proxyResponse} Res Response object from the proxy request
  30135. *
  30136. * @api private
  30137. */
  30138. writeStatusCode: function writeStatusCode(req, res, proxyRes) {
  30139. // From Node.js docs: response.writeHead(statusCode[, statusMessage][, headers])
  30140. if(proxyRes.statusMessage) {
  30141. res.statusCode = proxyRes.statusCode;
  30142. res.statusMessage = proxyRes.statusMessage;
  30143. } else {
  30144. res.statusCode = proxyRes.statusCode;
  30145. }
  30146. }
  30147. };
  30148. var followRedirects$1 = {exports: {}};
  30149. var debug$7;
  30150. var debug_1 = function () {
  30151. if (!debug$7) {
  30152. try {
  30153. /* eslint global-require: off */
  30154. debug$7 = nodeExports$1("follow-redirects");
  30155. }
  30156. catch (error) { /* */ }
  30157. if (typeof debug$7 !== "function") {
  30158. debug$7 = function () { /* */ };
  30159. }
  30160. }
  30161. debug$7.apply(null, arguments);
  30162. };
  30163. var url = require$$0$5;
  30164. var URL$1 = url.URL;
  30165. var http$1 = require$$1$2;
  30166. var https$1 = require$$1$3;
  30167. var Writable = require$$0$8.Writable;
  30168. var assert = require$$4$3;
  30169. var debug$6 = debug_1;
  30170. // Preventive platform detection
  30171. // istanbul ignore next
  30172. (function detectUnsupportedEnvironment() {
  30173. var looksLikeNode = typeof process !== "undefined";
  30174. var looksLikeBrowser = typeof window !== "undefined" && typeof document !== "undefined";
  30175. var looksLikeV8 = isFunction(Error.captureStackTrace);
  30176. if (!looksLikeNode && (looksLikeBrowser || !looksLikeV8)) {
  30177. console.warn("The follow-redirects package should be excluded from browser builds.");
  30178. }
  30179. }());
  30180. // Whether to use the native URL object or the legacy url module
  30181. var useNativeURL = false;
  30182. try {
  30183. assert(new URL$1(""));
  30184. }
  30185. catch (error) {
  30186. useNativeURL = error.code === "ERR_INVALID_URL";
  30187. }
  30188. // URL fields to preserve in copy operations
  30189. var preservedUrlFields = [
  30190. "auth",
  30191. "host",
  30192. "hostname",
  30193. "href",
  30194. "path",
  30195. "pathname",
  30196. "port",
  30197. "protocol",
  30198. "query",
  30199. "search",
  30200. "hash",
  30201. ];
  30202. // Create handlers that pass events from native requests
  30203. var events = ["abort", "aborted", "connect", "error", "socket", "timeout"];
  30204. var eventHandlers = Object.create(null);
  30205. events.forEach(function (event) {
  30206. eventHandlers[event] = function (arg1, arg2, arg3) {
  30207. this._redirectable.emit(event, arg1, arg2, arg3);
  30208. };
  30209. });
  30210. // Error types with codes
  30211. var InvalidUrlError = createErrorType(
  30212. "ERR_INVALID_URL",
  30213. "Invalid URL",
  30214. TypeError
  30215. );
  30216. var RedirectionError = createErrorType(
  30217. "ERR_FR_REDIRECTION_FAILURE",
  30218. "Redirected request failed"
  30219. );
  30220. var TooManyRedirectsError = createErrorType(
  30221. "ERR_FR_TOO_MANY_REDIRECTS",
  30222. "Maximum number of redirects exceeded",
  30223. RedirectionError
  30224. );
  30225. var MaxBodyLengthExceededError = createErrorType(
  30226. "ERR_FR_MAX_BODY_LENGTH_EXCEEDED",
  30227. "Request body larger than maxBodyLength limit"
  30228. );
  30229. var WriteAfterEndError = createErrorType(
  30230. "ERR_STREAM_WRITE_AFTER_END",
  30231. "write after end"
  30232. );
  30233. // istanbul ignore next
  30234. var destroy = Writable.prototype.destroy || noop$1;
  30235. // An HTTP(S) request that can be redirected
  30236. function RedirectableRequest(options, responseCallback) {
  30237. // Initialize the request
  30238. Writable.call(this);
  30239. this._sanitizeOptions(options);
  30240. this._options = options;
  30241. this._ended = false;
  30242. this._ending = false;
  30243. this._redirectCount = 0;
  30244. this._redirects = [];
  30245. this._requestBodyLength = 0;
  30246. this._requestBodyBuffers = [];
  30247. // Attach a callback if passed
  30248. if (responseCallback) {
  30249. this.on("response", responseCallback);
  30250. }
  30251. // React to responses of native requests
  30252. var self = this;
  30253. this._onNativeResponse = function (response) {
  30254. try {
  30255. self._processResponse(response);
  30256. }
  30257. catch (cause) {
  30258. self.emit("error", cause instanceof RedirectionError ?
  30259. cause : new RedirectionError({ cause: cause }));
  30260. }
  30261. };
  30262. // Perform the first request
  30263. this._performRequest();
  30264. }
  30265. RedirectableRequest.prototype = Object.create(Writable.prototype);
  30266. RedirectableRequest.prototype.abort = function () {
  30267. destroyRequest(this._currentRequest);
  30268. this._currentRequest.abort();
  30269. this.emit("abort");
  30270. };
  30271. RedirectableRequest.prototype.destroy = function (error) {
  30272. destroyRequest(this._currentRequest, error);
  30273. destroy.call(this, error);
  30274. return this;
  30275. };
  30276. // Writes buffered data to the current native request
  30277. RedirectableRequest.prototype.write = function (data, encoding, callback) {
  30278. // Writing is not allowed if end has been called
  30279. if (this._ending) {
  30280. throw new WriteAfterEndError();
  30281. }
  30282. // Validate input and shift parameters if necessary
  30283. if (!isString(data) && !isBuffer(data)) {
  30284. throw new TypeError("data should be a string, Buffer or Uint8Array");
  30285. }
  30286. if (isFunction(encoding)) {
  30287. callback = encoding;
  30288. encoding = null;
  30289. }
  30290. // Ignore empty buffers, since writing them doesn't invoke the callback
  30291. // https://github.com/nodejs/node/issues/22066
  30292. if (data.length === 0) {
  30293. if (callback) {
  30294. callback();
  30295. }
  30296. return;
  30297. }
  30298. // Only write when we don't exceed the maximum body length
  30299. if (this._requestBodyLength + data.length <= this._options.maxBodyLength) {
  30300. this._requestBodyLength += data.length;
  30301. this._requestBodyBuffers.push({ data: data, encoding: encoding });
  30302. this._currentRequest.write(data, encoding, callback);
  30303. }
  30304. // Error when we exceed the maximum body length
  30305. else {
  30306. this.emit("error", new MaxBodyLengthExceededError());
  30307. this.abort();
  30308. }
  30309. };
  30310. // Ends the current native request
  30311. RedirectableRequest.prototype.end = function (data, encoding, callback) {
  30312. // Shift parameters if necessary
  30313. if (isFunction(data)) {
  30314. callback = data;
  30315. data = encoding = null;
  30316. }
  30317. else if (isFunction(encoding)) {
  30318. callback = encoding;
  30319. encoding = null;
  30320. }
  30321. // Write data if needed and end
  30322. if (!data) {
  30323. this._ended = this._ending = true;
  30324. this._currentRequest.end(null, null, callback);
  30325. }
  30326. else {
  30327. var self = this;
  30328. var currentRequest = this._currentRequest;
  30329. this.write(data, encoding, function () {
  30330. self._ended = true;
  30331. currentRequest.end(null, null, callback);
  30332. });
  30333. this._ending = true;
  30334. }
  30335. };
  30336. // Sets a header value on the current native request
  30337. RedirectableRequest.prototype.setHeader = function (name, value) {
  30338. this._options.headers[name] = value;
  30339. this._currentRequest.setHeader(name, value);
  30340. };
  30341. // Clears a header value on the current native request
  30342. RedirectableRequest.prototype.removeHeader = function (name) {
  30343. delete this._options.headers[name];
  30344. this._currentRequest.removeHeader(name);
  30345. };
  30346. // Global timeout for all underlying requests
  30347. RedirectableRequest.prototype.setTimeout = function (msecs, callback) {
  30348. var self = this;
  30349. // Destroys the socket on timeout
  30350. function destroyOnTimeout(socket) {
  30351. socket.setTimeout(msecs);
  30352. socket.removeListener("timeout", socket.destroy);
  30353. socket.addListener("timeout", socket.destroy);
  30354. }
  30355. // Sets up a timer to trigger a timeout event
  30356. function startTimer(socket) {
  30357. if (self._timeout) {
  30358. clearTimeout(self._timeout);
  30359. }
  30360. self._timeout = setTimeout(function () {
  30361. self.emit("timeout");
  30362. clearTimer();
  30363. }, msecs);
  30364. destroyOnTimeout(socket);
  30365. }
  30366. // Stops a timeout from triggering
  30367. function clearTimer() {
  30368. // Clear the timeout
  30369. if (self._timeout) {
  30370. clearTimeout(self._timeout);
  30371. self._timeout = null;
  30372. }
  30373. // Clean up all attached listeners
  30374. self.removeListener("abort", clearTimer);
  30375. self.removeListener("error", clearTimer);
  30376. self.removeListener("response", clearTimer);
  30377. self.removeListener("close", clearTimer);
  30378. if (callback) {
  30379. self.removeListener("timeout", callback);
  30380. }
  30381. if (!self.socket) {
  30382. self._currentRequest.removeListener("socket", startTimer);
  30383. }
  30384. }
  30385. // Attach callback if passed
  30386. if (callback) {
  30387. this.on("timeout", callback);
  30388. }
  30389. // Start the timer if or when the socket is opened
  30390. if (this.socket) {
  30391. startTimer(this.socket);
  30392. }
  30393. else {
  30394. this._currentRequest.once("socket", startTimer);
  30395. }
  30396. // Clean up on events
  30397. this.on("socket", destroyOnTimeout);
  30398. this.on("abort", clearTimer);
  30399. this.on("error", clearTimer);
  30400. this.on("response", clearTimer);
  30401. this.on("close", clearTimer);
  30402. return this;
  30403. };
  30404. // Proxy all other public ClientRequest methods
  30405. [
  30406. "flushHeaders", "getHeader",
  30407. "setNoDelay", "setSocketKeepAlive",
  30408. ].forEach(function (method) {
  30409. RedirectableRequest.prototype[method] = function (a, b) {
  30410. return this._currentRequest[method](a, b);
  30411. };
  30412. });
  30413. // Proxy all public ClientRequest properties
  30414. ["aborted", "connection", "socket"].forEach(function (property) {
  30415. Object.defineProperty(RedirectableRequest.prototype, property, {
  30416. get: function () { return this._currentRequest[property]; },
  30417. });
  30418. });
  30419. RedirectableRequest.prototype._sanitizeOptions = function (options) {
  30420. // Ensure headers are always present
  30421. if (!options.headers) {
  30422. options.headers = {};
  30423. }
  30424. // Since http.request treats host as an alias of hostname,
  30425. // but the url module interprets host as hostname plus port,
  30426. // eliminate the host property to avoid confusion.
  30427. if (options.host) {
  30428. // Use hostname if set, because it has precedence
  30429. if (!options.hostname) {
  30430. options.hostname = options.host;
  30431. }
  30432. delete options.host;
  30433. }
  30434. // Complete the URL object when necessary
  30435. if (!options.pathname && options.path) {
  30436. var searchPos = options.path.indexOf("?");
  30437. if (searchPos < 0) {
  30438. options.pathname = options.path;
  30439. }
  30440. else {
  30441. options.pathname = options.path.substring(0, searchPos);
  30442. options.search = options.path.substring(searchPos);
  30443. }
  30444. }
  30445. };
  30446. // Executes the next native request (initial or redirect)
  30447. RedirectableRequest.prototype._performRequest = function () {
  30448. // Load the native protocol
  30449. var protocol = this._options.protocol;
  30450. var nativeProtocol = this._options.nativeProtocols[protocol];
  30451. if (!nativeProtocol) {
  30452. throw new TypeError("Unsupported protocol " + protocol);
  30453. }
  30454. // If specified, use the agent corresponding to the protocol
  30455. // (HTTP and HTTPS use different types of agents)
  30456. if (this._options.agents) {
  30457. var scheme = protocol.slice(0, -1);
  30458. this._options.agent = this._options.agents[scheme];
  30459. }
  30460. // Create the native request and set up its event handlers
  30461. var request = this._currentRequest =
  30462. nativeProtocol.request(this._options, this._onNativeResponse);
  30463. request._redirectable = this;
  30464. for (var event of events) {
  30465. request.on(event, eventHandlers[event]);
  30466. }
  30467. // RFC7230§5.3.1: When making a request directly to an origin server, […]
  30468. // a client MUST send only the absolute path […] as the request-target.
  30469. this._currentUrl = /^\//.test(this._options.path) ?
  30470. url.format(this._options) :
  30471. // When making a request to a proxy, […]
  30472. // a client MUST send the target URI in absolute-form […].
  30473. this._options.path;
  30474. // End a redirected request
  30475. // (The first request must be ended explicitly with RedirectableRequest#end)
  30476. if (this._isRedirect) {
  30477. // Write the request entity and end
  30478. var i = 0;
  30479. var self = this;
  30480. var buffers = this._requestBodyBuffers;
  30481. (function writeNext(error) {
  30482. // Only write if this request has not been redirected yet
  30483. // istanbul ignore else
  30484. if (request === self._currentRequest) {
  30485. // Report any write errors
  30486. // istanbul ignore if
  30487. if (error) {
  30488. self.emit("error", error);
  30489. }
  30490. // Write the next buffer if there are still left
  30491. else if (i < buffers.length) {
  30492. var buffer = buffers[i++];
  30493. // istanbul ignore else
  30494. if (!request.finished) {
  30495. request.write(buffer.data, buffer.encoding, writeNext);
  30496. }
  30497. }
  30498. // End the request if `end` has been called on us
  30499. else if (self._ended) {
  30500. request.end();
  30501. }
  30502. }
  30503. }());
  30504. }
  30505. };
  30506. // Processes a response from the current native request
  30507. RedirectableRequest.prototype._processResponse = function (response) {
  30508. // Store the redirected response
  30509. var statusCode = response.statusCode;
  30510. if (this._options.trackRedirects) {
  30511. this._redirects.push({
  30512. url: this._currentUrl,
  30513. headers: response.headers,
  30514. statusCode: statusCode,
  30515. });
  30516. }
  30517. // RFC7231§6.4: The 3xx (Redirection) class of status code indicates
  30518. // that further action needs to be taken by the user agent in order to
  30519. // fulfill the request. If a Location header field is provided,
  30520. // the user agent MAY automatically redirect its request to the URI
  30521. // referenced by the Location field value,
  30522. // even if the specific status code is not understood.
  30523. // If the response is not a redirect; return it as-is
  30524. var location = response.headers.location;
  30525. if (!location || this._options.followRedirects === false ||
  30526. statusCode < 300 || statusCode >= 400) {
  30527. response.responseUrl = this._currentUrl;
  30528. response.redirects = this._redirects;
  30529. this.emit("response", response);
  30530. // Clean up
  30531. this._requestBodyBuffers = [];
  30532. return;
  30533. }
  30534. // The response is a redirect, so abort the current request
  30535. destroyRequest(this._currentRequest);
  30536. // Discard the remainder of the response to avoid waiting for data
  30537. response.destroy();
  30538. // RFC7231§6.4: A client SHOULD detect and intervene
  30539. // in cyclical redirections (i.e., "infinite" redirection loops).
  30540. if (++this._redirectCount > this._options.maxRedirects) {
  30541. throw new TooManyRedirectsError();
  30542. }
  30543. // Store the request headers if applicable
  30544. var requestHeaders;
  30545. var beforeRedirect = this._options.beforeRedirect;
  30546. if (beforeRedirect) {
  30547. requestHeaders = Object.assign({
  30548. // The Host header was set by nativeProtocol.request
  30549. Host: response.req.getHeader("host"),
  30550. }, this._options.headers);
  30551. }
  30552. // RFC7231§6.4: Automatic redirection needs to done with
  30553. // care for methods not known to be safe, […]
  30554. // RFC7231§6.4.2–3: For historical reasons, a user agent MAY change
  30555. // the request method from POST to GET for the subsequent request.
  30556. var method = this._options.method;
  30557. if ((statusCode === 301 || statusCode === 302) && this._options.method === "POST" ||
  30558. // RFC7231§6.4.4: The 303 (See Other) status code indicates that
  30559. // the server is redirecting the user agent to a different resource […]
  30560. // A user agent can perform a retrieval request targeting that URI
  30561. // (a GET or HEAD request if using HTTP) […]
  30562. (statusCode === 303) && !/^(?:GET|HEAD)$/.test(this._options.method)) {
  30563. this._options.method = "GET";
  30564. // Drop a possible entity and headers related to it
  30565. this._requestBodyBuffers = [];
  30566. removeMatchingHeaders(/^content-/i, this._options.headers);
  30567. }
  30568. // Drop the Host header, as the redirect might lead to a different host
  30569. var currentHostHeader = removeMatchingHeaders(/^host$/i, this._options.headers);
  30570. // If the redirect is relative, carry over the host of the last request
  30571. var currentUrlParts = parseUrl(this._currentUrl);
  30572. var currentHost = currentHostHeader || currentUrlParts.host;
  30573. var currentUrl = /^\w+:/.test(location) ? this._currentUrl :
  30574. url.format(Object.assign(currentUrlParts, { host: currentHost }));
  30575. // Create the redirected request
  30576. var redirectUrl = resolveUrl(location, currentUrl);
  30577. debug$6("redirecting to", redirectUrl.href);
  30578. this._isRedirect = true;
  30579. spreadUrlObject(redirectUrl, this._options);
  30580. // Drop confidential headers when redirecting to a less secure protocol
  30581. // or to a different domain that is not a superdomain
  30582. if (redirectUrl.protocol !== currentUrlParts.protocol &&
  30583. redirectUrl.protocol !== "https:" ||
  30584. redirectUrl.host !== currentHost &&
  30585. !isSubdomain(redirectUrl.host, currentHost)) {
  30586. removeMatchingHeaders(/^(?:(?:proxy-)?authorization|cookie)$/i, this._options.headers);
  30587. }
  30588. // Evaluate the beforeRedirect callback
  30589. if (isFunction(beforeRedirect)) {
  30590. var responseDetails = {
  30591. headers: response.headers,
  30592. statusCode: statusCode,
  30593. };
  30594. var requestDetails = {
  30595. url: currentUrl,
  30596. method: method,
  30597. headers: requestHeaders,
  30598. };
  30599. beforeRedirect(this._options, responseDetails, requestDetails);
  30600. this._sanitizeOptions(this._options);
  30601. }
  30602. // Perform the redirected request
  30603. this._performRequest();
  30604. };
  30605. // Wraps the key/value object of protocols with redirect functionality
  30606. function wrap(protocols) {
  30607. // Default settings
  30608. var exports = {
  30609. maxRedirects: 21,
  30610. maxBodyLength: 10 * 1024 * 1024,
  30611. };
  30612. // Wrap each protocol
  30613. var nativeProtocols = {};
  30614. Object.keys(protocols).forEach(function (scheme) {
  30615. var protocol = scheme + ":";
  30616. var nativeProtocol = nativeProtocols[protocol] = protocols[scheme];
  30617. var wrappedProtocol = exports[scheme] = Object.create(nativeProtocol);
  30618. // Executes a request, following redirects
  30619. function request(input, options, callback) {
  30620. // Parse parameters, ensuring that input is an object
  30621. if (isURL(input)) {
  30622. input = spreadUrlObject(input);
  30623. }
  30624. else if (isString(input)) {
  30625. input = spreadUrlObject(parseUrl(input));
  30626. }
  30627. else {
  30628. callback = options;
  30629. options = validateUrl(input);
  30630. input = { protocol: protocol };
  30631. }
  30632. if (isFunction(options)) {
  30633. callback = options;
  30634. options = null;
  30635. }
  30636. // Set defaults
  30637. options = Object.assign({
  30638. maxRedirects: exports.maxRedirects,
  30639. maxBodyLength: exports.maxBodyLength,
  30640. }, input, options);
  30641. options.nativeProtocols = nativeProtocols;
  30642. if (!isString(options.host) && !isString(options.hostname)) {
  30643. options.hostname = "::1";
  30644. }
  30645. assert.equal(options.protocol, protocol, "protocol mismatch");
  30646. debug$6("options", options);
  30647. return new RedirectableRequest(options, callback);
  30648. }
  30649. // Executes a GET request, following redirects
  30650. function get(input, options, callback) {
  30651. var wrappedRequest = wrappedProtocol.request(input, options, callback);
  30652. wrappedRequest.end();
  30653. return wrappedRequest;
  30654. }
  30655. // Expose the properties on the wrapped protocol
  30656. Object.defineProperties(wrappedProtocol, {
  30657. request: { value: request, configurable: true, enumerable: true, writable: true },
  30658. get: { value: get, configurable: true, enumerable: true, writable: true },
  30659. });
  30660. });
  30661. return exports;
  30662. }
  30663. function noop$1() { /* empty */ }
  30664. function parseUrl(input) {
  30665. var parsed;
  30666. // istanbul ignore else
  30667. if (useNativeURL) {
  30668. parsed = new URL$1(input);
  30669. }
  30670. else {
  30671. // Ensure the URL is valid and absolute
  30672. parsed = validateUrl(url.parse(input));
  30673. if (!isString(parsed.protocol)) {
  30674. throw new InvalidUrlError({ input });
  30675. }
  30676. }
  30677. return parsed;
  30678. }
  30679. function resolveUrl(relative, base) {
  30680. // istanbul ignore next
  30681. return useNativeURL ? new URL$1(relative, base) : parseUrl(url.resolve(base, relative));
  30682. }
  30683. function validateUrl(input) {
  30684. if (/^\[/.test(input.hostname) && !/^\[[:0-9a-f]+\]$/i.test(input.hostname)) {
  30685. throw new InvalidUrlError({ input: input.href || input });
  30686. }
  30687. if (/^\[/.test(input.host) && !/^\[[:0-9a-f]+\](:\d+)?$/i.test(input.host)) {
  30688. throw new InvalidUrlError({ input: input.href || input });
  30689. }
  30690. return input;
  30691. }
  30692. function spreadUrlObject(urlObject, target) {
  30693. var spread = target || {};
  30694. for (var key of preservedUrlFields) {
  30695. spread[key] = urlObject[key];
  30696. }
  30697. // Fix IPv6 hostname
  30698. if (spread.hostname.startsWith("[")) {
  30699. spread.hostname = spread.hostname.slice(1, -1);
  30700. }
  30701. // Ensure port is a number
  30702. if (spread.port !== "") {
  30703. spread.port = Number(spread.port);
  30704. }
  30705. // Concatenate path
  30706. spread.path = spread.search ? spread.pathname + spread.search : spread.pathname;
  30707. return spread;
  30708. }
  30709. function removeMatchingHeaders(regex, headers) {
  30710. var lastValue;
  30711. for (var header in headers) {
  30712. if (regex.test(header)) {
  30713. lastValue = headers[header];
  30714. delete headers[header];
  30715. }
  30716. }
  30717. return (lastValue === null || typeof lastValue === "undefined") ?
  30718. undefined : String(lastValue).trim();
  30719. }
  30720. function createErrorType(code, message, baseClass) {
  30721. // Create constructor
  30722. function CustomError(properties) {
  30723. // istanbul ignore else
  30724. if (isFunction(Error.captureStackTrace)) {
  30725. Error.captureStackTrace(this, this.constructor);
  30726. }
  30727. Object.assign(this, properties || {});
  30728. this.code = code;
  30729. this.message = this.cause ? message + ": " + this.cause.message : message;
  30730. }
  30731. // Attach constructor and set default properties
  30732. CustomError.prototype = new (baseClass || Error)();
  30733. Object.defineProperties(CustomError.prototype, {
  30734. constructor: {
  30735. value: CustomError,
  30736. enumerable: false,
  30737. },
  30738. name: {
  30739. value: "Error [" + code + "]",
  30740. enumerable: false,
  30741. },
  30742. });
  30743. return CustomError;
  30744. }
  30745. function destroyRequest(request, error) {
  30746. for (var event of events) {
  30747. request.removeListener(event, eventHandlers[event]);
  30748. }
  30749. request.on("error", noop$1);
  30750. request.destroy(error);
  30751. }
  30752. function isSubdomain(subdomain, domain) {
  30753. assert(isString(subdomain) && isString(domain));
  30754. var dot = subdomain.length - domain.length - 1;
  30755. return dot > 0 && subdomain[dot] === "." && subdomain.endsWith(domain);
  30756. }
  30757. function isString(value) {
  30758. return typeof value === "string" || value instanceof String;
  30759. }
  30760. function isFunction(value) {
  30761. return typeof value === "function";
  30762. }
  30763. function isBuffer(value) {
  30764. return typeof value === "object" && ("length" in value);
  30765. }
  30766. function isURL(value) {
  30767. return URL$1 && value instanceof URL$1;
  30768. }
  30769. // Exports
  30770. followRedirects$1.exports = wrap({ http: http$1, https: https$1 });
  30771. followRedirects$1.exports.wrap = wrap;
  30772. var followRedirectsExports = followRedirects$1.exports;
  30773. var httpNative = require$$1$2,
  30774. httpsNative = require$$1$3,
  30775. web_o = webOutgoing,
  30776. common$1 = common$3,
  30777. followRedirects = followRedirectsExports;
  30778. web_o = Object.keys(web_o).map(function(pass) {
  30779. return web_o[pass];
  30780. });
  30781. var nativeAgents = { http: httpNative, https: httpsNative };
  30782. /*!
  30783. * Array of passes.
  30784. *
  30785. * A `pass` is just a function that is executed on `req, res, options`
  30786. * so that you can easily add new checks while still keeping the base
  30787. * flexible.
  30788. */
  30789. var webIncoming = {
  30790. /**
  30791. * Sets `content-length` to '0' if request is of DELETE type.
  30792. *
  30793. * @param {ClientRequest} Req Request object
  30794. * @param {IncomingMessage} Res Response object
  30795. * @param {Object} Options Config object passed to the proxy
  30796. *
  30797. * @api private
  30798. */
  30799. deleteLength: function deleteLength(req, res, options) {
  30800. if((req.method === 'DELETE' || req.method === 'OPTIONS')
  30801. && !req.headers['content-length']) {
  30802. req.headers['content-length'] = '0';
  30803. delete req.headers['transfer-encoding'];
  30804. }
  30805. },
  30806. /**
  30807. * Sets timeout in request socket if it was specified in options.
  30808. *
  30809. * @param {ClientRequest} Req Request object
  30810. * @param {IncomingMessage} Res Response object
  30811. * @param {Object} Options Config object passed to the proxy
  30812. *
  30813. * @api private
  30814. */
  30815. timeout: function timeout(req, res, options) {
  30816. if(options.timeout) {
  30817. req.socket.setTimeout(options.timeout);
  30818. }
  30819. },
  30820. /**
  30821. * Sets `x-forwarded-*` headers if specified in config.
  30822. *
  30823. * @param {ClientRequest} Req Request object
  30824. * @param {IncomingMessage} Res Response object
  30825. * @param {Object} Options Config object passed to the proxy
  30826. *
  30827. * @api private
  30828. */
  30829. XHeaders: function XHeaders(req, res, options) {
  30830. if(!options.xfwd) return;
  30831. var encrypted = req.isSpdy || common$1.hasEncryptedConnection(req);
  30832. var values = {
  30833. for : req.connection.remoteAddress || req.socket.remoteAddress,
  30834. port : common$1.getPort(req),
  30835. proto: encrypted ? 'https' : 'http'
  30836. };
  30837. ['for', 'port', 'proto'].forEach(function(header) {
  30838. req.headers['x-forwarded-' + header] =
  30839. (req.headers['x-forwarded-' + header] || '') +
  30840. (req.headers['x-forwarded-' + header] ? ',' : '') +
  30841. values[header];
  30842. });
  30843. req.headers['x-forwarded-host'] = req.headers['x-forwarded-host'] || req.headers['host'] || '';
  30844. },
  30845. /**
  30846. * Does the actual proxying. If `forward` is enabled fires up
  30847. * a ForwardStream, same happens for ProxyStream. The request
  30848. * just dies otherwise.
  30849. *
  30850. * @param {ClientRequest} Req Request object
  30851. * @param {IncomingMessage} Res Response object
  30852. * @param {Object} Options Config object passed to the proxy
  30853. *
  30854. * @api private
  30855. */
  30856. stream: function stream(req, res, options, _, server, clb) {
  30857. // And we begin!
  30858. server.emit('start', req, res, options.target || options.forward);
  30859. var agents = options.followRedirects ? followRedirects : nativeAgents;
  30860. var http = agents.http;
  30861. var https = agents.https;
  30862. if(options.forward) {
  30863. // If forward enable, so just pipe the request
  30864. var forwardReq = (options.forward.protocol === 'https:' ? https : http).request(
  30865. common$1.setupOutgoing(options.ssl || {}, options, req, 'forward')
  30866. );
  30867. // error handler (e.g. ECONNRESET, ECONNREFUSED)
  30868. // Handle errors on incoming request as well as it makes sense to
  30869. var forwardError = createErrorHandler(forwardReq, options.forward);
  30870. req.on('error', forwardError);
  30871. forwardReq.on('error', forwardError);
  30872. (options.buffer || req).pipe(forwardReq);
  30873. if(!options.target) { return res.end(); }
  30874. }
  30875. // Request initalization
  30876. var proxyReq = (options.target.protocol === 'https:' ? https : http).request(
  30877. common$1.setupOutgoing(options.ssl || {}, options, req)
  30878. );
  30879. // Enable developers to modify the proxyReq before headers are sent
  30880. proxyReq.on('socket', function(socket) {
  30881. if(server && !proxyReq.getHeader('expect')) {
  30882. server.emit('proxyReq', proxyReq, req, res, options);
  30883. }
  30884. });
  30885. // allow outgoing socket to timeout so that we could
  30886. // show an error page at the initial request
  30887. if(options.proxyTimeout) {
  30888. proxyReq.setTimeout(options.proxyTimeout, function() {
  30889. proxyReq.abort();
  30890. });
  30891. }
  30892. // Ensure we abort proxy if request is aborted
  30893. req.on('aborted', function () {
  30894. proxyReq.abort();
  30895. });
  30896. // handle errors in proxy and incoming request, just like for forward proxy
  30897. var proxyError = createErrorHandler(proxyReq, options.target);
  30898. req.on('error', proxyError);
  30899. proxyReq.on('error', proxyError);
  30900. function createErrorHandler(proxyReq, url) {
  30901. return function proxyError(err) {
  30902. if (req.socket.destroyed && err.code === 'ECONNRESET') {
  30903. server.emit('econnreset', err, req, res, url);
  30904. return proxyReq.abort();
  30905. }
  30906. if (clb) {
  30907. clb(err, req, res, url);
  30908. } else {
  30909. server.emit('error', err, req, res, url);
  30910. }
  30911. }
  30912. }
  30913. (options.buffer || req).pipe(proxyReq);
  30914. proxyReq.on('response', function(proxyRes) {
  30915. if(server) { server.emit('proxyRes', proxyRes, req, res); }
  30916. if(!res.headersSent && !options.selfHandleResponse) {
  30917. for(var i=0; i < web_o.length; i++) {
  30918. if(web_o[i](req, res, proxyRes, options)) { break; }
  30919. }
  30920. }
  30921. if (!res.finished) {
  30922. // Allow us to listen when the proxy has completed
  30923. proxyRes.on('end', function () {
  30924. if (server) server.emit('end', req, res, proxyRes);
  30925. });
  30926. // We pipe to the response unless its expected to be handled by the user
  30927. if (!options.selfHandleResponse) proxyRes.pipe(res);
  30928. } else {
  30929. if (server) server.emit('end', req, res, proxyRes);
  30930. }
  30931. });
  30932. }
  30933. };
  30934. var http = require$$1$2,
  30935. https = require$$1$3,
  30936. common = common$3;
  30937. /*!
  30938. * Array of passes.
  30939. *
  30940. * A `pass` is just a function that is executed on `req, socket, options`
  30941. * so that you can easily add new checks while still keeping the base
  30942. * flexible.
  30943. */
  30944. /*
  30945. * Websockets Passes
  30946. *
  30947. */
  30948. var wsIncoming = {
  30949. /**
  30950. * WebSocket requests must have the `GET` method and
  30951. * the `upgrade:websocket` header
  30952. *
  30953. * @param {ClientRequest} Req Request object
  30954. * @param {Socket} Websocket
  30955. *
  30956. * @api private
  30957. */
  30958. checkMethodAndHeader : function checkMethodAndHeader(req, socket) {
  30959. if (req.method !== 'GET' || !req.headers.upgrade) {
  30960. socket.destroy();
  30961. return true;
  30962. }
  30963. if (req.headers.upgrade.toLowerCase() !== 'websocket') {
  30964. socket.destroy();
  30965. return true;
  30966. }
  30967. },
  30968. /**
  30969. * Sets `x-forwarded-*` headers if specified in config.
  30970. *
  30971. * @param {ClientRequest} Req Request object
  30972. * @param {Socket} Websocket
  30973. * @param {Object} Options Config object passed to the proxy
  30974. *
  30975. * @api private
  30976. */
  30977. XHeaders : function XHeaders(req, socket, options) {
  30978. if(!options.xfwd) return;
  30979. var values = {
  30980. for : req.connection.remoteAddress || req.socket.remoteAddress,
  30981. port : common.getPort(req),
  30982. proto: common.hasEncryptedConnection(req) ? 'wss' : 'ws'
  30983. };
  30984. ['for', 'port', 'proto'].forEach(function(header) {
  30985. req.headers['x-forwarded-' + header] =
  30986. (req.headers['x-forwarded-' + header] || '') +
  30987. (req.headers['x-forwarded-' + header] ? ',' : '') +
  30988. values[header];
  30989. });
  30990. },
  30991. /**
  30992. * Does the actual proxying. Make the request and upgrade it
  30993. * send the Switching Protocols request and pipe the sockets.
  30994. *
  30995. * @param {ClientRequest} Req Request object
  30996. * @param {Socket} Websocket
  30997. * @param {Object} Options Config object passed to the proxy
  30998. *
  30999. * @api private
  31000. */
  31001. stream : function stream(req, socket, options, head, server, clb) {
  31002. var createHttpHeader = function(line, headers) {
  31003. return Object.keys(headers).reduce(function (head, key) {
  31004. var value = headers[key];
  31005. if (!Array.isArray(value)) {
  31006. head.push(key + ': ' + value);
  31007. return head;
  31008. }
  31009. for (var i = 0; i < value.length; i++) {
  31010. head.push(key + ': ' + value[i]);
  31011. }
  31012. return head;
  31013. }, [line])
  31014. .join('\r\n') + '\r\n\r\n';
  31015. };
  31016. common.setupSocket(socket);
  31017. if (head && head.length) socket.unshift(head);
  31018. var proxyReq = (common.isSSL.test(options.target.protocol) ? https : http).request(
  31019. common.setupOutgoing(options.ssl || {}, options, req)
  31020. );
  31021. // Enable developers to modify the proxyReq before headers are sent
  31022. if (server) { server.emit('proxyReqWs', proxyReq, req, socket, options, head); }
  31023. // Error Handler
  31024. proxyReq.on('error', onOutgoingError);
  31025. proxyReq.on('response', function (res) {
  31026. // if upgrade event isn't going to happen, close the socket
  31027. if (!res.upgrade) {
  31028. socket.write(createHttpHeader('HTTP/' + res.httpVersion + ' ' + res.statusCode + ' ' + res.statusMessage, res.headers));
  31029. res.pipe(socket);
  31030. }
  31031. });
  31032. proxyReq.on('upgrade', function(proxyRes, proxySocket, proxyHead) {
  31033. proxySocket.on('error', onOutgoingError);
  31034. // Allow us to listen when the websocket has completed
  31035. proxySocket.on('end', function () {
  31036. server.emit('close', proxyRes, proxySocket, proxyHead);
  31037. });
  31038. // The pipe below will end proxySocket if socket closes cleanly, but not
  31039. // if it errors (eg, vanishes from the net and starts returning
  31040. // EHOSTUNREACH). We need to do that explicitly.
  31041. socket.on('error', function () {
  31042. proxySocket.end();
  31043. });
  31044. common.setupSocket(proxySocket);
  31045. if (proxyHead && proxyHead.length) proxySocket.unshift(proxyHead);
  31046. //
  31047. // Remark: Handle writing the headers to the socket when switching protocols
  31048. // Also handles when a header is an array
  31049. //
  31050. socket.write(createHttpHeader('HTTP/1.1 101 Switching Protocols', proxyRes.headers));
  31051. proxySocket.pipe(socket).pipe(proxySocket);
  31052. server.emit('open', proxySocket);
  31053. server.emit('proxySocket', proxySocket); //DEPRECATED.
  31054. });
  31055. return proxyReq.end(); // XXX: CHECK IF THIS IS THIS CORRECT
  31056. function onOutgoingError(err) {
  31057. if (clb) {
  31058. clb(err, req, socket);
  31059. } else {
  31060. server.emit('error', err, req, socket);
  31061. }
  31062. socket.end();
  31063. }
  31064. }
  31065. };
  31066. (function (module) {
  31067. var httpProxy = module.exports,
  31068. parse_url = require$$0$5.parse,
  31069. EE3 = eventemitter3Exports,
  31070. http = require$$1$2,
  31071. https = require$$1$3,
  31072. web = webIncoming,
  31073. ws = wsIncoming;
  31074. httpProxy.Server = ProxyServer;
  31075. /**
  31076. * Returns a function that creates the loader for
  31077. * either `ws` or `web`'s passes.
  31078. *
  31079. * Examples:
  31080. *
  31081. * httpProxy.createRightProxy('ws')
  31082. * // => [Function]
  31083. *
  31084. * @param {String} Type Either 'ws' or 'web'
  31085. * @return {Function} Loader Function that when called returns an iterator for the right passes
  31086. *
  31087. * @api private
  31088. */
  31089. function createRightProxy(type) {
  31090. return function(options) {
  31091. return function(req, res /*, [head], [opts] */) {
  31092. var passes = (type === 'ws') ? this.wsPasses : this.webPasses,
  31093. args = [].slice.call(arguments),
  31094. cntr = args.length - 1,
  31095. head, cbl;
  31096. /* optional args parse begin */
  31097. if(typeof args[cntr] === 'function') {
  31098. cbl = args[cntr];
  31099. cntr--;
  31100. }
  31101. var requestOptions = options;
  31102. if(
  31103. !(args[cntr] instanceof Buffer) &&
  31104. args[cntr] !== res
  31105. ) {
  31106. //Copy global options
  31107. requestOptions = Object.assign({}, options);
  31108. //Overwrite with request options
  31109. Object.assign(requestOptions, args[cntr]);
  31110. cntr--;
  31111. }
  31112. if(args[cntr] instanceof Buffer) {
  31113. head = args[cntr];
  31114. }
  31115. /* optional args parse end */
  31116. ['target', 'forward'].forEach(function(e) {
  31117. if (typeof requestOptions[e] === 'string')
  31118. requestOptions[e] = parse_url(requestOptions[e]);
  31119. });
  31120. if (!requestOptions.target && !requestOptions.forward) {
  31121. return this.emit('error', new Error('Must provide a proper URL as target'));
  31122. }
  31123. for(var i=0; i < passes.length; i++) {
  31124. /**
  31125. * Call of passes functions
  31126. * pass(req, res, options, head)
  31127. *
  31128. * In WebSockets case the `res` variable
  31129. * refer to the connection socket
  31130. * pass(req, socket, options, head)
  31131. */
  31132. if(passes[i](req, res, requestOptions, head, this, cbl)) { // passes can return a truthy value to halt the loop
  31133. break;
  31134. }
  31135. }
  31136. };
  31137. };
  31138. }
  31139. httpProxy.createRightProxy = createRightProxy;
  31140. function ProxyServer(options) {
  31141. EE3.call(this);
  31142. options = options || {};
  31143. options.prependPath = options.prependPath === false ? false : true;
  31144. this.web = this.proxyRequest = createRightProxy('web')(options);
  31145. this.ws = this.proxyWebsocketRequest = createRightProxy('ws')(options);
  31146. this.options = options;
  31147. this.webPasses = Object.keys(web).map(function(pass) {
  31148. return web[pass];
  31149. });
  31150. this.wsPasses = Object.keys(ws).map(function(pass) {
  31151. return ws[pass];
  31152. });
  31153. this.on('error', this.onError, this);
  31154. }
  31155. require$$1.inherits(ProxyServer, EE3);
  31156. ProxyServer.prototype.onError = function (err) {
  31157. //
  31158. // Remark: Replicate node core behavior using EE3
  31159. // so we force people to handle their own errors
  31160. //
  31161. if(this.listeners('error').length === 1) {
  31162. throw err;
  31163. }
  31164. };
  31165. ProxyServer.prototype.listen = function(port, hostname) {
  31166. var self = this,
  31167. closure = function(req, res) { self.web(req, res); };
  31168. this._server = this.options.ssl ?
  31169. https.createServer(this.options.ssl, closure) :
  31170. http.createServer(closure);
  31171. if(this.options.ws) {
  31172. this._server.on('upgrade', function(req, socket, head) { self.ws(req, socket, head); });
  31173. }
  31174. this._server.listen(port, hostname);
  31175. return this;
  31176. };
  31177. ProxyServer.prototype.close = function(callback) {
  31178. var self = this;
  31179. if (this._server) {
  31180. this._server.close(done);
  31181. }
  31182. // Wrap callback to nullify server after all open connections are closed.
  31183. function done() {
  31184. self._server = null;
  31185. if (callback) {
  31186. callback.apply(null, arguments);
  31187. }
  31188. } };
  31189. ProxyServer.prototype.before = function(type, passName, callback) {
  31190. if (type !== 'ws' && type !== 'web') {
  31191. throw new Error('type must be `web` or `ws`');
  31192. }
  31193. var passes = (type === 'ws') ? this.wsPasses : this.webPasses,
  31194. i = false;
  31195. passes.forEach(function(v, idx) {
  31196. if(v.name === passName) i = idx;
  31197. });
  31198. if(i === false) throw new Error('No such pass');
  31199. passes.splice(i, 0, callback);
  31200. };
  31201. ProxyServer.prototype.after = function(type, passName, callback) {
  31202. if (type !== 'ws' && type !== 'web') {
  31203. throw new Error('type must be `web` or `ws`');
  31204. }
  31205. var passes = (type === 'ws') ? this.wsPasses : this.webPasses,
  31206. i = false;
  31207. passes.forEach(function(v, idx) {
  31208. if(v.name === passName) i = idx;
  31209. });
  31210. if(i === false) throw new Error('No such pass');
  31211. passes.splice(i++, 0, callback);
  31212. };
  31213. } (httpProxy$3));
  31214. var httpProxyExports = httpProxy$3.exports;
  31215. // Use explicit /index.js to help browserify negociation in require '/lib/http-proxy' (!)
  31216. var ProxyServer = httpProxyExports.Server;
  31217. /**
  31218. * Creates the proxy server.
  31219. *
  31220. * Examples:
  31221. *
  31222. * httpProxy.createProxyServer({ .. }, 8000)
  31223. * // => '{ web: [Function], ws: [Function] ... }'
  31224. *
  31225. * @param {Object} Options Config object passed to the proxy
  31226. *
  31227. * @return {Object} Proxy Proxy object with handlers for `ws` and `web` requests
  31228. *
  31229. * @api public
  31230. */
  31231. function createProxyServer(options) {
  31232. /*
  31233. * `options` is needed and it must have the following layout:
  31234. *
  31235. * {
  31236. * target : <url string to be parsed with the url module>
  31237. * forward: <url string to be parsed with the url module>
  31238. * agent : <object to be passed to http(s).request>
  31239. * ssl : <object to be passed to https.createServer()>
  31240. * ws : <true/false, if you want to proxy websockets>
  31241. * xfwd : <true/false, adds x-forward headers>
  31242. * secure : <true/false, verify SSL certificate>
  31243. * toProxy: <true/false, explicitly specify if we are proxying to another proxy>
  31244. * prependPath: <true/false, Default: true - specify whether you want to prepend the target's path to the proxy path>
  31245. * ignorePath: <true/false, Default: false - specify whether you want to ignore the proxy path of the incoming request>
  31246. * localAddress : <Local interface string to bind for outgoing connections>
  31247. * changeOrigin: <true/false, Default: false - changes the origin of the host header to the target URL>
  31248. * preserveHeaderKeyCase: <true/false, Default: false - specify whether you want to keep letter case of response header key >
  31249. * auth : Basic authentication i.e. 'user:password' to compute an Authorization header.
  31250. * hostRewrite: rewrites the location hostname on (201/301/302/307/308) redirects, Default: null.
  31251. * autoRewrite: rewrites the location host/port on (201/301/302/307/308) redirects based on requested host/port. Default: false.
  31252. * protocolRewrite: rewrites the location protocol on (201/301/302/307/308) redirects to 'http' or 'https'. Default: null.
  31253. * }
  31254. *
  31255. * NOTE: `options.ws` and `options.ssl` are optional.
  31256. * `options.target and `options.forward` cannot be
  31257. * both missing
  31258. * }
  31259. */
  31260. return new ProxyServer(options);
  31261. }
  31262. ProxyServer.createProxyServer = createProxyServer;
  31263. ProxyServer.createServer = createProxyServer;
  31264. ProxyServer.createProxy = createProxyServer;
  31265. /**
  31266. * Export the proxy "Server" as the main export.
  31267. */
  31268. var httpProxy$2 = ProxyServer;
  31269. /*!
  31270. * Caron dimonio, con occhi di bragia
  31271. * loro accennando, tutte le raccoglie;
  31272. * batte col remo qualunque s’adagia
  31273. *
  31274. * Charon the demon, with the eyes of glede,
  31275. * Beckoning to them, collects them all together,
  31276. * Beats with his oar whoever lags behind
  31277. *
  31278. * Dante - The Divine Comedy (Canto III)
  31279. */
  31280. var httpProxy = httpProxy$2;
  31281. var httpProxy$1 = /*@__PURE__*/getDefaultExportFromCjs(httpProxy);
  31282. const debug$5 = createDebugger("vite:proxy");
  31283. const rewriteOriginHeader = (proxyReq, options, config) => {
  31284. if (options.rewriteWsOrigin) {
  31285. const { target } = options;
  31286. if (proxyReq.headersSent) {
  31287. config.logger.warn(
  31288. colors$1.yellow(
  31289. `Unable to rewrite Origin header as headers are already sent.`
  31290. )
  31291. );
  31292. return;
  31293. }
  31294. if (proxyReq.getHeader("origin") && target) {
  31295. const changedOrigin = typeof target === "object" ? `${target.protocol}//${target.host}` : target;
  31296. proxyReq.setHeader("origin", changedOrigin);
  31297. }
  31298. }
  31299. };
  31300. function proxyMiddleware(httpServer, options, config) {
  31301. const proxies = {};
  31302. Object.keys(options).forEach((context) => {
  31303. let opts = options[context];
  31304. if (!opts) {
  31305. return;
  31306. }
  31307. if (typeof opts === "string") {
  31308. opts = { target: opts, changeOrigin: true };
  31309. }
  31310. const proxy = httpProxy$1.createProxyServer(opts);
  31311. if (opts.configure) {
  31312. opts.configure(proxy, opts);
  31313. }
  31314. proxy.on("error", (err, _req, originalRes) => {
  31315. const res = originalRes;
  31316. if (!res) {
  31317. config.logger.error(
  31318. `${colors$1.red(`http proxy error: ${err.message}`)}
  31319. ${err.stack}`,
  31320. {
  31321. timestamp: true,
  31322. error: err
  31323. }
  31324. );
  31325. } else if ("req" in res) {
  31326. config.logger.error(
  31327. `${colors$1.red(`http proxy error: ${originalRes.req.url}`)}
  31328. ${err.stack}`,
  31329. {
  31330. timestamp: true,
  31331. error: err
  31332. }
  31333. );
  31334. if (!res.headersSent && !res.writableEnded) {
  31335. res.writeHead(500, {
  31336. "Content-Type": "text/plain"
  31337. }).end();
  31338. }
  31339. } else {
  31340. config.logger.error(`${colors$1.red(`ws proxy error:`)}
  31341. ${err.stack}`, {
  31342. timestamp: true,
  31343. error: err
  31344. });
  31345. res.end();
  31346. }
  31347. });
  31348. proxy.on("proxyReqWs", (proxyReq, _req, socket, options2) => {
  31349. rewriteOriginHeader(proxyReq, options2, config);
  31350. socket.on("error", (err) => {
  31351. config.logger.error(
  31352. `${colors$1.red(`ws proxy socket error:`)}
  31353. ${err.stack}`,
  31354. {
  31355. timestamp: true,
  31356. error: err
  31357. }
  31358. );
  31359. });
  31360. });
  31361. proxy.on("proxyRes", (proxyRes, _req, res) => {
  31362. res.on("close", () => {
  31363. if (!res.writableEnded) {
  31364. debug$5?.("destroying proxyRes in proxyRes close event");
  31365. proxyRes.destroy();
  31366. }
  31367. });
  31368. });
  31369. proxies[context] = [proxy, { ...opts }];
  31370. });
  31371. if (httpServer) {
  31372. httpServer.on("upgrade", async (req, socket, head) => {
  31373. const url = req.url;
  31374. for (const context in proxies) {
  31375. if (doesProxyContextMatchUrl(context, url)) {
  31376. const [proxy, opts] = proxies[context];
  31377. if (opts.ws || opts.target?.toString().startsWith("ws:") || opts.target?.toString().startsWith("wss:")) {
  31378. if (opts.bypass) {
  31379. try {
  31380. const bypassResult = await opts.bypass(req, void 0, opts);
  31381. if (typeof bypassResult === "string") {
  31382. debug$5?.(`bypass: ${req.url} -> ${bypassResult}`);
  31383. req.url = bypassResult;
  31384. return;
  31385. }
  31386. if (bypassResult === false) {
  31387. debug$5?.(`bypass: ${req.url} -> 404`);
  31388. socket.end("HTTP/1.1 404 Not Found\r\n\r\n", "");
  31389. return;
  31390. }
  31391. } catch (err) {
  31392. config.logger.error(
  31393. `${colors$1.red(`ws proxy bypass error:`)}
  31394. ${err.stack}`,
  31395. {
  31396. timestamp: true,
  31397. error: err
  31398. }
  31399. );
  31400. return;
  31401. }
  31402. }
  31403. if (opts.rewrite) {
  31404. req.url = opts.rewrite(url);
  31405. }
  31406. debug$5?.(`${req.url} -> ws ${opts.target}`);
  31407. proxy.ws(req, socket, head);
  31408. return;
  31409. }
  31410. }
  31411. }
  31412. });
  31413. }
  31414. return async function viteProxyMiddleware(req, res, next) {
  31415. const url = req.url;
  31416. for (const context in proxies) {
  31417. if (doesProxyContextMatchUrl(context, url)) {
  31418. const [proxy, opts] = proxies[context];
  31419. const options2 = {};
  31420. if (opts.bypass) {
  31421. try {
  31422. const bypassResult = await opts.bypass(req, res, opts);
  31423. if (typeof bypassResult === "string") {
  31424. debug$5?.(`bypass: ${req.url} -> ${bypassResult}`);
  31425. req.url = bypassResult;
  31426. if (res.writableEnded) {
  31427. return;
  31428. }
  31429. return next();
  31430. }
  31431. if (bypassResult === false) {
  31432. debug$5?.(`bypass: ${req.url} -> 404`);
  31433. res.statusCode = 404;
  31434. return res.end();
  31435. }
  31436. } catch (e) {
  31437. debug$5?.(`bypass: ${req.url} -> ${e}`);
  31438. return next(e);
  31439. }
  31440. }
  31441. debug$5?.(`${req.url} -> ${opts.target || opts.forward}`);
  31442. if (opts.rewrite) {
  31443. req.url = opts.rewrite(req.url);
  31444. }
  31445. proxy.web(req, res, options2);
  31446. return;
  31447. }
  31448. }
  31449. next();
  31450. };
  31451. }
  31452. function doesProxyContextMatchUrl(context, url) {
  31453. return context[0] === "^" && new RegExp(context).test(url) || url.startsWith(context);
  31454. }
  31455. const debug$4 = createDebugger("vite:html-fallback");
  31456. function htmlFallbackMiddleware(root, spaFallback) {
  31457. return function viteHtmlFallbackMiddleware(req, _res, next) {
  31458. if (
  31459. // Only accept GET or HEAD
  31460. req.method !== "GET" && req.method !== "HEAD" || // Exclude default favicon requests
  31461. req.url === "/favicon.ico" || // Require Accept: text/html or */*
  31462. !(req.headers.accept === void 0 || // equivalent to `Accept: */*`
  31463. req.headers.accept === "" || // equivalent to `Accept: */*`
  31464. req.headers.accept.includes("text/html") || req.headers.accept.includes("*/*"))
  31465. ) {
  31466. return next();
  31467. }
  31468. const url = cleanUrl(req.url);
  31469. const pathname = decodeURIComponent(url);
  31470. if (pathname.endsWith(".html")) {
  31471. const filePath = path$b.join(root, pathname);
  31472. if (fs__default.existsSync(filePath)) {
  31473. debug$4?.(`Rewriting ${req.method} ${req.url} to ${url}`);
  31474. req.url = url;
  31475. return next();
  31476. }
  31477. } else if (pathname.endsWith("/")) {
  31478. const filePath = path$b.join(root, pathname, "index.html");
  31479. if (fs__default.existsSync(filePath)) {
  31480. const newUrl = url + "index.html";
  31481. debug$4?.(`Rewriting ${req.method} ${req.url} to ${newUrl}`);
  31482. req.url = newUrl;
  31483. return next();
  31484. }
  31485. } else {
  31486. const filePath = path$b.join(root, pathname + ".html");
  31487. if (fs__default.existsSync(filePath)) {
  31488. const newUrl = url + ".html";
  31489. debug$4?.(`Rewriting ${req.method} ${req.url} to ${newUrl}`);
  31490. req.url = newUrl;
  31491. return next();
  31492. }
  31493. }
  31494. if (spaFallback) {
  31495. debug$4?.(`Rewriting ${req.method} ${req.url} to /index.html`);
  31496. req.url = "/index.html";
  31497. }
  31498. next();
  31499. };
  31500. }
  31501. /*!
  31502. * etag
  31503. * Copyright(c) 2014-2016 Douglas Christopher Wilson
  31504. * MIT Licensed
  31505. */
  31506. /**
  31507. * Module exports.
  31508. * @public
  31509. */
  31510. var etag_1 = etag;
  31511. /**
  31512. * Module dependencies.
  31513. * @private
  31514. */
  31515. var crypto = require$$3;
  31516. var Stats = require$$0$4.Stats;
  31517. /**
  31518. * Module variables.
  31519. * @private
  31520. */
  31521. var toString = Object.prototype.toString;
  31522. /**
  31523. * Generate an entity tag.
  31524. *
  31525. * @param {Buffer|string} entity
  31526. * @return {string}
  31527. * @private
  31528. */
  31529. function entitytag (entity) {
  31530. if (entity.length === 0) {
  31531. // fast-path empty
  31532. return '"0-2jmj7l5rSw0yVb/vlWAYkK/YBwk"'
  31533. }
  31534. // compute hash of entity
  31535. var hash = crypto
  31536. .createHash('sha1')
  31537. .update(entity, 'utf8')
  31538. .digest('base64')
  31539. .substring(0, 27);
  31540. // compute length of entity
  31541. var len = typeof entity === 'string'
  31542. ? Buffer.byteLength(entity, 'utf8')
  31543. : entity.length;
  31544. return '"' + len.toString(16) + '-' + hash + '"'
  31545. }
  31546. /**
  31547. * Create a simple ETag.
  31548. *
  31549. * @param {string|Buffer|Stats} entity
  31550. * @param {object} [options]
  31551. * @param {boolean} [options.weak]
  31552. * @return {String}
  31553. * @public
  31554. */
  31555. function etag (entity, options) {
  31556. if (entity == null) {
  31557. throw new TypeError('argument entity is required')
  31558. }
  31559. // support fs.Stats object
  31560. var isStats = isstats(entity);
  31561. var weak = options && typeof options.weak === 'boolean'
  31562. ? options.weak
  31563. : isStats;
  31564. // validate argument
  31565. if (!isStats && typeof entity !== 'string' && !Buffer.isBuffer(entity)) {
  31566. throw new TypeError('argument entity must be string, Buffer, or fs.Stats')
  31567. }
  31568. // generate entity tag
  31569. var tag = isStats
  31570. ? stattag(entity)
  31571. : entitytag(entity);
  31572. return weak
  31573. ? 'W/' + tag
  31574. : tag
  31575. }
  31576. /**
  31577. * Determine if object is a Stats object.
  31578. *
  31579. * @param {object} obj
  31580. * @return {boolean}
  31581. * @api private
  31582. */
  31583. function isstats (obj) {
  31584. // genuine fs.Stats
  31585. if (typeof Stats === 'function' && obj instanceof Stats) {
  31586. return true
  31587. }
  31588. // quack quack
  31589. return obj && typeof obj === 'object' &&
  31590. 'ctime' in obj && toString.call(obj.ctime) === '[object Date]' &&
  31591. 'mtime' in obj && toString.call(obj.mtime) === '[object Date]' &&
  31592. 'ino' in obj && typeof obj.ino === 'number' &&
  31593. 'size' in obj && typeof obj.size === 'number'
  31594. }
  31595. /**
  31596. * Generate a tag for a stat.
  31597. *
  31598. * @param {object} stat
  31599. * @return {string}
  31600. * @private
  31601. */
  31602. function stattag (stat) {
  31603. var mtime = stat.mtime.getTime().toString(16);
  31604. var size = stat.size.toString(16);
  31605. return '"' + size + '-' + mtime + '"'
  31606. }
  31607. var getEtag = /*@__PURE__*/getDefaultExportFromCjs(etag_1);
  31608. const debug$3 = createDebugger("vite:send", {
  31609. onlyWhenFocused: true
  31610. });
  31611. const alias = {
  31612. js: "text/javascript",
  31613. css: "text/css",
  31614. html: "text/html",
  31615. json: "application/json"
  31616. };
  31617. function send$1(req, res, content, type, options) {
  31618. const {
  31619. etag = getEtag(content, { weak: true }),
  31620. cacheControl = "no-cache",
  31621. headers,
  31622. map
  31623. } = options;
  31624. if (res.writableEnded) {
  31625. return;
  31626. }
  31627. if (req.headers["if-none-match"] === etag) {
  31628. res.statusCode = 304;
  31629. res.end();
  31630. return;
  31631. }
  31632. res.setHeader("Content-Type", alias[type] || type);
  31633. res.setHeader("Cache-Control", cacheControl);
  31634. res.setHeader("Etag", etag);
  31635. if (headers) {
  31636. for (const name in headers) {
  31637. res.setHeader(name, headers[name]);
  31638. }
  31639. }
  31640. if (map && "version" in map && map.mappings) {
  31641. if (type === "js" || type === "css") {
  31642. content = getCodeWithSourcemap(type, content.toString(), map);
  31643. }
  31644. } else if (type === "js" && (!map || map.mappings !== "")) {
  31645. const code = content.toString();
  31646. if (convertSourceMap.mapFileCommentRegex.test(code)) {
  31647. debug$3?.(`Skipped injecting fallback sourcemap for ${req.url}`);
  31648. } else {
  31649. const urlWithoutTimestamp = removeTimestampQuery(req.url);
  31650. const ms = new MagicString(code);
  31651. content = getCodeWithSourcemap(
  31652. type,
  31653. code,
  31654. ms.generateMap({
  31655. source: path$b.basename(urlWithoutTimestamp),
  31656. hires: "boundary",
  31657. includeContent: true
  31658. })
  31659. );
  31660. }
  31661. }
  31662. res.statusCode = 200;
  31663. res.end(content);
  31664. return;
  31665. }
  31666. function totalist(dir, callback, pre='') {
  31667. dir = resolve$3('.', dir);
  31668. let arr = readdirSync(dir);
  31669. let i=0, abs, stats;
  31670. for (; i < arr.length; i++) {
  31671. abs = join(dir, arr[i]);
  31672. stats = statSync(abs);
  31673. stats.isDirectory()
  31674. ? totalist(abs, callback, join(pre, arr[i]))
  31675. : callback(join(pre, arr[i]), abs, stats);
  31676. }
  31677. }
  31678. /**
  31679. * @typedef ParsedURL
  31680. * @type {import('.').ParsedURL}
  31681. */
  31682. /**
  31683. * @typedef Request
  31684. * @property {string} url
  31685. * @property {ParsedURL} _parsedUrl
  31686. */
  31687. /**
  31688. * @param {Request} req
  31689. * @returns {ParsedURL|void}
  31690. */
  31691. function parse(req) {
  31692. let raw = req.url;
  31693. if (raw == null) return;
  31694. let prev = req._parsedUrl;
  31695. if (prev && prev.raw === raw) return prev;
  31696. let pathname=raw, search='', query;
  31697. if (raw.length > 1) {
  31698. let idx = raw.indexOf('?', 1);
  31699. if (idx !== -1) {
  31700. search = raw.substring(idx);
  31701. pathname = raw.substring(0, idx);
  31702. if (search.length > 1) {
  31703. query = qs.parse(search.substring(1));
  31704. }
  31705. }
  31706. }
  31707. return req._parsedUrl = { pathname, search, query, raw };
  31708. }
  31709. const noop = () => {};
  31710. function isMatch(uri, arr) {
  31711. for (let i=0; i < arr.length; i++) {
  31712. if (arr[i].test(uri)) return true;
  31713. }
  31714. }
  31715. function toAssume(uri, extns) {
  31716. let i=0, x, len=uri.length - 1;
  31717. if (uri.charCodeAt(len) === 47) {
  31718. uri = uri.substring(0, len);
  31719. }
  31720. let arr=[], tmp=`${uri}/index`;
  31721. for (; i < extns.length; i++) {
  31722. x = extns[i] ? `.${extns[i]}` : '';
  31723. if (uri) arr.push(uri + x);
  31724. arr.push(tmp + x);
  31725. }
  31726. return arr;
  31727. }
  31728. function viaCache(cache, uri, extns) {
  31729. let i=0, data, arr=toAssume(uri, extns);
  31730. for (; i < arr.length; i++) {
  31731. if (data = cache[arr[i]]) return data;
  31732. }
  31733. }
  31734. function viaLocal(dir, isEtag, uri, extns, shouldServe) {
  31735. let i=0, arr=toAssume(uri, extns);
  31736. let abs, stats, name, headers;
  31737. for (; i < arr.length; i++) {
  31738. abs = normalize(join$1(dir, name=arr[i]));
  31739. if (abs.startsWith(dir) && fs$8.existsSync(abs)) {
  31740. stats = fs$8.statSync(abs);
  31741. if (stats.isDirectory()) continue;
  31742. if (shouldServe && !shouldServe(abs)) continue;
  31743. headers = toHeaders(name, stats, isEtag);
  31744. headers['Cache-Control'] = isEtag ? 'no-cache' : 'no-store';
  31745. return { abs, stats, headers };
  31746. }
  31747. }
  31748. }
  31749. function is404(req, res) {
  31750. return (res.statusCode=404,res.end());
  31751. }
  31752. function send(req, res, file, stats, headers) {
  31753. let code=200, tmp, opts={};
  31754. headers = { ...headers };
  31755. for (let key in headers) {
  31756. tmp = res.getHeader(key);
  31757. if (tmp) headers[key] = tmp;
  31758. }
  31759. if (tmp = res.getHeader('content-type')) {
  31760. headers['Content-Type'] = tmp;
  31761. }
  31762. if (req.headers.range) {
  31763. code = 206;
  31764. let [x, y] = req.headers.range.replace('bytes=', '').split('-');
  31765. let end = opts.end = parseInt(y, 10) || stats.size - 1;
  31766. let start = opts.start = parseInt(x, 10) || 0;
  31767. if (end >= stats.size) {
  31768. end = stats.size - 1;
  31769. }
  31770. if (start >= stats.size) {
  31771. res.setHeader('Content-Range', `bytes */${stats.size}`);
  31772. res.statusCode = 416;
  31773. return res.end();
  31774. }
  31775. headers['Content-Range'] = `bytes ${start}-${end}/${stats.size}`;
  31776. headers['Content-Length'] = (end - start + 1);
  31777. headers['Accept-Ranges'] = 'bytes';
  31778. }
  31779. res.writeHead(code, headers);
  31780. fs$8.createReadStream(file, opts).pipe(res);
  31781. }
  31782. const ENCODING = {
  31783. '.br': 'br',
  31784. '.gz': 'gzip',
  31785. };
  31786. function toHeaders(name, stats, isEtag) {
  31787. let enc = ENCODING[name.slice(-3)];
  31788. let ctype = lookup(name.slice(0, enc && -3)) || '';
  31789. if (ctype === 'text/html') ctype += ';charset=utf-8';
  31790. let headers = {
  31791. 'Content-Length': stats.size,
  31792. 'Content-Type': ctype,
  31793. 'Last-Modified': stats.mtime.toUTCString(),
  31794. };
  31795. if (enc) headers['Content-Encoding'] = enc;
  31796. if (isEtag) headers['ETag'] = `W/"${stats.size}-${stats.mtime.getTime()}"`;
  31797. return headers;
  31798. }
  31799. function sirv (dir, opts={}) {
  31800. dir = resolve$4(dir || '.');
  31801. let isNotFound = opts.onNoMatch || is404;
  31802. let setHeaders = opts.setHeaders || noop;
  31803. let extensions = opts.extensions || ['html', 'htm'];
  31804. let gzips = opts.gzip && extensions.map(x => `${x}.gz`).concat('gz');
  31805. let brots = opts.brotli && extensions.map(x => `${x}.br`).concat('br');
  31806. const FILES = {};
  31807. let fallback = '/';
  31808. let isEtag = !!opts.etag;
  31809. let isSPA = !!opts.single;
  31810. if (typeof opts.single === 'string') {
  31811. let idx = opts.single.lastIndexOf('.');
  31812. fallback += !!~idx ? opts.single.substring(0, idx) : opts.single;
  31813. }
  31814. let ignores = [];
  31815. if (opts.ignores !== false) {
  31816. ignores.push(/[/]([A-Za-z\s\d~$._-]+\.\w+){1,}$/); // any extn
  31817. if (opts.dotfiles) ignores.push(/\/\.\w/);
  31818. else ignores.push(/\/\.well-known/);
  31819. [].concat(opts.ignores || []).forEach(x => {
  31820. ignores.push(new RegExp(x, 'i'));
  31821. });
  31822. }
  31823. let cc = opts.maxAge != null && `public,max-age=${opts.maxAge}`;
  31824. if (cc && opts.immutable) cc += ',immutable';
  31825. else if (cc && opts.maxAge === 0) cc += ',must-revalidate';
  31826. if (!opts.dev) {
  31827. totalist(dir, (name, abs, stats) => {
  31828. if (/\.well-known[\\+\/]/.test(name)) ; // keep
  31829. else if (!opts.dotfiles && /(^\.|[\\+|\/+]\.)/.test(name)) return;
  31830. let headers = toHeaders(name, stats, isEtag);
  31831. if (cc) headers['Cache-Control'] = cc;
  31832. FILES['/' + name.normalize().replace(/\\+/g, '/')] = { abs, stats, headers };
  31833. });
  31834. }
  31835. let lookup = opts.dev ? viaLocal.bind(0, dir, isEtag) : viaCache.bind(0, FILES);
  31836. return function (req, res, next) {
  31837. let extns = [''];
  31838. let pathname = parse(req).pathname;
  31839. let val = req.headers['accept-encoding'] || '';
  31840. if (gzips && val.includes('gzip')) extns.unshift(...gzips);
  31841. if (brots && /(br|brotli)/i.test(val)) extns.unshift(...brots);
  31842. extns.push(...extensions); // [...br, ...gz, orig, ...exts]
  31843. if (pathname.indexOf('%') !== -1) {
  31844. try { pathname = decodeURI(pathname); }
  31845. catch (err) { /* malform uri */ }
  31846. }
  31847. let data = lookup(pathname, extns, opts.shouldServe) || isSPA && !isMatch(pathname, ignores) && lookup(fallback, extns, opts.shouldServe);
  31848. if (!data) return next ? next() : isNotFound(req, res);
  31849. if (isEtag && req.headers['if-none-match'] === data.headers['ETag']) {
  31850. res.writeHead(304);
  31851. return res.end();
  31852. }
  31853. if (gzips || brots) {
  31854. res.setHeader('Vary', 'Accept-Encoding');
  31855. }
  31856. setHeaders(res, pathname, data.stats);
  31857. send(req, res, data.abs, data.stats, data.headers);
  31858. };
  31859. }
  31860. const knownJavascriptExtensionRE = /\.(?:[tj]sx?|[cm][tj]s)$/;
  31861. const ERR_DENIED_FILE = "ERR_DENIED_FILE";
  31862. const sirvOptions = ({
  31863. config,
  31864. getHeaders,
  31865. disableFsServeCheck
  31866. }) => {
  31867. return {
  31868. dev: true,
  31869. etag: true,
  31870. extensions: [],
  31871. setHeaders(res, pathname) {
  31872. if (knownJavascriptExtensionRE.test(pathname)) {
  31873. res.setHeader("Content-Type", "text/javascript");
  31874. }
  31875. const headers = getHeaders();
  31876. if (headers) {
  31877. for (const name in headers) {
  31878. res.setHeader(name, headers[name]);
  31879. }
  31880. }
  31881. },
  31882. shouldServe: disableFsServeCheck ? void 0 : (filePath) => {
  31883. const servingAccessResult = checkLoadingAccess(config, filePath);
  31884. if (servingAccessResult === "denied") {
  31885. const error = new Error("denied access");
  31886. error.code = ERR_DENIED_FILE;
  31887. error.path = filePath;
  31888. throw error;
  31889. }
  31890. if (servingAccessResult === "fallback") {
  31891. return false;
  31892. }
  31893. return true;
  31894. }
  31895. };
  31896. };
  31897. function servePublicMiddleware(server, publicFiles) {
  31898. const dir = server.config.publicDir;
  31899. const serve = sirv(
  31900. dir,
  31901. sirvOptions({
  31902. config: server.config,
  31903. getHeaders: () => server.config.server.headers,
  31904. disableFsServeCheck: true
  31905. })
  31906. );
  31907. const toFilePath = (url) => {
  31908. let filePath = cleanUrl(url);
  31909. if (filePath.indexOf("%") !== -1) {
  31910. try {
  31911. filePath = decodeURI(filePath);
  31912. } catch {
  31913. }
  31914. }
  31915. return normalizePath$3(filePath);
  31916. };
  31917. return function viteServePublicMiddleware(req, res, next) {
  31918. if (publicFiles && !publicFiles.has(toFilePath(req.url)) || isImportRequest(req.url) || isInternalRequest(req.url) || // for `/public-file.js?url` to be transformed
  31919. urlRE$1.test(req.url)) {
  31920. return next();
  31921. }
  31922. serve(req, res, next);
  31923. };
  31924. }
  31925. function serveStaticMiddleware(server) {
  31926. const dir = server.config.root;
  31927. const serve = sirv(
  31928. dir,
  31929. sirvOptions({
  31930. config: server.config,
  31931. getHeaders: () => server.config.server.headers
  31932. })
  31933. );
  31934. return function viteServeStaticMiddleware(req, res, next) {
  31935. const cleanedUrl = cleanUrl(req.url);
  31936. if (cleanedUrl.endsWith("/") || path$b.extname(cleanedUrl) === ".html" || isInternalRequest(req.url) || // skip url starting with // as these will be interpreted as
  31937. // scheme relative URLs by new URL() and will not be a valid file path
  31938. req.url?.startsWith("//")) {
  31939. return next();
  31940. }
  31941. const url = new URL(req.url, "http://example.com");
  31942. const pathname = decodeURI(url.pathname);
  31943. let redirectedPathname;
  31944. for (const { find, replacement } of server.config.resolve.alias) {
  31945. const matches = typeof find === "string" ? pathname.startsWith(find) : find.test(pathname);
  31946. if (matches) {
  31947. redirectedPathname = pathname.replace(find, replacement);
  31948. break;
  31949. }
  31950. }
  31951. if (redirectedPathname) {
  31952. if (redirectedPathname.startsWith(withTrailingSlash(dir))) {
  31953. redirectedPathname = redirectedPathname.slice(dir.length);
  31954. }
  31955. }
  31956. const resolvedPathname = redirectedPathname || pathname;
  31957. let fileUrl = path$b.resolve(dir, removeLeadingSlash(resolvedPathname));
  31958. if (resolvedPathname.endsWith("/") && fileUrl[fileUrl.length - 1] !== "/") {
  31959. fileUrl = withTrailingSlash(fileUrl);
  31960. }
  31961. if (redirectedPathname) {
  31962. url.pathname = encodeURI(redirectedPathname);
  31963. req.url = url.href.slice(url.origin.length);
  31964. }
  31965. try {
  31966. serve(req, res, next);
  31967. } catch (e) {
  31968. if (e && "code" in e && e.code === ERR_DENIED_FILE) {
  31969. respondWithAccessDenied(e.path, server, res);
  31970. return;
  31971. }
  31972. throw e;
  31973. }
  31974. };
  31975. }
  31976. function serveRawFsMiddleware(server) {
  31977. const serveFromRoot = sirv(
  31978. "/",
  31979. sirvOptions({
  31980. config: server.config,
  31981. getHeaders: () => server.config.server.headers
  31982. })
  31983. );
  31984. return function viteServeRawFsMiddleware(req, res, next) {
  31985. if (req.url.startsWith(FS_PREFIX)) {
  31986. const url = new URL(req.url, "http://example.com");
  31987. const pathname = decodeURI(url.pathname);
  31988. let newPathname = pathname.slice(FS_PREFIX.length);
  31989. if (isWindows$3) newPathname = newPathname.replace(/^[A-Z]:/i, "");
  31990. url.pathname = encodeURI(newPathname);
  31991. req.url = url.href.slice(url.origin.length);
  31992. try {
  31993. serveFromRoot(req, res, next);
  31994. } catch (e) {
  31995. if (e && "code" in e && e.code === ERR_DENIED_FILE) {
  31996. respondWithAccessDenied(e.path, server, res);
  31997. return;
  31998. }
  31999. throw e;
  32000. }
  32001. } else {
  32002. next();
  32003. }
  32004. };
  32005. }
  32006. function isFileServingAllowed(configOrUrl, urlOrServer) {
  32007. const config = typeof urlOrServer === "string" ? configOrUrl : urlOrServer.config;
  32008. const url = typeof urlOrServer === "string" ? urlOrServer : configOrUrl;
  32009. if (!config.server.fs.strict) return true;
  32010. const filePath = fsPathFromUrl(url);
  32011. return isFileLoadingAllowed(config, filePath);
  32012. }
  32013. function isUriInFilePath(uri, filePath) {
  32014. return isSameFileUri(uri, filePath) || isParentDirectory(uri, filePath);
  32015. }
  32016. function isFileLoadingAllowed(config, filePath) {
  32017. const { fs } = config.server;
  32018. if (!fs.strict) return true;
  32019. if (config.fsDenyGlob(filePath)) return false;
  32020. if (config.safeModulePaths.has(filePath)) return true;
  32021. if (fs.allow.some((uri) => isUriInFilePath(uri, filePath))) return true;
  32022. return false;
  32023. }
  32024. function checkLoadingAccess(config, path2) {
  32025. if (isFileLoadingAllowed(config, slash$1(path2))) {
  32026. return "allowed";
  32027. }
  32028. if (isFileReadable(path2)) {
  32029. return "denied";
  32030. }
  32031. return "fallback";
  32032. }
  32033. function checkServingAccess(url, server) {
  32034. if (isFileServingAllowed(url, server)) {
  32035. return "allowed";
  32036. }
  32037. if (isFileReadable(cleanUrl(url))) {
  32038. return "denied";
  32039. }
  32040. return "fallback";
  32041. }
  32042. function respondWithAccessDenied(url, server, res) {
  32043. const urlMessage = `The request url "${url}" is outside of Vite serving allow list.`;
  32044. const hintMessage = `
  32045. ${server.config.server.fs.allow.map((i) => `- ${i}`).join("\n")}
  32046. Refer to docs https://vite.dev/config/server-options.html#server-fs-allow for configurations and more details.`;
  32047. server.config.logger.error(urlMessage);
  32048. server.config.logger.warnOnce(hintMessage + "\n");
  32049. res.statusCode = 403;
  32050. res.write(renderRestrictedErrorHTML(urlMessage + "\n" + hintMessage));
  32051. res.end();
  32052. }
  32053. function renderRestrictedErrorHTML(msg) {
  32054. const html = String.raw;
  32055. return html`
  32056. <body>
  32057. <h1>403 Restricted</h1>
  32058. <p>${escapeHtml$2(msg).replace(/\n/g, "<br/>")}</p>
  32059. <style>
  32060. body {
  32061. padding: 1em 2em;
  32062. }
  32063. </style>
  32064. </body>
  32065. `;
  32066. }
  32067. const ERR_LOAD_URL = "ERR_LOAD_URL";
  32068. const ERR_LOAD_PUBLIC_URL = "ERR_LOAD_PUBLIC_URL";
  32069. const ERR_DENIED_ID = "ERR_DENIED_ID";
  32070. const debugLoad = createDebugger("vite:load");
  32071. const debugTransform = createDebugger("vite:transform");
  32072. const debugCache$1 = createDebugger("vite:cache");
  32073. function transformRequest(environment, url, options = {}) {
  32074. if (!options.ssr) {
  32075. options = { ...options, ssr: environment.config.consumer === "server" };
  32076. }
  32077. if (environment._closing && environment.config.dev.recoverable)
  32078. throwClosedServerError();
  32079. const cacheKey = `${options.html ? "html:" : ""}${url}`;
  32080. const timestamp = Date.now();
  32081. const pending = environment._pendingRequests.get(cacheKey);
  32082. if (pending) {
  32083. return environment.moduleGraph.getModuleByUrl(removeTimestampQuery(url)).then((module) => {
  32084. if (!module || pending.timestamp > module.lastInvalidationTimestamp) {
  32085. return pending.request;
  32086. } else {
  32087. pending.abort();
  32088. return transformRequest(environment, url, options);
  32089. }
  32090. });
  32091. }
  32092. const request = doTransform(environment, url, options, timestamp);
  32093. let cleared = false;
  32094. const clearCache = () => {
  32095. if (!cleared) {
  32096. environment._pendingRequests.delete(cacheKey);
  32097. cleared = true;
  32098. }
  32099. };
  32100. environment._pendingRequests.set(cacheKey, {
  32101. request,
  32102. timestamp,
  32103. abort: clearCache
  32104. });
  32105. return request.finally(clearCache);
  32106. }
  32107. async function doTransform(environment, url, options, timestamp) {
  32108. url = removeTimestampQuery(url);
  32109. const { pluginContainer } = environment;
  32110. let module = await environment.moduleGraph.getModuleByUrl(url);
  32111. if (module) {
  32112. const cached = await getCachedTransformResult(
  32113. environment,
  32114. url,
  32115. module,
  32116. timestamp
  32117. );
  32118. if (cached) return cached;
  32119. }
  32120. const resolved = module ? void 0 : await pluginContainer.resolveId(url, void 0) ?? void 0;
  32121. const id = module?.id ?? resolved?.id ?? url;
  32122. module ??= environment.moduleGraph.getModuleById(id);
  32123. if (module) {
  32124. await environment.moduleGraph._ensureEntryFromUrl(url, void 0, resolved);
  32125. const cached = await getCachedTransformResult(
  32126. environment,
  32127. url,
  32128. module,
  32129. timestamp
  32130. );
  32131. if (cached) return cached;
  32132. }
  32133. const result = loadAndTransform(
  32134. environment,
  32135. id,
  32136. url,
  32137. options,
  32138. timestamp,
  32139. module,
  32140. resolved
  32141. );
  32142. const { depsOptimizer } = environment;
  32143. if (!depsOptimizer?.isOptimizedDepFile(id)) {
  32144. environment._registerRequestProcessing(id, () => result);
  32145. }
  32146. return result;
  32147. }
  32148. async function getCachedTransformResult(environment, url, module, timestamp) {
  32149. const prettyUrl = debugCache$1 ? prettifyUrl(url, environment.config.root) : "";
  32150. const softInvalidatedTransformResult = await handleModuleSoftInvalidation(
  32151. environment,
  32152. module,
  32153. timestamp
  32154. );
  32155. if (softInvalidatedTransformResult) {
  32156. debugCache$1?.(`[memory-hmr] ${prettyUrl}`);
  32157. return softInvalidatedTransformResult;
  32158. }
  32159. const cached = module.transformResult;
  32160. if (cached) {
  32161. debugCache$1?.(`[memory] ${prettyUrl}`);
  32162. return cached;
  32163. }
  32164. }
  32165. async function loadAndTransform(environment, id, url, options, timestamp, mod, resolved) {
  32166. const { config, pluginContainer, logger } = environment;
  32167. const prettyUrl = debugLoad || debugTransform ? prettifyUrl(url, config.root) : "";
  32168. const moduleGraph = environment.moduleGraph;
  32169. if (options.allowId && !options.allowId(id)) {
  32170. const err = new Error(`Denied ID ${id}`);
  32171. err.code = ERR_DENIED_ID;
  32172. throw err;
  32173. }
  32174. let code = null;
  32175. let map = null;
  32176. const loadStart = debugLoad ? performance$1.now() : 0;
  32177. const loadResult = await pluginContainer.load(id);
  32178. if (loadResult == null) {
  32179. const file = cleanUrl(id);
  32180. if (options.html && !id.endsWith(".html")) {
  32181. return null;
  32182. }
  32183. if (environment.config.consumer === "server" || isFileLoadingAllowed(environment.getTopLevelConfig(), file)) {
  32184. try {
  32185. code = await fsp.readFile(file, "utf-8");
  32186. debugLoad?.(`${timeFrom(loadStart)} [fs] ${prettyUrl}`);
  32187. } catch (e) {
  32188. if (e.code !== "ENOENT") {
  32189. if (e.code === "EISDIR") {
  32190. e.message = `${e.message} ${file}`;
  32191. }
  32192. throw e;
  32193. }
  32194. }
  32195. if (code != null && environment.pluginContainer.watcher) {
  32196. ensureWatchedFile(
  32197. environment.pluginContainer.watcher,
  32198. file,
  32199. config.root
  32200. );
  32201. }
  32202. }
  32203. if (code) {
  32204. try {
  32205. const extracted = await extractSourcemapFromFile(code, file);
  32206. if (extracted) {
  32207. code = extracted.code;
  32208. map = extracted.map;
  32209. }
  32210. } catch (e) {
  32211. logger.warn(`Failed to load source map for ${file}.
  32212. ${e}`, {
  32213. timestamp: true
  32214. });
  32215. }
  32216. }
  32217. } else {
  32218. debugLoad?.(`${timeFrom(loadStart)} [plugin] ${prettyUrl}`);
  32219. if (isObject$1(loadResult)) {
  32220. code = loadResult.code;
  32221. map = loadResult.map;
  32222. } else {
  32223. code = loadResult;
  32224. }
  32225. }
  32226. if (code == null) {
  32227. const isPublicFile = checkPublicFile(url, environment.getTopLevelConfig());
  32228. let publicDirName = path$b.relative(config.root, config.publicDir);
  32229. if (publicDirName[0] !== ".") publicDirName = "/" + publicDirName;
  32230. 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?`;
  32231. const importerMod = moduleGraph.idToModuleMap.get(id)?.importers.values().next().value;
  32232. const importer = importerMod?.file || importerMod?.url;
  32233. const err = new Error(
  32234. `Failed to load url ${url} (resolved id: ${id})${importer ? ` in ${importer}` : ""}. ${msg}`
  32235. );
  32236. err.code = isPublicFile ? ERR_LOAD_PUBLIC_URL : ERR_LOAD_URL;
  32237. throw err;
  32238. }
  32239. if (environment._closing && environment.config.dev.recoverable)
  32240. throwClosedServerError();
  32241. mod ??= await moduleGraph._ensureEntryFromUrl(url, void 0, resolved);
  32242. const transformStart = debugTransform ? performance$1.now() : 0;
  32243. const transformResult = await pluginContainer.transform(code, id, {
  32244. inMap: map
  32245. });
  32246. const originalCode = code;
  32247. if (transformResult.code === originalCode) {
  32248. debugTransform?.(
  32249. timeFrom(transformStart) + colors$1.dim(` [skipped] ${prettyUrl}`)
  32250. );
  32251. } else {
  32252. debugTransform?.(`${timeFrom(transformStart)} ${prettyUrl}`);
  32253. code = transformResult.code;
  32254. map = transformResult.map;
  32255. }
  32256. let normalizedMap;
  32257. if (typeof map === "string") {
  32258. normalizedMap = JSON.parse(map);
  32259. } else if (map) {
  32260. normalizedMap = map;
  32261. } else {
  32262. normalizedMap = null;
  32263. }
  32264. if (normalizedMap && "version" in normalizedMap && mod.file) {
  32265. if (normalizedMap.mappings) {
  32266. await injectSourcesContent(normalizedMap, mod.file, logger);
  32267. }
  32268. const sourcemapPath = `${mod.file}.map`;
  32269. applySourcemapIgnoreList(
  32270. normalizedMap,
  32271. sourcemapPath,
  32272. config.server.sourcemapIgnoreList,
  32273. logger
  32274. );
  32275. if (path$b.isAbsolute(mod.file)) {
  32276. let modDirname;
  32277. for (let sourcesIndex = 0; sourcesIndex < normalizedMap.sources.length; ++sourcesIndex) {
  32278. const sourcePath = normalizedMap.sources[sourcesIndex];
  32279. if (sourcePath) {
  32280. if (path$b.isAbsolute(sourcePath)) {
  32281. modDirname ??= path$b.dirname(mod.file);
  32282. normalizedMap.sources[sourcesIndex] = path$b.relative(
  32283. modDirname,
  32284. sourcePath
  32285. );
  32286. }
  32287. }
  32288. }
  32289. }
  32290. }
  32291. if (environment._closing && environment.config.dev.recoverable)
  32292. throwClosedServerError();
  32293. const topLevelConfig = environment.getTopLevelConfig();
  32294. const result = environment.config.dev.moduleRunnerTransform ? await ssrTransform(code, normalizedMap, url, originalCode, {
  32295. json: {
  32296. stringify: topLevelConfig.json.stringify === true && topLevelConfig.json.namedExports !== true
  32297. }
  32298. }) : {
  32299. code,
  32300. map: normalizedMap,
  32301. etag: getEtag(code, { weak: true })
  32302. };
  32303. if (timestamp > mod.lastInvalidationTimestamp)
  32304. moduleGraph.updateModuleTransformResult(mod, result);
  32305. return result;
  32306. }
  32307. async function handleModuleSoftInvalidation(environment, mod, timestamp) {
  32308. const transformResult = mod.invalidationState;
  32309. mod.invalidationState = void 0;
  32310. if (!transformResult || transformResult === "HARD_INVALIDATED") return;
  32311. if (mod.transformResult) {
  32312. throw new Error(
  32313. `Internal server error: Soft-invalidated module "${mod.url}" should not have existing transform result`
  32314. );
  32315. }
  32316. let result;
  32317. if (transformResult.ssr) {
  32318. result = transformResult;
  32319. } else {
  32320. await init;
  32321. const source = transformResult.code;
  32322. const s = new MagicString(source);
  32323. const [imports] = parse$d(source, mod.id || void 0);
  32324. for (const imp of imports) {
  32325. let rawUrl = source.slice(imp.s, imp.e);
  32326. if (rawUrl === "import.meta") continue;
  32327. const hasQuotes = rawUrl[0] === '"' || rawUrl[0] === "'";
  32328. if (hasQuotes) {
  32329. rawUrl = rawUrl.slice(1, -1);
  32330. }
  32331. const urlWithoutTimestamp = removeTimestampQuery(rawUrl);
  32332. const hmrUrl = unwrapId$1(
  32333. stripBase(
  32334. removeImportQuery(urlWithoutTimestamp),
  32335. environment.config.base
  32336. )
  32337. );
  32338. for (const importedMod of mod.importedModules) {
  32339. if (importedMod.url !== hmrUrl) continue;
  32340. if (importedMod.lastHMRTimestamp > 0) {
  32341. const replacedUrl = injectQuery(
  32342. urlWithoutTimestamp,
  32343. `t=${importedMod.lastHMRTimestamp}`
  32344. );
  32345. const start = hasQuotes ? imp.s + 1 : imp.s;
  32346. const end = hasQuotes ? imp.e - 1 : imp.e;
  32347. s.overwrite(start, end, replacedUrl);
  32348. }
  32349. if (imp.d === -1 && environment.config.dev.preTransformRequests) {
  32350. environment.warmupRequest(hmrUrl);
  32351. }
  32352. break;
  32353. }
  32354. }
  32355. const code = s.toString();
  32356. result = {
  32357. ...transformResult,
  32358. code,
  32359. etag: getEtag(code, { weak: true })
  32360. };
  32361. }
  32362. if (timestamp > mod.lastInvalidationTimestamp)
  32363. environment.moduleGraph.updateModuleTransformResult(mod, result);
  32364. return result;
  32365. }
  32366. const ALLOWED_META_NAME = [
  32367. "msapplication-tileimage",
  32368. "msapplication-square70x70logo",
  32369. "msapplication-square150x150logo",
  32370. "msapplication-wide310x150logo",
  32371. "msapplication-square310x310logo",
  32372. "msapplication-config",
  32373. "twitter:image"
  32374. ];
  32375. const ALLOWED_META_PROPERTY = [
  32376. "og:image",
  32377. "og:image:url",
  32378. "og:image:secure_url",
  32379. "og:audio",
  32380. "og:audio:secure_url",
  32381. "og:video",
  32382. "og:video:secure_url"
  32383. ];
  32384. const DEFAULT_HTML_ASSET_SOURCES = {
  32385. audio: {
  32386. srcAttributes: ["src"]
  32387. },
  32388. embed: {
  32389. srcAttributes: ["src"]
  32390. },
  32391. img: {
  32392. srcAttributes: ["src"],
  32393. srcsetAttributes: ["srcset"]
  32394. },
  32395. image: {
  32396. srcAttributes: ["href", "xlink:href"]
  32397. },
  32398. input: {
  32399. srcAttributes: ["src"]
  32400. },
  32401. link: {
  32402. srcAttributes: ["href"],
  32403. srcsetAttributes: ["imagesrcset"]
  32404. },
  32405. object: {
  32406. srcAttributes: ["data"]
  32407. },
  32408. source: {
  32409. srcAttributes: ["src"],
  32410. srcsetAttributes: ["srcset"]
  32411. },
  32412. track: {
  32413. srcAttributes: ["src"]
  32414. },
  32415. use: {
  32416. srcAttributes: ["href", "xlink:href"]
  32417. },
  32418. video: {
  32419. srcAttributes: ["src", "poster"]
  32420. },
  32421. meta: {
  32422. srcAttributes: ["content"],
  32423. filter({ attributes }) {
  32424. if (attributes.name && ALLOWED_META_NAME.includes(attributes.name.trim().toLowerCase())) {
  32425. return true;
  32426. }
  32427. if (attributes.property && ALLOWED_META_PROPERTY.includes(attributes.property.trim().toLowerCase())) {
  32428. return true;
  32429. }
  32430. return false;
  32431. }
  32432. }
  32433. };
  32434. function getNodeAssetAttributes(node) {
  32435. const matched = DEFAULT_HTML_ASSET_SOURCES[node.nodeName];
  32436. if (!matched) return [];
  32437. const attributes = {};
  32438. for (const attr of node.attrs) {
  32439. attributes[getAttrKey(attr)] = attr.value;
  32440. }
  32441. if ("vite-ignore" in attributes) {
  32442. return [
  32443. {
  32444. type: "remove",
  32445. key: "vite-ignore",
  32446. value: "",
  32447. attributes,
  32448. location: node.sourceCodeLocation.attrs["vite-ignore"]
  32449. }
  32450. ];
  32451. }
  32452. const actions = [];
  32453. function handleAttributeKey(key, type) {
  32454. const value = attributes[key];
  32455. if (!value) return;
  32456. if (matched.filter && !matched.filter({ key, value, attributes })) return;
  32457. const location = node.sourceCodeLocation.attrs[key];
  32458. actions.push({ type, key, value, attributes, location });
  32459. }
  32460. matched.srcAttributes?.forEach((key) => handleAttributeKey(key, "src"));
  32461. matched.srcsetAttributes?.forEach((key) => handleAttributeKey(key, "srcset"));
  32462. return actions;
  32463. }
  32464. function getAttrKey(attr) {
  32465. return attr.prefix === void 0 ? attr.name : `${attr.prefix}:${attr.name}`;
  32466. }
  32467. const modulePreloadPolyfillId = "vite/modulepreload-polyfill";
  32468. const resolvedModulePreloadPolyfillId = "\0" + modulePreloadPolyfillId + ".js";
  32469. function modulePreloadPolyfillPlugin(config) {
  32470. let polyfillString;
  32471. return {
  32472. name: "vite:modulepreload-polyfill",
  32473. resolveId: {
  32474. handler(id) {
  32475. if (id === modulePreloadPolyfillId) {
  32476. return resolvedModulePreloadPolyfillId;
  32477. }
  32478. }
  32479. },
  32480. load: {
  32481. handler(id) {
  32482. if (id === resolvedModulePreloadPolyfillId) {
  32483. if (config.command !== "build" || this.environment.config.consumer !== "client") {
  32484. return "";
  32485. }
  32486. if (!polyfillString) {
  32487. polyfillString = `${isModernFlag}&&(${polyfill.toString()}());`;
  32488. }
  32489. return { code: polyfillString, moduleSideEffects: true };
  32490. }
  32491. }
  32492. }
  32493. };
  32494. }
  32495. function polyfill() {
  32496. const relList = document.createElement("link").relList;
  32497. if (relList && relList.supports && relList.supports("modulepreload")) {
  32498. return;
  32499. }
  32500. for (const link of document.querySelectorAll('link[rel="modulepreload"]')) {
  32501. processPreload(link);
  32502. }
  32503. new MutationObserver((mutations) => {
  32504. for (const mutation of mutations) {
  32505. if (mutation.type !== "childList") {
  32506. continue;
  32507. }
  32508. for (const node of mutation.addedNodes) {
  32509. if (node.tagName === "LINK" && node.rel === "modulepreload")
  32510. processPreload(node);
  32511. }
  32512. }
  32513. }).observe(document, { childList: true, subtree: true });
  32514. function getFetchOpts(link) {
  32515. const fetchOpts = {};
  32516. if (link.integrity) fetchOpts.integrity = link.integrity;
  32517. if (link.referrerPolicy) fetchOpts.referrerPolicy = link.referrerPolicy;
  32518. if (link.crossOrigin === "use-credentials")
  32519. fetchOpts.credentials = "include";
  32520. else if (link.crossOrigin === "anonymous") fetchOpts.credentials = "omit";
  32521. else fetchOpts.credentials = "same-origin";
  32522. return fetchOpts;
  32523. }
  32524. function processPreload(link) {
  32525. if (link.ep)
  32526. return;
  32527. link.ep = true;
  32528. const fetchOpts = getFetchOpts(link);
  32529. fetch(link.href, fetchOpts);
  32530. }
  32531. }
  32532. const htmlProxyRE$1 = /[?&]html-proxy=?(?:&inline-css)?(?:&style-attr)?&index=(\d+)\.(?:js|css)$/;
  32533. const isHtmlProxyRE = /[?&]html-proxy\b/;
  32534. const inlineCSSRE$1 = /__VITE_INLINE_CSS__([a-z\d]{8}_\d+)__/g;
  32535. const inlineImportRE = /(?<!(?<!\.\.)\.)\bimport\s*\(("(?:[^"]|(?<=\\)")*"|'(?:[^']|(?<=\\)')*')\)/dg;
  32536. const htmlLangRE = /\.(?:html|htm)$/;
  32537. const spaceRe = /[\t\n\f\r ]/;
  32538. const importMapRE = /[ \t]*<script[^>]*type\s*=\s*(?:"importmap"|'importmap'|importmap)[^>]*>.*?<\/script>/is;
  32539. const moduleScriptRE = /[ \t]*<script[^>]*type\s*=\s*(?:"module"|'module'|module)[^>]*>/i;
  32540. const modulePreloadLinkRE = /[ \t]*<link[^>]*rel\s*=\s*(?:"modulepreload"|'modulepreload'|modulepreload)[\s\S]*?\/>/i;
  32541. const importMapAppendRE = new RegExp(
  32542. [moduleScriptRE, modulePreloadLinkRE].map((r) => r.source).join("|"),
  32543. "i"
  32544. );
  32545. const isHTMLProxy = (id) => isHtmlProxyRE.test(id);
  32546. const isHTMLRequest = (request) => htmlLangRE.test(request);
  32547. const htmlProxyMap = /* @__PURE__ */ new WeakMap();
  32548. const htmlProxyResult = /* @__PURE__ */ new Map();
  32549. function htmlInlineProxyPlugin(config) {
  32550. htmlProxyMap.set(config, /* @__PURE__ */ new Map());
  32551. return {
  32552. name: "vite:html-inline-proxy",
  32553. resolveId: {
  32554. handler(id) {
  32555. if (isHTMLProxy(id)) {
  32556. return id;
  32557. }
  32558. }
  32559. },
  32560. load: {
  32561. handler(id) {
  32562. const proxyMatch = htmlProxyRE$1.exec(id);
  32563. if (proxyMatch) {
  32564. const index = Number(proxyMatch[1]);
  32565. const file = cleanUrl(id);
  32566. const url = file.replace(normalizePath$3(config.root), "");
  32567. const result = htmlProxyMap.get(config).get(url)?.[index];
  32568. if (result) {
  32569. return { ...result, moduleSideEffects: true };
  32570. } else {
  32571. throw new Error(`No matching HTML proxy module found from ${id}`);
  32572. }
  32573. }
  32574. }
  32575. }
  32576. };
  32577. }
  32578. function addToHTMLProxyCache(config, filePath, index, result) {
  32579. if (!htmlProxyMap.get(config)) {
  32580. htmlProxyMap.set(config, /* @__PURE__ */ new Map());
  32581. }
  32582. if (!htmlProxyMap.get(config).get(filePath)) {
  32583. htmlProxyMap.get(config).set(filePath, []);
  32584. }
  32585. htmlProxyMap.get(config).get(filePath)[index] = result;
  32586. }
  32587. function addToHTMLProxyTransformResult(hash, code) {
  32588. htmlProxyResult.set(hash, code);
  32589. }
  32590. const noInlineLinkRels = /* @__PURE__ */ new Set([
  32591. "icon",
  32592. "apple-touch-icon",
  32593. "apple-touch-startup-image",
  32594. "manifest"
  32595. ]);
  32596. const isAsyncScriptMap = /* @__PURE__ */ new WeakMap();
  32597. function nodeIsElement(node) {
  32598. return node.nodeName[0] !== "#";
  32599. }
  32600. function traverseNodes(node, visitor) {
  32601. if (node.nodeName === "template") {
  32602. node = node.content;
  32603. }
  32604. visitor(node);
  32605. if (nodeIsElement(node) || node.nodeName === "#document" || node.nodeName === "#document-fragment") {
  32606. node.childNodes.forEach((childNode) => traverseNodes(childNode, visitor));
  32607. }
  32608. }
  32609. async function traverseHtml(html, filePath, visitor) {
  32610. const { parse } = await import('./dep-CvfTChi5.js');
  32611. const ast = parse(html, {
  32612. scriptingEnabled: false,
  32613. // parse inside <noscript>
  32614. sourceCodeLocationInfo: true,
  32615. onParseError: (e) => {
  32616. handleParseError(e, html, filePath);
  32617. }
  32618. });
  32619. traverseNodes(ast, visitor);
  32620. }
  32621. function getScriptInfo(node) {
  32622. let src;
  32623. let srcSourceCodeLocation;
  32624. let isModule = false;
  32625. let isAsync = false;
  32626. let isIgnored = false;
  32627. for (const p of node.attrs) {
  32628. if (p.prefix !== void 0) continue;
  32629. if (p.name === "src") {
  32630. if (!src) {
  32631. src = p;
  32632. srcSourceCodeLocation = node.sourceCodeLocation?.attrs["src"];
  32633. }
  32634. } else if (p.name === "type" && p.value === "module") {
  32635. isModule = true;
  32636. } else if (p.name === "async") {
  32637. isAsync = true;
  32638. } else if (p.name === "vite-ignore") {
  32639. isIgnored = true;
  32640. }
  32641. }
  32642. return { src, srcSourceCodeLocation, isModule, isAsync, isIgnored };
  32643. }
  32644. const attrValueStartRE = /=\s*(.)/;
  32645. function overwriteAttrValue(s, sourceCodeLocation, newValue) {
  32646. const srcString = s.slice(
  32647. sourceCodeLocation.startOffset,
  32648. sourceCodeLocation.endOffset
  32649. );
  32650. const valueStart = attrValueStartRE.exec(srcString);
  32651. if (!valueStart) {
  32652. throw new Error(
  32653. `[vite:html] internal error, failed to overwrite attribute value`
  32654. );
  32655. }
  32656. const wrapOffset = valueStart[1] === '"' || valueStart[1] === "'" ? 1 : 0;
  32657. const valueOffset = valueStart.index + valueStart[0].length - 1;
  32658. s.update(
  32659. sourceCodeLocation.startOffset + valueOffset + wrapOffset,
  32660. sourceCodeLocation.endOffset - wrapOffset,
  32661. newValue
  32662. );
  32663. return s;
  32664. }
  32665. function removeViteIgnoreAttr(s, sourceCodeLocation) {
  32666. const loc = sourceCodeLocation.attrs?.["vite-ignore"];
  32667. if (loc) {
  32668. s.remove(loc.startOffset, loc.endOffset);
  32669. }
  32670. return s;
  32671. }
  32672. function formatParseError(parserError, id, html) {
  32673. const formattedError = {
  32674. code: parserError.code,
  32675. message: `parse5 error code ${parserError.code}`,
  32676. frame: generateCodeFrame(
  32677. html,
  32678. parserError.startOffset,
  32679. parserError.endOffset
  32680. ),
  32681. loc: {
  32682. file: id,
  32683. line: parserError.startLine,
  32684. column: parserError.startCol
  32685. }
  32686. };
  32687. return formattedError;
  32688. }
  32689. function handleParseError(parserError, html, filePath) {
  32690. switch (parserError.code) {
  32691. case "missing-doctype":
  32692. return;
  32693. case "abandoned-head-element-child":
  32694. return;
  32695. case "duplicate-attribute":
  32696. return;
  32697. case "non-void-html-element-start-tag-with-trailing-solidus":
  32698. return;
  32699. case "unexpected-question-mark-instead-of-tag-name":
  32700. return;
  32701. }
  32702. const parseError = formatParseError(parserError, filePath, html);
  32703. throw new Error(
  32704. `Unable to parse HTML; ${parseError.message}
  32705. at ${parseError.loc.file}:${parseError.loc.line}:${parseError.loc.column}
  32706. ${parseError.frame}`
  32707. );
  32708. }
  32709. function buildHtmlPlugin(config) {
  32710. const [preHooks, normalHooks, postHooks] = resolveHtmlTransforms(
  32711. config.plugins,
  32712. config.logger
  32713. );
  32714. preHooks.unshift(injectCspNonceMetaTagHook(config));
  32715. preHooks.unshift(preImportMapHook(config));
  32716. preHooks.push(htmlEnvHook(config));
  32717. postHooks.push(injectNonceAttributeTagHook(config));
  32718. postHooks.push(postImportMapHook());
  32719. const processedHtml = perEnvironmentState(() => /* @__PURE__ */ new Map());
  32720. const isExcludedUrl = (url) => url[0] === "#" || isExternalUrl(url) || isDataUrl(url);
  32721. isAsyncScriptMap.set(config, /* @__PURE__ */ new Map());
  32722. return {
  32723. name: "vite:build-html",
  32724. transform: {
  32725. async handler(html, id) {
  32726. if (id.endsWith(".html")) {
  32727. id = normalizePath$3(id);
  32728. const relativeUrlPath = normalizePath$3(path$b.relative(config.root, id));
  32729. const publicPath = `/${relativeUrlPath}`;
  32730. const publicBase = getBaseInHTML(relativeUrlPath, config);
  32731. const publicToRelative = (filename) => publicBase + filename;
  32732. const toOutputPublicFilePath = (url) => toOutputFilePathInHtml(
  32733. url.slice(1),
  32734. "public",
  32735. relativeUrlPath,
  32736. "html",
  32737. config,
  32738. publicToRelative
  32739. );
  32740. const nodeStartWithLeadingWhitespace = (node) => {
  32741. const startOffset = node.sourceCodeLocation.startOffset;
  32742. if (startOffset === 0) return 0;
  32743. const lineStartOffset = startOffset - node.sourceCodeLocation.startCol;
  32744. let isLineEmpty = false;
  32745. try {
  32746. const line = s.slice(Math.max(0, lineStartOffset), startOffset);
  32747. isLineEmpty = !line.trim();
  32748. } catch {
  32749. }
  32750. return isLineEmpty ? lineStartOffset : startOffset;
  32751. };
  32752. html = await applyHtmlTransforms(html, preHooks, {
  32753. path: publicPath,
  32754. filename: id
  32755. });
  32756. let js = "";
  32757. const s = new MagicString(html);
  32758. const scriptUrls = [];
  32759. const styleUrls = [];
  32760. let inlineModuleIndex = -1;
  32761. let everyScriptIsAsync = true;
  32762. let someScriptsAreAsync = false;
  32763. let someScriptsAreDefer = false;
  32764. const assetUrlsPromises = [];
  32765. const namedOutput = Object.keys(
  32766. config.build.rollupOptions.input || {}
  32767. );
  32768. const processAssetUrl = async (url, shouldInline) => {
  32769. if (url !== "" && // Empty attribute
  32770. !namedOutput.includes(url) && // Direct reference to named output
  32771. !namedOutput.includes(removeLeadingSlash(url))) {
  32772. try {
  32773. return await urlToBuiltUrl(this, url, id, shouldInline);
  32774. } catch (e) {
  32775. if (e.code !== "ENOENT") {
  32776. throw e;
  32777. }
  32778. }
  32779. }
  32780. return url;
  32781. };
  32782. const setModuleSideEffectPromises = [];
  32783. await traverseHtml(html, id, (node) => {
  32784. if (!nodeIsElement(node)) {
  32785. return;
  32786. }
  32787. let shouldRemove = false;
  32788. if (node.nodeName === "script") {
  32789. const {
  32790. src,
  32791. srcSourceCodeLocation,
  32792. isModule,
  32793. isAsync,
  32794. isIgnored
  32795. } = getScriptInfo(node);
  32796. if (isIgnored) {
  32797. removeViteIgnoreAttr(s, node.sourceCodeLocation);
  32798. } else {
  32799. const url = src && src.value;
  32800. const isPublicFile = !!(url && checkPublicFile(url, config));
  32801. if (isPublicFile) {
  32802. overwriteAttrValue(
  32803. s,
  32804. srcSourceCodeLocation,
  32805. partialEncodeURIPath(toOutputPublicFilePath(url))
  32806. );
  32807. }
  32808. if (isModule) {
  32809. inlineModuleIndex++;
  32810. if (url && !isExcludedUrl(url) && !isPublicFile) {
  32811. setModuleSideEffectPromises.push(
  32812. this.resolve(url, id).then((resolved) => {
  32813. if (!resolved) {
  32814. return Promise.reject(
  32815. new Error(`Failed to resolve ${url} from ${id}`)
  32816. );
  32817. }
  32818. const moduleInfo = this.getModuleInfo(resolved.id);
  32819. if (moduleInfo) {
  32820. moduleInfo.moduleSideEffects = true;
  32821. } else if (!resolved.external) {
  32822. return this.load(resolved).then((mod) => {
  32823. mod.moduleSideEffects = true;
  32824. });
  32825. }
  32826. })
  32827. );
  32828. js += `
  32829. import ${JSON.stringify(url)}`;
  32830. shouldRemove = true;
  32831. } else if (node.childNodes.length) {
  32832. const scriptNode = node.childNodes.pop();
  32833. const contents = scriptNode.value;
  32834. const filePath = id.replace(normalizePath$3(config.root), "");
  32835. addToHTMLProxyCache(config, filePath, inlineModuleIndex, {
  32836. code: contents
  32837. });
  32838. js += `
  32839. import "${id}?html-proxy&index=${inlineModuleIndex}.js"`;
  32840. shouldRemove = true;
  32841. }
  32842. everyScriptIsAsync &&= isAsync;
  32843. someScriptsAreAsync ||= isAsync;
  32844. someScriptsAreDefer ||= !isAsync;
  32845. } else if (url && !isPublicFile) {
  32846. if (!isExcludedUrl(url)) {
  32847. config.logger.warn(
  32848. `<script src="${url}"> in "${publicPath}" can't be bundled without type="module" attribute`
  32849. );
  32850. }
  32851. } else if (node.childNodes.length) {
  32852. const scriptNode = node.childNodes.pop();
  32853. scriptUrls.push(
  32854. ...extractImportExpressionFromClassicScript(scriptNode)
  32855. );
  32856. }
  32857. }
  32858. }
  32859. const assetAttributes = getNodeAssetAttributes(node);
  32860. for (const attr of assetAttributes) {
  32861. if (attr.type === "remove") {
  32862. s.remove(attr.location.startOffset, attr.location.endOffset);
  32863. continue;
  32864. } else if (attr.type === "srcset") {
  32865. assetUrlsPromises.push(
  32866. (async () => {
  32867. const processedEncodedUrl = await processSrcSet(
  32868. attr.value,
  32869. async ({ url }) => {
  32870. const decodedUrl = decodeURIIfPossible(url);
  32871. if (decodedUrl !== void 0 && !isExcludedUrl(decodedUrl)) {
  32872. const result = await processAssetUrl(url);
  32873. return result !== decodedUrl ? encodeURIPath(result) : url;
  32874. }
  32875. return url;
  32876. }
  32877. );
  32878. if (processedEncodedUrl !== attr.value) {
  32879. overwriteAttrValue(s, attr.location, processedEncodedUrl);
  32880. }
  32881. })()
  32882. );
  32883. } else if (attr.type === "src") {
  32884. const url = decodeURIIfPossible(attr.value);
  32885. if (url === void 0) ; else if (checkPublicFile(url, config)) {
  32886. overwriteAttrValue(
  32887. s,
  32888. attr.location,
  32889. partialEncodeURIPath(toOutputPublicFilePath(url))
  32890. );
  32891. } else if (!isExcludedUrl(url)) {
  32892. if (node.nodeName === "link" && isCSSRequest(url) && // should not be converted if following attributes are present (#6748)
  32893. !("media" in attr.attributes || "disabled" in attr.attributes)) {
  32894. const importExpression = `
  32895. import ${JSON.stringify(url)}`;
  32896. styleUrls.push({
  32897. url,
  32898. start: nodeStartWithLeadingWhitespace(node),
  32899. end: node.sourceCodeLocation.endOffset
  32900. });
  32901. js += importExpression;
  32902. } else {
  32903. const isNoInlineLink = node.nodeName === "link" && attr.attributes.rel && parseRelAttr(attr.attributes.rel).some(
  32904. (v) => noInlineLinkRels.has(v)
  32905. );
  32906. const shouldInline = isNoInlineLink ? false : void 0;
  32907. assetUrlsPromises.push(
  32908. (async () => {
  32909. const processedUrl = await processAssetUrl(
  32910. url,
  32911. shouldInline
  32912. );
  32913. if (processedUrl !== url) {
  32914. overwriteAttrValue(
  32915. s,
  32916. attr.location,
  32917. partialEncodeURIPath(processedUrl)
  32918. );
  32919. }
  32920. })()
  32921. );
  32922. }
  32923. }
  32924. }
  32925. }
  32926. const inlineStyle = findNeedTransformStyleAttribute(node);
  32927. if (inlineStyle) {
  32928. inlineModuleIndex++;
  32929. const code = inlineStyle.attr.value;
  32930. const filePath = id.replace(normalizePath$3(config.root), "");
  32931. addToHTMLProxyCache(config, filePath, inlineModuleIndex, { code });
  32932. js += `
  32933. import "${id}?html-proxy&inline-css&style-attr&index=${inlineModuleIndex}.css"`;
  32934. const hash = getHash(cleanUrl(id));
  32935. overwriteAttrValue(
  32936. s,
  32937. inlineStyle.location,
  32938. `__VITE_INLINE_CSS__${hash}_${inlineModuleIndex}__`
  32939. );
  32940. }
  32941. if (node.nodeName === "style" && node.childNodes.length) {
  32942. const styleNode = node.childNodes.pop();
  32943. const filePath = id.replace(normalizePath$3(config.root), "");
  32944. inlineModuleIndex++;
  32945. addToHTMLProxyCache(config, filePath, inlineModuleIndex, {
  32946. code: styleNode.value
  32947. });
  32948. js += `
  32949. import "${id}?html-proxy&inline-css&index=${inlineModuleIndex}.css"`;
  32950. const hash = getHash(cleanUrl(id));
  32951. s.update(
  32952. styleNode.sourceCodeLocation.startOffset,
  32953. styleNode.sourceCodeLocation.endOffset,
  32954. `__VITE_INLINE_CSS__${hash}_${inlineModuleIndex}__`
  32955. );
  32956. }
  32957. if (shouldRemove) {
  32958. s.remove(
  32959. nodeStartWithLeadingWhitespace(node),
  32960. node.sourceCodeLocation.endOffset
  32961. );
  32962. }
  32963. });
  32964. isAsyncScriptMap.get(config).set(id, everyScriptIsAsync);
  32965. if (someScriptsAreAsync && someScriptsAreDefer) {
  32966. config.logger.warn(
  32967. `
  32968. Mixed 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.`
  32969. );
  32970. }
  32971. await Promise.all(assetUrlsPromises);
  32972. for (const { start, end, url } of scriptUrls) {
  32973. if (checkPublicFile(url, config)) {
  32974. s.update(
  32975. start,
  32976. end,
  32977. partialEncodeURIPath(toOutputPublicFilePath(url))
  32978. );
  32979. } else if (!isExcludedUrl(url)) {
  32980. s.update(
  32981. start,
  32982. end,
  32983. partialEncodeURIPath(await urlToBuiltUrl(this, url, id))
  32984. );
  32985. }
  32986. }
  32987. const resolvedStyleUrls = await Promise.all(
  32988. styleUrls.map(async (styleUrl) => ({
  32989. ...styleUrl,
  32990. resolved: await this.resolve(styleUrl.url, id)
  32991. }))
  32992. );
  32993. for (const { start, end, url, resolved } of resolvedStyleUrls) {
  32994. if (resolved == null) {
  32995. config.logger.warnOnce(
  32996. `
  32997. ${url} doesn't exist at build time, it will remain unchanged to be resolved at runtime`
  32998. );
  32999. const importExpression = `
  33000. import ${JSON.stringify(url)}`;
  33001. js = js.replace(importExpression, "");
  33002. } else {
  33003. s.remove(start, end);
  33004. }
  33005. }
  33006. processedHtml(this).set(id, s.toString());
  33007. const { modulePreload } = this.environment.config.build;
  33008. if (modulePreload !== false && modulePreload.polyfill && (someScriptsAreAsync || someScriptsAreDefer)) {
  33009. js = `import "${modulePreloadPolyfillId}";
  33010. ${js}`;
  33011. }
  33012. await Promise.all(setModuleSideEffectPromises);
  33013. return { code: js, moduleSideEffects: "no-treeshake" };
  33014. }
  33015. }
  33016. },
  33017. async generateBundle(options, bundle) {
  33018. const analyzedImportedCssFiles = /* @__PURE__ */ new Map();
  33019. const inlineEntryChunk = /* @__PURE__ */ new Set();
  33020. const getImportedChunks = (chunk, seen = /* @__PURE__ */ new Set()) => {
  33021. const chunks = [];
  33022. chunk.imports.forEach((file) => {
  33023. const importee = bundle[file];
  33024. if (importee) {
  33025. if (importee.type === "chunk" && !seen.has(file)) {
  33026. seen.add(file);
  33027. chunks.push(...getImportedChunks(importee, seen));
  33028. chunks.push(importee);
  33029. }
  33030. } else {
  33031. chunks.push(file);
  33032. }
  33033. });
  33034. return chunks;
  33035. };
  33036. const toScriptTag = (chunkOrUrl, toOutputPath, isAsync) => ({
  33037. tag: "script",
  33038. attrs: {
  33039. ...isAsync ? { async: true } : {},
  33040. type: "module",
  33041. // crossorigin must be set not only for serving assets in a different origin
  33042. // but also to make it possible to preload the script using `<link rel="preload">`.
  33043. // `<script type="module">` used to fetch the script with credential mode `omit`,
  33044. // however `crossorigin` attribute cannot specify that value.
  33045. // https://developer.chrome.com/blog/modulepreload/#ok-so-why-doesnt-link-relpreload-work-for-modules:~:text=For%20%3Cscript%3E,of%20other%20modules.
  33046. // Now `<script type="module">` uses `same origin`: https://github.com/whatwg/html/pull/3656#:~:text=Module%20scripts%20are%20always%20fetched%20with%20credentials%20mode%20%22same%2Dorigin%22%20by%20default%20and%20can%20no%20longer%0Ause%20%22omit%22
  33047. crossorigin: true,
  33048. src: typeof chunkOrUrl === "string" ? chunkOrUrl : toOutputPath(chunkOrUrl.fileName)
  33049. }
  33050. });
  33051. const toPreloadTag = (filename, toOutputPath) => ({
  33052. tag: "link",
  33053. attrs: {
  33054. rel: "modulepreload",
  33055. crossorigin: true,
  33056. href: toOutputPath(filename)
  33057. }
  33058. });
  33059. const toStyleSheetLinkTag = (file, toOutputPath) => ({
  33060. tag: "link",
  33061. attrs: {
  33062. rel: "stylesheet",
  33063. crossorigin: true,
  33064. href: toOutputPath(file)
  33065. }
  33066. });
  33067. const getCssFilesForChunk = (chunk, seenChunks = /* @__PURE__ */ new Set(), seenCss = /* @__PURE__ */ new Set()) => {
  33068. if (seenChunks.has(chunk.fileName)) {
  33069. return [];
  33070. }
  33071. seenChunks.add(chunk.fileName);
  33072. if (analyzedImportedCssFiles.has(chunk)) {
  33073. const files2 = analyzedImportedCssFiles.get(chunk);
  33074. const additionals = files2.filter((file) => !seenCss.has(file));
  33075. additionals.forEach((file) => seenCss.add(file));
  33076. return additionals;
  33077. }
  33078. const files = [];
  33079. chunk.imports.forEach((file) => {
  33080. const importee = bundle[file];
  33081. if (importee?.type === "chunk") {
  33082. files.push(...getCssFilesForChunk(importee, seenChunks, seenCss));
  33083. }
  33084. });
  33085. analyzedImportedCssFiles.set(chunk, files);
  33086. chunk.viteMetadata.importedCss.forEach((file) => {
  33087. if (!seenCss.has(file)) {
  33088. seenCss.add(file);
  33089. files.push(file);
  33090. }
  33091. });
  33092. return files;
  33093. };
  33094. const getCssTagsForChunk = (chunk, toOutputPath) => getCssFilesForChunk(chunk).map(
  33095. (file) => toStyleSheetLinkTag(file, toOutputPath)
  33096. );
  33097. for (const [normalizedId, html] of processedHtml(this)) {
  33098. const relativeUrlPath = normalizePath$3(
  33099. path$b.relative(config.root, normalizedId)
  33100. );
  33101. const assetsBase = getBaseInHTML(relativeUrlPath, config);
  33102. const toOutputFilePath = (filename, type) => {
  33103. if (isExternalUrl(filename)) {
  33104. return filename;
  33105. } else {
  33106. return toOutputFilePathInHtml(
  33107. filename,
  33108. type,
  33109. relativeUrlPath,
  33110. "html",
  33111. config,
  33112. (filename2) => assetsBase + filename2
  33113. );
  33114. }
  33115. };
  33116. const toOutputAssetFilePath = (filename) => toOutputFilePath(filename, "asset");
  33117. const toOutputPublicAssetFilePath = (filename) => toOutputFilePath(filename, "public");
  33118. const isAsync = isAsyncScriptMap.get(config).get(normalizedId);
  33119. let result = html;
  33120. const chunk = Object.values(bundle).find(
  33121. (chunk2) => chunk2.type === "chunk" && chunk2.isEntry && chunk2.facadeModuleId && normalizePath$3(chunk2.facadeModuleId) === normalizedId
  33122. );
  33123. let canInlineEntry = false;
  33124. if (chunk) {
  33125. if (options.format === "es" && isEntirelyImport(chunk.code)) {
  33126. canInlineEntry = true;
  33127. }
  33128. const imports = getImportedChunks(chunk);
  33129. let assetTags;
  33130. if (canInlineEntry) {
  33131. assetTags = imports.map(
  33132. (chunk2) => toScriptTag(chunk2, toOutputAssetFilePath, isAsync)
  33133. );
  33134. } else {
  33135. const { modulePreload } = this.environment.config.build;
  33136. assetTags = [toScriptTag(chunk, toOutputAssetFilePath, isAsync)];
  33137. if (modulePreload !== false) {
  33138. const resolveDependencies = typeof modulePreload === "object" && modulePreload.resolveDependencies;
  33139. const importsFileNames = imports.filter((chunkOrUrl) => typeof chunkOrUrl !== "string").map((chunk2) => chunk2.fileName);
  33140. const resolvedDeps = resolveDependencies ? resolveDependencies(chunk.fileName, importsFileNames, {
  33141. hostId: relativeUrlPath,
  33142. hostType: "html"
  33143. }) : importsFileNames;
  33144. assetTags.push(
  33145. ...resolvedDeps.map(
  33146. (i) => toPreloadTag(i, toOutputAssetFilePath)
  33147. )
  33148. );
  33149. }
  33150. }
  33151. assetTags.push(...getCssTagsForChunk(chunk, toOutputAssetFilePath));
  33152. result = injectToHead(result, assetTags);
  33153. }
  33154. if (!this.environment.config.build.cssCodeSplit) {
  33155. const cssBundleName = cssBundleNameCache.get(config);
  33156. const cssChunk = cssBundleName && Object.values(bundle).find(
  33157. (chunk2) => chunk2.type === "asset" && chunk2.names.includes(cssBundleName)
  33158. );
  33159. if (cssChunk) {
  33160. result = injectToHead(result, [
  33161. {
  33162. tag: "link",
  33163. attrs: {
  33164. rel: "stylesheet",
  33165. crossorigin: true,
  33166. href: toOutputAssetFilePath(cssChunk.fileName)
  33167. }
  33168. }
  33169. ]);
  33170. }
  33171. }
  33172. let match;
  33173. let s;
  33174. inlineCSSRE$1.lastIndex = 0;
  33175. while (match = inlineCSSRE$1.exec(result)) {
  33176. s ||= new MagicString(result);
  33177. const { 0: full, 1: scopedName } = match;
  33178. const cssTransformedCode = htmlProxyResult.get(scopedName);
  33179. s.update(match.index, match.index + full.length, cssTransformedCode);
  33180. }
  33181. if (s) {
  33182. result = s.toString();
  33183. }
  33184. result = await applyHtmlTransforms(
  33185. result,
  33186. [...normalHooks, ...postHooks],
  33187. {
  33188. path: "/" + relativeUrlPath,
  33189. filename: normalizedId,
  33190. bundle,
  33191. chunk
  33192. }
  33193. );
  33194. result = result.replace(assetUrlRE, (_, fileHash, postfix = "") => {
  33195. const file = this.getFileName(fileHash);
  33196. if (chunk) {
  33197. chunk.viteMetadata.importedAssets.add(cleanUrl(file));
  33198. }
  33199. return encodeURIPath(toOutputAssetFilePath(file)) + postfix;
  33200. });
  33201. result = result.replace(publicAssetUrlRE, (_, fileHash) => {
  33202. const publicAssetPath = toOutputPublicAssetFilePath(
  33203. getPublicAssetFilename(fileHash, config)
  33204. );
  33205. return encodeURIPath(
  33206. urlCanParse(publicAssetPath) ? publicAssetPath : normalizePath$3(publicAssetPath)
  33207. );
  33208. });
  33209. if (chunk && canInlineEntry) {
  33210. inlineEntryChunk.add(chunk.fileName);
  33211. }
  33212. const shortEmitName = normalizePath$3(
  33213. path$b.relative(config.root, normalizedId)
  33214. );
  33215. this.emitFile({
  33216. type: "asset",
  33217. originalFileName: normalizedId,
  33218. fileName: shortEmitName,
  33219. source: result
  33220. });
  33221. }
  33222. for (const fileName of inlineEntryChunk) {
  33223. delete bundle[fileName];
  33224. }
  33225. }
  33226. };
  33227. }
  33228. function parseRelAttr(attr) {
  33229. return attr.split(spaceRe).map((v) => v.toLowerCase());
  33230. }
  33231. function findNeedTransformStyleAttribute(node) {
  33232. const attr = node.attrs.find(
  33233. (prop) => prop.prefix === void 0 && prop.name === "style" && // only url(...) or image-set(...) in css need to emit file
  33234. (prop.value.includes("url(") || prop.value.includes("image-set("))
  33235. );
  33236. if (!attr) return void 0;
  33237. const location = node.sourceCodeLocation?.attrs?.["style"];
  33238. return { attr, location };
  33239. }
  33240. function extractImportExpressionFromClassicScript(scriptTextNode) {
  33241. const startOffset = scriptTextNode.sourceCodeLocation.startOffset;
  33242. const cleanCode = stripLiteral(scriptTextNode.value);
  33243. const scriptUrls = [];
  33244. let match;
  33245. inlineImportRE.lastIndex = 0;
  33246. while (match = inlineImportRE.exec(cleanCode)) {
  33247. const [, [urlStart, urlEnd]] = match.indices;
  33248. const start = urlStart + 1;
  33249. const end = urlEnd - 1;
  33250. scriptUrls.push({
  33251. start: start + startOffset,
  33252. end: end + startOffset,
  33253. url: scriptTextNode.value.slice(start, end)
  33254. });
  33255. }
  33256. return scriptUrls;
  33257. }
  33258. function preImportMapHook(config) {
  33259. return (html, ctx) => {
  33260. const importMapIndex = html.search(importMapRE);
  33261. if (importMapIndex < 0) return;
  33262. const importMapAppendIndex = html.search(importMapAppendRE);
  33263. if (importMapAppendIndex < 0) return;
  33264. if (importMapAppendIndex < importMapIndex) {
  33265. const relativeHtml = normalizePath$3(
  33266. path$b.relative(config.root, ctx.filename)
  33267. );
  33268. config.logger.warnOnce(
  33269. colors$1.yellow(
  33270. colors$1.bold(
  33271. `(!) <script type="importmap"> should come before <script type="module"> and <link rel="modulepreload"> in /${relativeHtml}`
  33272. )
  33273. )
  33274. );
  33275. }
  33276. };
  33277. }
  33278. function postImportMapHook() {
  33279. return (html) => {
  33280. if (!importMapAppendRE.test(html)) return;
  33281. let importMap;
  33282. html = html.replace(importMapRE, (match) => {
  33283. importMap = match;
  33284. return "";
  33285. });
  33286. if (importMap) {
  33287. html = html.replace(
  33288. importMapAppendRE,
  33289. (match) => `${importMap}
  33290. ${match}`
  33291. );
  33292. }
  33293. return html;
  33294. };
  33295. }
  33296. function injectCspNonceMetaTagHook(config) {
  33297. return () => {
  33298. if (!config.html?.cspNonce) return;
  33299. return [
  33300. {
  33301. tag: "meta",
  33302. injectTo: "head",
  33303. // use nonce attribute so that it's hidden
  33304. // https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/nonce#accessing_nonces_and_nonce_hiding
  33305. attrs: { property: "csp-nonce", nonce: config.html.cspNonce }
  33306. }
  33307. ];
  33308. };
  33309. }
  33310. function htmlEnvHook(config) {
  33311. const pattern = /%(\S+?)%/g;
  33312. const envPrefix = resolveEnvPrefix({ envPrefix: config.envPrefix });
  33313. const env = { ...config.env };
  33314. for (const key in config.define) {
  33315. if (key.startsWith(`import.meta.env.`)) {
  33316. const val = config.define[key];
  33317. if (typeof val === "string") {
  33318. try {
  33319. const parsed = JSON.parse(val);
  33320. env[key.slice(16)] = typeof parsed === "string" ? parsed : val;
  33321. } catch {
  33322. env[key.slice(16)] = val;
  33323. }
  33324. } else {
  33325. env[key.slice(16)] = JSON.stringify(val);
  33326. }
  33327. }
  33328. }
  33329. return (html, ctx) => {
  33330. return html.replace(pattern, (text, key) => {
  33331. if (key in env) {
  33332. return env[key];
  33333. } else {
  33334. if (envPrefix.some((prefix) => key.startsWith(prefix))) {
  33335. const relativeHtml = normalizePath$3(
  33336. path$b.relative(config.root, ctx.filename)
  33337. );
  33338. config.logger.warn(
  33339. colors$1.yellow(
  33340. colors$1.bold(
  33341. `(!) ${text} is not defined in env variables found in /${relativeHtml}. Is the variable mistyped?`
  33342. )
  33343. )
  33344. );
  33345. }
  33346. return text;
  33347. }
  33348. });
  33349. };
  33350. }
  33351. function injectNonceAttributeTagHook(config) {
  33352. const processRelType = /* @__PURE__ */ new Set(["stylesheet", "modulepreload", "preload"]);
  33353. return async (html, { filename }) => {
  33354. const nonce = config.html?.cspNonce;
  33355. if (!nonce) return;
  33356. const s = new MagicString(html);
  33357. await traverseHtml(html, filename, (node) => {
  33358. if (!nodeIsElement(node)) {
  33359. return;
  33360. }
  33361. const { nodeName, attrs, sourceCodeLocation } = node;
  33362. if (nodeName === "script" || nodeName === "style" || nodeName === "link" && attrs.some(
  33363. (attr) => attr.name === "rel" && parseRelAttr(attr.value).some((a) => processRelType.has(a))
  33364. )) {
  33365. if (attrs.some(({ name }) => name === "nonce")) {
  33366. return;
  33367. }
  33368. const startTagEndOffset = sourceCodeLocation.startTag.endOffset;
  33369. const appendOffset = html[startTagEndOffset - 2] === "/" ? 2 : 1;
  33370. s.appendRight(startTagEndOffset - appendOffset, ` nonce="${nonce}"`);
  33371. }
  33372. });
  33373. return s.toString();
  33374. };
  33375. }
  33376. function resolveHtmlTransforms(plugins, logger) {
  33377. const preHooks = [];
  33378. const normalHooks = [];
  33379. const postHooks = [];
  33380. for (const plugin of plugins) {
  33381. const hook = plugin.transformIndexHtml;
  33382. if (!hook) continue;
  33383. if (typeof hook === "function") {
  33384. normalHooks.push(hook);
  33385. } else {
  33386. if (!("order" in hook) && "enforce" in hook) {
  33387. logger.warnOnce(
  33388. colors$1.yellow(
  33389. `plugin '${plugin.name}' uses deprecated 'enforce' option. Use 'order' option instead.`
  33390. )
  33391. );
  33392. }
  33393. if (!("handler" in hook) && "transform" in hook) {
  33394. logger.warnOnce(
  33395. colors$1.yellow(
  33396. `plugin '${plugin.name}' uses deprecated 'transform' option. Use 'handler' option instead.`
  33397. )
  33398. );
  33399. }
  33400. const order = hook.order ?? (hook.enforce === "pre" ? "pre" : void 0);
  33401. const handler = hook.handler ?? hook.transform;
  33402. if (order === "pre") {
  33403. preHooks.push(handler);
  33404. } else if (order === "post") {
  33405. postHooks.push(handler);
  33406. } else {
  33407. normalHooks.push(handler);
  33408. }
  33409. }
  33410. }
  33411. return [preHooks, normalHooks, postHooks];
  33412. }
  33413. const elementsAllowedInHead = /* @__PURE__ */ new Set([
  33414. "title",
  33415. "base",
  33416. "link",
  33417. "style",
  33418. "meta",
  33419. "script",
  33420. "noscript",
  33421. "template"
  33422. ]);
  33423. function headTagInsertCheck(tags, ctx) {
  33424. if (!tags.length) return;
  33425. const { logger } = ctx.server?.config || {};
  33426. const disallowedTags = tags.filter(
  33427. (tagDescriptor) => !elementsAllowedInHead.has(tagDescriptor.tag)
  33428. );
  33429. if (disallowedTags.length) {
  33430. const dedupedTags = unique(
  33431. disallowedTags.map((tagDescriptor) => `<${tagDescriptor.tag}>`)
  33432. );
  33433. logger?.warn(
  33434. colors$1.yellow(
  33435. colors$1.bold(
  33436. `[${dedupedTags.join(",")}] can not be used inside the <head> Element, please check the 'injectTo' value`
  33437. )
  33438. )
  33439. );
  33440. }
  33441. }
  33442. async function applyHtmlTransforms(html, hooks, ctx) {
  33443. for (const hook of hooks) {
  33444. const res = await hook(html, ctx);
  33445. if (!res) {
  33446. continue;
  33447. }
  33448. if (typeof res === "string") {
  33449. html = res;
  33450. } else {
  33451. let tags;
  33452. if (Array.isArray(res)) {
  33453. tags = res;
  33454. } else {
  33455. html = res.html || html;
  33456. tags = res.tags;
  33457. }
  33458. let headTags;
  33459. let headPrependTags;
  33460. let bodyTags;
  33461. let bodyPrependTags;
  33462. for (const tag of tags) {
  33463. switch (tag.injectTo) {
  33464. case "body":
  33465. (bodyTags ??= []).push(tag);
  33466. break;
  33467. case "body-prepend":
  33468. (bodyPrependTags ??= []).push(tag);
  33469. break;
  33470. case "head":
  33471. (headTags ??= []).push(tag);
  33472. break;
  33473. default:
  33474. (headPrependTags ??= []).push(tag);
  33475. }
  33476. }
  33477. headTagInsertCheck([...headTags || [], ...headPrependTags || []], ctx);
  33478. if (headPrependTags) html = injectToHead(html, headPrependTags, true);
  33479. if (headTags) html = injectToHead(html, headTags);
  33480. if (bodyPrependTags) html = injectToBody(html, bodyPrependTags, true);
  33481. if (bodyTags) html = injectToBody(html, bodyTags);
  33482. }
  33483. }
  33484. return html;
  33485. }
  33486. const importRE = /\bimport\s*(?:"[^"]*[^\\]"|'[^']*[^\\]');*/g;
  33487. const commentRE = /\/\*[\s\S]*?\*\/|\/\/.*$/gm;
  33488. function isEntirelyImport(code) {
  33489. return !code.replace(importRE, "").replace(commentRE, "").trim().length;
  33490. }
  33491. function getBaseInHTML(urlRelativePath, config) {
  33492. return config.base === "./" || config.base === "" ? path$b.posix.join(
  33493. path$b.posix.relative(urlRelativePath, "").slice(0, -2),
  33494. "./"
  33495. ) : config.base;
  33496. }
  33497. const headInjectRE = /([ \t]*)<\/head>/i;
  33498. const headPrependInjectRE = /([ \t]*)<head[^>]*>/i;
  33499. const htmlInjectRE = /<\/html>/i;
  33500. const htmlPrependInjectRE = /([ \t]*)<html[^>]*>/i;
  33501. const bodyInjectRE = /([ \t]*)<\/body>/i;
  33502. const bodyPrependInjectRE = /([ \t]*)<body[^>]*>/i;
  33503. const doctypePrependInjectRE = /<!doctype html>/i;
  33504. function injectToHead(html, tags, prepend = false) {
  33505. if (tags.length === 0) return html;
  33506. if (prepend) {
  33507. if (headPrependInjectRE.test(html)) {
  33508. return html.replace(
  33509. headPrependInjectRE,
  33510. (match, p1) => `${match}
  33511. ${serializeTags(tags, incrementIndent(p1))}`
  33512. );
  33513. }
  33514. } else {
  33515. if (headInjectRE.test(html)) {
  33516. return html.replace(
  33517. headInjectRE,
  33518. (match, p1) => `${serializeTags(tags, incrementIndent(p1))}${match}`
  33519. );
  33520. }
  33521. if (bodyPrependInjectRE.test(html)) {
  33522. return html.replace(
  33523. bodyPrependInjectRE,
  33524. (match, p1) => `${serializeTags(tags, p1)}
  33525. ${match}`
  33526. );
  33527. }
  33528. }
  33529. return prependInjectFallback(html, tags);
  33530. }
  33531. function injectToBody(html, tags, prepend = false) {
  33532. if (tags.length === 0) return html;
  33533. if (prepend) {
  33534. if (bodyPrependInjectRE.test(html)) {
  33535. return html.replace(
  33536. bodyPrependInjectRE,
  33537. (match, p1) => `${match}
  33538. ${serializeTags(tags, incrementIndent(p1))}`
  33539. );
  33540. }
  33541. if (headInjectRE.test(html)) {
  33542. return html.replace(
  33543. headInjectRE,
  33544. (match, p1) => `${match}
  33545. ${serializeTags(tags, p1)}`
  33546. );
  33547. }
  33548. return prependInjectFallback(html, tags);
  33549. } else {
  33550. if (bodyInjectRE.test(html)) {
  33551. return html.replace(
  33552. bodyInjectRE,
  33553. (match, p1) => `${serializeTags(tags, incrementIndent(p1))}${match}`
  33554. );
  33555. }
  33556. if (htmlInjectRE.test(html)) {
  33557. return html.replace(htmlInjectRE, `${serializeTags(tags)}
  33558. $&`);
  33559. }
  33560. return html + `
  33561. ` + serializeTags(tags);
  33562. }
  33563. }
  33564. function prependInjectFallback(html, tags) {
  33565. if (htmlPrependInjectRE.test(html)) {
  33566. return html.replace(htmlPrependInjectRE, `$&
  33567. ${serializeTags(tags)}`);
  33568. }
  33569. if (doctypePrependInjectRE.test(html)) {
  33570. return html.replace(doctypePrependInjectRE, `$&
  33571. ${serializeTags(tags)}`);
  33572. }
  33573. return serializeTags(tags) + html;
  33574. }
  33575. const unaryTags = /* @__PURE__ */ new Set(["link", "meta", "base"]);
  33576. function serializeTag({ tag, attrs, children }, indent = "") {
  33577. if (unaryTags.has(tag)) {
  33578. return `<${tag}${serializeAttrs(attrs)}>`;
  33579. } else {
  33580. return `<${tag}${serializeAttrs(attrs)}>${serializeTags(
  33581. children,
  33582. incrementIndent(indent)
  33583. )}</${tag}>`;
  33584. }
  33585. }
  33586. function serializeTags(tags, indent = "") {
  33587. if (typeof tags === "string") {
  33588. return tags;
  33589. } else if (tags && tags.length) {
  33590. return tags.map((tag) => `${indent}${serializeTag(tag, indent)}
  33591. `).join("");
  33592. }
  33593. return "";
  33594. }
  33595. function serializeAttrs(attrs) {
  33596. let res = "";
  33597. for (const key in attrs) {
  33598. if (typeof attrs[key] === "boolean") {
  33599. res += attrs[key] ? ` ${key}` : ``;
  33600. } else {
  33601. res += ` ${key}="${escapeHtml$2(attrs[key])}"`;
  33602. }
  33603. }
  33604. return res;
  33605. }
  33606. function incrementIndent(indent = "") {
  33607. return `${indent}${indent[0] === " " ? " " : " "}`;
  33608. }
  33609. function decodeURIIfPossible(input) {
  33610. try {
  33611. return decodeURI(input);
  33612. } catch {
  33613. return;
  33614. }
  33615. }
  33616. const debugCache = createDebugger("vite:cache");
  33617. const knownIgnoreList = /* @__PURE__ */ new Set(["/", "/favicon.ico"]);
  33618. const trailingQuerySeparatorsRE = /[?&]+$/;
  33619. const urlRE = /[?&]url\b/;
  33620. const rawRE = /[?&]raw\b/;
  33621. const inlineRE$2 = /[?&]inline\b/;
  33622. const svgRE = /\.svg\b/;
  33623. function deniedServingAccessForTransform(url, server, res, next) {
  33624. if (rawRE.test(url) || urlRE.test(url) || inlineRE$2.test(url) || svgRE.test(url)) {
  33625. const servingAccessResult = checkServingAccess(url, server);
  33626. if (servingAccessResult === "denied") {
  33627. respondWithAccessDenied(url, server, res);
  33628. return true;
  33629. }
  33630. if (servingAccessResult === "fallback") {
  33631. next();
  33632. return true;
  33633. }
  33634. }
  33635. return false;
  33636. }
  33637. function cachedTransformMiddleware(server) {
  33638. return function viteCachedTransformMiddleware(req, res, next) {
  33639. const environment = server.environments.client;
  33640. const ifNoneMatch = req.headers["if-none-match"];
  33641. if (ifNoneMatch) {
  33642. const moduleByEtag = environment.moduleGraph.getModuleByEtag(ifNoneMatch);
  33643. if (moduleByEtag?.transformResult?.etag === ifNoneMatch && moduleByEtag.url === req.url) {
  33644. const maybeMixedEtag = isCSSRequest(req.url);
  33645. if (!maybeMixedEtag) {
  33646. debugCache?.(`[304] ${prettifyUrl(req.url, server.config.root)}`);
  33647. res.statusCode = 304;
  33648. return res.end();
  33649. }
  33650. }
  33651. }
  33652. next();
  33653. };
  33654. }
  33655. function transformMiddleware(server) {
  33656. const { root, publicDir } = server.config;
  33657. const publicDirInRoot = publicDir.startsWith(withTrailingSlash(root));
  33658. const publicPath = `${publicDir.slice(root.length)}/`;
  33659. return async function viteTransformMiddleware(req, res, next) {
  33660. const environment = server.environments.client;
  33661. if (req.method !== "GET" || knownIgnoreList.has(req.url)) {
  33662. return next();
  33663. }
  33664. let url;
  33665. try {
  33666. url = decodeURI(removeTimestampQuery(req.url)).replace(
  33667. NULL_BYTE_PLACEHOLDER,
  33668. "\0"
  33669. );
  33670. } catch (e) {
  33671. if (e instanceof URIError) {
  33672. server.config.logger.warn(
  33673. colors$1.yellow("Malformed URI sequence in request URL")
  33674. );
  33675. return next();
  33676. }
  33677. return next(e);
  33678. }
  33679. const withoutQuery = cleanUrl(url);
  33680. try {
  33681. const isSourceMap = withoutQuery.endsWith(".map");
  33682. if (isSourceMap) {
  33683. const depsOptimizer = environment.depsOptimizer;
  33684. if (depsOptimizer?.isOptimizedDepUrl(url)) {
  33685. const sourcemapPath = url.startsWith(FS_PREFIX) ? fsPathFromId(url) : normalizePath$3(path$b.resolve(server.config.root, url.slice(1)));
  33686. try {
  33687. const map = JSON.parse(
  33688. await fsp.readFile(sourcemapPath, "utf-8")
  33689. );
  33690. applySourcemapIgnoreList(
  33691. map,
  33692. sourcemapPath,
  33693. server.config.server.sourcemapIgnoreList,
  33694. server.config.logger
  33695. );
  33696. return send$1(req, res, JSON.stringify(map), "json", {
  33697. headers: server.config.server.headers
  33698. });
  33699. } catch {
  33700. const dummySourceMap = {
  33701. version: 3,
  33702. file: sourcemapPath.replace(/\.map$/, ""),
  33703. sources: [],
  33704. sourcesContent: [],
  33705. names: [],
  33706. mappings: ";;;;;;;;;"
  33707. };
  33708. return send$1(req, res, JSON.stringify(dummySourceMap), "json", {
  33709. cacheControl: "no-cache",
  33710. headers: server.config.server.headers
  33711. });
  33712. }
  33713. } else {
  33714. const originalUrl = url.replace(/\.map($|\?)/, "$1");
  33715. const map = (await environment.moduleGraph.getModuleByUrl(originalUrl))?.transformResult?.map;
  33716. if (map) {
  33717. return send$1(req, res, JSON.stringify(map), "json", {
  33718. headers: server.config.server.headers
  33719. });
  33720. } else {
  33721. return next();
  33722. }
  33723. }
  33724. }
  33725. if (publicDirInRoot && url.startsWith(publicPath)) {
  33726. warnAboutExplicitPublicPathInUrl(url);
  33727. }
  33728. const urlWithoutTrailingQuerySeparators = url.replace(
  33729. trailingQuerySeparatorsRE,
  33730. ""
  33731. );
  33732. if (deniedServingAccessForTransform(
  33733. urlWithoutTrailingQuerySeparators,
  33734. server,
  33735. res,
  33736. next
  33737. )) {
  33738. return;
  33739. }
  33740. if (req.headers["sec-fetch-dest"] === "script" || isJSRequest(url) || isImportRequest(url) || isCSSRequest(url) || isHTMLProxy(url)) {
  33741. url = removeImportQuery(url);
  33742. url = unwrapId$1(url);
  33743. if (isCSSRequest(url)) {
  33744. if (req.headers.accept?.includes("text/css") && !isDirectRequest(url)) {
  33745. url = injectQuery(url, "direct");
  33746. }
  33747. const ifNoneMatch = req.headers["if-none-match"];
  33748. if (ifNoneMatch && (await environment.moduleGraph.getModuleByUrl(url))?.transformResult?.etag === ifNoneMatch) {
  33749. debugCache?.(`[304] ${prettifyUrl(url, server.config.root)}`);
  33750. res.statusCode = 304;
  33751. return res.end();
  33752. }
  33753. }
  33754. const result = await transformRequest(environment, url, {
  33755. html: req.headers.accept?.includes("text/html"),
  33756. allowId(id) {
  33757. return !deniedServingAccessForTransform(id, server, res, next);
  33758. }
  33759. });
  33760. if (result) {
  33761. const depsOptimizer = environment.depsOptimizer;
  33762. const type = isDirectCSSRequest(url) ? "css" : "js";
  33763. const isDep = DEP_VERSION_RE.test(url) || depsOptimizer?.isOptimizedDepUrl(url);
  33764. return send$1(req, res, result.code, type, {
  33765. etag: result.etag,
  33766. // allow browser to cache npm deps!
  33767. cacheControl: isDep ? "max-age=31536000,immutable" : "no-cache",
  33768. headers: server.config.server.headers,
  33769. map: result.map
  33770. });
  33771. }
  33772. }
  33773. } catch (e) {
  33774. if (e?.code === ERR_OPTIMIZE_DEPS_PROCESSING_ERROR) {
  33775. if (!res.writableEnded) {
  33776. res.statusCode = 504;
  33777. res.statusMessage = "Optimize Deps Processing Error";
  33778. res.end();
  33779. }
  33780. server.config.logger.error(e.message);
  33781. return;
  33782. }
  33783. if (e?.code === ERR_OUTDATED_OPTIMIZED_DEP) {
  33784. if (!res.writableEnded) {
  33785. res.statusCode = 504;
  33786. res.statusMessage = "Outdated Optimize Dep";
  33787. res.end();
  33788. }
  33789. return;
  33790. }
  33791. if (e?.code === ERR_CLOSED_SERVER) {
  33792. if (!res.writableEnded) {
  33793. res.statusCode = 504;
  33794. res.statusMessage = "Outdated Request";
  33795. res.end();
  33796. }
  33797. return;
  33798. }
  33799. if (e?.code === ERR_FILE_NOT_FOUND_IN_OPTIMIZED_DEP_DIR) {
  33800. if (!res.writableEnded) {
  33801. res.statusCode = 404;
  33802. res.end();
  33803. }
  33804. server.config.logger.warn(colors$1.yellow(e.message));
  33805. return;
  33806. }
  33807. if (e?.code === ERR_LOAD_URL) {
  33808. return next();
  33809. }
  33810. if (e?.code === ERR_DENIED_ID) {
  33811. return;
  33812. }
  33813. return next(e);
  33814. }
  33815. next();
  33816. };
  33817. function warnAboutExplicitPublicPathInUrl(url) {
  33818. let warning;
  33819. if (isImportRequest(url)) {
  33820. const rawUrl = removeImportQuery(url);
  33821. if (urlRE.test(url)) {
  33822. warning = `Assets in the public directory are served at the root path.
  33823. Instead of ${colors$1.cyan(rawUrl)}, use ${colors$1.cyan(
  33824. rawUrl.replace(publicPath, "/")
  33825. )}.`;
  33826. } else {
  33827. warning = `Assets in public directory cannot be imported from JavaScript.
  33828. If you intend to import that asset, put the file in the src directory, and use ${colors$1.cyan(
  33829. rawUrl.replace(publicPath, "/src/")
  33830. )} instead of ${colors$1.cyan(rawUrl)}.
  33831. If you intend to use the URL of that asset, use ${colors$1.cyan(
  33832. injectQuery(rawUrl.replace(publicPath, "/"), "url")
  33833. )}.`;
  33834. }
  33835. } else {
  33836. warning = `Files in the public directory are served at the root path.
  33837. Instead of ${colors$1.cyan(url)}, use ${colors$1.cyan(
  33838. url.replace(publicPath, "/")
  33839. )}.`;
  33840. }
  33841. server.config.logger.warn(colors$1.yellow(warning));
  33842. }
  33843. }
  33844. function createDevHtmlTransformFn(config) {
  33845. const [preHooks, normalHooks, postHooks] = resolveHtmlTransforms(
  33846. config.plugins,
  33847. config.logger
  33848. );
  33849. const transformHooks = [
  33850. preImportMapHook(config),
  33851. injectCspNonceMetaTagHook(config),
  33852. ...preHooks,
  33853. htmlEnvHook(config),
  33854. devHtmlHook,
  33855. ...normalHooks,
  33856. ...postHooks,
  33857. injectNonceAttributeTagHook(config),
  33858. postImportMapHook()
  33859. ];
  33860. return (server, url, html, originalUrl) => {
  33861. return applyHtmlTransforms(html, transformHooks, {
  33862. path: url,
  33863. filename: getHtmlFilename(url, server),
  33864. server,
  33865. originalUrl
  33866. });
  33867. };
  33868. }
  33869. function getHtmlFilename(url, server) {
  33870. if (url.startsWith(FS_PREFIX)) {
  33871. return decodeURIComponent(fsPathFromId(url));
  33872. } else {
  33873. return decodeURIComponent(
  33874. normalizePath$3(path$b.join(server.config.root, url.slice(1)))
  33875. );
  33876. }
  33877. }
  33878. function shouldPreTransform(url, config) {
  33879. return !checkPublicFile(url, config) && (isJSRequest(url) || isCSSRequest(url));
  33880. }
  33881. const wordCharRE = /\w/;
  33882. function isBareRelative(url) {
  33883. return wordCharRE.test(url[0]) && !url.includes(":");
  33884. }
  33885. const processNodeUrl = (url, useSrcSetReplacer, config, htmlPath, originalUrl, server, isClassicScriptLink) => {
  33886. const replacer = (url2) => {
  33887. if (url2[0] === "/" && url2[1] !== "/" || // #3230 if some request url (localhost:3000/a/b) return to fallback html, the relative assets
  33888. // path will add `/a/` prefix, it will caused 404.
  33889. //
  33890. // skip if url contains `:` as it implies a url protocol or Windows path that we don't want to replace.
  33891. //
  33892. // rewrite `./index.js` -> `localhost:5173/a/index.js`.
  33893. // rewrite `../index.js` -> `localhost:5173/index.js`.
  33894. // rewrite `relative/index.js` -> `localhost:5173/a/relative/index.js`.
  33895. (url2[0] === "." || isBareRelative(url2)) && originalUrl && originalUrl !== "/" && htmlPath === "/index.html") {
  33896. url2 = path$b.posix.join(config.base, url2);
  33897. }
  33898. let preTransformUrl;
  33899. if (!isClassicScriptLink && shouldPreTransform(url2, config)) {
  33900. if (url2[0] === "/" && url2[1] !== "/") {
  33901. preTransformUrl = url2;
  33902. } else if (url2[0] === "." || isBareRelative(url2)) {
  33903. preTransformUrl = path$b.posix.join(
  33904. config.base,
  33905. path$b.posix.dirname(htmlPath),
  33906. url2
  33907. );
  33908. }
  33909. }
  33910. if (server) {
  33911. const mod = server.environments.client.moduleGraph.urlToModuleMap.get(
  33912. preTransformUrl || url2
  33913. );
  33914. if (mod && mod.lastHMRTimestamp > 0) {
  33915. url2 = injectQuery(url2, `t=${mod.lastHMRTimestamp}`);
  33916. }
  33917. }
  33918. if (server && preTransformUrl) {
  33919. try {
  33920. preTransformUrl = decodeURI(preTransformUrl);
  33921. } catch {
  33922. return url2;
  33923. }
  33924. preTransformRequest(server, preTransformUrl, config.decodedBase);
  33925. }
  33926. return url2;
  33927. };
  33928. const processedUrl = useSrcSetReplacer ? processSrcSetSync(url, ({ url: url2 }) => replacer(url2)) : replacer(url);
  33929. return processedUrl;
  33930. };
  33931. const devHtmlHook = async (html, { path: htmlPath, filename, server, originalUrl }) => {
  33932. const { config, watcher } = server;
  33933. const base = config.base || "/";
  33934. const decodedBase = config.decodedBase || "/";
  33935. let proxyModulePath;
  33936. let proxyModuleUrl;
  33937. const trailingSlash = htmlPath.endsWith("/");
  33938. if (!trailingSlash && fs__default.existsSync(filename)) {
  33939. proxyModulePath = htmlPath;
  33940. proxyModuleUrl = proxyModulePath;
  33941. } else {
  33942. const validPath = `${htmlPath}${trailingSlash ? "index.html" : ""}`;
  33943. proxyModulePath = `\0${validPath}`;
  33944. proxyModuleUrl = wrapId$1(proxyModulePath);
  33945. }
  33946. proxyModuleUrl = joinUrlSegments(decodedBase, proxyModuleUrl);
  33947. const s = new MagicString(html);
  33948. let inlineModuleIndex = -1;
  33949. const proxyCacheUrl = decodeURI(
  33950. cleanUrl(proxyModulePath).replace(normalizePath$3(config.root), "")
  33951. );
  33952. const styleUrl = [];
  33953. const inlineStyles = [];
  33954. const inlineModulePaths = [];
  33955. const addInlineModule = (node, ext) => {
  33956. inlineModuleIndex++;
  33957. const contentNode = node.childNodes[0];
  33958. const code = contentNode.value;
  33959. let map;
  33960. if (proxyModulePath[0] !== "\0") {
  33961. map = new MagicString(html).snip(
  33962. contentNode.sourceCodeLocation.startOffset,
  33963. contentNode.sourceCodeLocation.endOffset
  33964. ).generateMap({ hires: "boundary" });
  33965. map.sources = [filename];
  33966. map.file = filename;
  33967. }
  33968. addToHTMLProxyCache(config, proxyCacheUrl, inlineModuleIndex, { code, map });
  33969. const modulePath = `${proxyModuleUrl}?html-proxy&index=${inlineModuleIndex}.${ext}`;
  33970. inlineModulePaths.push(modulePath);
  33971. s.update(
  33972. node.sourceCodeLocation.startOffset,
  33973. node.sourceCodeLocation.endOffset,
  33974. `<script type="module" src="${modulePath}"><\/script>`
  33975. );
  33976. preTransformRequest(server, modulePath, decodedBase);
  33977. };
  33978. await traverseHtml(html, filename, (node) => {
  33979. if (!nodeIsElement(node)) {
  33980. return;
  33981. }
  33982. if (node.nodeName === "script") {
  33983. const { src, srcSourceCodeLocation, isModule, isIgnored } = getScriptInfo(node);
  33984. if (isIgnored) {
  33985. removeViteIgnoreAttr(s, node.sourceCodeLocation);
  33986. } else if (src) {
  33987. const processedUrl = processNodeUrl(
  33988. src.value,
  33989. /* useSrcSetReplacer */
  33990. false,
  33991. config,
  33992. htmlPath,
  33993. originalUrl,
  33994. server,
  33995. !isModule
  33996. );
  33997. if (processedUrl !== src.value) {
  33998. overwriteAttrValue(s, srcSourceCodeLocation, processedUrl);
  33999. }
  34000. } else if (isModule && node.childNodes.length) {
  34001. addInlineModule(node, "js");
  34002. } else if (node.childNodes.length) {
  34003. const scriptNode = node.childNodes[node.childNodes.length - 1];
  34004. for (const {
  34005. url,
  34006. start,
  34007. end
  34008. } of extractImportExpressionFromClassicScript(scriptNode)) {
  34009. const processedUrl = processNodeUrl(
  34010. url,
  34011. false,
  34012. config,
  34013. htmlPath,
  34014. originalUrl
  34015. );
  34016. if (processedUrl !== url) {
  34017. s.update(start, end, processedUrl);
  34018. }
  34019. }
  34020. }
  34021. }
  34022. const inlineStyle = findNeedTransformStyleAttribute(node);
  34023. if (inlineStyle) {
  34024. inlineModuleIndex++;
  34025. inlineStyles.push({
  34026. index: inlineModuleIndex,
  34027. location: inlineStyle.location,
  34028. code: inlineStyle.attr.value
  34029. });
  34030. }
  34031. if (node.nodeName === "style" && node.childNodes.length) {
  34032. const children = node.childNodes[0];
  34033. styleUrl.push({
  34034. start: children.sourceCodeLocation.startOffset,
  34035. end: children.sourceCodeLocation.endOffset,
  34036. code: children.value
  34037. });
  34038. }
  34039. const assetAttributes = getNodeAssetAttributes(node);
  34040. for (const attr of assetAttributes) {
  34041. if (attr.type === "remove") {
  34042. s.remove(attr.location.startOffset, attr.location.endOffset);
  34043. } else {
  34044. const processedUrl = processNodeUrl(
  34045. attr.value,
  34046. attr.type === "srcset",
  34047. config,
  34048. htmlPath,
  34049. originalUrl
  34050. );
  34051. if (processedUrl !== attr.value) {
  34052. overwriteAttrValue(s, attr.location, processedUrl);
  34053. }
  34054. }
  34055. }
  34056. });
  34057. const clientModuelGraph = server?.environments.client.moduleGraph;
  34058. if (clientModuelGraph) {
  34059. await Promise.all(
  34060. inlineModulePaths.map(async (url) => {
  34061. const module = await clientModuelGraph.getModuleByUrl(url);
  34062. if (module) {
  34063. clientModuelGraph.invalidateModule(module);
  34064. }
  34065. })
  34066. );
  34067. }
  34068. await Promise.all([
  34069. ...styleUrl.map(async ({ start, end, code }, index) => {
  34070. const url = `${proxyModulePath}?html-proxy&direct&index=${index}.css`;
  34071. const mod = await server.environments.client.moduleGraph.ensureEntryFromUrl(
  34072. url,
  34073. false
  34074. );
  34075. ensureWatchedFile(watcher, mod.file, config.root);
  34076. const result = await server.pluginContainer.transform(code, mod.id, {
  34077. environment: server.environments.client
  34078. });
  34079. let content = "";
  34080. if (result.map && "version" in result.map) {
  34081. if (result.map.mappings) {
  34082. await injectSourcesContent(result.map, proxyModulePath, config.logger);
  34083. }
  34084. content = getCodeWithSourcemap("css", result.code, result.map);
  34085. } else {
  34086. content = result.code;
  34087. }
  34088. s.overwrite(start, end, content);
  34089. }),
  34090. ...inlineStyles.map(async ({ index, location, code }) => {
  34091. const url = `${proxyModulePath}?html-proxy&inline-css&style-attr&index=${index}.css`;
  34092. const mod = await server.environments.client.moduleGraph.ensureEntryFromUrl(
  34093. url,
  34094. false
  34095. );
  34096. ensureWatchedFile(watcher, mod.file, config.root);
  34097. await server?.pluginContainer.transform(code, mod.id, {
  34098. environment: server.environments.client
  34099. });
  34100. const hash = getHash(cleanUrl(mod.id));
  34101. const result = htmlProxyResult.get(`${hash}_${index}`);
  34102. overwriteAttrValue(s, location, result ?? "");
  34103. })
  34104. ]);
  34105. html = s.toString();
  34106. return {
  34107. html,
  34108. tags: [
  34109. {
  34110. tag: "script",
  34111. attrs: {
  34112. type: "module",
  34113. src: path$b.posix.join(base, CLIENT_PUBLIC_PATH)
  34114. },
  34115. injectTo: "head-prepend"
  34116. }
  34117. ]
  34118. };
  34119. };
  34120. function indexHtmlMiddleware(root, server) {
  34121. const isDev = isDevServer(server);
  34122. return async function viteIndexHtmlMiddleware(req, res, next) {
  34123. if (res.writableEnded) {
  34124. return next();
  34125. }
  34126. const url = req.url && cleanUrl(req.url);
  34127. if (url?.endsWith(".html") && req.headers["sec-fetch-dest"] !== "script") {
  34128. let filePath;
  34129. if (isDev && url.startsWith(FS_PREFIX)) {
  34130. filePath = decodeURIComponent(fsPathFromId(url));
  34131. } else {
  34132. filePath = path$b.join(root, decodeURIComponent(url));
  34133. }
  34134. if (fs__default.existsSync(filePath)) {
  34135. const headers = isDev ? server.config.server.headers : server.config.preview.headers;
  34136. try {
  34137. let html = await fsp.readFile(filePath, "utf-8");
  34138. if (isDev) {
  34139. html = await server.transformIndexHtml(url, html, req.originalUrl);
  34140. }
  34141. return send$1(req, res, html, "html", { headers });
  34142. } catch (e) {
  34143. return next(e);
  34144. }
  34145. }
  34146. }
  34147. next();
  34148. };
  34149. }
  34150. function preTransformRequest(server, decodedUrl, decodedBase) {
  34151. if (!server.config.server.preTransformRequests) return;
  34152. decodedUrl = unwrapId$1(stripBase(decodedUrl, decodedBase));
  34153. server.warmupRequest(decodedUrl);
  34154. }
  34155. const logTime = createDebugger("vite:time");
  34156. function timeMiddleware(root) {
  34157. return function viteTimeMiddleware(req, res, next) {
  34158. const start = performance$1.now();
  34159. const end = res.end;
  34160. res.end = (...args) => {
  34161. logTime?.(`${timeFrom(start)} ${prettifyUrl(req.url, root)}`);
  34162. return end.call(res, ...args);
  34163. };
  34164. next();
  34165. };
  34166. }
  34167. const EMPTY_OBJECT$1 = Object.freeze({});
  34168. class ModuleNode {
  34169. _moduleGraph;
  34170. _clientModule;
  34171. _ssrModule;
  34172. constructor(moduleGraph, clientModule, ssrModule) {
  34173. this._moduleGraph = moduleGraph;
  34174. this._clientModule = clientModule;
  34175. this._ssrModule = ssrModule;
  34176. }
  34177. _get(prop) {
  34178. return this._clientModule?.[prop] ?? this._ssrModule?.[prop];
  34179. }
  34180. _set(prop, value) {
  34181. if (this._clientModule) {
  34182. this._clientModule[prop] = value;
  34183. }
  34184. if (this._ssrModule) {
  34185. this._ssrModule[prop] = value;
  34186. }
  34187. }
  34188. _wrapModuleSet(prop, module) {
  34189. if (!module) {
  34190. return /* @__PURE__ */ new Set();
  34191. }
  34192. return createBackwardCompatibleModuleSet(this._moduleGraph, prop, module);
  34193. }
  34194. _getModuleSetUnion(prop) {
  34195. const importedModules = /* @__PURE__ */ new Set();
  34196. const ids = /* @__PURE__ */ new Set();
  34197. if (this._clientModule) {
  34198. for (const mod of this._clientModule[prop]) {
  34199. if (mod.id) ids.add(mod.id);
  34200. importedModules.add(
  34201. this._moduleGraph.getBackwardCompatibleModuleNode(mod)
  34202. );
  34203. }
  34204. }
  34205. if (this._ssrModule) {
  34206. for (const mod of this._ssrModule[prop]) {
  34207. if (mod.id && !ids.has(mod.id)) {
  34208. importedModules.add(
  34209. this._moduleGraph.getBackwardCompatibleModuleNode(mod)
  34210. );
  34211. }
  34212. }
  34213. }
  34214. return importedModules;
  34215. }
  34216. _getModuleInfoUnion(prop) {
  34217. const _clientValue = this._clientModule?.[prop];
  34218. const _ssrValue = this._ssrModule?.[prop];
  34219. if (_clientValue == null && _ssrValue == null) return void 0;
  34220. return new Proxy({}, {
  34221. get: (_, key) => {
  34222. if (key === "meta") {
  34223. return this.meta || EMPTY_OBJECT$1;
  34224. }
  34225. if (_clientValue) {
  34226. if (key in _clientValue) {
  34227. return _clientValue[key];
  34228. }
  34229. }
  34230. if (_ssrValue) {
  34231. if (key in _ssrValue) {
  34232. return _ssrValue[key];
  34233. }
  34234. }
  34235. }
  34236. });
  34237. }
  34238. _getModuleObjectUnion(prop) {
  34239. const _clientValue = this._clientModule?.[prop];
  34240. const _ssrValue = this._ssrModule?.[prop];
  34241. if (_clientValue == null && _ssrValue == null) return void 0;
  34242. const info = {};
  34243. if (_ssrValue) {
  34244. Object.assign(info, _ssrValue);
  34245. }
  34246. if (_clientValue) {
  34247. Object.assign(info, _clientValue);
  34248. }
  34249. return info;
  34250. }
  34251. get url() {
  34252. return this._get("url");
  34253. }
  34254. set url(value) {
  34255. this._set("url", value);
  34256. }
  34257. get id() {
  34258. return this._get("id");
  34259. }
  34260. set id(value) {
  34261. this._set("id", value);
  34262. }
  34263. get file() {
  34264. return this._get("file");
  34265. }
  34266. set file(value) {
  34267. this._set("file", value);
  34268. }
  34269. get type() {
  34270. return this._get("type");
  34271. }
  34272. // `info` needs special care as it's defined as a proxy in `pluginContainer`,
  34273. // so we also merge it as a proxy too
  34274. get info() {
  34275. return this._getModuleInfoUnion("info");
  34276. }
  34277. get meta() {
  34278. return this._getModuleObjectUnion("meta");
  34279. }
  34280. get importers() {
  34281. return this._getModuleSetUnion("importers");
  34282. }
  34283. get clientImportedModules() {
  34284. return this._wrapModuleSet("importedModules", this._clientModule);
  34285. }
  34286. get ssrImportedModules() {
  34287. return this._wrapModuleSet("importedModules", this._ssrModule);
  34288. }
  34289. get importedModules() {
  34290. return this._getModuleSetUnion("importedModules");
  34291. }
  34292. get acceptedHmrDeps() {
  34293. return this._wrapModuleSet("acceptedHmrDeps", this._clientModule);
  34294. }
  34295. get acceptedHmrExports() {
  34296. return this._clientModule?.acceptedHmrExports ?? null;
  34297. }
  34298. get importedBindings() {
  34299. return this._clientModule?.importedBindings ?? null;
  34300. }
  34301. get isSelfAccepting() {
  34302. return this._clientModule?.isSelfAccepting;
  34303. }
  34304. get transformResult() {
  34305. return this._clientModule?.transformResult ?? null;
  34306. }
  34307. set transformResult(value) {
  34308. if (this._clientModule) {
  34309. this._clientModule.transformResult = value;
  34310. }
  34311. }
  34312. get ssrTransformResult() {
  34313. return this._ssrModule?.transformResult ?? null;
  34314. }
  34315. set ssrTransformResult(value) {
  34316. if (this._ssrModule) {
  34317. this._ssrModule.transformResult = value;
  34318. }
  34319. }
  34320. get ssrModule() {
  34321. return this._ssrModule?.ssrModule ?? null;
  34322. }
  34323. get ssrError() {
  34324. return this._ssrModule?.ssrError ?? null;
  34325. }
  34326. get lastHMRTimestamp() {
  34327. return Math.max(
  34328. this._clientModule?.lastHMRTimestamp ?? 0,
  34329. this._ssrModule?.lastHMRTimestamp ?? 0
  34330. );
  34331. }
  34332. set lastHMRTimestamp(value) {
  34333. if (this._clientModule) {
  34334. this._clientModule.lastHMRTimestamp = value;
  34335. }
  34336. if (this._ssrModule) {
  34337. this._ssrModule.lastHMRTimestamp = value;
  34338. }
  34339. }
  34340. get lastInvalidationTimestamp() {
  34341. return Math.max(
  34342. this._clientModule?.lastInvalidationTimestamp ?? 0,
  34343. this._ssrModule?.lastInvalidationTimestamp ?? 0
  34344. );
  34345. }
  34346. get invalidationState() {
  34347. return this._clientModule?.invalidationState;
  34348. }
  34349. get ssrInvalidationState() {
  34350. return this._ssrModule?.invalidationState;
  34351. }
  34352. }
  34353. function mapIterator(iterable, transform) {
  34354. return {
  34355. [Symbol.iterator]() {
  34356. return this;
  34357. },
  34358. next() {
  34359. const r = iterable.next();
  34360. return r.done ? r : {
  34361. value: transform(r.value),
  34362. done: false
  34363. };
  34364. }
  34365. };
  34366. }
  34367. class ModuleGraph {
  34368. /** @internal */
  34369. _moduleGraphs;
  34370. /** @internal */
  34371. get _client() {
  34372. return this._moduleGraphs.client();
  34373. }
  34374. /** @internal */
  34375. get _ssr() {
  34376. return this._moduleGraphs.ssr();
  34377. }
  34378. urlToModuleMap;
  34379. idToModuleMap;
  34380. etagToModuleMap;
  34381. fileToModulesMap;
  34382. moduleNodeCache = new DualWeakMap();
  34383. constructor(moduleGraphs) {
  34384. this._moduleGraphs = moduleGraphs;
  34385. const getModuleMapUnion = (prop) => () => {
  34386. if (this._ssr[prop].size === 0) {
  34387. return this._client[prop];
  34388. }
  34389. const map = new Map(this._client[prop]);
  34390. for (const [key, module] of this._ssr[prop]) {
  34391. if (!map.has(key)) {
  34392. map.set(key, module);
  34393. }
  34394. }
  34395. return map;
  34396. };
  34397. this.urlToModuleMap = createBackwardCompatibleModuleMap(
  34398. this,
  34399. "urlToModuleMap",
  34400. getModuleMapUnion("urlToModuleMap")
  34401. );
  34402. this.idToModuleMap = createBackwardCompatibleModuleMap(
  34403. this,
  34404. "idToModuleMap",
  34405. getModuleMapUnion("idToModuleMap")
  34406. );
  34407. this.etagToModuleMap = createBackwardCompatibleModuleMap(
  34408. this,
  34409. "etagToModuleMap",
  34410. () => this._client.etagToModuleMap
  34411. );
  34412. this.fileToModulesMap = createBackwardCompatibleFileToModulesMap(this);
  34413. }
  34414. getModuleById(id) {
  34415. const clientModule = this._client.getModuleById(id);
  34416. const ssrModule = this._ssr.getModuleById(id);
  34417. if (!clientModule && !ssrModule) {
  34418. return;
  34419. }
  34420. return this.getBackwardCompatibleModuleNodeDual(clientModule, ssrModule);
  34421. }
  34422. async getModuleByUrl(url, _ssr) {
  34423. const [clientModule, ssrModule] = await Promise.all([
  34424. this._client.getModuleByUrl(url),
  34425. this._ssr.getModuleByUrl(url)
  34426. ]);
  34427. if (!clientModule && !ssrModule) {
  34428. return;
  34429. }
  34430. return this.getBackwardCompatibleModuleNodeDual(clientModule, ssrModule);
  34431. }
  34432. getModulesByFile(file) {
  34433. const clientModules = this._client.getModulesByFile(file);
  34434. const ssrModules = this._ssr.getModulesByFile(file);
  34435. if (!clientModules && !ssrModules) {
  34436. return void 0;
  34437. }
  34438. const result = /* @__PURE__ */ new Set();
  34439. if (clientModules) {
  34440. for (const mod of clientModules) {
  34441. result.add(this.getBackwardCompatibleBrowserModuleNode(mod));
  34442. }
  34443. }
  34444. if (ssrModules) {
  34445. for (const mod of ssrModules) {
  34446. if (mod.id == null || !this._client.getModuleById(mod.id)) {
  34447. result.add(this.getBackwardCompatibleServerModuleNode(mod));
  34448. }
  34449. }
  34450. }
  34451. return result;
  34452. }
  34453. onFileChange(file) {
  34454. this._client.onFileChange(file);
  34455. this._ssr.onFileChange(file);
  34456. }
  34457. onFileDelete(file) {
  34458. this._client.onFileDelete(file);
  34459. this._ssr.onFileDelete(file);
  34460. }
  34461. /** @internal */
  34462. _getModuleGraph(environment) {
  34463. switch (environment) {
  34464. case "client":
  34465. return this._client;
  34466. case "ssr":
  34467. return this._ssr;
  34468. default:
  34469. throw new Error(`Invalid module node environment ${environment}`);
  34470. }
  34471. }
  34472. invalidateModule(mod, seen = /* @__PURE__ */ new Set(), timestamp = Date.now(), isHmr = false, softInvalidate = false) {
  34473. if (mod._clientModule) {
  34474. this._client.invalidateModule(
  34475. mod._clientModule,
  34476. new Set(
  34477. [...seen].map((mod2) => mod2._clientModule).filter(Boolean)
  34478. ),
  34479. timestamp,
  34480. isHmr,
  34481. softInvalidate
  34482. );
  34483. }
  34484. if (mod._ssrModule) {
  34485. this._ssr.invalidateModule(
  34486. mod._ssrModule,
  34487. new Set(
  34488. [...seen].map((mod2) => mod2._ssrModule).filter(Boolean)
  34489. ),
  34490. timestamp,
  34491. isHmr,
  34492. softInvalidate
  34493. );
  34494. }
  34495. }
  34496. invalidateAll() {
  34497. this._client.invalidateAll();
  34498. this._ssr.invalidateAll();
  34499. }
  34500. /* TODO: It seems there isn't usage of this method in the ecosystem
  34501. Waiting to check if we really need this for backwards compatibility
  34502. async updateModuleInfo(
  34503. module: ModuleNode,
  34504. importedModules: Set<string | ModuleNode>,
  34505. importedBindings: Map<string, Set<string>> | null,
  34506. acceptedModules: Set<string | ModuleNode>,
  34507. acceptedExports: Set<string> | null,
  34508. isSelfAccepting: boolean,
  34509. ssr?: boolean,
  34510. staticImportedUrls?: Set<string>, // internal
  34511. ): Promise<Set<ModuleNode> | undefined> {
  34512. // Not implemented
  34513. }
  34514. */
  34515. async ensureEntryFromUrl(rawUrl, ssr, setIsSelfAccepting = true) {
  34516. const module = await (ssr ? this._ssr : this._client).ensureEntryFromUrl(
  34517. rawUrl,
  34518. setIsSelfAccepting
  34519. );
  34520. return this.getBackwardCompatibleModuleNode(module);
  34521. }
  34522. createFileOnlyEntry(file) {
  34523. const clientModule = this._client.createFileOnlyEntry(file);
  34524. const ssrModule = this._ssr.createFileOnlyEntry(file);
  34525. return this.getBackwardCompatibleModuleNodeDual(clientModule, ssrModule);
  34526. }
  34527. async resolveUrl(url, ssr) {
  34528. return ssr ? this._ssr.resolveUrl(url) : this._client.resolveUrl(url);
  34529. }
  34530. updateModuleTransformResult(mod, result, ssr) {
  34531. const environment = ssr ? "ssr" : "client";
  34532. this._getModuleGraph(environment).updateModuleTransformResult(
  34533. environment === "client" ? mod._clientModule : mod._ssrModule,
  34534. result
  34535. );
  34536. }
  34537. getModuleByEtag(etag) {
  34538. const mod = this._client.etagToModuleMap.get(etag);
  34539. return mod && this.getBackwardCompatibleBrowserModuleNode(mod);
  34540. }
  34541. getBackwardCompatibleBrowserModuleNode(clientModule) {
  34542. return this.getBackwardCompatibleModuleNodeDual(
  34543. clientModule,
  34544. clientModule.id ? this._ssr.getModuleById(clientModule.id) : void 0
  34545. );
  34546. }
  34547. getBackwardCompatibleServerModuleNode(ssrModule) {
  34548. return this.getBackwardCompatibleModuleNodeDual(
  34549. ssrModule.id ? this._client.getModuleById(ssrModule.id) : void 0,
  34550. ssrModule
  34551. );
  34552. }
  34553. getBackwardCompatibleModuleNode(mod) {
  34554. return mod.environment === "client" ? this.getBackwardCompatibleBrowserModuleNode(mod) : this.getBackwardCompatibleServerModuleNode(mod);
  34555. }
  34556. getBackwardCompatibleModuleNodeDual(clientModule, ssrModule) {
  34557. const cached = this.moduleNodeCache.get(clientModule, ssrModule);
  34558. if (cached) {
  34559. return cached;
  34560. }
  34561. const moduleNode = new ModuleNode(this, clientModule, ssrModule);
  34562. this.moduleNodeCache.set(clientModule, ssrModule, moduleNode);
  34563. return moduleNode;
  34564. }
  34565. }
  34566. class DualWeakMap {
  34567. map = /* @__PURE__ */ new WeakMap();
  34568. undefinedKey = {};
  34569. get(key1, key2) {
  34570. const k1 = key1 ?? this.undefinedKey;
  34571. const k2 = key2 ?? this.undefinedKey;
  34572. return this.map.get(k1)?.get(k2);
  34573. }
  34574. set(key1, key2, value) {
  34575. const k1 = key1 ?? this.undefinedKey;
  34576. const k2 = key2 ?? this.undefinedKey;
  34577. if (!this.map.has(k1)) {
  34578. this.map.set(k1, /* @__PURE__ */ new Map());
  34579. }
  34580. const m = this.map.get(k1);
  34581. m.set(k2, value);
  34582. }
  34583. }
  34584. function createBackwardCompatibleModuleSet(moduleGraph, prop, module) {
  34585. return {
  34586. [Symbol.iterator]() {
  34587. return this.keys();
  34588. },
  34589. has(key) {
  34590. if (!key.id) {
  34591. return false;
  34592. }
  34593. const keyModule = moduleGraph._getModuleGraph(module.environment).getModuleById(key.id);
  34594. return keyModule !== void 0 && module[prop].has(keyModule);
  34595. },
  34596. values() {
  34597. return this.keys();
  34598. },
  34599. keys() {
  34600. return mapIterator(
  34601. module[prop].keys(),
  34602. (mod) => moduleGraph.getBackwardCompatibleModuleNode(mod)
  34603. );
  34604. },
  34605. get size() {
  34606. return module[prop].size;
  34607. },
  34608. forEach(callback, thisArg) {
  34609. return module[prop].forEach((mod) => {
  34610. const backwardCompatibleMod = moduleGraph.getBackwardCompatibleModuleNode(mod);
  34611. callback.call(
  34612. thisArg,
  34613. backwardCompatibleMod,
  34614. backwardCompatibleMod,
  34615. this
  34616. );
  34617. });
  34618. }
  34619. // There are several methods missing. We can implement them if downstream
  34620. // projects are relying on them: add, clear, delete, difference, intersection,
  34621. // sDisjointFrom, isSubsetOf, isSupersetOf, symmetricDifference, union
  34622. };
  34623. }
  34624. function createBackwardCompatibleModuleMap(moduleGraph, prop, getModuleMap) {
  34625. return {
  34626. [Symbol.iterator]() {
  34627. return this.entries();
  34628. },
  34629. get(key) {
  34630. const clientModule = moduleGraph._client[prop].get(key);
  34631. const ssrModule = moduleGraph._ssr[prop].get(key);
  34632. if (!clientModule && !ssrModule) {
  34633. return;
  34634. }
  34635. return moduleGraph.getBackwardCompatibleModuleNodeDual(
  34636. clientModule,
  34637. ssrModule
  34638. );
  34639. },
  34640. set(key, mod) {
  34641. const clientModule = mod._clientModule;
  34642. if (clientModule) {
  34643. moduleGraph._client[prop].set(key, clientModule);
  34644. }
  34645. const ssrModule = mod._ssrModule;
  34646. if (ssrModule) {
  34647. moduleGraph._ssr[prop].set(key, ssrModule);
  34648. }
  34649. },
  34650. keys() {
  34651. return getModuleMap().keys();
  34652. },
  34653. values() {
  34654. return mapIterator(
  34655. getModuleMap().values(),
  34656. (mod) => moduleGraph.getBackwardCompatibleModuleNode(mod)
  34657. );
  34658. },
  34659. entries() {
  34660. return mapIterator(getModuleMap().entries(), ([key, mod]) => [
  34661. key,
  34662. moduleGraph.getBackwardCompatibleModuleNode(mod)
  34663. ]);
  34664. },
  34665. get size() {
  34666. return getModuleMap().size;
  34667. },
  34668. forEach(callback, thisArg) {
  34669. return getModuleMap().forEach((mod, key) => {
  34670. const backwardCompatibleMod = moduleGraph.getBackwardCompatibleModuleNode(mod);
  34671. callback.call(thisArg, backwardCompatibleMod, key, this);
  34672. });
  34673. }
  34674. };
  34675. }
  34676. function createBackwardCompatibleFileToModulesMap(moduleGraph) {
  34677. const getFileToModulesMap = () => {
  34678. if (!moduleGraph._ssr.fileToModulesMap.size) {
  34679. return moduleGraph._client.fileToModulesMap;
  34680. }
  34681. const map = new Map(moduleGraph._client.fileToModulesMap);
  34682. for (const [key, modules] of moduleGraph._ssr.fileToModulesMap) {
  34683. const modulesSet = map.get(key);
  34684. if (!modulesSet) {
  34685. map.set(key, modules);
  34686. } else {
  34687. for (const ssrModule of modules) {
  34688. let hasModule = false;
  34689. for (const clientModule of modulesSet) {
  34690. hasModule ||= clientModule.id === ssrModule.id;
  34691. if (hasModule) {
  34692. break;
  34693. }
  34694. }
  34695. if (!hasModule) {
  34696. modulesSet.add(ssrModule);
  34697. }
  34698. }
  34699. }
  34700. }
  34701. return map;
  34702. };
  34703. const getBackwardCompatibleModules = (modules) => new Set(
  34704. [...modules].map(
  34705. (mod) => moduleGraph.getBackwardCompatibleModuleNode(mod)
  34706. )
  34707. );
  34708. return {
  34709. [Symbol.iterator]() {
  34710. return this.entries();
  34711. },
  34712. get(key) {
  34713. const clientModules = moduleGraph._client.fileToModulesMap.get(key);
  34714. const ssrModules = moduleGraph._ssr.fileToModulesMap.get(key);
  34715. if (!clientModules && !ssrModules) {
  34716. return;
  34717. }
  34718. const modules = clientModules ?? /* @__PURE__ */ new Set();
  34719. if (ssrModules) {
  34720. for (const ssrModule of ssrModules) {
  34721. if (ssrModule.id) {
  34722. let found = false;
  34723. for (const mod of modules) {
  34724. found ||= mod.id === ssrModule.id;
  34725. if (found) {
  34726. break;
  34727. }
  34728. }
  34729. if (!found) {
  34730. modules.add(ssrModule);
  34731. }
  34732. }
  34733. }
  34734. }
  34735. return getBackwardCompatibleModules(modules);
  34736. },
  34737. keys() {
  34738. return getFileToModulesMap().keys();
  34739. },
  34740. values() {
  34741. return mapIterator(
  34742. getFileToModulesMap().values(),
  34743. getBackwardCompatibleModules
  34744. );
  34745. },
  34746. entries() {
  34747. return mapIterator(getFileToModulesMap().entries(), ([key, modules]) => [
  34748. key,
  34749. getBackwardCompatibleModules(modules)
  34750. ]);
  34751. },
  34752. get size() {
  34753. return getFileToModulesMap().size;
  34754. },
  34755. forEach(callback, thisArg) {
  34756. return getFileToModulesMap().forEach((modules, key) => {
  34757. callback.call(thisArg, getBackwardCompatibleModules(modules), key, this);
  34758. });
  34759. }
  34760. };
  34761. }
  34762. function notFoundMiddleware() {
  34763. return function vite404Middleware(_, res) {
  34764. res.statusCode = 404;
  34765. res.end();
  34766. };
  34767. }
  34768. const ROOT_FILES = [
  34769. // '.git',
  34770. // https://pnpm.io/workspaces/
  34771. "pnpm-workspace.yaml",
  34772. // https://rushjs.io/pages/advanced/config_files/
  34773. // 'rush.json',
  34774. // https://nx.dev/latest/react/getting-started/nx-setup
  34775. // 'workspace.json',
  34776. // 'nx.json',
  34777. // https://github.com/lerna/lerna#lernajson
  34778. "lerna.json"
  34779. ];
  34780. function hasWorkspacePackageJSON(root) {
  34781. const path = join$1(root, "package.json");
  34782. if (!isFileReadable(path)) {
  34783. return false;
  34784. }
  34785. try {
  34786. const content = JSON.parse(fs__default.readFileSync(path, "utf-8")) || {};
  34787. return !!content.workspaces;
  34788. } catch {
  34789. return false;
  34790. }
  34791. }
  34792. function hasRootFile(root) {
  34793. return ROOT_FILES.some((file) => fs__default.existsSync(join$1(root, file)));
  34794. }
  34795. function hasPackageJSON(root) {
  34796. const path = join$1(root, "package.json");
  34797. return fs__default.existsSync(path);
  34798. }
  34799. function searchForPackageRoot(current, root = current) {
  34800. if (hasPackageJSON(current)) return current;
  34801. const dir = dirname$2(current);
  34802. if (!dir || dir === current) return root;
  34803. return searchForPackageRoot(dir, root);
  34804. }
  34805. function searchForWorkspaceRoot(current, root = searchForPackageRoot(current)) {
  34806. if (hasRootFile(current)) return current;
  34807. if (hasWorkspacePackageJSON(current)) return current;
  34808. const dir = dirname$2(current);
  34809. if (!dir || dir === current) return root;
  34810. return searchForWorkspaceRoot(dir, root);
  34811. }
  34812. function rejectInvalidRequestMiddleware() {
  34813. return function viteRejectInvalidRequestMiddleware(req, res, next) {
  34814. if (req.url?.includes("#")) {
  34815. res.writeHead(400);
  34816. res.end();
  34817. return;
  34818. }
  34819. return next();
  34820. };
  34821. }
  34822. function createServer(inlineConfig = {}) {
  34823. return _createServer(inlineConfig, { listen: true });
  34824. }
  34825. async function _createServer(inlineConfig = {}, options) {
  34826. const config = await resolveConfig(inlineConfig, "serve");
  34827. const initPublicFilesPromise = initPublicFiles(config);
  34828. const { root, server: serverConfig } = config;
  34829. const httpsOptions = await resolveHttpsConfig(config.server.https);
  34830. const { middlewareMode } = serverConfig;
  34831. const resolvedOutDirs = getResolvedOutDirs(
  34832. config.root,
  34833. config.build.outDir,
  34834. config.build.rollupOptions.output
  34835. );
  34836. const emptyOutDir = resolveEmptyOutDir(
  34837. config.build.emptyOutDir,
  34838. config.root,
  34839. resolvedOutDirs
  34840. );
  34841. const resolvedWatchOptions = resolveChokidarOptions(
  34842. {
  34843. disableGlobbing: true,
  34844. ...serverConfig.watch
  34845. },
  34846. resolvedOutDirs,
  34847. emptyOutDir,
  34848. config.cacheDir
  34849. );
  34850. const middlewares = connect$1();
  34851. const httpServer = middlewareMode ? null : await resolveHttpServer(serverConfig, middlewares, httpsOptions);
  34852. const ws = createWebSocketServer(httpServer, config, httpsOptions);
  34853. const publicFiles = await initPublicFilesPromise;
  34854. const { publicDir } = config;
  34855. if (httpServer) {
  34856. setClientErrorHandler(httpServer, config.logger);
  34857. }
  34858. const watchEnabled = serverConfig.watch !== null;
  34859. const watcher = watchEnabled ? chokidar.watch(
  34860. // config file dependencies and env file might be outside of root
  34861. [
  34862. root,
  34863. ...config.configFileDependencies,
  34864. ...getEnvFilesForMode(config.mode, config.envDir),
  34865. // Watch the public directory explicitly because it might be outside
  34866. // of the root directory.
  34867. ...publicDir && publicFiles ? [publicDir] : []
  34868. ],
  34869. resolvedWatchOptions
  34870. ) : createNoopWatcher(resolvedWatchOptions);
  34871. const environments = {};
  34872. for (const [name, environmentOptions] of Object.entries(
  34873. config.environments
  34874. )) {
  34875. environments[name] = await environmentOptions.dev.createEnvironment(
  34876. name,
  34877. config,
  34878. {
  34879. ws
  34880. }
  34881. );
  34882. }
  34883. for (const environment of Object.values(environments)) {
  34884. const previousInstance = options.previousEnvironments?.[environment.name];
  34885. await environment.init({ watcher, previousInstance });
  34886. }
  34887. let moduleGraph = new ModuleGraph({
  34888. client: () => environments.client.moduleGraph,
  34889. ssr: () => environments.ssr.moduleGraph
  34890. });
  34891. const pluginContainer = createPluginContainer(environments);
  34892. const closeHttpServer = createServerCloseFn(httpServer);
  34893. const devHtmlTransformFn = createDevHtmlTransformFn(config);
  34894. let closeServerPromise;
  34895. const closeServer = async () => {
  34896. if (!middlewareMode) {
  34897. teardownSIGTERMListener(closeServerAndExit);
  34898. }
  34899. await Promise.allSettled([
  34900. watcher.close(),
  34901. ws.close(),
  34902. Promise.allSettled(
  34903. Object.values(server.environments).map(
  34904. (environment) => environment.close()
  34905. )
  34906. ),
  34907. closeHttpServer(),
  34908. server._ssrCompatModuleRunner?.close()
  34909. ]);
  34910. server.resolvedUrls = null;
  34911. server._ssrCompatModuleRunner = void 0;
  34912. };
  34913. let server = {
  34914. config,
  34915. middlewares,
  34916. httpServer,
  34917. watcher,
  34918. ws,
  34919. hot: createDeprecatedHotBroadcaster(ws),
  34920. environments,
  34921. pluginContainer,
  34922. get moduleGraph() {
  34923. warnFutureDeprecation(config, "removeServerModuleGraph");
  34924. return moduleGraph;
  34925. },
  34926. set moduleGraph(graph) {
  34927. moduleGraph = graph;
  34928. },
  34929. resolvedUrls: null,
  34930. // will be set on listen
  34931. ssrTransform(code, inMap, url, originalCode = code) {
  34932. return ssrTransform(code, inMap, url, originalCode, {
  34933. json: {
  34934. stringify: config.json.stringify === true && config.json.namedExports !== true
  34935. }
  34936. });
  34937. },
  34938. // environment.transformRequest and .warmupRequest don't take an options param for now,
  34939. // so the logic and error handling needs to be duplicated here.
  34940. // The only param in options that could be important is `html`, but we may remove it as
  34941. // that is part of the internal control flow for the vite dev server to be able to bail
  34942. // out and do the html fallback
  34943. transformRequest(url, options2) {
  34944. warnFutureDeprecation(
  34945. config,
  34946. "removeServerTransformRequest",
  34947. "server.transformRequest() is deprecated. Use environment.transformRequest() instead."
  34948. );
  34949. const environment = server.environments[options2?.ssr ? "ssr" : "client"];
  34950. return transformRequest(environment, url, options2);
  34951. },
  34952. async warmupRequest(url, options2) {
  34953. try {
  34954. const environment = server.environments[options2?.ssr ? "ssr" : "client"];
  34955. await transformRequest(environment, url, options2);
  34956. } catch (e) {
  34957. if (e?.code === ERR_OUTDATED_OPTIMIZED_DEP || e?.code === ERR_CLOSED_SERVER) {
  34958. return;
  34959. }
  34960. server.config.logger.error(
  34961. buildErrorMessage(e, [`Pre-transform error: ${e.message}`], false),
  34962. {
  34963. error: e,
  34964. timestamp: true
  34965. }
  34966. );
  34967. }
  34968. },
  34969. transformIndexHtml(url, html, originalUrl) {
  34970. return devHtmlTransformFn(server, url, html, originalUrl);
  34971. },
  34972. async ssrLoadModule(url, opts) {
  34973. warnFutureDeprecation(config, "removeSsrLoadModule");
  34974. return ssrLoadModule(url, server, opts?.fixStacktrace);
  34975. },
  34976. ssrFixStacktrace(e) {
  34977. ssrFixStacktrace(e, server.environments.ssr.moduleGraph);
  34978. },
  34979. ssrRewriteStacktrace(stack) {
  34980. return ssrRewriteStacktrace(stack, server.environments.ssr.moduleGraph);
  34981. },
  34982. async reloadModule(module) {
  34983. if (serverConfig.hmr !== false && module.file) {
  34984. const environmentModule = module._clientModule ?? module._ssrModule;
  34985. updateModules(
  34986. environments[environmentModule.environment],
  34987. module.file,
  34988. [environmentModule],
  34989. Date.now()
  34990. );
  34991. }
  34992. },
  34993. async listen(port, isRestart) {
  34994. await startServer(server, port);
  34995. if (httpServer) {
  34996. server.resolvedUrls = await resolveServerUrls(
  34997. httpServer,
  34998. config.server,
  34999. httpsOptions,
  35000. config
  35001. );
  35002. if (!isRestart && config.server.open) server.openBrowser();
  35003. }
  35004. return server;
  35005. },
  35006. openBrowser() {
  35007. const options2 = server.config.server;
  35008. const url = getServerUrlByHost(server.resolvedUrls, options2.host);
  35009. if (url) {
  35010. const path2 = typeof options2.open === "string" ? new URL(options2.open, url).href : url;
  35011. if (server.config.server.preTransformRequests) {
  35012. setTimeout(() => {
  35013. const getMethod = path2.startsWith("https:") ? get$1 : get$2;
  35014. getMethod(
  35015. path2,
  35016. {
  35017. headers: {
  35018. // Allow the history middleware to redirect to /index.html
  35019. Accept: "text/html"
  35020. }
  35021. },
  35022. (res) => {
  35023. res.on("end", () => {
  35024. });
  35025. }
  35026. ).on("error", () => {
  35027. }).end();
  35028. }, 0);
  35029. }
  35030. openBrowser(path2, true, server.config.logger);
  35031. } else {
  35032. server.config.logger.warn("No URL available to open in browser");
  35033. }
  35034. },
  35035. async close() {
  35036. if (!closeServerPromise) {
  35037. closeServerPromise = closeServer();
  35038. }
  35039. return closeServerPromise;
  35040. },
  35041. printUrls() {
  35042. if (server.resolvedUrls) {
  35043. printServerUrls(
  35044. server.resolvedUrls,
  35045. serverConfig.host,
  35046. config.logger.info
  35047. );
  35048. } else if (middlewareMode) {
  35049. throw new Error("cannot print server URLs in middleware mode.");
  35050. } else {
  35051. throw new Error(
  35052. "cannot print server URLs before server.listen is called."
  35053. );
  35054. }
  35055. },
  35056. bindCLIShortcuts(options2) {
  35057. bindCLIShortcuts(server, options2);
  35058. },
  35059. async restart(forceOptimize) {
  35060. if (!server._restartPromise) {
  35061. server._forceOptimizeOnRestart = !!forceOptimize;
  35062. server._restartPromise = restartServer(server).finally(() => {
  35063. server._restartPromise = null;
  35064. server._forceOptimizeOnRestart = false;
  35065. });
  35066. }
  35067. return server._restartPromise;
  35068. },
  35069. waitForRequestsIdle(ignoredId) {
  35070. return environments.client.waitForRequestsIdle(ignoredId);
  35071. },
  35072. _setInternalServer(_server) {
  35073. server = _server;
  35074. },
  35075. _importGlobMap: /* @__PURE__ */ new Map(),
  35076. _restartPromise: null,
  35077. _forceOptimizeOnRestart: false,
  35078. _shortcutsOptions: void 0
  35079. };
  35080. const reflexServer = new Proxy(server, {
  35081. get: (_, property) => {
  35082. return server[property];
  35083. },
  35084. set: (_, property, value) => {
  35085. server[property] = value;
  35086. return true;
  35087. }
  35088. });
  35089. const closeServerAndExit = async (_, exitCode) => {
  35090. try {
  35091. await server.close();
  35092. } finally {
  35093. process.exitCode ??= exitCode ? 128 + exitCode : void 0;
  35094. process.exit();
  35095. }
  35096. };
  35097. if (!middlewareMode) {
  35098. setupSIGTERMListener(closeServerAndExit);
  35099. }
  35100. const onHMRUpdate = async (type, file) => {
  35101. if (serverConfig.hmr !== false) {
  35102. await handleHMRUpdate(type, file, server);
  35103. }
  35104. };
  35105. const onFileAddUnlink = async (file, isUnlink) => {
  35106. file = normalizePath$3(file);
  35107. reloadOnTsconfigChange(server, file);
  35108. await pluginContainer.watchChange(file, {
  35109. event: isUnlink ? "delete" : "create"
  35110. });
  35111. if (publicDir && publicFiles) {
  35112. if (file.startsWith(publicDir)) {
  35113. const path2 = file.slice(publicDir.length);
  35114. publicFiles[isUnlink ? "delete" : "add"](path2);
  35115. if (!isUnlink) {
  35116. const clientModuleGraph = server.environments.client.moduleGraph;
  35117. const moduleWithSamePath = await clientModuleGraph.getModuleByUrl(path2);
  35118. const etag = moduleWithSamePath?.transformResult?.etag;
  35119. if (etag) {
  35120. clientModuleGraph.etagToModuleMap.delete(etag);
  35121. }
  35122. }
  35123. }
  35124. }
  35125. if (isUnlink) {
  35126. for (const environment of Object.values(server.environments)) {
  35127. environment.moduleGraph.onFileDelete(file);
  35128. }
  35129. }
  35130. await onHMRUpdate(isUnlink ? "delete" : "create", file);
  35131. };
  35132. watcher.on("change", async (file) => {
  35133. file = normalizePath$3(file);
  35134. reloadOnTsconfigChange(server, file);
  35135. await pluginContainer.watchChange(file, { event: "update" });
  35136. for (const environment of Object.values(server.environments)) {
  35137. environment.moduleGraph.onFileChange(file);
  35138. }
  35139. await onHMRUpdate("update", file);
  35140. });
  35141. watcher.on("add", (file) => {
  35142. onFileAddUnlink(file, false);
  35143. });
  35144. watcher.on("unlink", (file) => {
  35145. onFileAddUnlink(file, true);
  35146. });
  35147. if (!middlewareMode && httpServer) {
  35148. httpServer.once("listening", () => {
  35149. serverConfig.port = httpServer.address().port;
  35150. });
  35151. }
  35152. const postHooks = [];
  35153. for (const hook of config.getSortedPluginHooks("configureServer")) {
  35154. postHooks.push(await hook(reflexServer));
  35155. }
  35156. if (process.env.DEBUG) {
  35157. middlewares.use(timeMiddleware(root));
  35158. }
  35159. middlewares.use(rejectInvalidRequestMiddleware());
  35160. const { cors } = serverConfig;
  35161. if (cors !== false) {
  35162. middlewares.use(corsMiddleware(typeof cors === "boolean" ? {} : cors));
  35163. }
  35164. const { allowedHosts } = serverConfig;
  35165. if (allowedHosts !== true && !serverConfig.https) {
  35166. middlewares.use(hostCheckMiddleware(config, false));
  35167. }
  35168. middlewares.use(cachedTransformMiddleware(server));
  35169. const { proxy } = serverConfig;
  35170. if (proxy) {
  35171. const middlewareServer = (isObject$1(middlewareMode) ? middlewareMode.server : null) || httpServer;
  35172. middlewares.use(proxyMiddleware(middlewareServer, proxy, config));
  35173. }
  35174. if (config.base !== "/") {
  35175. middlewares.use(baseMiddleware(config.rawBase, !!middlewareMode));
  35176. }
  35177. middlewares.use("/__open-in-editor", launchEditorMiddleware$1());
  35178. middlewares.use(function viteHMRPingMiddleware(req, res, next) {
  35179. if (req.headers["accept"] === "text/x-vite-ping") {
  35180. res.writeHead(204).end();
  35181. } else {
  35182. next();
  35183. }
  35184. });
  35185. if (publicDir) {
  35186. middlewares.use(servePublicMiddleware(server, publicFiles));
  35187. }
  35188. middlewares.use(transformMiddleware(server));
  35189. middlewares.use(serveRawFsMiddleware(server));
  35190. middlewares.use(serveStaticMiddleware(server));
  35191. if (config.appType === "spa" || config.appType === "mpa") {
  35192. middlewares.use(htmlFallbackMiddleware(root, config.appType === "spa"));
  35193. }
  35194. postHooks.forEach((fn) => fn && fn());
  35195. if (config.appType === "spa" || config.appType === "mpa") {
  35196. middlewares.use(indexHtmlMiddleware(root, server));
  35197. middlewares.use(notFoundMiddleware());
  35198. }
  35199. middlewares.use(errorMiddleware(server, !!middlewareMode));
  35200. let initingServer;
  35201. let serverInited = false;
  35202. const initServer = async (onListen) => {
  35203. if (serverInited) return;
  35204. if (initingServer) return initingServer;
  35205. initingServer = async function() {
  35206. await environments.client.pluginContainer.buildStart();
  35207. if (onListen || options.listen) {
  35208. await Promise.all(
  35209. Object.values(environments).map((e) => e.listen(server))
  35210. );
  35211. }
  35212. initingServer = void 0;
  35213. serverInited = true;
  35214. }();
  35215. return initingServer;
  35216. };
  35217. if (!middlewareMode && httpServer) {
  35218. const listen = httpServer.listen.bind(httpServer);
  35219. httpServer.listen = async (port, ...args) => {
  35220. try {
  35221. await initServer(true);
  35222. } catch (e) {
  35223. httpServer.emit("error", e);
  35224. return;
  35225. }
  35226. return listen(port, ...args);
  35227. };
  35228. } else {
  35229. await initServer(false);
  35230. }
  35231. return server;
  35232. }
  35233. async function startServer(server, inlinePort) {
  35234. const httpServer = server.httpServer;
  35235. if (!httpServer) {
  35236. throw new Error("Cannot call server.listen in middleware mode.");
  35237. }
  35238. const options = server.config.server;
  35239. const hostname = await resolveHostname(options.host);
  35240. const configPort = inlinePort ?? options.port;
  35241. const port = (!configPort || configPort === server._configServerPort ? server._currentServerPort : configPort) ?? DEFAULT_DEV_PORT;
  35242. server._configServerPort = configPort;
  35243. const serverPort = await httpServerStart(httpServer, {
  35244. port,
  35245. strictPort: options.strictPort,
  35246. host: hostname.host,
  35247. logger: server.config.logger
  35248. });
  35249. server._currentServerPort = serverPort;
  35250. }
  35251. function createServerCloseFn(server) {
  35252. if (!server) {
  35253. return () => Promise.resolve();
  35254. }
  35255. let hasListened = false;
  35256. const openSockets = /* @__PURE__ */ new Set();
  35257. server.on("connection", (socket) => {
  35258. openSockets.add(socket);
  35259. socket.on("close", () => {
  35260. openSockets.delete(socket);
  35261. });
  35262. });
  35263. server.once("listening", () => {
  35264. hasListened = true;
  35265. });
  35266. return () => new Promise((resolve, reject) => {
  35267. openSockets.forEach((s) => s.destroy());
  35268. if (hasListened) {
  35269. server.close((err) => {
  35270. if (err) {
  35271. reject(err);
  35272. } else {
  35273. resolve();
  35274. }
  35275. });
  35276. } else {
  35277. resolve();
  35278. }
  35279. });
  35280. }
  35281. function resolvedAllowDir(root, dir) {
  35282. return normalizePath$3(path$b.resolve(root, dir));
  35283. }
  35284. const serverConfigDefaults = Object.freeze({
  35285. port: DEFAULT_DEV_PORT,
  35286. strictPort: false,
  35287. host: "localhost",
  35288. allowedHosts: [],
  35289. https: void 0,
  35290. open: false,
  35291. proxy: void 0,
  35292. cors: { origin: defaultAllowedOrigins },
  35293. headers: {},
  35294. // hmr
  35295. // ws
  35296. warmup: {
  35297. clientFiles: [],
  35298. ssrFiles: []
  35299. },
  35300. // watch
  35301. middlewareMode: false,
  35302. fs: {
  35303. strict: true,
  35304. // allow
  35305. deny: [".env", ".env.*", "*.{crt,pem}", "**/.git/**"]
  35306. },
  35307. // origin
  35308. preTransformRequests: true,
  35309. // sourcemapIgnoreList
  35310. perEnvironmentStartEndDuringDev: false
  35311. // hotUpdateEnvironments
  35312. });
  35313. function resolveServerOptions(root, raw, logger) {
  35314. const _server = mergeWithDefaults(
  35315. {
  35316. ...serverConfigDefaults,
  35317. host: void 0,
  35318. // do not set here to detect whether host is set or not
  35319. sourcemapIgnoreList: isInNodeModules$1
  35320. },
  35321. raw ?? {}
  35322. );
  35323. const server = {
  35324. ..._server,
  35325. fs: {
  35326. ..._server.fs,
  35327. // run searchForWorkspaceRoot only if needed
  35328. allow: raw?.fs?.allow ?? [searchForWorkspaceRoot(root)]
  35329. },
  35330. sourcemapIgnoreList: _server.sourcemapIgnoreList === false ? () => false : _server.sourcemapIgnoreList
  35331. };
  35332. let allowDirs = server.fs.allow;
  35333. if (process.versions.pnp) {
  35334. const cwd = searchForPackageRoot(root);
  35335. try {
  35336. const enableGlobalCache = execSync("yarn config get enableGlobalCache", { cwd }).toString().trim() === "true";
  35337. const yarnCacheDir = execSync(
  35338. `yarn config get ${enableGlobalCache ? "globalFolder" : "cacheFolder"}`,
  35339. { cwd }
  35340. ).toString().trim();
  35341. allowDirs.push(yarnCacheDir);
  35342. } catch (e) {
  35343. logger.warn(`Get yarn cache dir error: ${e.message}`, {
  35344. timestamp: true
  35345. });
  35346. }
  35347. }
  35348. allowDirs = allowDirs.map((i) => resolvedAllowDir(root, i));
  35349. const resolvedClientDir = resolvedAllowDir(root, CLIENT_DIR);
  35350. if (!allowDirs.some((dir) => isParentDirectory(dir, resolvedClientDir))) {
  35351. allowDirs.push(resolvedClientDir);
  35352. }
  35353. server.fs.allow = allowDirs;
  35354. if (server.origin?.endsWith("/")) {
  35355. server.origin = server.origin.slice(0, -1);
  35356. logger.warn(
  35357. colors$1.yellow(
  35358. `${colors$1.bold("(!)")} server.origin should not end with "/". Using "${server.origin}" instead.`
  35359. )
  35360. );
  35361. }
  35362. if (process.env.__VITE_ADDITIONAL_SERVER_ALLOWED_HOSTS && Array.isArray(server.allowedHosts)) {
  35363. const additionalHost = process.env.__VITE_ADDITIONAL_SERVER_ALLOWED_HOSTS;
  35364. server.allowedHosts = [...server.allowedHosts, additionalHost];
  35365. }
  35366. return server;
  35367. }
  35368. async function restartServer(server) {
  35369. global.__vite_start_time = performance$1.now();
  35370. const shortcutsOptions = server._shortcutsOptions;
  35371. let inlineConfig = server.config.inlineConfig;
  35372. if (server._forceOptimizeOnRestart) {
  35373. inlineConfig = mergeConfig(inlineConfig, {
  35374. forceOptimizeDeps: true
  35375. });
  35376. }
  35377. {
  35378. let newServer = null;
  35379. try {
  35380. newServer = await _createServer(inlineConfig, {
  35381. listen: false,
  35382. previousEnvironments: server.environments
  35383. });
  35384. } catch (err) {
  35385. server.config.logger.error(err.message, {
  35386. timestamp: true
  35387. });
  35388. server.config.logger.error("server restart failed", { timestamp: true });
  35389. return;
  35390. }
  35391. await server.close();
  35392. const middlewares = server.middlewares;
  35393. newServer._configServerPort = server._configServerPort;
  35394. newServer._currentServerPort = server._currentServerPort;
  35395. Object.assign(server, newServer);
  35396. middlewares.stack = newServer.middlewares.stack;
  35397. server.middlewares = middlewares;
  35398. newServer._setInternalServer(server);
  35399. }
  35400. const {
  35401. logger,
  35402. server: { port, middlewareMode }
  35403. } = server.config;
  35404. if (!middlewareMode) {
  35405. await server.listen(port, true);
  35406. } else {
  35407. await Promise.all(
  35408. Object.values(server.environments).map((e) => e.listen(server))
  35409. );
  35410. }
  35411. logger.info("server restarted.", { timestamp: true });
  35412. if (shortcutsOptions) {
  35413. shortcutsOptions.print = false;
  35414. bindCLIShortcuts(server, shortcutsOptions);
  35415. }
  35416. }
  35417. async function restartServerWithUrls(server) {
  35418. if (server.config.server.middlewareMode) {
  35419. await server.restart();
  35420. return;
  35421. }
  35422. const { port: prevPort, host: prevHost } = server.config.server;
  35423. const prevUrls = server.resolvedUrls;
  35424. await server.restart();
  35425. const {
  35426. logger,
  35427. server: { port, host }
  35428. } = server.config;
  35429. if ((port ?? DEFAULT_DEV_PORT) !== (prevPort ?? DEFAULT_DEV_PORT) || host !== prevHost || diffDnsOrderChange(prevUrls, server.resolvedUrls)) {
  35430. logger.info("");
  35431. server.printUrls();
  35432. }
  35433. }
  35434. var index = {
  35435. __proto__: null,
  35436. _createServer: _createServer,
  35437. createServer: createServer,
  35438. createServerCloseFn: createServerCloseFn,
  35439. resolveServerOptions: resolveServerOptions,
  35440. restartServerWithUrls: restartServerWithUrls,
  35441. serverConfigDefaults: serverConfigDefaults
  35442. };
  35443. const debugHmr = createDebugger("vite:hmr");
  35444. const whitespaceRE = /\s/;
  35445. const normalizedClientDir = normalizePath$3(CLIENT_DIR);
  35446. function getShortName(file, root) {
  35447. return file.startsWith(withTrailingSlash(root)) ? path$b.posix.relative(root, file) : file;
  35448. }
  35449. const normalizeHotChannel = (channel, enableHmr, normalizeClient = true) => {
  35450. const normalizedListenerMap = /* @__PURE__ */ new WeakMap();
  35451. const listenersForEvents = /* @__PURE__ */ new Map();
  35452. let invokeHandlers;
  35453. let listenerForInvokeHandler;
  35454. const handleInvoke = async (payload) => {
  35455. if (!invokeHandlers) {
  35456. return {
  35457. error: {
  35458. name: "TransportError",
  35459. message: "invokeHandlers is not set",
  35460. stack: new Error().stack
  35461. }
  35462. };
  35463. }
  35464. const data = payload.data;
  35465. const { name, data: args } = data;
  35466. try {
  35467. const invokeHandler = invokeHandlers[name];
  35468. const result = await invokeHandler(...args);
  35469. return { result };
  35470. } catch (error2) {
  35471. return {
  35472. error: {
  35473. name: error2.name,
  35474. message: error2.message,
  35475. stack: error2.stack,
  35476. ...error2
  35477. // preserve enumerable properties such as RollupError.loc, frame, plugin
  35478. }
  35479. };
  35480. }
  35481. };
  35482. return {
  35483. ...channel,
  35484. on: (event, fn) => {
  35485. if (event === "connection" || !normalizeClient) {
  35486. channel.on?.(event, fn);
  35487. return;
  35488. }
  35489. const listenerWithNormalizedClient = (data, client) => {
  35490. const normalizedClient = {
  35491. send: (...args) => {
  35492. let payload;
  35493. if (typeof args[0] === "string") {
  35494. payload = {
  35495. type: "custom",
  35496. event: args[0],
  35497. data: args[1]
  35498. };
  35499. } else {
  35500. payload = args[0];
  35501. }
  35502. client.send(payload);
  35503. }
  35504. };
  35505. fn(data, normalizedClient);
  35506. };
  35507. normalizedListenerMap.set(fn, listenerWithNormalizedClient);
  35508. channel.on?.(event, listenerWithNormalizedClient);
  35509. if (!listenersForEvents.has(event)) {
  35510. listenersForEvents.set(event, /* @__PURE__ */ new Set());
  35511. }
  35512. listenersForEvents.get(event).add(listenerWithNormalizedClient);
  35513. },
  35514. off: (event, fn) => {
  35515. if (event === "connection" || !normalizeClient) {
  35516. channel.off?.(event, fn);
  35517. return;
  35518. }
  35519. const normalizedListener = normalizedListenerMap.get(fn);
  35520. if (normalizedListener) {
  35521. channel.off?.(event, normalizedListener);
  35522. listenersForEvents.get(event)?.delete(normalizedListener);
  35523. }
  35524. },
  35525. setInvokeHandler(_invokeHandlers) {
  35526. invokeHandlers = _invokeHandlers;
  35527. if (!_invokeHandlers) {
  35528. if (listenerForInvokeHandler) {
  35529. channel.off?.("vite:invoke", listenerForInvokeHandler);
  35530. }
  35531. return;
  35532. }
  35533. listenerForInvokeHandler = async (payload, client) => {
  35534. const responseInvoke = payload.id.replace("send", "response");
  35535. client.send({
  35536. type: "custom",
  35537. event: "vite:invoke",
  35538. data: {
  35539. name: payload.name,
  35540. id: responseInvoke,
  35541. data: await handleInvoke({
  35542. data: payload
  35543. })
  35544. }
  35545. });
  35546. };
  35547. channel.on?.("vite:invoke", listenerForInvokeHandler);
  35548. },
  35549. handleInvoke,
  35550. send: (...args) => {
  35551. let payload;
  35552. if (typeof args[0] === "string") {
  35553. payload = {
  35554. type: "custom",
  35555. event: args[0],
  35556. data: args[1]
  35557. };
  35558. } else {
  35559. payload = args[0];
  35560. }
  35561. if (enableHmr || payload.type === "connected" || payload.type === "ping" || payload.type === "custom" || payload.type === "error") {
  35562. channel.send?.(payload);
  35563. }
  35564. },
  35565. listen() {
  35566. return channel.listen?.();
  35567. },
  35568. close() {
  35569. return channel.close?.();
  35570. }
  35571. };
  35572. };
  35573. function getSortedPluginsByHotUpdateHook(plugins) {
  35574. const sortedPlugins = [];
  35575. let pre = 0, normal = 0, post = 0;
  35576. for (const plugin of plugins) {
  35577. const hook = plugin["hotUpdate"] ?? plugin["handleHotUpdate"];
  35578. if (hook) {
  35579. if (typeof hook === "object") {
  35580. if (hook.order === "pre") {
  35581. sortedPlugins.splice(pre++, 0, plugin);
  35582. continue;
  35583. }
  35584. if (hook.order === "post") {
  35585. sortedPlugins.splice(pre + normal + post++, 0, plugin);
  35586. continue;
  35587. }
  35588. }
  35589. sortedPlugins.splice(pre + normal++, 0, plugin);
  35590. }
  35591. }
  35592. return sortedPlugins;
  35593. }
  35594. const sortedHotUpdatePluginsCache = /* @__PURE__ */ new WeakMap();
  35595. function getSortedHotUpdatePlugins(environment) {
  35596. let sortedPlugins = sortedHotUpdatePluginsCache.get(environment);
  35597. if (!sortedPlugins) {
  35598. sortedPlugins = getSortedPluginsByHotUpdateHook(environment.plugins);
  35599. sortedHotUpdatePluginsCache.set(environment, sortedPlugins);
  35600. }
  35601. return sortedPlugins;
  35602. }
  35603. async function handleHMRUpdate(type, file, server) {
  35604. const { config } = server;
  35605. const mixedModuleGraph = ignoreDeprecationWarnings(() => server.moduleGraph);
  35606. const environments = Object.values(server.environments);
  35607. const shortFile = getShortName(file, config.root);
  35608. const isConfig = file === config.configFile;
  35609. const isConfigDependency = config.configFileDependencies.some(
  35610. (name) => file === name
  35611. );
  35612. const isEnv = config.envDir !== false && getEnvFilesForMode(config.mode, config.envDir).includes(file);
  35613. if (isConfig || isConfigDependency || isEnv) {
  35614. debugHmr?.(`[config change] ${colors$1.dim(shortFile)}`);
  35615. config.logger.info(
  35616. colors$1.green(
  35617. `${normalizePath$3(
  35618. path$b.relative(process.cwd(), file)
  35619. )} changed, restarting server...`
  35620. ),
  35621. { clear: true, timestamp: true }
  35622. );
  35623. try {
  35624. await restartServerWithUrls(server);
  35625. } catch (e) {
  35626. config.logger.error(colors$1.red(e));
  35627. }
  35628. return;
  35629. }
  35630. debugHmr?.(`[file change] ${colors$1.dim(shortFile)}`);
  35631. if (file.startsWith(withTrailingSlash(normalizedClientDir))) {
  35632. environments.forEach(
  35633. ({ hot }) => hot.send({
  35634. type: "full-reload",
  35635. path: "*",
  35636. triggeredBy: path$b.resolve(config.root, file)
  35637. })
  35638. );
  35639. return;
  35640. }
  35641. const timestamp = Date.now();
  35642. const contextMeta = {
  35643. type,
  35644. file,
  35645. timestamp,
  35646. read: () => readModifiedFile(file),
  35647. server
  35648. };
  35649. const hotMap = /* @__PURE__ */ new Map();
  35650. for (const environment of Object.values(server.environments)) {
  35651. const mods = new Set(environment.moduleGraph.getModulesByFile(file));
  35652. if (type === "create") {
  35653. for (const mod of environment.moduleGraph._hasResolveFailedErrorModules) {
  35654. mods.add(mod);
  35655. }
  35656. }
  35657. const options = {
  35658. ...contextMeta,
  35659. modules: [...mods],
  35660. // later on hotUpdate will be called for each runtime with a new HotUpdateOptions
  35661. environment
  35662. };
  35663. hotMap.set(environment, { options });
  35664. }
  35665. const mixedMods = new Set(mixedModuleGraph.getModulesByFile(file));
  35666. const mixedHmrContext = {
  35667. ...contextMeta,
  35668. modules: [...mixedMods]
  35669. };
  35670. const clientEnvironment = server.environments.client;
  35671. const ssrEnvironment = server.environments.ssr;
  35672. const clientContext = { environment: clientEnvironment };
  35673. const clientHotUpdateOptions = hotMap.get(clientEnvironment).options;
  35674. const ssrHotUpdateOptions = hotMap.get(ssrEnvironment)?.options;
  35675. try {
  35676. for (const plugin of getSortedHotUpdatePlugins(
  35677. server.environments.client
  35678. )) {
  35679. if (plugin.hotUpdate) {
  35680. const filteredModules = await getHookHandler(plugin.hotUpdate).call(
  35681. clientContext,
  35682. clientHotUpdateOptions
  35683. );
  35684. if (filteredModules) {
  35685. clientHotUpdateOptions.modules = filteredModules;
  35686. mixedHmrContext.modules = mixedHmrContext.modules.filter(
  35687. (mixedMod) => filteredModules.some((mod) => mixedMod.id === mod.id) || ssrHotUpdateOptions?.modules.some(
  35688. (ssrMod) => ssrMod.id === mixedMod.id
  35689. )
  35690. );
  35691. mixedHmrContext.modules.push(
  35692. ...filteredModules.filter(
  35693. (mod) => !mixedHmrContext.modules.some(
  35694. (mixedMod) => mixedMod.id === mod.id
  35695. )
  35696. ).map(
  35697. (mod) => mixedModuleGraph.getBackwardCompatibleModuleNode(mod)
  35698. )
  35699. );
  35700. }
  35701. } else if (type === "update") {
  35702. warnFutureDeprecation(
  35703. config,
  35704. "removePluginHookHandleHotUpdate",
  35705. `Used in plugin "${plugin.name}".`,
  35706. false
  35707. );
  35708. const filteredModules = await getHookHandler(plugin.handleHotUpdate)(
  35709. mixedHmrContext
  35710. );
  35711. if (filteredModules) {
  35712. mixedHmrContext.modules = filteredModules;
  35713. clientHotUpdateOptions.modules = clientHotUpdateOptions.modules.filter(
  35714. (mod) => filteredModules.some((mixedMod) => mod.id === mixedMod.id)
  35715. );
  35716. clientHotUpdateOptions.modules.push(
  35717. ...filteredModules.filter(
  35718. (mixedMod) => !clientHotUpdateOptions.modules.some(
  35719. (mod) => mod.id === mixedMod.id
  35720. )
  35721. ).map((mixedMod) => mixedMod._clientModule).filter(Boolean)
  35722. );
  35723. if (ssrHotUpdateOptions) {
  35724. ssrHotUpdateOptions.modules = ssrHotUpdateOptions.modules.filter(
  35725. (mod) => filteredModules.some((mixedMod) => mod.id === mixedMod.id)
  35726. );
  35727. ssrHotUpdateOptions.modules.push(
  35728. ...filteredModules.filter(
  35729. (mixedMod) => !ssrHotUpdateOptions.modules.some(
  35730. (mod) => mod.id === mixedMod.id
  35731. )
  35732. ).map((mixedMod) => mixedMod._ssrModule).filter(Boolean)
  35733. );
  35734. }
  35735. }
  35736. }
  35737. }
  35738. } catch (error2) {
  35739. hotMap.get(server.environments.client).error = error2;
  35740. }
  35741. for (const environment of Object.values(server.environments)) {
  35742. if (environment.name === "client") continue;
  35743. const hot = hotMap.get(environment);
  35744. const environmentThis = { environment };
  35745. try {
  35746. for (const plugin of getSortedHotUpdatePlugins(environment)) {
  35747. if (plugin.hotUpdate) {
  35748. const filteredModules = await getHookHandler(plugin.hotUpdate).call(
  35749. environmentThis,
  35750. hot.options
  35751. );
  35752. if (filteredModules) {
  35753. hot.options.modules = filteredModules;
  35754. }
  35755. }
  35756. }
  35757. } catch (error2) {
  35758. hot.error = error2;
  35759. }
  35760. }
  35761. async function hmr(environment) {
  35762. try {
  35763. const { options, error: error2 } = hotMap.get(environment);
  35764. if (error2) {
  35765. throw error2;
  35766. }
  35767. if (!options.modules.length) {
  35768. if (file.endsWith(".html") && environment.name === "client") {
  35769. environment.logger.info(
  35770. colors$1.green(`page reload `) + colors$1.dim(shortFile),
  35771. {
  35772. clear: true,
  35773. timestamp: true
  35774. }
  35775. );
  35776. environment.hot.send({
  35777. type: "full-reload",
  35778. path: config.server.middlewareMode ? "*" : "/" + normalizePath$3(path$b.relative(config.root, file))
  35779. });
  35780. } else {
  35781. debugHmr?.(
  35782. `(${environment.name}) [no modules matched] ${colors$1.dim(shortFile)}`
  35783. );
  35784. }
  35785. return;
  35786. }
  35787. updateModules(environment, shortFile, options.modules, timestamp);
  35788. } catch (err) {
  35789. environment.hot.send({
  35790. type: "error",
  35791. err: prepareError(err)
  35792. });
  35793. }
  35794. }
  35795. const hotUpdateEnvironments = server.config.server.hotUpdateEnvironments ?? ((server2, hmr2) => {
  35796. return Promise.all(
  35797. Object.values(server2.environments).map(
  35798. (environment) => hmr2(environment)
  35799. )
  35800. );
  35801. });
  35802. await hotUpdateEnvironments(server, hmr);
  35803. }
  35804. function updateModules(environment, file, modules, timestamp, firstInvalidatedBy) {
  35805. const { hot } = environment;
  35806. const updates = [];
  35807. const invalidatedModules = /* @__PURE__ */ new Set();
  35808. const traversedModules = /* @__PURE__ */ new Set();
  35809. let needFullReload = modules.length === 0;
  35810. for (const mod of modules) {
  35811. const boundaries = [];
  35812. const hasDeadEnd = propagateUpdate(mod, traversedModules, boundaries);
  35813. environment.moduleGraph.invalidateModule(
  35814. mod,
  35815. invalidatedModules,
  35816. timestamp,
  35817. true
  35818. );
  35819. if (needFullReload) {
  35820. continue;
  35821. }
  35822. if (hasDeadEnd) {
  35823. needFullReload = hasDeadEnd;
  35824. continue;
  35825. }
  35826. if (firstInvalidatedBy && boundaries.some(
  35827. ({ acceptedVia }) => normalizeHmrUrl(acceptedVia.url) === firstInvalidatedBy
  35828. )) {
  35829. needFullReload = "circular import invalidate";
  35830. continue;
  35831. }
  35832. updates.push(
  35833. ...boundaries.map(
  35834. ({ boundary, acceptedVia, isWithinCircularImport }) => ({
  35835. type: `${boundary.type}-update`,
  35836. timestamp,
  35837. path: normalizeHmrUrl(boundary.url),
  35838. acceptedPath: normalizeHmrUrl(acceptedVia.url),
  35839. explicitImportRequired: boundary.type === "js" ? isExplicitImportRequired(acceptedVia.url) : false,
  35840. isWithinCircularImport,
  35841. firstInvalidatedBy
  35842. })
  35843. )
  35844. );
  35845. }
  35846. if (needFullReload) {
  35847. const reason = typeof needFullReload === "string" ? colors$1.dim(` (${needFullReload})`) : "";
  35848. environment.logger.info(
  35849. colors$1.green(`page reload `) + colors$1.dim(file) + reason,
  35850. { clear: !firstInvalidatedBy, timestamp: true }
  35851. );
  35852. hot.send({
  35853. type: "full-reload",
  35854. triggeredBy: path$b.resolve(environment.config.root, file)
  35855. });
  35856. return;
  35857. }
  35858. if (updates.length === 0) {
  35859. debugHmr?.(colors$1.yellow(`no update happened `) + colors$1.dim(file));
  35860. return;
  35861. }
  35862. environment.logger.info(
  35863. colors$1.green(`hmr update `) + colors$1.dim([...new Set(updates.map((u) => u.path))].join(", ")),
  35864. { clear: !firstInvalidatedBy, timestamp: true }
  35865. );
  35866. hot.send({
  35867. type: "update",
  35868. updates
  35869. });
  35870. }
  35871. function areAllImportsAccepted(importedBindings, acceptedExports) {
  35872. for (const binding of importedBindings) {
  35873. if (!acceptedExports.has(binding)) {
  35874. return false;
  35875. }
  35876. }
  35877. return true;
  35878. }
  35879. function propagateUpdate(node, traversedModules, boundaries, currentChain = [node]) {
  35880. if (traversedModules.has(node)) {
  35881. return false;
  35882. }
  35883. traversedModules.add(node);
  35884. if (node.id && node.isSelfAccepting === void 0) {
  35885. debugHmr?.(
  35886. `[propagate update] stop propagation because not analyzed: ${colors$1.dim(
  35887. node.id
  35888. )}`
  35889. );
  35890. return false;
  35891. }
  35892. if (node.isSelfAccepting) {
  35893. boundaries.push({
  35894. boundary: node,
  35895. acceptedVia: node,
  35896. isWithinCircularImport: isNodeWithinCircularImports(node, currentChain)
  35897. });
  35898. for (const importer of node.importers) {
  35899. if (isCSSRequest(importer.url) && !currentChain.includes(importer)) {
  35900. propagateUpdate(
  35901. importer,
  35902. traversedModules,
  35903. boundaries,
  35904. currentChain.concat(importer)
  35905. );
  35906. }
  35907. }
  35908. return false;
  35909. }
  35910. if (node.acceptedHmrExports) {
  35911. boundaries.push({
  35912. boundary: node,
  35913. acceptedVia: node,
  35914. isWithinCircularImport: isNodeWithinCircularImports(node, currentChain)
  35915. });
  35916. } else {
  35917. if (!node.importers.size) {
  35918. return true;
  35919. }
  35920. if (!isCSSRequest(node.url) && // we assume .svg is never an entrypoint and does not need a full reload
  35921. // to avoid frequent full reloads when an SVG file is referenced in CSS files (#18979)
  35922. !node.file?.endsWith(".svg") && [...node.importers].every((i) => isCSSRequest(i.url))) {
  35923. return true;
  35924. }
  35925. }
  35926. for (const importer of node.importers) {
  35927. const subChain = currentChain.concat(importer);
  35928. if (importer.acceptedHmrDeps.has(node)) {
  35929. boundaries.push({
  35930. boundary: importer,
  35931. acceptedVia: node,
  35932. isWithinCircularImport: isNodeWithinCircularImports(importer, subChain)
  35933. });
  35934. continue;
  35935. }
  35936. if (node.id && node.acceptedHmrExports && importer.importedBindings) {
  35937. const importedBindingsFromNode = importer.importedBindings.get(node.id);
  35938. if (importedBindingsFromNode && areAllImportsAccepted(importedBindingsFromNode, node.acceptedHmrExports)) {
  35939. continue;
  35940. }
  35941. }
  35942. if (!currentChain.includes(importer) && propagateUpdate(importer, traversedModules, boundaries, subChain)) {
  35943. return true;
  35944. }
  35945. }
  35946. return false;
  35947. }
  35948. function isNodeWithinCircularImports(node, nodeChain, currentChain = [node], traversedModules = /* @__PURE__ */ new Set()) {
  35949. if (traversedModules.has(node)) {
  35950. return false;
  35951. }
  35952. traversedModules.add(node);
  35953. for (const importer of node.importers) {
  35954. if (importer === node) continue;
  35955. if (isCSSRequest(importer.url)) continue;
  35956. const importerIndex = nodeChain.indexOf(importer);
  35957. if (importerIndex > -1) {
  35958. if (debugHmr) {
  35959. const importChain = [
  35960. importer,
  35961. ...[...currentChain].reverse(),
  35962. ...nodeChain.slice(importerIndex, -1).reverse()
  35963. ];
  35964. debugHmr(
  35965. colors$1.yellow(`circular imports detected: `) + importChain.map((m) => colors$1.dim(m.url)).join(" -> ")
  35966. );
  35967. }
  35968. return true;
  35969. }
  35970. if (!currentChain.includes(importer)) {
  35971. const result = isNodeWithinCircularImports(
  35972. importer,
  35973. nodeChain,
  35974. currentChain.concat(importer),
  35975. traversedModules
  35976. );
  35977. if (result) return result;
  35978. }
  35979. }
  35980. return false;
  35981. }
  35982. function handlePrunedModules(mods, { hot }) {
  35983. const t = Date.now();
  35984. mods.forEach((mod) => {
  35985. mod.lastHMRTimestamp = t;
  35986. mod.lastHMRInvalidationReceived = false;
  35987. debugHmr?.(`[dispose] ${colors$1.dim(mod.file)}`);
  35988. });
  35989. hot.send({
  35990. type: "prune",
  35991. paths: [...mods].map((m) => m.url)
  35992. });
  35993. }
  35994. function lexAcceptedHmrDeps(code, start, urls) {
  35995. let state = 0 /* inCall */;
  35996. let prevState = 0 /* inCall */;
  35997. let currentDep = "";
  35998. function addDep(index) {
  35999. urls.add({
  36000. url: currentDep,
  36001. start: index - currentDep.length - 1,
  36002. end: index + 1
  36003. });
  36004. currentDep = "";
  36005. }
  36006. for (let i = start; i < code.length; i++) {
  36007. const char = code.charAt(i);
  36008. switch (state) {
  36009. case 0 /* inCall */:
  36010. case 4 /* inArray */:
  36011. if (char === `'`) {
  36012. prevState = state;
  36013. state = 1 /* inSingleQuoteString */;
  36014. } else if (char === `"`) {
  36015. prevState = state;
  36016. state = 2 /* inDoubleQuoteString */;
  36017. } else if (char === "`") {
  36018. prevState = state;
  36019. state = 3 /* inTemplateString */;
  36020. } else if (whitespaceRE.test(char)) {
  36021. continue;
  36022. } else {
  36023. if (state === 0 /* inCall */) {
  36024. if (char === `[`) {
  36025. state = 4 /* inArray */;
  36026. } else {
  36027. return true;
  36028. }
  36029. } else {
  36030. if (char === `]`) {
  36031. return false;
  36032. } else if (char === ",") {
  36033. continue;
  36034. } else {
  36035. error(i);
  36036. }
  36037. }
  36038. }
  36039. break;
  36040. case 1 /* inSingleQuoteString */:
  36041. if (char === `'`) {
  36042. addDep(i);
  36043. if (prevState === 0 /* inCall */) {
  36044. return false;
  36045. } else {
  36046. state = prevState;
  36047. }
  36048. } else {
  36049. currentDep += char;
  36050. }
  36051. break;
  36052. case 2 /* inDoubleQuoteString */:
  36053. if (char === `"`) {
  36054. addDep(i);
  36055. if (prevState === 0 /* inCall */) {
  36056. return false;
  36057. } else {
  36058. state = prevState;
  36059. }
  36060. } else {
  36061. currentDep += char;
  36062. }
  36063. break;
  36064. case 3 /* inTemplateString */:
  36065. if (char === "`") {
  36066. addDep(i);
  36067. if (prevState === 0 /* inCall */) {
  36068. return false;
  36069. } else {
  36070. state = prevState;
  36071. }
  36072. } else if (char === "$" && code.charAt(i + 1) === "{") {
  36073. error(i);
  36074. } else {
  36075. currentDep += char;
  36076. }
  36077. break;
  36078. default:
  36079. throw new Error("unknown import.meta.hot lexer state");
  36080. }
  36081. }
  36082. return false;
  36083. }
  36084. function lexAcceptedHmrExports(code, start, exportNames) {
  36085. const urls = /* @__PURE__ */ new Set();
  36086. lexAcceptedHmrDeps(code, start, urls);
  36087. for (const { url } of urls) {
  36088. exportNames.add(url);
  36089. }
  36090. return urls.size > 0;
  36091. }
  36092. function normalizeHmrUrl(url) {
  36093. if (url[0] !== "." && url[0] !== "/") {
  36094. url = wrapId$1(url);
  36095. }
  36096. return url;
  36097. }
  36098. function error(pos) {
  36099. const err = new Error(
  36100. `import.meta.hot.accept() can only accept string literals or an Array of string literals.`
  36101. );
  36102. err.pos = pos;
  36103. throw err;
  36104. }
  36105. async function readModifiedFile(file) {
  36106. const content = await fsp.readFile(file, "utf-8");
  36107. if (!content) {
  36108. const mtime = (await fsp.stat(file)).mtimeMs;
  36109. for (let n = 0; n < 10; n++) {
  36110. await new Promise((r) => setTimeout(r, 10));
  36111. const newMtime = (await fsp.stat(file)).mtimeMs;
  36112. if (newMtime !== mtime) {
  36113. break;
  36114. }
  36115. }
  36116. return await fsp.readFile(file, "utf-8");
  36117. } else {
  36118. return content;
  36119. }
  36120. }
  36121. function createServerHotChannel() {
  36122. const innerEmitter = new EventEmitter$4();
  36123. const outsideEmitter = new EventEmitter$4();
  36124. return {
  36125. send(payload) {
  36126. outsideEmitter.emit("send", payload);
  36127. },
  36128. off(event, listener) {
  36129. innerEmitter.off(event, listener);
  36130. },
  36131. on: (event, listener) => {
  36132. innerEmitter.on(event, listener);
  36133. },
  36134. close() {
  36135. innerEmitter.removeAllListeners();
  36136. outsideEmitter.removeAllListeners();
  36137. },
  36138. listen() {
  36139. innerEmitter.emit("connection");
  36140. },
  36141. api: {
  36142. innerEmitter,
  36143. outsideEmitter
  36144. }
  36145. };
  36146. }
  36147. function createDeprecatedHotBroadcaster(ws) {
  36148. const broadcaster = {
  36149. on: ws.on,
  36150. off: ws.off,
  36151. listen: ws.listen,
  36152. send: ws.send,
  36153. setInvokeHandler: ws.setInvokeHandler,
  36154. handleInvoke: async () => ({
  36155. error: {
  36156. name: "TransportError",
  36157. message: "handleInvoke not implemented",
  36158. stack: new Error().stack
  36159. }
  36160. }),
  36161. get channels() {
  36162. return [ws];
  36163. },
  36164. addChannel() {
  36165. return broadcaster;
  36166. },
  36167. close() {
  36168. return Promise.all(broadcaster.channels.map((channel) => channel.close()));
  36169. }
  36170. };
  36171. return broadcaster;
  36172. }
  36173. const nonJsRe = /\.json(?:$|\?)/;
  36174. const isNonJsRequest = (request) => nonJsRe.test(request);
  36175. const importMetaEnvMarker = "__vite_import_meta_env__";
  36176. const importMetaEnvKeyReCache = /* @__PURE__ */ new Map();
  36177. function definePlugin(config) {
  36178. const isBuild = config.command === "build";
  36179. const isBuildLib = isBuild && config.build.lib;
  36180. const processEnv = {};
  36181. if (!isBuildLib) {
  36182. const nodeEnv = process.env.NODE_ENV || config.mode;
  36183. Object.assign(processEnv, {
  36184. "process.env": `{}`,
  36185. "global.process.env": `{}`,
  36186. "globalThis.process.env": `{}`,
  36187. "process.env.NODE_ENV": JSON.stringify(nodeEnv),
  36188. "global.process.env.NODE_ENV": JSON.stringify(nodeEnv),
  36189. "globalThis.process.env.NODE_ENV": JSON.stringify(nodeEnv)
  36190. });
  36191. }
  36192. const importMetaKeys = {};
  36193. const importMetaEnvKeys = {};
  36194. const importMetaFallbackKeys = {};
  36195. if (isBuild) {
  36196. importMetaKeys["import.meta.hot"] = `undefined`;
  36197. for (const key in config.env) {
  36198. const val = JSON.stringify(config.env[key]);
  36199. importMetaKeys[`import.meta.env.${key}`] = val;
  36200. importMetaEnvKeys[key] = val;
  36201. }
  36202. importMetaKeys["import.meta.env.SSR"] = `undefined`;
  36203. importMetaFallbackKeys["import.meta.env"] = `undefined`;
  36204. }
  36205. function generatePattern(environment) {
  36206. const keepProcessEnv = environment.config.keepProcessEnv;
  36207. const userDefine = {};
  36208. const userDefineEnv = {};
  36209. for (const key in environment.config.define) {
  36210. userDefine[key] = handleDefineValue(environment.config.define[key]);
  36211. if (isBuild && key.startsWith("import.meta.env.")) {
  36212. userDefineEnv[key.slice(16)] = environment.config.define[key];
  36213. }
  36214. }
  36215. const define = {
  36216. ...keepProcessEnv ? {} : processEnv,
  36217. ...importMetaKeys,
  36218. ...userDefine,
  36219. ...importMetaFallbackKeys
  36220. };
  36221. const ssr = environment.config.consumer === "server";
  36222. if ("import.meta.env.SSR" in define) {
  36223. define["import.meta.env.SSR"] = ssr + "";
  36224. }
  36225. if ("import.meta.env" in define) {
  36226. define["import.meta.env"] = importMetaEnvMarker;
  36227. }
  36228. const importMetaEnvVal = serializeDefine({
  36229. ...importMetaEnvKeys,
  36230. SSR: ssr + "",
  36231. ...userDefineEnv
  36232. });
  36233. const patternKeys = Object.keys(userDefine);
  36234. if (!keepProcessEnv && Object.keys(processEnv).length) {
  36235. patternKeys.push("process.env");
  36236. }
  36237. if (Object.keys(importMetaKeys).length) {
  36238. patternKeys.push("import.meta.env", "import.meta.hot");
  36239. }
  36240. const pattern = patternKeys.length ? new RegExp(patternKeys.map(escapeRegex).join("|")) : null;
  36241. return [define, pattern, importMetaEnvVal];
  36242. }
  36243. const patternsCache = /* @__PURE__ */ new WeakMap();
  36244. function getPattern(environment) {
  36245. let pattern = patternsCache.get(environment);
  36246. if (!pattern) {
  36247. pattern = generatePattern(environment);
  36248. patternsCache.set(environment, pattern);
  36249. }
  36250. return pattern;
  36251. }
  36252. return {
  36253. name: "vite:define",
  36254. transform: {
  36255. async handler(code, id) {
  36256. if (this.environment.config.consumer === "client" && !isBuild) {
  36257. return;
  36258. }
  36259. if (
  36260. // exclude html, css and static assets for performance
  36261. isHTMLRequest(id) || isCSSRequest(id) || isNonJsRequest(id) || config.assetsInclude(id)
  36262. ) {
  36263. return;
  36264. }
  36265. let [define, pattern, importMetaEnvVal] = getPattern(this.environment);
  36266. if (!pattern) return;
  36267. pattern.lastIndex = 0;
  36268. if (!pattern.test(code)) return;
  36269. const hasDefineImportMetaEnv = "import.meta.env" in define;
  36270. let marker = importMetaEnvMarker;
  36271. if (hasDefineImportMetaEnv && code.includes(marker)) {
  36272. let i = 1;
  36273. do {
  36274. marker = importMetaEnvMarker + i++;
  36275. } while (code.includes(marker));
  36276. if (marker !== importMetaEnvMarker) {
  36277. define = { ...define, "import.meta.env": marker };
  36278. }
  36279. }
  36280. const result = await replaceDefine(this.environment, code, id, define);
  36281. if (hasDefineImportMetaEnv) {
  36282. result.code = result.code.replaceAll(
  36283. getImportMetaEnvKeyRe(marker),
  36284. (m) => "undefined".padEnd(m.length)
  36285. );
  36286. if (result.code.includes(marker)) {
  36287. result.code = `const ${marker} = ${importMetaEnvVal};
  36288. ` + result.code;
  36289. if (result.map) {
  36290. const map = JSON.parse(result.map);
  36291. map.mappings = ";" + map.mappings;
  36292. result.map = map;
  36293. }
  36294. }
  36295. }
  36296. return result;
  36297. }
  36298. }
  36299. };
  36300. }
  36301. async function replaceDefine(environment, code, id, define) {
  36302. const esbuildOptions = environment.config.esbuild || {};
  36303. const result = await transform$1(code, {
  36304. loader: "js",
  36305. charset: esbuildOptions.charset ?? "utf8",
  36306. platform: "neutral",
  36307. define,
  36308. sourcefile: id,
  36309. sourcemap: environment.config.command === "build" ? !!environment.config.build.sourcemap : true
  36310. });
  36311. if (result.map.includes("<define:")) {
  36312. const originalMap = new TraceMap(result.map);
  36313. if (originalMap.sources.length >= 2) {
  36314. const sourceIndex = originalMap.sources.indexOf(id);
  36315. const decoded = decodedMap(originalMap);
  36316. decoded.sources = [id];
  36317. decoded.mappings = decoded.mappings.map(
  36318. (segments) => segments.filter((segment) => {
  36319. const index = segment[1];
  36320. segment[1] = 0;
  36321. return index === sourceIndex;
  36322. })
  36323. );
  36324. result.map = JSON.stringify(encodedMap(new TraceMap(decoded)));
  36325. }
  36326. }
  36327. return {
  36328. code: result.code,
  36329. map: result.map || null
  36330. };
  36331. }
  36332. function serializeDefine(define) {
  36333. let res = `{`;
  36334. const keys = Object.keys(define).sort();
  36335. for (let i = 0; i < keys.length; i++) {
  36336. const key = keys[i];
  36337. const val = define[key];
  36338. res += `${JSON.stringify(key)}: ${handleDefineValue(val)}`;
  36339. if (i !== keys.length - 1) {
  36340. res += `, `;
  36341. }
  36342. }
  36343. return res + `}`;
  36344. }
  36345. function handleDefineValue(value) {
  36346. if (typeof value === "undefined") return "undefined";
  36347. if (typeof value === "string") return value;
  36348. return JSON.stringify(value);
  36349. }
  36350. function getImportMetaEnvKeyRe(marker) {
  36351. let re = importMetaEnvKeyReCache.get(marker);
  36352. if (!re) {
  36353. re = new RegExp(`${marker}\\..+?\\b`, "g");
  36354. importMetaEnvKeyReCache.set(marker, re);
  36355. }
  36356. return re;
  36357. }
  36358. const workerOrSharedWorkerRE = /(?:\?|&)(worker|sharedworker)(?:&|$)/;
  36359. const workerFileRE = /(?:\?|&)worker_file&type=(\w+)(?:&|$)/;
  36360. const inlineRE$1 = /[?&]inline\b/;
  36361. const WORKER_FILE_ID = "worker_file";
  36362. const workerCache = /* @__PURE__ */ new WeakMap();
  36363. function saveEmitWorkerAsset(config, asset) {
  36364. const workerMap = workerCache.get(config.mainConfig || config);
  36365. const duplicateAsset = workerMap.assets.get(asset.fileName);
  36366. if (duplicateAsset) {
  36367. if (!isSameContent(duplicateAsset.source, asset.source)) {
  36368. config.logger.warn(
  36369. `
  36370. ` + colors$1.yellow(
  36371. `The emitted file ${JSON.stringify(asset.fileName)} overwrites a previously emitted file of the same name.`
  36372. )
  36373. );
  36374. }
  36375. }
  36376. workerMap.assets.set(asset.fileName, asset);
  36377. }
  36378. async function bundleWorkerEntry(config, id) {
  36379. const input = cleanUrl(id);
  36380. const newBundleChain = [...config.bundleChain, input];
  36381. if (config.bundleChain.includes(input)) {
  36382. throw new Error(
  36383. `Circular worker imports detected. Vite does not support it. Import chain: ${newBundleChain.map((id2) => prettifyUrl(id2, config.root)).join(" -> ")}`
  36384. );
  36385. }
  36386. const { rollup } = await import('rollup');
  36387. const { plugins, rollupOptions, format } = config.worker;
  36388. const workerConfig = await plugins(newBundleChain);
  36389. const workerEnvironment = new BuildEnvironment("client", workerConfig);
  36390. await workerEnvironment.init();
  36391. const bundle = await rollup({
  36392. ...rollupOptions,
  36393. input,
  36394. plugins: workerEnvironment.plugins.map(
  36395. (p) => injectEnvironmentAndFilterToHooks(workerEnvironment, p)
  36396. ),
  36397. onLog(level, log) {
  36398. onRollupLog(level, log, workerEnvironment);
  36399. },
  36400. preserveEntrySignatures: false
  36401. });
  36402. let chunk;
  36403. try {
  36404. const workerOutputConfig = config.worker.rollupOptions.output;
  36405. const workerConfig2 = workerOutputConfig ? Array.isArray(workerOutputConfig) ? workerOutputConfig[0] || {} : workerOutputConfig : {};
  36406. const {
  36407. output: [outputChunk, ...outputChunks]
  36408. } = await bundle.generate({
  36409. entryFileNames: path$b.posix.join(
  36410. config.build.assetsDir,
  36411. "[name]-[hash].js"
  36412. ),
  36413. chunkFileNames: path$b.posix.join(
  36414. config.build.assetsDir,
  36415. "[name]-[hash].js"
  36416. ),
  36417. assetFileNames: path$b.posix.join(
  36418. config.build.assetsDir,
  36419. "[name]-[hash].[ext]"
  36420. ),
  36421. ...workerConfig2,
  36422. format,
  36423. sourcemap: config.build.sourcemap
  36424. });
  36425. chunk = outputChunk;
  36426. outputChunks.forEach((outputChunk2) => {
  36427. if (outputChunk2.type === "asset") {
  36428. saveEmitWorkerAsset(config, outputChunk2);
  36429. } else if (outputChunk2.type === "chunk") {
  36430. saveEmitWorkerAsset(config, {
  36431. fileName: outputChunk2.fileName,
  36432. originalFileName: null,
  36433. originalFileNames: [],
  36434. source: outputChunk2.code
  36435. });
  36436. }
  36437. });
  36438. } catch (e) {
  36439. if (e instanceof Error && e.name === "RollupError" && e.code === "INVALID_OPTION" && e.message.includes('"output.format"')) {
  36440. e.message = e.message.replace("output.format", "worker.format");
  36441. }
  36442. throw e;
  36443. } finally {
  36444. await bundle.close();
  36445. }
  36446. return emitSourcemapForWorkerEntry(config, chunk);
  36447. }
  36448. function emitSourcemapForWorkerEntry(config, chunk) {
  36449. const { map: sourcemap } = chunk;
  36450. if (sourcemap) {
  36451. if (config.build.sourcemap === "hidden" || config.build.sourcemap === true) {
  36452. const data = sourcemap.toString();
  36453. const mapFileName = chunk.fileName + ".map";
  36454. saveEmitWorkerAsset(config, {
  36455. fileName: mapFileName,
  36456. originalFileName: null,
  36457. originalFileNames: [],
  36458. source: data
  36459. });
  36460. }
  36461. }
  36462. return chunk;
  36463. }
  36464. const workerAssetUrlRE = /__VITE_WORKER_ASSET__([a-z\d]{8})__/g;
  36465. function encodeWorkerAssetFileName(fileName, workerCache2) {
  36466. const { fileNameHash } = workerCache2;
  36467. const hash = getHash(fileName);
  36468. if (!fileNameHash.get(hash)) {
  36469. fileNameHash.set(hash, fileName);
  36470. }
  36471. return `__VITE_WORKER_ASSET__${hash}__`;
  36472. }
  36473. async function workerFileToUrl(config, id) {
  36474. const workerMap = workerCache.get(config.mainConfig || config);
  36475. let fileName = workerMap.bundle.get(id);
  36476. if (!fileName) {
  36477. const outputChunk = await bundleWorkerEntry(config, id);
  36478. fileName = outputChunk.fileName;
  36479. saveEmitWorkerAsset(config, {
  36480. fileName,
  36481. originalFileName: null,
  36482. originalFileNames: [],
  36483. source: outputChunk.code
  36484. });
  36485. workerMap.bundle.set(id, fileName);
  36486. }
  36487. return encodeWorkerAssetFileName(fileName, workerMap);
  36488. }
  36489. function webWorkerPostPlugin() {
  36490. return {
  36491. name: "vite:worker-post",
  36492. resolveImportMeta(property, { format }) {
  36493. if (format === "iife") {
  36494. if (!property) {
  36495. return `{
  36496. url: self.location.href
  36497. }`;
  36498. }
  36499. if (property === "url") {
  36500. return "self.location.href";
  36501. }
  36502. }
  36503. return null;
  36504. }
  36505. };
  36506. }
  36507. function webWorkerPlugin(config) {
  36508. const isBuild = config.command === "build";
  36509. const isWorker = config.isWorker;
  36510. return {
  36511. name: "vite:worker",
  36512. buildStart() {
  36513. if (isWorker) {
  36514. return;
  36515. }
  36516. workerCache.set(config, {
  36517. assets: /* @__PURE__ */ new Map(),
  36518. bundle: /* @__PURE__ */ new Map(),
  36519. fileNameHash: /* @__PURE__ */ new Map()
  36520. });
  36521. },
  36522. load: {
  36523. handler(id) {
  36524. if (isBuild && workerOrSharedWorkerRE.test(id)) {
  36525. return "";
  36526. }
  36527. }
  36528. },
  36529. shouldTransformCachedModule({ id }) {
  36530. if (isBuild && config.build.watch && workerOrSharedWorkerRE.test(id)) {
  36531. return true;
  36532. }
  36533. },
  36534. transform: {
  36535. async handler(raw, id) {
  36536. const workerFileMatch = workerFileRE.exec(id);
  36537. if (workerFileMatch) {
  36538. const workerType2 = workerFileMatch[1];
  36539. let injectEnv = "";
  36540. const scriptPath = JSON.stringify(
  36541. path$b.posix.join(config.base, ENV_PUBLIC_PATH)
  36542. );
  36543. if (workerType2 === "classic") {
  36544. injectEnv = `importScripts(${scriptPath})
  36545. `;
  36546. } else if (workerType2 === "module") {
  36547. injectEnv = `import ${scriptPath}
  36548. `;
  36549. } else if (workerType2 === "ignore") {
  36550. if (isBuild) {
  36551. injectEnv = "";
  36552. } else {
  36553. const environment = this.environment;
  36554. const moduleGraph = environment.mode === "dev" ? environment.moduleGraph : void 0;
  36555. const module = moduleGraph?.getModuleById(ENV_ENTRY);
  36556. injectEnv = module?.transformResult?.code || "";
  36557. }
  36558. }
  36559. if (injectEnv) {
  36560. const s = new MagicString(raw);
  36561. s.prepend(injectEnv + ";\n");
  36562. return {
  36563. code: s.toString(),
  36564. map: s.generateMap({ hires: "boundary" })
  36565. };
  36566. }
  36567. return;
  36568. }
  36569. const workerMatch = workerOrSharedWorkerRE.exec(id);
  36570. if (!workerMatch) return;
  36571. const { format } = config.worker;
  36572. const workerConstructor = workerMatch[1] === "sharedworker" ? "SharedWorker" : "Worker";
  36573. const workerType = isBuild ? format === "es" ? "module" : "classic" : "module";
  36574. const workerTypeOption = `{
  36575. ${workerType === "module" ? `type: "module",` : ""}
  36576. name: options?.name
  36577. }`;
  36578. let urlCode;
  36579. if (isBuild) {
  36580. if (isWorker && config.bundleChain.at(-1) === cleanUrl(id)) {
  36581. urlCode = "self.location.href";
  36582. } else if (inlineRE$1.test(id)) {
  36583. const chunk = await bundleWorkerEntry(config, id);
  36584. const jsContent = `const jsContent = ${JSON.stringify(chunk.code)};`;
  36585. const code = (
  36586. // Using blob URL for SharedWorker results in multiple instances of a same worker
  36587. workerConstructor === "Worker" ? `${jsContent}
  36588. const blob = typeof self !== "undefined" && self.Blob && new Blob([${workerType === "classic" ? "" : (
  36589. // `URL` is always available, in `Worker[type="module"]`
  36590. `'URL.revokeObjectURL(import.meta.url);',`
  36591. )}jsContent], { type: "text/javascript;charset=utf-8" });
  36592. export default function WorkerWrapper(options) {
  36593. let objURL;
  36594. try {
  36595. objURL = blob && (self.URL || self.webkitURL).createObjectURL(blob);
  36596. if (!objURL) throw ''
  36597. const worker = new ${workerConstructor}(objURL, ${workerTypeOption});
  36598. worker.addEventListener("error", () => {
  36599. (self.URL || self.webkitURL).revokeObjectURL(objURL);
  36600. });
  36601. return worker;
  36602. } catch(e) {
  36603. return new ${workerConstructor}(
  36604. 'data:text/javascript;charset=utf-8,' + encodeURIComponent(jsContent),
  36605. ${workerTypeOption}
  36606. );
  36607. }${// For module workers, we should not revoke the URL until the worker runs,
  36608. // otherwise the worker fails to run
  36609. workerType === "classic" ? ` finally {
  36610. objURL && (self.URL || self.webkitURL).revokeObjectURL(objURL);
  36611. }` : ""}
  36612. }` : `${jsContent}
  36613. export default function WorkerWrapper(options) {
  36614. return new ${workerConstructor}(
  36615. 'data:text/javascript;charset=utf-8,' + encodeURIComponent(jsContent),
  36616. ${workerTypeOption}
  36617. );
  36618. }
  36619. `
  36620. );
  36621. return {
  36622. code,
  36623. // Empty sourcemap to suppress Rollup warning
  36624. map: { mappings: "" }
  36625. };
  36626. } else {
  36627. urlCode = JSON.stringify(await workerFileToUrl(config, id));
  36628. }
  36629. } else {
  36630. let url = await fileToUrl$1(this, cleanUrl(id));
  36631. url = injectQuery(url, `${WORKER_FILE_ID}&type=${workerType}`);
  36632. urlCode = JSON.stringify(url);
  36633. }
  36634. if (urlRE$1.test(id)) {
  36635. return {
  36636. code: `export default ${urlCode}`,
  36637. map: { mappings: "" }
  36638. // Empty sourcemap to suppress Rollup warning
  36639. };
  36640. }
  36641. return {
  36642. code: `export default function WorkerWrapper(options) {
  36643. return new ${workerConstructor}(
  36644. ${urlCode},
  36645. ${workerTypeOption}
  36646. );
  36647. }`,
  36648. map: { mappings: "" }
  36649. // Empty sourcemap to suppress Rollup warning
  36650. };
  36651. }
  36652. },
  36653. renderChunk(code, chunk, outputOptions) {
  36654. let s;
  36655. const result = () => {
  36656. return s && {
  36657. code: s.toString(),
  36658. map: this.environment.config.build.sourcemap ? s.generateMap({ hires: "boundary" }) : null
  36659. };
  36660. };
  36661. workerAssetUrlRE.lastIndex = 0;
  36662. if (workerAssetUrlRE.test(code)) {
  36663. const toRelativeRuntime = createToImportMetaURLBasedRelativeRuntime(
  36664. outputOptions.format,
  36665. this.environment.config.isWorker
  36666. );
  36667. let match;
  36668. s = new MagicString(code);
  36669. workerAssetUrlRE.lastIndex = 0;
  36670. const workerMap = workerCache.get(config.mainConfig || config);
  36671. const { fileNameHash } = workerMap;
  36672. while (match = workerAssetUrlRE.exec(code)) {
  36673. const [full, hash] = match;
  36674. const filename = fileNameHash.get(hash);
  36675. const replacement = toOutputFilePathInJS(
  36676. this.environment,
  36677. filename,
  36678. "asset",
  36679. chunk.fileName,
  36680. "js",
  36681. toRelativeRuntime
  36682. );
  36683. const replacementString = typeof replacement === "string" ? JSON.stringify(encodeURIPath(replacement)).slice(1, -1) : `"+${replacement.runtime}+"`;
  36684. s.update(match.index, match.index + full.length, replacementString);
  36685. }
  36686. }
  36687. return result();
  36688. },
  36689. generateBundle(opts, bundle) {
  36690. if (opts.__vite_skip_asset_emit__ || isWorker) {
  36691. return;
  36692. }
  36693. const workerMap = workerCache.get(config);
  36694. workerMap.assets.forEach((asset) => {
  36695. const duplicateAsset = bundle[asset.fileName];
  36696. if (duplicateAsset) {
  36697. const content = duplicateAsset.type === "asset" ? duplicateAsset.source : duplicateAsset.code;
  36698. if (isSameContent(content, asset.source)) {
  36699. return;
  36700. }
  36701. }
  36702. this.emitFile({
  36703. type: "asset",
  36704. fileName: asset.fileName,
  36705. source: asset.source
  36706. // NOTE: fileName is already generated when bundling the worker
  36707. // so no need to pass originalFileNames/names
  36708. });
  36709. });
  36710. workerMap.assets.clear();
  36711. }
  36712. };
  36713. }
  36714. function isSameContent(a, b) {
  36715. if (typeof a === "string") {
  36716. if (typeof b === "string") {
  36717. return a === b;
  36718. }
  36719. return Buffer.from(a).equals(b);
  36720. }
  36721. return Buffer.from(b).equals(a);
  36722. }
  36723. function preAliasPlugin(config) {
  36724. const findPatterns = getAliasPatterns(config.resolve.alias);
  36725. return {
  36726. name: "vite:pre-alias",
  36727. applyToEnvironment(environment) {
  36728. return !isDepOptimizationDisabled(environment.config.optimizeDeps);
  36729. },
  36730. async resolveId(id, importer, options) {
  36731. const environment = this.environment;
  36732. const ssr = environment.config.consumer === "server";
  36733. const depsOptimizer = environment.depsOptimizer;
  36734. if (importer && depsOptimizer && bareImportRE.test(id) && !options.scan && id !== "@vite/client" && id !== "@vite/env") {
  36735. if (findPatterns.find((pattern) => matches(pattern, id))) {
  36736. const optimizedId = await tryOptimizedResolve(
  36737. depsOptimizer,
  36738. id,
  36739. importer,
  36740. config.resolve.preserveSymlinks,
  36741. config.packageCache
  36742. );
  36743. if (optimizedId) {
  36744. return optimizedId;
  36745. }
  36746. if (depsOptimizer.options.noDiscovery) {
  36747. return;
  36748. }
  36749. const resolved = await this.resolve(id, importer, options);
  36750. if (resolved && !depsOptimizer.isOptimizedDepFile(resolved.id)) {
  36751. const optimizeDeps = depsOptimizer.options;
  36752. const resolvedId = cleanUrl(resolved.id);
  36753. const isVirtual = resolvedId === id || resolvedId.includes("\0");
  36754. if (!isVirtual && fs__default.existsSync(resolvedId) && !moduleListContains(optimizeDeps.exclude, id) && path$b.isAbsolute(resolvedId) && (isInNodeModules$1(resolvedId) || optimizeDeps.include?.includes(id)) && isOptimizable(resolvedId, optimizeDeps) && (!ssr || optimizeAliasReplacementForSSR(resolvedId, optimizeDeps))) {
  36755. const optimizedInfo = depsOptimizer.registerMissingImport(
  36756. id,
  36757. resolvedId
  36758. );
  36759. return { id: depsOptimizer.getOptimizedDepId(optimizedInfo) };
  36760. }
  36761. }
  36762. return resolved;
  36763. }
  36764. }
  36765. }
  36766. };
  36767. }
  36768. function optimizeAliasReplacementForSSR(id, optimizeDeps) {
  36769. if (optimizeDeps.include?.includes(id)) {
  36770. return true;
  36771. }
  36772. return false;
  36773. }
  36774. function matches(pattern, importee) {
  36775. if (pattern instanceof RegExp) {
  36776. return pattern.test(importee);
  36777. }
  36778. if (importee.length < pattern.length) {
  36779. return false;
  36780. }
  36781. if (importee === pattern) {
  36782. return true;
  36783. }
  36784. return importee.startsWith(withTrailingSlash(pattern));
  36785. }
  36786. function getAliasPatterns(entries) {
  36787. if (Array.isArray(entries)) {
  36788. return entries.map((entry) => entry.find);
  36789. }
  36790. return Object.entries(entries).map(([find]) => find);
  36791. }
  36792. function getAliasPatternMatcher(entries) {
  36793. const patterns = getAliasPatterns(entries);
  36794. return (importee) => patterns.some((pattern) => matches(pattern, importee));
  36795. }
  36796. const debug$2 = createDebugger("vite:import-analysis");
  36797. const clientDir = normalizePath$3(CLIENT_DIR);
  36798. const skipRE = /\.(?:map|json)(?:$|\?)/;
  36799. const canSkipImportAnalysis = (id) => skipRE.test(id) || isDirectCSSRequest(id);
  36800. const optimizedDepChunkRE = /\/chunk-[A-Z\d]{8}\.js/;
  36801. const optimizedDepDynamicRE = /-[A-Z\d]{8}\.js/;
  36802. const hasViteIgnoreRE = /\/\*\s*@vite-ignore\s*\*\//;
  36803. const urlIsStringRE = /^(?:'.*'|".*"|`.*`)$/;
  36804. const templateLiteralRE = /^\s*`(.*)`\s*$/;
  36805. function isExplicitImportRequired(url) {
  36806. return !isJSRequest(url) && !isCSSRequest(url);
  36807. }
  36808. function normalizeResolvedIdToUrl(environment, url, resolved) {
  36809. const root = environment.config.root;
  36810. const depsOptimizer = environment.depsOptimizer;
  36811. if (resolved.id.startsWith(withTrailingSlash(root))) {
  36812. url = resolved.id.slice(root.length);
  36813. } else if (depsOptimizer?.isOptimizedDepFile(resolved.id) || // vite-plugin-react isn't following the leading \0 virtual module convention.
  36814. // This is a temporary hack to avoid expensive fs checks for React apps.
  36815. // We'll remove this as soon we're able to fix the react plugins.
  36816. resolved.id !== "/@react-refresh" && path$b.isAbsolute(resolved.id) && fs__default.existsSync(cleanUrl(resolved.id))) {
  36817. url = path$b.posix.join(FS_PREFIX, resolved.id);
  36818. } else {
  36819. url = resolved.id;
  36820. }
  36821. if (url[0] !== "." && url[0] !== "/") {
  36822. url = wrapId$1(resolved.id);
  36823. }
  36824. return url;
  36825. }
  36826. function extractImportedBindings(id, source, importSpec, importedBindings) {
  36827. let bindings = importedBindings.get(id);
  36828. if (!bindings) {
  36829. bindings = /* @__PURE__ */ new Set();
  36830. importedBindings.set(id, bindings);
  36831. }
  36832. const isDynamic = importSpec.d > -1;
  36833. const isMeta = importSpec.d === -2;
  36834. if (isDynamic || isMeta) {
  36835. bindings.add("*");
  36836. return;
  36837. }
  36838. const exp = source.slice(importSpec.ss, importSpec.se);
  36839. ESM_STATIC_IMPORT_RE.lastIndex = 0;
  36840. const match = ESM_STATIC_IMPORT_RE.exec(exp);
  36841. if (!match) {
  36842. return;
  36843. }
  36844. const staticImport = {
  36845. type: "static",
  36846. code: match[0],
  36847. start: match.index,
  36848. end: match.index + match[0].length,
  36849. imports: match.groups.imports,
  36850. specifier: match.groups.specifier
  36851. };
  36852. const parsed = parseStaticImport(staticImport);
  36853. if (parsed.namespacedImport) {
  36854. bindings.add("*");
  36855. }
  36856. if (parsed.defaultImport) {
  36857. bindings.add("default");
  36858. }
  36859. if (parsed.namedImports) {
  36860. for (const name of Object.keys(parsed.namedImports)) {
  36861. bindings.add(name);
  36862. }
  36863. }
  36864. }
  36865. function importAnalysisPlugin(config) {
  36866. const { root, base } = config;
  36867. const clientPublicPath = path$b.posix.join(base, CLIENT_PUBLIC_PATH);
  36868. const enablePartialAccept = config.experimental.hmrPartialAccept;
  36869. const matchAlias = getAliasPatternMatcher(config.resolve.alias);
  36870. let _env;
  36871. let _ssrEnv;
  36872. function getEnv(ssr) {
  36873. if (!_ssrEnv || !_env) {
  36874. const importMetaEnvKeys = {};
  36875. const userDefineEnv = {};
  36876. for (const key in config.env) {
  36877. importMetaEnvKeys[key] = JSON.stringify(config.env[key]);
  36878. }
  36879. for (const key in config.define) {
  36880. if (key.startsWith("import.meta.env.")) {
  36881. userDefineEnv[key.slice(16)] = config.define[key];
  36882. }
  36883. }
  36884. const env = `import.meta.env = ${serializeDefine({
  36885. ...importMetaEnvKeys,
  36886. SSR: "__vite_ssr__",
  36887. ...userDefineEnv
  36888. })};`;
  36889. _ssrEnv = env.replace("__vite_ssr__", "true");
  36890. _env = env.replace("__vite_ssr__", "false");
  36891. }
  36892. return ssr ? _ssrEnv : _env;
  36893. }
  36894. return {
  36895. name: "vite:import-analysis",
  36896. async transform(source, importer) {
  36897. const environment = this.environment;
  36898. const ssr = environment.config.consumer === "server";
  36899. const moduleGraph = environment.moduleGraph;
  36900. if (canSkipImportAnalysis(importer)) {
  36901. debug$2?.(colors$1.dim(`[skipped] ${prettifyUrl(importer, root)}`));
  36902. return null;
  36903. }
  36904. const msAtStart = debug$2 ? performance$1.now() : 0;
  36905. await init;
  36906. let imports;
  36907. let exports;
  36908. source = stripBomTag(source);
  36909. try {
  36910. [imports, exports] = parse$d(source);
  36911. } catch (_e) {
  36912. const e = _e;
  36913. const { message, showCodeFrame } = createParseErrorInfo(
  36914. importer,
  36915. source
  36916. );
  36917. this.error(message, showCodeFrame ? e.idx : void 0);
  36918. }
  36919. const depsOptimizer = environment.depsOptimizer;
  36920. const importerModule = moduleGraph.getModuleById(importer);
  36921. if (!importerModule) {
  36922. throwOutdatedRequest(importer);
  36923. }
  36924. if (!imports.length && !this._addedImports) {
  36925. importerModule.isSelfAccepting = false;
  36926. debug$2?.(
  36927. `${timeFrom(msAtStart)} ${colors$1.dim(
  36928. `[no imports] ${prettifyUrl(importer, root)}`
  36929. )}`
  36930. );
  36931. return source;
  36932. }
  36933. let hasHMR = false;
  36934. let isSelfAccepting = false;
  36935. let hasEnv = false;
  36936. let needQueryInjectHelper = false;
  36937. let s;
  36938. const str = () => s || (s = new MagicString(source));
  36939. let isPartiallySelfAccepting = false;
  36940. const importedBindings = enablePartialAccept ? /* @__PURE__ */ new Map() : null;
  36941. const toAbsoluteUrl = (url) => path$b.posix.resolve(path$b.posix.dirname(importerModule.url), url);
  36942. const normalizeUrl = async (url, pos, forceSkipImportAnalysis = false) => {
  36943. url = stripBase(url, base);
  36944. let importerFile = importer;
  36945. if (depsOptimizer && moduleListContains(depsOptimizer.options.exclude, url)) {
  36946. await depsOptimizer.scanProcessing;
  36947. for (const optimizedModule of depsOptimizer.metadata.depInfoList) {
  36948. if (!optimizedModule.src) continue;
  36949. if (optimizedModule.file === importerModule.file) {
  36950. importerFile = optimizedModule.src;
  36951. }
  36952. }
  36953. }
  36954. const resolved = await this.resolve(url, importerFile).catch((e) => {
  36955. if (e instanceof Error) {
  36956. e.pos ??= pos;
  36957. }
  36958. throw e;
  36959. });
  36960. if (!resolved || resolved.meta?.["vite:alias"]?.noResolved) {
  36961. if (ssr) {
  36962. return [url, null];
  36963. }
  36964. importerModule.isSelfAccepting = false;
  36965. moduleGraph._hasResolveFailedErrorModules.add(importerModule);
  36966. return this.error(
  36967. `Failed to resolve import "${url}" from "${normalizePath$3(
  36968. path$b.relative(process.cwd(), importerFile)
  36969. )}". Does the file exist?`,
  36970. pos
  36971. );
  36972. }
  36973. if (isExternalUrl(resolved.id)) {
  36974. return [resolved.id, resolved.id];
  36975. }
  36976. const isRelative = url[0] === ".";
  36977. const isSelfImport = !isRelative && cleanUrl(url) === cleanUrl(importer);
  36978. url = normalizeResolvedIdToUrl(environment, url, resolved);
  36979. if (environment.config.consumer === "client") {
  36980. if (isExplicitImportRequired(url)) {
  36981. url = injectQuery(url, "import");
  36982. } else if ((isRelative || isSelfImport) && !DEP_VERSION_RE.test(url)) {
  36983. const versionMatch = DEP_VERSION_RE.exec(importer);
  36984. if (versionMatch) {
  36985. url = injectQuery(url, versionMatch[1]);
  36986. }
  36987. }
  36988. }
  36989. try {
  36990. const depModule = await moduleGraph._ensureEntryFromUrl(
  36991. unwrapId$1(url),
  36992. canSkipImportAnalysis(url) || forceSkipImportAnalysis,
  36993. resolved
  36994. );
  36995. if (environment.config.consumer === "client" && depModule.lastHMRTimestamp > 0) {
  36996. url = injectQuery(url, `t=${depModule.lastHMRTimestamp}`);
  36997. }
  36998. } catch (e) {
  36999. e.pos = pos;
  37000. throw e;
  37001. }
  37002. if (!ssr) url = joinUrlSegments(base, url);
  37003. return [url, resolved.id];
  37004. };
  37005. const orderedImportedUrls = new Array(imports.length);
  37006. const orderedAcceptedUrls = new Array(
  37007. imports.length
  37008. );
  37009. const orderedAcceptedExports = new Array(
  37010. imports.length
  37011. );
  37012. await Promise.all(
  37013. imports.map(async (importSpecifier, index) => {
  37014. const {
  37015. s: start,
  37016. e: end,
  37017. ss: expStart,
  37018. se: expEnd,
  37019. d: dynamicIndex,
  37020. a: attributeIndex
  37021. } = importSpecifier;
  37022. let specifier = importSpecifier.n;
  37023. const rawUrl = source.slice(start, end);
  37024. if (rawUrl === "import.meta") {
  37025. const prop = source.slice(end, end + 4);
  37026. if (prop === ".hot") {
  37027. hasHMR = true;
  37028. const endHot = end + 4 + (source[end + 4] === "?" ? 1 : 0);
  37029. if (source.slice(endHot, endHot + 7) === ".accept") {
  37030. if (source.slice(endHot, endHot + 14) === ".acceptExports") {
  37031. const importAcceptedExports = orderedAcceptedExports[index] = /* @__PURE__ */ new Set();
  37032. lexAcceptedHmrExports(
  37033. source,
  37034. source.indexOf("(", endHot + 14) + 1,
  37035. importAcceptedExports
  37036. );
  37037. isPartiallySelfAccepting = true;
  37038. } else {
  37039. const importAcceptedUrls = orderedAcceptedUrls[index] = /* @__PURE__ */ new Set();
  37040. if (lexAcceptedHmrDeps(
  37041. source,
  37042. source.indexOf("(", endHot + 7) + 1,
  37043. importAcceptedUrls
  37044. )) {
  37045. isSelfAccepting = true;
  37046. }
  37047. }
  37048. }
  37049. } else if (prop === ".env") {
  37050. hasEnv = true;
  37051. }
  37052. return;
  37053. } else if (templateLiteralRE.test(rawUrl)) {
  37054. if (!(rawUrl.includes("${") && rawUrl.includes("}"))) {
  37055. specifier = rawUrl.replace(templateLiteralRE, "$1");
  37056. }
  37057. }
  37058. const isDynamicImport = dynamicIndex > -1;
  37059. if (!isDynamicImport && attributeIndex > -1) {
  37060. str().remove(end + 1, expEnd);
  37061. }
  37062. if (specifier !== void 0) {
  37063. if (isExternalUrl(specifier) && !specifier.startsWith("file://") || isDataUrl(specifier)) {
  37064. return;
  37065. }
  37066. if (ssr && !matchAlias(specifier)) {
  37067. if (shouldExternalize(environment, specifier, importer)) {
  37068. return;
  37069. }
  37070. if (isBuiltin(environment.config.resolve.builtins, specifier)) {
  37071. return;
  37072. }
  37073. }
  37074. if (specifier === clientPublicPath) {
  37075. return;
  37076. }
  37077. if (specifier[0] === "/" && !(config.assetsInclude(cleanUrl(specifier)) || urlRE$1.test(specifier)) && checkPublicFile(specifier, config)) {
  37078. throw new Error(
  37079. `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(
  37080. specifier,
  37081. "url"
  37082. )} instead.`
  37083. );
  37084. }
  37085. let [url, resolvedId] = await normalizeUrl(specifier, start);
  37086. resolvedId = resolvedId || url;
  37087. config.safeModulePaths.add(fsPathFromUrl(stripBase(url, base)));
  37088. if (url !== specifier) {
  37089. let rewriteDone = false;
  37090. if (depsOptimizer?.isOptimizedDepFile(resolvedId) && !optimizedDepChunkRE.test(resolvedId)) {
  37091. const file = cleanUrl(resolvedId);
  37092. const needsInterop = await optimizedDepNeedsInterop(
  37093. environment,
  37094. depsOptimizer.metadata,
  37095. file
  37096. );
  37097. if (needsInterop === void 0) {
  37098. if (!optimizedDepDynamicRE.test(file)) {
  37099. config.logger.error(
  37100. colors$1.red(
  37101. `Vite Error, ${url} optimized info should be defined`
  37102. )
  37103. );
  37104. }
  37105. } else if (needsInterop) {
  37106. debug$2?.(`${url} needs interop`);
  37107. interopNamedImports(
  37108. str(),
  37109. importSpecifier,
  37110. url,
  37111. index,
  37112. importer,
  37113. config
  37114. );
  37115. rewriteDone = true;
  37116. }
  37117. } else if (url.includes(browserExternalId) && source.slice(expStart, start).includes("{")) {
  37118. interopNamedImports(
  37119. str(),
  37120. importSpecifier,
  37121. url,
  37122. index,
  37123. importer,
  37124. config
  37125. );
  37126. rewriteDone = true;
  37127. }
  37128. if (!rewriteDone) {
  37129. const rewrittenUrl = JSON.stringify(url);
  37130. const s2 = isDynamicImport ? start : start - 1;
  37131. const e = isDynamicImport ? end : end + 1;
  37132. str().overwrite(s2, e, rewrittenUrl, {
  37133. contentOnly: true
  37134. });
  37135. }
  37136. }
  37137. const hmrUrl = unwrapId$1(stripBase(url, base));
  37138. const isLocalImport = !isExternalUrl(hmrUrl) && !isDataUrl(hmrUrl);
  37139. if (isLocalImport) {
  37140. orderedImportedUrls[index] = hmrUrl;
  37141. }
  37142. if (enablePartialAccept && importedBindings) {
  37143. extractImportedBindings(
  37144. resolvedId,
  37145. source,
  37146. importSpecifier,
  37147. importedBindings
  37148. );
  37149. }
  37150. if (!isDynamicImport && isLocalImport && environment.config.dev.preTransformRequests) {
  37151. const url2 = removeImportQuery(hmrUrl);
  37152. environment.warmupRequest(url2);
  37153. }
  37154. } else if (!importer.startsWith(withTrailingSlash(clientDir))) {
  37155. if (!isInNodeModules$1(importer)) {
  37156. const hasViteIgnore = hasViteIgnoreRE.test(
  37157. // complete expression inside parens
  37158. source.slice(dynamicIndex + 1, end)
  37159. );
  37160. if (!hasViteIgnore) {
  37161. this.warn(
  37162. `
  37163. ` + colors$1.cyan(importerModule.file) + `
  37164. ` + colors$1.reset(generateCodeFrame(source, start, end)) + colors$1.yellow(
  37165. `
  37166. The above dynamic import cannot be analyzed by Vite.
  37167. See ${colors$1.blue(
  37168. `https://github.com/rollup/plugins/tree/master/packages/dynamic-import-vars#limitations`
  37169. )} 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.
  37170. `
  37171. )
  37172. );
  37173. }
  37174. }
  37175. if (!ssr) {
  37176. if (!urlIsStringRE.test(rawUrl) || isExplicitImportRequired(rawUrl.slice(1, -1))) {
  37177. needQueryInjectHelper = true;
  37178. str().overwrite(
  37179. start,
  37180. end,
  37181. `__vite__injectQuery(${rawUrl}, 'import')`,
  37182. { contentOnly: true }
  37183. );
  37184. }
  37185. }
  37186. }
  37187. })
  37188. );
  37189. const _orderedImportedUrls = orderedImportedUrls.filter(isDefined);
  37190. const importedUrls = new Set(_orderedImportedUrls);
  37191. const staticImportedUrls = new Set(
  37192. _orderedImportedUrls.map((url) => removeTimestampQuery(url))
  37193. );
  37194. const acceptedUrls = mergeAcceptedUrls(orderedAcceptedUrls);
  37195. const acceptedExports = mergeAcceptedUrls(orderedAcceptedExports);
  37196. const isClassicWorker = importer.includes(WORKER_FILE_ID) && importer.includes("type=classic");
  37197. if (hasEnv && !isClassicWorker) {
  37198. str().prepend(getEnv(ssr));
  37199. }
  37200. if (hasHMR && !ssr && !isClassicWorker) {
  37201. debugHmr?.(
  37202. `${isSelfAccepting ? `[self-accepts]` : isPartiallySelfAccepting ? `[accepts-exports]` : acceptedUrls.size ? `[accepts-deps]` : `[detected api usage]`} ${prettifyUrl(importer, root)}`
  37203. );
  37204. str().prepend(
  37205. `import { createHotContext as __vite__createHotContext } from "${clientPublicPath}";import.meta.hot = __vite__createHotContext(${JSON.stringify(
  37206. normalizeHmrUrl(importerModule.url)
  37207. )});`
  37208. );
  37209. }
  37210. if (needQueryInjectHelper) {
  37211. if (isClassicWorker) {
  37212. str().append("\n" + __vite__injectQuery.toString());
  37213. } else {
  37214. str().prepend(
  37215. `import { injectQuery as __vite__injectQuery } from "${clientPublicPath}";`
  37216. );
  37217. }
  37218. }
  37219. const normalizedAcceptedUrls = /* @__PURE__ */ new Set();
  37220. for (const { url, start, end } of acceptedUrls) {
  37221. let [normalized, resolvedId] = await normalizeUrl(url, start).catch(
  37222. () => []
  37223. );
  37224. if (resolvedId) {
  37225. const mod = moduleGraph.getModuleById(resolvedId);
  37226. if (!mod) {
  37227. this.error(
  37228. `module was not found for ${JSON.stringify(resolvedId)}`,
  37229. start
  37230. );
  37231. return;
  37232. }
  37233. normalized = mod.url;
  37234. } else {
  37235. try {
  37236. const [resolved] = await moduleGraph.resolveUrl(toAbsoluteUrl(url));
  37237. normalized = resolved;
  37238. if (resolved) {
  37239. this.warn({
  37240. message: `Failed to resolve ${JSON.stringify(url)} from ${importer}. An id should be written. Did you pass a URL?`,
  37241. pos: start
  37242. });
  37243. }
  37244. } catch {
  37245. this.error(`Failed to resolve ${JSON.stringify(url)}`, start);
  37246. return;
  37247. }
  37248. }
  37249. normalizedAcceptedUrls.add(normalized);
  37250. const hmrAccept = normalizeHmrUrl(normalized);
  37251. str().overwrite(start, end, JSON.stringify(hmrAccept), {
  37252. contentOnly: true
  37253. });
  37254. }
  37255. if (!isCSSRequest(importer) || SPECIAL_QUERY_RE.test(importer)) {
  37256. const pluginImports = this._addedImports;
  37257. if (pluginImports) {
  37258. (await Promise.all(
  37259. [...pluginImports].map((id) => normalizeUrl(id, 0, true))
  37260. )).forEach(([url]) => importedUrls.add(stripBase(url, base)));
  37261. }
  37262. if (ssr && importerModule.isSelfAccepting) {
  37263. isSelfAccepting = true;
  37264. }
  37265. if (!isSelfAccepting && isPartiallySelfAccepting && acceptedExports.size >= exports.length && exports.every((e) => acceptedExports.has(e.n))) {
  37266. isSelfAccepting = true;
  37267. }
  37268. const prunedImports = await moduleGraph.updateModuleInfo(
  37269. importerModule,
  37270. importedUrls,
  37271. importedBindings,
  37272. normalizedAcceptedUrls,
  37273. isPartiallySelfAccepting ? acceptedExports : null,
  37274. isSelfAccepting,
  37275. staticImportedUrls
  37276. );
  37277. if (hasHMR && prunedImports) {
  37278. handlePrunedModules(prunedImports, environment);
  37279. }
  37280. }
  37281. debug$2?.(
  37282. `${timeFrom(msAtStart)} ${colors$1.dim(
  37283. `[${importedUrls.size} imports rewritten] ${prettifyUrl(
  37284. importer,
  37285. root
  37286. )}`
  37287. )}`
  37288. );
  37289. if (s) {
  37290. return transformStableResult(s, importer, config);
  37291. } else {
  37292. return source;
  37293. }
  37294. }
  37295. };
  37296. }
  37297. function mergeAcceptedUrls(orderedUrls) {
  37298. const acceptedUrls = /* @__PURE__ */ new Set();
  37299. for (const urls of orderedUrls) {
  37300. if (!urls) continue;
  37301. for (const url of urls) acceptedUrls.add(url);
  37302. }
  37303. return acceptedUrls;
  37304. }
  37305. function createParseErrorInfo(importer, source) {
  37306. const isVue = importer.endsWith(".vue");
  37307. const isJsx = importer.endsWith(".jsx") || importer.endsWith(".tsx");
  37308. const maybeJSX = !isVue && isJSRequest(importer);
  37309. const probablyBinary = source.includes(
  37310. "\uFFFD"
  37311. );
  37312. const msg = 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$b.extname(
  37313. importer
  37314. )} file format, or if it's an asset, add "**/*${path$b.extname(
  37315. importer
  37316. )}" to \`assetsInclude\` in your configuration.`;
  37317. return {
  37318. message: `Failed to parse source for import analysis because the content contains invalid JS syntax. ` + msg,
  37319. showCodeFrame: !probablyBinary
  37320. };
  37321. }
  37322. const interopHelper = (m) => m?.__esModule ? m : { ...typeof m === "object" && !Array.isArray(m) || typeof m === "function" ? m : {}, default: m };
  37323. function interopNamedImports(str, importSpecifier, rewrittenUrl, importIndex, importer, config) {
  37324. const source = str.original;
  37325. const {
  37326. s: start,
  37327. e: end,
  37328. ss: expStart,
  37329. se: expEnd,
  37330. d: dynamicIndex
  37331. } = importSpecifier;
  37332. const exp = source.slice(expStart, expEnd);
  37333. if (dynamicIndex > -1) {
  37334. str.overwrite(
  37335. expStart,
  37336. expEnd,
  37337. `import('${rewrittenUrl}').then(m => (${interopHelper.toString()})(m.default))` + getLineBreaks(exp),
  37338. { contentOnly: true }
  37339. );
  37340. } else {
  37341. const rawUrl = source.slice(start, end);
  37342. const rewritten = transformCjsImport(
  37343. exp,
  37344. rewrittenUrl,
  37345. rawUrl,
  37346. importIndex,
  37347. importer,
  37348. config
  37349. );
  37350. if (rewritten) {
  37351. str.overwrite(expStart, expEnd, rewritten + getLineBreaks(exp), {
  37352. contentOnly: true
  37353. });
  37354. } else {
  37355. str.overwrite(
  37356. start,
  37357. end,
  37358. rewrittenUrl + getLineBreaks(source.slice(start, end)),
  37359. {
  37360. contentOnly: true
  37361. }
  37362. );
  37363. }
  37364. }
  37365. }
  37366. function getLineBreaks(str) {
  37367. return str.includes("\n") ? "\n".repeat(str.split("\n").length - 1) : "";
  37368. }
  37369. function transformCjsImport(importExp, url, rawUrl, importIndex, importer, config) {
  37370. const node = parseAst(importExp).body[0];
  37371. if (config.command === "serve" && node.type === "ExportAllDeclaration" && !node.exported) {
  37372. config.logger.warn(
  37373. colors$1.yellow(
  37374. `
  37375. Unable 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}"\``
  37376. )
  37377. );
  37378. } else if (node.type === "ImportDeclaration" || node.type === "ExportNamedDeclaration") {
  37379. if (!node.specifiers.length) {
  37380. return `import "${url}"`;
  37381. }
  37382. const importNames = [];
  37383. const exportNames = [];
  37384. let defaultExports = "";
  37385. for (const spec of node.specifiers) {
  37386. if (spec.type === "ImportSpecifier") {
  37387. const importedName = getIdentifierNameOrLiteralValue(
  37388. spec.imported
  37389. );
  37390. const localName = spec.local.name;
  37391. importNames.push({ importedName, localName });
  37392. } else if (spec.type === "ImportDefaultSpecifier") {
  37393. importNames.push({
  37394. importedName: "default",
  37395. localName: spec.local.name
  37396. });
  37397. } else if (spec.type === "ImportNamespaceSpecifier") {
  37398. importNames.push({ importedName: "*", localName: spec.local.name });
  37399. } else if (spec.type === "ExportSpecifier") {
  37400. const importedName = getIdentifierNameOrLiteralValue(
  37401. spec.local
  37402. );
  37403. const exportedName = getIdentifierNameOrLiteralValue(
  37404. spec.exported
  37405. );
  37406. if (exportedName === "default") {
  37407. defaultExports = makeLegalIdentifier(
  37408. `__vite__cjsExportDefault_${importIndex}`
  37409. );
  37410. importNames.push({ importedName, localName: defaultExports });
  37411. } else {
  37412. const localName = `__vite__cjsExport${spec.exported.type === "Literal" ? `L_${getHash(spec.exported.value)}` : "I_" + spec.exported.name}`;
  37413. importNames.push({ importedName, localName });
  37414. exportNames.push(
  37415. `${localName} as ${spec.exported.type === "Literal" ? JSON.stringify(exportedName) : exportedName}`
  37416. );
  37417. }
  37418. }
  37419. }
  37420. const cjsModuleName = makeLegalIdentifier(
  37421. `__vite__cjsImport${importIndex}_${rawUrl}`
  37422. );
  37423. const lines = [`import ${cjsModuleName} from "${url}"`];
  37424. importNames.forEach(({ importedName, localName }) => {
  37425. if (importedName === "*") {
  37426. lines.push(
  37427. `const ${localName} = (${interopHelper.toString()})(${cjsModuleName})`
  37428. );
  37429. } else if (importedName === "default") {
  37430. lines.push(
  37431. `const ${localName} = ${cjsModuleName}.__esModule ? ${cjsModuleName}.default : ${cjsModuleName}`
  37432. );
  37433. } else {
  37434. lines.push(`const ${localName} = ${cjsModuleName}["${importedName}"]`);
  37435. }
  37436. });
  37437. if (defaultExports) {
  37438. lines.push(`export default ${defaultExports}`);
  37439. }
  37440. if (exportNames.length) {
  37441. lines.push(`export { ${exportNames.join(", ")} }`);
  37442. }
  37443. return lines.join("; ");
  37444. }
  37445. }
  37446. function getIdentifierNameOrLiteralValue(node) {
  37447. return node.type === "Identifier" ? node.name : node.value;
  37448. }
  37449. function __vite__injectQuery(url, queryToInject) {
  37450. if (url[0] !== "." && url[0] !== "/") {
  37451. return url;
  37452. }
  37453. const pathname = url.replace(/[?#].*$/, "");
  37454. const { search, hash } = new URL(url, "http://vite.dev");
  37455. return `${pathname}?${queryToInject}${search ? `&` + search.slice(1) : ""}${hash || ""}`;
  37456. }
  37457. const normalizedClientEntry = normalizePath$3(CLIENT_ENTRY);
  37458. const normalizedEnvEntry = normalizePath$3(ENV_ENTRY);
  37459. function clientInjectionsPlugin(config) {
  37460. let injectConfigValues;
  37461. const getDefineReplacer = perEnvironmentState((environment) => {
  37462. const userDefine = {};
  37463. for (const key in environment.config.define) {
  37464. if (!key.startsWith("import.meta.env.")) {
  37465. userDefine[key] = environment.config.define[key];
  37466. }
  37467. }
  37468. const serializedDefines = serializeDefine(userDefine);
  37469. const definesReplacement = () => serializedDefines;
  37470. return (code) => code.replace(`__DEFINES__`, definesReplacement);
  37471. });
  37472. return {
  37473. name: "vite:client-inject",
  37474. async buildStart() {
  37475. const resolvedServerHostname = (await resolveHostname(config.server.host)).name;
  37476. const resolvedServerPort = config.server.port;
  37477. const devBase = config.base;
  37478. const serverHost = `${resolvedServerHostname}:${resolvedServerPort}${devBase}`;
  37479. let hmrConfig = config.server.hmr;
  37480. hmrConfig = isObject$1(hmrConfig) ? hmrConfig : void 0;
  37481. const host = hmrConfig?.host || null;
  37482. const protocol = hmrConfig?.protocol || null;
  37483. const timeout = hmrConfig?.timeout || 3e4;
  37484. const overlay = hmrConfig?.overlay !== false;
  37485. const isHmrServerSpecified = !!hmrConfig?.server;
  37486. const hmrConfigName = path$b.basename(config.configFile || "vite.config.js");
  37487. let port = hmrConfig?.clientPort || hmrConfig?.port || null;
  37488. if (config.server.middlewareMode && !isHmrServerSpecified) {
  37489. port ||= 24678;
  37490. }
  37491. let directTarget = hmrConfig?.host || resolvedServerHostname;
  37492. directTarget += `:${hmrConfig?.port || resolvedServerPort}`;
  37493. directTarget += devBase;
  37494. let hmrBase = devBase;
  37495. if (hmrConfig?.path) {
  37496. hmrBase = path$b.posix.join(hmrBase, hmrConfig.path);
  37497. }
  37498. const modeReplacement = escapeReplacement(config.mode);
  37499. const baseReplacement = escapeReplacement(devBase);
  37500. const serverHostReplacement = escapeReplacement(serverHost);
  37501. const hmrProtocolReplacement = escapeReplacement(protocol);
  37502. const hmrHostnameReplacement = escapeReplacement(host);
  37503. const hmrPortReplacement = escapeReplacement(port);
  37504. const hmrDirectTargetReplacement = escapeReplacement(directTarget);
  37505. const hmrBaseReplacement = escapeReplacement(hmrBase);
  37506. const hmrTimeoutReplacement = escapeReplacement(timeout);
  37507. const hmrEnableOverlayReplacement = escapeReplacement(overlay);
  37508. const hmrConfigNameReplacement = escapeReplacement(hmrConfigName);
  37509. const wsTokenReplacement = escapeReplacement(config.webSocketToken);
  37510. injectConfigValues = (code) => {
  37511. return 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);
  37512. };
  37513. },
  37514. async transform(code, id, options) {
  37515. const ssr = options?.ssr ?? this.environment.config.consumer === "server";
  37516. if (id === normalizedClientEntry || id === normalizedEnvEntry) {
  37517. const defineReplacer = getDefineReplacer(this);
  37518. return defineReplacer(injectConfigValues(code));
  37519. } else if (!ssr && code.includes("process.env.NODE_ENV")) {
  37520. const nodeEnv = this.environment.config.define?.["process.env.NODE_ENV"] || JSON.stringify(process.env.NODE_ENV || config.mode);
  37521. return await replaceDefine(this.environment, code, id, {
  37522. "process.env.NODE_ENV": nodeEnv,
  37523. "global.process.env.NODE_ENV": nodeEnv,
  37524. "globalThis.process.env.NODE_ENV": nodeEnv
  37525. });
  37526. }
  37527. }
  37528. };
  37529. }
  37530. function escapeReplacement(value) {
  37531. const jsonValue = JSON.stringify(value);
  37532. return () => jsonValue;
  37533. }
  37534. const wasmHelperId = "\0vite/wasm-helper.js";
  37535. const wasmInitRE = /(?<![?#].*)\.wasm\?init/;
  37536. const wasmHelper = async (opts = {}, url) => {
  37537. let result;
  37538. if (url.startsWith("data:")) {
  37539. const urlContent = url.replace(/^data:.*?base64,/, "");
  37540. let bytes;
  37541. if (typeof Buffer === "function" && typeof Buffer.from === "function") {
  37542. bytes = Buffer.from(urlContent, "base64");
  37543. } else if (typeof atob === "function") {
  37544. const binaryString = atob(urlContent);
  37545. bytes = new Uint8Array(binaryString.length);
  37546. for (let i = 0; i < binaryString.length; i++) {
  37547. bytes[i] = binaryString.charCodeAt(i);
  37548. }
  37549. } else {
  37550. throw new Error(
  37551. "Failed to decode base64-encoded data URL, Buffer and atob are not supported"
  37552. );
  37553. }
  37554. result = await WebAssembly.instantiate(bytes, opts);
  37555. } else {
  37556. const response = await fetch(url);
  37557. const contentType = response.headers.get("Content-Type") || "";
  37558. if ("instantiateStreaming" in WebAssembly && contentType.startsWith("application/wasm")) {
  37559. result = await WebAssembly.instantiateStreaming(response, opts);
  37560. } else {
  37561. const buffer = await response.arrayBuffer();
  37562. result = await WebAssembly.instantiate(buffer, opts);
  37563. }
  37564. }
  37565. return result.instance;
  37566. };
  37567. const wasmHelperCode = wasmHelper.toString();
  37568. const wasmHelperPlugin = () => {
  37569. return {
  37570. name: "vite:wasm-helper",
  37571. resolveId: {
  37572. handler(id) {
  37573. if (id === wasmHelperId) {
  37574. return id;
  37575. }
  37576. }
  37577. },
  37578. load: {
  37579. async handler(id) {
  37580. if (id === wasmHelperId) {
  37581. return `export default ${wasmHelperCode}`;
  37582. }
  37583. if (!wasmInitRE.test(id)) {
  37584. return;
  37585. }
  37586. const url = await fileToUrl$1(this, id);
  37587. return `
  37588. import initWasm from "${wasmHelperId}"
  37589. export default opts => initWasm(opts, ${JSON.stringify(url)})
  37590. `;
  37591. }
  37592. }
  37593. };
  37594. };
  37595. const wasmFallbackPlugin = () => {
  37596. return {
  37597. name: "vite:wasm-fallback",
  37598. load: {
  37599. handler(id) {
  37600. if (!id.endsWith(".wasm")) {
  37601. return;
  37602. }
  37603. throw new Error(
  37604. '"ESM integration proposal for Wasm" is not supported currently. Use vite-plugin-wasm or other community plugins to handle this. Alternatively, you can use `.wasm?init` or `.wasm?url`. See https://vite.dev/guide/features.html#webassembly for more details.'
  37605. );
  37606. }
  37607. }
  37608. };
  37609. };
  37610. function err(e, pos) {
  37611. const error = new Error(e);
  37612. error.pos = pos;
  37613. return error;
  37614. }
  37615. function findClosingParen(input, fromIndex) {
  37616. let count = 1;
  37617. for (let i = fromIndex; i < input.length; i++) {
  37618. if (input[i] === "(") count++;
  37619. if (input[i] === ")") count--;
  37620. if (count === 0) return i;
  37621. }
  37622. return -1;
  37623. }
  37624. function extractWorkerTypeFromAst(expression, optsStartIndex) {
  37625. if (expression.type !== "ObjectExpression") {
  37626. return;
  37627. }
  37628. let lastSpreadElementIndex = -1;
  37629. let typeProperty = null;
  37630. let typePropertyIndex = -1;
  37631. for (let i = 0; i < expression.properties.length; i++) {
  37632. const property = expression.properties[i];
  37633. if (property.type === "SpreadElement") {
  37634. lastSpreadElementIndex = i;
  37635. continue;
  37636. }
  37637. if (property.type === "Property" && (property.key.type === "Identifier" && property.key.name === "type" || property.key.type === "Literal" && property.key.value === "type")) {
  37638. typeProperty = property;
  37639. typePropertyIndex = i;
  37640. }
  37641. }
  37642. if (typePropertyIndex === -1 && lastSpreadElementIndex === -1) {
  37643. return "classic";
  37644. }
  37645. if (typePropertyIndex < lastSpreadElementIndex) {
  37646. throw err(
  37647. "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.",
  37648. optsStartIndex
  37649. );
  37650. }
  37651. if (typeProperty?.value.type !== "Literal") {
  37652. throw err(
  37653. "Expected worker options type property to be a literal value.",
  37654. optsStartIndex
  37655. );
  37656. }
  37657. return typeProperty?.value.value === "module" ? "module" : "classic";
  37658. }
  37659. async function parseWorkerOptions(rawOpts, optsStartIndex) {
  37660. let opts = {};
  37661. try {
  37662. opts = evalValue(rawOpts);
  37663. } catch {
  37664. const optsNode = (await parseAstAsync(`(${rawOpts})`)).body[0].expression;
  37665. const type = extractWorkerTypeFromAst(optsNode, optsStartIndex);
  37666. if (type) {
  37667. return { type };
  37668. }
  37669. throw err(
  37670. "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.",
  37671. optsStartIndex
  37672. );
  37673. }
  37674. if (opts == null) {
  37675. return {};
  37676. }
  37677. if (typeof opts !== "object") {
  37678. throw err(
  37679. `Expected worker options to be an object, got ${typeof opts}`,
  37680. optsStartIndex
  37681. );
  37682. }
  37683. return opts;
  37684. }
  37685. async function getWorkerType(raw, clean, i) {
  37686. const commaIndex = clean.indexOf(",", i);
  37687. if (commaIndex === -1) {
  37688. return "classic";
  37689. }
  37690. const endIndex = findClosingParen(clean, i);
  37691. if (commaIndex > endIndex) {
  37692. return "classic";
  37693. }
  37694. let workerOptString = raw.substring(commaIndex + 1, endIndex);
  37695. const hasViteIgnore = hasViteIgnoreRE.test(workerOptString);
  37696. if (hasViteIgnore) {
  37697. return "ignore";
  37698. }
  37699. const cleanWorkerOptString = clean.substring(commaIndex + 1, endIndex);
  37700. const trimmedCleanWorkerOptString = cleanWorkerOptString.trim();
  37701. if (!trimmedCleanWorkerOptString.length) {
  37702. return "classic";
  37703. }
  37704. if (trimmedCleanWorkerOptString.endsWith(",")) {
  37705. workerOptString = workerOptString.slice(
  37706. 0,
  37707. cleanWorkerOptString.lastIndexOf(",")
  37708. );
  37709. }
  37710. const workerOpts = await parseWorkerOptions(workerOptString, commaIndex + 1);
  37711. if (workerOpts.type && (workerOpts.type === "module" || workerOpts.type === "classic")) {
  37712. return workerOpts.type;
  37713. }
  37714. return "classic";
  37715. }
  37716. function isIncludeWorkerImportMetaUrl(code) {
  37717. if ((code.includes("new Worker") || code.includes("new SharedWorker")) && code.includes("new URL") && code.includes(`import.meta.url`)) {
  37718. return true;
  37719. }
  37720. return false;
  37721. }
  37722. function workerImportMetaUrlPlugin(config) {
  37723. const isBuild = config.command === "build";
  37724. let workerResolver;
  37725. const fsResolveOptions = {
  37726. ...config.resolve,
  37727. root: config.root,
  37728. isProduction: config.isProduction,
  37729. isBuild: config.command === "build",
  37730. packageCache: config.packageCache,
  37731. asSrc: true
  37732. };
  37733. return {
  37734. name: "vite:worker-import-meta-url",
  37735. applyToEnvironment(environment) {
  37736. return environment.config.consumer === "client";
  37737. },
  37738. shouldTransformCachedModule({ code }) {
  37739. if (isBuild && config.build.watch && isIncludeWorkerImportMetaUrl(code)) {
  37740. return true;
  37741. }
  37742. },
  37743. transform: {
  37744. async handler(code, id) {
  37745. if (isIncludeWorkerImportMetaUrl(code)) {
  37746. let s;
  37747. const cleanString = stripLiteral(code);
  37748. const workerImportMetaUrlRE = /\bnew\s+(?:Worker|SharedWorker)\s*\(\s*(new\s+URL\s*\(\s*('[^']+'|"[^"]+"|`[^`]+`)\s*,\s*import\.meta\.url\s*\))/dg;
  37749. let match;
  37750. while (match = workerImportMetaUrlRE.exec(cleanString)) {
  37751. const [[, endIndex], [expStart, expEnd], [urlStart, urlEnd]] = match.indices;
  37752. const rawUrl = code.slice(urlStart, urlEnd);
  37753. if (rawUrl[0] === "`" && rawUrl.includes("${")) {
  37754. this.error(
  37755. `\`new URL(url, import.meta.url)\` is not supported in dynamic template string.`,
  37756. expStart
  37757. );
  37758. }
  37759. s ||= new MagicString(code);
  37760. const workerType = await getWorkerType(code, cleanString, endIndex);
  37761. const url = rawUrl.slice(1, -1);
  37762. let file;
  37763. if (url[0] === ".") {
  37764. file = path$b.resolve(path$b.dirname(id), url);
  37765. file = slash$1(tryFsResolve(file, fsResolveOptions) ?? file);
  37766. } else {
  37767. workerResolver ??= createBackCompatIdResolver(config, {
  37768. extensions: [],
  37769. tryIndex: false,
  37770. preferRelative: true
  37771. });
  37772. file = await workerResolver(this.environment, url, id);
  37773. file ??= url[0] === "/" ? slash$1(path$b.join(config.publicDir, url)) : slash$1(path$b.resolve(path$b.dirname(id), url));
  37774. }
  37775. if (isBuild && config.isWorker && config.bundleChain.at(-1) === cleanUrl(file)) {
  37776. s.update(expStart, expEnd, "self.location.href");
  37777. } else {
  37778. let builtUrl;
  37779. if (isBuild) {
  37780. builtUrl = await workerFileToUrl(config, file);
  37781. } else {
  37782. builtUrl = await fileToUrl$1(this, cleanUrl(file));
  37783. builtUrl = injectQuery(
  37784. builtUrl,
  37785. `${WORKER_FILE_ID}&type=${workerType}`
  37786. );
  37787. }
  37788. s.update(
  37789. expStart,
  37790. expEnd,
  37791. `new URL(/* @vite-ignore */ ${JSON.stringify(builtUrl)}, import.meta.url)`
  37792. );
  37793. }
  37794. }
  37795. if (s) {
  37796. return transformStableResult(s, id, config);
  37797. }
  37798. return null;
  37799. }
  37800. }
  37801. }
  37802. };
  37803. }
  37804. function assetImportMetaUrlPlugin(config) {
  37805. const { publicDir } = config;
  37806. let assetResolver;
  37807. const fsResolveOptions = {
  37808. ...config.resolve,
  37809. root: config.root,
  37810. isProduction: config.isProduction,
  37811. isBuild: config.command === "build",
  37812. packageCache: config.packageCache,
  37813. asSrc: true
  37814. };
  37815. return {
  37816. name: "vite:asset-import-meta-url",
  37817. applyToEnvironment(environment) {
  37818. return environment.config.consumer === "client";
  37819. },
  37820. transform: {
  37821. async handler(code, id) {
  37822. if (id !== preloadHelperId && id !== CLIENT_ENTRY && code.includes("new URL") && code.includes(`import.meta.url`)) {
  37823. let s;
  37824. const assetImportMetaUrlRE = /\bnew\s+URL\s*\(\s*('[^']+'|"[^"]+"|`[^`]+`)\s*,\s*import\.meta\.url\s*(?:,\s*)?\)/dg;
  37825. const cleanString = stripLiteral(code);
  37826. let match;
  37827. while (match = assetImportMetaUrlRE.exec(cleanString)) {
  37828. const [[startIndex, endIndex], [urlStart, urlEnd]] = match.indices;
  37829. if (hasViteIgnoreRE.test(code.slice(startIndex, urlStart))) continue;
  37830. const rawUrl = code.slice(urlStart, urlEnd);
  37831. if (!s) s = new MagicString(code);
  37832. if (rawUrl[0] === "`" && rawUrl.includes("${")) {
  37833. const queryDelimiterIndex = getQueryDelimiterIndex(rawUrl);
  37834. const hasQueryDelimiter = queryDelimiterIndex !== -1;
  37835. const pureUrl = hasQueryDelimiter ? rawUrl.slice(0, queryDelimiterIndex) + "`" : rawUrl;
  37836. const queryString = hasQueryDelimiter ? rawUrl.slice(queryDelimiterIndex, -1) : "";
  37837. const ast = this.parse(pureUrl);
  37838. const templateLiteral = ast.body[0].expression;
  37839. if (templateLiteral.expressions.length) {
  37840. const pattern = buildGlobPattern(templateLiteral);
  37841. if (pattern.startsWith("*")) {
  37842. continue;
  37843. }
  37844. const globOptions = {
  37845. eager: true,
  37846. import: "default",
  37847. // A hack to allow 'as' & 'query' exist at the same time
  37848. query: injectQuery(queryString, "url")
  37849. };
  37850. s.update(
  37851. startIndex,
  37852. endIndex,
  37853. `new URL((import.meta.glob(${JSON.stringify(
  37854. pattern
  37855. )}, ${JSON.stringify(
  37856. globOptions
  37857. )}))[${pureUrl}], import.meta.url)`
  37858. );
  37859. continue;
  37860. }
  37861. }
  37862. const url = rawUrl.slice(1, -1);
  37863. if (isDataUrl(url)) {
  37864. continue;
  37865. }
  37866. let file;
  37867. if (url[0] === ".") {
  37868. file = slash$1(path$b.resolve(path$b.dirname(id), url));
  37869. file = tryFsResolve(file, fsResolveOptions) ?? file;
  37870. } else {
  37871. assetResolver ??= createBackCompatIdResolver(config, {
  37872. extensions: [],
  37873. mainFields: [],
  37874. tryIndex: false,
  37875. preferRelative: true
  37876. });
  37877. file = await assetResolver(this.environment, url, id);
  37878. file ??= url[0] === "/" ? slash$1(path$b.join(publicDir, url)) : slash$1(path$b.resolve(path$b.dirname(id), url));
  37879. }
  37880. let builtUrl;
  37881. if (file) {
  37882. try {
  37883. if (publicDir && isParentDirectory(publicDir, file)) {
  37884. const publicPath = "/" + path$b.posix.relative(publicDir, file);
  37885. builtUrl = await fileToUrl$1(this, publicPath);
  37886. } else {
  37887. builtUrl = await fileToUrl$1(this, file);
  37888. }
  37889. } catch {
  37890. }
  37891. }
  37892. if (!builtUrl) {
  37893. const rawExp = code.slice(startIndex, endIndex);
  37894. config.logger.warnOnce(
  37895. `
  37896. ${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.`
  37897. );
  37898. builtUrl = url;
  37899. }
  37900. s.update(
  37901. startIndex,
  37902. endIndex,
  37903. `new URL(${JSON.stringify(builtUrl)}, import.meta.url)`
  37904. );
  37905. }
  37906. if (s) {
  37907. return transformStableResult(s, id, config);
  37908. }
  37909. }
  37910. return null;
  37911. }
  37912. }
  37913. };
  37914. }
  37915. function buildGlobPattern(ast) {
  37916. let pattern = "";
  37917. let lastIsGlob = false;
  37918. for (let i = 0; i < ast.quasis.length; i++) {
  37919. const str = ast.quasis[i].value.raw;
  37920. if (str) {
  37921. pattern += str;
  37922. lastIsGlob = false;
  37923. }
  37924. if (ast.expressions[i] && !lastIsGlob) {
  37925. pattern += "*";
  37926. lastIsGlob = true;
  37927. }
  37928. }
  37929. return pattern;
  37930. }
  37931. function getQueryDelimiterIndex(rawUrl) {
  37932. let bracketsStack = 0;
  37933. for (let i = 0; i < rawUrl.length; i++) {
  37934. if (rawUrl[i] === "{") {
  37935. bracketsStack++;
  37936. } else if (rawUrl[i] === "}") {
  37937. bracketsStack--;
  37938. } else if (rawUrl[i] === "?" && bracketsStack === 0) {
  37939. return i;
  37940. }
  37941. }
  37942. return -1;
  37943. }
  37944. function metadataPlugin() {
  37945. return {
  37946. name: "vite:build-metadata",
  37947. async renderChunk(_code, chunk) {
  37948. chunk.viteMetadata = {
  37949. importedAssets: /* @__PURE__ */ new Set(),
  37950. importedCss: /* @__PURE__ */ new Set()
  37951. };
  37952. return null;
  37953. }
  37954. };
  37955. }
  37956. class VariableDynamicImportError extends Error {}
  37957. /* eslint-disable-next-line no-template-curly-in-string */
  37958. const example = 'For example: import(`./foo/${bar}.js`).';
  37959. function sanitizeString(str) {
  37960. if (str === '') return str;
  37961. if (str.includes('*')) {
  37962. throw new VariableDynamicImportError('A dynamic import cannot contain * characters.');
  37963. }
  37964. return escapePath(str);
  37965. }
  37966. function templateLiteralToGlob(node) {
  37967. let glob = '';
  37968. for (let i = 0; i < node.quasis.length; i += 1) {
  37969. glob += sanitizeString(node.quasis[i].value.raw);
  37970. if (node.expressions[i]) {
  37971. glob += expressionToGlob(node.expressions[i]);
  37972. }
  37973. }
  37974. return glob;
  37975. }
  37976. function callExpressionToGlob(node) {
  37977. const { callee } = node;
  37978. if (
  37979. callee.type === 'MemberExpression' &&
  37980. callee.property.type === 'Identifier' &&
  37981. callee.property.name === 'concat'
  37982. ) {
  37983. return `${expressionToGlob(callee.object)}${node.arguments.map(expressionToGlob).join('')}`;
  37984. }
  37985. return '*';
  37986. }
  37987. function binaryExpressionToGlob(node) {
  37988. if (node.operator !== '+') {
  37989. throw new VariableDynamicImportError(`${node.operator} operator is not supported.`);
  37990. }
  37991. return `${expressionToGlob(node.left)}${expressionToGlob(node.right)}`;
  37992. }
  37993. function expressionToGlob(node) {
  37994. switch (node.type) {
  37995. case 'TemplateLiteral':
  37996. return templateLiteralToGlob(node);
  37997. case 'CallExpression':
  37998. return callExpressionToGlob(node);
  37999. case 'BinaryExpression':
  38000. return binaryExpressionToGlob(node);
  38001. case 'Literal': {
  38002. return sanitizeString(node.value);
  38003. }
  38004. default:
  38005. return '*';
  38006. }
  38007. }
  38008. const defaultProtocol = 'file:';
  38009. const ignoredProtocols = ['data:', 'http:', 'https:'];
  38010. function shouldIgnore(glob) {
  38011. const containsAsterisk = glob.includes('*');
  38012. const globURL = new URL(glob, defaultProtocol);
  38013. const containsIgnoredProtocol = ignoredProtocols.some(
  38014. (ignoredProtocol) => ignoredProtocol === globURL.protocol
  38015. );
  38016. return !containsAsterisk || containsIgnoredProtocol;
  38017. }
  38018. function dynamicImportToGlob(node, sourceString) {
  38019. let glob = expressionToGlob(node);
  38020. if (shouldIgnore(glob)) {
  38021. return null;
  38022. }
  38023. glob = glob.replace(/\*\*/g, '*');
  38024. if (glob.startsWith('*')) {
  38025. throw new VariableDynamicImportError(
  38026. `invalid import "${sourceString}". It cannot be statically analyzed. Variable dynamic imports must start with ./ and be limited to a specific directory. ${example}`
  38027. );
  38028. }
  38029. if (glob.startsWith('/')) {
  38030. throw new VariableDynamicImportError(
  38031. `invalid import "${sourceString}". Variable absolute imports are not supported, imports must start with ./ in the static part of the import. ${example}`
  38032. );
  38033. }
  38034. if (!glob.startsWith('./') && !glob.startsWith('../')) {
  38035. throw new VariableDynamicImportError(
  38036. `invalid import "${sourceString}". Variable bare imports are not supported, imports must start with ./ in the static part of the import. ${example}`
  38037. );
  38038. }
  38039. // Disallow ./*.ext
  38040. const ownDirectoryStarExtension = /^\.\/\*\.\w+$/;
  38041. if (ownDirectoryStarExtension.test(glob)) {
  38042. throw new VariableDynamicImportError(
  38043. `${
  38044. `invalid import "${sourceString}". Variable imports cannot import their own directory, ` +
  38045. 'place imports in a separate directory or make the import filename more specific. '
  38046. }${example}`
  38047. );
  38048. }
  38049. if (require$$0$2.extname(glob) === '') {
  38050. throw new VariableDynamicImportError(
  38051. `invalid import "${sourceString}". A file extension must be included in the static part of the import. ${example}`
  38052. );
  38053. }
  38054. return glob;
  38055. }
  38056. const dynamicImportHelperId = "\0vite/dynamic-import-helper.js";
  38057. const relativePathRE = /^\.{1,2}\//;
  38058. const hasDynamicImportRE = /\bimport\s*[(/]/;
  38059. const dynamicImportHelper = (glob, path, segs) => {
  38060. const v = glob[path];
  38061. if (v) {
  38062. return typeof v === "function" ? v() : Promise.resolve(v);
  38063. }
  38064. return new Promise((_, reject) => {
  38065. (typeof queueMicrotask === "function" ? queueMicrotask : setTimeout)(
  38066. reject.bind(
  38067. null,
  38068. new Error(
  38069. "Unknown variable dynamic import: " + path + (path.split("/").length !== segs ? ". Note that variables only represent file names one level deep." : "")
  38070. )
  38071. )
  38072. );
  38073. });
  38074. };
  38075. function parseDynamicImportPattern(strings) {
  38076. const filename = strings.slice(1, -1);
  38077. const ast = parseAst(strings).body[0].expression;
  38078. const userPatternQuery = dynamicImportToGlob(ast, filename);
  38079. if (!userPatternQuery) {
  38080. return null;
  38081. }
  38082. const [userPattern] = userPatternQuery.split(
  38083. // ? is escaped on posix OS
  38084. requestQueryMaybeEscapedSplitRE,
  38085. 2
  38086. );
  38087. let [rawPattern, search] = filename.split(requestQuerySplitRE, 2);
  38088. let globParams = null;
  38089. if (search) {
  38090. search = "?" + search;
  38091. if (workerOrSharedWorkerRE.test(search) || urlRE$1.test(search) || rawRE$1.test(search)) {
  38092. globParams = {
  38093. query: search,
  38094. import: "*"
  38095. };
  38096. } else {
  38097. globParams = {
  38098. query: search
  38099. };
  38100. }
  38101. }
  38102. return {
  38103. globParams,
  38104. userPattern,
  38105. rawPattern
  38106. };
  38107. }
  38108. async function transformDynamicImport(importSource, importer, resolve, root) {
  38109. if (importSource[1] !== "." && importSource[1] !== "/") {
  38110. const resolvedFileName = await resolve(importSource.slice(1, -1), importer);
  38111. if (!resolvedFileName) {
  38112. return null;
  38113. }
  38114. const relativeFileName = normalizePath$3(
  38115. posix$1.relative(
  38116. posix$1.dirname(normalizePath$3(importer)),
  38117. normalizePath$3(resolvedFileName)
  38118. )
  38119. );
  38120. importSource = "`" + (relativeFileName[0] === "." ? "" : "./") + relativeFileName + "`";
  38121. }
  38122. const dynamicImportPattern = parseDynamicImportPattern(importSource);
  38123. if (!dynamicImportPattern) {
  38124. return null;
  38125. }
  38126. const { globParams, rawPattern, userPattern } = dynamicImportPattern;
  38127. const params = globParams ? `, ${JSON.stringify(globParams)}` : "";
  38128. const dir = importer ? posix$1.dirname(importer) : root;
  38129. const normalized = rawPattern[0] === "/" ? posix$1.join(root, rawPattern.slice(1)) : posix$1.join(dir, rawPattern);
  38130. let newRawPattern = posix$1.relative(posix$1.dirname(importer), normalized);
  38131. if (!relativePathRE.test(newRawPattern)) {
  38132. newRawPattern = `./${newRawPattern}`;
  38133. }
  38134. const exp = `(import.meta.glob(${JSON.stringify(userPattern)}${params}))`;
  38135. return {
  38136. rawPattern: newRawPattern,
  38137. pattern: userPattern,
  38138. glob: exp
  38139. };
  38140. }
  38141. function dynamicImportVarsPlugin(config) {
  38142. const resolve = createBackCompatIdResolver(config, {
  38143. preferRelative: true,
  38144. tryIndex: false,
  38145. extensions: []
  38146. });
  38147. const getFilter = perEnvironmentState((environment) => {
  38148. const { include, exclude } = environment.config.build.dynamicImportVarsOptions;
  38149. return createFilter$1(include, exclude);
  38150. });
  38151. return {
  38152. name: "vite:dynamic-import-vars",
  38153. resolveId: {
  38154. handler(id) {
  38155. if (id === dynamicImportHelperId) {
  38156. return id;
  38157. }
  38158. }
  38159. },
  38160. load: {
  38161. handler(id) {
  38162. if (id === dynamicImportHelperId) {
  38163. return `export default ${dynamicImportHelper.toString()}`;
  38164. }
  38165. }
  38166. },
  38167. transform: {
  38168. async handler(source, importer) {
  38169. const { environment } = this;
  38170. if (!getFilter(this)(importer) || importer === CLIENT_ENTRY || !hasDynamicImportRE.test(source)) {
  38171. return;
  38172. }
  38173. await init;
  38174. let imports = [];
  38175. try {
  38176. imports = parse$d(source)[0];
  38177. } catch {
  38178. return null;
  38179. }
  38180. if (!imports.length) {
  38181. return null;
  38182. }
  38183. let s;
  38184. let needDynamicImportHelper = false;
  38185. for (let index = 0; index < imports.length; index++) {
  38186. const {
  38187. s: start,
  38188. e: end,
  38189. ss: expStart,
  38190. se: expEnd,
  38191. d: dynamicIndex
  38192. } = imports[index];
  38193. if (dynamicIndex === -1 || source[start] !== "`") {
  38194. continue;
  38195. }
  38196. if (hasViteIgnoreRE.test(source.slice(expStart, expEnd))) {
  38197. continue;
  38198. }
  38199. s ||= new MagicString(source);
  38200. let result;
  38201. try {
  38202. result = await transformDynamicImport(
  38203. source.slice(start, end),
  38204. importer,
  38205. (id, importer2) => resolve(environment, id, importer2),
  38206. config.root
  38207. );
  38208. } catch (error) {
  38209. if (environment.config.build.dynamicImportVarsOptions.warnOnError) {
  38210. this.warn(error);
  38211. } else {
  38212. this.error(error);
  38213. }
  38214. }
  38215. if (!result) {
  38216. continue;
  38217. }
  38218. const { rawPattern, glob } = result;
  38219. needDynamicImportHelper = true;
  38220. s.overwrite(
  38221. expStart,
  38222. expEnd,
  38223. `__variableDynamicImportRuntimeHelper(${glob}, \`${rawPattern}\`, ${rawPattern.split("/").length})`
  38224. );
  38225. }
  38226. if (s) {
  38227. if (needDynamicImportHelper) {
  38228. s.prepend(
  38229. `import __variableDynamicImportRuntimeHelper from "${dynamicImportHelperId}";`
  38230. );
  38231. }
  38232. return transformStableResult(s, importer, config);
  38233. }
  38234. }
  38235. }
  38236. };
  38237. }
  38238. function getMatcherString(glob, cwd) {
  38239. if (glob.startsWith("**") || path$b.isAbsolute(glob)) {
  38240. return slash$1(glob);
  38241. }
  38242. const resolved = path$b.join(cwd, glob);
  38243. return slash$1(resolved);
  38244. }
  38245. function patternToIdFilter(pattern, cwd) {
  38246. if (pattern instanceof RegExp) {
  38247. return (id) => {
  38248. const normalizedId = slash$1(id);
  38249. const result = pattern.test(normalizedId);
  38250. pattern.lastIndex = 0;
  38251. return result;
  38252. };
  38253. }
  38254. const glob = getMatcherString(pattern, cwd);
  38255. const matcher = picomatch$2(glob, { dot: true });
  38256. return (id) => {
  38257. const normalizedId = slash$1(id);
  38258. return matcher(normalizedId);
  38259. };
  38260. }
  38261. function patternToCodeFilter(pattern) {
  38262. if (pattern instanceof RegExp) {
  38263. return (code) => {
  38264. const result = pattern.test(code);
  38265. pattern.lastIndex = 0;
  38266. return result;
  38267. };
  38268. }
  38269. return (code) => code.includes(pattern);
  38270. }
  38271. function createFilter(exclude, include) {
  38272. if (!exclude && !include) {
  38273. return;
  38274. }
  38275. return (input) => {
  38276. if (exclude?.some((filter) => filter(input))) {
  38277. return false;
  38278. }
  38279. if (include?.some((filter) => filter(input))) {
  38280. return true;
  38281. }
  38282. return !(include && include.length > 0);
  38283. };
  38284. }
  38285. function normalizeFilter(filter) {
  38286. if (typeof filter === "string" || filter instanceof RegExp) {
  38287. return {
  38288. include: [filter]
  38289. };
  38290. }
  38291. if (Array.isArray(filter)) {
  38292. return {
  38293. include: filter
  38294. };
  38295. }
  38296. return {
  38297. include: filter.include ? arraify(filter.include) : void 0,
  38298. exclude: filter.exclude ? arraify(filter.exclude) : void 0
  38299. };
  38300. }
  38301. function createIdFilter(filter, cwd = process.cwd()) {
  38302. if (!filter) return;
  38303. const { exclude, include } = normalizeFilter(filter);
  38304. const excludeFilter = exclude?.map((p) => patternToIdFilter(p, cwd));
  38305. const includeFilter = include?.map((p) => patternToIdFilter(p, cwd));
  38306. return createFilter(excludeFilter, includeFilter);
  38307. }
  38308. function createCodeFilter(filter) {
  38309. if (!filter) return;
  38310. const { exclude, include } = normalizeFilter(filter);
  38311. const excludeFilter = exclude?.map(patternToCodeFilter);
  38312. const includeFilter = include?.map(patternToCodeFilter);
  38313. return createFilter(excludeFilter, includeFilter);
  38314. }
  38315. function createFilterForTransform(idFilter, codeFilter, cwd) {
  38316. if (!idFilter && !codeFilter) return;
  38317. const idFilterFn = createIdFilter(idFilter, cwd);
  38318. const codeFilterFn = createCodeFilter(codeFilter);
  38319. return (id, code) => {
  38320. let fallback = true;
  38321. if (idFilterFn) {
  38322. fallback &&= idFilterFn(id);
  38323. }
  38324. if (!fallback) {
  38325. return false;
  38326. }
  38327. if (codeFilterFn) {
  38328. fallback &&= codeFilterFn(code);
  38329. }
  38330. return fallback;
  38331. };
  38332. }
  38333. async function resolvePlugins(config, prePlugins, normalPlugins, postPlugins) {
  38334. const isBuild = config.command === "build";
  38335. const isWorker = config.isWorker;
  38336. const buildPlugins = isBuild ? await (await Promise.resolve().then(function () { return build$1; })).resolveBuildPlugins(config) : { pre: [], post: [] };
  38337. const { modulePreload } = config.build;
  38338. return [
  38339. !isBuild ? optimizedDepsPlugin() : null,
  38340. isBuild ? metadataPlugin() : null,
  38341. !isWorker ? watchPackageDataPlugin(config.packageCache) : null,
  38342. !isBuild ? preAliasPlugin(config) : null,
  38343. alias$1({
  38344. entries: config.resolve.alias,
  38345. customResolver: viteAliasCustomResolver
  38346. }),
  38347. ...prePlugins,
  38348. modulePreload !== false && modulePreload.polyfill ? modulePreloadPolyfillPlugin(config) : null,
  38349. resolvePlugin({
  38350. root: config.root,
  38351. isProduction: config.isProduction,
  38352. isBuild,
  38353. packageCache: config.packageCache,
  38354. asSrc: true,
  38355. optimizeDeps: true,
  38356. externalize: true
  38357. }),
  38358. htmlInlineProxyPlugin(config),
  38359. cssPlugin(config),
  38360. config.esbuild !== false ? esbuildPlugin(config) : null,
  38361. jsonPlugin(config.json, isBuild),
  38362. wasmHelperPlugin(),
  38363. webWorkerPlugin(config),
  38364. assetPlugin(config),
  38365. ...normalPlugins,
  38366. wasmFallbackPlugin(),
  38367. definePlugin(config),
  38368. cssPostPlugin(config),
  38369. isBuild && buildHtmlPlugin(config),
  38370. workerImportMetaUrlPlugin(config),
  38371. assetImportMetaUrlPlugin(config),
  38372. ...buildPlugins.pre,
  38373. dynamicImportVarsPlugin(config),
  38374. importGlobPlugin(config),
  38375. ...postPlugins,
  38376. ...buildPlugins.post,
  38377. // internal server-only plugins are always applied after everything else
  38378. ...isBuild ? [] : [
  38379. clientInjectionsPlugin(config),
  38380. cssAnalysisPlugin(config),
  38381. importAnalysisPlugin(config)
  38382. ]
  38383. ].filter(Boolean);
  38384. }
  38385. function createPluginHookUtils(plugins) {
  38386. const sortedPluginsCache = /* @__PURE__ */ new Map();
  38387. function getSortedPlugins(hookName) {
  38388. if (sortedPluginsCache.has(hookName))
  38389. return sortedPluginsCache.get(hookName);
  38390. const sorted = getSortedPluginsByHook(hookName, plugins);
  38391. sortedPluginsCache.set(hookName, sorted);
  38392. return sorted;
  38393. }
  38394. function getSortedPluginHooks(hookName) {
  38395. const plugins2 = getSortedPlugins(hookName);
  38396. return plugins2.map((p) => getHookHandler(p[hookName])).filter(Boolean);
  38397. }
  38398. return {
  38399. getSortedPlugins,
  38400. getSortedPluginHooks
  38401. };
  38402. }
  38403. function getSortedPluginsByHook(hookName, plugins) {
  38404. const sortedPlugins = [];
  38405. let pre = 0, normal = 0, post = 0;
  38406. for (const plugin of plugins) {
  38407. const hook = plugin[hookName];
  38408. if (hook) {
  38409. if (typeof hook === "object") {
  38410. if (hook.order === "pre") {
  38411. sortedPlugins.splice(pre++, 0, plugin);
  38412. continue;
  38413. }
  38414. if (hook.order === "post") {
  38415. sortedPlugins.splice(pre + normal + post++, 0, plugin);
  38416. continue;
  38417. }
  38418. }
  38419. sortedPlugins.splice(pre + normal++, 0, plugin);
  38420. }
  38421. }
  38422. return sortedPlugins;
  38423. }
  38424. function getHookHandler(hook) {
  38425. return typeof hook === "object" ? hook.handler : hook;
  38426. }
  38427. const filterForPlugin = /* @__PURE__ */ new WeakMap();
  38428. function getCachedFilterForPlugin(plugin, hookName) {
  38429. let filters = filterForPlugin.get(plugin);
  38430. if (filters && hookName in filters) {
  38431. return filters[hookName];
  38432. }
  38433. if (!filters) {
  38434. filters = {};
  38435. filterForPlugin.set(plugin, filters);
  38436. }
  38437. let filter;
  38438. switch (hookName) {
  38439. case "resolveId": {
  38440. const rawFilter = typeof plugin.resolveId === "object" ? plugin.resolveId.filter?.id : void 0;
  38441. filters.resolveId = createIdFilter(rawFilter);
  38442. filter = filters.resolveId;
  38443. break;
  38444. }
  38445. case "load": {
  38446. const rawFilter = typeof plugin.load === "object" ? plugin.load.filter?.id : void 0;
  38447. filters.load = createIdFilter(rawFilter);
  38448. filter = filters.load;
  38449. break;
  38450. }
  38451. case "transform": {
  38452. const rawFilters = typeof plugin.transform === "object" ? plugin.transform.filter : void 0;
  38453. filters.transform = createFilterForTransform(
  38454. rawFilters?.id,
  38455. rawFilters?.code
  38456. );
  38457. filter = filters.transform;
  38458. break;
  38459. }
  38460. }
  38461. return filter;
  38462. }
  38463. const viteAliasCustomResolver = async function(id, importer, options) {
  38464. const resolved = await this.resolve(id, importer, options);
  38465. return resolved || { id, meta: { "vite:alias": { noResolved: true } } };
  38466. };
  38467. const EMPTY_OBJECT = Object.freeze({});
  38468. const debugSourcemapCombineFilter = process.env.DEBUG_VITE_SOURCEMAP_COMBINE_FILTER;
  38469. const debugSourcemapCombine = createDebugger("vite:sourcemap-combine", {
  38470. onlyWhenFocused: true
  38471. });
  38472. const debugResolve = createDebugger("vite:resolve");
  38473. const debugPluginResolve = createDebugger("vite:plugin-resolve", {
  38474. onlyWhenFocused: "vite:plugin"
  38475. });
  38476. const debugPluginTransform = createDebugger("vite:plugin-transform", {
  38477. onlyWhenFocused: "vite:plugin"
  38478. });
  38479. const debugPluginContainerContext = createDebugger(
  38480. "vite:plugin-container-context"
  38481. );
  38482. const ERR_CLOSED_SERVER = "ERR_CLOSED_SERVER";
  38483. function throwClosedServerError() {
  38484. const err = new Error(
  38485. "The server is being restarted or closed. Request is outdated"
  38486. );
  38487. err.code = ERR_CLOSED_SERVER;
  38488. throw err;
  38489. }
  38490. async function createEnvironmentPluginContainer(environment, plugins, watcher, autoStart = true) {
  38491. const container = new EnvironmentPluginContainer(
  38492. environment,
  38493. plugins,
  38494. watcher,
  38495. autoStart
  38496. );
  38497. await container.resolveRollupOptions();
  38498. return container;
  38499. }
  38500. class EnvironmentPluginContainer {
  38501. /**
  38502. * @internal use `createEnvironmentPluginContainer` instead
  38503. */
  38504. constructor(environment, plugins, watcher, autoStart = true) {
  38505. this.environment = environment;
  38506. this.plugins = plugins;
  38507. this.watcher = watcher;
  38508. this._started = !autoStart;
  38509. this.minimalContext = new MinimalPluginContext(
  38510. { rollupVersion, watchMode: true },
  38511. environment
  38512. );
  38513. const utils = createPluginHookUtils(plugins);
  38514. this.getSortedPlugins = utils.getSortedPlugins;
  38515. this.getSortedPluginHooks = utils.getSortedPluginHooks;
  38516. this.moduleGraph = environment.mode === "dev" ? environment.moduleGraph : void 0;
  38517. }
  38518. _pluginContextMap = /* @__PURE__ */ new Map();
  38519. _resolvedRollupOptions;
  38520. _processesing = /* @__PURE__ */ new Set();
  38521. _seenResolves = {};
  38522. // _addedFiles from the `load()` hook gets saved here so it can be reused in the `transform()` hook
  38523. _moduleNodeToLoadAddedImports = /* @__PURE__ */ new WeakMap();
  38524. getSortedPluginHooks;
  38525. getSortedPlugins;
  38526. moduleGraph;
  38527. watchFiles = /* @__PURE__ */ new Set();
  38528. minimalContext;
  38529. _started = false;
  38530. _buildStartPromise;
  38531. _closed = false;
  38532. _updateModuleLoadAddedImports(id, addedImports) {
  38533. const module = this.moduleGraph?.getModuleById(id);
  38534. if (module) {
  38535. this._moduleNodeToLoadAddedImports.set(module, addedImports);
  38536. }
  38537. }
  38538. _getAddedImports(id) {
  38539. const module = this.moduleGraph?.getModuleById(id);
  38540. return module ? this._moduleNodeToLoadAddedImports.get(module) || null : null;
  38541. }
  38542. getModuleInfo(id) {
  38543. const module = this.moduleGraph?.getModuleById(id);
  38544. if (!module) {
  38545. return null;
  38546. }
  38547. if (!module.info) {
  38548. module.info = new Proxy(
  38549. { id, meta: module.meta || EMPTY_OBJECT },
  38550. // throw when an unsupported ModuleInfo property is accessed,
  38551. // so that incompatible plugins fail in a non-cryptic way.
  38552. {
  38553. get(info, key) {
  38554. if (key in info) {
  38555. return info[key];
  38556. }
  38557. if (key === "then") {
  38558. return void 0;
  38559. }
  38560. throw Error(
  38561. `[vite] The "${key}" property of ModuleInfo is not supported.`
  38562. );
  38563. }
  38564. }
  38565. );
  38566. }
  38567. return module.info ?? null;
  38568. }
  38569. // keeps track of hook promises so that we can wait for them all to finish upon closing the server
  38570. handleHookPromise(maybePromise) {
  38571. if (!maybePromise?.then) {
  38572. return maybePromise;
  38573. }
  38574. const promise = maybePromise;
  38575. this._processesing.add(promise);
  38576. return promise.finally(() => this._processesing.delete(promise));
  38577. }
  38578. get options() {
  38579. return this._resolvedRollupOptions;
  38580. }
  38581. async resolveRollupOptions() {
  38582. if (!this._resolvedRollupOptions) {
  38583. let options = this.environment.config.build.rollupOptions;
  38584. for (const optionsHook of this.getSortedPluginHooks("options")) {
  38585. if (this._closed) {
  38586. throwClosedServerError();
  38587. }
  38588. options = await this.handleHookPromise(
  38589. optionsHook.call(this.minimalContext, options)
  38590. ) || options;
  38591. }
  38592. this._resolvedRollupOptions = options;
  38593. }
  38594. return this._resolvedRollupOptions;
  38595. }
  38596. _getPluginContext(plugin) {
  38597. if (!this._pluginContextMap.has(plugin)) {
  38598. this._pluginContextMap.set(plugin, new PluginContext(plugin, this));
  38599. }
  38600. return this._pluginContextMap.get(plugin);
  38601. }
  38602. // parallel, ignores returns
  38603. async hookParallel(hookName, context, args, condition) {
  38604. const parallelPromises = [];
  38605. for (const plugin of this.getSortedPlugins(hookName)) {
  38606. if (condition && !condition(plugin)) continue;
  38607. const hook = plugin[hookName];
  38608. const handler = getHookHandler(hook);
  38609. if (hook.sequential) {
  38610. await Promise.all(parallelPromises);
  38611. parallelPromises.length = 0;
  38612. await handler.apply(context(plugin), args(plugin));
  38613. } else {
  38614. parallelPromises.push(handler.apply(context(plugin), args(plugin)));
  38615. }
  38616. }
  38617. await Promise.all(parallelPromises);
  38618. }
  38619. async buildStart(_options) {
  38620. if (this._started) {
  38621. if (this._buildStartPromise) {
  38622. await this._buildStartPromise;
  38623. }
  38624. return;
  38625. }
  38626. this._started = true;
  38627. const config = this.environment.getTopLevelConfig();
  38628. this._buildStartPromise = this.handleHookPromise(
  38629. this.hookParallel(
  38630. "buildStart",
  38631. (plugin) => this._getPluginContext(plugin),
  38632. () => [this.options],
  38633. (plugin) => this.environment.name === "client" || config.server.perEnvironmentStartEndDuringDev || plugin.perEnvironmentStartEndDuringDev
  38634. )
  38635. );
  38636. await this._buildStartPromise;
  38637. this._buildStartPromise = void 0;
  38638. }
  38639. async resolveId(rawId, importer = join$1(
  38640. this.environment.config.root,
  38641. "index.html"
  38642. ), options) {
  38643. if (!this._started) {
  38644. this.buildStart();
  38645. await this._buildStartPromise;
  38646. }
  38647. const skip = options?.skip;
  38648. const skipCalls = options?.skipCalls;
  38649. const scan = !!options?.scan;
  38650. const ssr = this.environment.config.consumer === "server";
  38651. const ctx = new ResolveIdContext(this, skip, skipCalls, scan);
  38652. const mergedSkip = new Set(skip);
  38653. for (const call of skipCalls ?? []) {
  38654. if (call.called || call.id === rawId && call.importer === importer) {
  38655. mergedSkip.add(call.plugin);
  38656. }
  38657. }
  38658. const resolveStart = debugResolve ? performance$1.now() : 0;
  38659. let id = null;
  38660. const partial = {};
  38661. for (const plugin of this.getSortedPlugins("resolveId")) {
  38662. if (this._closed && this.environment.config.dev.recoverable)
  38663. throwClosedServerError();
  38664. if (mergedSkip?.has(plugin)) continue;
  38665. const filter = getCachedFilterForPlugin(plugin, "resolveId");
  38666. if (filter && !filter(rawId)) continue;
  38667. ctx._plugin = plugin;
  38668. const pluginResolveStart = debugPluginResolve ? performance$1.now() : 0;
  38669. const handler = getHookHandler(plugin.resolveId);
  38670. const result = await this.handleHookPromise(
  38671. handler.call(ctx, rawId, importer, {
  38672. attributes: options?.attributes ?? {},
  38673. custom: options?.custom,
  38674. isEntry: !!options?.isEntry,
  38675. ssr,
  38676. scan
  38677. })
  38678. );
  38679. if (!result) continue;
  38680. if (typeof result === "string") {
  38681. id = result;
  38682. } else {
  38683. id = result.id;
  38684. Object.assign(partial, result);
  38685. }
  38686. debugPluginResolve?.(
  38687. timeFrom(pluginResolveStart),
  38688. plugin.name,
  38689. prettifyUrl(id, this.environment.config.root)
  38690. );
  38691. break;
  38692. }
  38693. if (debugResolve && rawId !== id && !rawId.startsWith(FS_PREFIX)) {
  38694. const key = rawId + id;
  38695. if (!this._seenResolves[key]) {
  38696. this._seenResolves[key] = true;
  38697. debugResolve(
  38698. `${timeFrom(resolveStart)} ${colors$1.cyan(rawId)} -> ${colors$1.dim(
  38699. id
  38700. )}`
  38701. );
  38702. }
  38703. }
  38704. if (id) {
  38705. partial.id = isExternalUrl(id) ? id : normalizePath$3(id);
  38706. return partial;
  38707. } else {
  38708. return null;
  38709. }
  38710. }
  38711. async load(id) {
  38712. const ssr = this.environment.config.consumer === "server";
  38713. const options = { ssr };
  38714. const ctx = new LoadPluginContext(this);
  38715. for (const plugin of this.getSortedPlugins("load")) {
  38716. if (this._closed && this.environment.config.dev.recoverable)
  38717. throwClosedServerError();
  38718. const filter = getCachedFilterForPlugin(plugin, "load");
  38719. if (filter && !filter(id)) continue;
  38720. ctx._plugin = plugin;
  38721. const handler = getHookHandler(plugin.load);
  38722. const result = await this.handleHookPromise(
  38723. handler.call(ctx, id, options)
  38724. );
  38725. if (result != null) {
  38726. if (isObject$1(result)) {
  38727. ctx._updateModuleInfo(id, result);
  38728. }
  38729. this._updateModuleLoadAddedImports(id, ctx._addedImports);
  38730. return result;
  38731. }
  38732. }
  38733. this._updateModuleLoadAddedImports(id, ctx._addedImports);
  38734. return null;
  38735. }
  38736. async transform(code, id, options) {
  38737. const ssr = this.environment.config.consumer === "server";
  38738. const optionsWithSSR = options ? { ...options, ssr } : { ssr };
  38739. const inMap = options?.inMap;
  38740. const ctx = new TransformPluginContext(this, id, code, inMap);
  38741. ctx._addedImports = this._getAddedImports(id);
  38742. for (const plugin of this.getSortedPlugins("transform")) {
  38743. if (this._closed && this.environment.config.dev.recoverable)
  38744. throwClosedServerError();
  38745. const filter = getCachedFilterForPlugin(plugin, "transform");
  38746. if (filter && !filter(id, code)) continue;
  38747. ctx._updateActiveInfo(plugin, id, code);
  38748. const start = debugPluginTransform ? performance$1.now() : 0;
  38749. let result;
  38750. const handler = getHookHandler(plugin.transform);
  38751. try {
  38752. result = await this.handleHookPromise(
  38753. handler.call(ctx, code, id, optionsWithSSR)
  38754. );
  38755. } catch (e) {
  38756. ctx.error(e);
  38757. }
  38758. if (!result) continue;
  38759. debugPluginTransform?.(
  38760. timeFrom(start),
  38761. plugin.name,
  38762. prettifyUrl(id, this.environment.config.root)
  38763. );
  38764. if (isObject$1(result)) {
  38765. if (result.code !== void 0) {
  38766. code = result.code;
  38767. if (result.map) {
  38768. if (debugSourcemapCombine) {
  38769. result.map.name = plugin.name;
  38770. }
  38771. ctx.sourcemapChain.push(result.map);
  38772. }
  38773. }
  38774. ctx._updateModuleInfo(id, result);
  38775. } else {
  38776. code = result;
  38777. }
  38778. }
  38779. return {
  38780. code,
  38781. map: ctx._getCombinedSourcemap()
  38782. };
  38783. }
  38784. async watchChange(id, change) {
  38785. await this.hookParallel(
  38786. "watchChange",
  38787. (plugin) => this._getPluginContext(plugin),
  38788. () => [id, change]
  38789. );
  38790. }
  38791. async close() {
  38792. if (this._closed) return;
  38793. this._closed = true;
  38794. await Promise.allSettled(Array.from(this._processesing));
  38795. const config = this.environment.getTopLevelConfig();
  38796. await this.hookParallel(
  38797. "buildEnd",
  38798. (plugin) => this._getPluginContext(plugin),
  38799. () => [],
  38800. (plugin) => this.environment.name === "client" || config.server.perEnvironmentStartEndDuringDev || plugin.perEnvironmentStartEndDuringDev
  38801. );
  38802. await this.hookParallel(
  38803. "closeBundle",
  38804. (plugin) => this._getPluginContext(plugin),
  38805. () => []
  38806. );
  38807. }
  38808. }
  38809. class MinimalPluginContext {
  38810. constructor(meta, environment) {
  38811. this.meta = meta;
  38812. this.environment = environment;
  38813. }
  38814. debug(rawLog) {
  38815. const log = this._normalizeRawLog(rawLog);
  38816. const msg = buildErrorMessage(log, [`debug: ${log.message}`], false);
  38817. debugPluginContainerContext?.(msg);
  38818. }
  38819. info(rawLog) {
  38820. const log = this._normalizeRawLog(rawLog);
  38821. const msg = buildErrorMessage(log, [`info: ${log.message}`], false);
  38822. this.environment.logger.info(msg, { clear: true, timestamp: true });
  38823. }
  38824. warn(rawLog) {
  38825. const log = this._normalizeRawLog(rawLog);
  38826. const msg = buildErrorMessage(
  38827. log,
  38828. [colors$1.yellow(`warning: ${log.message}`)],
  38829. false
  38830. );
  38831. this.environment.logger.warn(msg, { clear: true, timestamp: true });
  38832. }
  38833. error(e) {
  38834. const err = typeof e === "string" ? new Error(e) : e;
  38835. throw err;
  38836. }
  38837. _normalizeRawLog(rawLog) {
  38838. const logValue = typeof rawLog === "function" ? rawLog() : rawLog;
  38839. return typeof logValue === "string" ? new Error(logValue) : logValue;
  38840. }
  38841. }
  38842. class PluginContext extends MinimalPluginContext {
  38843. constructor(_plugin, _container) {
  38844. super(_container.minimalContext.meta, _container.environment);
  38845. this._plugin = _plugin;
  38846. this._container = _container;
  38847. }
  38848. ssr = false;
  38849. _scan = false;
  38850. _activeId = null;
  38851. _activeCode = null;
  38852. _resolveSkips;
  38853. _resolveSkipCalls;
  38854. parse(code, opts) {
  38855. return parseAst(code, opts);
  38856. }
  38857. async resolve(id, importer, options) {
  38858. let skipCalls;
  38859. if (options?.skipSelf === false) {
  38860. skipCalls = this._resolveSkipCalls;
  38861. } else if (this._resolveSkipCalls) {
  38862. const skipCallsTemp = [...this._resolveSkipCalls];
  38863. const sameCallIndex = this._resolveSkipCalls.findIndex(
  38864. (c) => c.id === id && c.importer === importer && c.plugin === this._plugin
  38865. );
  38866. if (sameCallIndex !== -1) {
  38867. skipCallsTemp[sameCallIndex] = {
  38868. ...skipCallsTemp[sameCallIndex],
  38869. called: true
  38870. };
  38871. } else {
  38872. skipCallsTemp.push({ id, importer, plugin: this._plugin });
  38873. }
  38874. skipCalls = skipCallsTemp;
  38875. } else {
  38876. skipCalls = [{ id, importer, plugin: this._plugin }];
  38877. }
  38878. let out = await this._container.resolveId(id, importer, {
  38879. attributes: options?.attributes,
  38880. custom: options?.custom,
  38881. isEntry: !!options?.isEntry,
  38882. skip: this._resolveSkips,
  38883. skipCalls,
  38884. scan: this._scan
  38885. });
  38886. if (typeof out === "string") out = { id: out };
  38887. return out;
  38888. }
  38889. async load(options) {
  38890. await this._container.moduleGraph?.ensureEntryFromUrl(unwrapId$1(options.id));
  38891. this._updateModuleInfo(options.id, options);
  38892. const loadResult = await this._container.load(options.id);
  38893. const code = typeof loadResult === "object" ? loadResult?.code : loadResult;
  38894. if (code != null) {
  38895. await this._container.transform(code, options.id);
  38896. }
  38897. const moduleInfo = this.getModuleInfo(options.id);
  38898. if (!moduleInfo) throw Error(`Failed to load module with id ${options.id}`);
  38899. return moduleInfo;
  38900. }
  38901. getModuleInfo(id) {
  38902. return this._container.getModuleInfo(id);
  38903. }
  38904. _updateModuleInfo(id, { meta }) {
  38905. if (meta) {
  38906. const moduleInfo = this.getModuleInfo(id);
  38907. if (moduleInfo) {
  38908. moduleInfo.meta = { ...moduleInfo.meta, ...meta };
  38909. }
  38910. }
  38911. }
  38912. getModuleIds() {
  38913. return this._container.moduleGraph ? this._container.moduleGraph.idToModuleMap.keys() : Array.prototype[Symbol.iterator]();
  38914. }
  38915. addWatchFile(id) {
  38916. this._container.watchFiles.add(id);
  38917. if (this._container.watcher)
  38918. ensureWatchedFile(
  38919. this._container.watcher,
  38920. id,
  38921. this.environment.config.root
  38922. );
  38923. }
  38924. getWatchFiles() {
  38925. return [...this._container.watchFiles];
  38926. }
  38927. emitFile(_assetOrFile) {
  38928. this._warnIncompatibleMethod(`emitFile`);
  38929. return "";
  38930. }
  38931. setAssetSource() {
  38932. this._warnIncompatibleMethod(`setAssetSource`);
  38933. }
  38934. getFileName() {
  38935. this._warnIncompatibleMethod(`getFileName`);
  38936. return "";
  38937. }
  38938. debug(log) {
  38939. const err = this._formatLog(typeof log === "function" ? log() : log);
  38940. super.debug(err);
  38941. }
  38942. info(log) {
  38943. const err = this._formatLog(typeof log === "function" ? log() : log);
  38944. super.info(err);
  38945. }
  38946. warn(log, position) {
  38947. const err = this._formatLog(
  38948. typeof log === "function" ? log() : log,
  38949. position
  38950. );
  38951. super.warn(err);
  38952. }
  38953. error(e, position) {
  38954. throw this._formatLog(e, position);
  38955. }
  38956. _formatLog(e, position) {
  38957. const err = typeof e === "string" ? new Error(e) : e;
  38958. if (err.pluginCode) {
  38959. return err;
  38960. }
  38961. err.plugin = this._plugin.name;
  38962. if (this._activeId && !err.id) err.id = this._activeId;
  38963. if (this._activeCode) {
  38964. err.pluginCode = this._activeCode;
  38965. const pos = position ?? err.pos ?? err.position;
  38966. if (pos != null) {
  38967. let errLocation;
  38968. try {
  38969. errLocation = numberToPos(this._activeCode, pos);
  38970. } catch (err2) {
  38971. this.environment.logger.error(
  38972. colors$1.red(
  38973. `Error in error handler:
  38974. ${err2.stack || err2.message}
  38975. `
  38976. ),
  38977. // print extra newline to separate the two errors
  38978. { error: err2 }
  38979. );
  38980. throw err;
  38981. }
  38982. err.loc = err.loc || {
  38983. file: err.id,
  38984. ...errLocation
  38985. };
  38986. err.frame = err.frame || generateCodeFrame(this._activeCode, pos);
  38987. } else if (err.loc) {
  38988. if (!err.frame) {
  38989. let code = this._activeCode;
  38990. if (err.loc.file) {
  38991. err.id = normalizePath$3(err.loc.file);
  38992. try {
  38993. code = fs__default.readFileSync(err.loc.file, "utf-8");
  38994. } catch {
  38995. }
  38996. }
  38997. err.frame = generateCodeFrame(code, err.loc);
  38998. }
  38999. } else if (err.line && err.column) {
  39000. err.loc = {
  39001. file: err.id,
  39002. line: err.line,
  39003. column: err.column
  39004. };
  39005. err.frame = err.frame || generateCodeFrame(this._activeCode, err.loc);
  39006. }
  39007. if (this instanceof TransformPluginContext && typeof err.loc?.line === "number" && typeof err.loc.column === "number") {
  39008. const rawSourceMap = this._getCombinedSourcemap();
  39009. if (rawSourceMap && "version" in rawSourceMap) {
  39010. const traced = new TraceMap(rawSourceMap);
  39011. const { source, line, column } = originalPositionFor$1(traced, {
  39012. line: Number(err.loc.line),
  39013. column: Number(err.loc.column)
  39014. });
  39015. if (source) {
  39016. err.loc = { file: source, line, column };
  39017. }
  39018. }
  39019. }
  39020. } else if (err.loc) {
  39021. if (!err.frame) {
  39022. let code = err.pluginCode;
  39023. if (err.loc.file) {
  39024. err.id = normalizePath$3(err.loc.file);
  39025. if (!code) {
  39026. try {
  39027. code = fs__default.readFileSync(err.loc.file, "utf-8");
  39028. } catch {
  39029. }
  39030. }
  39031. }
  39032. if (code) {
  39033. err.frame = generateCodeFrame(`${code}`, err.loc);
  39034. }
  39035. }
  39036. }
  39037. if (typeof err.loc?.column !== "number" && typeof err.loc?.line !== "number" && !err.loc?.file) {
  39038. delete err.loc;
  39039. }
  39040. return err;
  39041. }
  39042. _warnIncompatibleMethod(method) {
  39043. this.environment.logger.warn(
  39044. colors$1.cyan(`[plugin:${this._plugin.name}] `) + colors$1.yellow(
  39045. `context method ${colors$1.bold(
  39046. `${method}()`
  39047. )} is not supported in serve mode. This plugin is likely not vite-compatible.`
  39048. )
  39049. );
  39050. }
  39051. }
  39052. class ResolveIdContext extends PluginContext {
  39053. constructor(container, skip, skipCalls, scan) {
  39054. super(null, container);
  39055. this._resolveSkips = skip;
  39056. this._resolveSkipCalls = skipCalls;
  39057. this._scan = scan;
  39058. }
  39059. }
  39060. class LoadPluginContext extends PluginContext {
  39061. _addedImports = null;
  39062. constructor(container) {
  39063. super(null, container);
  39064. }
  39065. addWatchFile(id) {
  39066. if (!this._addedImports) {
  39067. this._addedImports = /* @__PURE__ */ new Set();
  39068. }
  39069. this._addedImports.add(id);
  39070. super.addWatchFile(id);
  39071. }
  39072. }
  39073. class TransformPluginContext extends LoadPluginContext {
  39074. filename;
  39075. originalCode;
  39076. originalSourcemap = null;
  39077. sourcemapChain = [];
  39078. combinedMap = null;
  39079. constructor(container, id, code, inMap) {
  39080. super(container);
  39081. this.filename = id;
  39082. this.originalCode = code;
  39083. if (inMap) {
  39084. if (debugSourcemapCombine) {
  39085. inMap.name = "$inMap";
  39086. }
  39087. this.sourcemapChain.push(inMap);
  39088. }
  39089. }
  39090. _getCombinedSourcemap() {
  39091. if (debugSourcemapCombine && debugSourcemapCombineFilter && this.filename.includes(debugSourcemapCombineFilter)) {
  39092. debugSourcemapCombine("----------", this.filename);
  39093. debugSourcemapCombine(this.combinedMap);
  39094. debugSourcemapCombine(this.sourcemapChain);
  39095. debugSourcemapCombine("----------");
  39096. }
  39097. let combinedMap = this.combinedMap;
  39098. if (combinedMap && !("version" in combinedMap) && combinedMap.mappings === "") {
  39099. this.sourcemapChain.length = 0;
  39100. return combinedMap;
  39101. }
  39102. for (let m of this.sourcemapChain) {
  39103. if (typeof m === "string") m = JSON.parse(m);
  39104. if (!("version" in m)) {
  39105. if (m.mappings === "") {
  39106. combinedMap = { mappings: "" };
  39107. break;
  39108. }
  39109. combinedMap = null;
  39110. break;
  39111. }
  39112. if (!combinedMap) {
  39113. const sm = m;
  39114. if (sm.sources.length === 1 && !sm.sources[0]) {
  39115. combinedMap = {
  39116. ...sm,
  39117. sources: [this.filename],
  39118. sourcesContent: [this.originalCode]
  39119. };
  39120. } else {
  39121. combinedMap = sm;
  39122. }
  39123. } else {
  39124. combinedMap = combineSourcemaps(cleanUrl(this.filename), [
  39125. m,
  39126. combinedMap
  39127. ]);
  39128. }
  39129. }
  39130. if (combinedMap !== this.combinedMap) {
  39131. this.combinedMap = combinedMap;
  39132. this.sourcemapChain.length = 0;
  39133. }
  39134. return this.combinedMap;
  39135. }
  39136. getCombinedSourcemap() {
  39137. const map = this._getCombinedSourcemap();
  39138. if (!map || !("version" in map) && map.mappings === "") {
  39139. return new MagicString(this.originalCode).generateMap({
  39140. includeContent: true,
  39141. hires: "boundary",
  39142. source: cleanUrl(this.filename)
  39143. });
  39144. }
  39145. return map;
  39146. }
  39147. _updateActiveInfo(plugin, id, code) {
  39148. this._plugin = plugin;
  39149. this._activeId = id;
  39150. this._activeCode = code;
  39151. }
  39152. }
  39153. class PluginContainer {
  39154. constructor(environments) {
  39155. this.environments = environments;
  39156. }
  39157. // Backward compatibility
  39158. // Users should call pluginContainer.resolveId (and load/transform) passing the environment they want to work with
  39159. // But there is code that is going to call it without passing an environment, or with the ssr flag to get the ssr environment
  39160. _getEnvironment(options) {
  39161. return options?.environment ? options.environment : this.environments[options?.ssr ? "ssr" : "client"];
  39162. }
  39163. _getPluginContainer(options) {
  39164. return this._getEnvironment(options).pluginContainer;
  39165. }
  39166. getModuleInfo(id) {
  39167. const clientModuleInfo = this.environments.client.pluginContainer.getModuleInfo(id);
  39168. const ssrModuleInfo = this.environments.ssr.pluginContainer.getModuleInfo(id);
  39169. if (clientModuleInfo == null && ssrModuleInfo == null) return null;
  39170. return new Proxy({}, {
  39171. get: (_, key) => {
  39172. if (key === "meta") {
  39173. const meta = {};
  39174. if (ssrModuleInfo) {
  39175. Object.assign(meta, ssrModuleInfo.meta);
  39176. }
  39177. if (clientModuleInfo) {
  39178. Object.assign(meta, clientModuleInfo.meta);
  39179. }
  39180. return meta;
  39181. }
  39182. if (clientModuleInfo) {
  39183. if (key in clientModuleInfo) {
  39184. return clientModuleInfo[key];
  39185. }
  39186. }
  39187. if (ssrModuleInfo) {
  39188. if (key in ssrModuleInfo) {
  39189. return ssrModuleInfo[key];
  39190. }
  39191. }
  39192. }
  39193. });
  39194. }
  39195. get options() {
  39196. return this.environments.client.pluginContainer.options;
  39197. }
  39198. // For backward compatibility, buildStart and watchChange are called only for the client environment
  39199. // buildStart is called per environment for a plugin with the perEnvironmentStartEndDuring dev flag
  39200. async buildStart(_options) {
  39201. return this.environments.client.pluginContainer.buildStart(_options);
  39202. }
  39203. async watchChange(id, change) {
  39204. return this.environments.client.pluginContainer.watchChange(id, change);
  39205. }
  39206. async resolveId(rawId, importer, options) {
  39207. return this._getPluginContainer(options).resolveId(rawId, importer, options);
  39208. }
  39209. async load(id, options) {
  39210. return this._getPluginContainer(options).load(id);
  39211. }
  39212. async transform(code, id, options) {
  39213. return this._getPluginContainer(options).transform(code, id, options);
  39214. }
  39215. async close() {
  39216. }
  39217. }
  39218. function createPluginContainer(environments) {
  39219. return new PluginContainer(environments);
  39220. }
  39221. function createBackCompatIdResolver(config, options) {
  39222. const compatResolve = config.createResolver(options);
  39223. let resolve;
  39224. return async (environment, id, importer, aliasOnly) => {
  39225. if (environment.name === "client" || environment.name === "ssr") {
  39226. return compatResolve(id, importer, aliasOnly, environment.name === "ssr");
  39227. }
  39228. resolve ??= createIdResolver(config, options);
  39229. return resolve(environment, id, importer, aliasOnly);
  39230. };
  39231. }
  39232. function createIdResolver(config, options) {
  39233. const scan = options?.scan;
  39234. const pluginContainerMap = /* @__PURE__ */ new Map();
  39235. async function resolve(environment, id, importer) {
  39236. let pluginContainer = pluginContainerMap.get(environment);
  39237. if (!pluginContainer) {
  39238. pluginContainer = await createEnvironmentPluginContainer(
  39239. environment,
  39240. [
  39241. alias$1({ entries: environment.config.resolve.alias }),
  39242. resolvePlugin({
  39243. root: config.root,
  39244. isProduction: config.isProduction,
  39245. isBuild: config.command === "build",
  39246. asSrc: true,
  39247. preferRelative: false,
  39248. tryIndex: true,
  39249. ...options,
  39250. // Ignore sideEffects and other computations as we only need the id
  39251. idOnly: true
  39252. })
  39253. ],
  39254. void 0,
  39255. false
  39256. );
  39257. pluginContainerMap.set(environment, pluginContainer);
  39258. }
  39259. return await pluginContainer.resolveId(id, importer, { scan });
  39260. }
  39261. const aliasOnlyPluginContainerMap = /* @__PURE__ */ new Map();
  39262. async function resolveAlias(environment, id, importer) {
  39263. let pluginContainer = aliasOnlyPluginContainerMap.get(environment);
  39264. if (!pluginContainer) {
  39265. pluginContainer = await createEnvironmentPluginContainer(
  39266. environment,
  39267. [alias$1({ entries: environment.config.resolve.alias })],
  39268. void 0,
  39269. false
  39270. );
  39271. aliasOnlyPluginContainerMap.set(environment, pluginContainer);
  39272. }
  39273. return await pluginContainer.resolveId(id, importer, { scan });
  39274. }
  39275. return async (environment, id, importer, aliasOnly) => {
  39276. const resolveFn = aliasOnly ? resolveAlias : resolve;
  39277. const resolved = await resolveFn(environment, id, importer);
  39278. return resolved?.id;
  39279. };
  39280. }
  39281. const decoder = new TextDecoder();
  39282. const cssConfigDefaults = Object.freeze({
  39283. /** @experimental */
  39284. transformer: "postcss",
  39285. // modules
  39286. // preprocessorOptions
  39287. /** @experimental */
  39288. preprocessorMaxWorkers: 0,
  39289. // postcss
  39290. /** @experimental */
  39291. devSourcemap: false
  39292. // lightningcss
  39293. });
  39294. function resolveCSSOptions(options) {
  39295. const resolved = mergeWithDefaults(cssConfigDefaults, options ?? {});
  39296. if (resolved.transformer === "lightningcss") {
  39297. resolved.lightningcss ??= {};
  39298. resolved.lightningcss.targets ??= convertTargets(ESBUILD_MODULES_TARGET);
  39299. }
  39300. return resolved;
  39301. }
  39302. const cssModuleRE = new RegExp(`\\.module${CSS_LANGS_RE.source}`);
  39303. const directRequestRE = /[?&]direct\b/;
  39304. const htmlProxyRE = /[?&]html-proxy\b/;
  39305. const htmlProxyIndexRE = /&index=(\d+)/;
  39306. const commonjsProxyRE = /[?&]commonjs-proxy/;
  39307. const inlineRE = /[?&]inline\b/;
  39308. const inlineCSSRE = /[?&]inline-css\b/;
  39309. const styleAttrRE = /[?&]style-attr\b/;
  39310. const functionCallRE = /^[A-Z_][.\w-]*\(/i;
  39311. const transformOnlyRE = /[?&]transform-only\b/;
  39312. const nonEscapedDoubleQuoteRe = /(?<!\\)"/g;
  39313. const defaultCssBundleName = "style.css";
  39314. const isCSSRequest = (request) => CSS_LANGS_RE.test(request);
  39315. const isModuleCSSRequest = (request) => cssModuleRE.test(request);
  39316. const isDirectCSSRequest = (request) => CSS_LANGS_RE.test(request) && directRequestRE.test(request);
  39317. const isDirectRequest = (request) => directRequestRE.test(request);
  39318. const cssModulesCache = /* @__PURE__ */ new WeakMap();
  39319. const removedPureCssFilesCache = /* @__PURE__ */ new WeakMap();
  39320. const cssBundleNameCache = /* @__PURE__ */ new WeakMap();
  39321. const postcssConfigCache = /* @__PURE__ */ new WeakMap();
  39322. function encodePublicUrlsInCSS(config) {
  39323. return config.command === "build";
  39324. }
  39325. const cssUrlAssetRE = /__VITE_CSS_URL__([\da-f]+)__/g;
  39326. function cssPlugin(config) {
  39327. const isBuild = config.command === "build";
  39328. let moduleCache;
  39329. const idResolver = createBackCompatIdResolver(config, {
  39330. preferRelative: true,
  39331. tryIndex: false,
  39332. extensions: []
  39333. });
  39334. let preprocessorWorkerController;
  39335. if (config.css.transformer !== "lightningcss") {
  39336. resolvePostcssConfig(config).catch(() => {
  39337. });
  39338. }
  39339. const plugin = {
  39340. name: "vite:css",
  39341. buildStart() {
  39342. moduleCache = /* @__PURE__ */ new Map();
  39343. cssModulesCache.set(config, moduleCache);
  39344. removedPureCssFilesCache.set(config, /* @__PURE__ */ new Map());
  39345. preprocessorWorkerController = createPreprocessorWorkerController(
  39346. normalizeMaxWorkers(config.css.preprocessorMaxWorkers)
  39347. );
  39348. preprocessorWorkerControllerCache.set(
  39349. config,
  39350. preprocessorWorkerController
  39351. );
  39352. },
  39353. buildEnd() {
  39354. preprocessorWorkerController?.close();
  39355. },
  39356. load: {
  39357. async handler(id) {
  39358. if (!isCSSRequest(id)) return;
  39359. if (urlRE$1.test(id)) {
  39360. if (isModuleCSSRequest(id)) {
  39361. throw new Error(
  39362. `?url is not supported with CSS modules. (tried to import ${JSON.stringify(
  39363. id
  39364. )})`
  39365. );
  39366. }
  39367. if (isBuild) {
  39368. id = injectQuery(removeUrlQuery(id), "transform-only");
  39369. return `import ${JSON.stringify(id)};export default "__VITE_CSS_URL__${Buffer.from(id).toString(
  39370. "hex"
  39371. )}__"`;
  39372. }
  39373. }
  39374. }
  39375. }
  39376. };
  39377. const transformHook = {
  39378. async handler(raw, id) {
  39379. if (!isCSSRequest(id) || commonjsProxyRE.test(id) || SPECIAL_QUERY_RE.test(id)) {
  39380. return;
  39381. }
  39382. const { environment } = this;
  39383. const resolveUrl = (url, importer) => idResolver(environment, url, importer);
  39384. const urlResolver = async (url, importer) => {
  39385. const decodedUrl = decodeURI(url);
  39386. if (checkPublicFile(decodedUrl, config)) {
  39387. if (encodePublicUrlsInCSS(config)) {
  39388. return [publicFileToBuiltUrl(decodedUrl, config), void 0];
  39389. } else {
  39390. return [joinUrlSegments(config.base, decodedUrl), void 0];
  39391. }
  39392. }
  39393. const [id2, fragment] = decodedUrl.split("#");
  39394. let resolved = await resolveUrl(id2, importer);
  39395. if (resolved) {
  39396. if (fragment) resolved += "#" + fragment;
  39397. return [await fileToUrl$1(this, resolved), resolved];
  39398. }
  39399. if (config.command === "build") {
  39400. const isExternal = config.build.rollupOptions.external ? resolveUserExternal(
  39401. config.build.rollupOptions.external,
  39402. decodedUrl,
  39403. // use URL as id since id could not be resolved
  39404. id2,
  39405. false
  39406. ) : false;
  39407. if (!isExternal) {
  39408. config.logger.warnOnce(
  39409. `
  39410. ${decodedUrl} referenced in ${id2} didn't resolve at build time, it will remain unchanged to be resolved at runtime`
  39411. );
  39412. }
  39413. }
  39414. return [url, void 0];
  39415. };
  39416. const {
  39417. code: css,
  39418. modules,
  39419. deps,
  39420. map: map2
  39421. } = await compileCSS(
  39422. environment,
  39423. id,
  39424. raw,
  39425. preprocessorWorkerController,
  39426. urlResolver
  39427. );
  39428. if (modules) {
  39429. moduleCache.set(id, modules);
  39430. }
  39431. if (deps) {
  39432. for (const file of deps) {
  39433. this.addWatchFile(file);
  39434. }
  39435. }
  39436. return {
  39437. code: css,
  39438. map: map2
  39439. };
  39440. }
  39441. };
  39442. plugin.transform = transformHook.handler;
  39443. plugin.transform.handler = transformHook.handler;
  39444. return plugin;
  39445. }
  39446. function cssPostPlugin(config) {
  39447. const styles = /* @__PURE__ */ new Map();
  39448. let codeSplitEmitQueue = createSerialPromiseQueue();
  39449. const urlEmitQueue = createSerialPromiseQueue();
  39450. let pureCssChunks;
  39451. let hasEmitted = false;
  39452. let chunkCSSMap;
  39453. const rollupOptionsOutput = config.build.rollupOptions.output;
  39454. const assetFileNames = (Array.isArray(rollupOptionsOutput) ? rollupOptionsOutput[0] : rollupOptionsOutput)?.assetFileNames;
  39455. const getCssAssetDirname = (cssAssetName) => {
  39456. const cssAssetNameDir = path$b.dirname(cssAssetName);
  39457. if (!assetFileNames) {
  39458. return path$b.join(config.build.assetsDir, cssAssetNameDir);
  39459. } else if (typeof assetFileNames === "string") {
  39460. return path$b.join(path$b.dirname(assetFileNames), cssAssetNameDir);
  39461. } else {
  39462. return path$b.dirname(
  39463. assetFileNames({
  39464. type: "asset",
  39465. name: cssAssetName,
  39466. names: [cssAssetName],
  39467. originalFileName: null,
  39468. originalFileNames: [],
  39469. source: "/* vite internal call, ignore */"
  39470. })
  39471. );
  39472. }
  39473. };
  39474. function getCssBundleName() {
  39475. const cached = cssBundleNameCache.get(config);
  39476. if (cached) return cached;
  39477. const cssBundleName = config.build.lib ? resolveLibCssFilename(
  39478. config.build.lib,
  39479. config.root,
  39480. config.packageCache
  39481. ) : defaultCssBundleName;
  39482. cssBundleNameCache.set(config, cssBundleName);
  39483. return cssBundleName;
  39484. }
  39485. const plugin = {
  39486. name: "vite:css-post",
  39487. renderStart() {
  39488. pureCssChunks = /* @__PURE__ */ new Set();
  39489. hasEmitted = false;
  39490. chunkCSSMap = /* @__PURE__ */ new Map();
  39491. codeSplitEmitQueue = createSerialPromiseQueue();
  39492. },
  39493. transform: {
  39494. async handler(css, id) {
  39495. if (!isCSSRequest(id) || commonjsProxyRE.test(id) || SPECIAL_QUERY_RE.test(id)) {
  39496. return;
  39497. }
  39498. css = stripBomTag(css);
  39499. const inlineCSS = inlineCSSRE.test(id);
  39500. const isHTMLProxy = htmlProxyRE.test(id);
  39501. if (inlineCSS && isHTMLProxy) {
  39502. if (styleAttrRE.test(id)) {
  39503. css = css.replace(/"/g, "&quot;");
  39504. }
  39505. const index = htmlProxyIndexRE.exec(id)?.[1];
  39506. if (index == null) {
  39507. throw new Error(`HTML proxy index in "${id}" not found`);
  39508. }
  39509. addToHTMLProxyTransformResult(
  39510. `${getHash(cleanUrl(id))}_${Number.parseInt(index)}`,
  39511. css
  39512. );
  39513. return `export default ''`;
  39514. }
  39515. const inlined = inlineRE.test(id);
  39516. const modules = cssModulesCache.get(config).get(id);
  39517. const modulesCode = modules && !inlined && dataToEsm(modules, { namedExports: true, preferConst: true });
  39518. if (config.command === "serve") {
  39519. const getContentWithSourcemap = async (content) => {
  39520. if (config.css.devSourcemap) {
  39521. const sourcemap = this.getCombinedSourcemap();
  39522. if (sourcemap.mappings) {
  39523. await injectSourcesContent(
  39524. sourcemap,
  39525. cleanUrl(id),
  39526. config.logger
  39527. );
  39528. }
  39529. return getCodeWithSourcemap("css", content, sourcemap);
  39530. }
  39531. return content;
  39532. };
  39533. if (isDirectCSSRequest(id)) {
  39534. return null;
  39535. }
  39536. if (inlined) {
  39537. return `export default ${JSON.stringify(css)}`;
  39538. }
  39539. if (this.environment.config.consumer === "server") {
  39540. return modulesCode || "export {}";
  39541. }
  39542. const cssContent = await getContentWithSourcemap(css);
  39543. const code2 = [
  39544. `import { updateStyle as __vite__updateStyle, removeStyle as __vite__removeStyle } from ${JSON.stringify(
  39545. path$b.posix.join(config.base, CLIENT_PUBLIC_PATH)
  39546. )}`,
  39547. `const __vite__id = ${JSON.stringify(id)}`,
  39548. `const __vite__css = ${JSON.stringify(cssContent)}`,
  39549. `__vite__updateStyle(__vite__id, __vite__css)`,
  39550. // css modules exports change on edit so it can't self accept
  39551. `${modulesCode || "import.meta.hot.accept()"}`,
  39552. `import.meta.hot.prune(() => __vite__removeStyle(__vite__id))`
  39553. ].join("\n");
  39554. return { code: code2, map: { mappings: "" } };
  39555. }
  39556. if (!inlined) {
  39557. styles.set(id, css);
  39558. }
  39559. let code;
  39560. if (modulesCode) {
  39561. code = modulesCode;
  39562. } else if (inlined) {
  39563. let content = css;
  39564. if (config.build.cssMinify) {
  39565. content = await minifyCSS(content, config, true);
  39566. }
  39567. code = `export default ${JSON.stringify(content)}`;
  39568. } else {
  39569. code = "";
  39570. }
  39571. return {
  39572. code,
  39573. map: { mappings: "" },
  39574. // avoid the css module from being tree-shaken so that we can retrieve
  39575. // it in renderChunk()
  39576. moduleSideEffects: modulesCode || inlined ? false : "no-treeshake"
  39577. };
  39578. }
  39579. },
  39580. async renderChunk(code, chunk, opts, meta) {
  39581. let chunkCSS = "";
  39582. const renderedModules = new Proxy(
  39583. {},
  39584. {
  39585. get(_target, p) {
  39586. for (const name in meta.chunks) {
  39587. const modules = meta.chunks[name].modules;
  39588. const module = modules[p];
  39589. if (module) {
  39590. return module;
  39591. }
  39592. }
  39593. }
  39594. }
  39595. );
  39596. const isJsChunkEmpty = code === "" && !chunk.isEntry;
  39597. let isPureCssChunk = chunk.exports.length === 0;
  39598. const ids = Object.keys(chunk.modules);
  39599. for (const id of ids) {
  39600. if (styles.has(id)) {
  39601. if (transformOnlyRE.test(id)) {
  39602. continue;
  39603. }
  39604. const cssScopeTo = this.getModuleInfo(id)?.meta?.vite?.cssScopeTo;
  39605. if (cssScopeTo && !isCssScopeToRendered(cssScopeTo, renderedModules)) {
  39606. continue;
  39607. }
  39608. if (cssModuleRE.test(id)) {
  39609. isPureCssChunk = false;
  39610. }
  39611. chunkCSS += styles.get(id);
  39612. } else if (!isJsChunkEmpty) {
  39613. isPureCssChunk = false;
  39614. }
  39615. }
  39616. const publicAssetUrlMap = publicAssetUrlCache.get(config);
  39617. const resolveAssetUrlsInCss = (chunkCSS2, cssAssetName) => {
  39618. const encodedPublicUrls = encodePublicUrlsInCSS(config);
  39619. const relative = config.base === "./" || config.base === "";
  39620. const cssAssetDirname = encodedPublicUrls || relative ? slash$1(getCssAssetDirname(cssAssetName)) : void 0;
  39621. const toRelative = (filename) => {
  39622. const relativePath = normalizePath$3(
  39623. path$b.relative(cssAssetDirname, filename)
  39624. );
  39625. return relativePath[0] === "." ? relativePath : "./" + relativePath;
  39626. };
  39627. chunkCSS2 = chunkCSS2.replace(assetUrlRE, (_, fileHash, postfix = "") => {
  39628. const filename = this.getFileName(fileHash) + postfix;
  39629. chunk.viteMetadata.importedAssets.add(cleanUrl(filename));
  39630. return encodeURIPath(
  39631. toOutputFilePathInCss(
  39632. filename,
  39633. "asset",
  39634. cssAssetName,
  39635. "css",
  39636. config,
  39637. toRelative
  39638. )
  39639. );
  39640. });
  39641. if (encodedPublicUrls) {
  39642. const relativePathToPublicFromCSS = normalizePath$3(
  39643. path$b.relative(cssAssetDirname, "")
  39644. );
  39645. chunkCSS2 = chunkCSS2.replace(publicAssetUrlRE, (_, hash) => {
  39646. const publicUrl = publicAssetUrlMap.get(hash).slice(1);
  39647. return encodeURIPath(
  39648. toOutputFilePathInCss(
  39649. publicUrl,
  39650. "public",
  39651. cssAssetName,
  39652. "css",
  39653. config,
  39654. () => `${relativePathToPublicFromCSS}/${publicUrl}`
  39655. )
  39656. );
  39657. });
  39658. }
  39659. return chunkCSS2;
  39660. };
  39661. function ensureFileExt(name, ext) {
  39662. return normalizePath$3(
  39663. path$b.format({ ...path$b.parse(name), base: void 0, ext })
  39664. );
  39665. }
  39666. let s;
  39667. const urlEmitTasks = [];
  39668. if (code.includes("__VITE_CSS_URL__")) {
  39669. let match;
  39670. cssUrlAssetRE.lastIndex = 0;
  39671. while (match = cssUrlAssetRE.exec(code)) {
  39672. const [full, idHex] = match;
  39673. const id = Buffer.from(idHex, "hex").toString();
  39674. const originalFileName = cleanUrl(id);
  39675. const cssAssetName = ensureFileExt(
  39676. path$b.basename(originalFileName),
  39677. ".css"
  39678. );
  39679. if (!styles.has(id)) {
  39680. throw new Error(
  39681. `css content for ${JSON.stringify(id)} was not found`
  39682. );
  39683. }
  39684. let cssContent = styles.get(id);
  39685. cssContent = resolveAssetUrlsInCss(cssContent, cssAssetName);
  39686. urlEmitTasks.push({
  39687. cssAssetName,
  39688. originalFileName,
  39689. content: cssContent,
  39690. start: match.index,
  39691. end: match.index + full.length
  39692. });
  39693. }
  39694. }
  39695. await urlEmitQueue.run(
  39696. async () => Promise.all(
  39697. urlEmitTasks.map(async (info) => {
  39698. info.content = await finalizeCss(info.content, true, config);
  39699. })
  39700. )
  39701. );
  39702. if (urlEmitTasks.length > 0) {
  39703. const toRelativeRuntime = createToImportMetaURLBasedRelativeRuntime(
  39704. opts.format,
  39705. config.isWorker
  39706. );
  39707. s ||= new MagicString(code);
  39708. for (const {
  39709. cssAssetName,
  39710. originalFileName,
  39711. content,
  39712. start,
  39713. end
  39714. } of urlEmitTasks) {
  39715. const referenceId = this.emitFile({
  39716. type: "asset",
  39717. name: cssAssetName,
  39718. originalFileName,
  39719. source: content
  39720. });
  39721. const filename = this.getFileName(referenceId);
  39722. chunk.viteMetadata.importedAssets.add(cleanUrl(filename));
  39723. const replacement = toOutputFilePathInJS(
  39724. this.environment,
  39725. filename,
  39726. "asset",
  39727. chunk.fileName,
  39728. "js",
  39729. toRelativeRuntime
  39730. );
  39731. const replacementString = typeof replacement === "string" ? JSON.stringify(encodeURIPath(replacement)).slice(1, -1) : `"+${replacement.runtime}+"`;
  39732. s.update(start, end, replacementString);
  39733. }
  39734. }
  39735. if (chunkCSS) {
  39736. if (isPureCssChunk && (opts.format === "es" || opts.format === "cjs")) {
  39737. pureCssChunks.add(chunk);
  39738. }
  39739. if (this.environment.config.build.cssCodeSplit) {
  39740. if (opts.format === "es" || opts.format === "cjs") {
  39741. const isEntry = chunk.isEntry && isPureCssChunk;
  39742. const cssFullAssetName = ensureFileExt(chunk.name, ".css");
  39743. const cssAssetName = chunk.isEntry && (!chunk.facadeModuleId || !isCSSRequest(chunk.facadeModuleId)) ? path$b.basename(cssFullAssetName) : cssFullAssetName;
  39744. const originalFileName = getChunkOriginalFileName(
  39745. chunk,
  39746. config.root,
  39747. opts.format
  39748. );
  39749. chunkCSS = resolveAssetUrlsInCss(chunkCSS, cssAssetName);
  39750. chunkCSS = await codeSplitEmitQueue.run(async () => {
  39751. return finalizeCss(chunkCSS, true, config);
  39752. });
  39753. const referenceId = this.emitFile({
  39754. type: "asset",
  39755. name: cssAssetName,
  39756. originalFileName,
  39757. source: chunkCSS
  39758. });
  39759. if (isEntry) {
  39760. cssEntriesMap.get(this.environment).add(referenceId);
  39761. }
  39762. chunk.viteMetadata.importedCss.add(this.getFileName(referenceId));
  39763. } else if (this.environment.config.consumer === "client") {
  39764. chunkCSS = await finalizeCss(chunkCSS, true, config);
  39765. let cssString = JSON.stringify(chunkCSS);
  39766. cssString = renderAssetUrlInJS(this, chunk, opts, cssString)?.toString() || cssString;
  39767. const style = `__vite_style__`;
  39768. const injectCode = `var ${style} = document.createElement('style');${style}.textContent = ${cssString};document.head.appendChild(${style});`;
  39769. let injectionPoint;
  39770. const wrapIdx = code.indexOf("System.register");
  39771. const singleQuoteUseStrict = `'use strict';`;
  39772. const doubleQuoteUseStrict = `"use strict";`;
  39773. if (wrapIdx >= 0) {
  39774. const executeFnStart = code.indexOf("execute:", wrapIdx);
  39775. injectionPoint = code.indexOf("{", executeFnStart) + 1;
  39776. } else if (code.includes(singleQuoteUseStrict)) {
  39777. injectionPoint = code.indexOf(singleQuoteUseStrict) + singleQuoteUseStrict.length;
  39778. } else if (code.includes(doubleQuoteUseStrict)) {
  39779. injectionPoint = code.indexOf(doubleQuoteUseStrict) + doubleQuoteUseStrict.length;
  39780. } else {
  39781. throw new Error("Injection point for inlined CSS not found");
  39782. }
  39783. s ||= new MagicString(code);
  39784. s.appendRight(injectionPoint, injectCode);
  39785. }
  39786. } else {
  39787. chunkCSS = resolveAssetUrlsInCss(chunkCSS, getCssBundleName());
  39788. chunkCSSMap.set(chunk.fileName, chunkCSS);
  39789. }
  39790. }
  39791. if (s) {
  39792. if (config.build.sourcemap) {
  39793. return {
  39794. code: s.toString(),
  39795. map: s.generateMap({ hires: "boundary" })
  39796. };
  39797. } else {
  39798. return { code: s.toString() };
  39799. }
  39800. }
  39801. return null;
  39802. },
  39803. augmentChunkHash(chunk) {
  39804. if (chunk.viteMetadata?.importedCss.size) {
  39805. let hash = "";
  39806. for (const id of chunk.viteMetadata.importedCss) {
  39807. hash += id;
  39808. }
  39809. return hash;
  39810. }
  39811. },
  39812. async generateBundle(opts, bundle) {
  39813. if (opts.__vite_skip_asset_emit__) {
  39814. return;
  39815. }
  39816. if (!this.environment.config.build.cssCodeSplit && !hasEmitted) {
  39817. let collect2 = function(chunk) {
  39818. if (!chunk || chunk.type !== "chunk" || collected.has(chunk)) return;
  39819. collected.add(chunk);
  39820. chunk.imports.forEach((importName) => collect2(bundle[importName]));
  39821. chunk.dynamicImports.forEach(
  39822. (importName) => dynamicImports.add(importName)
  39823. );
  39824. extractedCss += chunkCSSMap.get(chunk.preliminaryFileName) ?? "";
  39825. };
  39826. let extractedCss = "";
  39827. const collected = /* @__PURE__ */ new Set();
  39828. const dynamicImports = /* @__PURE__ */ new Set();
  39829. for (const chunk of Object.values(bundle)) {
  39830. if (chunk.type === "chunk" && chunk.isEntry) {
  39831. collect2(chunk);
  39832. }
  39833. }
  39834. for (const chunkName of dynamicImports) {
  39835. collect2(bundle[chunkName]);
  39836. }
  39837. if (extractedCss) {
  39838. hasEmitted = true;
  39839. extractedCss = await finalizeCss(extractedCss, true, config);
  39840. this.emitFile({
  39841. name: getCssBundleName(),
  39842. type: "asset",
  39843. source: extractedCss,
  39844. // this file is an implicit entry point, use `style.css` as the original file name
  39845. // this name is also used as a key in the manifest
  39846. originalFileName: "style.css"
  39847. });
  39848. }
  39849. }
  39850. if (pureCssChunks.size) {
  39851. const prelimaryNameToChunkMap = Object.fromEntries(
  39852. Object.values(bundle).filter((chunk) => chunk.type === "chunk").map((chunk) => [chunk.preliminaryFileName, chunk.fileName])
  39853. );
  39854. const pureCssChunkNames = [...pureCssChunks].map((pureCssChunk) => prelimaryNameToChunkMap[pureCssChunk.fileName]).filter(Boolean);
  39855. const replaceEmptyChunk = getEmptyChunkReplacer(
  39856. pureCssChunkNames,
  39857. opts.format
  39858. );
  39859. for (const file in bundle) {
  39860. const chunk = bundle[file];
  39861. if (chunk.type === "chunk") {
  39862. let chunkImportsPureCssChunk = false;
  39863. chunk.imports = chunk.imports.filter((file2) => {
  39864. if (pureCssChunkNames.includes(file2)) {
  39865. const { importedCss, importedAssets } = bundle[file2].viteMetadata;
  39866. importedCss.forEach(
  39867. (file3) => chunk.viteMetadata.importedCss.add(file3)
  39868. );
  39869. importedAssets.forEach(
  39870. (file3) => chunk.viteMetadata.importedAssets.add(file3)
  39871. );
  39872. chunkImportsPureCssChunk = true;
  39873. return false;
  39874. }
  39875. return true;
  39876. });
  39877. if (chunkImportsPureCssChunk) {
  39878. chunk.code = replaceEmptyChunk(chunk.code);
  39879. }
  39880. }
  39881. }
  39882. const removedPureCssFiles = removedPureCssFilesCache.get(config);
  39883. pureCssChunkNames.forEach((fileName) => {
  39884. removedPureCssFiles.set(fileName, bundle[fileName]);
  39885. delete bundle[fileName];
  39886. delete bundle[`${fileName}.map`];
  39887. });
  39888. }
  39889. const cssAssets = Object.values(bundle).filter(
  39890. (asset) => asset.type === "asset" && asset.fileName.endsWith(".css")
  39891. );
  39892. for (const cssAsset of cssAssets) {
  39893. if (typeof cssAsset.source === "string") {
  39894. cssAsset.source = cssAsset.source.replace(viteHashUpdateMarkerRE, "");
  39895. }
  39896. }
  39897. }
  39898. };
  39899. const handler = plugin.transform.handler;
  39900. plugin.transform = handler;
  39901. plugin.transform.handler = handler;
  39902. return plugin;
  39903. }
  39904. function cssAnalysisPlugin(config) {
  39905. return {
  39906. name: "vite:css-analysis",
  39907. transform: {
  39908. async handler(_, id) {
  39909. if (!isCSSRequest(id) || commonjsProxyRE.test(id) || SPECIAL_QUERY_RE.test(id)) {
  39910. return;
  39911. }
  39912. const { moduleGraph } = this.environment;
  39913. const thisModule = moduleGraph.getModuleById(id);
  39914. if (thisModule) {
  39915. const isSelfAccepting = !cssModulesCache.get(config)?.get(id) && !inlineRE.test(id) && !htmlProxyRE.test(id);
  39916. const pluginImports = this._addedImports;
  39917. if (pluginImports) {
  39918. const depModules = /* @__PURE__ */ new Set();
  39919. for (const file of pluginImports) {
  39920. if (isCSSRequest(file)) {
  39921. depModules.add(moduleGraph.createFileOnlyEntry(file));
  39922. } else {
  39923. const url = await fileToDevUrl(
  39924. this.environment,
  39925. file,
  39926. /* skipBase */
  39927. true
  39928. );
  39929. if (url.startsWith("data:")) {
  39930. depModules.add(moduleGraph.createFileOnlyEntry(file));
  39931. } else {
  39932. depModules.add(await moduleGraph.ensureEntryFromUrl(url));
  39933. }
  39934. }
  39935. }
  39936. moduleGraph.updateModuleInfo(
  39937. thisModule,
  39938. depModules,
  39939. null,
  39940. // The root CSS proxy module is self-accepting and should not
  39941. // have an explicit accept list
  39942. /* @__PURE__ */ new Set(),
  39943. null,
  39944. isSelfAccepting
  39945. );
  39946. } else {
  39947. thisModule.isSelfAccepting = isSelfAccepting;
  39948. }
  39949. }
  39950. }
  39951. }
  39952. };
  39953. }
  39954. function isCssScopeToRendered(cssScopeTo, renderedModules) {
  39955. const [importerId, exp] = cssScopeTo;
  39956. const importer = renderedModules[importerId];
  39957. return importer && (exp === void 0 || importer.renderedExports.includes(exp));
  39958. }
  39959. function getEmptyChunkReplacer(pureCssChunkNames, outputFormat) {
  39960. const emptyChunkFiles = pureCssChunkNames.map((file) => escapeRegex(path$b.basename(file))).join("|");
  39961. const emptyChunkRE = new RegExp(
  39962. outputFormat === "es" ? `\\bimport\\s*["'][^"']*(?:${emptyChunkFiles})["'];` : `(\\b|,\\s*)require\\(\\s*["'][^"']*(?:${emptyChunkFiles})["']\\)(;|,)`,
  39963. "g"
  39964. );
  39965. return (code) => code.replace(
  39966. emptyChunkRE,
  39967. // remove css import while preserving source map location
  39968. (m, p1, p2) => {
  39969. if (outputFormat === "es") {
  39970. return `/* empty css ${"".padEnd(m.length - 15)}*/`;
  39971. }
  39972. if (p2 === ";") {
  39973. return `${p2}/* empty css ${"".padEnd(m.length - 16)}*/`;
  39974. }
  39975. return `${p1}/* empty css ${"".padEnd(m.length - 15 - p1.length)}*/`;
  39976. }
  39977. );
  39978. }
  39979. const fileURLWithWindowsDriveRE = /^file:\/\/\/[a-zA-Z]:\//;
  39980. function createCSSResolvers(config) {
  39981. let cssResolve;
  39982. let sassResolve;
  39983. let lessResolve;
  39984. return {
  39985. get css() {
  39986. return cssResolve ??= createBackCompatIdResolver(config, {
  39987. extensions: [".css"],
  39988. mainFields: ["style"],
  39989. conditions: ["style", DEV_PROD_CONDITION],
  39990. tryIndex: false,
  39991. preferRelative: true
  39992. });
  39993. },
  39994. get sass() {
  39995. if (!sassResolve) {
  39996. const resolver = createBackCompatIdResolver(config, {
  39997. extensions: [".scss", ".sass", ".css"],
  39998. mainFields: ["sass", "style"],
  39999. conditions: ["sass", "style", DEV_PROD_CONDITION],
  40000. tryIndex: true,
  40001. tryPrefix: "_",
  40002. preferRelative: true
  40003. });
  40004. sassResolve = async (...args) => {
  40005. if (args[1].startsWith("file://")) {
  40006. args[1] = fileURLToPath$1(args[1], {
  40007. windows: (
  40008. // file:///foo cannot be converted to path with windows mode
  40009. isWindows$3 && !fileURLWithWindowsDriveRE.test(args[1]) ? false : void 0
  40010. )
  40011. });
  40012. }
  40013. return resolver(...args);
  40014. };
  40015. }
  40016. return sassResolve;
  40017. },
  40018. get less() {
  40019. return lessResolve ??= createBackCompatIdResolver(config, {
  40020. extensions: [".less", ".css"],
  40021. mainFields: ["less", "style"],
  40022. conditions: ["less", "style", DEV_PROD_CONDITION],
  40023. tryIndex: false,
  40024. preferRelative: true
  40025. });
  40026. }
  40027. };
  40028. }
  40029. function getCssResolversKeys(resolvers) {
  40030. return Object.keys(resolvers);
  40031. }
  40032. async function compileCSSPreprocessors(environment, id, lang, code, workerController) {
  40033. const { config } = environment;
  40034. const { preprocessorOptions, devSourcemap } = config.css;
  40035. const atImportResolvers = getAtImportResolvers(
  40036. environment.getTopLevelConfig()
  40037. );
  40038. const opts = {
  40039. ...preprocessorOptions && preprocessorOptions[lang] || {},
  40040. alias: config.resolve.alias,
  40041. // important: set this for relative import resolving
  40042. filename: cleanUrl(id),
  40043. enableSourcemap: devSourcemap ?? false
  40044. };
  40045. const preProcessor = workerController[lang];
  40046. const preprocessResult = await preProcessor(
  40047. environment,
  40048. code,
  40049. config.root,
  40050. opts,
  40051. atImportResolvers
  40052. );
  40053. if (preprocessResult.error) {
  40054. throw preprocessResult.error;
  40055. }
  40056. let deps;
  40057. if (preprocessResult.deps.length > 0) {
  40058. const normalizedFilename = normalizePath$3(opts.filename);
  40059. deps = new Set(
  40060. [...preprocessResult.deps].filter(
  40061. (dep) => normalizePath$3(dep) !== normalizedFilename
  40062. )
  40063. );
  40064. }
  40065. return {
  40066. code: preprocessResult.code,
  40067. map: combineSourcemapsIfExists(
  40068. opts.filename,
  40069. preprocessResult.map,
  40070. preprocessResult.additionalMap
  40071. ),
  40072. deps
  40073. };
  40074. }
  40075. const configToAtImportResolvers = /* @__PURE__ */ new WeakMap();
  40076. function getAtImportResolvers(config) {
  40077. let atImportResolvers = configToAtImportResolvers.get(config);
  40078. if (!atImportResolvers) {
  40079. atImportResolvers = createCSSResolvers(config);
  40080. configToAtImportResolvers.set(config, atImportResolvers);
  40081. }
  40082. return atImportResolvers;
  40083. }
  40084. async function compileCSS(environment, id, code, workerController, urlResolver) {
  40085. const { config } = environment;
  40086. const lang = CSS_LANGS_RE.exec(id)?.[1];
  40087. const deps = /* @__PURE__ */ new Set();
  40088. let preprocessorMap;
  40089. if (isPreProcessor(lang)) {
  40090. const preprocessorResult = await compileCSSPreprocessors(
  40091. environment,
  40092. id,
  40093. lang,
  40094. code,
  40095. workerController
  40096. );
  40097. code = preprocessorResult.code;
  40098. preprocessorMap = preprocessorResult.map;
  40099. preprocessorResult.deps?.forEach((dep) => deps.add(dep));
  40100. } else if (lang === "sss" && config.css.transformer === "lightningcss") {
  40101. const sssResult = await transformSugarSS(environment, id, code);
  40102. code = sssResult.code;
  40103. preprocessorMap = sssResult.map;
  40104. }
  40105. const transformResult = await (config.css.transformer === "lightningcss" ? compileLightningCSS(
  40106. environment,
  40107. id,
  40108. code,
  40109. deps,
  40110. workerController,
  40111. urlResolver
  40112. ) : compilePostCSS(
  40113. environment,
  40114. id,
  40115. code,
  40116. deps,
  40117. lang,
  40118. workerController,
  40119. urlResolver
  40120. ));
  40121. if (!transformResult) {
  40122. return {
  40123. code,
  40124. map: config.css.devSourcemap ? preprocessorMap : { mappings: "" },
  40125. deps
  40126. };
  40127. }
  40128. return {
  40129. ...transformResult,
  40130. map: config.css.devSourcemap ? combineSourcemapsIfExists(
  40131. cleanUrl(id),
  40132. typeof transformResult.map === "string" ? JSON.parse(transformResult.map) : transformResult.map,
  40133. preprocessorMap
  40134. ) : { mappings: "" },
  40135. deps
  40136. };
  40137. }
  40138. async function compilePostCSS(environment, id, code, deps, lang, workerController, urlResolver) {
  40139. const { config } = environment;
  40140. const { modules: modulesOptions, devSourcemap } = config.css;
  40141. const isModule = modulesOptions !== false && cssModuleRE.test(id);
  40142. const needInlineImport = code.includes("@import");
  40143. const hasUrl = cssUrlRE.test(code) || cssImageSetRE.test(code);
  40144. const postcssConfig = await resolvePostcssConfig(
  40145. environment.getTopLevelConfig()
  40146. );
  40147. if (lang !== "sss" && !postcssConfig && !isModule && !needInlineImport && !hasUrl) {
  40148. return;
  40149. }
  40150. const atImportResolvers = getAtImportResolvers(
  40151. environment.getTopLevelConfig()
  40152. );
  40153. const postcssPlugins = postcssConfig?.plugins.slice() ?? [];
  40154. if (needInlineImport) {
  40155. postcssPlugins.unshift(
  40156. (await importPostcssImport()).default({
  40157. async resolve(id2, basedir) {
  40158. const publicFile = checkPublicFile(
  40159. id2,
  40160. environment.getTopLevelConfig()
  40161. );
  40162. if (publicFile) {
  40163. return publicFile;
  40164. }
  40165. const resolved = await atImportResolvers.css(
  40166. environment,
  40167. id2,
  40168. path$b.join(basedir, "*")
  40169. );
  40170. if (resolved) {
  40171. return path$b.resolve(resolved);
  40172. }
  40173. if (!path$b.isAbsolute(id2)) {
  40174. environment.logger.error(
  40175. colors$1.red(
  40176. `Unable to resolve \`@import "${id2}"\` from ${basedir}`
  40177. )
  40178. );
  40179. }
  40180. return id2;
  40181. },
  40182. async load(id2) {
  40183. const code2 = await fs__default.promises.readFile(id2, "utf-8");
  40184. const lang2 = CSS_LANGS_RE.exec(id2)?.[1];
  40185. if (isPreProcessor(lang2)) {
  40186. const result2 = await compileCSSPreprocessors(
  40187. environment,
  40188. id2,
  40189. lang2,
  40190. code2,
  40191. workerController
  40192. );
  40193. result2.deps?.forEach((dep) => deps.add(dep));
  40194. return result2.code;
  40195. }
  40196. return code2;
  40197. },
  40198. nameLayer(index) {
  40199. return `vite--anon-layer-${getHash(id)}-${index}`;
  40200. }
  40201. })
  40202. );
  40203. }
  40204. if (urlResolver && // when a postcss plugin is used (including the internal postcss plugins),
  40205. // we need to add this plugin regardless of whether
  40206. // this file contains url() or image-set(),
  40207. // because we don't know the content injected by those plugins
  40208. (postcssPlugins.length > 0 || isModule || hasUrl)) {
  40209. postcssPlugins.push(
  40210. UrlRewritePostcssPlugin({
  40211. resolver: urlResolver,
  40212. deps,
  40213. logger: environment.logger
  40214. })
  40215. );
  40216. }
  40217. let modules;
  40218. if (isModule) {
  40219. postcssPlugins.unshift(
  40220. (await importPostcssModules()).default({
  40221. ...modulesOptions,
  40222. localsConvention: modulesOptions?.localsConvention,
  40223. getJSON(cssFileName, _modules, outputFileName) {
  40224. modules = _modules;
  40225. if (modulesOptions && typeof modulesOptions.getJSON === "function") {
  40226. modulesOptions.getJSON(cssFileName, _modules, outputFileName);
  40227. }
  40228. },
  40229. async resolve(id2, importer) {
  40230. for (const key of getCssResolversKeys(atImportResolvers)) {
  40231. const resolved = await atImportResolvers[key](
  40232. environment,
  40233. id2,
  40234. importer
  40235. );
  40236. if (resolved) {
  40237. return path$b.resolve(resolved);
  40238. }
  40239. }
  40240. return id2;
  40241. }
  40242. })
  40243. );
  40244. }
  40245. const postcssOptions = postcssConfig?.options ?? {};
  40246. const postcssParser = lang === "sss" ? loadSss(config.root) : postcssOptions.parser;
  40247. if (!postcssPlugins.length && !postcssParser) {
  40248. return;
  40249. }
  40250. const result = await runPostCSS(
  40251. id,
  40252. code,
  40253. postcssPlugins,
  40254. { ...postcssOptions, parser: postcssParser },
  40255. deps,
  40256. environment.logger,
  40257. devSourcemap
  40258. );
  40259. return { ...result, modules };
  40260. }
  40261. async function transformSugarSS(environment, id, code) {
  40262. const { config } = environment;
  40263. const { devSourcemap } = config.css;
  40264. const result = await runPostCSS(
  40265. id,
  40266. code,
  40267. [],
  40268. { parser: loadSss(config.root) },
  40269. void 0,
  40270. environment.logger,
  40271. devSourcemap
  40272. );
  40273. return result;
  40274. }
  40275. async function runPostCSS(id, code, plugins, options, deps, logger, enableSourcemap) {
  40276. let postcssResult;
  40277. try {
  40278. const source = removeDirectQuery(id);
  40279. const postcss = await importPostcss();
  40280. postcssResult = await postcss.default(plugins).process(code, {
  40281. ...options,
  40282. to: source,
  40283. from: source,
  40284. ...enableSourcemap ? {
  40285. map: {
  40286. inline: false,
  40287. annotation: false,
  40288. // postcss may return virtual files
  40289. // we cannot obtain content of them, so this needs to be enabled
  40290. sourcesContent: true
  40291. // when "prev: preprocessorMap", the result map may include duplicate filename in `postcssResult.map.sources`
  40292. // prev: preprocessorMap,
  40293. }
  40294. } : {}
  40295. });
  40296. for (const message of postcssResult.messages) {
  40297. if (message.type === "dependency") {
  40298. deps?.add(normalizePath$3(message.file));
  40299. } else if (message.type === "dir-dependency") {
  40300. const { dir, glob: globPattern = "**" } = message;
  40301. const files = globSync(globPattern, {
  40302. absolute: true,
  40303. cwd: path$b.resolve(path$b.dirname(id), dir),
  40304. expandDirectories: false,
  40305. ignore: ["**/node_modules/**"]
  40306. });
  40307. for (let i = 0; i < files.length; i++) {
  40308. deps?.add(files[i]);
  40309. }
  40310. } else if (message.type === "warning") {
  40311. const warning = message;
  40312. let msg = `[vite:css][postcss] ${warning.text}`;
  40313. msg += `
  40314. ${generateCodeFrame(
  40315. code,
  40316. {
  40317. line: warning.line,
  40318. column: warning.column - 1
  40319. // 1-based
  40320. },
  40321. warning.endLine !== void 0 && warning.endColumn !== void 0 ? {
  40322. line: warning.endLine,
  40323. column: warning.endColumn - 1
  40324. // 1-based
  40325. } : void 0
  40326. )}`;
  40327. logger.warn(colors$1.yellow(msg));
  40328. }
  40329. }
  40330. } catch (e) {
  40331. e.message = `[postcss] ${e.message}`;
  40332. e.code = code;
  40333. e.loc = {
  40334. file: e.file,
  40335. line: e.line,
  40336. column: e.column - 1
  40337. // 1-based
  40338. };
  40339. throw e;
  40340. }
  40341. if (!enableSourcemap) {
  40342. return {
  40343. code: postcssResult.css,
  40344. map: { mappings: "" }
  40345. };
  40346. }
  40347. const rawPostcssMap = postcssResult.map.toJSON();
  40348. const postcssMap = await formatPostcssSourceMap(
  40349. // version property of rawPostcssMap is declared as string
  40350. // but actually it is a number
  40351. rawPostcssMap,
  40352. cleanUrl(id)
  40353. );
  40354. return {
  40355. code: postcssResult.css,
  40356. map: postcssMap
  40357. };
  40358. }
  40359. function createCachedImport(imp) {
  40360. let cached;
  40361. return () => {
  40362. if (!cached) {
  40363. cached = imp().then((module) => {
  40364. cached = module;
  40365. return module;
  40366. });
  40367. }
  40368. return cached;
  40369. };
  40370. }
  40371. const importPostcssImport = createCachedImport(() => import('./dep-AiMcmC_f.js').then(function (n) { return n.i; }));
  40372. const importPostcssModules = createCachedImport(() => import('./dep-SgSik2vo.js').then(function (n) { return n.i; }));
  40373. const importPostcss = createCachedImport(() => import('postcss'));
  40374. const preprocessorWorkerControllerCache = /* @__PURE__ */ new WeakMap();
  40375. let alwaysFakeWorkerWorkerControllerCache;
  40376. async function preprocessCSS(code, filename, config) {
  40377. let workerController = preprocessorWorkerControllerCache.get(config);
  40378. if (!workerController) {
  40379. alwaysFakeWorkerWorkerControllerCache ||= createPreprocessorWorkerController(0);
  40380. workerController = alwaysFakeWorkerWorkerControllerCache;
  40381. }
  40382. const environment = new PartialEnvironment(
  40383. "client",
  40384. config
  40385. );
  40386. return await compileCSS(environment, filename, code, workerController);
  40387. }
  40388. async function formatPostcssSourceMap(rawMap, file) {
  40389. const inputFileDir = path$b.dirname(file);
  40390. const sources = rawMap.sources.map((source) => {
  40391. const cleanSource = cleanUrl(decodeURIComponent(source));
  40392. if (cleanSource[0] === "<" && cleanSource.endsWith(">")) {
  40393. return `\0${cleanSource}`;
  40394. }
  40395. return normalizePath$3(path$b.resolve(inputFileDir, cleanSource));
  40396. });
  40397. return {
  40398. file,
  40399. mappings: rawMap.mappings,
  40400. names: rawMap.names,
  40401. sources,
  40402. sourcesContent: rawMap.sourcesContent,
  40403. version: rawMap.version
  40404. };
  40405. }
  40406. function combineSourcemapsIfExists(filename, map1, map2) {
  40407. if (!map1 || !map2) {
  40408. return map1;
  40409. }
  40410. if (map1.mappings === "" || map2.mappings === "") {
  40411. return { mappings: "" };
  40412. }
  40413. return combineSourcemaps(filename, [
  40414. // type of version property of ExistingRawSourceMap is number
  40415. // but it is always 3
  40416. map1,
  40417. map2
  40418. ]);
  40419. }
  40420. const viteHashUpdateMarker = "/*$vite$:1*/";
  40421. const viteHashUpdateMarkerRE = /\/\*\$vite\$:\d+\*\//;
  40422. async function finalizeCss(css, minify, config) {
  40423. if (css.includes("@import") || css.includes("@charset")) {
  40424. css = await hoistAtRules(css);
  40425. }
  40426. if (config.build.cssMinify) {
  40427. css = await minifyCSS(css, config, false);
  40428. }
  40429. css += viteHashUpdateMarker;
  40430. return css;
  40431. }
  40432. async function resolvePostcssConfig(config) {
  40433. let result = postcssConfigCache.get(config);
  40434. if (result !== void 0) {
  40435. return await result;
  40436. }
  40437. const inlineOptions = config.css.postcss;
  40438. if (isObject$1(inlineOptions)) {
  40439. const options = { ...inlineOptions };
  40440. delete options.plugins;
  40441. result = {
  40442. options,
  40443. plugins: inlineOptions.plugins || []
  40444. };
  40445. } else {
  40446. const searchPath = typeof inlineOptions === "string" ? inlineOptions : config.root;
  40447. const stopDir = searchForWorkspaceRoot(config.root);
  40448. result = postcssrc({}, searchPath, { stopDir }).catch((e) => {
  40449. if (!e.message.includes("No PostCSS Config found")) {
  40450. if (e instanceof Error) {
  40451. const { name, message, stack } = e;
  40452. e.name = "Failed to load PostCSS config";
  40453. e.message = `Failed to load PostCSS config (searchPath: ${searchPath}): [${name}] ${message}
  40454. ${stack}`;
  40455. e.stack = "";
  40456. throw e;
  40457. } else {
  40458. throw new Error(`Failed to load PostCSS config: ${e}`);
  40459. }
  40460. }
  40461. return null;
  40462. });
  40463. result.then(
  40464. (resolved) => {
  40465. postcssConfigCache.set(config, resolved);
  40466. },
  40467. () => {
  40468. }
  40469. );
  40470. }
  40471. postcssConfigCache.set(config, result);
  40472. return result;
  40473. }
  40474. const cssUrlRE = /(?<!@import\s+)(?<=^|[^\w\-\u0080-\uffff])url\((\s*('[^']+'|"[^"]+")\s*|[^'")]+)\)/;
  40475. const cssDataUriRE = /(?<=^|[^\w\-\u0080-\uffff])data-uri\((\s*('[^']+'|"[^"]+")\s*|[^'")]+)\)/;
  40476. const importCssRE = /@import\s+(?:url\()?('[^']+\.css'|"[^"]+\.css"|[^'"\s)]+\.css)/;
  40477. const cssImageSetRE = /(?<=image-set\()((?:[\w-]{1,256}\([^)]*\)|[^)])*)(?=\))/;
  40478. const UrlRewritePostcssPlugin = (opts) => {
  40479. if (!opts) {
  40480. throw new Error("base or replace is required");
  40481. }
  40482. return {
  40483. postcssPlugin: "vite-url-rewrite",
  40484. Once(root) {
  40485. const promises = [];
  40486. root.walkDecls((declaration) => {
  40487. const importer = declaration.source?.input.file;
  40488. if (!importer) {
  40489. opts.logger.warnOnce(
  40490. "\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."
  40491. );
  40492. }
  40493. const isCssUrl = cssUrlRE.test(declaration.value);
  40494. const isCssImageSet = cssImageSetRE.test(declaration.value);
  40495. if (isCssUrl || isCssImageSet) {
  40496. const replacerForDeclaration = async (rawUrl) => {
  40497. const [newUrl, resolvedId] = await opts.resolver(rawUrl, importer);
  40498. if (newUrl.startsWith("data:") && resolvedId) {
  40499. opts.deps.add(resolvedId);
  40500. }
  40501. return newUrl;
  40502. };
  40503. if (isCssUrl && isCssImageSet) {
  40504. promises.push(
  40505. rewriteCssUrls(declaration.value, replacerForDeclaration).then((url) => rewriteCssImageSet(url, replacerForDeclaration)).then((url) => {
  40506. declaration.value = url;
  40507. })
  40508. );
  40509. } else {
  40510. const rewriterToUse = isCssImageSet ? rewriteCssImageSet : rewriteCssUrls;
  40511. promises.push(
  40512. rewriterToUse(declaration.value, replacerForDeclaration).then(
  40513. (url) => {
  40514. declaration.value = url;
  40515. }
  40516. )
  40517. );
  40518. }
  40519. }
  40520. });
  40521. if (promises.length) {
  40522. return Promise.all(promises);
  40523. }
  40524. }
  40525. };
  40526. };
  40527. UrlRewritePostcssPlugin.postcss = true;
  40528. function rewriteCssUrls(css, replacer) {
  40529. return asyncReplace(css, cssUrlRE, async (match) => {
  40530. const [matched, rawUrl] = match;
  40531. return await doUrlReplace(rawUrl.trim(), matched, replacer);
  40532. });
  40533. }
  40534. function rewriteCssDataUris(css, replacer) {
  40535. return asyncReplace(css, cssDataUriRE, async (match) => {
  40536. const [matched, rawUrl] = match;
  40537. return await doUrlReplace(rawUrl.trim(), matched, replacer, "data-uri");
  40538. });
  40539. }
  40540. function rewriteImportCss(css, replacer) {
  40541. return asyncReplace(css, importCssRE, async (match) => {
  40542. const [matched, rawUrl] = match;
  40543. return await doImportCSSReplace(rawUrl, matched, replacer);
  40544. });
  40545. }
  40546. const cssNotProcessedRE = /(?:gradient|element|cross-fade|image)\(/;
  40547. async function rewriteCssImageSet(css, replacer) {
  40548. return await asyncReplace(css, cssImageSetRE, async (match) => {
  40549. const [, rawUrl] = match;
  40550. const url = await processSrcSet(rawUrl, async ({ url: url2 }) => {
  40551. if (cssUrlRE.test(url2)) {
  40552. return await rewriteCssUrls(url2, replacer);
  40553. }
  40554. if (!cssNotProcessedRE.test(url2)) {
  40555. return await doUrlReplace(url2, url2, replacer);
  40556. }
  40557. return url2;
  40558. });
  40559. return url;
  40560. });
  40561. }
  40562. function skipUrlReplacer(rawUrl) {
  40563. return isExternalUrl(rawUrl) || isDataUrl(rawUrl) || rawUrl[0] === "#" || functionCallRE.test(rawUrl);
  40564. }
  40565. async function doUrlReplace(rawUrl, matched, replacer, funcName = "url") {
  40566. let wrap = "";
  40567. const first = rawUrl[0];
  40568. if (first === `"` || first === `'`) {
  40569. wrap = first;
  40570. rawUrl = rawUrl.slice(1, -1);
  40571. }
  40572. if (skipUrlReplacer(rawUrl)) {
  40573. return matched;
  40574. }
  40575. let newUrl = await replacer(rawUrl);
  40576. if (wrap === "" && newUrl !== encodeURI(newUrl)) {
  40577. wrap = '"';
  40578. }
  40579. if (wrap === "'" && newUrl.includes("'")) {
  40580. wrap = '"';
  40581. }
  40582. if (wrap === '"' && newUrl.includes('"')) {
  40583. newUrl = newUrl.replace(nonEscapedDoubleQuoteRe, '\\"');
  40584. }
  40585. return `${funcName}(${wrap}${newUrl}${wrap})`;
  40586. }
  40587. async function doImportCSSReplace(rawUrl, matched, replacer) {
  40588. let wrap = "";
  40589. const first = rawUrl[0];
  40590. if (first === `"` || first === `'`) {
  40591. wrap = first;
  40592. rawUrl = rawUrl.slice(1, -1);
  40593. }
  40594. if (isExternalUrl(rawUrl) || isDataUrl(rawUrl) || rawUrl[0] === "#") {
  40595. return matched;
  40596. }
  40597. const prefix = matched.includes("url(") ? "url(" : "";
  40598. return `@import ${prefix}${wrap}${await replacer(rawUrl)}${wrap}`;
  40599. }
  40600. async function minifyCSS(css, config, inlined) {
  40601. if (config.build.cssMinify === "lightningcss") {
  40602. try {
  40603. const { code, warnings } = (await importLightningCSS()).transform({
  40604. ...config.css.lightningcss,
  40605. targets: convertTargets(config.build.cssTarget),
  40606. cssModules: void 0,
  40607. // TODO: Pass actual filename here, which can also be passed to esbuild's
  40608. // `sourcefile` option below to improve error messages
  40609. filename: defaultCssBundleName,
  40610. code: Buffer.from(css),
  40611. minify: true
  40612. });
  40613. for (const warning of warnings) {
  40614. let msg = `[lightningcss minify] ${warning.message}`;
  40615. msg += `
  40616. ${generateCodeFrame(css, {
  40617. line: warning.loc.line,
  40618. column: warning.loc.column - 1
  40619. // 1-based
  40620. })}`;
  40621. config.logger.warn(colors$1.yellow(msg));
  40622. }
  40623. return decoder.decode(code) + (inlined ? "" : "\n");
  40624. } catch (e) {
  40625. e.message = `[lightningcss minify] ${e.message}`;
  40626. const friendlyMessage = getLightningCssErrorMessageForIeSyntaxes(css);
  40627. if (friendlyMessage) {
  40628. e.message += friendlyMessage;
  40629. }
  40630. if (e.loc) {
  40631. e.loc = {
  40632. line: e.loc.line,
  40633. column: e.loc.column - 1
  40634. // 1-based
  40635. };
  40636. e.frame = generateCodeFrame(css, e.loc);
  40637. }
  40638. throw e;
  40639. }
  40640. }
  40641. try {
  40642. const { code, warnings } = await transform$1(css, {
  40643. loader: "css",
  40644. target: config.build.cssTarget || void 0,
  40645. ...resolveMinifyCssEsbuildOptions(config.esbuild || {})
  40646. });
  40647. if (warnings.length) {
  40648. const msgs = await formatMessages(warnings, { kind: "warning" });
  40649. config.logger.warn(
  40650. colors$1.yellow(`[esbuild css minify]
  40651. ${msgs.join("\n")}`)
  40652. );
  40653. }
  40654. return inlined ? code.trimEnd() : code;
  40655. } catch (e) {
  40656. if (e.errors) {
  40657. e.message = "[esbuild css minify] " + e.message;
  40658. const msgs = await formatMessages(e.errors, { kind: "error" });
  40659. e.frame = "\n" + msgs.join("\n");
  40660. e.loc = e.errors[0].location;
  40661. }
  40662. throw e;
  40663. }
  40664. }
  40665. function resolveMinifyCssEsbuildOptions(options) {
  40666. const base = {
  40667. charset: options.charset ?? "utf8",
  40668. logLevel: options.logLevel,
  40669. logLimit: options.logLimit,
  40670. logOverride: options.logOverride,
  40671. legalComments: options.legalComments
  40672. };
  40673. if (options.minifyIdentifiers != null || options.minifySyntax != null || options.minifyWhitespace != null) {
  40674. return {
  40675. ...base,
  40676. minifyIdentifiers: options.minifyIdentifiers ?? true,
  40677. minifySyntax: options.minifySyntax ?? true,
  40678. minifyWhitespace: options.minifyWhitespace ?? true
  40679. };
  40680. } else {
  40681. return { ...base, minify: true };
  40682. }
  40683. }
  40684. const atImportRE = /@import(?:\s*(?:url\([^)]*\)|"(?:[^"]|(?<=\\)")*"|'(?:[^']|(?<=\\)')*').*?|[^;]*);/g;
  40685. const atCharsetRE = /@charset(?:\s*(?:"(?:[^"]|(?<=\\)")*"|'(?:[^']|(?<=\\)')*').*?|[^;]*);/g;
  40686. async function hoistAtRules(css) {
  40687. const s = new MagicString(css);
  40688. const cleanCss = emptyCssComments(css);
  40689. let match;
  40690. atImportRE.lastIndex = 0;
  40691. while (match = atImportRE.exec(cleanCss)) {
  40692. s.remove(match.index, match.index + match[0].length);
  40693. s.appendLeft(0, match[0]);
  40694. }
  40695. atCharsetRE.lastIndex = 0;
  40696. let foundCharset = false;
  40697. while (match = atCharsetRE.exec(cleanCss)) {
  40698. s.remove(match.index, match.index + match[0].length);
  40699. if (!foundCharset) {
  40700. s.prepend(match[0]);
  40701. foundCharset = true;
  40702. }
  40703. }
  40704. return s.toString();
  40705. }
  40706. const loadedPreprocessorPath = {};
  40707. function loadPreprocessorPath(lang, root) {
  40708. const cached = loadedPreprocessorPath[lang];
  40709. if (cached) {
  40710. return cached;
  40711. }
  40712. try {
  40713. const resolved = requireResolveFromRootWithFallback(root, lang);
  40714. return loadedPreprocessorPath[lang] = resolved;
  40715. } catch (e) {
  40716. if (e.code === "MODULE_NOT_FOUND") {
  40717. const installCommand = getPackageManagerCommand("install");
  40718. throw new Error(
  40719. `Preprocessor dependency "${lang}" not found. Did you install it? Try \`${installCommand} -D ${lang}\`.`
  40720. );
  40721. } else {
  40722. const message = new Error(
  40723. `Preprocessor dependency "${lang}" failed to load:
  40724. ${e.message}`
  40725. );
  40726. message.stack = e.stack + "\n" + message.stack;
  40727. throw message;
  40728. }
  40729. }
  40730. }
  40731. function loadSassPackage(root) {
  40732. try {
  40733. const path2 = loadPreprocessorPath("sass-embedded", root);
  40734. return { name: "sass-embedded", path: path2 };
  40735. } catch (e1) {
  40736. try {
  40737. const path2 = loadPreprocessorPath("sass" /* sass */, root);
  40738. return { name: "sass", path: path2 };
  40739. } catch {
  40740. throw e1;
  40741. }
  40742. }
  40743. }
  40744. let cachedSss;
  40745. function loadSss(root) {
  40746. if (cachedSss) return cachedSss;
  40747. const sssPath = loadPreprocessorPath("sugarss" /* sss */, root);
  40748. cachedSss = createRequire$1(import.meta.url)(sssPath);
  40749. return cachedSss;
  40750. }
  40751. function cleanScssBugUrl(url) {
  40752. if (
  40753. // check bug via `window` and `location` global
  40754. typeof window !== "undefined" && typeof location !== "undefined" && typeof location.href === "string"
  40755. ) {
  40756. const prefix = location.href.replace(/\/$/, "");
  40757. return url.replace(prefix, "");
  40758. } else {
  40759. return url;
  40760. }
  40761. }
  40762. function fixScssBugImportValue(data) {
  40763. if (
  40764. // check bug via `window` and `location` global
  40765. typeof window !== "undefined" && typeof location !== "undefined" && data && "file" in data && (!("contents" in data) || data.contents == null)
  40766. ) {
  40767. data.contents = fs__default.readFileSync(data.file, "utf-8");
  40768. }
  40769. return data;
  40770. }
  40771. const makeScssWorker = (environment, resolvers, alias, maxWorkers, packageName) => {
  40772. const internalImporter = async (url, importer, filename) => {
  40773. importer = cleanScssBugUrl(importer);
  40774. const resolved = await resolvers.sass(environment, url, importer);
  40775. if (resolved) {
  40776. try {
  40777. const data = await rebaseUrls(
  40778. environment,
  40779. resolved,
  40780. filename,
  40781. alias,
  40782. "$",
  40783. resolvers.sass
  40784. );
  40785. if (packageName === "sass-embedded") {
  40786. return data;
  40787. }
  40788. return fixScssBugImportValue(data);
  40789. } catch (data) {
  40790. return data;
  40791. }
  40792. } else {
  40793. return null;
  40794. }
  40795. };
  40796. const worker = new WorkerWithFallback(
  40797. () => async (sassPath, data, options) => {
  40798. const sass = require(sassPath);
  40799. const path2 = require("node:path");
  40800. const _internalImporter = (url, importer2, done) => {
  40801. internalImporter(url, importer2, options.filename).then(
  40802. (data2) => done(data2)
  40803. );
  40804. };
  40805. const importer = [_internalImporter];
  40806. if (options.importer) {
  40807. if (Array.isArray(options.importer)) {
  40808. importer.unshift(...options.importer);
  40809. } else {
  40810. importer.unshift(options.importer);
  40811. }
  40812. }
  40813. const finalOptions = {
  40814. // support @import from node dependencies by default
  40815. includePaths: ["node_modules"],
  40816. ...options,
  40817. data,
  40818. file: options.filename,
  40819. outFile: options.filename,
  40820. importer,
  40821. ...options.enableSourcemap ? {
  40822. sourceMap: true,
  40823. omitSourceMapUrl: true,
  40824. sourceMapRoot: path2.dirname(options.filename)
  40825. } : {}
  40826. };
  40827. return new Promise((resolve, reject) => {
  40828. sass.render(finalOptions, (err, res) => {
  40829. if (err) {
  40830. reject(err);
  40831. } else {
  40832. resolve({
  40833. css: res.css.toString(),
  40834. map: res.map?.toString(),
  40835. stats: res.stats
  40836. });
  40837. }
  40838. });
  40839. });
  40840. },
  40841. {
  40842. parentFunctions: { internalImporter },
  40843. shouldUseFake(_sassPath, _data, options) {
  40844. return !!(options.functions && Object.keys(options.functions).length > 0 || options.importer && (!Array.isArray(options.importer) || options.importer.length > 0) || options.logger || options.pkgImporter);
  40845. },
  40846. max: maxWorkers
  40847. }
  40848. );
  40849. return worker;
  40850. };
  40851. const makeModernScssWorker = (environment, resolvers, alias, maxWorkers) => {
  40852. const internalCanonicalize = async (url, importer) => {
  40853. importer = cleanScssBugUrl(importer);
  40854. const resolved = await resolvers.sass(environment, url, importer);
  40855. return resolved ?? null;
  40856. };
  40857. const internalLoad = async (file, rootFile) => {
  40858. const result = await rebaseUrls(
  40859. environment,
  40860. file,
  40861. rootFile,
  40862. alias,
  40863. "$",
  40864. resolvers.sass
  40865. );
  40866. if (result.contents) {
  40867. return result.contents;
  40868. }
  40869. return await fsp.readFile(result.file, "utf-8");
  40870. };
  40871. const worker = new WorkerWithFallback(
  40872. () => async (sassPath, data, options) => {
  40873. const sass = require(sassPath);
  40874. const path2 = require("node:path");
  40875. const { fileURLToPath: fileURLToPath2, pathToFileURL: pathToFileURL2 } = (
  40876. // eslint-disable-next-line no-restricted-globals
  40877. require("node:url")
  40878. );
  40879. const sassOptions = { ...options };
  40880. sassOptions.url = pathToFileURL2(options.filename);
  40881. sassOptions.sourceMap = options.enableSourcemap;
  40882. const internalImporter = {
  40883. async canonicalize(url, context) {
  40884. const importer = context.containingUrl ? fileURLToPath2(context.containingUrl) : options.filename;
  40885. const resolved = await internalCanonicalize(url, importer);
  40886. if (resolved && // only limit to these extensions because:
  40887. // - for the `@import`/`@use`s written in file loaded by `load` function,
  40888. // the `canonicalize` function of that `importer` is called first
  40889. // - the `load` function of an importer is only called for the importer
  40890. // that returned a non-null result from its `canonicalize` function
  40891. (resolved.endsWith(".css") || resolved.endsWith(".scss") || resolved.endsWith(".sass"))) {
  40892. return pathToFileURL2(resolved);
  40893. }
  40894. return null;
  40895. },
  40896. async load(canonicalUrl) {
  40897. const ext = path2.extname(canonicalUrl.pathname);
  40898. let syntax = "scss";
  40899. if (ext === ".sass") {
  40900. syntax = "indented";
  40901. } else if (ext === ".css") {
  40902. syntax = "css";
  40903. }
  40904. const contents = await internalLoad(
  40905. fileURLToPath2(canonicalUrl),
  40906. options.filename
  40907. );
  40908. return { contents, syntax, sourceMapUrl: canonicalUrl };
  40909. }
  40910. };
  40911. sassOptions.importers = [
  40912. ...sassOptions.importers ?? [],
  40913. internalImporter
  40914. ];
  40915. const result = await sass.compileStringAsync(data, sassOptions);
  40916. return {
  40917. css: result.css,
  40918. map: result.sourceMap ? JSON.stringify(result.sourceMap) : void 0,
  40919. stats: {
  40920. includedFiles: result.loadedUrls.filter((url) => url.protocol === "file:").map((url) => fileURLToPath2(url))
  40921. }
  40922. };
  40923. },
  40924. {
  40925. parentFunctions: {
  40926. internalCanonicalize,
  40927. internalLoad
  40928. },
  40929. shouldUseFake(_sassPath, _data, options) {
  40930. return !!(options.functions && Object.keys(options.functions).length > 0 || options.importers && (!Array.isArray(options.importers) || options.importers.length > 0) || options.logger);
  40931. },
  40932. max: maxWorkers
  40933. }
  40934. );
  40935. return worker;
  40936. };
  40937. const makeModernCompilerScssWorker = (environment, resolvers, alias, _maxWorkers) => {
  40938. let compilerPromise;
  40939. const worker = {
  40940. async run(sassPath, data, options) {
  40941. const sass = (await import(pathToFileURL$1(sassPath).href)).default;
  40942. compilerPromise ??= sass.initAsyncCompiler();
  40943. const compiler = await compilerPromise;
  40944. const sassOptions = { ...options };
  40945. sassOptions.url = pathToFileURL$1(options.filename);
  40946. sassOptions.sourceMap = options.enableSourcemap;
  40947. const internalImporter = {
  40948. async canonicalize(url, context) {
  40949. const importer = context.containingUrl ? fileURLToPath$1(context.containingUrl) : options.filename;
  40950. const resolved = await resolvers.sass(
  40951. environment,
  40952. url,
  40953. cleanScssBugUrl(importer)
  40954. );
  40955. if (resolved && (resolved.endsWith(".css") || resolved.endsWith(".scss") || resolved.endsWith(".sass"))) {
  40956. return pathToFileURL$1(resolved);
  40957. }
  40958. return null;
  40959. },
  40960. async load(canonicalUrl) {
  40961. const ext = path$b.extname(canonicalUrl.pathname);
  40962. let syntax = "scss";
  40963. if (ext === ".sass") {
  40964. syntax = "indented";
  40965. } else if (ext === ".css") {
  40966. syntax = "css";
  40967. }
  40968. const result2 = await rebaseUrls(
  40969. environment,
  40970. fileURLToPath$1(canonicalUrl),
  40971. options.filename,
  40972. alias,
  40973. "$",
  40974. resolvers.sass
  40975. );
  40976. const contents = result2.contents ?? await fsp.readFile(result2.file, "utf-8");
  40977. return { contents, syntax, sourceMapUrl: canonicalUrl };
  40978. }
  40979. };
  40980. sassOptions.importers = [
  40981. ...sassOptions.importers ?? [],
  40982. internalImporter
  40983. ];
  40984. const result = await compiler.compileStringAsync(data, sassOptions);
  40985. return {
  40986. css: result.css,
  40987. map: result.sourceMap ? JSON.stringify(result.sourceMap) : void 0,
  40988. stats: {
  40989. includedFiles: result.loadedUrls.filter((url) => url.protocol === "file:").map((url) => fileURLToPath$1(url))
  40990. }
  40991. };
  40992. },
  40993. async stop() {
  40994. (await compilerPromise)?.dispose();
  40995. compilerPromise = void 0;
  40996. }
  40997. };
  40998. return worker;
  40999. };
  41000. const scssProcessor = (maxWorkers) => {
  41001. const workerMap = /* @__PURE__ */ new Map();
  41002. return {
  41003. close() {
  41004. for (const worker of workerMap.values()) {
  41005. worker.stop();
  41006. }
  41007. },
  41008. async process(environment, source, root, options, resolvers) {
  41009. const sassPackage = loadSassPackage(root);
  41010. const api = options.api ?? (sassPackage.name === "sass-embedded" ? "modern-compiler" : "modern");
  41011. if (!workerMap.has(options.alias)) {
  41012. workerMap.set(
  41013. options.alias,
  41014. api === "modern-compiler" ? makeModernCompilerScssWorker(
  41015. environment,
  41016. resolvers,
  41017. options.alias) : api === "modern" ? makeModernScssWorker(
  41018. environment,
  41019. resolvers,
  41020. options.alias,
  41021. maxWorkers
  41022. ) : makeScssWorker(
  41023. environment,
  41024. resolvers,
  41025. options.alias,
  41026. maxWorkers,
  41027. sassPackage.name
  41028. )
  41029. );
  41030. }
  41031. const worker = workerMap.get(options.alias);
  41032. const { content: data, map: additionalMap } = await getSource(
  41033. source,
  41034. options.filename,
  41035. options.additionalData,
  41036. options.enableSourcemap
  41037. );
  41038. const optionsWithoutAdditionalData = {
  41039. ...options,
  41040. additionalData: void 0
  41041. };
  41042. try {
  41043. const result = await worker.run(
  41044. sassPackage.path,
  41045. data,
  41046. // @ts-expect-error the correct worker is selected for `options.type`
  41047. optionsWithoutAdditionalData
  41048. );
  41049. const deps = result.stats.includedFiles.map((f) => cleanScssBugUrl(f));
  41050. const map2 = result.map ? JSON.parse(result.map.toString()) : void 0;
  41051. if (map2) {
  41052. map2.sources = map2.sources.map(
  41053. (url) => url.startsWith("file://") ? normalizePath$3(fileURLToPath$1(url)) : url
  41054. );
  41055. }
  41056. return {
  41057. code: result.css.toString(),
  41058. map: map2,
  41059. additionalMap,
  41060. deps
  41061. };
  41062. } catch (e) {
  41063. e.message = `[sass] ${e.message}`;
  41064. e.id = e.file;
  41065. e.frame = e.formatted;
  41066. if (e.span?.start) {
  41067. e.line = e.span.start.line + 1;
  41068. e.column = e.span.start.column + 1;
  41069. e.frame = e.message;
  41070. }
  41071. return { code: "", error: e, deps: [] };
  41072. }
  41073. }
  41074. };
  41075. };
  41076. async function rebaseUrls(environment, file, rootFile, alias, variablePrefix, resolver) {
  41077. file = path$b.resolve(file);
  41078. const fileDir = path$b.dirname(file);
  41079. const rootDir = path$b.dirname(rootFile);
  41080. if (fileDir === rootDir) {
  41081. return { file };
  41082. }
  41083. const content = await fsp.readFile(file, "utf-8");
  41084. const hasUrls = cssUrlRE.test(content);
  41085. const hasDataUris = cssDataUriRE.test(content);
  41086. const hasImportCss = importCssRE.test(content);
  41087. if (!hasUrls && !hasDataUris && !hasImportCss) {
  41088. return { file };
  41089. }
  41090. let rebased;
  41091. const rebaseFn = async (url) => {
  41092. if (url[0] === "/") return url;
  41093. if (url.startsWith(variablePrefix)) return url;
  41094. for (const { find } of alias) {
  41095. const matches = typeof find === "string" ? url.startsWith(find) : find.test(url);
  41096. if (matches) {
  41097. return url;
  41098. }
  41099. }
  41100. const absolute = await resolver(environment, url, file) || path$b.resolve(fileDir, url);
  41101. const relative = path$b.relative(rootDir, absolute);
  41102. return normalizePath$3(relative);
  41103. };
  41104. if (hasImportCss) {
  41105. rebased = await rewriteImportCss(content, rebaseFn);
  41106. }
  41107. if (hasUrls) {
  41108. rebased = await rewriteCssUrls(rebased || content, rebaseFn);
  41109. }
  41110. if (hasDataUris) {
  41111. rebased = await rewriteCssDataUris(rebased || content, rebaseFn);
  41112. }
  41113. return {
  41114. file,
  41115. contents: rebased
  41116. };
  41117. }
  41118. const makeLessWorker = (environment, resolvers, alias, maxWorkers) => {
  41119. const viteLessResolve = async (filename, dir, rootFile, mime) => {
  41120. const resolved = await resolvers.less(
  41121. environment,
  41122. filename,
  41123. path$b.join(dir, "*")
  41124. );
  41125. if (!resolved) return void 0;
  41126. if (mime === "application/javascript") {
  41127. const file = path$b.resolve(resolved);
  41128. return { resolved: file };
  41129. }
  41130. const result = await rebaseUrls(
  41131. environment,
  41132. resolved,
  41133. rootFile,
  41134. alias,
  41135. "@",
  41136. resolvers.less
  41137. );
  41138. return {
  41139. resolved,
  41140. contents: "contents" in result ? result.contents : void 0
  41141. };
  41142. };
  41143. const worker = new WorkerWithFallback(
  41144. () => {
  41145. const fsp2 = require("node:fs/promises");
  41146. const path2 = require("node:path");
  41147. let ViteLessManager;
  41148. const createViteLessPlugin = (less, rootFile) => {
  41149. const { FileManager } = less;
  41150. ViteLessManager ??= class ViteManager extends FileManager {
  41151. rootFile;
  41152. constructor(rootFile2) {
  41153. super();
  41154. this.rootFile = rootFile2;
  41155. }
  41156. supports(filename) {
  41157. return !/^(?:https?:)?\/\//.test(filename);
  41158. }
  41159. supportsSync() {
  41160. return false;
  41161. }
  41162. async loadFile(filename, dir, opts, env) {
  41163. const result = await viteLessResolve(
  41164. filename,
  41165. dir,
  41166. this.rootFile,
  41167. opts.mime
  41168. );
  41169. if (result) {
  41170. return {
  41171. filename: path2.resolve(result.resolved),
  41172. contents: result.contents ?? await fsp2.readFile(result.resolved, "utf-8")
  41173. };
  41174. } else {
  41175. return super.loadFile(filename, dir, opts, env);
  41176. }
  41177. }
  41178. };
  41179. return {
  41180. install(_, pluginManager) {
  41181. pluginManager.addFileManager(new ViteLessManager(rootFile));
  41182. },
  41183. minVersion: [3, 0, 0]
  41184. };
  41185. };
  41186. return async (lessPath, content, options) => {
  41187. const nodeLess = require(lessPath);
  41188. const viteResolverPlugin = createViteLessPlugin(
  41189. nodeLess,
  41190. options.filename
  41191. );
  41192. const result = await nodeLess.render(content, {
  41193. // support @import from node dependencies by default
  41194. paths: ["node_modules"],
  41195. ...options,
  41196. plugins: [viteResolverPlugin, ...options.plugins || []],
  41197. ...options.enableSourcemap ? {
  41198. sourceMap: {
  41199. outputSourceFiles: true,
  41200. sourceMapFileInline: false
  41201. }
  41202. } : {}
  41203. });
  41204. return result;
  41205. };
  41206. },
  41207. {
  41208. parentFunctions: { viteLessResolve },
  41209. shouldUseFake(_lessPath, _content, options) {
  41210. return !!options.plugins && options.plugins.length > 0;
  41211. },
  41212. max: maxWorkers
  41213. }
  41214. );
  41215. return worker;
  41216. };
  41217. const lessProcessor = (maxWorkers) => {
  41218. const workerMap = /* @__PURE__ */ new Map();
  41219. return {
  41220. close() {
  41221. for (const worker of workerMap.values()) {
  41222. worker.stop();
  41223. }
  41224. },
  41225. async process(environment, source, root, options, resolvers) {
  41226. const lessPath = loadPreprocessorPath("less" /* less */, root);
  41227. if (!workerMap.has(options.alias)) {
  41228. workerMap.set(
  41229. options.alias,
  41230. makeLessWorker(environment, resolvers, options.alias, maxWorkers)
  41231. );
  41232. }
  41233. const worker = workerMap.get(options.alias);
  41234. const { content, map: additionalMap } = await getSource(
  41235. source,
  41236. options.filename,
  41237. options.additionalData,
  41238. options.enableSourcemap
  41239. );
  41240. let result;
  41241. const optionsWithoutAdditionalData = {
  41242. ...options,
  41243. additionalData: void 0
  41244. };
  41245. try {
  41246. result = await worker.run(
  41247. lessPath,
  41248. content,
  41249. optionsWithoutAdditionalData
  41250. );
  41251. } catch (e) {
  41252. const error = e;
  41253. const normalizedError = new Error(
  41254. `[less] ${error.message || error.type}`
  41255. );
  41256. normalizedError.loc = {
  41257. file: error.filename || options.filename,
  41258. line: error.line,
  41259. column: error.column
  41260. };
  41261. return { code: "", error: normalizedError, deps: [] };
  41262. }
  41263. const map2 = result.map && JSON.parse(result.map);
  41264. if (map2) {
  41265. delete map2.sourcesContent;
  41266. }
  41267. return {
  41268. code: result.css.toString(),
  41269. map: map2,
  41270. additionalMap,
  41271. deps: result.imports
  41272. };
  41273. }
  41274. };
  41275. };
  41276. const makeStylWorker = (maxWorkers) => {
  41277. const worker = new WorkerWithFallback(
  41278. () => {
  41279. return async (stylusPath, content, root, options) => {
  41280. const nodeStylus = require(stylusPath);
  41281. const ref = nodeStylus(content, {
  41282. // support @import from node dependencies by default
  41283. paths: ["node_modules"],
  41284. ...options
  41285. });
  41286. if (options.define) {
  41287. for (const key in options.define) {
  41288. ref.define(key, options.define[key]);
  41289. }
  41290. }
  41291. if (options.enableSourcemap) {
  41292. ref.set("sourcemap", {
  41293. comment: false,
  41294. inline: false,
  41295. basePath: root
  41296. });
  41297. }
  41298. return {
  41299. code: ref.render(),
  41300. // @ts-expect-error sourcemap exists
  41301. map: ref.sourcemap,
  41302. deps: ref.deps()
  41303. };
  41304. };
  41305. },
  41306. {
  41307. shouldUseFake(_stylusPath, _content, _root, options) {
  41308. return !!(options.define && Object.values(options.define).some((d) => typeof d === "function"));
  41309. },
  41310. max: maxWorkers
  41311. }
  41312. );
  41313. return worker;
  41314. };
  41315. const stylProcessor = (maxWorkers) => {
  41316. const workerMap = /* @__PURE__ */ new Map();
  41317. return {
  41318. close() {
  41319. for (const worker of workerMap.values()) {
  41320. worker.stop();
  41321. }
  41322. },
  41323. async process(_environment, source, root, options, _resolvers) {
  41324. const stylusPath = loadPreprocessorPath("stylus" /* stylus */, root);
  41325. if (!workerMap.has(options.alias)) {
  41326. workerMap.set(options.alias, makeStylWorker(maxWorkers));
  41327. }
  41328. const worker = workerMap.get(options.alias);
  41329. const { content, map: additionalMap } = await getSource(
  41330. source,
  41331. options.filename,
  41332. options.additionalData,
  41333. options.enableSourcemap,
  41334. "\n"
  41335. );
  41336. const importsDeps = (options.imports ?? []).map(
  41337. (dep) => path$b.resolve(dep)
  41338. );
  41339. const optionsWithoutAdditionalData = {
  41340. ...options,
  41341. additionalData: void 0
  41342. };
  41343. try {
  41344. const { code, map: map2, deps } = await worker.run(
  41345. stylusPath,
  41346. content,
  41347. root,
  41348. optionsWithoutAdditionalData
  41349. );
  41350. return {
  41351. code,
  41352. map: formatStylusSourceMap(map2, root),
  41353. additionalMap,
  41354. // Concat imports deps with computed deps
  41355. deps: [...deps, ...importsDeps]
  41356. };
  41357. } catch (e) {
  41358. const wrapped = new Error(`[stylus] ${e.message}`);
  41359. wrapped.name = e.name;
  41360. wrapped.stack = e.stack;
  41361. return { code: "", error: wrapped, deps: [] };
  41362. }
  41363. }
  41364. };
  41365. };
  41366. function formatStylusSourceMap(mapBefore, root) {
  41367. if (!mapBefore) return void 0;
  41368. const map2 = { ...mapBefore };
  41369. const resolveFromRoot = (p) => normalizePath$3(path$b.resolve(root, p));
  41370. if (map2.file) {
  41371. map2.file = resolveFromRoot(map2.file);
  41372. }
  41373. map2.sources = map2.sources.map(resolveFromRoot);
  41374. return map2;
  41375. }
  41376. async function getSource(source, filename, additionalData, enableSourcemap, sep = "") {
  41377. if (!additionalData) return { content: source };
  41378. if (typeof additionalData === "function") {
  41379. const newContent = await additionalData(source, filename);
  41380. if (typeof newContent === "string") {
  41381. return { content: newContent };
  41382. }
  41383. return newContent;
  41384. }
  41385. if (!enableSourcemap) {
  41386. return { content: additionalData + sep + source };
  41387. }
  41388. const ms = new MagicString(source);
  41389. ms.appendLeft(0, sep);
  41390. ms.appendLeft(0, additionalData);
  41391. const map2 = ms.generateMap({ hires: "boundary" });
  41392. map2.file = filename;
  41393. map2.sources = [filename];
  41394. return {
  41395. content: ms.toString(),
  41396. map: map2
  41397. };
  41398. }
  41399. const createPreprocessorWorkerController = (maxWorkers) => {
  41400. const scss = scssProcessor(maxWorkers);
  41401. const less = lessProcessor(maxWorkers);
  41402. const styl = stylProcessor(maxWorkers);
  41403. const sassProcess = (environment, source, root, options, resolvers) => {
  41404. const opts = { ...options };
  41405. if (opts.api === "legacy") {
  41406. opts.indentedSyntax = true;
  41407. } else {
  41408. opts.syntax = "indented";
  41409. }
  41410. return scss.process(environment, source, root, opts, resolvers);
  41411. };
  41412. const close = () => {
  41413. less.close();
  41414. scss.close();
  41415. styl.close();
  41416. };
  41417. return {
  41418. ["less" /* less */]: less.process,
  41419. ["scss" /* scss */]: scss.process,
  41420. ["sass" /* sass */]: sassProcess,
  41421. ["styl" /* styl */]: styl.process,
  41422. ["stylus" /* stylus */]: styl.process,
  41423. close
  41424. };
  41425. };
  41426. const normalizeMaxWorkers = (maxWorker) => {
  41427. if (maxWorker === void 0) return 0;
  41428. if (maxWorker === true) return void 0;
  41429. return maxWorker;
  41430. };
  41431. const preprocessorSet = /* @__PURE__ */ new Set([
  41432. "less" /* less */,
  41433. "sass" /* sass */,
  41434. "scss" /* scss */,
  41435. "styl" /* styl */,
  41436. "stylus" /* stylus */
  41437. ]);
  41438. function isPreProcessor(lang) {
  41439. return lang && preprocessorSet.has(lang);
  41440. }
  41441. const importLightningCSS = createCachedImport(() => import('lightningcss'));
  41442. async function compileLightningCSS(environment, id, src, deps, workerController, urlResolver) {
  41443. const { config } = environment;
  41444. const filename = removeDirectQuery(id).replace("\0", NULL_BYTE_PLACEHOLDER);
  41445. let res;
  41446. try {
  41447. res = styleAttrRE.test(id) ? (await importLightningCSS()).transformStyleAttribute({
  41448. filename,
  41449. code: Buffer.from(src),
  41450. targets: config.css.lightningcss?.targets,
  41451. minify: config.isProduction && !!config.build.cssMinify,
  41452. analyzeDependencies: true
  41453. }) : await (await importLightningCSS()).bundleAsync({
  41454. ...config.css.lightningcss,
  41455. filename,
  41456. // projectRoot is needed to get stable hash when using CSS modules
  41457. projectRoot: config.root,
  41458. resolver: {
  41459. async read(filePath) {
  41460. if (filePath === filename) {
  41461. return src;
  41462. }
  41463. const code = fs__default.readFileSync(filePath, "utf-8");
  41464. const lang = CSS_LANGS_RE.exec(filePath)?.[1];
  41465. if (isPreProcessor(lang)) {
  41466. const result = await compileCSSPreprocessors(
  41467. environment,
  41468. id,
  41469. lang,
  41470. code,
  41471. workerController
  41472. );
  41473. result.deps?.forEach((dep) => deps.add(dep));
  41474. return result.code;
  41475. } else if (lang === "sss") {
  41476. const sssResult = await transformSugarSS(environment, id, code);
  41477. return sssResult.code;
  41478. }
  41479. return code;
  41480. },
  41481. async resolve(id2, from) {
  41482. const publicFile = checkPublicFile(
  41483. id2,
  41484. environment.getTopLevelConfig()
  41485. );
  41486. if (publicFile) {
  41487. return publicFile;
  41488. }
  41489. const atImportResolvers = getAtImportResolvers(
  41490. environment.getTopLevelConfig()
  41491. );
  41492. const lang = CSS_LANGS_RE.exec(from)?.[1];
  41493. let resolver;
  41494. switch (lang) {
  41495. case "css":
  41496. case "sss":
  41497. case "styl":
  41498. case "stylus":
  41499. case void 0:
  41500. resolver = atImportResolvers.css;
  41501. break;
  41502. case "sass":
  41503. case "scss":
  41504. resolver = atImportResolvers.sass;
  41505. break;
  41506. case "less":
  41507. resolver = atImportResolvers.less;
  41508. break;
  41509. default:
  41510. throw new Error(`Unknown lang: ${lang}`);
  41511. }
  41512. const resolved = await resolver(environment, id2, from);
  41513. if (resolved) {
  41514. deps.add(resolved);
  41515. return resolved;
  41516. }
  41517. return id2;
  41518. }
  41519. },
  41520. minify: config.isProduction && !!config.build.cssMinify,
  41521. sourceMap: config.command === "build" ? !!config.build.sourcemap : config.css.devSourcemap,
  41522. analyzeDependencies: true,
  41523. cssModules: cssModuleRE.test(id) ? config.css.lightningcss?.cssModules ?? true : void 0
  41524. });
  41525. } catch (e) {
  41526. e.message = `[lightningcss] ${e.message}`;
  41527. if (e.loc) {
  41528. e.loc = {
  41529. file: e.fileName.replace(NULL_BYTE_PLACEHOLDER, "\0"),
  41530. line: e.loc.line,
  41531. column: e.loc.column - 1
  41532. // 1-based
  41533. };
  41534. try {
  41535. const code = fs__default.readFileSync(e.fileName, "utf-8");
  41536. const friendlyMessage = getLightningCssErrorMessageForIeSyntaxes(code);
  41537. if (friendlyMessage) {
  41538. e.message += friendlyMessage;
  41539. }
  41540. } catch {
  41541. }
  41542. }
  41543. throw e;
  41544. }
  41545. for (const warning of res.warnings) {
  41546. let msg = `[vite:css][lightningcss] ${warning.message}`;
  41547. msg += `
  41548. ${generateCodeFrame(src, {
  41549. line: warning.loc.line,
  41550. column: warning.loc.column - 1
  41551. // 1-based
  41552. })}`;
  41553. environment.logger.warn(colors$1.yellow(msg));
  41554. }
  41555. let css = decoder.decode(res.code);
  41556. for (const dep of res.dependencies) {
  41557. switch (dep.type) {
  41558. case "url": {
  41559. let replaceUrl;
  41560. if (skipUrlReplacer(dep.url)) {
  41561. replaceUrl = dep.url;
  41562. } else if (urlResolver) {
  41563. const [newUrl, resolvedId] = await urlResolver(
  41564. dep.url,
  41565. dep.loc.filePath.replace(NULL_BYTE_PLACEHOLDER, "\0")
  41566. );
  41567. if (newUrl.startsWith("data:") && resolvedId) {
  41568. deps.add(resolvedId);
  41569. }
  41570. replaceUrl = newUrl;
  41571. } else {
  41572. replaceUrl = dep.url;
  41573. }
  41574. css = css.replace(
  41575. dep.placeholder,
  41576. // lightningcss always generates `url("placeholder")`
  41577. // (`url('placeholder')`, `url(placeholder)` is not generated)
  41578. // so escape double quotes
  41579. () => replaceUrl.replaceAll('"', '\\"')
  41580. );
  41581. break;
  41582. }
  41583. default:
  41584. throw new Error(`Unsupported dependency type: ${dep.type}`);
  41585. }
  41586. }
  41587. let modules;
  41588. if ("exports" in res && res.exports) {
  41589. modules = {};
  41590. const sortedEntries = Object.entries(res.exports).sort(
  41591. (a, b) => a[0].localeCompare(b[0])
  41592. );
  41593. for (const [key, value] of sortedEntries) {
  41594. modules[key] = value.name;
  41595. for (const c of value.composes) {
  41596. modules[key] += " " + c.name;
  41597. }
  41598. }
  41599. }
  41600. return {
  41601. code: css,
  41602. map: "map" in res ? res.map?.toString() : void 0,
  41603. modules
  41604. };
  41605. }
  41606. function getLightningCssErrorMessageForIeSyntaxes(code) {
  41607. 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.";
  41608. if (/[\s;{]\*[a-zA-Z-][\w-]+\s*:/.test(code)) {
  41609. return ".\nThis file contains star property hack (e.g. `*zoom`)" + commonIeMessage;
  41610. }
  41611. if (/min-width:\s*0\\0/.test(code)) {
  41612. return ".\nThis file contains @media zero hack (e.g. `@media (min-width: 0\\0)`)" + commonIeMessage;
  41613. }
  41614. return void 0;
  41615. }
  41616. const map = {
  41617. chrome: "chrome",
  41618. edge: "edge",
  41619. firefox: "firefox",
  41620. hermes: false,
  41621. ie: "ie",
  41622. ios: "ios_saf",
  41623. node: false,
  41624. opera: "opera",
  41625. rhino: false,
  41626. safari: "safari"
  41627. };
  41628. const esMap = {
  41629. // https://caniuse.com/?search=es2015
  41630. 2015: ["chrome49", "edge13", "safari10", "firefox44", "opera36"],
  41631. // https://caniuse.com/?search=es2016
  41632. 2016: ["chrome50", "edge13", "safari10", "firefox43", "opera37"],
  41633. // https://caniuse.com/?search=es2017
  41634. 2017: ["chrome58", "edge15", "safari11", "firefox52", "opera45"],
  41635. // https://caniuse.com/?search=es2018
  41636. 2018: ["chrome63", "edge79", "safari12", "firefox58", "opera50"],
  41637. // https://caniuse.com/?search=es2019
  41638. 2019: ["chrome73", "edge79", "safari12.1", "firefox64", "opera60"],
  41639. // https://caniuse.com/?search=es2020
  41640. 2020: ["chrome80", "edge80", "safari14.1", "firefox80", "opera67"],
  41641. // https://caniuse.com/?search=es2021
  41642. 2021: ["chrome85", "edge85", "safari14.1", "firefox80", "opera71"],
  41643. // https://caniuse.com/?search=es2022
  41644. 2022: ["chrome94", "edge94", "safari16.4", "firefox93", "opera80"],
  41645. // https://caniuse.com/?search=es2023
  41646. 2023: ["chrome110", "edge110", "safari16.4", "opera96"]
  41647. };
  41648. const esRE = /es(\d{4})/;
  41649. const versionRE = /\d/;
  41650. const convertTargetsCache = /* @__PURE__ */ new Map();
  41651. const convertTargets = (esbuildTarget) => {
  41652. if (!esbuildTarget) return {};
  41653. const cached = convertTargetsCache.get(esbuildTarget);
  41654. if (cached) return cached;
  41655. const targets = {};
  41656. const entriesWithoutES = arraify(esbuildTarget).flatMap((e) => {
  41657. const match = esRE.exec(e);
  41658. if (!match) return e;
  41659. const year = Number(match[1]);
  41660. if (!esMap[year]) throw new Error(`Unsupported target "${e}"`);
  41661. return esMap[year];
  41662. });
  41663. for (const entry of entriesWithoutES) {
  41664. if (entry === "esnext") continue;
  41665. const index = entry.search(versionRE);
  41666. if (index >= 0) {
  41667. const browser = map[entry.slice(0, index)];
  41668. if (browser === false) continue;
  41669. if (browser) {
  41670. const [major, minor = 0] = entry.slice(index).split(".").map((v) => parseInt(v, 10));
  41671. if (!isNaN(major) && !isNaN(minor)) {
  41672. const version = major << 16 | minor << 8;
  41673. if (!targets[browser] || version < targets[browser]) {
  41674. targets[browser] = version;
  41675. }
  41676. continue;
  41677. }
  41678. }
  41679. }
  41680. throw new Error(`Unsupported target "${entry}"`);
  41681. }
  41682. convertTargetsCache.set(esbuildTarget, targets);
  41683. return targets;
  41684. };
  41685. function resolveLibCssFilename(libOptions, root, packageCache) {
  41686. if (typeof libOptions.cssFileName === "string") {
  41687. return `${libOptions.cssFileName}.css`;
  41688. } else if (typeof libOptions.fileName === "string") {
  41689. return `${libOptions.fileName}.css`;
  41690. }
  41691. const packageJson = findNearestMainPackageData(root, packageCache)?.data;
  41692. const name = packageJson ? getPkgName(packageJson.name) : void 0;
  41693. if (!name)
  41694. throw new Error(
  41695. 'Name in package.json is required if option "build.lib.cssFileName" is not provided.'
  41696. );
  41697. return `${name}.css`;
  41698. }
  41699. const isModernFlag = `__VITE_IS_MODERN__`;
  41700. const preloadMethod = `__vitePreload`;
  41701. const preloadMarker = `__VITE_PRELOAD__`;
  41702. const preloadHelperId = "\0vite/preload-helper.js";
  41703. const preloadMarkerRE = new RegExp(preloadMarker, "g");
  41704. const dynamicImportPrefixRE = /import\s*\(/;
  41705. const dynamicImportTreeshakenRE = /((?:\bconst\s+|\blet\s+|\bvar\s+|,\s*)(\{[^{}.=]+\})\s*=\s*await\s+import\([^)]+\))|(\(\s*await\s+import\([^)]+\)\s*\)(\??\.[\w$]+))|\bimport\([^)]+\)(\s*\.then\(\s*(?:function\s*)?\(\s*\{([^{}.=]+)\}\))/g;
  41706. function toRelativePath(filename, importer) {
  41707. const relPath = path$b.posix.relative(path$b.posix.dirname(importer), filename);
  41708. return relPath[0] === "." ? relPath : `./${relPath}`;
  41709. }
  41710. function indexOfMatchInSlice(str, reg, pos = 0) {
  41711. reg.lastIndex = pos;
  41712. const result = reg.exec(str);
  41713. return result?.index ?? -1;
  41714. }
  41715. function detectScriptRel() {
  41716. const relList = typeof document !== "undefined" && document.createElement("link").relList;
  41717. return relList && relList.supports && relList.supports("modulepreload") ? "modulepreload" : "preload";
  41718. }
  41719. function preload(baseModule, deps, importerUrl) {
  41720. let promise = Promise.resolve();
  41721. if (__VITE_IS_MODERN__ && deps && deps.length > 0) {
  41722. let allSettled2 = function(promises) {
  41723. return Promise.all(
  41724. promises.map(
  41725. (p) => Promise.resolve(p).then(
  41726. (value) => ({ status: "fulfilled", value }),
  41727. (reason) => ({ status: "rejected", reason })
  41728. )
  41729. )
  41730. );
  41731. };
  41732. const links = document.getElementsByTagName("link");
  41733. const cspNonceMeta = document.querySelector(
  41734. "meta[property=csp-nonce]"
  41735. );
  41736. const cspNonce = cspNonceMeta?.nonce || cspNonceMeta?.getAttribute("nonce");
  41737. promise = allSettled2(
  41738. deps.map((dep) => {
  41739. dep = assetsURL(dep, importerUrl);
  41740. if (dep in seen) return;
  41741. seen[dep] = true;
  41742. const isCss = dep.endsWith(".css");
  41743. const cssSelector = isCss ? '[rel="stylesheet"]' : "";
  41744. const isBaseRelative = !!importerUrl;
  41745. if (isBaseRelative) {
  41746. for (let i = links.length - 1; i >= 0; i--) {
  41747. const link2 = links[i];
  41748. if (link2.href === dep && (!isCss || link2.rel === "stylesheet")) {
  41749. return;
  41750. }
  41751. }
  41752. } else if (document.querySelector(`link[href="${dep}"]${cssSelector}`)) {
  41753. return;
  41754. }
  41755. const link = document.createElement("link");
  41756. link.rel = isCss ? "stylesheet" : scriptRel;
  41757. if (!isCss) {
  41758. link.as = "script";
  41759. }
  41760. link.crossOrigin = "";
  41761. link.href = dep;
  41762. if (cspNonce) {
  41763. link.setAttribute("nonce", cspNonce);
  41764. }
  41765. document.head.appendChild(link);
  41766. if (isCss) {
  41767. return new Promise((res, rej) => {
  41768. link.addEventListener("load", res);
  41769. link.addEventListener(
  41770. "error",
  41771. () => rej(new Error(`Unable to preload CSS for ${dep}`))
  41772. );
  41773. });
  41774. }
  41775. })
  41776. );
  41777. }
  41778. function handlePreloadError(err) {
  41779. const e = new Event("vite:preloadError", {
  41780. cancelable: true
  41781. });
  41782. e.payload = err;
  41783. window.dispatchEvent(e);
  41784. if (!e.defaultPrevented) {
  41785. throw err;
  41786. }
  41787. }
  41788. return promise.then((res) => {
  41789. for (const item of res || []) {
  41790. if (item.status !== "rejected") continue;
  41791. handlePreloadError(item.reason);
  41792. }
  41793. return baseModule().catch(handlePreloadError);
  41794. });
  41795. }
  41796. function buildImportAnalysisPlugin(config) {
  41797. const getInsertPreload = (environment) => environment.config.consumer === "client" && !config.isWorker && !config.build.lib;
  41798. const renderBuiltUrl = config.experimental.renderBuiltUrl;
  41799. const isRelativeBase = config.base === "./" || config.base === "";
  41800. return {
  41801. name: "vite:build-import-analysis",
  41802. resolveId: {
  41803. handler(id) {
  41804. if (id === preloadHelperId) {
  41805. return id;
  41806. }
  41807. }
  41808. },
  41809. load: {
  41810. handler(id) {
  41811. if (id === preloadHelperId) {
  41812. const { modulePreload } = this.environment.config.build;
  41813. const scriptRel2 = modulePreload && modulePreload.polyfill ? `'modulepreload'` : `/* @__PURE__ */ (${detectScriptRel.toString()})()`;
  41814. const assetsURL2 = renderBuiltUrl || isRelativeBase ? (
  41815. // If `experimental.renderBuiltUrl` is used, the dependencies might be relative to the current chunk.
  41816. // If relative base is used, the dependencies are relative to the current chunk.
  41817. // The importerUrl is passed as third parameter to __vitePreload in this case
  41818. `function(dep, importerUrl) { return new URL(dep, importerUrl).href }`
  41819. ) : (
  41820. // If the base isn't relative, then the deps are relative to the projects `outDir` and the base
  41821. // is appended inside __vitePreload too.
  41822. `function(dep) { return ${JSON.stringify(config.base)}+dep }`
  41823. );
  41824. const preloadCode = `const scriptRel = ${scriptRel2};const assetsURL = ${assetsURL2};const seen = {};export const ${preloadMethod} = ${preload.toString()}`;
  41825. return { code: preloadCode, moduleSideEffects: false };
  41826. }
  41827. }
  41828. },
  41829. transform: {
  41830. async handler(source, importer) {
  41831. if (isInNodeModules$1(importer) && !dynamicImportPrefixRE.test(source)) {
  41832. return;
  41833. }
  41834. await init;
  41835. let imports = [];
  41836. try {
  41837. imports = parse$d(source)[0];
  41838. } catch (_e) {
  41839. const e = _e;
  41840. const { message, showCodeFrame } = createParseErrorInfo(
  41841. importer,
  41842. source
  41843. );
  41844. this.error(message, showCodeFrame ? e.idx : void 0);
  41845. }
  41846. if (!imports.length) {
  41847. return null;
  41848. }
  41849. const insertPreload = getInsertPreload(this.environment);
  41850. const dynamicImports = {};
  41851. if (insertPreload) {
  41852. let match;
  41853. while (match = dynamicImportTreeshakenRE.exec(source)) {
  41854. if (match[1]) {
  41855. dynamicImports[dynamicImportTreeshakenRE.lastIndex] = {
  41856. declaration: `const ${match[2]}`,
  41857. names: match[2]?.trim()
  41858. };
  41859. continue;
  41860. }
  41861. if (match[3]) {
  41862. let names2 = /\.([^.?]+)/.exec(match[4])?.[1] || "";
  41863. if (names2 === "default") {
  41864. names2 = "default: __vite_default__";
  41865. }
  41866. dynamicImports[dynamicImportTreeshakenRE.lastIndex - match[4]?.length - 1] = { declaration: `const {${names2}}`, names: `{ ${names2} }` };
  41867. continue;
  41868. }
  41869. const names = match[6]?.trim();
  41870. dynamicImports[dynamicImportTreeshakenRE.lastIndex - match[5]?.length] = { declaration: `const {${names}}`, names: `{ ${names} }` };
  41871. }
  41872. }
  41873. let s;
  41874. const str = () => s || (s = new MagicString(source));
  41875. let needPreloadHelper = false;
  41876. for (let index = 0; index < imports.length; index++) {
  41877. const {
  41878. s: start,
  41879. e: end,
  41880. ss: expStart,
  41881. se: expEnd,
  41882. d: dynamicIndex,
  41883. a: attributeIndex
  41884. } = imports[index];
  41885. const isDynamicImport = dynamicIndex > -1;
  41886. if (!isDynamicImport && attributeIndex > -1) {
  41887. str().remove(end + 1, expEnd);
  41888. }
  41889. if (isDynamicImport && insertPreload && // Only preload static urls
  41890. (source[start] === '"' || source[start] === "'" || source[start] === "`")) {
  41891. needPreloadHelper = true;
  41892. const { declaration, names } = dynamicImports[expEnd] || {};
  41893. if (names) {
  41894. str().prependLeft(
  41895. expStart,
  41896. `${preloadMethod}(async () => { ${declaration} = await `
  41897. );
  41898. str().appendRight(expEnd, `;return ${names}}`);
  41899. } else {
  41900. str().prependLeft(expStart, `${preloadMethod}(() => `);
  41901. }
  41902. str().appendRight(
  41903. expEnd,
  41904. `,${isModernFlag}?${preloadMarker}:void 0${renderBuiltUrl || isRelativeBase ? ",import.meta.url" : ""})`
  41905. );
  41906. }
  41907. }
  41908. if (needPreloadHelper && insertPreload && !source.includes(`const ${preloadMethod} =`)) {
  41909. str().prepend(
  41910. `import { ${preloadMethod} } from "${preloadHelperId}";`
  41911. );
  41912. }
  41913. if (s) {
  41914. return {
  41915. code: s.toString(),
  41916. map: this.environment.config.build.sourcemap ? s.generateMap({ hires: "boundary" }) : null
  41917. };
  41918. }
  41919. }
  41920. },
  41921. renderChunk(code, _, { format }) {
  41922. if (code.indexOf(isModernFlag) > -1) {
  41923. const re = new RegExp(isModernFlag, "g");
  41924. const isModern = String(format === "es");
  41925. const isModernWithPadding = isModern + " ".repeat(isModernFlag.length - isModern.length);
  41926. return {
  41927. code: code.replace(re, isModernWithPadding),
  41928. map: null
  41929. };
  41930. }
  41931. return null;
  41932. },
  41933. generateBundle({ format }, bundle) {
  41934. if (format !== "es") {
  41935. return;
  41936. }
  41937. if (!getInsertPreload(this.environment)) {
  41938. const removedPureCssFiles = removedPureCssFilesCache.get(config);
  41939. if (removedPureCssFiles && removedPureCssFiles.size > 0) {
  41940. for (const file in bundle) {
  41941. const chunk = bundle[file];
  41942. if (chunk.type === "chunk" && chunk.code.includes("import")) {
  41943. const code = chunk.code;
  41944. let imports;
  41945. try {
  41946. imports = parse$d(code)[0].filter((i) => i.d > -1);
  41947. } catch (e) {
  41948. const loc = numberToPos(code, e.idx);
  41949. this.error({
  41950. name: e.name,
  41951. message: e.message,
  41952. stack: e.stack,
  41953. cause: e.cause,
  41954. pos: e.idx,
  41955. loc: { ...loc, file: chunk.fileName },
  41956. frame: generateCodeFrame(code, loc)
  41957. });
  41958. }
  41959. for (const imp of imports) {
  41960. const {
  41961. n: name,
  41962. s: start,
  41963. e: end,
  41964. ss: expStart,
  41965. se: expEnd
  41966. } = imp;
  41967. let url = name;
  41968. if (!url) {
  41969. const rawUrl = code.slice(start, end);
  41970. if (rawUrl[0] === `"` && rawUrl.endsWith(`"`))
  41971. url = rawUrl.slice(1, -1);
  41972. }
  41973. if (!url) continue;
  41974. const normalizedFile = path$b.posix.join(
  41975. path$b.posix.dirname(chunk.fileName),
  41976. url
  41977. );
  41978. if (removedPureCssFiles.has(normalizedFile)) {
  41979. chunk.code = chunk.code.slice(0, expStart) + `Promise.resolve({${"".padEnd(expEnd - expStart - 19, " ")}})` + chunk.code.slice(expEnd);
  41980. }
  41981. }
  41982. }
  41983. }
  41984. }
  41985. return;
  41986. }
  41987. const buildSourcemap = this.environment.config.build.sourcemap;
  41988. const { modulePreload } = this.environment.config.build;
  41989. for (const file in bundle) {
  41990. const chunk = bundle[file];
  41991. if (chunk.type === "chunk" && chunk.code.indexOf(preloadMarker) > -1) {
  41992. const code = chunk.code;
  41993. let imports;
  41994. try {
  41995. imports = parse$d(code)[0].filter((i) => i.d > -1);
  41996. } catch (e) {
  41997. const loc = numberToPos(code, e.idx);
  41998. this.error({
  41999. name: e.name,
  42000. message: e.message,
  42001. stack: e.stack,
  42002. cause: e.cause,
  42003. pos: e.idx,
  42004. loc: { ...loc, file: chunk.fileName },
  42005. frame: generateCodeFrame(code, loc)
  42006. });
  42007. }
  42008. const s = new MagicString(code);
  42009. const rewroteMarkerStartPos = /* @__PURE__ */ new Set();
  42010. const fileDeps = [];
  42011. const addFileDep = (url, runtime = false) => {
  42012. const index = fileDeps.findIndex((dep) => dep.url === url);
  42013. if (index === -1) {
  42014. return fileDeps.push({ url, runtime }) - 1;
  42015. } else {
  42016. return index;
  42017. }
  42018. };
  42019. if (imports.length) {
  42020. for (let index = 0; index < imports.length; index++) {
  42021. const {
  42022. n: name,
  42023. s: start,
  42024. e: end,
  42025. ss: expStart,
  42026. se: expEnd
  42027. } = imports[index];
  42028. let url = name;
  42029. if (!url) {
  42030. const rawUrl = code.slice(start, end);
  42031. if (rawUrl[0] === `"` && rawUrl.endsWith(`"`))
  42032. url = rawUrl.slice(1, -1);
  42033. }
  42034. const deps = /* @__PURE__ */ new Set();
  42035. let hasRemovedPureCssChunk = false;
  42036. let normalizedFile = void 0;
  42037. if (url) {
  42038. normalizedFile = path$b.posix.join(
  42039. path$b.posix.dirname(chunk.fileName),
  42040. url
  42041. );
  42042. const ownerFilename = chunk.fileName;
  42043. const analyzed = /* @__PURE__ */ new Set();
  42044. const addDeps = (filename) => {
  42045. if (filename === ownerFilename) return;
  42046. if (analyzed.has(filename)) return;
  42047. analyzed.add(filename);
  42048. const chunk2 = bundle[filename];
  42049. if (chunk2) {
  42050. deps.add(chunk2.fileName);
  42051. if (chunk2.type === "chunk") {
  42052. chunk2.imports.forEach(addDeps);
  42053. chunk2.viteMetadata.importedCss.forEach((file2) => {
  42054. deps.add(file2);
  42055. });
  42056. }
  42057. } else {
  42058. const removedPureCssFiles = removedPureCssFilesCache.get(config);
  42059. const chunk3 = removedPureCssFiles.get(filename);
  42060. if (chunk3) {
  42061. if (chunk3.viteMetadata.importedCss.size) {
  42062. chunk3.viteMetadata.importedCss.forEach((file2) => {
  42063. deps.add(file2);
  42064. });
  42065. hasRemovedPureCssChunk = true;
  42066. }
  42067. s.update(expStart, expEnd, "Promise.resolve({})");
  42068. }
  42069. }
  42070. };
  42071. addDeps(normalizedFile);
  42072. }
  42073. let markerStartPos2 = indexOfMatchInSlice(
  42074. code,
  42075. preloadMarkerRE,
  42076. end
  42077. );
  42078. if (markerStartPos2 === -1 && imports.length === 1) {
  42079. markerStartPos2 = indexOfMatchInSlice(code, preloadMarkerRE);
  42080. }
  42081. if (markerStartPos2 > 0) {
  42082. let depsArray = deps.size > 1 || // main chunk is removed
  42083. hasRemovedPureCssChunk && deps.size > 0 ? modulePreload === false ? (
  42084. // CSS deps use the same mechanism as module preloads, so even if disabled,
  42085. // we still need to pass these deps to the preload helper in dynamic imports.
  42086. [...deps].filter((d) => d.endsWith(".css"))
  42087. ) : [...deps] : [];
  42088. const resolveDependencies = modulePreload ? modulePreload.resolveDependencies : void 0;
  42089. if (resolveDependencies && normalizedFile) {
  42090. const cssDeps = [];
  42091. const otherDeps = [];
  42092. for (const dep of depsArray) {
  42093. (dep.endsWith(".css") ? cssDeps : otherDeps).push(dep);
  42094. }
  42095. depsArray = [
  42096. ...resolveDependencies(normalizedFile, otherDeps, {
  42097. hostId: file,
  42098. hostType: "js"
  42099. }),
  42100. ...cssDeps
  42101. ];
  42102. }
  42103. let renderedDeps;
  42104. if (renderBuiltUrl) {
  42105. renderedDeps = depsArray.map((dep) => {
  42106. const replacement = toOutputFilePathInJS(
  42107. this.environment,
  42108. dep,
  42109. "asset",
  42110. chunk.fileName,
  42111. "js",
  42112. toRelativePath
  42113. );
  42114. if (typeof replacement === "string") {
  42115. return addFileDep(replacement);
  42116. }
  42117. return addFileDep(replacement.runtime, true);
  42118. });
  42119. } else {
  42120. renderedDeps = depsArray.map(
  42121. (d) => (
  42122. // Don't include the assets dir if the default asset file names
  42123. // are used, the path will be reconstructed by the import preload helper
  42124. isRelativeBase ? addFileDep(toRelativePath(d, file)) : addFileDep(d)
  42125. )
  42126. );
  42127. }
  42128. s.update(
  42129. markerStartPos2,
  42130. markerStartPos2 + preloadMarker.length,
  42131. renderedDeps.length > 0 ? `__vite__mapDeps([${renderedDeps.join(",")}])` : `[]`
  42132. );
  42133. rewroteMarkerStartPos.add(markerStartPos2);
  42134. }
  42135. }
  42136. }
  42137. if (fileDeps.length > 0) {
  42138. const fileDepsCode = `[${fileDeps.map(
  42139. (fileDep) => fileDep.runtime ? fileDep.url : JSON.stringify(fileDep.url)
  42140. ).join(",")}]`;
  42141. const mapDepsCode = `const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=${fileDepsCode})))=>i.map(i=>d[i]);
  42142. `;
  42143. if (code.startsWith("#!")) {
  42144. s.prependLeft(code.indexOf("\n") + 1, mapDepsCode);
  42145. } else {
  42146. s.prepend(mapDepsCode);
  42147. }
  42148. }
  42149. let markerStartPos = indexOfMatchInSlice(code, preloadMarkerRE);
  42150. while (markerStartPos >= 0) {
  42151. if (!rewroteMarkerStartPos.has(markerStartPos)) {
  42152. s.update(
  42153. markerStartPos,
  42154. markerStartPos + preloadMarker.length,
  42155. "void 0"
  42156. );
  42157. }
  42158. markerStartPos = indexOfMatchInSlice(
  42159. code,
  42160. preloadMarkerRE,
  42161. markerStartPos + preloadMarker.length
  42162. );
  42163. }
  42164. if (s.hasChanged()) {
  42165. chunk.code = s.toString();
  42166. if (buildSourcemap && chunk.map) {
  42167. const nextMap = s.generateMap({
  42168. source: chunk.fileName,
  42169. hires: "boundary"
  42170. });
  42171. const map = combineSourcemaps(chunk.fileName, [
  42172. nextMap,
  42173. chunk.map
  42174. ]);
  42175. map.toUrl = () => genSourceMapUrl(map);
  42176. const originalDebugId = chunk.map.debugId;
  42177. chunk.map = map;
  42178. if (buildSourcemap === "inline") {
  42179. chunk.code = chunk.code.replace(
  42180. convertSourceMap.mapFileCommentRegex,
  42181. ""
  42182. );
  42183. chunk.code += `
  42184. //# sourceMappingURL=${genSourceMapUrl(map)}`;
  42185. } else {
  42186. if (originalDebugId) {
  42187. map.debugId = originalDebugId;
  42188. }
  42189. const mapAsset = bundle[chunk.fileName + ".map"];
  42190. if (mapAsset && mapAsset.type === "asset") {
  42191. mapAsset.source = map.toString();
  42192. }
  42193. }
  42194. }
  42195. }
  42196. }
  42197. }
  42198. }
  42199. };
  42200. }
  42201. function ssrManifestPlugin() {
  42202. const getSsrManifest = perEnvironmentState(() => {
  42203. return {};
  42204. });
  42205. return {
  42206. name: "vite:ssr-manifest",
  42207. applyToEnvironment(environment) {
  42208. return !!environment.config.build.ssrManifest;
  42209. },
  42210. generateBundle(_options, bundle) {
  42211. const config = this.environment.config;
  42212. const ssrManifest = getSsrManifest(this);
  42213. const { base } = config;
  42214. for (const file in bundle) {
  42215. const chunk = bundle[file];
  42216. if (chunk.type === "chunk") {
  42217. for (const id in chunk.modules) {
  42218. const normalizedId = normalizePath$3(relative$2(config.root, id));
  42219. const mappedChunks = ssrManifest[normalizedId] ?? (ssrManifest[normalizedId] = []);
  42220. if (!chunk.isEntry) {
  42221. mappedChunks.push(joinUrlSegments(base, chunk.fileName));
  42222. chunk.viteMetadata.importedCss.forEach((file2) => {
  42223. mappedChunks.push(joinUrlSegments(base, file2));
  42224. });
  42225. }
  42226. chunk.viteMetadata.importedAssets.forEach((file2) => {
  42227. mappedChunks.push(joinUrlSegments(base, file2));
  42228. });
  42229. }
  42230. if (chunk.code.includes(preloadMethod)) {
  42231. const code = chunk.code;
  42232. let imports = [];
  42233. try {
  42234. imports = parse$d(code)[0].filter((i) => i.n && i.d > -1);
  42235. } catch (_e) {
  42236. const e = _e;
  42237. const loc = numberToPos(code, e.idx);
  42238. this.error({
  42239. name: e.name,
  42240. message: e.message,
  42241. stack: e.stack,
  42242. cause: e.cause,
  42243. pos: e.idx,
  42244. loc: { ...loc, file: chunk.fileName },
  42245. frame: generateCodeFrame(code, loc)
  42246. });
  42247. }
  42248. if (imports.length) {
  42249. for (let index = 0; index < imports.length; index++) {
  42250. const { s: start, e: end, n: name } = imports[index];
  42251. const url = code.slice(start, end);
  42252. const deps = [];
  42253. const ownerFilename = chunk.fileName;
  42254. const analyzed = /* @__PURE__ */ new Set();
  42255. const addDeps = (filename) => {
  42256. if (filename === ownerFilename) return;
  42257. if (analyzed.has(filename)) return;
  42258. analyzed.add(filename);
  42259. const chunk2 = bundle[filename];
  42260. if (chunk2) {
  42261. chunk2.viteMetadata.importedCss.forEach((file2) => {
  42262. deps.push(joinUrlSegments(base, file2));
  42263. });
  42264. chunk2.imports.forEach(addDeps);
  42265. }
  42266. };
  42267. const normalizedFile = normalizePath$3(
  42268. join$1(dirname$2(chunk.fileName), url.slice(1, -1))
  42269. );
  42270. addDeps(normalizedFile);
  42271. ssrManifest[basename$2(name)] = deps;
  42272. }
  42273. }
  42274. }
  42275. }
  42276. }
  42277. this.emitFile({
  42278. fileName: typeof config.build.ssrManifest === "string" ? config.build.ssrManifest : ".vite/ssr-manifest.json",
  42279. type: "asset",
  42280. source: JSON.stringify(sortObjectKeys(ssrManifest), void 0, 2)
  42281. });
  42282. }
  42283. };
  42284. }
  42285. function buildLoadFallbackPlugin() {
  42286. return {
  42287. name: "vite:load-fallback",
  42288. load: {
  42289. async handler(id) {
  42290. try {
  42291. const cleanedId = cleanUrl(id);
  42292. const content = await fsp.readFile(cleanedId, "utf-8");
  42293. this.addWatchFile(cleanedId);
  42294. return content;
  42295. } catch {
  42296. const content = await fsp.readFile(id, "utf-8");
  42297. this.addWatchFile(id);
  42298. return content;
  42299. }
  42300. }
  42301. }
  42302. };
  42303. }
  42304. function completeSystemWrapPlugin() {
  42305. const SystemJSWrapRE = /System.register\(.*?(\(exports\)|\(\))/g;
  42306. return {
  42307. name: "vite:force-systemjs-wrap-complete",
  42308. renderChunk(code, _chunk, opts) {
  42309. if (opts.format === "system") {
  42310. return {
  42311. code: code.replace(
  42312. SystemJSWrapRE,
  42313. (s, s1) => s.replace(s1, "(exports, module)")
  42314. ),
  42315. map: null
  42316. };
  42317. }
  42318. }
  42319. };
  42320. }
  42321. const buildEnvironmentOptionsDefaults = Object.freeze({
  42322. target: "modules",
  42323. /** @deprecated */
  42324. polyfillModulePreload: true,
  42325. modulePreload: true,
  42326. outDir: "dist",
  42327. assetsDir: "assets",
  42328. assetsInlineLimit: DEFAULT_ASSETS_INLINE_LIMIT,
  42329. // cssCodeSplit
  42330. // cssTarget
  42331. // cssMinify
  42332. sourcemap: false,
  42333. // minify
  42334. terserOptions: {},
  42335. rollupOptions: {},
  42336. commonjsOptions: {
  42337. include: [/node_modules/],
  42338. extensions: [".js", ".cjs"]
  42339. },
  42340. dynamicImportVarsOptions: {
  42341. warnOnError: true,
  42342. exclude: [/node_modules/]
  42343. },
  42344. write: true,
  42345. emptyOutDir: null,
  42346. copyPublicDir: true,
  42347. manifest: false,
  42348. lib: false,
  42349. // ssr
  42350. ssrManifest: false,
  42351. ssrEmitAssets: false,
  42352. // emitAssets
  42353. reportCompressedSize: true,
  42354. chunkSizeWarningLimit: 500,
  42355. watch: null
  42356. // createEnvironment
  42357. });
  42358. function resolveBuildEnvironmentOptions(raw, logger, consumer) {
  42359. const deprecatedPolyfillModulePreload = raw.polyfillModulePreload;
  42360. const { polyfillModulePreload, ...rest } = raw;
  42361. raw = rest;
  42362. if (deprecatedPolyfillModulePreload !== void 0) {
  42363. logger.warn(
  42364. "polyfillModulePreload is deprecated. Use modulePreload.polyfill instead."
  42365. );
  42366. }
  42367. if (deprecatedPolyfillModulePreload === false && raw.modulePreload === void 0) {
  42368. raw.modulePreload = { polyfill: false };
  42369. }
  42370. const merged = mergeWithDefaults(
  42371. {
  42372. ...buildEnvironmentOptionsDefaults,
  42373. cssCodeSplit: !raw.lib,
  42374. minify: consumer === "server" ? false : "esbuild",
  42375. ssr: consumer === "server",
  42376. emitAssets: consumer === "client",
  42377. createEnvironment: (name, config) => new BuildEnvironment(name, config)
  42378. },
  42379. raw
  42380. );
  42381. if (merged.target === "modules") {
  42382. merged.target = ESBUILD_MODULES_TARGET;
  42383. }
  42384. if (merged.minify === "false") {
  42385. merged.minify = false;
  42386. } else if (merged.minify === true) {
  42387. merged.minify = "esbuild";
  42388. }
  42389. const defaultModulePreload = {
  42390. polyfill: true
  42391. };
  42392. const resolved = {
  42393. ...merged,
  42394. cssTarget: merged.cssTarget ?? merged.target,
  42395. cssMinify: merged.cssMinify ?? (consumer === "server" ? "esbuild" : !!merged.minify),
  42396. // Resolve to false | object
  42397. modulePreload: merged.modulePreload === false ? false : merged.modulePreload === true ? defaultModulePreload : {
  42398. ...defaultModulePreload,
  42399. ...merged.modulePreload
  42400. }
  42401. };
  42402. return resolved;
  42403. }
  42404. async function resolveBuildPlugins(config) {
  42405. return {
  42406. pre: [
  42407. completeSystemWrapPlugin(),
  42408. perEnvironmentPlugin("commonjs", (environment) => {
  42409. const { commonjsOptions } = environment.config.build;
  42410. const usePluginCommonjs = !Array.isArray(commonjsOptions.include) || commonjsOptions.include.length !== 0;
  42411. return usePluginCommonjs ? commonjs(commonjsOptions) : false;
  42412. }),
  42413. dataURIPlugin(),
  42414. perEnvironmentPlugin(
  42415. "vite:rollup-options-plugins",
  42416. async (environment) => (await asyncFlatten(
  42417. arraify(environment.config.build.rollupOptions.plugins)
  42418. )).filter(Boolean)
  42419. ),
  42420. ...config.isWorker ? [webWorkerPostPlugin()] : []
  42421. ],
  42422. post: [
  42423. buildImportAnalysisPlugin(config),
  42424. buildEsbuildPlugin(),
  42425. terserPlugin(config),
  42426. ...!config.isWorker ? [manifestPlugin(), ssrManifestPlugin(), buildReporterPlugin(config)] : [],
  42427. buildLoadFallbackPlugin()
  42428. ]
  42429. };
  42430. }
  42431. async function build(inlineConfig = {}) {
  42432. const builder = await createBuilder(inlineConfig, true);
  42433. const environment = Object.values(builder.environments)[0];
  42434. if (!environment) throw new Error("No environment found");
  42435. return builder.build(environment);
  42436. }
  42437. function resolveConfigToBuild(inlineConfig = {}, patchConfig, patchPlugins) {
  42438. return resolveConfig(
  42439. inlineConfig,
  42440. "build",
  42441. "production",
  42442. "production",
  42443. false,
  42444. patchConfig,
  42445. patchPlugins
  42446. );
  42447. }
  42448. async function buildEnvironment(environment) {
  42449. const { root, packageCache } = environment.config;
  42450. const options = environment.config.build;
  42451. const libOptions = options.lib;
  42452. const { logger } = environment;
  42453. const ssr = environment.config.consumer === "server";
  42454. logger.info(
  42455. colors$1.cyan(
  42456. `vite v${VERSION} ${colors$1.green(
  42457. `building ${ssr ? `SSR bundle ` : ``}for ${environment.config.mode}...`
  42458. )}`
  42459. )
  42460. );
  42461. const resolve = (p) => path$b.resolve(root, p);
  42462. const input = libOptions ? options.rollupOptions.input || (typeof libOptions.entry === "string" ? resolve(libOptions.entry) : Array.isArray(libOptions.entry) ? libOptions.entry.map(resolve) : Object.fromEntries(
  42463. Object.entries(libOptions.entry).map(([alias, file]) => [
  42464. alias,
  42465. resolve(file)
  42466. ])
  42467. )) : typeof options.ssr === "string" ? resolve(options.ssr) : options.rollupOptions.input || resolve("index.html");
  42468. if (ssr && typeof input === "string" && input.endsWith(".html")) {
  42469. throw new Error(
  42470. `rollupOptions.input should not be an html file when building for SSR. Please specify a dedicated SSR entry.`
  42471. );
  42472. }
  42473. if (options.cssCodeSplit === false) {
  42474. const inputs = typeof input === "string" ? [input] : Array.isArray(input) ? input : Object.values(input);
  42475. if (inputs.some((input2) => input2.endsWith(".css"))) {
  42476. throw new Error(
  42477. `When "build.cssCodeSplit: false" is set, "rollupOptions.input" should not include CSS files.`
  42478. );
  42479. }
  42480. }
  42481. const outDir = resolve(options.outDir);
  42482. const plugins = environment.plugins.map(
  42483. (p) => injectEnvironmentAndFilterToHooks(environment, p)
  42484. );
  42485. const rollupOptions = {
  42486. preserveEntrySignatures: ssr ? "allow-extension" : libOptions ? "strict" : false,
  42487. cache: options.watch ? void 0 : false,
  42488. ...options.rollupOptions,
  42489. output: options.rollupOptions.output,
  42490. input,
  42491. plugins,
  42492. external: options.rollupOptions.external,
  42493. onLog(level, log) {
  42494. onRollupLog(level, log, environment);
  42495. }
  42496. };
  42497. function extractStack(e) {
  42498. const { stack, name = "Error", message } = e;
  42499. if (!stack) {
  42500. return stack;
  42501. }
  42502. const expectedPrefix = `${name}: ${message}
  42503. `;
  42504. if (stack.startsWith(expectedPrefix)) {
  42505. return stack.slice(expectedPrefix.length);
  42506. }
  42507. return stack;
  42508. }
  42509. const normalizeCodeFrame = (frame) => {
  42510. const trimmedPadding = frame.replace(/^\n|\n$/g, "");
  42511. return `
  42512. ${trimmedPadding}
  42513. `;
  42514. };
  42515. const enhanceRollupError = (e) => {
  42516. const stackOnly = extractStack(e);
  42517. let msg = colors$1.red((e.plugin ? `[${e.plugin}] ` : "") + e.message);
  42518. if (e.loc && e.loc.file && e.loc.file !== e.id) {
  42519. msg += `
  42520. file: ${colors$1.cyan(
  42521. `${e.loc.file}:${e.loc.line}:${e.loc.column}` + (e.id ? ` (${e.id})` : "")
  42522. )}`;
  42523. } else if (e.id) {
  42524. msg += `
  42525. file: ${colors$1.cyan(
  42526. e.id + (e.loc ? `:${e.loc.line}:${e.loc.column}` : "")
  42527. )}`;
  42528. }
  42529. if (e.frame) {
  42530. msg += `
  42531. ` + colors$1.yellow(normalizeCodeFrame(e.frame));
  42532. }
  42533. e.message = msg;
  42534. if (stackOnly !== void 0) {
  42535. e.stack = `${e.message}
  42536. ${stackOnly}`;
  42537. }
  42538. };
  42539. const outputBuildError = (e) => {
  42540. enhanceRollupError(e);
  42541. clearLine();
  42542. logger.error(e.message, { error: e });
  42543. };
  42544. const isSsrTargetWebworkerEnvironment = environment.name === "ssr" && environment.getTopLevelConfig().ssr?.target === "webworker";
  42545. let bundle;
  42546. let startTime;
  42547. try {
  42548. const buildOutputOptions = (output = {}) => {
  42549. if (output.output) {
  42550. logger.warn(
  42551. `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.`
  42552. );
  42553. }
  42554. if (output.file) {
  42555. throw new Error(
  42556. `Vite does not support "rollupOptions.output.file". Please use "rollupOptions.output.dir" and "rollupOptions.output.entryFileNames" instead.`
  42557. );
  42558. }
  42559. if (output.sourcemap) {
  42560. logger.warnOnce(
  42561. colors$1.yellow(
  42562. `Vite does not support "rollupOptions.output.sourcemap". Please use "build.sourcemap" instead.`
  42563. )
  42564. );
  42565. }
  42566. const format = output.format || "es";
  42567. const jsExt = ssr && !isSsrTargetWebworkerEnvironment || libOptions ? resolveOutputJsExtension(
  42568. format,
  42569. findNearestPackageData(root, packageCache)?.data.type
  42570. ) : "js";
  42571. return {
  42572. dir: outDir,
  42573. // Default format is 'es' for regular and for SSR builds
  42574. format,
  42575. exports: "auto",
  42576. sourcemap: options.sourcemap,
  42577. name: libOptions ? libOptions.name : void 0,
  42578. hoistTransitiveImports: libOptions ? false : void 0,
  42579. // es2015 enables `generatedCode.symbols`
  42580. // - #764 add `Symbol.toStringTag` when build es module into cjs chunk
  42581. // - #1048 add `Symbol.toStringTag` for module default export
  42582. generatedCode: "es2015",
  42583. entryFileNames: ssr ? `[name].${jsExt}` : libOptions ? ({ name }) => resolveLibFilename(
  42584. libOptions,
  42585. format,
  42586. name,
  42587. root,
  42588. jsExt,
  42589. packageCache
  42590. ) : path$b.posix.join(options.assetsDir, `[name]-[hash].${jsExt}`),
  42591. chunkFileNames: libOptions ? `[name]-[hash].${jsExt}` : path$b.posix.join(options.assetsDir, `[name]-[hash].${jsExt}`),
  42592. assetFileNames: libOptions ? `[name].[ext]` : path$b.posix.join(options.assetsDir, `[name]-[hash].[ext]`),
  42593. inlineDynamicImports: output.format === "umd" || output.format === "iife" || isSsrTargetWebworkerEnvironment && (typeof input === "string" || Object.keys(input).length === 1),
  42594. ...output
  42595. };
  42596. };
  42597. const outputs = resolveBuildOutputs(
  42598. options.rollupOptions.output,
  42599. libOptions,
  42600. logger
  42601. );
  42602. const normalizedOutputs = [];
  42603. if (Array.isArray(outputs)) {
  42604. for (const resolvedOutput of outputs) {
  42605. normalizedOutputs.push(buildOutputOptions(resolvedOutput));
  42606. }
  42607. } else {
  42608. normalizedOutputs.push(buildOutputOptions(outputs));
  42609. }
  42610. const resolvedOutDirs = getResolvedOutDirs(
  42611. root,
  42612. options.outDir,
  42613. options.rollupOptions.output
  42614. );
  42615. const emptyOutDir = resolveEmptyOutDir(
  42616. options.emptyOutDir,
  42617. root,
  42618. resolvedOutDirs,
  42619. logger
  42620. );
  42621. if (options.watch) {
  42622. logger.info(colors$1.cyan(`
  42623. watching for file changes...`));
  42624. const resolvedChokidarOptions = resolveChokidarOptions(
  42625. options.watch.chokidar,
  42626. resolvedOutDirs,
  42627. emptyOutDir,
  42628. environment.config.cacheDir
  42629. );
  42630. const { watch } = await import('rollup');
  42631. const watcher = watch({
  42632. ...rollupOptions,
  42633. output: normalizedOutputs,
  42634. watch: {
  42635. ...options.watch,
  42636. chokidar: resolvedChokidarOptions
  42637. }
  42638. });
  42639. watcher.on("event", (event) => {
  42640. if (event.code === "BUNDLE_START") {
  42641. logger.info(colors$1.cyan(`
  42642. build started...`));
  42643. if (options.write) {
  42644. prepareOutDir(resolvedOutDirs, emptyOutDir, environment);
  42645. }
  42646. } else if (event.code === "BUNDLE_END") {
  42647. event.result.close();
  42648. logger.info(colors$1.cyan(`built in ${event.duration}ms.`));
  42649. } else if (event.code === "ERROR") {
  42650. outputBuildError(event.error);
  42651. }
  42652. });
  42653. return watcher;
  42654. }
  42655. const { rollup } = await import('rollup');
  42656. startTime = Date.now();
  42657. bundle = await rollup(rollupOptions);
  42658. if (options.write) {
  42659. prepareOutDir(resolvedOutDirs, emptyOutDir, environment);
  42660. }
  42661. const res = [];
  42662. for (const output of normalizedOutputs) {
  42663. res.push(await bundle[options.write ? "write" : "generate"](output));
  42664. }
  42665. logger.info(
  42666. `${colors$1.green(`\u2713 built in ${displayTime(Date.now() - startTime)}`)}`
  42667. );
  42668. return Array.isArray(outputs) ? res : res[0];
  42669. } catch (e) {
  42670. enhanceRollupError(e);
  42671. clearLine();
  42672. if (startTime) {
  42673. logger.error(
  42674. `${colors$1.red("\u2717")} Build failed in ${displayTime(Date.now() - startTime)}`
  42675. );
  42676. startTime = void 0;
  42677. }
  42678. throw e;
  42679. } finally {
  42680. if (bundle) await bundle.close();
  42681. }
  42682. }
  42683. function prepareOutDir(outDirs, emptyOutDir, environment) {
  42684. const { publicDir } = environment.config;
  42685. const outDirsArray = [...outDirs];
  42686. for (const outDir of outDirs) {
  42687. if (emptyOutDir !== false && fs__default.existsSync(outDir)) {
  42688. const skipDirs = outDirsArray.map((dir) => {
  42689. const relative = path$b.relative(outDir, dir);
  42690. if (relative && !relative.startsWith("..") && !path$b.isAbsolute(relative)) {
  42691. return relative;
  42692. }
  42693. return "";
  42694. }).filter(Boolean);
  42695. emptyDir(outDir, [...skipDirs, ".git"]);
  42696. }
  42697. if (environment.config.build.copyPublicDir && publicDir && fs__default.existsSync(publicDir)) {
  42698. if (!areSeparateFolders(outDir, publicDir)) {
  42699. environment.logger.warn(
  42700. colors$1.yellow(
  42701. `
  42702. ${colors$1.bold(
  42703. `(!)`
  42704. )} The public directory feature may not work correctly. outDir ${colors$1.white(
  42705. colors$1.dim(outDir)
  42706. )} and publicDir ${colors$1.white(
  42707. colors$1.dim(publicDir)
  42708. )} are not separate folders.
  42709. `
  42710. )
  42711. );
  42712. }
  42713. copyDir(publicDir, outDir);
  42714. }
  42715. }
  42716. }
  42717. function resolveOutputJsExtension(format, type = "commonjs") {
  42718. if (type === "module") {
  42719. return format === "cjs" || format === "umd" ? "cjs" : "js";
  42720. } else {
  42721. return format === "es" ? "mjs" : "js";
  42722. }
  42723. }
  42724. function resolveLibFilename(libOptions, format, entryName, root, extension, packageCache) {
  42725. if (typeof libOptions.fileName === "function") {
  42726. return libOptions.fileName(format, entryName);
  42727. }
  42728. const packageJson = findNearestMainPackageData(root, packageCache)?.data;
  42729. const name = libOptions.fileName || (packageJson && typeof libOptions.entry === "string" ? getPkgName(packageJson.name) : entryName);
  42730. if (!name)
  42731. throw new Error(
  42732. 'Name in package.json is required if option "build.lib.fileName" is not provided.'
  42733. );
  42734. extension ??= resolveOutputJsExtension(format, packageJson?.type);
  42735. if (format === "cjs" || format === "es") {
  42736. return `${name}.${extension}`;
  42737. }
  42738. return `${name}.${format}.${extension}`;
  42739. }
  42740. function resolveBuildOutputs(outputs, libOptions, logger) {
  42741. if (libOptions) {
  42742. const libHasMultipleEntries = typeof libOptions.entry !== "string" && Object.values(libOptions.entry).length > 1;
  42743. const libFormats = libOptions.formats || (libHasMultipleEntries ? ["es", "cjs"] : ["es", "umd"]);
  42744. if (!Array.isArray(outputs)) {
  42745. if (libFormats.includes("umd") || libFormats.includes("iife")) {
  42746. if (libHasMultipleEntries) {
  42747. throw new Error(
  42748. 'Multiple entry points are not supported when output formats include "umd" or "iife".'
  42749. );
  42750. }
  42751. if (!libOptions.name) {
  42752. throw new Error(
  42753. 'Option "build.lib.name" is required when output formats include "umd" or "iife".'
  42754. );
  42755. }
  42756. }
  42757. return libFormats.map((format) => ({ ...outputs, format }));
  42758. }
  42759. if (libOptions.formats) {
  42760. logger.warn(
  42761. colors$1.yellow(
  42762. '"build.lib.formats" will be ignored because "build.rollupOptions.output" is already an array format.'
  42763. )
  42764. );
  42765. }
  42766. outputs.forEach((output) => {
  42767. if ((output.format === "umd" || output.format === "iife") && !output.name) {
  42768. throw new Error(
  42769. 'Entries in "build.rollupOptions.output" must specify "name" when the format is "umd" or "iife".'
  42770. );
  42771. }
  42772. });
  42773. }
  42774. return outputs;
  42775. }
  42776. const warningIgnoreList = [`CIRCULAR_DEPENDENCY`, `THIS_IS_UNDEFINED`];
  42777. const dynamicImportWarningIgnoreList = [
  42778. `Unsupported expression`,
  42779. `statically analyzed`
  42780. ];
  42781. function clearLine() {
  42782. const tty = process.stdout.isTTY && !process.env.CI;
  42783. if (tty) {
  42784. process.stdout.clearLine(0);
  42785. process.stdout.cursorTo(0);
  42786. }
  42787. }
  42788. function onRollupLog(level, log, environment) {
  42789. const debugLogger = createDebugger("vite:build");
  42790. const viteLog = (logLeveling, rawLogging) => {
  42791. const logging = typeof rawLogging === "object" ? rawLogging : { message: rawLogging };
  42792. if (logging.code === "UNRESOLVED_IMPORT") {
  42793. const id = logging.id;
  42794. const exporter = logging.exporter;
  42795. if (!id || !id.endsWith("?commonjs-external")) {
  42796. throw new Error(
  42797. `[vite]: Rollup failed to resolve import "${exporter}" from "${id}".
  42798. This is most likely unintended because it can break your application at runtime.
  42799. If you do want to externalize this module explicitly add it to
  42800. \`build.rollupOptions.external\``
  42801. );
  42802. }
  42803. }
  42804. if (logLeveling === "warn") {
  42805. if (logging.plugin === "rollup-plugin-dynamic-import-variables" && dynamicImportWarningIgnoreList.some(
  42806. (msg) => logging.message.includes(msg)
  42807. )) {
  42808. return;
  42809. }
  42810. if (warningIgnoreList.includes(logging.code)) {
  42811. return;
  42812. }
  42813. }
  42814. switch (logLeveling) {
  42815. case "info":
  42816. environment.logger.info(logging.message);
  42817. return;
  42818. case "warn":
  42819. environment.logger.warn(colors$1.yellow(logging.message));
  42820. return;
  42821. case "error":
  42822. environment.logger.error(colors$1.red(logging.message));
  42823. return;
  42824. case "debug":
  42825. debugLogger?.(logging.message);
  42826. return;
  42827. default:
  42828. environment.logger.info(logging.message);
  42829. return;
  42830. }
  42831. };
  42832. clearLine();
  42833. const userOnLog = environment.config.build.rollupOptions?.onLog;
  42834. const userOnWarn = environment.config.build.rollupOptions?.onwarn;
  42835. if (userOnLog) {
  42836. if (userOnWarn) {
  42837. const normalizedUserOnWarn = normalizeUserOnWarn(userOnWarn, viteLog);
  42838. userOnLog(level, log, normalizedUserOnWarn);
  42839. } else {
  42840. userOnLog(level, log, viteLog);
  42841. }
  42842. } else if (userOnWarn) {
  42843. const normalizedUserOnWarn = normalizeUserOnWarn(userOnWarn, viteLog);
  42844. normalizedUserOnWarn(level, log);
  42845. } else {
  42846. viteLog(level, log);
  42847. }
  42848. }
  42849. function normalizeUserOnWarn(userOnWarn, defaultHandler) {
  42850. return (logLevel, logging) => {
  42851. if (logLevel === "warn") {
  42852. userOnWarn(
  42853. normalizeLog(logging),
  42854. (log) => defaultHandler("warn", typeof log === "function" ? log() : log)
  42855. );
  42856. } else {
  42857. defaultHandler(logLevel, logging);
  42858. }
  42859. };
  42860. }
  42861. const normalizeLog = (log) => typeof log === "string" ? { message: log } : log;
  42862. function resolveUserExternal(user, id, parentId, isResolved) {
  42863. if (typeof user === "function") {
  42864. return user(id, parentId, isResolved);
  42865. } else if (Array.isArray(user)) {
  42866. return user.some((test) => isExternal(id, test));
  42867. } else {
  42868. return isExternal(id, user);
  42869. }
  42870. }
  42871. function isExternal(id, test) {
  42872. if (typeof test === "string") {
  42873. return id === test;
  42874. } else {
  42875. return test.test(id);
  42876. }
  42877. }
  42878. function injectEnvironmentAndFilterToHooks(environment, plugin) {
  42879. const { resolveId, load, transform } = plugin;
  42880. const clone = { ...plugin };
  42881. for (const hook of Object.keys(clone)) {
  42882. switch (hook) {
  42883. case "resolveId":
  42884. clone[hook] = wrapEnvironmentAndFilterResolveId(environment, resolveId);
  42885. break;
  42886. case "load":
  42887. clone[hook] = wrapEnvironmentAndFilterLoad(environment, load);
  42888. break;
  42889. case "transform":
  42890. clone[hook] = wrapEnvironmentAndFilterTransform(environment, transform);
  42891. break;
  42892. default:
  42893. if (ROLLUP_HOOKS.includes(hook)) {
  42894. clone[hook] = wrapEnvironmentHook(environment, clone[hook]);
  42895. }
  42896. break;
  42897. }
  42898. }
  42899. return clone;
  42900. }
  42901. function wrapEnvironmentAndFilterResolveId(environment, hook) {
  42902. if (!hook) return;
  42903. const rawIdFilter = typeof hook === "object" ? hook.filter?.id : void 0;
  42904. const idFilter = rawIdFilter ? createIdFilter(rawIdFilter) : void 0;
  42905. const fn = getHookHandler(hook);
  42906. const handler = function(id, importer, options) {
  42907. if (idFilter && !idFilter(id)) {
  42908. return;
  42909. }
  42910. return fn.call(
  42911. injectEnvironmentInContext(this, environment),
  42912. id,
  42913. importer,
  42914. injectSsrFlag(options, environment)
  42915. );
  42916. };
  42917. if ("handler" in hook) {
  42918. return {
  42919. ...hook,
  42920. handler
  42921. };
  42922. } else {
  42923. return handler;
  42924. }
  42925. }
  42926. function wrapEnvironmentAndFilterLoad(environment, hook) {
  42927. if (!hook) return;
  42928. const rawIdFilter = typeof hook === "object" ? hook.filter?.id : void 0;
  42929. const idFilter = rawIdFilter ? createIdFilter(rawIdFilter) : void 0;
  42930. const fn = getHookHandler(hook);
  42931. const handler = function(id, ...args) {
  42932. if (idFilter && !idFilter(id)) {
  42933. return;
  42934. }
  42935. return fn.call(
  42936. injectEnvironmentInContext(this, environment),
  42937. id,
  42938. injectSsrFlag(args[0], environment)
  42939. );
  42940. };
  42941. if ("handler" in hook) {
  42942. return {
  42943. ...hook,
  42944. handler
  42945. };
  42946. } else {
  42947. return handler;
  42948. }
  42949. }
  42950. function wrapEnvironmentAndFilterTransform(environment, hook) {
  42951. if (!hook) return;
  42952. const filters = typeof hook === "object" ? hook.filter : void 0;
  42953. const filter = filters ? createFilterForTransform(filters.id, filters.code) : void 0;
  42954. const fn = getHookHandler(hook);
  42955. const handler = function(code, importer, ...args) {
  42956. if (filter && !filter(importer, code)) {
  42957. return;
  42958. }
  42959. return fn.call(
  42960. injectEnvironmentInContext(this, environment),
  42961. code,
  42962. importer,
  42963. injectSsrFlag(args[0], environment)
  42964. );
  42965. };
  42966. if ("handler" in hook) {
  42967. return {
  42968. ...hook,
  42969. handler
  42970. };
  42971. } else {
  42972. return handler;
  42973. }
  42974. }
  42975. function wrapEnvironmentHook(environment, hook) {
  42976. if (!hook) return;
  42977. const fn = getHookHandler(hook);
  42978. if (typeof fn !== "function") return hook;
  42979. const handler = function(...args) {
  42980. return fn.call(injectEnvironmentInContext(this, environment), ...args);
  42981. };
  42982. if ("handler" in hook) {
  42983. return {
  42984. ...hook,
  42985. handler
  42986. };
  42987. } else {
  42988. return handler;
  42989. }
  42990. }
  42991. function injectEnvironmentInContext(context, environment) {
  42992. context.environment ??= environment;
  42993. return context;
  42994. }
  42995. function injectSsrFlag(options, environment) {
  42996. const ssr = environment ? environment.config.consumer === "server" : true;
  42997. return { ...options ?? {}, ssr };
  42998. }
  42999. const needsEscapeRegEx = /[\n\r'\\\u2028\u2029]/;
  43000. const quoteNewlineRegEx = /([\n\r'\u2028\u2029])/g;
  43001. const backSlashRegEx = /\\/g;
  43002. function escapeId(id) {
  43003. if (!needsEscapeRegEx.test(id)) return id;
  43004. return id.replace(backSlashRegEx, "\\\\").replace(quoteNewlineRegEx, "\\$1");
  43005. }
  43006. const getResolveUrl = (path2, URL = "URL") => `new ${URL}(${path2}).href`;
  43007. const getRelativeUrlFromDocument = (relativePath, umd = false) => getResolveUrl(
  43008. `'${escapeId(partialEncodeURIPath(relativePath))}', ${umd ? `typeof document === 'undefined' ? location.href : ` : ""}document.currentScript && document.currentScript.tagName.toUpperCase() === 'SCRIPT' && document.currentScript.src || document.baseURI`
  43009. );
  43010. const getFileUrlFromFullPath = (path2) => `require('u' + 'rl').pathToFileURL(${path2}).href`;
  43011. const getFileUrlFromRelativePath = (path2) => getFileUrlFromFullPath(`__dirname + '/${escapeId(path2)}'`);
  43012. const relativeUrlMechanisms = {
  43013. amd: (relativePath) => {
  43014. if (relativePath[0] !== ".") relativePath = "./" + relativePath;
  43015. return getResolveUrl(
  43016. `require.toUrl('${escapeId(relativePath)}'), document.baseURI`
  43017. );
  43018. },
  43019. cjs: (relativePath) => `(typeof document === 'undefined' ? ${getFileUrlFromRelativePath(
  43020. relativePath
  43021. )} : ${getRelativeUrlFromDocument(relativePath)})`,
  43022. es: (relativePath) => getResolveUrl(
  43023. `'${escapeId(partialEncodeURIPath(relativePath))}', import.meta.url`
  43024. ),
  43025. iife: (relativePath) => getRelativeUrlFromDocument(relativePath),
  43026. // NOTE: make sure rollup generate `module` params
  43027. system: (relativePath) => getResolveUrl(
  43028. `'${escapeId(partialEncodeURIPath(relativePath))}', module.meta.url`
  43029. ),
  43030. umd: (relativePath) => `(typeof document === 'undefined' && typeof location === 'undefined' ? ${getFileUrlFromRelativePath(
  43031. relativePath
  43032. )} : ${getRelativeUrlFromDocument(relativePath, true)})`
  43033. };
  43034. const customRelativeUrlMechanisms = {
  43035. ...relativeUrlMechanisms,
  43036. "worker-iife": (relativePath) => getResolveUrl(
  43037. `'${escapeId(partialEncodeURIPath(relativePath))}', self.location.href`
  43038. )
  43039. };
  43040. function toOutputFilePathInJS(environment, filename, type, hostId, hostType, toRelative) {
  43041. const { experimental, base, decodedBase } = environment.config;
  43042. const ssr = environment.config.consumer === "server";
  43043. const { renderBuiltUrl } = experimental;
  43044. let relative = base === "" || base === "./";
  43045. if (renderBuiltUrl) {
  43046. const result = renderBuiltUrl(filename, {
  43047. hostId,
  43048. hostType,
  43049. type,
  43050. ssr
  43051. });
  43052. if (typeof result === "object") {
  43053. if (result.runtime) {
  43054. return { runtime: result.runtime };
  43055. }
  43056. if (typeof result.relative === "boolean") {
  43057. relative = result.relative;
  43058. }
  43059. } else if (result) {
  43060. return result;
  43061. }
  43062. }
  43063. if (relative && !ssr) {
  43064. return toRelative(filename, hostId);
  43065. }
  43066. return joinUrlSegments(decodedBase, filename);
  43067. }
  43068. function createToImportMetaURLBasedRelativeRuntime(format, isWorker) {
  43069. const formatLong = isWorker && format === "iife" ? "worker-iife" : format;
  43070. const toRelativePath = customRelativeUrlMechanisms[formatLong];
  43071. return (filename, importer) => ({
  43072. runtime: toRelativePath(
  43073. path$b.posix.relative(path$b.dirname(importer), filename)
  43074. )
  43075. });
  43076. }
  43077. function toOutputFilePathWithoutRuntime(filename, type, hostId, hostType, config, toRelative) {
  43078. const { renderBuiltUrl } = config.experimental;
  43079. let relative = config.base === "" || config.base === "./";
  43080. if (renderBuiltUrl) {
  43081. const result = renderBuiltUrl(filename, {
  43082. hostId,
  43083. hostType,
  43084. type,
  43085. ssr: !!config.build.ssr
  43086. });
  43087. if (typeof result === "object") {
  43088. if (result.runtime) {
  43089. throw new Error(
  43090. `{ runtime: "${result.runtime}" } is not supported for assets in ${hostType} files: ${filename}`
  43091. );
  43092. }
  43093. if (typeof result.relative === "boolean") {
  43094. relative = result.relative;
  43095. }
  43096. } else if (result) {
  43097. return result;
  43098. }
  43099. }
  43100. if (relative && !config.build.ssr) {
  43101. return toRelative(filename, hostId);
  43102. } else {
  43103. return joinUrlSegments(config.decodedBase, filename);
  43104. }
  43105. }
  43106. const toOutputFilePathInCss = toOutputFilePathWithoutRuntime;
  43107. const toOutputFilePathInHtml = toOutputFilePathWithoutRuntime;
  43108. function areSeparateFolders(a, b) {
  43109. const na = normalizePath$3(a);
  43110. const nb = normalizePath$3(b);
  43111. return na !== nb && !na.startsWith(withTrailingSlash(nb)) && !nb.startsWith(withTrailingSlash(na));
  43112. }
  43113. class BuildEnvironment extends BaseEnvironment {
  43114. mode = "build";
  43115. constructor(name, config, setup) {
  43116. let options = config.environments[name] ?? getDefaultResolvedEnvironmentOptions(config);
  43117. if (setup?.options) {
  43118. options = mergeConfig(
  43119. options,
  43120. setup.options
  43121. );
  43122. }
  43123. super(name, config, options);
  43124. }
  43125. async init() {
  43126. if (this._initiated) {
  43127. return;
  43128. }
  43129. this._initiated = true;
  43130. this._plugins = await resolveEnvironmentPlugins(this);
  43131. }
  43132. }
  43133. async function defaultBuildApp(builder) {
  43134. for (const environment of Object.values(builder.environments)) {
  43135. await builder.build(environment);
  43136. }
  43137. }
  43138. const builderOptionsDefaults = Object.freeze({
  43139. sharedConfigBuild: false,
  43140. sharedPlugins: false
  43141. // buildApp
  43142. });
  43143. function resolveBuilderOptions(options) {
  43144. if (!options) return;
  43145. return mergeWithDefaults(
  43146. { ...builderOptionsDefaults, buildApp: defaultBuildApp },
  43147. options
  43148. );
  43149. }
  43150. async function createBuilder(inlineConfig = {}, useLegacyBuilder = false) {
  43151. const patchConfig = (resolved) => {
  43152. if (!(useLegacyBuilder ?? !resolved.builder)) return;
  43153. const environmentName = resolved.build.ssr ? "ssr" : "client";
  43154. resolved.build = {
  43155. ...resolved.environments[environmentName].build
  43156. };
  43157. };
  43158. const config = await resolveConfigToBuild(inlineConfig, patchConfig);
  43159. useLegacyBuilder ??= !config.builder;
  43160. const configBuilder = config.builder ?? resolveBuilderOptions({});
  43161. const environments = {};
  43162. const builder = {
  43163. environments,
  43164. config,
  43165. async buildApp() {
  43166. return configBuilder.buildApp(builder);
  43167. },
  43168. async build(environment) {
  43169. return buildEnvironment(environment);
  43170. }
  43171. };
  43172. async function setupEnvironment(name, config2) {
  43173. const environment = await config2.build.createEnvironment(name, config2);
  43174. await environment.init();
  43175. environments[name] = environment;
  43176. }
  43177. if (useLegacyBuilder) {
  43178. await setupEnvironment(config.build.ssr ? "ssr" : "client", config);
  43179. } else {
  43180. for (const environmentName of Object.keys(config.environments)) {
  43181. let environmentConfig = config;
  43182. if (!configBuilder.sharedConfigBuild) {
  43183. const patchConfig2 = (resolved) => {
  43184. resolved.build = {
  43185. ...resolved.environments[environmentName].build
  43186. };
  43187. };
  43188. const patchPlugins = (resolvedPlugins) => {
  43189. let j = 0;
  43190. for (let i = 0; i < resolvedPlugins.length; i++) {
  43191. const environmentPlugin = resolvedPlugins[i];
  43192. if (configBuilder.sharedPlugins || environmentPlugin.sharedDuringBuild) {
  43193. for (let k = j; k < config.plugins.length; k++) {
  43194. if (environmentPlugin.name === config.plugins[k].name) {
  43195. resolvedPlugins[i] = config.plugins[k];
  43196. j = k + 1;
  43197. break;
  43198. }
  43199. }
  43200. }
  43201. }
  43202. };
  43203. environmentConfig = await resolveConfigToBuild(
  43204. inlineConfig,
  43205. patchConfig2,
  43206. patchPlugins
  43207. );
  43208. }
  43209. await setupEnvironment(environmentName, environmentConfig);
  43210. }
  43211. }
  43212. return builder;
  43213. }
  43214. var build$1 = {
  43215. __proto__: null,
  43216. BuildEnvironment: BuildEnvironment,
  43217. build: build,
  43218. buildEnvironmentOptionsDefaults: buildEnvironmentOptionsDefaults,
  43219. builderOptionsDefaults: builderOptionsDefaults,
  43220. createBuilder: createBuilder,
  43221. createToImportMetaURLBasedRelativeRuntime: createToImportMetaURLBasedRelativeRuntime,
  43222. injectEnvironmentAndFilterToHooks: injectEnvironmentAndFilterToHooks,
  43223. onRollupLog: onRollupLog,
  43224. resolveBuildEnvironmentOptions: resolveBuildEnvironmentOptions,
  43225. resolveBuildOutputs: resolveBuildOutputs,
  43226. resolveBuildPlugins: resolveBuildPlugins,
  43227. resolveBuilderOptions: resolveBuilderOptions,
  43228. resolveLibFilename: resolveLibFilename,
  43229. resolveUserExternal: resolveUserExternal,
  43230. toOutputFilePathInCss: toOutputFilePathInCss,
  43231. toOutputFilePathInHtml: toOutputFilePathInHtml,
  43232. toOutputFilePathInJS: toOutputFilePathInJS,
  43233. toOutputFilePathWithoutRuntime: toOutputFilePathWithoutRuntime
  43234. };
  43235. async function fetchModule(environment, url, importer, options = {}) {
  43236. if (url.startsWith("data:") || isBuiltin(environment.config.resolve.builtins, url)) {
  43237. return { externalize: url, type: "builtin" };
  43238. }
  43239. const isFileUrl = url.startsWith("file://");
  43240. if (isExternalUrl(url) && !isFileUrl) {
  43241. return { externalize: url, type: "network" };
  43242. }
  43243. if (!isFileUrl && importer && url[0] !== "." && url[0] !== "/") {
  43244. const { isProduction, root } = environment.config;
  43245. const { externalConditions, dedupe, preserveSymlinks } = environment.config.resolve;
  43246. const resolved = tryNodeResolve(url, importer, {
  43247. mainFields: ["main"],
  43248. conditions: externalConditions,
  43249. externalConditions,
  43250. external: [],
  43251. noExternal: [],
  43252. extensions: [".js", ".cjs", ".json"],
  43253. dedupe,
  43254. preserveSymlinks,
  43255. isBuild: false,
  43256. isProduction,
  43257. root,
  43258. packageCache: environment.config.packageCache,
  43259. builtins: environment.config.resolve.builtins
  43260. });
  43261. if (!resolved) {
  43262. const err = new Error(
  43263. `Cannot find module '${url}' imported from '${importer}'`
  43264. );
  43265. err.code = "ERR_MODULE_NOT_FOUND";
  43266. throw err;
  43267. }
  43268. const file = pathToFileURL$1(resolved.id).toString();
  43269. const type = isFilePathESM(resolved.id, environment.config.packageCache) ? "module" : "commonjs";
  43270. return { externalize: file, type };
  43271. }
  43272. url = unwrapId$1(url);
  43273. const mod = await environment.moduleGraph.ensureEntryFromUrl(url);
  43274. const cached = !!mod.transformResult;
  43275. if (options.cached && cached) {
  43276. return { cache: true };
  43277. }
  43278. let result = await environment.transformRequest(url);
  43279. if (!result) {
  43280. throw new Error(
  43281. `[vite] transform failed for module '${url}'${importer ? ` imported from '${importer}'` : ""}.`
  43282. );
  43283. }
  43284. if (options.inlineSourceMap !== false) {
  43285. result = inlineSourceMap(mod, result, options.startOffset);
  43286. }
  43287. if (result.code[0] === "#")
  43288. result.code = result.code.replace(/^#!.*/, (s) => " ".repeat(s.length));
  43289. return {
  43290. code: result.code,
  43291. file: mod.file,
  43292. id: mod.id,
  43293. url: mod.url,
  43294. invalidate: !cached
  43295. };
  43296. }
  43297. const OTHER_SOURCE_MAP_REGEXP = new RegExp(
  43298. `//# ${SOURCEMAPPING_URL}=data:application/json[^,]+base64,([A-Za-z0-9+/=]+)$`,
  43299. "gm"
  43300. );
  43301. function inlineSourceMap(mod, result, startOffset) {
  43302. const map = result.map;
  43303. let code = result.code;
  43304. if (!map || !("version" in map) || code.includes(MODULE_RUNNER_SOURCEMAPPING_SOURCE))
  43305. return result;
  43306. OTHER_SOURCE_MAP_REGEXP.lastIndex = 0;
  43307. if (OTHER_SOURCE_MAP_REGEXP.test(code))
  43308. code = code.replace(OTHER_SOURCE_MAP_REGEXP, "");
  43309. const sourceMap = startOffset ? Object.assign({}, map, {
  43310. mappings: ";".repeat(startOffset) + map.mappings
  43311. }) : map;
  43312. result.code = `${code.trimEnd()}
  43313. //# sourceURL=${mod.id}
  43314. ${MODULE_RUNNER_SOURCEMAPPING_SOURCE}
  43315. //# ${SOURCEMAPPING_URL}=${genSourceMapUrl(sourceMap)}
  43316. `;
  43317. return result;
  43318. }
  43319. const debug$1 = createDebugger("vite:deps");
  43320. const debounceMs = 100;
  43321. function createDepsOptimizer(environment) {
  43322. const { logger } = environment;
  43323. const sessionTimestamp = Date.now().toString();
  43324. let debounceProcessingHandle;
  43325. let closed = false;
  43326. const options = environment.config.optimizeDeps;
  43327. const { noDiscovery, holdUntilCrawlEnd } = options;
  43328. let metadata = initDepsOptimizerMetadata(
  43329. environment,
  43330. sessionTimestamp
  43331. );
  43332. const depsOptimizer = {
  43333. init,
  43334. metadata,
  43335. registerMissingImport,
  43336. run: () => debouncedProcessing(0),
  43337. isOptimizedDepFile: createIsOptimizedDepFile(environment),
  43338. isOptimizedDepUrl: createIsOptimizedDepUrl(environment),
  43339. getOptimizedDepId: (depInfo) => `${depInfo.file}?v=${depInfo.browserHash}`,
  43340. close,
  43341. options
  43342. };
  43343. let newDepsDiscovered = false;
  43344. let newDepsToLog = [];
  43345. let newDepsToLogHandle;
  43346. const logNewlyDiscoveredDeps = () => {
  43347. if (newDepsToLog.length) {
  43348. logger.info(
  43349. colors$1.green(
  43350. `\u2728 new dependencies optimized: ${depsLogString(newDepsToLog)}`
  43351. ),
  43352. {
  43353. timestamp: true
  43354. }
  43355. );
  43356. newDepsToLog = [];
  43357. }
  43358. };
  43359. let discoveredDepsWhileScanning = [];
  43360. const logDiscoveredDepsWhileScanning = () => {
  43361. if (discoveredDepsWhileScanning.length) {
  43362. logger.info(
  43363. colors$1.green(
  43364. `\u2728 discovered while scanning: ${depsLogString(
  43365. discoveredDepsWhileScanning
  43366. )}`
  43367. ),
  43368. {
  43369. timestamp: true
  43370. }
  43371. );
  43372. discoveredDepsWhileScanning = [];
  43373. }
  43374. };
  43375. let depOptimizationProcessing = promiseWithResolvers();
  43376. let depOptimizationProcessingQueue = [];
  43377. const resolveEnqueuedProcessingPromises = () => {
  43378. for (const processing of depOptimizationProcessingQueue) {
  43379. processing.resolve();
  43380. }
  43381. depOptimizationProcessingQueue = [];
  43382. };
  43383. let enqueuedRerun;
  43384. let currentlyProcessing = false;
  43385. let firstRunCalled = false;
  43386. let warnAboutMissedDependencies = false;
  43387. let waitingForCrawlEnd = false;
  43388. let optimizationResult;
  43389. let discover;
  43390. async function close() {
  43391. closed = true;
  43392. await Promise.allSettled([
  43393. discover?.cancel(),
  43394. depsOptimizer.scanProcessing,
  43395. optimizationResult?.cancel()
  43396. ]);
  43397. }
  43398. let inited = false;
  43399. async function init() {
  43400. if (inited) return;
  43401. inited = true;
  43402. const cachedMetadata = await loadCachedDepOptimizationMetadata(environment);
  43403. firstRunCalled = !!cachedMetadata;
  43404. metadata = depsOptimizer.metadata = cachedMetadata || initDepsOptimizerMetadata(environment, sessionTimestamp);
  43405. if (!cachedMetadata) {
  43406. waitingForCrawlEnd = true;
  43407. currentlyProcessing = true;
  43408. const manuallyIncludedDeps = {};
  43409. await addManuallyIncludedOptimizeDeps(environment, manuallyIncludedDeps);
  43410. const manuallyIncludedDepsInfo = toDiscoveredDependencies(
  43411. environment,
  43412. manuallyIncludedDeps,
  43413. sessionTimestamp
  43414. );
  43415. for (const depInfo of Object.values(manuallyIncludedDepsInfo)) {
  43416. addOptimizedDepInfo(metadata, "discovered", {
  43417. ...depInfo,
  43418. processing: depOptimizationProcessing.promise
  43419. });
  43420. newDepsDiscovered = true;
  43421. }
  43422. environment.waitForRequestsIdle().then(onCrawlEnd);
  43423. if (noDiscovery) {
  43424. runOptimizer();
  43425. } else {
  43426. depsOptimizer.scanProcessing = new Promise((resolve) => {
  43427. (async () => {
  43428. try {
  43429. debug$1?.(colors$1.green(`scanning for dependencies...`));
  43430. discover = discoverProjectDependencies(
  43431. devToScanEnvironment(environment)
  43432. );
  43433. const deps = await discover.result;
  43434. discover = void 0;
  43435. const manuallyIncluded = Object.keys(manuallyIncludedDepsInfo);
  43436. discoveredDepsWhileScanning.push(
  43437. ...Object.keys(metadata.discovered).filter(
  43438. (dep) => !deps[dep] && !manuallyIncluded.includes(dep)
  43439. )
  43440. );
  43441. for (const id of Object.keys(deps)) {
  43442. if (!metadata.discovered[id]) {
  43443. addMissingDep(id, deps[id]);
  43444. }
  43445. }
  43446. const knownDeps = prepareKnownDeps();
  43447. startNextDiscoveredBatch();
  43448. optimizationResult = runOptimizeDeps(environment, knownDeps);
  43449. if (!holdUntilCrawlEnd) {
  43450. optimizationResult.result.then((result) => {
  43451. if (!waitingForCrawlEnd) return;
  43452. optimizationResult = void 0;
  43453. runOptimizer(result);
  43454. });
  43455. }
  43456. } catch (e) {
  43457. logger.error(e.stack || e.message);
  43458. } finally {
  43459. resolve();
  43460. depsOptimizer.scanProcessing = void 0;
  43461. }
  43462. })();
  43463. });
  43464. }
  43465. }
  43466. }
  43467. function startNextDiscoveredBatch() {
  43468. newDepsDiscovered = false;
  43469. depOptimizationProcessingQueue.push(depOptimizationProcessing);
  43470. depOptimizationProcessing = promiseWithResolvers();
  43471. }
  43472. function prepareKnownDeps() {
  43473. const knownDeps = {};
  43474. const metadata2 = depsOptimizer.metadata;
  43475. for (const dep of Object.keys(metadata2.optimized)) {
  43476. knownDeps[dep] = { ...metadata2.optimized[dep] };
  43477. }
  43478. for (const dep of Object.keys(metadata2.discovered)) {
  43479. const { processing, ...info } = metadata2.discovered[dep];
  43480. knownDeps[dep] = info;
  43481. }
  43482. return knownDeps;
  43483. }
  43484. async function runOptimizer(preRunResult) {
  43485. const isRerun = firstRunCalled;
  43486. firstRunCalled = true;
  43487. enqueuedRerun = void 0;
  43488. if (debounceProcessingHandle) clearTimeout(debounceProcessingHandle);
  43489. if (closed) {
  43490. currentlyProcessing = false;
  43491. depOptimizationProcessing.resolve();
  43492. resolveEnqueuedProcessingPromises();
  43493. return;
  43494. }
  43495. currentlyProcessing = true;
  43496. try {
  43497. let processingResult;
  43498. if (preRunResult) {
  43499. processingResult = preRunResult;
  43500. } else {
  43501. const knownDeps = prepareKnownDeps();
  43502. startNextDiscoveredBatch();
  43503. optimizationResult = runOptimizeDeps(environment, knownDeps);
  43504. processingResult = await optimizationResult.result;
  43505. optimizationResult = void 0;
  43506. }
  43507. if (closed) {
  43508. currentlyProcessing = false;
  43509. processingResult.cancel();
  43510. resolveEnqueuedProcessingPromises();
  43511. return;
  43512. }
  43513. const newData = processingResult.metadata;
  43514. const needsInteropMismatch = findInteropMismatches(
  43515. metadata.discovered,
  43516. newData.optimized
  43517. );
  43518. const needsReload = needsInteropMismatch.length > 0 || metadata.hash !== newData.hash || Object.keys(metadata.optimized).some((dep) => {
  43519. return metadata.optimized[dep].fileHash !== newData.optimized[dep].fileHash;
  43520. });
  43521. const commitProcessing = async () => {
  43522. await processingResult.commit();
  43523. for (const id in metadata.discovered) {
  43524. if (!newData.optimized[id]) {
  43525. addOptimizedDepInfo(newData, "discovered", metadata.discovered[id]);
  43526. }
  43527. }
  43528. if (!needsReload) {
  43529. newData.browserHash = metadata.browserHash;
  43530. for (const dep in newData.chunks) {
  43531. newData.chunks[dep].browserHash = metadata.browserHash;
  43532. }
  43533. for (const dep in newData.optimized) {
  43534. newData.optimized[dep].browserHash = (metadata.optimized[dep] || metadata.discovered[dep]).browserHash;
  43535. }
  43536. }
  43537. for (const o in newData.optimized) {
  43538. const discovered = metadata.discovered[o];
  43539. if (discovered) {
  43540. const optimized = newData.optimized[o];
  43541. discovered.browserHash = optimized.browserHash;
  43542. discovered.fileHash = optimized.fileHash;
  43543. discovered.needsInterop = optimized.needsInterop;
  43544. discovered.processing = void 0;
  43545. }
  43546. }
  43547. if (isRerun) {
  43548. newDepsToLog.push(
  43549. ...Object.keys(newData.optimized).filter(
  43550. (dep) => !metadata.optimized[dep]
  43551. )
  43552. );
  43553. }
  43554. metadata = depsOptimizer.metadata = newData;
  43555. resolveEnqueuedProcessingPromises();
  43556. };
  43557. if (!needsReload) {
  43558. await commitProcessing();
  43559. if (!debug$1) {
  43560. if (newDepsToLogHandle) clearTimeout(newDepsToLogHandle);
  43561. newDepsToLogHandle = setTimeout(() => {
  43562. newDepsToLogHandle = void 0;
  43563. logNewlyDiscoveredDeps();
  43564. if (warnAboutMissedDependencies) {
  43565. logDiscoveredDepsWhileScanning();
  43566. logger.info(
  43567. colors$1.magenta(
  43568. `\u2757 add these dependencies to optimizeDeps.include to speed up cold start`
  43569. ),
  43570. { timestamp: true }
  43571. );
  43572. warnAboutMissedDependencies = false;
  43573. }
  43574. }, 2 * debounceMs);
  43575. } else {
  43576. debug$1(
  43577. colors$1.green(
  43578. `\u2728 ${!isRerun ? `dependencies optimized` : `optimized dependencies unchanged`}`
  43579. )
  43580. );
  43581. }
  43582. } else {
  43583. if (newDepsDiscovered) {
  43584. processingResult.cancel();
  43585. debug$1?.(
  43586. colors$1.green(
  43587. `\u2728 delaying reload as new dependencies have been found...`
  43588. )
  43589. );
  43590. } else {
  43591. await commitProcessing();
  43592. if (!debug$1) {
  43593. if (newDepsToLogHandle) clearTimeout(newDepsToLogHandle);
  43594. newDepsToLogHandle = void 0;
  43595. logNewlyDiscoveredDeps();
  43596. if (warnAboutMissedDependencies) {
  43597. logDiscoveredDepsWhileScanning();
  43598. logger.info(
  43599. colors$1.magenta(
  43600. `\u2757 add these dependencies to optimizeDeps.include to avoid a full page reload during cold start`
  43601. ),
  43602. { timestamp: true }
  43603. );
  43604. warnAboutMissedDependencies = false;
  43605. }
  43606. }
  43607. logger.info(
  43608. colors$1.green(`\u2728 optimized dependencies changed. reloading`),
  43609. {
  43610. timestamp: true
  43611. }
  43612. );
  43613. if (needsInteropMismatch.length > 0) {
  43614. logger.warn(
  43615. `Mixed ESM and CJS detected in ${colors$1.yellow(
  43616. needsInteropMismatch.join(", ")
  43617. )}, add ${needsInteropMismatch.length === 1 ? "it" : "them"} to optimizeDeps.needsInterop to speed up cold start`,
  43618. {
  43619. timestamp: true
  43620. }
  43621. );
  43622. }
  43623. fullReload();
  43624. }
  43625. }
  43626. } catch (e) {
  43627. logger.error(
  43628. colors$1.red(`error while updating dependencies:
  43629. ${e.stack}`),
  43630. { timestamp: true, error: e }
  43631. );
  43632. resolveEnqueuedProcessingPromises();
  43633. metadata.discovered = {};
  43634. }
  43635. currentlyProcessing = false;
  43636. enqueuedRerun?.();
  43637. }
  43638. function fullReload() {
  43639. environment.moduleGraph.invalidateAll();
  43640. environment.hot.send({
  43641. type: "full-reload",
  43642. path: "*"
  43643. });
  43644. }
  43645. async function rerun() {
  43646. const deps = Object.keys(metadata.discovered);
  43647. const depsString = depsLogString(deps);
  43648. debug$1?.(colors$1.green(`new dependencies found: ${depsString}`));
  43649. runOptimizer();
  43650. }
  43651. function getDiscoveredBrowserHash(hash, deps, missing) {
  43652. return getHash(
  43653. hash + JSON.stringify(deps) + JSON.stringify(missing) + sessionTimestamp
  43654. );
  43655. }
  43656. function registerMissingImport(id, resolved) {
  43657. const optimized = metadata.optimized[id];
  43658. if (optimized) {
  43659. return optimized;
  43660. }
  43661. const chunk = metadata.chunks[id];
  43662. if (chunk) {
  43663. return chunk;
  43664. }
  43665. let missing = metadata.discovered[id];
  43666. if (missing) {
  43667. return missing;
  43668. }
  43669. missing = addMissingDep(id, resolved);
  43670. if (!waitingForCrawlEnd) {
  43671. debouncedProcessing();
  43672. }
  43673. return missing;
  43674. }
  43675. function addMissingDep(id, resolved) {
  43676. newDepsDiscovered = true;
  43677. return addOptimizedDepInfo(metadata, "discovered", {
  43678. id,
  43679. file: getOptimizedDepPath(environment, id),
  43680. src: resolved,
  43681. // Adding a browserHash to this missing dependency that is unique to
  43682. // the current state of known + missing deps. If its optimizeDeps run
  43683. // doesn't alter the bundled files of previous known dependencies,
  43684. // we don't need a full reload and this browserHash will be kept
  43685. browserHash: getDiscoveredBrowserHash(
  43686. metadata.hash,
  43687. depsFromOptimizedDepInfo(metadata.optimized),
  43688. depsFromOptimizedDepInfo(metadata.discovered)
  43689. ),
  43690. // loading of this pre-bundled dep needs to await for its processing
  43691. // promise to be resolved
  43692. processing: depOptimizationProcessing.promise,
  43693. exportsData: extractExportsData(environment, resolved)
  43694. });
  43695. }
  43696. function debouncedProcessing(timeout = debounceMs) {
  43697. enqueuedRerun = void 0;
  43698. if (debounceProcessingHandle) clearTimeout(debounceProcessingHandle);
  43699. if (newDepsToLogHandle) clearTimeout(newDepsToLogHandle);
  43700. newDepsToLogHandle = void 0;
  43701. debounceProcessingHandle = setTimeout(() => {
  43702. debounceProcessingHandle = void 0;
  43703. enqueuedRerun = rerun;
  43704. if (!currentlyProcessing) {
  43705. enqueuedRerun();
  43706. }
  43707. }, timeout);
  43708. }
  43709. async function onCrawlEnd() {
  43710. waitingForCrawlEnd = false;
  43711. debug$1?.(colors$1.green(`\u2728 static imports crawl ended`));
  43712. if (closed) {
  43713. return;
  43714. }
  43715. await depsOptimizer.scanProcessing;
  43716. if (optimizationResult && !options.noDiscovery) {
  43717. const afterScanResult = optimizationResult.result;
  43718. optimizationResult = void 0;
  43719. const result = await afterScanResult;
  43720. currentlyProcessing = false;
  43721. const crawlDeps = Object.keys(metadata.discovered);
  43722. const scanDeps = Object.keys(result.metadata.optimized);
  43723. if (scanDeps.length === 0 && crawlDeps.length === 0) {
  43724. debug$1?.(
  43725. colors$1.green(
  43726. `\u2728 no dependencies found by the scanner or crawling static imports`
  43727. )
  43728. );
  43729. startNextDiscoveredBatch();
  43730. runOptimizer(result);
  43731. return;
  43732. }
  43733. const needsInteropMismatch = findInteropMismatches(
  43734. metadata.discovered,
  43735. result.metadata.optimized
  43736. );
  43737. const scannerMissedDeps = crawlDeps.some((dep) => !scanDeps.includes(dep));
  43738. const outdatedResult = needsInteropMismatch.length > 0 || scannerMissedDeps;
  43739. if (outdatedResult) {
  43740. result.cancel();
  43741. for (const dep of scanDeps) {
  43742. if (!crawlDeps.includes(dep)) {
  43743. addMissingDep(dep, result.metadata.optimized[dep].src);
  43744. }
  43745. }
  43746. if (scannerMissedDeps) {
  43747. debug$1?.(
  43748. colors$1.yellow(
  43749. `\u2728 new dependencies were found while crawling that weren't detected by the scanner`
  43750. )
  43751. );
  43752. }
  43753. debug$1?.(colors$1.green(`\u2728 re-running optimizer`));
  43754. debouncedProcessing(0);
  43755. } else {
  43756. debug$1?.(
  43757. colors$1.green(
  43758. `\u2728 using post-scan optimizer result, the scanner found every used dependency`
  43759. )
  43760. );
  43761. startNextDiscoveredBatch();
  43762. runOptimizer(result);
  43763. }
  43764. } else if (!holdUntilCrawlEnd) {
  43765. if (newDepsDiscovered) {
  43766. debug$1?.(
  43767. colors$1.green(
  43768. `\u2728 new dependencies were found while crawling static imports, re-running optimizer`
  43769. )
  43770. );
  43771. warnAboutMissedDependencies = true;
  43772. debouncedProcessing(0);
  43773. }
  43774. } else {
  43775. const crawlDeps = Object.keys(metadata.discovered);
  43776. currentlyProcessing = false;
  43777. if (crawlDeps.length === 0) {
  43778. debug$1?.(
  43779. colors$1.green(
  43780. `\u2728 no dependencies found while crawling the static imports`
  43781. )
  43782. );
  43783. firstRunCalled = true;
  43784. }
  43785. debouncedProcessing(0);
  43786. }
  43787. }
  43788. return depsOptimizer;
  43789. }
  43790. function createExplicitDepsOptimizer(environment) {
  43791. const depsOptimizer = {
  43792. metadata: initDepsOptimizerMetadata(environment),
  43793. isOptimizedDepFile: createIsOptimizedDepFile(environment),
  43794. isOptimizedDepUrl: createIsOptimizedDepUrl(environment),
  43795. getOptimizedDepId: (depInfo) => `${depInfo.file}?v=${depInfo.browserHash}`,
  43796. registerMissingImport: () => {
  43797. throw new Error(
  43798. `Vite Internal Error: registerMissingImport is not supported in dev ${environment.name}`
  43799. );
  43800. },
  43801. init,
  43802. // noop, there is no scanning during dev SSR
  43803. // the optimizer blocks the server start
  43804. run: () => {
  43805. },
  43806. close: async () => {
  43807. },
  43808. options: environment.config.optimizeDeps
  43809. };
  43810. let inited = false;
  43811. async function init() {
  43812. if (inited) return;
  43813. inited = true;
  43814. depsOptimizer.metadata = await optimizeExplicitEnvironmentDeps(environment);
  43815. }
  43816. return depsOptimizer;
  43817. }
  43818. function findInteropMismatches(discovered, optimized) {
  43819. const needsInteropMismatch = [];
  43820. for (const dep in discovered) {
  43821. const discoveredDepInfo = discovered[dep];
  43822. if (discoveredDepInfo.needsInterop === void 0) continue;
  43823. const depInfo = optimized[dep];
  43824. if (!depInfo) continue;
  43825. if (depInfo.needsInterop !== discoveredDepInfo.needsInterop) {
  43826. needsInteropMismatch.push(dep);
  43827. debug$1?.(colors$1.cyan(`\u2728 needsInterop mismatch detected for ${dep}`));
  43828. }
  43829. }
  43830. return needsInteropMismatch;
  43831. }
  43832. class EnvironmentModuleNode {
  43833. environment;
  43834. /**
  43835. * Public served url path, starts with /
  43836. */
  43837. url;
  43838. /**
  43839. * Resolved file system path + query
  43840. */
  43841. id = null;
  43842. file = null;
  43843. type;
  43844. info;
  43845. meta;
  43846. importers = /* @__PURE__ */ new Set();
  43847. importedModules = /* @__PURE__ */ new Set();
  43848. acceptedHmrDeps = /* @__PURE__ */ new Set();
  43849. acceptedHmrExports = null;
  43850. importedBindings = null;
  43851. isSelfAccepting;
  43852. transformResult = null;
  43853. // ssrModule and ssrError are no longer needed. They are on the module runner module cache.
  43854. // Once `ssrLoadModule` is re-implemented on top of the new APIs, we can delete these.
  43855. ssrModule = null;
  43856. ssrError = null;
  43857. lastHMRTimestamp = 0;
  43858. /**
  43859. * `import.meta.hot.invalidate` is called by the client.
  43860. * If there's multiple clients, multiple `invalidate` request is received.
  43861. * This property is used to dedupe those request to avoid multiple updates happening.
  43862. * @internal
  43863. */
  43864. lastHMRInvalidationReceived = false;
  43865. lastInvalidationTimestamp = 0;
  43866. /**
  43867. * If the module only needs to update its imports timestamp (e.g. within an HMR chain),
  43868. * it is considered soft-invalidated. In this state, its `transformResult` should exist,
  43869. * and the next `transformRequest` for this module will replace the timestamps.
  43870. *
  43871. * By default the value is `undefined` if it's not soft/hard-invalidated. If it gets
  43872. * soft-invalidated, this will contain the previous `transformResult` value. If it gets
  43873. * hard-invalidated, this will be set to `'HARD_INVALIDATED'`.
  43874. * @internal
  43875. */
  43876. invalidationState;
  43877. /**
  43878. * The module urls that are statically imported in the code. This information is separated
  43879. * out from `importedModules` as only importers that statically import the module can be
  43880. * soft invalidated. Other imports (e.g. watched files) needs the importer to be hard invalidated.
  43881. * @internal
  43882. */
  43883. staticImportedUrls;
  43884. /**
  43885. * @param setIsSelfAccepting - set `false` to set `isSelfAccepting` later. e.g. #7870
  43886. */
  43887. constructor(url, environment, setIsSelfAccepting = true) {
  43888. this.environment = environment;
  43889. this.url = url;
  43890. this.type = isDirectCSSRequest(url) ? "css" : "js";
  43891. if (setIsSelfAccepting) {
  43892. this.isSelfAccepting = false;
  43893. }
  43894. }
  43895. }
  43896. class EnvironmentModuleGraph {
  43897. environment;
  43898. urlToModuleMap = /* @__PURE__ */ new Map();
  43899. idToModuleMap = /* @__PURE__ */ new Map();
  43900. etagToModuleMap = /* @__PURE__ */ new Map();
  43901. // a single file may corresponds to multiple modules with different queries
  43902. fileToModulesMap = /* @__PURE__ */ new Map();
  43903. /**
  43904. * @internal
  43905. */
  43906. _unresolvedUrlToModuleMap = /* @__PURE__ */ new Map();
  43907. /**
  43908. * @internal
  43909. */
  43910. _resolveId;
  43911. /** @internal */
  43912. _hasResolveFailedErrorModules = /* @__PURE__ */ new Set();
  43913. constructor(environment, resolveId) {
  43914. this.environment = environment;
  43915. this._resolveId = resolveId;
  43916. }
  43917. async getModuleByUrl(rawUrl) {
  43918. rawUrl = removeImportQuery(removeTimestampQuery(rawUrl));
  43919. const mod = this._getUnresolvedUrlToModule(rawUrl);
  43920. if (mod) {
  43921. return mod;
  43922. }
  43923. const [url] = await this._resolveUrl(rawUrl);
  43924. return this.urlToModuleMap.get(url);
  43925. }
  43926. getModuleById(id) {
  43927. return this.idToModuleMap.get(removeTimestampQuery(id));
  43928. }
  43929. getModulesByFile(file) {
  43930. return this.fileToModulesMap.get(file);
  43931. }
  43932. onFileChange(file) {
  43933. const mods = this.getModulesByFile(file);
  43934. if (mods) {
  43935. const seen = /* @__PURE__ */ new Set();
  43936. mods.forEach((mod) => {
  43937. this.invalidateModule(mod, seen);
  43938. });
  43939. }
  43940. }
  43941. onFileDelete(file) {
  43942. const mods = this.getModulesByFile(file);
  43943. if (mods) {
  43944. mods.forEach((mod) => {
  43945. mod.importedModules.forEach((importedMod) => {
  43946. importedMod.importers.delete(mod);
  43947. });
  43948. });
  43949. }
  43950. }
  43951. invalidateModule(mod, seen = /* @__PURE__ */ new Set(), timestamp = Date.now(), isHmr = false, softInvalidate = false) {
  43952. const prevInvalidationState = mod.invalidationState;
  43953. if (softInvalidate) {
  43954. mod.invalidationState ??= mod.transformResult ?? "HARD_INVALIDATED";
  43955. } else {
  43956. mod.invalidationState = "HARD_INVALIDATED";
  43957. }
  43958. if (seen.has(mod) && prevInvalidationState === mod.invalidationState) {
  43959. return;
  43960. }
  43961. seen.add(mod);
  43962. if (isHmr) {
  43963. mod.lastHMRTimestamp = timestamp;
  43964. mod.lastHMRInvalidationReceived = false;
  43965. } else {
  43966. mod.lastInvalidationTimestamp = timestamp;
  43967. }
  43968. const etag = mod.transformResult?.etag;
  43969. if (etag) this.etagToModuleMap.delete(etag);
  43970. mod.transformResult = null;
  43971. mod.ssrModule = null;
  43972. mod.ssrError = null;
  43973. mod.importers.forEach((importer) => {
  43974. if (!importer.acceptedHmrDeps.has(mod)) {
  43975. const shouldSoftInvalidateImporter = (importer.staticImportedUrls?.has(mod.url) || softInvalidate) && importer.type !== "css";
  43976. this.invalidateModule(
  43977. importer,
  43978. seen,
  43979. timestamp,
  43980. isHmr,
  43981. shouldSoftInvalidateImporter
  43982. );
  43983. }
  43984. });
  43985. this._hasResolveFailedErrorModules.delete(mod);
  43986. }
  43987. invalidateAll() {
  43988. const timestamp = Date.now();
  43989. const seen = /* @__PURE__ */ new Set();
  43990. this.idToModuleMap.forEach((mod) => {
  43991. this.invalidateModule(mod, seen, timestamp);
  43992. });
  43993. }
  43994. /**
  43995. * Update the module graph based on a module's updated imports information
  43996. * If there are dependencies that no longer have any importers, they are
  43997. * returned as a Set.
  43998. *
  43999. * @param staticImportedUrls Subset of `importedModules` where they're statically imported in code.
  44000. * This is only used for soft invalidations so `undefined` is fine but may cause more runtime processing.
  44001. */
  44002. async updateModuleInfo(mod, importedModules, importedBindings, acceptedModules, acceptedExports, isSelfAccepting, staticImportedUrls) {
  44003. mod.isSelfAccepting = isSelfAccepting;
  44004. const prevImports = mod.importedModules;
  44005. let noLongerImported;
  44006. let resolvePromises = [];
  44007. let resolveResults = new Array(importedModules.size);
  44008. let index = 0;
  44009. for (const imported of importedModules) {
  44010. const nextIndex = index++;
  44011. if (typeof imported === "string") {
  44012. resolvePromises.push(
  44013. this.ensureEntryFromUrl(imported).then((dep) => {
  44014. dep.importers.add(mod);
  44015. resolveResults[nextIndex] = dep;
  44016. })
  44017. );
  44018. } else {
  44019. imported.importers.add(mod);
  44020. resolveResults[nextIndex] = imported;
  44021. }
  44022. }
  44023. if (resolvePromises.length) {
  44024. await Promise.all(resolvePromises);
  44025. }
  44026. const nextImports = new Set(resolveResults);
  44027. mod.importedModules = nextImports;
  44028. prevImports.forEach((dep) => {
  44029. if (!mod.importedModules.has(dep)) {
  44030. dep.importers.delete(mod);
  44031. if (!dep.importers.size) {
  44032. (noLongerImported || (noLongerImported = /* @__PURE__ */ new Set())).add(dep);
  44033. }
  44034. }
  44035. });
  44036. resolvePromises = [];
  44037. resolveResults = new Array(acceptedModules.size);
  44038. index = 0;
  44039. for (const accepted of acceptedModules) {
  44040. const nextIndex = index++;
  44041. if (typeof accepted === "string") {
  44042. resolvePromises.push(
  44043. this.ensureEntryFromUrl(accepted).then((dep) => {
  44044. resolveResults[nextIndex] = dep;
  44045. })
  44046. );
  44047. } else {
  44048. resolveResults[nextIndex] = accepted;
  44049. }
  44050. }
  44051. if (resolvePromises.length) {
  44052. await Promise.all(resolvePromises);
  44053. }
  44054. mod.acceptedHmrDeps = new Set(resolveResults);
  44055. mod.staticImportedUrls = staticImportedUrls;
  44056. mod.acceptedHmrExports = acceptedExports;
  44057. mod.importedBindings = importedBindings;
  44058. return noLongerImported;
  44059. }
  44060. async ensureEntryFromUrl(rawUrl, setIsSelfAccepting = true) {
  44061. return this._ensureEntryFromUrl(rawUrl, setIsSelfAccepting);
  44062. }
  44063. /**
  44064. * @internal
  44065. */
  44066. async _ensureEntryFromUrl(rawUrl, setIsSelfAccepting = true, resolved) {
  44067. rawUrl = removeImportQuery(removeTimestampQuery(rawUrl));
  44068. let mod = this._getUnresolvedUrlToModule(rawUrl);
  44069. if (mod) {
  44070. return mod;
  44071. }
  44072. const modPromise = (async () => {
  44073. const [url, resolvedId, meta] = await this._resolveUrl(rawUrl, resolved);
  44074. mod = this.idToModuleMap.get(resolvedId);
  44075. if (!mod) {
  44076. mod = new EnvironmentModuleNode(
  44077. url,
  44078. this.environment,
  44079. setIsSelfAccepting
  44080. );
  44081. if (meta) mod.meta = meta;
  44082. this.urlToModuleMap.set(url, mod);
  44083. mod.id = resolvedId;
  44084. this.idToModuleMap.set(resolvedId, mod);
  44085. const file = mod.file = cleanUrl(resolvedId);
  44086. let fileMappedModules = this.fileToModulesMap.get(file);
  44087. if (!fileMappedModules) {
  44088. fileMappedModules = /* @__PURE__ */ new Set();
  44089. this.fileToModulesMap.set(file, fileMappedModules);
  44090. }
  44091. fileMappedModules.add(mod);
  44092. } else if (!this.urlToModuleMap.has(url)) {
  44093. this.urlToModuleMap.set(url, mod);
  44094. }
  44095. this._setUnresolvedUrlToModule(rawUrl, mod);
  44096. return mod;
  44097. })();
  44098. this._setUnresolvedUrlToModule(rawUrl, modPromise);
  44099. return modPromise;
  44100. }
  44101. // some deps, like a css file referenced via @import, don't have its own
  44102. // url because they are inlined into the main css import. But they still
  44103. // need to be represented in the module graph so that they can trigger
  44104. // hmr in the importing css file.
  44105. createFileOnlyEntry(file) {
  44106. file = normalizePath$3(file);
  44107. let fileMappedModules = this.fileToModulesMap.get(file);
  44108. if (!fileMappedModules) {
  44109. fileMappedModules = /* @__PURE__ */ new Set();
  44110. this.fileToModulesMap.set(file, fileMappedModules);
  44111. }
  44112. const url = `${FS_PREFIX}${file}`;
  44113. for (const m of fileMappedModules) {
  44114. if (m.url === url || m.id === file) {
  44115. return m;
  44116. }
  44117. }
  44118. const mod = new EnvironmentModuleNode(url, this.environment);
  44119. mod.file = file;
  44120. fileMappedModules.add(mod);
  44121. return mod;
  44122. }
  44123. // for incoming urls, it is important to:
  44124. // 1. remove the HMR timestamp query (?t=xxxx) and the ?import query
  44125. // 2. resolve its extension so that urls with or without extension all map to
  44126. // the same module
  44127. async resolveUrl(url) {
  44128. url = removeImportQuery(removeTimestampQuery(url));
  44129. const mod = await this._getUnresolvedUrlToModule(url);
  44130. if (mod?.id) {
  44131. return [mod.url, mod.id, mod.meta];
  44132. }
  44133. return this._resolveUrl(url);
  44134. }
  44135. updateModuleTransformResult(mod, result) {
  44136. if (this.environment === "client") {
  44137. const prevEtag = mod.transformResult?.etag;
  44138. if (prevEtag) this.etagToModuleMap.delete(prevEtag);
  44139. if (result?.etag) this.etagToModuleMap.set(result.etag, mod);
  44140. }
  44141. mod.transformResult = result;
  44142. }
  44143. getModuleByEtag(etag) {
  44144. return this.etagToModuleMap.get(etag);
  44145. }
  44146. /**
  44147. * @internal
  44148. */
  44149. _getUnresolvedUrlToModule(url) {
  44150. return this._unresolvedUrlToModuleMap.get(url);
  44151. }
  44152. /**
  44153. * @internal
  44154. */
  44155. _setUnresolvedUrlToModule(url, mod) {
  44156. this._unresolvedUrlToModuleMap.set(url, mod);
  44157. }
  44158. /**
  44159. * @internal
  44160. */
  44161. async _resolveUrl(url, alreadyResolved) {
  44162. const resolved = alreadyResolved ?? await this._resolveId(url);
  44163. const resolvedId = resolved?.id || url;
  44164. if (url !== resolvedId && !url.includes("\0") && !url.startsWith(`virtual:`)) {
  44165. const ext = extname$1(cleanUrl(resolvedId));
  44166. if (ext) {
  44167. const pathname = cleanUrl(url);
  44168. if (!pathname.endsWith(ext)) {
  44169. url = pathname + ext + url.slice(pathname.length);
  44170. }
  44171. }
  44172. }
  44173. return [url, resolvedId, resolved?.meta];
  44174. }
  44175. }
  44176. function warmupFiles(server, environment) {
  44177. const { root } = server.config;
  44178. mapFiles(environment.config.dev.warmup, root).then((files) => {
  44179. for (const file of files) {
  44180. warmupFile(server, environment, file);
  44181. }
  44182. });
  44183. }
  44184. async function warmupFile(server, environment, file) {
  44185. if (file.endsWith(".html")) {
  44186. const url = htmlFileToUrl(file, server.config.root);
  44187. if (url) {
  44188. try {
  44189. const html = await fsp.readFile(file, "utf-8");
  44190. await server.transformIndexHtml(url, html);
  44191. } catch (e) {
  44192. environment.logger.error(
  44193. `Pre-transform error (${colors$1.cyan(file)}): ${e.message}`,
  44194. {
  44195. error: e,
  44196. timestamp: true
  44197. }
  44198. );
  44199. }
  44200. }
  44201. } else {
  44202. const url = fileToUrl(file, server.config.root);
  44203. await environment.warmupRequest(url);
  44204. }
  44205. }
  44206. function htmlFileToUrl(file, root) {
  44207. const url = path$b.relative(root, file);
  44208. if (url[0] === ".") return;
  44209. return "/" + normalizePath$3(url);
  44210. }
  44211. function fileToUrl(file, root) {
  44212. const url = path$b.relative(root, file);
  44213. if (url[0] === ".") {
  44214. return path$b.posix.join(FS_PREFIX, normalizePath$3(file));
  44215. }
  44216. return "/" + normalizePath$3(url);
  44217. }
  44218. async function mapFiles(files, root) {
  44219. if (!files.length) return [];
  44220. const result = [];
  44221. const globs = [];
  44222. for (const file of files) {
  44223. if (isDynamicPattern(file)) {
  44224. globs.push(file);
  44225. } else {
  44226. if (path$b.isAbsolute(file)) {
  44227. result.push(file);
  44228. } else {
  44229. result.push(path$b.resolve(root, file));
  44230. }
  44231. }
  44232. }
  44233. if (globs.length) {
  44234. result.push(
  44235. ...await glob(globs, {
  44236. absolute: true,
  44237. cwd: root,
  44238. expandDirectories: false,
  44239. ignore: ["**/.git/**", "**/node_modules/**"]
  44240. })
  44241. );
  44242. }
  44243. return result;
  44244. }
  44245. class DevEnvironment extends BaseEnvironment {
  44246. mode = "dev";
  44247. moduleGraph;
  44248. depsOptimizer;
  44249. /**
  44250. * @internal
  44251. */
  44252. _remoteRunnerOptions;
  44253. get pluginContainer() {
  44254. if (!this._pluginContainer)
  44255. throw new Error(
  44256. `${this.name} environment.pluginContainer called before initialized`
  44257. );
  44258. return this._pluginContainer;
  44259. }
  44260. /**
  44261. * @internal
  44262. */
  44263. _pluginContainer;
  44264. /**
  44265. * @internal
  44266. */
  44267. _closing = false;
  44268. /**
  44269. * @internal
  44270. */
  44271. _pendingRequests;
  44272. /**
  44273. * @internal
  44274. */
  44275. _crawlEndFinder;
  44276. /**
  44277. * Hot channel for this environment. If not provided or disabled,
  44278. * it will be a noop channel that does nothing.
  44279. *
  44280. * @example
  44281. * environment.hot.send({ type: 'full-reload' })
  44282. */
  44283. hot;
  44284. constructor(name, config, context) {
  44285. let options = config.environments[name] ?? getDefaultResolvedEnvironmentOptions(config);
  44286. if (context.options) {
  44287. options = mergeConfig(
  44288. options,
  44289. context.options
  44290. );
  44291. }
  44292. super(name, config, options);
  44293. this._pendingRequests = /* @__PURE__ */ new Map();
  44294. this.moduleGraph = new EnvironmentModuleGraph(
  44295. name,
  44296. (url) => this.pluginContainer.resolveId(url, void 0)
  44297. );
  44298. this._crawlEndFinder = setupOnCrawlEnd();
  44299. this._remoteRunnerOptions = context.remoteRunner ?? {};
  44300. this.hot = context.transport ? isWebSocketServer in context.transport ? context.transport : normalizeHotChannel(context.transport, context.hot) : normalizeHotChannel({}, context.hot);
  44301. this.hot.setInvokeHandler({
  44302. fetchModule: (id, importer, options2) => {
  44303. return this.fetchModule(id, importer, options2);
  44304. }
  44305. });
  44306. this.hot.on(
  44307. "vite:invalidate",
  44308. async ({ path, message, firstInvalidatedBy }) => {
  44309. invalidateModule(this, {
  44310. path,
  44311. message,
  44312. firstInvalidatedBy
  44313. });
  44314. }
  44315. );
  44316. const { optimizeDeps } = this.config;
  44317. if (context.depsOptimizer) {
  44318. this.depsOptimizer = context.depsOptimizer;
  44319. } else if (isDepOptimizationDisabled(optimizeDeps)) {
  44320. this.depsOptimizer = void 0;
  44321. } else {
  44322. this.depsOptimizer = (optimizeDeps.noDiscovery ? createExplicitDepsOptimizer : createDepsOptimizer)(this);
  44323. }
  44324. }
  44325. async init(options) {
  44326. if (this._initiated) {
  44327. return;
  44328. }
  44329. this._initiated = true;
  44330. this._plugins = await resolveEnvironmentPlugins(this);
  44331. this._pluginContainer = await createEnvironmentPluginContainer(
  44332. this,
  44333. this._plugins,
  44334. options?.watcher
  44335. );
  44336. }
  44337. /**
  44338. * When the dev server is restarted, the methods are called in the following order:
  44339. * - new instance `init`
  44340. * - previous instance `close`
  44341. * - new instance `listen`
  44342. */
  44343. async listen(server) {
  44344. this.hot.listen();
  44345. await this.depsOptimizer?.init();
  44346. warmupFiles(server, this);
  44347. }
  44348. fetchModule(id, importer, options) {
  44349. return fetchModule(this, id, importer, {
  44350. ...this._remoteRunnerOptions,
  44351. ...options
  44352. });
  44353. }
  44354. async reloadModule(module) {
  44355. if (this.config.server.hmr !== false && module.file) {
  44356. updateModules(this, module.file, [module], Date.now());
  44357. }
  44358. }
  44359. transformRequest(url) {
  44360. return transformRequest(this, url);
  44361. }
  44362. async warmupRequest(url) {
  44363. try {
  44364. await this.transformRequest(url);
  44365. } catch (e) {
  44366. if (e?.code === ERR_OUTDATED_OPTIMIZED_DEP || e?.code === ERR_CLOSED_SERVER) {
  44367. return;
  44368. }
  44369. this.logger.error(
  44370. buildErrorMessage(e, [`Pre-transform error: ${e.message}`], false),
  44371. {
  44372. error: e,
  44373. timestamp: true
  44374. }
  44375. );
  44376. }
  44377. }
  44378. async close() {
  44379. this._closing = true;
  44380. this._crawlEndFinder.cancel();
  44381. await Promise.allSettled([
  44382. this.pluginContainer.close(),
  44383. this.depsOptimizer?.close(),
  44384. // WebSocketServer is independent of HotChannel and should not be closed on environment close
  44385. isWebSocketServer in this.hot ? Promise.resolve() : this.hot.close(),
  44386. (async () => {
  44387. while (this._pendingRequests.size > 0) {
  44388. await Promise.allSettled(
  44389. [...this._pendingRequests.values()].map(
  44390. (pending) => pending.request
  44391. )
  44392. );
  44393. }
  44394. })()
  44395. ]);
  44396. }
  44397. /**
  44398. * Calling `await environment.waitForRequestsIdle(id)` will wait until all static imports
  44399. * are processed after the first transformRequest call. If called from a load or transform
  44400. * plugin hook, the id needs to be passed as a parameter to avoid deadlocks.
  44401. * Calling this function after the first static imports section of the module graph has been
  44402. * processed will resolve immediately.
  44403. * @experimental
  44404. */
  44405. waitForRequestsIdle(ignoredId) {
  44406. return this._crawlEndFinder.waitForRequestsIdle(ignoredId);
  44407. }
  44408. /**
  44409. * @internal
  44410. */
  44411. _registerRequestProcessing(id, done) {
  44412. this._crawlEndFinder.registerRequestProcessing(id, done);
  44413. }
  44414. }
  44415. function invalidateModule(environment, m) {
  44416. const mod = environment.moduleGraph.urlToModuleMap.get(m.path);
  44417. if (mod && mod.isSelfAccepting && mod.lastHMRTimestamp > 0 && !mod.lastHMRInvalidationReceived) {
  44418. mod.lastHMRInvalidationReceived = true;
  44419. environment.logger.info(
  44420. colors$1.yellow(`hmr invalidate `) + colors$1.dim(m.path) + (m.message ? ` ${m.message}` : ""),
  44421. { timestamp: true }
  44422. );
  44423. const file = getShortName(mod.file, environment.config.root);
  44424. updateModules(
  44425. environment,
  44426. file,
  44427. [...mod.importers],
  44428. mod.lastHMRTimestamp,
  44429. m.firstInvalidatedBy
  44430. );
  44431. }
  44432. }
  44433. const callCrawlEndIfIdleAfterMs = 50;
  44434. function setupOnCrawlEnd() {
  44435. const registeredIds = /* @__PURE__ */ new Set();
  44436. const seenIds = /* @__PURE__ */ new Set();
  44437. const onCrawlEndPromiseWithResolvers = promiseWithResolvers();
  44438. let timeoutHandle;
  44439. let cancelled = false;
  44440. function cancel() {
  44441. cancelled = true;
  44442. }
  44443. function registerRequestProcessing(id, done) {
  44444. if (!seenIds.has(id)) {
  44445. seenIds.add(id);
  44446. registeredIds.add(id);
  44447. done().catch(() => {
  44448. }).finally(() => markIdAsDone(id));
  44449. }
  44450. }
  44451. function waitForRequestsIdle(ignoredId) {
  44452. if (ignoredId) {
  44453. seenIds.add(ignoredId);
  44454. markIdAsDone(ignoredId);
  44455. } else {
  44456. checkIfCrawlEndAfterTimeout();
  44457. }
  44458. return onCrawlEndPromiseWithResolvers.promise;
  44459. }
  44460. function markIdAsDone(id) {
  44461. registeredIds.delete(id);
  44462. checkIfCrawlEndAfterTimeout();
  44463. }
  44464. function checkIfCrawlEndAfterTimeout() {
  44465. if (cancelled || registeredIds.size > 0) return;
  44466. if (timeoutHandle) clearTimeout(timeoutHandle);
  44467. timeoutHandle = setTimeout(
  44468. callOnCrawlEndWhenIdle,
  44469. callCrawlEndIfIdleAfterMs
  44470. );
  44471. }
  44472. async function callOnCrawlEndWhenIdle() {
  44473. if (cancelled || registeredIds.size > 0) return;
  44474. onCrawlEndPromiseWithResolvers.resolve();
  44475. }
  44476. return {
  44477. registerRequestProcessing,
  44478. waitForRequestsIdle,
  44479. cancel
  44480. };
  44481. }
  44482. function createRunnableDevEnvironment(name, config, context = {}) {
  44483. if (context.transport == null) {
  44484. context.transport = createServerHotChannel();
  44485. }
  44486. if (context.hot == null) {
  44487. context.hot = true;
  44488. }
  44489. return new RunnableDevEnvironment(name, config, context);
  44490. }
  44491. function isRunnableDevEnvironment(environment) {
  44492. return environment instanceof RunnableDevEnvironment;
  44493. }
  44494. class RunnableDevEnvironment extends DevEnvironment {
  44495. _runner;
  44496. _runnerFactory;
  44497. _runnerOptions;
  44498. constructor(name, config, context) {
  44499. super(name, config, context);
  44500. this._runnerFactory = context.runner;
  44501. this._runnerOptions = context.runnerOptions;
  44502. }
  44503. get runner() {
  44504. if (this._runner) {
  44505. return this._runner;
  44506. }
  44507. const factory = this._runnerFactory || createServerModuleRunner;
  44508. this._runner = factory(this, this._runnerOptions);
  44509. return this._runner;
  44510. }
  44511. async close() {
  44512. await super.close();
  44513. if (this._runner) {
  44514. await this._runner.close();
  44515. }
  44516. }
  44517. }
  44518. // NOTE: supports Node 6.x
  44519. const NOOP = () => {};
  44520. const MIMES = /text|javascript|\/json|xml/i;
  44521. /**
  44522. * @param {any} chunk
  44523. * @param {BufferEncoding} enc
  44524. * @returns {number}
  44525. */
  44526. function getChunkSize(chunk, enc) {
  44527. return chunk ? Buffer.byteLength(chunk, enc) : 0;
  44528. }
  44529. /**
  44530. * @param {import('./index.d.mts').Options} [options]
  44531. * @returns {import('./index.d.mts').Middleware}
  44532. */
  44533. function compression ({ threshold = 1024, level = -1, brotli = false, gzip = true, mimes = MIMES } = {}) {
  44534. const brotliOpts = (typeof brotli === 'object' && brotli) || {};
  44535. const gzipOpts = (typeof gzip === 'object' && gzip) || {};
  44536. // disable Brotli on Node<12.7 where it is unsupported:
  44537. if (!zlib$1.createBrotliCompress) brotli = false;
  44538. return (req, res, next = NOOP) => {
  44539. const accept = req.headers['accept-encoding'] + '';
  44540. const encoding = ((brotli && accept.match(/\bbr\b/)) || (gzip && accept.match(/\bgzip\b/)) || [])[0];
  44541. // skip if no response body or no supported encoding:
  44542. if (req.method === 'HEAD' || !encoding) return next();
  44543. /** @type {zlib.Gzip | zlib.BrotliCompress} */
  44544. let compress;
  44545. /** @type {Array<[string, function]>?} */
  44546. let pendingListeners = [];
  44547. let pendingStatus = 0;
  44548. let started = false;
  44549. let size = 0;
  44550. function start() {
  44551. started = true;
  44552. // @ts-ignore
  44553. size = res.getHeader('Content-Length') | 0 || size;
  44554. const compressible = mimes.test(
  44555. String(res.getHeader('Content-Type') || 'text/plain')
  44556. );
  44557. const cleartext = !res.getHeader('Content-Encoding');
  44558. const listeners = pendingListeners || [];
  44559. if (compressible && cleartext && size >= threshold) {
  44560. res.setHeader('Content-Encoding', encoding);
  44561. res.removeHeader('Content-Length');
  44562. if (encoding === 'br') {
  44563. compress = zlib$1.createBrotliCompress({
  44564. params: Object.assign({
  44565. [zlib$1.constants.BROTLI_PARAM_QUALITY]: level,
  44566. [zlib$1.constants.BROTLI_PARAM_SIZE_HINT]: size,
  44567. }, brotliOpts)
  44568. });
  44569. } else {
  44570. compress = zlib$1.createGzip(
  44571. Object.assign({ level }, gzipOpts)
  44572. );
  44573. }
  44574. // backpressure
  44575. compress.on('data', chunk => write.call(res, chunk) || compress.pause());
  44576. on.call(res, 'drain', () => compress.resume());
  44577. compress.on('end', () => end.call(res));
  44578. listeners.forEach(p => compress.on.apply(compress, p));
  44579. } else {
  44580. pendingListeners = null;
  44581. listeners.forEach(p => on.apply(res, p));
  44582. }
  44583. writeHead.call(res, pendingStatus || res.statusCode);
  44584. }
  44585. const { end, write, on, writeHead } = res;
  44586. res.writeHead = function (status, reason, headers) {
  44587. if (typeof reason !== 'string') [headers, reason] = [reason, headers];
  44588. if (headers) for (let k in headers) res.setHeader(k, headers[k]);
  44589. pendingStatus = status;
  44590. return this;
  44591. };
  44592. res.write = function (chunk, enc) {
  44593. size += getChunkSize(chunk, enc);
  44594. if (!started) start();
  44595. if (!compress) return write.apply(this, arguments);
  44596. return compress.write.apply(compress, arguments);
  44597. };
  44598. res.end = function (chunk, enc) {
  44599. if (arguments.length > 0 && typeof chunk !== 'function') {
  44600. size += getChunkSize(chunk, enc);
  44601. }
  44602. if (!started) start();
  44603. if (!compress) return end.apply(this, arguments);
  44604. return compress.end.apply(compress, arguments);
  44605. };
  44606. res.on = function (type, listener) {
  44607. if (!pendingListeners) on.call(this, type, listener);
  44608. else if (compress) compress.on(type, listener);
  44609. else pendingListeners.push([type, listener]);
  44610. return this;
  44611. };
  44612. next();
  44613. };
  44614. }
  44615. function resolvePreviewOptions(preview2, server) {
  44616. return {
  44617. port: preview2?.port ?? DEFAULT_PREVIEW_PORT,
  44618. strictPort: preview2?.strictPort ?? server.strictPort,
  44619. host: preview2?.host ?? server.host,
  44620. allowedHosts: preview2?.allowedHosts ?? server.allowedHosts,
  44621. https: preview2?.https ?? server.https,
  44622. open: preview2?.open ?? server.open,
  44623. proxy: preview2?.proxy ?? server.proxy,
  44624. cors: preview2?.cors ?? server.cors,
  44625. headers: preview2?.headers ?? server.headers
  44626. };
  44627. }
  44628. async function preview(inlineConfig = {}) {
  44629. const config = await resolveConfig(
  44630. inlineConfig,
  44631. "serve",
  44632. "production",
  44633. "production",
  44634. true
  44635. );
  44636. const clientOutDir = config.environments.client.build.outDir;
  44637. const distDir = path$b.resolve(config.root, clientOutDir);
  44638. if (!fs__default.existsSync(distDir) && // error if no plugins implement `configurePreviewServer`
  44639. config.plugins.every((plugin) => !plugin.configurePreviewServer) && // error if called in CLI only. programmatic usage could access `httpServer`
  44640. // and affect file serving
  44641. process.argv[1]?.endsWith(path$b.normalize("bin/vite.js")) && process.argv[2] === "preview") {
  44642. throw new Error(
  44643. `The directory "${clientOutDir}" does not exist. Did you build your project?`
  44644. );
  44645. }
  44646. const httpsOptions = await resolveHttpsConfig(config.preview.https);
  44647. const app = connect$1();
  44648. const httpServer = await resolveHttpServer(config.preview, app, httpsOptions);
  44649. setClientErrorHandler(httpServer, config.logger);
  44650. const options = config.preview;
  44651. const logger = config.logger;
  44652. const closeHttpServer = createServerCloseFn(httpServer);
  44653. let closeServerPromise;
  44654. const closeServer = async () => {
  44655. teardownSIGTERMListener(closeServerAndExit);
  44656. await closeHttpServer();
  44657. server.resolvedUrls = null;
  44658. };
  44659. const server = {
  44660. config,
  44661. middlewares: app,
  44662. httpServer,
  44663. async close() {
  44664. if (!closeServerPromise) {
  44665. closeServerPromise = closeServer();
  44666. }
  44667. return closeServerPromise;
  44668. },
  44669. resolvedUrls: null,
  44670. printUrls() {
  44671. if (server.resolvedUrls) {
  44672. printServerUrls(server.resolvedUrls, options.host, logger.info);
  44673. } else {
  44674. throw new Error("cannot print server URLs before server is listening.");
  44675. }
  44676. },
  44677. bindCLIShortcuts(options2) {
  44678. bindCLIShortcuts(server, options2);
  44679. }
  44680. };
  44681. const closeServerAndExit = async (_, exitCode) => {
  44682. try {
  44683. await server.close();
  44684. } finally {
  44685. process.exitCode ??= exitCode ? 128 + exitCode : void 0;
  44686. process.exit();
  44687. }
  44688. };
  44689. setupSIGTERMListener(closeServerAndExit);
  44690. const postHooks = [];
  44691. for (const hook of config.getSortedPluginHooks("configurePreviewServer")) {
  44692. postHooks.push(await hook(server));
  44693. }
  44694. const { cors } = config.preview;
  44695. if (cors !== false) {
  44696. app.use(corsMiddleware(typeof cors === "boolean" ? {} : cors));
  44697. }
  44698. const { allowedHosts } = config.preview;
  44699. if (allowedHosts !== true && !config.preview.https) {
  44700. app.use(hostCheckMiddleware(config, true));
  44701. }
  44702. const { proxy } = config.preview;
  44703. if (proxy) {
  44704. app.use(proxyMiddleware(httpServer, proxy, config));
  44705. }
  44706. app.use(compression());
  44707. if (config.base !== "/") {
  44708. app.use(baseMiddleware(config.rawBase, false));
  44709. }
  44710. const headers = config.preview.headers;
  44711. const viteAssetMiddleware = (...args) => sirv(distDir, {
  44712. etag: true,
  44713. dev: true,
  44714. extensions: [],
  44715. ignores: false,
  44716. setHeaders(res) {
  44717. if (headers) {
  44718. for (const name in headers) {
  44719. res.setHeader(name, headers[name]);
  44720. }
  44721. }
  44722. },
  44723. shouldServe(filePath) {
  44724. return shouldServeFile(filePath, distDir);
  44725. }
  44726. })(...args);
  44727. app.use(viteAssetMiddleware);
  44728. if (config.appType === "spa" || config.appType === "mpa") {
  44729. app.use(htmlFallbackMiddleware(distDir, config.appType === "spa"));
  44730. }
  44731. postHooks.forEach((fn) => fn && fn());
  44732. if (config.appType === "spa" || config.appType === "mpa") {
  44733. app.use(indexHtmlMiddleware(distDir, server));
  44734. app.use(notFoundMiddleware());
  44735. }
  44736. const hostname = await resolveHostname(options.host);
  44737. await httpServerStart(httpServer, {
  44738. port: options.port,
  44739. strictPort: options.strictPort,
  44740. host: hostname.host,
  44741. logger
  44742. });
  44743. server.resolvedUrls = await resolveServerUrls(
  44744. httpServer,
  44745. config.preview,
  44746. httpsOptions,
  44747. config
  44748. );
  44749. if (options.open) {
  44750. const url = getServerUrlByHost(server.resolvedUrls, options.host);
  44751. if (url) {
  44752. const path2 = typeof options.open === "string" ? new URL(options.open, url).href : url;
  44753. openBrowser(path2, true, logger);
  44754. }
  44755. }
  44756. return server;
  44757. }
  44758. var preview$1 = {
  44759. __proto__: null,
  44760. preview: preview,
  44761. resolvePreviewOptions: resolvePreviewOptions
  44762. };
  44763. const ssrConfigDefaults = Object.freeze({
  44764. // noExternal
  44765. // external
  44766. target: "node",
  44767. optimizeDeps: {}
  44768. // resolve
  44769. });
  44770. function resolveSSROptions(ssr, preserveSymlinks) {
  44771. const defaults = mergeWithDefaults(ssrConfigDefaults, {
  44772. optimizeDeps: { esbuildOptions: { preserveSymlinks } }
  44773. });
  44774. return mergeWithDefaults(defaults, ssr ?? {});
  44775. }
  44776. async function runnerImport(moduleId, inlineConfig) {
  44777. const isModuleSyncConditionEnabled = (await import('#module-sync-enabled')).default;
  44778. const config = await resolveConfig(
  44779. mergeConfig(inlineConfig || {}, {
  44780. configFile: false,
  44781. envDir: false,
  44782. cacheDir: process.cwd(),
  44783. environments: {
  44784. inline: {
  44785. consumer: "server",
  44786. dev: {
  44787. moduleRunnerTransform: true
  44788. },
  44789. resolve: {
  44790. external: true,
  44791. mainFields: [],
  44792. conditions: [
  44793. "node",
  44794. ...isModuleSyncConditionEnabled ? ["module-sync"] : []
  44795. ]
  44796. }
  44797. }
  44798. }
  44799. }),
  44800. "serve"
  44801. );
  44802. const environment = createRunnableDevEnvironment("inline", config, {
  44803. runnerOptions: {
  44804. hmr: {
  44805. logger: false
  44806. }
  44807. },
  44808. hot: false
  44809. });
  44810. await environment.init();
  44811. try {
  44812. const module = await environment.runner.import(moduleId);
  44813. const modules = [
  44814. ...environment.runner.evaluatedModules.urlToIdModuleMap.values()
  44815. ];
  44816. const dependencies = modules.filter((m) => {
  44817. if (!m.meta || "externalize" in m.meta) {
  44818. return false;
  44819. }
  44820. return m.exports !== module;
  44821. }).map((m) => m.file);
  44822. return {
  44823. module,
  44824. dependencies
  44825. };
  44826. } finally {
  44827. await environment.close();
  44828. }
  44829. }
  44830. const debug = createDebugger("vite:config", { depth: 10 });
  44831. const promisifiedRealpath = promisify$4(fs__default.realpath);
  44832. function defineConfig(config) {
  44833. return config;
  44834. }
  44835. function defaultCreateClientDevEnvironment(name, config, context) {
  44836. return new DevEnvironment(name, config, {
  44837. hot: true,
  44838. transport: context.ws
  44839. });
  44840. }
  44841. function defaultCreateDevEnvironment(name, config) {
  44842. return createRunnableDevEnvironment(name, config);
  44843. }
  44844. const configDefaults = Object.freeze({
  44845. define: {},
  44846. dev: {
  44847. warmup: [],
  44848. // preTransformRequests
  44849. /** @experimental */
  44850. sourcemap: { js: true },
  44851. sourcemapIgnoreList: void 0
  44852. // createEnvironment
  44853. // recoverable
  44854. // moduleRunnerTransform
  44855. },
  44856. build: buildEnvironmentOptionsDefaults,
  44857. resolve: {
  44858. // mainFields
  44859. // conditions
  44860. externalConditions: ["node"],
  44861. extensions: [".mjs", ".js", ".mts", ".ts", ".jsx", ".tsx", ".json"],
  44862. dedupe: [],
  44863. /** @experimental */
  44864. noExternal: [],
  44865. external: [],
  44866. preserveSymlinks: false,
  44867. alias: []
  44868. },
  44869. // root
  44870. base: "/",
  44871. publicDir: "public",
  44872. // cacheDir
  44873. // mode
  44874. plugins: [],
  44875. html: {
  44876. cspNonce: void 0
  44877. },
  44878. css: cssConfigDefaults,
  44879. json: {
  44880. namedExports: true,
  44881. stringify: "auto"
  44882. },
  44883. // esbuild
  44884. assetsInclude: void 0,
  44885. /** @experimental */
  44886. builder: builderOptionsDefaults,
  44887. server: serverConfigDefaults,
  44888. preview: {
  44889. port: DEFAULT_PREVIEW_PORT
  44890. // strictPort
  44891. // host
  44892. // https
  44893. // open
  44894. // proxy
  44895. // cors
  44896. // headers
  44897. },
  44898. /** @experimental */
  44899. experimental: {
  44900. importGlobRestoreExtension: false,
  44901. renderBuiltUrl: void 0,
  44902. hmrPartialAccept: false,
  44903. skipSsrTransform: false
  44904. },
  44905. future: {
  44906. removePluginHookHandleHotUpdate: void 0,
  44907. removePluginHookSsrArgument: void 0,
  44908. removeServerModuleGraph: void 0,
  44909. removeServerHot: void 0,
  44910. removeServerTransformRequest: void 0,
  44911. removeSsrLoadModule: void 0
  44912. },
  44913. legacy: {
  44914. proxySsrExternalModules: false,
  44915. skipWebSocketTokenCheck: false
  44916. },
  44917. logLevel: "info",
  44918. customLogger: void 0,
  44919. clearScreen: true,
  44920. envDir: void 0,
  44921. envPrefix: "VITE_",
  44922. worker: {
  44923. format: "iife",
  44924. plugins: () => []
  44925. // rollupOptions
  44926. },
  44927. optimizeDeps: {
  44928. include: [],
  44929. exclude: [],
  44930. needsInterop: [],
  44931. // esbuildOptions
  44932. /** @experimental */
  44933. extensions: [],
  44934. /** @deprecated @experimental */
  44935. disabled: "build",
  44936. // noDiscovery
  44937. /** @experimental */
  44938. holdUntilCrawlEnd: true,
  44939. // entries
  44940. /** @experimental */
  44941. force: false
  44942. },
  44943. ssr: ssrConfigDefaults,
  44944. environments: {},
  44945. appType: "spa"
  44946. });
  44947. function resolveDevEnvironmentOptions(dev, environmentName, consumer, skipSsrTransform, preTransformRequest) {
  44948. const resolved = mergeWithDefaults(
  44949. {
  44950. ...configDefaults.dev,
  44951. sourcemapIgnoreList: isInNodeModules$1,
  44952. preTransformRequests: preTransformRequest ?? consumer === "client",
  44953. createEnvironment: environmentName === "client" ? defaultCreateClientDevEnvironment : defaultCreateDevEnvironment,
  44954. recoverable: consumer === "client",
  44955. moduleRunnerTransform: skipSsrTransform !== void 0 && consumer === "server" ? skipSsrTransform : consumer === "server"
  44956. },
  44957. dev ?? {}
  44958. );
  44959. return {
  44960. ...resolved,
  44961. sourcemapIgnoreList: resolved.sourcemapIgnoreList === false ? () => false : resolved.sourcemapIgnoreList
  44962. };
  44963. }
  44964. function resolveEnvironmentOptions(options, alias, preserveSymlinks, forceOptimizeDeps, logger, environmentName, skipSsrTransform, isSsrTargetWebworkerSet, preTransformRequests) {
  44965. const isClientEnvironment = environmentName === "client";
  44966. const consumer = options.consumer ?? (isClientEnvironment ? "client" : "server");
  44967. const isSsrTargetWebworkerEnvironment = isSsrTargetWebworkerSet && environmentName === "ssr";
  44968. if (options.define?.["process.env"]) {
  44969. const processEnvDefine = options.define["process.env"];
  44970. if (typeof processEnvDefine === "object") {
  44971. const pathKey = Object.entries(processEnvDefine).find(
  44972. // check with toLowerCase() to match with `Path` / `PATH` (Windows uses `Path`)
  44973. ([key, value]) => key.toLowerCase() === "path" && !!value
  44974. )?.[0];
  44975. if (pathKey) {
  44976. logger.warnOnce(
  44977. colors$1.yellow(
  44978. `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.`
  44979. )
  44980. );
  44981. }
  44982. }
  44983. }
  44984. const resolve = resolveEnvironmentResolveOptions(
  44985. options.resolve,
  44986. alias,
  44987. preserveSymlinks,
  44988. logger,
  44989. consumer,
  44990. isSsrTargetWebworkerEnvironment
  44991. );
  44992. return {
  44993. define: options.define,
  44994. resolve,
  44995. keepProcessEnv: options.keepProcessEnv ?? (isSsrTargetWebworkerEnvironment ? false : consumer === "server"),
  44996. consumer,
  44997. optimizeDeps: resolveDepOptimizationOptions(
  44998. options.optimizeDeps,
  44999. resolve.preserveSymlinks,
  45000. forceOptimizeDeps,
  45001. consumer
  45002. ),
  45003. dev: resolveDevEnvironmentOptions(
  45004. options.dev,
  45005. environmentName,
  45006. consumer,
  45007. skipSsrTransform,
  45008. preTransformRequests
  45009. ),
  45010. build: resolveBuildEnvironmentOptions(
  45011. options.build ?? {},
  45012. logger,
  45013. consumer
  45014. )
  45015. };
  45016. }
  45017. function getDefaultEnvironmentOptions(config) {
  45018. return {
  45019. define: config.define,
  45020. resolve: {
  45021. ...config.resolve,
  45022. // mainFields and conditions are not inherited
  45023. mainFields: void 0,
  45024. conditions: void 0
  45025. },
  45026. dev: config.dev,
  45027. build: config.build
  45028. };
  45029. }
  45030. function checkBadCharactersInPath(name, path2, logger) {
  45031. const badChars = [];
  45032. if (path2.includes("#")) {
  45033. badChars.push("#");
  45034. }
  45035. if (path2.includes("?")) {
  45036. badChars.push("?");
  45037. }
  45038. if (path2.includes("*")) {
  45039. badChars.push("*");
  45040. }
  45041. if (badChars.length > 0) {
  45042. const charString = badChars.map((c) => `"${c}"`).join(" and ");
  45043. const inflectedChars = badChars.length > 1 ? "characters" : "character";
  45044. logger.warn(
  45045. colors$1.yellow(
  45046. `${name} contains the ${charString} ${inflectedChars} (${colors$1.cyan(
  45047. path2
  45048. )}), which may not work when running Vite. Consider renaming the directory / file to remove the characters.`
  45049. )
  45050. );
  45051. }
  45052. }
  45053. const clientAlias = [
  45054. {
  45055. find: /^\/?@vite\/env/,
  45056. replacement: path$b.posix.join(FS_PREFIX, normalizePath$3(ENV_ENTRY))
  45057. },
  45058. {
  45059. find: /^\/?@vite\/client/,
  45060. replacement: path$b.posix.join(FS_PREFIX, normalizePath$3(CLIENT_ENTRY))
  45061. }
  45062. ];
  45063. function resolveEnvironmentResolveOptions(resolve, alias, preserveSymlinks, logger, consumer, isSsrTargetWebworkerEnvironment) {
  45064. const resolvedResolve = mergeWithDefaults(
  45065. {
  45066. ...configDefaults.resolve,
  45067. mainFields: consumer === void 0 || consumer === "client" || isSsrTargetWebworkerEnvironment ? DEFAULT_CLIENT_MAIN_FIELDS : DEFAULT_SERVER_MAIN_FIELDS,
  45068. conditions: consumer === void 0 || consumer === "client" || isSsrTargetWebworkerEnvironment ? DEFAULT_CLIENT_CONDITIONS : DEFAULT_SERVER_CONDITIONS.filter((c) => c !== "browser"),
  45069. builtins: resolve?.builtins ?? (consumer === "server" ? isSsrTargetWebworkerEnvironment && resolve?.noExternal === true ? [] : nodeLikeBuiltins : [])
  45070. },
  45071. resolve ?? {}
  45072. );
  45073. resolvedResolve.preserveSymlinks = preserveSymlinks;
  45074. resolvedResolve.alias = alias;
  45075. if (
  45076. // @ts-expect-error removed field
  45077. resolve?.browserField === false && resolvedResolve.mainFields.includes("browser")
  45078. ) {
  45079. logger.warn(
  45080. colors$1.yellow(
  45081. `\`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.`
  45082. )
  45083. );
  45084. }
  45085. return resolvedResolve;
  45086. }
  45087. function resolveResolveOptions(resolve, logger) {
  45088. const alias = normalizeAlias(
  45089. mergeAlias(clientAlias, resolve?.alias || configDefaults.resolve.alias)
  45090. );
  45091. const preserveSymlinks = resolve?.preserveSymlinks ?? configDefaults.resolve.preserveSymlinks;
  45092. if (alias.some((a) => a.find === "/")) {
  45093. logger.warn(
  45094. colors$1.yellow(
  45095. `\`resolve.alias\` contains an alias that maps \`/\`. This is not recommended as it can cause unexpected behavior when resolving paths.`
  45096. )
  45097. );
  45098. }
  45099. return resolveEnvironmentResolveOptions(
  45100. resolve,
  45101. alias,
  45102. preserveSymlinks,
  45103. logger,
  45104. void 0
  45105. );
  45106. }
  45107. function resolveDepOptimizationOptions(optimizeDeps, preserveSymlinks, forceOptimizeDeps, consumer) {
  45108. return mergeWithDefaults(
  45109. {
  45110. ...configDefaults.optimizeDeps,
  45111. disabled: void 0,
  45112. // do not set here to avoid deprecation warning
  45113. noDiscovery: consumer !== "client",
  45114. esbuildOptions: {
  45115. preserveSymlinks
  45116. },
  45117. force: forceOptimizeDeps ?? configDefaults.optimizeDeps.force
  45118. },
  45119. optimizeDeps ?? {}
  45120. );
  45121. }
  45122. async function resolveConfig(inlineConfig, command, defaultMode = "development", defaultNodeEnv = "development", isPreview = false, patchConfig = void 0, patchPlugins = void 0) {
  45123. let config = inlineConfig;
  45124. let configFileDependencies = [];
  45125. let mode = inlineConfig.mode || defaultMode;
  45126. const isNodeEnvSet = !!process.env.NODE_ENV;
  45127. const packageCache = /* @__PURE__ */ new Map();
  45128. if (!isNodeEnvSet) {
  45129. process.env.NODE_ENV = defaultNodeEnv;
  45130. }
  45131. const configEnv = {
  45132. mode,
  45133. command,
  45134. isSsrBuild: command === "build" && !!config.build?.ssr,
  45135. isPreview
  45136. };
  45137. let { configFile } = config;
  45138. if (configFile !== false) {
  45139. const loadResult = await loadConfigFromFile(
  45140. configEnv,
  45141. configFile,
  45142. config.root,
  45143. config.logLevel,
  45144. config.customLogger,
  45145. config.configLoader
  45146. );
  45147. if (loadResult) {
  45148. config = mergeConfig(loadResult.config, config);
  45149. configFile = loadResult.path;
  45150. configFileDependencies = loadResult.dependencies;
  45151. }
  45152. }
  45153. mode = inlineConfig.mode || config.mode || mode;
  45154. configEnv.mode = mode;
  45155. const filterPlugin = (p) => {
  45156. if (!p) {
  45157. return false;
  45158. } else if (!p.apply) {
  45159. return true;
  45160. } else if (typeof p.apply === "function") {
  45161. return p.apply({ ...config, mode }, configEnv);
  45162. } else {
  45163. return p.apply === command;
  45164. }
  45165. };
  45166. const rawPlugins = (await asyncFlatten(config.plugins || [])).filter(
  45167. filterPlugin
  45168. );
  45169. const [prePlugins, normalPlugins, postPlugins] = sortUserPlugins(rawPlugins);
  45170. const isBuild = command === "build";
  45171. const userPlugins = [...prePlugins, ...normalPlugins, ...postPlugins];
  45172. config = await runConfigHook(config, userPlugins, configEnv);
  45173. config.environments ??= {};
  45174. if (!config.environments.ssr && (!isBuild || config.ssr || config.build?.ssr)) {
  45175. config.environments = { ssr: {}, ...config.environments };
  45176. }
  45177. if (!config.environments.client) {
  45178. config.environments = { client: {}, ...config.environments };
  45179. }
  45180. const logger = createLogger(config.logLevel, {
  45181. allowClearScreen: config.clearScreen,
  45182. customLogger: config.customLogger
  45183. });
  45184. const resolvedRoot = normalizePath$3(
  45185. config.root ? path$b.resolve(config.root) : process.cwd()
  45186. );
  45187. checkBadCharactersInPath("The project root", resolvedRoot, logger);
  45188. const configEnvironmentsClient = config.environments.client;
  45189. configEnvironmentsClient.dev ??= {};
  45190. const deprecatedSsrOptimizeDepsConfig = config.ssr?.optimizeDeps ?? {};
  45191. let configEnvironmentsSsr = config.environments.ssr;
  45192. const warmupOptions = config.server?.warmup;
  45193. if (warmupOptions?.clientFiles) {
  45194. configEnvironmentsClient.dev.warmup = warmupOptions.clientFiles;
  45195. }
  45196. if (warmupOptions?.ssrFiles) {
  45197. configEnvironmentsSsr ??= {};
  45198. configEnvironmentsSsr.dev ??= {};
  45199. configEnvironmentsSsr.dev.warmup = warmupOptions.ssrFiles;
  45200. }
  45201. if (configEnvironmentsSsr) {
  45202. configEnvironmentsSsr.optimizeDeps = mergeConfig(
  45203. deprecatedSsrOptimizeDepsConfig,
  45204. configEnvironmentsSsr.optimizeDeps ?? {}
  45205. );
  45206. configEnvironmentsSsr.resolve = mergeConfig(
  45207. {
  45208. conditions: config.ssr?.resolve?.conditions,
  45209. externalConditions: config.ssr?.resolve?.externalConditions,
  45210. mainFields: config.ssr?.resolve?.mainFields,
  45211. external: config.ssr?.external,
  45212. noExternal: config.ssr?.noExternal
  45213. },
  45214. configEnvironmentsSsr.resolve ?? {}
  45215. );
  45216. }
  45217. if (config.build?.ssrEmitAssets !== void 0) {
  45218. configEnvironmentsSsr ??= {};
  45219. configEnvironmentsSsr.build ??= {};
  45220. configEnvironmentsSsr.build.emitAssets = config.build.ssrEmitAssets;
  45221. }
  45222. if (!config.environments.client || !config.environments.ssr && !isBuild) {
  45223. throw new Error(
  45224. "Required environments configuration were stripped out in the config hook"
  45225. );
  45226. }
  45227. const defaultEnvironmentOptions = getDefaultEnvironmentOptions(config);
  45228. const defaultClientEnvironmentOptions = {
  45229. ...defaultEnvironmentOptions,
  45230. resolve: config.resolve,
  45231. // inherit everything including mainFields and conditions
  45232. optimizeDeps: config.optimizeDeps
  45233. };
  45234. const defaultNonClientEnvironmentOptions = {
  45235. ...defaultEnvironmentOptions,
  45236. dev: {
  45237. ...defaultEnvironmentOptions.dev,
  45238. createEnvironment: void 0,
  45239. warmup: void 0
  45240. },
  45241. build: {
  45242. ...defaultEnvironmentOptions.build,
  45243. createEnvironment: void 0
  45244. }
  45245. };
  45246. for (const name of Object.keys(config.environments)) {
  45247. config.environments[name] = mergeConfig(
  45248. name === "client" ? defaultClientEnvironmentOptions : defaultNonClientEnvironmentOptions,
  45249. config.environments[name]
  45250. );
  45251. }
  45252. await runConfigEnvironmentHook(
  45253. config.environments,
  45254. userPlugins,
  45255. configEnv,
  45256. config.ssr?.target === "webworker"
  45257. );
  45258. config.resolve ??= {};
  45259. config.resolve.conditions = config.environments.client.resolve?.conditions;
  45260. config.resolve.mainFields = config.environments.client.resolve?.mainFields;
  45261. const resolvedDefaultResolve = resolveResolveOptions(config.resolve, logger);
  45262. const resolvedEnvironments = {};
  45263. for (const environmentName of Object.keys(config.environments)) {
  45264. resolvedEnvironments[environmentName] = resolveEnvironmentOptions(
  45265. config.environments[environmentName],
  45266. resolvedDefaultResolve.alias,
  45267. resolvedDefaultResolve.preserveSymlinks,
  45268. inlineConfig.forceOptimizeDeps,
  45269. logger,
  45270. environmentName,
  45271. config.experimental?.skipSsrTransform,
  45272. config.ssr?.target === "webworker",
  45273. config.server?.preTransformRequests
  45274. );
  45275. }
  45276. const backwardCompatibleOptimizeDeps = resolvedEnvironments.client.optimizeDeps;
  45277. const resolvedDevEnvironmentOptions = resolveDevEnvironmentOptions(
  45278. config.dev,
  45279. // default environment options
  45280. void 0,
  45281. void 0
  45282. );
  45283. const resolvedBuildOptions = resolveBuildEnvironmentOptions(
  45284. config.build ?? {},
  45285. logger,
  45286. void 0
  45287. );
  45288. const patchedConfigSsr = {
  45289. ...config.ssr,
  45290. external: resolvedEnvironments.ssr?.resolve.external,
  45291. noExternal: resolvedEnvironments.ssr?.resolve.noExternal,
  45292. optimizeDeps: resolvedEnvironments.ssr?.optimizeDeps,
  45293. resolve: {
  45294. ...config.ssr?.resolve,
  45295. conditions: resolvedEnvironments.ssr?.resolve.conditions,
  45296. externalConditions: resolvedEnvironments.ssr?.resolve.externalConditions
  45297. }
  45298. };
  45299. const ssr = resolveSSROptions(
  45300. patchedConfigSsr,
  45301. resolvedDefaultResolve.preserveSymlinks
  45302. );
  45303. let envDir = config.envFile === false ? false : config.envDir;
  45304. if (envDir !== false) {
  45305. envDir = config.envDir ? normalizePath$3(path$b.resolve(resolvedRoot, config.envDir)) : resolvedRoot;
  45306. }
  45307. const userEnv = loadEnv(mode, envDir, resolveEnvPrefix(config));
  45308. const userNodeEnv = process.env.VITE_USER_NODE_ENV;
  45309. if (!isNodeEnvSet && userNodeEnv) {
  45310. if (userNodeEnv === "development") {
  45311. process.env.NODE_ENV = "development";
  45312. } else {
  45313. logger.warn(
  45314. `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.`
  45315. );
  45316. }
  45317. }
  45318. const isProduction = process.env.NODE_ENV === "production";
  45319. const relativeBaseShortcut = config.base === "" || config.base === "./";
  45320. const resolvedBase = relativeBaseShortcut ? !isBuild || config.build?.ssr ? "/" : "./" : resolveBaseUrl(config.base, isBuild, logger);
  45321. const pkgDir = findNearestPackageData(resolvedRoot, packageCache)?.dir;
  45322. const cacheDir = normalizePath$3(
  45323. config.cacheDir ? path$b.resolve(resolvedRoot, config.cacheDir) : pkgDir ? path$b.join(pkgDir, `node_modules/.vite`) : path$b.join(resolvedRoot, `.vite`)
  45324. );
  45325. const assetsFilter = config.assetsInclude && (!Array.isArray(config.assetsInclude) || config.assetsInclude.length) ? createFilter$1(config.assetsInclude) : () => false;
  45326. const { publicDir } = config;
  45327. const resolvedPublicDir = publicDir !== false && publicDir !== "" ? normalizePath$3(
  45328. path$b.resolve(
  45329. resolvedRoot,
  45330. typeof publicDir === "string" ? publicDir : configDefaults.publicDir
  45331. )
  45332. ) : "";
  45333. const server = resolveServerOptions(resolvedRoot, config.server, logger);
  45334. const builder = resolveBuilderOptions(config.builder);
  45335. const BASE_URL = resolvedBase;
  45336. let resolved;
  45337. let createUserWorkerPlugins = config.worker?.plugins;
  45338. if (Array.isArray(createUserWorkerPlugins)) {
  45339. createUserWorkerPlugins = () => config.worker?.plugins;
  45340. logger.warn(
  45341. colors$1.yellow(
  45342. `worker.plugins is now a function that returns an array of plugins. Please update your Vite config accordingly.
  45343. `
  45344. )
  45345. );
  45346. }
  45347. const createWorkerPlugins = async function(bundleChain) {
  45348. const rawWorkerUserPlugins = (await asyncFlatten(createUserWorkerPlugins?.() || [])).filter(filterPlugin);
  45349. let workerConfig = mergeConfig({}, config);
  45350. const [workerPrePlugins, workerNormalPlugins, workerPostPlugins] = sortUserPlugins(rawWorkerUserPlugins);
  45351. const workerUserPlugins = [
  45352. ...workerPrePlugins,
  45353. ...workerNormalPlugins,
  45354. ...workerPostPlugins
  45355. ];
  45356. workerConfig = await runConfigHook(
  45357. workerConfig,
  45358. workerUserPlugins,
  45359. configEnv
  45360. );
  45361. const workerResolved = {
  45362. ...workerConfig,
  45363. ...resolved,
  45364. isWorker: true,
  45365. mainConfig: resolved,
  45366. bundleChain
  45367. };
  45368. const resolvedWorkerPlugins = await resolvePlugins(
  45369. workerResolved,
  45370. workerPrePlugins,
  45371. workerNormalPlugins,
  45372. workerPostPlugins
  45373. );
  45374. await Promise.all(
  45375. createPluginHookUtils(resolvedWorkerPlugins).getSortedPluginHooks("configResolved").map((hook) => hook(workerResolved))
  45376. );
  45377. return {
  45378. ...workerResolved,
  45379. plugins: resolvedWorkerPlugins
  45380. };
  45381. };
  45382. const resolvedWorkerOptions = {
  45383. format: config.worker?.format || "iife",
  45384. plugins: createWorkerPlugins,
  45385. rollupOptions: config.worker?.rollupOptions || {}
  45386. };
  45387. const base = withTrailingSlash(resolvedBase);
  45388. const preview = resolvePreviewOptions(config.preview, server);
  45389. resolved = {
  45390. configFile: configFile ? normalizePath$3(configFile) : void 0,
  45391. configFileDependencies: configFileDependencies.map(
  45392. (name) => normalizePath$3(path$b.resolve(name))
  45393. ),
  45394. inlineConfig,
  45395. root: resolvedRoot,
  45396. base,
  45397. decodedBase: decodeBase(base),
  45398. rawBase: resolvedBase,
  45399. publicDir: resolvedPublicDir,
  45400. cacheDir,
  45401. command,
  45402. mode,
  45403. isWorker: false,
  45404. mainConfig: null,
  45405. bundleChain: [],
  45406. isProduction,
  45407. plugins: userPlugins,
  45408. // placeholder to be replaced
  45409. css: resolveCSSOptions(config.css),
  45410. json: mergeWithDefaults(configDefaults.json, config.json ?? {}),
  45411. esbuild: config.esbuild === false ? false : {
  45412. jsxDev: !isProduction,
  45413. ...config.esbuild
  45414. },
  45415. server,
  45416. builder,
  45417. preview,
  45418. envDir,
  45419. env: {
  45420. ...userEnv,
  45421. BASE_URL,
  45422. MODE: mode,
  45423. DEV: !isProduction,
  45424. PROD: isProduction
  45425. },
  45426. assetsInclude(file) {
  45427. return DEFAULT_ASSETS_RE.test(file) || assetsFilter(file);
  45428. },
  45429. logger,
  45430. packageCache,
  45431. worker: resolvedWorkerOptions,
  45432. appType: config.appType ?? "spa",
  45433. experimental: {
  45434. importGlobRestoreExtension: false,
  45435. hmrPartialAccept: false,
  45436. ...config.experimental
  45437. },
  45438. future: config.future,
  45439. ssr,
  45440. optimizeDeps: backwardCompatibleOptimizeDeps,
  45441. resolve: resolvedDefaultResolve,
  45442. dev: resolvedDevEnvironmentOptions,
  45443. build: resolvedBuildOptions,
  45444. environments: resolvedEnvironments,
  45445. // random 72 bits (12 base64 chars)
  45446. // at least 64bits is recommended
  45447. // https://owasp.org/www-community/vulnerabilities/Insufficient_Session-ID_Length
  45448. webSocketToken: Buffer.from(
  45449. crypto$2.getRandomValues(new Uint8Array(9))
  45450. ).toString("base64url"),
  45451. getSortedPlugins: void 0,
  45452. getSortedPluginHooks: void 0,
  45453. /**
  45454. * createResolver is deprecated. It only works for the client and ssr
  45455. * environments. The `aliasOnly` option is also not being used any more
  45456. * Plugins should move to createIdResolver(environment) instead.
  45457. * create an internal resolver to be used in special scenarios, e.g.
  45458. * optimizer & handling css @imports
  45459. */
  45460. createResolver(options) {
  45461. const resolve = createIdResolver(this, options);
  45462. const clientEnvironment = new PartialEnvironment("client", this);
  45463. let ssrEnvironment;
  45464. return async (id, importer, aliasOnly, ssr2) => {
  45465. if (ssr2) {
  45466. ssrEnvironment ??= new PartialEnvironment("ssr", this);
  45467. }
  45468. return await resolve(
  45469. ssr2 ? ssrEnvironment : clientEnvironment,
  45470. id,
  45471. importer,
  45472. aliasOnly
  45473. );
  45474. };
  45475. },
  45476. fsDenyGlob: picomatch$2(
  45477. // matchBase: true does not work as it's documented
  45478. // https://github.com/micromatch/picomatch/issues/89
  45479. // convert patterns without `/` on our side for now
  45480. server.fs.deny.map(
  45481. (pattern) => pattern.includes("/") ? pattern : `**/${pattern}`
  45482. ),
  45483. {
  45484. matchBase: false,
  45485. nocase: true,
  45486. dot: true
  45487. }
  45488. ),
  45489. safeModulePaths: /* @__PURE__ */ new Set(),
  45490. additionalAllowedHosts: getAdditionalAllowedHosts(server, preview)
  45491. };
  45492. resolved = {
  45493. ...config,
  45494. ...resolved
  45495. };
  45496. patchConfig?.(resolved);
  45497. const resolvedPlugins = await resolvePlugins(
  45498. resolved,
  45499. prePlugins,
  45500. normalPlugins,
  45501. postPlugins
  45502. );
  45503. patchPlugins?.(resolvedPlugins);
  45504. resolved.plugins = resolvedPlugins;
  45505. Object.assign(resolved, createPluginHookUtils(resolved.plugins));
  45506. await Promise.all(
  45507. resolved.getSortedPluginHooks("configResolved").map((hook) => hook(resolved))
  45508. );
  45509. optimizeDepsDisabledBackwardCompatibility(resolved, resolved.optimizeDeps);
  45510. optimizeDepsDisabledBackwardCompatibility(
  45511. resolved,
  45512. resolved.ssr.optimizeDeps,
  45513. "ssr."
  45514. );
  45515. if (resolved.environments.ssr) {
  45516. resolved.environments.ssr.build.emitAssets = resolved.build.ssrEmitAssets || resolved.build.emitAssets;
  45517. }
  45518. debug?.(`using resolved config: %O`, {
  45519. ...resolved,
  45520. plugins: resolved.plugins.map((p) => p.name),
  45521. worker: {
  45522. ...resolved.worker,
  45523. plugins: `() => plugins`
  45524. }
  45525. });
  45526. const outputOption = config.build?.rollupOptions?.output ?? [];
  45527. if (Array.isArray(outputOption)) {
  45528. const assetFileNamesList = outputOption.map(
  45529. (output) => output.assetFileNames
  45530. );
  45531. if (assetFileNamesList.length > 1) {
  45532. const firstAssetFileNames = assetFileNamesList[0];
  45533. const hasDifferentReference = assetFileNamesList.some(
  45534. (assetFileNames) => assetFileNames !== firstAssetFileNames
  45535. );
  45536. if (hasDifferentReference) {
  45537. resolved.logger.warn(
  45538. colors$1.yellow(`
  45539. assetFileNames isn't equal for every build.rollupOptions.output. A single pattern across all outputs is supported by Vite.
  45540. `)
  45541. );
  45542. }
  45543. }
  45544. }
  45545. if (
  45546. // @ts-expect-error Option removed
  45547. config.legacy?.buildSsrCjsExternalHeuristics || // @ts-expect-error Option removed
  45548. config.ssr?.format === "cjs"
  45549. ) {
  45550. resolved.logger.warn(
  45551. colors$1.yellow(`
  45552. (!) Experimental legacy.buildSsrCjsExternalHeuristics and ssr.format were be removed in Vite 5.
  45553. The only SSR Output format is ESM. Find more information at https://github.com/vitejs/vite/discussions/13816.
  45554. `)
  45555. );
  45556. }
  45557. const resolvedBuildOutDir = normalizePath$3(
  45558. path$b.resolve(resolved.root, resolved.build.outDir)
  45559. );
  45560. if (isParentDirectory(resolvedBuildOutDir, resolved.root) || resolvedBuildOutDir === resolved.root) {
  45561. resolved.logger.warn(
  45562. colors$1.yellow(`
  45563. (!) 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.
  45564. `)
  45565. );
  45566. }
  45567. return resolved;
  45568. }
  45569. function resolveBaseUrl(base = configDefaults.base, isBuild, logger) {
  45570. if (base[0] === ".") {
  45571. logger.warn(
  45572. colors$1.yellow(
  45573. colors$1.bold(
  45574. `(!) invalid "base" option: "${base}". The value can only be an absolute URL, "./", or an empty string.`
  45575. )
  45576. )
  45577. );
  45578. return "/";
  45579. }
  45580. const isExternal = isExternalUrl(base);
  45581. if (!isExternal && base[0] !== "/") {
  45582. logger.warn(
  45583. colors$1.yellow(
  45584. colors$1.bold(`(!) "base" option should start with a slash.`)
  45585. )
  45586. );
  45587. }
  45588. if (!isBuild || !isExternal) {
  45589. base = new URL(base, "http://vite.dev").pathname;
  45590. if (base[0] !== "/") {
  45591. base = "/" + base;
  45592. }
  45593. }
  45594. return base;
  45595. }
  45596. function decodeBase(base) {
  45597. try {
  45598. return decodeURI(base);
  45599. } catch {
  45600. throw new Error(
  45601. 'The value passed to "base" option was malformed. It should be a valid URL.'
  45602. );
  45603. }
  45604. }
  45605. function sortUserPlugins(plugins) {
  45606. const prePlugins = [];
  45607. const postPlugins = [];
  45608. const normalPlugins = [];
  45609. if (plugins) {
  45610. plugins.flat().forEach((p) => {
  45611. if (p.enforce === "pre") prePlugins.push(p);
  45612. else if (p.enforce === "post") postPlugins.push(p);
  45613. else normalPlugins.push(p);
  45614. });
  45615. }
  45616. return [prePlugins, normalPlugins, postPlugins];
  45617. }
  45618. async function loadConfigFromFile(configEnv, configFile, configRoot = process.cwd(), logLevel, customLogger, configLoader = "bundle") {
  45619. if (configLoader !== "bundle" && configLoader !== "runner" && configLoader !== "native") {
  45620. throw new Error(
  45621. `Unsupported configLoader: ${configLoader}. Accepted values are 'bundle', 'runner', and 'native'.`
  45622. );
  45623. }
  45624. const start = performance$1.now();
  45625. const getTime = () => `${(performance$1.now() - start).toFixed(2)}ms`;
  45626. let resolvedPath;
  45627. if (configFile) {
  45628. resolvedPath = path$b.resolve(configFile);
  45629. } else {
  45630. for (const filename of DEFAULT_CONFIG_FILES) {
  45631. const filePath = path$b.resolve(configRoot, filename);
  45632. if (!fs__default.existsSync(filePath)) continue;
  45633. resolvedPath = filePath;
  45634. break;
  45635. }
  45636. }
  45637. if (!resolvedPath) {
  45638. debug?.("no config file found.");
  45639. return null;
  45640. }
  45641. try {
  45642. const resolver = configLoader === "bundle" ? bundleAndLoadConfigFile : configLoader === "runner" ? runnerImportConfigFile : nativeImportConfigFile;
  45643. const { configExport, dependencies } = await resolver(resolvedPath);
  45644. debug?.(`config file loaded in ${getTime()}`);
  45645. const config = await (typeof configExport === "function" ? configExport(configEnv) : configExport);
  45646. if (!isObject$1(config)) {
  45647. throw new Error(`config must export or return an object.`);
  45648. }
  45649. return {
  45650. path: normalizePath$3(resolvedPath),
  45651. config,
  45652. dependencies
  45653. };
  45654. } catch (e) {
  45655. const logger = createLogger(logLevel, { customLogger });
  45656. checkBadCharactersInPath("The config path", resolvedPath, logger);
  45657. logger.error(colors$1.red(`failed to load config from ${resolvedPath}`), {
  45658. error: e
  45659. });
  45660. throw e;
  45661. }
  45662. }
  45663. async function nativeImportConfigFile(resolvedPath) {
  45664. const module = await import(pathToFileURL$1(resolvedPath).href + "?t=" + Date.now());
  45665. return {
  45666. configExport: module.default,
  45667. dependencies: []
  45668. };
  45669. }
  45670. async function runnerImportConfigFile(resolvedPath) {
  45671. const { module, dependencies } = await runnerImport(resolvedPath);
  45672. return {
  45673. configExport: module.default,
  45674. dependencies
  45675. };
  45676. }
  45677. async function bundleAndLoadConfigFile(resolvedPath) {
  45678. const isESM = typeof process.versions.deno === "string" || isFilePathESM(resolvedPath);
  45679. const bundled = await bundleConfigFile(resolvedPath, isESM);
  45680. const userConfig = await loadConfigFromBundledFile(
  45681. resolvedPath,
  45682. bundled.code,
  45683. isESM
  45684. );
  45685. return {
  45686. configExport: userConfig,
  45687. dependencies: bundled.dependencies
  45688. };
  45689. }
  45690. async function bundleConfigFile(fileName, isESM) {
  45691. const isModuleSyncConditionEnabled = (await import('#module-sync-enabled')).default;
  45692. const dirnameVarName = "__vite_injected_original_dirname";
  45693. const filenameVarName = "__vite_injected_original_filename";
  45694. const importMetaUrlVarName = "__vite_injected_original_import_meta_url";
  45695. const result = await build$3({
  45696. absWorkingDir: process.cwd(),
  45697. entryPoints: [fileName],
  45698. write: false,
  45699. target: [`node${process.versions.node}`],
  45700. platform: "node",
  45701. bundle: true,
  45702. format: isESM ? "esm" : "cjs",
  45703. mainFields: ["main"],
  45704. sourcemap: "inline",
  45705. // the last slash is needed to make the path correct
  45706. sourceRoot: path$b.dirname(fileName) + path$b.sep,
  45707. metafile: true,
  45708. define: {
  45709. __dirname: dirnameVarName,
  45710. __filename: filenameVarName,
  45711. "import.meta.url": importMetaUrlVarName,
  45712. "import.meta.dirname": dirnameVarName,
  45713. "import.meta.filename": filenameVarName
  45714. },
  45715. plugins: [
  45716. {
  45717. name: "externalize-deps",
  45718. setup(build2) {
  45719. const packageCache = /* @__PURE__ */ new Map();
  45720. const resolveByViteResolver = (id, importer, isRequire) => {
  45721. return tryNodeResolve(id, importer, {
  45722. root: path$b.dirname(fileName),
  45723. isBuild: true,
  45724. isProduction: true,
  45725. preferRelative: false,
  45726. tryIndex: true,
  45727. mainFields: [],
  45728. conditions: [
  45729. "node",
  45730. ...isModuleSyncConditionEnabled ? ["module-sync"] : []
  45731. ],
  45732. externalConditions: [],
  45733. external: [],
  45734. noExternal: [],
  45735. dedupe: [],
  45736. extensions: configDefaults.resolve.extensions,
  45737. preserveSymlinks: false,
  45738. packageCache,
  45739. isRequire,
  45740. builtins: nodeLikeBuiltins
  45741. })?.id;
  45742. };
  45743. build2.onResolve(
  45744. { filter: /^[^.#].*/ },
  45745. async ({ path: id, importer, kind }) => {
  45746. if (kind === "entry-point" || path$b.isAbsolute(id) || isNodeBuiltin(id)) {
  45747. return;
  45748. }
  45749. if (isNodeLikeBuiltin(id)) {
  45750. return { external: true };
  45751. }
  45752. const isImport = isESM || kind === "dynamic-import";
  45753. let idFsPath;
  45754. try {
  45755. idFsPath = resolveByViteResolver(id, importer, !isImport);
  45756. } catch (e) {
  45757. if (!isImport) {
  45758. let canResolveWithImport = false;
  45759. try {
  45760. canResolveWithImport = !!resolveByViteResolver(
  45761. id,
  45762. importer,
  45763. false
  45764. );
  45765. } catch {
  45766. }
  45767. if (canResolveWithImport) {
  45768. throw new Error(
  45769. `Failed to resolve ${JSON.stringify(
  45770. id
  45771. )}. 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.`
  45772. );
  45773. }
  45774. }
  45775. throw e;
  45776. }
  45777. if (idFsPath && isImport) {
  45778. idFsPath = pathToFileURL$1(idFsPath).href;
  45779. }
  45780. return {
  45781. path: idFsPath,
  45782. external: true
  45783. };
  45784. }
  45785. );
  45786. }
  45787. },
  45788. {
  45789. name: "inject-file-scope-variables",
  45790. setup(build2) {
  45791. build2.onLoad({ filter: /\.[cm]?[jt]s$/ }, async (args) => {
  45792. const contents = await fsp.readFile(args.path, "utf-8");
  45793. const injectValues = `const ${dirnameVarName} = ${JSON.stringify(
  45794. path$b.dirname(args.path)
  45795. )};const ${filenameVarName} = ${JSON.stringify(args.path)};const ${importMetaUrlVarName} = ${JSON.stringify(
  45796. pathToFileURL$1(args.path).href
  45797. )};`;
  45798. return {
  45799. loader: args.path.endsWith("ts") ? "ts" : "js",
  45800. contents: injectValues + contents
  45801. };
  45802. });
  45803. }
  45804. }
  45805. ]
  45806. });
  45807. const { text } = result.outputFiles[0];
  45808. return {
  45809. code: text,
  45810. dependencies: Object.keys(result.metafile.inputs)
  45811. };
  45812. }
  45813. const _require = createRequire$1(import.meta.url);
  45814. async function loadConfigFromBundledFile(fileName, bundledCode, isESM) {
  45815. if (isESM) {
  45816. let nodeModulesDir = typeof process.versions.deno === "string" ? void 0 : findNearestNodeModules(path$b.dirname(fileName));
  45817. if (nodeModulesDir) {
  45818. try {
  45819. await fsp.mkdir(path$b.resolve(nodeModulesDir, ".vite-temp/"), {
  45820. recursive: true
  45821. });
  45822. } catch (e) {
  45823. if (e.code === "EACCES") {
  45824. nodeModulesDir = void 0;
  45825. } else {
  45826. throw e;
  45827. }
  45828. }
  45829. }
  45830. const hash = `timestamp-${Date.now()}-${Math.random().toString(16).slice(2)}`;
  45831. const tempFileName = nodeModulesDir ? path$b.resolve(
  45832. nodeModulesDir,
  45833. `.vite-temp/${path$b.basename(fileName)}.${hash}.mjs`
  45834. ) : `${fileName}.${hash}.mjs`;
  45835. await fsp.writeFile(tempFileName, bundledCode);
  45836. try {
  45837. return (await import(pathToFileURL$1(tempFileName).href)).default;
  45838. } finally {
  45839. fs__default.unlink(tempFileName, () => {
  45840. });
  45841. }
  45842. } else {
  45843. const extension = path$b.extname(fileName);
  45844. const realFileName = await promisifiedRealpath(fileName);
  45845. const loaderExt = extension in _require.extensions ? extension : ".js";
  45846. const defaultLoader = _require.extensions[loaderExt];
  45847. _require.extensions[loaderExt] = (module, filename) => {
  45848. if (filename === realFileName) {
  45849. module._compile(bundledCode, filename);
  45850. } else {
  45851. defaultLoader(module, filename);
  45852. }
  45853. };
  45854. delete _require.cache[_require.resolve(fileName)];
  45855. const raw = _require(fileName);
  45856. _require.extensions[loaderExt] = defaultLoader;
  45857. return raw.__esModule ? raw.default : raw;
  45858. }
  45859. }
  45860. async function runConfigHook(config, plugins, configEnv) {
  45861. let conf = config;
  45862. for (const p of getSortedPluginsByHook("config", plugins)) {
  45863. const hook = p.config;
  45864. const handler = getHookHandler(hook);
  45865. const res = await handler(conf, configEnv);
  45866. if (res && res !== conf) {
  45867. conf = mergeConfig(conf, res);
  45868. }
  45869. }
  45870. return conf;
  45871. }
  45872. async function runConfigEnvironmentHook(environments, plugins, configEnv, isSsrTargetWebworkerSet) {
  45873. const environmentNames = Object.keys(environments);
  45874. for (const p of getSortedPluginsByHook("configEnvironment", plugins)) {
  45875. const hook = p.configEnvironment;
  45876. const handler = getHookHandler(hook);
  45877. for (const name of environmentNames) {
  45878. const res = await handler(name, environments[name], {
  45879. ...configEnv,
  45880. isSsrTargetWebworker: isSsrTargetWebworkerSet && name === "ssr"
  45881. });
  45882. if (res) {
  45883. environments[name] = mergeConfig(environments[name], res);
  45884. }
  45885. }
  45886. }
  45887. }
  45888. function optimizeDepsDisabledBackwardCompatibility(resolved, optimizeDeps, optimizeDepsPath = "") {
  45889. const optimizeDepsDisabled = optimizeDeps.disabled;
  45890. if (optimizeDepsDisabled !== void 0) {
  45891. if (optimizeDepsDisabled === true || optimizeDepsDisabled === "dev") {
  45892. const commonjsOptionsInclude = resolved.build.commonjsOptions.include;
  45893. const commonjsPluginDisabled = Array.isArray(commonjsOptionsInclude) && commonjsOptionsInclude.length === 0;
  45894. optimizeDeps.noDiscovery = true;
  45895. optimizeDeps.include = void 0;
  45896. if (commonjsPluginDisabled) {
  45897. resolved.build.commonjsOptions.include = void 0;
  45898. }
  45899. resolved.logger.warn(
  45900. colors$1.yellow(`(!) Experimental ${optimizeDepsPath}optimizeDeps.disabled and deps pre-bundling during build were removed in Vite 5.1.
  45901. To disable the deps optimizer, set ${optimizeDepsPath}optimizeDeps.noDiscovery to true and ${optimizeDepsPath}optimizeDeps.include as undefined or empty.
  45902. Please remove ${optimizeDepsPath}optimizeDeps.disabled from your config.
  45903. ${commonjsPluginDisabled ? "Empty config.build.commonjsOptions.include will be ignored to support CJS during build. This config should also be removed." : ""}
  45904. `)
  45905. );
  45906. } else if (optimizeDepsDisabled === false || optimizeDepsDisabled === "build") {
  45907. resolved.logger.warn(
  45908. colors$1.yellow(`(!) Experimental ${optimizeDepsPath}optimizeDeps.disabled and deps pre-bundling during build were removed in Vite 5.1.
  45909. Setting it to ${optimizeDepsDisabled} now has no effect.
  45910. Please remove ${optimizeDepsPath}optimizeDeps.disabled from your config.
  45911. `)
  45912. );
  45913. }
  45914. }
  45915. }
  45916. export { normalizePath$3 as A, BuildEnvironment as B, mergeConfig as C, DevEnvironment as D, mergeAlias as E, createFilter$1 as F, rollupVersion as G, send$1 as H, createLogger as I, searchForWorkspaceRoot as J, isFileServingAllowed as K, isFileLoadingAllowed as L, loadEnv as M, resolveEnvPrefix as N, colors$1 as O, getDefaultExportFromCjs as P, commonjsGlobal as Q, index$1 as R, index as S, build$1 as T, preview$1 as U, arraify as a, perEnvironmentState as b, createServer as c, defineConfig as d, preview as e, build as f, createBuilder as g, createIdResolver as h, isInNodeModules$1 as i, formatPostcssSourceMap as j, preprocessCSS as k, loadConfigFromFile as l, buildErrorMessage as m, createRunnableDevEnvironment as n, optimizeDeps as o, perEnvironmentPlugin as p, isRunnableDevEnvironment as q, resolveConfig as r, sortUserPlugins as s, transformWithEsbuild as t, runnerImport as u, fetchModule as v, createServerModuleRunner as w, createServerModuleRunnerTransport as x, createServerHotChannel as y, ssrTransform as z };