entry.worker.js 226 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744
  1. var __create = Object.create;
  2. var __defProp = Object.defineProperty;
  3. var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
  4. var __getOwnPropNames = Object.getOwnPropertyNames;
  5. var __getProtoOf = Object.getPrototypeOf;
  6. var __hasOwnProp = Object.prototype.hasOwnProperty;
  7. var __esm = (fn, res) => function __init() {
  8. return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
  9. };
  10. var __commonJS = (cb, mod) => function __require() {
  11. return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
  12. };
  13. var __export = (target, all) => {
  14. for (var name in all)
  15. __defProp(target, name, { get: all[name], enumerable: true });
  16. };
  17. var __copyProps = (to, from, except, desc) => {
  18. if (from && typeof from === "object" || typeof from === "function") {
  19. for (let key of __getOwnPropNames(from))
  20. if (!__hasOwnProp.call(to, key) && key !== except)
  21. __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  22. }
  23. return to;
  24. };
  25. var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  26. // If the importer is in node compatibility mode or this is not an ESM
  27. // file that has been converted to a CommonJS file using a Babel-
  28. // compatible transform (i.e. "__esModule" has not been set), then set
  29. // "default" to the CommonJS "module.exports" for node compatibility.
  30. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  31. mod
  32. ));
  33. var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
  34. // node_modules/base64-js/index.js
  35. var require_base64_js = __commonJS({
  36. "node_modules/base64-js/index.js"(exports) {
  37. "use strict";
  38. exports.byteLength = byteLength;
  39. exports.toByteArray = toByteArray;
  40. exports.fromByteArray = fromByteArray;
  41. var lookup = [];
  42. var revLookup = [];
  43. var Arr = typeof Uint8Array !== "undefined" ? Uint8Array : Array;
  44. var code = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  45. for (i = 0, len = code.length; i < len; ++i) {
  46. lookup[i] = code[i];
  47. revLookup[code.charCodeAt(i)] = i;
  48. }
  49. var i;
  50. var len;
  51. revLookup["-".charCodeAt(0)] = 62;
  52. revLookup["_".charCodeAt(0)] = 63;
  53. function getLens(b64) {
  54. var len2 = b64.length;
  55. if (len2 % 4 > 0) {
  56. throw new Error("Invalid string. Length must be a multiple of 4");
  57. }
  58. var validLen = b64.indexOf("=");
  59. if (validLen === -1)
  60. validLen = len2;
  61. var placeHoldersLen = validLen === len2 ? 0 : 4 - validLen % 4;
  62. return [validLen, placeHoldersLen];
  63. }
  64. function byteLength(b64) {
  65. var lens = getLens(b64);
  66. var validLen = lens[0];
  67. var placeHoldersLen = lens[1];
  68. return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen;
  69. }
  70. function _byteLength(b64, validLen, placeHoldersLen) {
  71. return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen;
  72. }
  73. function toByteArray(b64) {
  74. var tmp;
  75. var lens = getLens(b64);
  76. var validLen = lens[0];
  77. var placeHoldersLen = lens[1];
  78. var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen));
  79. var curByte = 0;
  80. var len2 = placeHoldersLen > 0 ? validLen - 4 : validLen;
  81. var i2;
  82. for (i2 = 0; i2 < len2; i2 += 4) {
  83. tmp = revLookup[b64.charCodeAt(i2)] << 18 | revLookup[b64.charCodeAt(i2 + 1)] << 12 | revLookup[b64.charCodeAt(i2 + 2)] << 6 | revLookup[b64.charCodeAt(i2 + 3)];
  84. arr[curByte++] = tmp >> 16 & 255;
  85. arr[curByte++] = tmp >> 8 & 255;
  86. arr[curByte++] = tmp & 255;
  87. }
  88. if (placeHoldersLen === 2) {
  89. tmp = revLookup[b64.charCodeAt(i2)] << 2 | revLookup[b64.charCodeAt(i2 + 1)] >> 4;
  90. arr[curByte++] = tmp & 255;
  91. }
  92. if (placeHoldersLen === 1) {
  93. tmp = revLookup[b64.charCodeAt(i2)] << 10 | revLookup[b64.charCodeAt(i2 + 1)] << 4 | revLookup[b64.charCodeAt(i2 + 2)] >> 2;
  94. arr[curByte++] = tmp >> 8 & 255;
  95. arr[curByte++] = tmp & 255;
  96. }
  97. return arr;
  98. }
  99. function tripletToBase64(num) {
  100. return lookup[num >> 18 & 63] + lookup[num >> 12 & 63] + lookup[num >> 6 & 63] + lookup[num & 63];
  101. }
  102. function encodeChunk(uint8, start, end) {
  103. var tmp;
  104. var output = [];
  105. for (var i2 = start; i2 < end; i2 += 3) {
  106. tmp = (uint8[i2] << 16 & 16711680) + (uint8[i2 + 1] << 8 & 65280) + (uint8[i2 + 2] & 255);
  107. output.push(tripletToBase64(tmp));
  108. }
  109. return output.join("");
  110. }
  111. function fromByteArray(uint8) {
  112. var tmp;
  113. var len2 = uint8.length;
  114. var extraBytes = len2 % 3;
  115. var parts = [];
  116. var maxChunkLength = 16383;
  117. for (var i2 = 0, len22 = len2 - extraBytes; i2 < len22; i2 += maxChunkLength) {
  118. parts.push(encodeChunk(uint8, i2, i2 + maxChunkLength > len22 ? len22 : i2 + maxChunkLength));
  119. }
  120. if (extraBytes === 1) {
  121. tmp = uint8[len2 - 1];
  122. parts.push(
  123. lookup[tmp >> 2] + lookup[tmp << 4 & 63] + "=="
  124. );
  125. } else if (extraBytes === 2) {
  126. tmp = (uint8[len2 - 2] << 8) + uint8[len2 - 1];
  127. parts.push(
  128. lookup[tmp >> 10] + lookup[tmp >> 4 & 63] + lookup[tmp << 2 & 63] + "="
  129. );
  130. }
  131. return parts.join("");
  132. }
  133. }
  134. });
  135. // node_modules/ieee754/index.js
  136. var require_ieee754 = __commonJS({
  137. "node_modules/ieee754/index.js"(exports) {
  138. exports.read = function(buffer, offset, isLE, mLen, nBytes) {
  139. var e, m;
  140. var eLen = nBytes * 8 - mLen - 1;
  141. var eMax = (1 << eLen) - 1;
  142. var eBias = eMax >> 1;
  143. var nBits = -7;
  144. var i = isLE ? nBytes - 1 : 0;
  145. var d = isLE ? -1 : 1;
  146. var s = buffer[offset + i];
  147. i += d;
  148. e = s & (1 << -nBits) - 1;
  149. s >>= -nBits;
  150. nBits += eLen;
  151. for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {
  152. }
  153. m = e & (1 << -nBits) - 1;
  154. e >>= -nBits;
  155. nBits += mLen;
  156. for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {
  157. }
  158. if (e === 0) {
  159. e = 1 - eBias;
  160. } else if (e === eMax) {
  161. return m ? NaN : (s ? -1 : 1) * Infinity;
  162. } else {
  163. m = m + Math.pow(2, mLen);
  164. e = e - eBias;
  165. }
  166. return (s ? -1 : 1) * m * Math.pow(2, e - mLen);
  167. };
  168. exports.write = function(buffer, value, offset, isLE, mLen, nBytes) {
  169. var e, m, c;
  170. var eLen = nBytes * 8 - mLen - 1;
  171. var eMax = (1 << eLen) - 1;
  172. var eBias = eMax >> 1;
  173. var rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0;
  174. var i = isLE ? 0 : nBytes - 1;
  175. var d = isLE ? 1 : -1;
  176. var s = value < 0 || value === 0 && 1 / value < 0 ? 1 : 0;
  177. value = Math.abs(value);
  178. if (isNaN(value) || value === Infinity) {
  179. m = isNaN(value) ? 1 : 0;
  180. e = eMax;
  181. } else {
  182. e = Math.floor(Math.log(value) / Math.LN2);
  183. if (value * (c = Math.pow(2, -e)) < 1) {
  184. e--;
  185. c *= 2;
  186. }
  187. if (e + eBias >= 1) {
  188. value += rt / c;
  189. } else {
  190. value += rt * Math.pow(2, 1 - eBias);
  191. }
  192. if (value * c >= 2) {
  193. e++;
  194. c /= 2;
  195. }
  196. if (e + eBias >= eMax) {
  197. m = 0;
  198. e = eMax;
  199. } else if (e + eBias >= 1) {
  200. m = (value * c - 1) * Math.pow(2, mLen);
  201. e = e + eBias;
  202. } else {
  203. m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
  204. e = 0;
  205. }
  206. }
  207. for (; mLen >= 8; buffer[offset + i] = m & 255, i += d, m /= 256, mLen -= 8) {
  208. }
  209. e = e << mLen | m;
  210. eLen += mLen;
  211. for (; eLen > 0; buffer[offset + i] = e & 255, i += d, e /= 256, eLen -= 8) {
  212. }
  213. buffer[offset + i - d] |= s * 128;
  214. };
  215. }
  216. });
  217. // node_modules/@remix-pwa/cache/node_modules/buffer/index.js
  218. var require_buffer = __commonJS({
  219. "node_modules/@remix-pwa/cache/node_modules/buffer/index.js"(exports) {
  220. "use strict";
  221. var base64 = require_base64_js();
  222. var ieee754 = require_ieee754();
  223. var customInspectSymbol = typeof Symbol === "function" && typeof Symbol["for"] === "function" ? Symbol["for"]("nodejs.util.inspect.custom") : null;
  224. exports.Buffer = Buffer3;
  225. exports.SlowBuffer = SlowBuffer;
  226. exports.INSPECT_MAX_BYTES = 50;
  227. var K_MAX_LENGTH = 2147483647;
  228. exports.kMaxLength = K_MAX_LENGTH;
  229. Buffer3.TYPED_ARRAY_SUPPORT = typedArraySupport();
  230. if (!Buffer3.TYPED_ARRAY_SUPPORT && typeof console !== "undefined" && typeof console.error === "function") {
  231. console.error(
  232. "This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support."
  233. );
  234. }
  235. function typedArraySupport() {
  236. try {
  237. const arr = new Uint8Array(1);
  238. const proto = { foo: function() {
  239. return 42;
  240. } };
  241. Object.setPrototypeOf(proto, Uint8Array.prototype);
  242. Object.setPrototypeOf(arr, proto);
  243. return arr.foo() === 42;
  244. } catch (e) {
  245. return false;
  246. }
  247. }
  248. Object.defineProperty(Buffer3.prototype, "parent", {
  249. enumerable: true,
  250. get: function() {
  251. if (!Buffer3.isBuffer(this))
  252. return void 0;
  253. return this.buffer;
  254. }
  255. });
  256. Object.defineProperty(Buffer3.prototype, "offset", {
  257. enumerable: true,
  258. get: function() {
  259. if (!Buffer3.isBuffer(this))
  260. return void 0;
  261. return this.byteOffset;
  262. }
  263. });
  264. function createBuffer(length) {
  265. if (length > K_MAX_LENGTH) {
  266. throw new RangeError('The value "' + length + '" is invalid for option "size"');
  267. }
  268. const buf = new Uint8Array(length);
  269. Object.setPrototypeOf(buf, Buffer3.prototype);
  270. return buf;
  271. }
  272. function Buffer3(arg, encodingOrOffset, length) {
  273. if (typeof arg === "number") {
  274. if (typeof encodingOrOffset === "string") {
  275. throw new TypeError(
  276. 'The "string" argument must be of type string. Received type number'
  277. );
  278. }
  279. return allocUnsafe(arg);
  280. }
  281. return from(arg, encodingOrOffset, length);
  282. }
  283. Buffer3.poolSize = 8192;
  284. function from(value, encodingOrOffset, length) {
  285. if (typeof value === "string") {
  286. return fromString(value, encodingOrOffset);
  287. }
  288. if (ArrayBuffer.isView(value)) {
  289. return fromArrayView(value);
  290. }
  291. if (value == null) {
  292. throw new TypeError(
  293. "The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type " + typeof value
  294. );
  295. }
  296. if (isInstance(value, ArrayBuffer) || value && isInstance(value.buffer, ArrayBuffer)) {
  297. return fromArrayBuffer(value, encodingOrOffset, length);
  298. }
  299. if (typeof SharedArrayBuffer !== "undefined" && (isInstance(value, SharedArrayBuffer) || value && isInstance(value.buffer, SharedArrayBuffer))) {
  300. return fromArrayBuffer(value, encodingOrOffset, length);
  301. }
  302. if (typeof value === "number") {
  303. throw new TypeError(
  304. 'The "value" argument must not be of type number. Received type number'
  305. );
  306. }
  307. const valueOf = value.valueOf && value.valueOf();
  308. if (valueOf != null && valueOf !== value) {
  309. return Buffer3.from(valueOf, encodingOrOffset, length);
  310. }
  311. const b2 = fromObject(value);
  312. if (b2)
  313. return b2;
  314. if (typeof Symbol !== "undefined" && Symbol.toPrimitive != null && typeof value[Symbol.toPrimitive] === "function") {
  315. return Buffer3.from(value[Symbol.toPrimitive]("string"), encodingOrOffset, length);
  316. }
  317. throw new TypeError(
  318. "The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type " + typeof value
  319. );
  320. }
  321. Buffer3.from = function(value, encodingOrOffset, length) {
  322. return from(value, encodingOrOffset, length);
  323. };
  324. Object.setPrototypeOf(Buffer3.prototype, Uint8Array.prototype);
  325. Object.setPrototypeOf(Buffer3, Uint8Array);
  326. function assertSize(size) {
  327. if (typeof size !== "number") {
  328. throw new TypeError('"size" argument must be of type number');
  329. } else if (size < 0) {
  330. throw new RangeError('The value "' + size + '" is invalid for option "size"');
  331. }
  332. }
  333. function alloc(size, fill, encoding) {
  334. assertSize(size);
  335. if (size <= 0) {
  336. return createBuffer(size);
  337. }
  338. if (fill !== void 0) {
  339. return typeof encoding === "string" ? createBuffer(size).fill(fill, encoding) : createBuffer(size).fill(fill);
  340. }
  341. return createBuffer(size);
  342. }
  343. Buffer3.alloc = function(size, fill, encoding) {
  344. return alloc(size, fill, encoding);
  345. };
  346. function allocUnsafe(size) {
  347. assertSize(size);
  348. return createBuffer(size < 0 ? 0 : checked(size) | 0);
  349. }
  350. Buffer3.allocUnsafe = function(size) {
  351. return allocUnsafe(size);
  352. };
  353. Buffer3.allocUnsafeSlow = function(size) {
  354. return allocUnsafe(size);
  355. };
  356. function fromString(string, encoding) {
  357. if (typeof encoding !== "string" || encoding === "") {
  358. encoding = "utf8";
  359. }
  360. if (!Buffer3.isEncoding(encoding)) {
  361. throw new TypeError("Unknown encoding: " + encoding);
  362. }
  363. const length = byteLength(string, encoding) | 0;
  364. let buf = createBuffer(length);
  365. const actual = buf.write(string, encoding);
  366. if (actual !== length) {
  367. buf = buf.slice(0, actual);
  368. }
  369. return buf;
  370. }
  371. function fromArrayLike(array) {
  372. const length = array.length < 0 ? 0 : checked(array.length) | 0;
  373. const buf = createBuffer(length);
  374. for (let i = 0; i < length; i += 1) {
  375. buf[i] = array[i] & 255;
  376. }
  377. return buf;
  378. }
  379. function fromArrayView(arrayView) {
  380. if (isInstance(arrayView, Uint8Array)) {
  381. const copy = new Uint8Array(arrayView);
  382. return fromArrayBuffer(copy.buffer, copy.byteOffset, copy.byteLength);
  383. }
  384. return fromArrayLike(arrayView);
  385. }
  386. function fromArrayBuffer(array, byteOffset, length) {
  387. if (byteOffset < 0 || array.byteLength < byteOffset) {
  388. throw new RangeError('"offset" is outside of buffer bounds');
  389. }
  390. if (array.byteLength < byteOffset + (length || 0)) {
  391. throw new RangeError('"length" is outside of buffer bounds');
  392. }
  393. let buf;
  394. if (byteOffset === void 0 && length === void 0) {
  395. buf = new Uint8Array(array);
  396. } else if (length === void 0) {
  397. buf = new Uint8Array(array, byteOffset);
  398. } else {
  399. buf = new Uint8Array(array, byteOffset, length);
  400. }
  401. Object.setPrototypeOf(buf, Buffer3.prototype);
  402. return buf;
  403. }
  404. function fromObject(obj) {
  405. if (Buffer3.isBuffer(obj)) {
  406. const len = checked(obj.length) | 0;
  407. const buf = createBuffer(len);
  408. if (buf.length === 0) {
  409. return buf;
  410. }
  411. obj.copy(buf, 0, 0, len);
  412. return buf;
  413. }
  414. if (obj.length !== void 0) {
  415. if (typeof obj.length !== "number" || numberIsNaN(obj.length)) {
  416. return createBuffer(0);
  417. }
  418. return fromArrayLike(obj);
  419. }
  420. if (obj.type === "Buffer" && Array.isArray(obj.data)) {
  421. return fromArrayLike(obj.data);
  422. }
  423. }
  424. function checked(length) {
  425. if (length >= K_MAX_LENGTH) {
  426. throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x" + K_MAX_LENGTH.toString(16) + " bytes");
  427. }
  428. return length | 0;
  429. }
  430. function SlowBuffer(length) {
  431. if (+length != length) {
  432. length = 0;
  433. }
  434. return Buffer3.alloc(+length);
  435. }
  436. Buffer3.isBuffer = function isBuffer(b2) {
  437. return b2 != null && b2._isBuffer === true && b2 !== Buffer3.prototype;
  438. };
  439. Buffer3.compare = function compare(a, b2) {
  440. if (isInstance(a, Uint8Array))
  441. a = Buffer3.from(a, a.offset, a.byteLength);
  442. if (isInstance(b2, Uint8Array))
  443. b2 = Buffer3.from(b2, b2.offset, b2.byteLength);
  444. if (!Buffer3.isBuffer(a) || !Buffer3.isBuffer(b2)) {
  445. throw new TypeError(
  446. 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array'
  447. );
  448. }
  449. if (a === b2)
  450. return 0;
  451. let x = a.length;
  452. let y2 = b2.length;
  453. for (let i = 0, len = Math.min(x, y2); i < len; ++i) {
  454. if (a[i] !== b2[i]) {
  455. x = a[i];
  456. y2 = b2[i];
  457. break;
  458. }
  459. }
  460. if (x < y2)
  461. return -1;
  462. if (y2 < x)
  463. return 1;
  464. return 0;
  465. };
  466. Buffer3.isEncoding = function isEncoding(encoding) {
  467. switch (String(encoding).toLowerCase()) {
  468. case "hex":
  469. case "utf8":
  470. case "utf-8":
  471. case "ascii":
  472. case "latin1":
  473. case "binary":
  474. case "base64":
  475. case "ucs2":
  476. case "ucs-2":
  477. case "utf16le":
  478. case "utf-16le":
  479. return true;
  480. default:
  481. return false;
  482. }
  483. };
  484. Buffer3.concat = function concat(list, length) {
  485. if (!Array.isArray(list)) {
  486. throw new TypeError('"list" argument must be an Array of Buffers');
  487. }
  488. if (list.length === 0) {
  489. return Buffer3.alloc(0);
  490. }
  491. let i;
  492. if (length === void 0) {
  493. length = 0;
  494. for (i = 0; i < list.length; ++i) {
  495. length += list[i].length;
  496. }
  497. }
  498. const buffer = Buffer3.allocUnsafe(length);
  499. let pos = 0;
  500. for (i = 0; i < list.length; ++i) {
  501. let buf = list[i];
  502. if (isInstance(buf, Uint8Array)) {
  503. if (pos + buf.length > buffer.length) {
  504. if (!Buffer3.isBuffer(buf))
  505. buf = Buffer3.from(buf);
  506. buf.copy(buffer, pos);
  507. } else {
  508. Uint8Array.prototype.set.call(
  509. buffer,
  510. buf,
  511. pos
  512. );
  513. }
  514. } else if (!Buffer3.isBuffer(buf)) {
  515. throw new TypeError('"list" argument must be an Array of Buffers');
  516. } else {
  517. buf.copy(buffer, pos);
  518. }
  519. pos += buf.length;
  520. }
  521. return buffer;
  522. };
  523. function byteLength(string, encoding) {
  524. if (Buffer3.isBuffer(string)) {
  525. return string.length;
  526. }
  527. if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {
  528. return string.byteLength;
  529. }
  530. if (typeof string !== "string") {
  531. throw new TypeError(
  532. 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type ' + typeof string
  533. );
  534. }
  535. const len = string.length;
  536. const mustMatch = arguments.length > 2 && arguments[2] === true;
  537. if (!mustMatch && len === 0)
  538. return 0;
  539. let loweredCase = false;
  540. for (; ; ) {
  541. switch (encoding) {
  542. case "ascii":
  543. case "latin1":
  544. case "binary":
  545. return len;
  546. case "utf8":
  547. case "utf-8":
  548. return utf8ToBytes(string).length;
  549. case "ucs2":
  550. case "ucs-2":
  551. case "utf16le":
  552. case "utf-16le":
  553. return len * 2;
  554. case "hex":
  555. return len >>> 1;
  556. case "base64":
  557. return base64ToBytes(string).length;
  558. default:
  559. if (loweredCase) {
  560. return mustMatch ? -1 : utf8ToBytes(string).length;
  561. }
  562. encoding = ("" + encoding).toLowerCase();
  563. loweredCase = true;
  564. }
  565. }
  566. }
  567. Buffer3.byteLength = byteLength;
  568. function slowToString(encoding, start, end) {
  569. let loweredCase = false;
  570. if (start === void 0 || start < 0) {
  571. start = 0;
  572. }
  573. if (start > this.length) {
  574. return "";
  575. }
  576. if (end === void 0 || end > this.length) {
  577. end = this.length;
  578. }
  579. if (end <= 0) {
  580. return "";
  581. }
  582. end >>>= 0;
  583. start >>>= 0;
  584. if (end <= start) {
  585. return "";
  586. }
  587. if (!encoding)
  588. encoding = "utf8";
  589. while (true) {
  590. switch (encoding) {
  591. case "hex":
  592. return hexSlice(this, start, end);
  593. case "utf8":
  594. case "utf-8":
  595. return utf8Slice(this, start, end);
  596. case "ascii":
  597. return asciiSlice(this, start, end);
  598. case "latin1":
  599. case "binary":
  600. return latin1Slice(this, start, end);
  601. case "base64":
  602. return base64Slice(this, start, end);
  603. case "ucs2":
  604. case "ucs-2":
  605. case "utf16le":
  606. case "utf-16le":
  607. return utf16leSlice(this, start, end);
  608. default:
  609. if (loweredCase)
  610. throw new TypeError("Unknown encoding: " + encoding);
  611. encoding = (encoding + "").toLowerCase();
  612. loweredCase = true;
  613. }
  614. }
  615. }
  616. Buffer3.prototype._isBuffer = true;
  617. function swap(b2, n, m) {
  618. const i = b2[n];
  619. b2[n] = b2[m];
  620. b2[m] = i;
  621. }
  622. Buffer3.prototype.swap16 = function swap16() {
  623. const len = this.length;
  624. if (len % 2 !== 0) {
  625. throw new RangeError("Buffer size must be a multiple of 16-bits");
  626. }
  627. for (let i = 0; i < len; i += 2) {
  628. swap(this, i, i + 1);
  629. }
  630. return this;
  631. };
  632. Buffer3.prototype.swap32 = function swap32() {
  633. const len = this.length;
  634. if (len % 4 !== 0) {
  635. throw new RangeError("Buffer size must be a multiple of 32-bits");
  636. }
  637. for (let i = 0; i < len; i += 4) {
  638. swap(this, i, i + 3);
  639. swap(this, i + 1, i + 2);
  640. }
  641. return this;
  642. };
  643. Buffer3.prototype.swap64 = function swap64() {
  644. const len = this.length;
  645. if (len % 8 !== 0) {
  646. throw new RangeError("Buffer size must be a multiple of 64-bits");
  647. }
  648. for (let i = 0; i < len; i += 8) {
  649. swap(this, i, i + 7);
  650. swap(this, i + 1, i + 6);
  651. swap(this, i + 2, i + 5);
  652. swap(this, i + 3, i + 4);
  653. }
  654. return this;
  655. };
  656. Buffer3.prototype.toString = function toString() {
  657. const length = this.length;
  658. if (length === 0)
  659. return "";
  660. if (arguments.length === 0)
  661. return utf8Slice(this, 0, length);
  662. return slowToString.apply(this, arguments);
  663. };
  664. Buffer3.prototype.toLocaleString = Buffer3.prototype.toString;
  665. Buffer3.prototype.equals = function equals(b2) {
  666. if (!Buffer3.isBuffer(b2))
  667. throw new TypeError("Argument must be a Buffer");
  668. if (this === b2)
  669. return true;
  670. return Buffer3.compare(this, b2) === 0;
  671. };
  672. Buffer3.prototype.inspect = function inspect() {
  673. let str = "";
  674. const max = exports.INSPECT_MAX_BYTES;
  675. str = this.toString("hex", 0, max).replace(/(.{2})/g, "$1 ").trim();
  676. if (this.length > max)
  677. str += " ... ";
  678. return "<Buffer " + str + ">";
  679. };
  680. if (customInspectSymbol) {
  681. Buffer3.prototype[customInspectSymbol] = Buffer3.prototype.inspect;
  682. }
  683. Buffer3.prototype.compare = function compare(target, start, end, thisStart, thisEnd) {
  684. if (isInstance(target, Uint8Array)) {
  685. target = Buffer3.from(target, target.offset, target.byteLength);
  686. }
  687. if (!Buffer3.isBuffer(target)) {
  688. throw new TypeError(
  689. 'The "target" argument must be one of type Buffer or Uint8Array. Received type ' + typeof target
  690. );
  691. }
  692. if (start === void 0) {
  693. start = 0;
  694. }
  695. if (end === void 0) {
  696. end = target ? target.length : 0;
  697. }
  698. if (thisStart === void 0) {
  699. thisStart = 0;
  700. }
  701. if (thisEnd === void 0) {
  702. thisEnd = this.length;
  703. }
  704. if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
  705. throw new RangeError("out of range index");
  706. }
  707. if (thisStart >= thisEnd && start >= end) {
  708. return 0;
  709. }
  710. if (thisStart >= thisEnd) {
  711. return -1;
  712. }
  713. if (start >= end) {
  714. return 1;
  715. }
  716. start >>>= 0;
  717. end >>>= 0;
  718. thisStart >>>= 0;
  719. thisEnd >>>= 0;
  720. if (this === target)
  721. return 0;
  722. let x = thisEnd - thisStart;
  723. let y2 = end - start;
  724. const len = Math.min(x, y2);
  725. const thisCopy = this.slice(thisStart, thisEnd);
  726. const targetCopy = target.slice(start, end);
  727. for (let i = 0; i < len; ++i) {
  728. if (thisCopy[i] !== targetCopy[i]) {
  729. x = thisCopy[i];
  730. y2 = targetCopy[i];
  731. break;
  732. }
  733. }
  734. if (x < y2)
  735. return -1;
  736. if (y2 < x)
  737. return 1;
  738. return 0;
  739. };
  740. function bidirectionalIndexOf(buffer, val, byteOffset, encoding, dir) {
  741. if (buffer.length === 0)
  742. return -1;
  743. if (typeof byteOffset === "string") {
  744. encoding = byteOffset;
  745. byteOffset = 0;
  746. } else if (byteOffset > 2147483647) {
  747. byteOffset = 2147483647;
  748. } else if (byteOffset < -2147483648) {
  749. byteOffset = -2147483648;
  750. }
  751. byteOffset = +byteOffset;
  752. if (numberIsNaN(byteOffset)) {
  753. byteOffset = dir ? 0 : buffer.length - 1;
  754. }
  755. if (byteOffset < 0)
  756. byteOffset = buffer.length + byteOffset;
  757. if (byteOffset >= buffer.length) {
  758. if (dir)
  759. return -1;
  760. else
  761. byteOffset = buffer.length - 1;
  762. } else if (byteOffset < 0) {
  763. if (dir)
  764. byteOffset = 0;
  765. else
  766. return -1;
  767. }
  768. if (typeof val === "string") {
  769. val = Buffer3.from(val, encoding);
  770. }
  771. if (Buffer3.isBuffer(val)) {
  772. if (val.length === 0) {
  773. return -1;
  774. }
  775. return arrayIndexOf(buffer, val, byteOffset, encoding, dir);
  776. } else if (typeof val === "number") {
  777. val = val & 255;
  778. if (typeof Uint8Array.prototype.indexOf === "function") {
  779. if (dir) {
  780. return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset);
  781. } else {
  782. return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset);
  783. }
  784. }
  785. return arrayIndexOf(buffer, [val], byteOffset, encoding, dir);
  786. }
  787. throw new TypeError("val must be string, number or Buffer");
  788. }
  789. function arrayIndexOf(arr, val, byteOffset, encoding, dir) {
  790. let indexSize = 1;
  791. let arrLength = arr.length;
  792. let valLength = val.length;
  793. if (encoding !== void 0) {
  794. encoding = String(encoding).toLowerCase();
  795. if (encoding === "ucs2" || encoding === "ucs-2" || encoding === "utf16le" || encoding === "utf-16le") {
  796. if (arr.length < 2 || val.length < 2) {
  797. return -1;
  798. }
  799. indexSize = 2;
  800. arrLength /= 2;
  801. valLength /= 2;
  802. byteOffset /= 2;
  803. }
  804. }
  805. function read(buf, i2) {
  806. if (indexSize === 1) {
  807. return buf[i2];
  808. } else {
  809. return buf.readUInt16BE(i2 * indexSize);
  810. }
  811. }
  812. let i;
  813. if (dir) {
  814. let foundIndex = -1;
  815. for (i = byteOffset; i < arrLength; i++) {
  816. if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
  817. if (foundIndex === -1)
  818. foundIndex = i;
  819. if (i - foundIndex + 1 === valLength)
  820. return foundIndex * indexSize;
  821. } else {
  822. if (foundIndex !== -1)
  823. i -= i - foundIndex;
  824. foundIndex = -1;
  825. }
  826. }
  827. } else {
  828. if (byteOffset + valLength > arrLength)
  829. byteOffset = arrLength - valLength;
  830. for (i = byteOffset; i >= 0; i--) {
  831. let found = true;
  832. for (let j = 0; j < valLength; j++) {
  833. if (read(arr, i + j) !== read(val, j)) {
  834. found = false;
  835. break;
  836. }
  837. }
  838. if (found)
  839. return i;
  840. }
  841. }
  842. return -1;
  843. }
  844. Buffer3.prototype.includes = function includes(val, byteOffset, encoding) {
  845. return this.indexOf(val, byteOffset, encoding) !== -1;
  846. };
  847. Buffer3.prototype.indexOf = function indexOf(val, byteOffset, encoding) {
  848. return bidirectionalIndexOf(this, val, byteOffset, encoding, true);
  849. };
  850. Buffer3.prototype.lastIndexOf = function lastIndexOf(val, byteOffset, encoding) {
  851. return bidirectionalIndexOf(this, val, byteOffset, encoding, false);
  852. };
  853. function hexWrite(buf, string, offset, length) {
  854. offset = Number(offset) || 0;
  855. const remaining = buf.length - offset;
  856. if (!length) {
  857. length = remaining;
  858. } else {
  859. length = Number(length);
  860. if (length > remaining) {
  861. length = remaining;
  862. }
  863. }
  864. const strLen = string.length;
  865. if (length > strLen / 2) {
  866. length = strLen / 2;
  867. }
  868. let i;
  869. for (i = 0; i < length; ++i) {
  870. const parsed = parseInt(string.substr(i * 2, 2), 16);
  871. if (numberIsNaN(parsed))
  872. return i;
  873. buf[offset + i] = parsed;
  874. }
  875. return i;
  876. }
  877. function utf8Write(buf, string, offset, length) {
  878. return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length);
  879. }
  880. function asciiWrite(buf, string, offset, length) {
  881. return blitBuffer(asciiToBytes(string), buf, offset, length);
  882. }
  883. function base64Write(buf, string, offset, length) {
  884. return blitBuffer(base64ToBytes(string), buf, offset, length);
  885. }
  886. function ucs2Write(buf, string, offset, length) {
  887. return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length);
  888. }
  889. Buffer3.prototype.write = function write(string, offset, length, encoding) {
  890. if (offset === void 0) {
  891. encoding = "utf8";
  892. length = this.length;
  893. offset = 0;
  894. } else if (length === void 0 && typeof offset === "string") {
  895. encoding = offset;
  896. length = this.length;
  897. offset = 0;
  898. } else if (isFinite(offset)) {
  899. offset = offset >>> 0;
  900. if (isFinite(length)) {
  901. length = length >>> 0;
  902. if (encoding === void 0)
  903. encoding = "utf8";
  904. } else {
  905. encoding = length;
  906. length = void 0;
  907. }
  908. } else {
  909. throw new Error(
  910. "Buffer.write(string, encoding, offset[, length]) is no longer supported"
  911. );
  912. }
  913. const remaining = this.length - offset;
  914. if (length === void 0 || length > remaining)
  915. length = remaining;
  916. if (string.length > 0 && (length < 0 || offset < 0) || offset > this.length) {
  917. throw new RangeError("Attempt to write outside buffer bounds");
  918. }
  919. if (!encoding)
  920. encoding = "utf8";
  921. let loweredCase = false;
  922. for (; ; ) {
  923. switch (encoding) {
  924. case "hex":
  925. return hexWrite(this, string, offset, length);
  926. case "utf8":
  927. case "utf-8":
  928. return utf8Write(this, string, offset, length);
  929. case "ascii":
  930. case "latin1":
  931. case "binary":
  932. return asciiWrite(this, string, offset, length);
  933. case "base64":
  934. return base64Write(this, string, offset, length);
  935. case "ucs2":
  936. case "ucs-2":
  937. case "utf16le":
  938. case "utf-16le":
  939. return ucs2Write(this, string, offset, length);
  940. default:
  941. if (loweredCase)
  942. throw new TypeError("Unknown encoding: " + encoding);
  943. encoding = ("" + encoding).toLowerCase();
  944. loweredCase = true;
  945. }
  946. }
  947. };
  948. Buffer3.prototype.toJSON = function toJSON2() {
  949. return {
  950. type: "Buffer",
  951. data: Array.prototype.slice.call(this._arr || this, 0)
  952. };
  953. };
  954. function base64Slice(buf, start, end) {
  955. if (start === 0 && end === buf.length) {
  956. return base64.fromByteArray(buf);
  957. } else {
  958. return base64.fromByteArray(buf.slice(start, end));
  959. }
  960. }
  961. function utf8Slice(buf, start, end) {
  962. end = Math.min(buf.length, end);
  963. const res = [];
  964. let i = start;
  965. while (i < end) {
  966. const firstByte = buf[i];
  967. let codePoint = null;
  968. let bytesPerSequence = firstByte > 239 ? 4 : firstByte > 223 ? 3 : firstByte > 191 ? 2 : 1;
  969. if (i + bytesPerSequence <= end) {
  970. let secondByte, thirdByte, fourthByte, tempCodePoint;
  971. switch (bytesPerSequence) {
  972. case 1:
  973. if (firstByte < 128) {
  974. codePoint = firstByte;
  975. }
  976. break;
  977. case 2:
  978. secondByte = buf[i + 1];
  979. if ((secondByte & 192) === 128) {
  980. tempCodePoint = (firstByte & 31) << 6 | secondByte & 63;
  981. if (tempCodePoint > 127) {
  982. codePoint = tempCodePoint;
  983. }
  984. }
  985. break;
  986. case 3:
  987. secondByte = buf[i + 1];
  988. thirdByte = buf[i + 2];
  989. if ((secondByte & 192) === 128 && (thirdByte & 192) === 128) {
  990. tempCodePoint = (firstByte & 15) << 12 | (secondByte & 63) << 6 | thirdByte & 63;
  991. if (tempCodePoint > 2047 && (tempCodePoint < 55296 || tempCodePoint > 57343)) {
  992. codePoint = tempCodePoint;
  993. }
  994. }
  995. break;
  996. case 4:
  997. secondByte = buf[i + 1];
  998. thirdByte = buf[i + 2];
  999. fourthByte = buf[i + 3];
  1000. if ((secondByte & 192) === 128 && (thirdByte & 192) === 128 && (fourthByte & 192) === 128) {
  1001. tempCodePoint = (firstByte & 15) << 18 | (secondByte & 63) << 12 | (thirdByte & 63) << 6 | fourthByte & 63;
  1002. if (tempCodePoint > 65535 && tempCodePoint < 1114112) {
  1003. codePoint = tempCodePoint;
  1004. }
  1005. }
  1006. }
  1007. }
  1008. if (codePoint === null) {
  1009. codePoint = 65533;
  1010. bytesPerSequence = 1;
  1011. } else if (codePoint > 65535) {
  1012. codePoint -= 65536;
  1013. res.push(codePoint >>> 10 & 1023 | 55296);
  1014. codePoint = 56320 | codePoint & 1023;
  1015. }
  1016. res.push(codePoint);
  1017. i += bytesPerSequence;
  1018. }
  1019. return decodeCodePointsArray(res);
  1020. }
  1021. var MAX_ARGUMENTS_LENGTH = 4096;
  1022. function decodeCodePointsArray(codePoints) {
  1023. const len = codePoints.length;
  1024. if (len <= MAX_ARGUMENTS_LENGTH) {
  1025. return String.fromCharCode.apply(String, codePoints);
  1026. }
  1027. let res = "";
  1028. let i = 0;
  1029. while (i < len) {
  1030. res += String.fromCharCode.apply(
  1031. String,
  1032. codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
  1033. );
  1034. }
  1035. return res;
  1036. }
  1037. function asciiSlice(buf, start, end) {
  1038. let ret = "";
  1039. end = Math.min(buf.length, end);
  1040. for (let i = start; i < end; ++i) {
  1041. ret += String.fromCharCode(buf[i] & 127);
  1042. }
  1043. return ret;
  1044. }
  1045. function latin1Slice(buf, start, end) {
  1046. let ret = "";
  1047. end = Math.min(buf.length, end);
  1048. for (let i = start; i < end; ++i) {
  1049. ret += String.fromCharCode(buf[i]);
  1050. }
  1051. return ret;
  1052. }
  1053. function hexSlice(buf, start, end) {
  1054. const len = buf.length;
  1055. if (!start || start < 0)
  1056. start = 0;
  1057. if (!end || end < 0 || end > len)
  1058. end = len;
  1059. let out = "";
  1060. for (let i = start; i < end; ++i) {
  1061. out += hexSliceLookupTable[buf[i]];
  1062. }
  1063. return out;
  1064. }
  1065. function utf16leSlice(buf, start, end) {
  1066. const bytes = buf.slice(start, end);
  1067. let res = "";
  1068. for (let i = 0; i < bytes.length - 1; i += 2) {
  1069. res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256);
  1070. }
  1071. return res;
  1072. }
  1073. Buffer3.prototype.slice = function slice(start, end) {
  1074. const len = this.length;
  1075. start = ~~start;
  1076. end = end === void 0 ? len : ~~end;
  1077. if (start < 0) {
  1078. start += len;
  1079. if (start < 0)
  1080. start = 0;
  1081. } else if (start > len) {
  1082. start = len;
  1083. }
  1084. if (end < 0) {
  1085. end += len;
  1086. if (end < 0)
  1087. end = 0;
  1088. } else if (end > len) {
  1089. end = len;
  1090. }
  1091. if (end < start)
  1092. end = start;
  1093. const newBuf = this.subarray(start, end);
  1094. Object.setPrototypeOf(newBuf, Buffer3.prototype);
  1095. return newBuf;
  1096. };
  1097. function checkOffset(offset, ext, length) {
  1098. if (offset % 1 !== 0 || offset < 0)
  1099. throw new RangeError("offset is not uint");
  1100. if (offset + ext > length)
  1101. throw new RangeError("Trying to access beyond buffer length");
  1102. }
  1103. Buffer3.prototype.readUintLE = Buffer3.prototype.readUIntLE = function readUIntLE(offset, byteLength2, noAssert) {
  1104. offset = offset >>> 0;
  1105. byteLength2 = byteLength2 >>> 0;
  1106. if (!noAssert)
  1107. checkOffset(offset, byteLength2, this.length);
  1108. let val = this[offset];
  1109. let mul = 1;
  1110. let i = 0;
  1111. while (++i < byteLength2 && (mul *= 256)) {
  1112. val += this[offset + i] * mul;
  1113. }
  1114. return val;
  1115. };
  1116. Buffer3.prototype.readUintBE = Buffer3.prototype.readUIntBE = function readUIntBE(offset, byteLength2, noAssert) {
  1117. offset = offset >>> 0;
  1118. byteLength2 = byteLength2 >>> 0;
  1119. if (!noAssert) {
  1120. checkOffset(offset, byteLength2, this.length);
  1121. }
  1122. let val = this[offset + --byteLength2];
  1123. let mul = 1;
  1124. while (byteLength2 > 0 && (mul *= 256)) {
  1125. val += this[offset + --byteLength2] * mul;
  1126. }
  1127. return val;
  1128. };
  1129. Buffer3.prototype.readUint8 = Buffer3.prototype.readUInt8 = function readUInt8(offset, noAssert) {
  1130. offset = offset >>> 0;
  1131. if (!noAssert)
  1132. checkOffset(offset, 1, this.length);
  1133. return this[offset];
  1134. };
  1135. Buffer3.prototype.readUint16LE = Buffer3.prototype.readUInt16LE = function readUInt16LE(offset, noAssert) {
  1136. offset = offset >>> 0;
  1137. if (!noAssert)
  1138. checkOffset(offset, 2, this.length);
  1139. return this[offset] | this[offset + 1] << 8;
  1140. };
  1141. Buffer3.prototype.readUint16BE = Buffer3.prototype.readUInt16BE = function readUInt16BE(offset, noAssert) {
  1142. offset = offset >>> 0;
  1143. if (!noAssert)
  1144. checkOffset(offset, 2, this.length);
  1145. return this[offset] << 8 | this[offset + 1];
  1146. };
  1147. Buffer3.prototype.readUint32LE = Buffer3.prototype.readUInt32LE = function readUInt32LE(offset, noAssert) {
  1148. offset = offset >>> 0;
  1149. if (!noAssert)
  1150. checkOffset(offset, 4, this.length);
  1151. return (this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16) + this[offset + 3] * 16777216;
  1152. };
  1153. Buffer3.prototype.readUint32BE = Buffer3.prototype.readUInt32BE = function readUInt32BE(offset, noAssert) {
  1154. offset = offset >>> 0;
  1155. if (!noAssert)
  1156. checkOffset(offset, 4, this.length);
  1157. return this[offset] * 16777216 + (this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3]);
  1158. };
  1159. Buffer3.prototype.readBigUInt64LE = defineBigIntMethod(function readBigUInt64LE(offset) {
  1160. offset = offset >>> 0;
  1161. validateNumber(offset, "offset");
  1162. const first = this[offset];
  1163. const last = this[offset + 7];
  1164. if (first === void 0 || last === void 0) {
  1165. boundsError(offset, this.length - 8);
  1166. }
  1167. const lo = first + this[++offset] * 2 ** 8 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 24;
  1168. const hi = this[++offset] + this[++offset] * 2 ** 8 + this[++offset] * 2 ** 16 + last * 2 ** 24;
  1169. return BigInt(lo) + (BigInt(hi) << BigInt(32));
  1170. });
  1171. Buffer3.prototype.readBigUInt64BE = defineBigIntMethod(function readBigUInt64BE(offset) {
  1172. offset = offset >>> 0;
  1173. validateNumber(offset, "offset");
  1174. const first = this[offset];
  1175. const last = this[offset + 7];
  1176. if (first === void 0 || last === void 0) {
  1177. boundsError(offset, this.length - 8);
  1178. }
  1179. const hi = first * 2 ** 24 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 8 + this[++offset];
  1180. const lo = this[++offset] * 2 ** 24 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 8 + last;
  1181. return (BigInt(hi) << BigInt(32)) + BigInt(lo);
  1182. });
  1183. Buffer3.prototype.readIntLE = function readIntLE(offset, byteLength2, noAssert) {
  1184. offset = offset >>> 0;
  1185. byteLength2 = byteLength2 >>> 0;
  1186. if (!noAssert)
  1187. checkOffset(offset, byteLength2, this.length);
  1188. let val = this[offset];
  1189. let mul = 1;
  1190. let i = 0;
  1191. while (++i < byteLength2 && (mul *= 256)) {
  1192. val += this[offset + i] * mul;
  1193. }
  1194. mul *= 128;
  1195. if (val >= mul)
  1196. val -= Math.pow(2, 8 * byteLength2);
  1197. return val;
  1198. };
  1199. Buffer3.prototype.readIntBE = function readIntBE(offset, byteLength2, noAssert) {
  1200. offset = offset >>> 0;
  1201. byteLength2 = byteLength2 >>> 0;
  1202. if (!noAssert)
  1203. checkOffset(offset, byteLength2, this.length);
  1204. let i = byteLength2;
  1205. let mul = 1;
  1206. let val = this[offset + --i];
  1207. while (i > 0 && (mul *= 256)) {
  1208. val += this[offset + --i] * mul;
  1209. }
  1210. mul *= 128;
  1211. if (val >= mul)
  1212. val -= Math.pow(2, 8 * byteLength2);
  1213. return val;
  1214. };
  1215. Buffer3.prototype.readInt8 = function readInt8(offset, noAssert) {
  1216. offset = offset >>> 0;
  1217. if (!noAssert)
  1218. checkOffset(offset, 1, this.length);
  1219. if (!(this[offset] & 128))
  1220. return this[offset];
  1221. return (255 - this[offset] + 1) * -1;
  1222. };
  1223. Buffer3.prototype.readInt16LE = function readInt16LE(offset, noAssert) {
  1224. offset = offset >>> 0;
  1225. if (!noAssert)
  1226. checkOffset(offset, 2, this.length);
  1227. const val = this[offset] | this[offset + 1] << 8;
  1228. return val & 32768 ? val | 4294901760 : val;
  1229. };
  1230. Buffer3.prototype.readInt16BE = function readInt16BE(offset, noAssert) {
  1231. offset = offset >>> 0;
  1232. if (!noAssert)
  1233. checkOffset(offset, 2, this.length);
  1234. const val = this[offset + 1] | this[offset] << 8;
  1235. return val & 32768 ? val | 4294901760 : val;
  1236. };
  1237. Buffer3.prototype.readInt32LE = function readInt32LE(offset, noAssert) {
  1238. offset = offset >>> 0;
  1239. if (!noAssert)
  1240. checkOffset(offset, 4, this.length);
  1241. return this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16 | this[offset + 3] << 24;
  1242. };
  1243. Buffer3.prototype.readInt32BE = function readInt32BE(offset, noAssert) {
  1244. offset = offset >>> 0;
  1245. if (!noAssert)
  1246. checkOffset(offset, 4, this.length);
  1247. return this[offset] << 24 | this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3];
  1248. };
  1249. Buffer3.prototype.readBigInt64LE = defineBigIntMethod(function readBigInt64LE(offset) {
  1250. offset = offset >>> 0;
  1251. validateNumber(offset, "offset");
  1252. const first = this[offset];
  1253. const last = this[offset + 7];
  1254. if (first === void 0 || last === void 0) {
  1255. boundsError(offset, this.length - 8);
  1256. }
  1257. const val = this[offset + 4] + this[offset + 5] * 2 ** 8 + this[offset + 6] * 2 ** 16 + (last << 24);
  1258. return (BigInt(val) << BigInt(32)) + BigInt(first + this[++offset] * 2 ** 8 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 24);
  1259. });
  1260. Buffer3.prototype.readBigInt64BE = defineBigIntMethod(function readBigInt64BE(offset) {
  1261. offset = offset >>> 0;
  1262. validateNumber(offset, "offset");
  1263. const first = this[offset];
  1264. const last = this[offset + 7];
  1265. if (first === void 0 || last === void 0) {
  1266. boundsError(offset, this.length - 8);
  1267. }
  1268. const val = (first << 24) + // Overflow
  1269. this[++offset] * 2 ** 16 + this[++offset] * 2 ** 8 + this[++offset];
  1270. return (BigInt(val) << BigInt(32)) + BigInt(this[++offset] * 2 ** 24 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 8 + last);
  1271. });
  1272. Buffer3.prototype.readFloatLE = function readFloatLE(offset, noAssert) {
  1273. offset = offset >>> 0;
  1274. if (!noAssert)
  1275. checkOffset(offset, 4, this.length);
  1276. return ieee754.read(this, offset, true, 23, 4);
  1277. };
  1278. Buffer3.prototype.readFloatBE = function readFloatBE(offset, noAssert) {
  1279. offset = offset >>> 0;
  1280. if (!noAssert)
  1281. checkOffset(offset, 4, this.length);
  1282. return ieee754.read(this, offset, false, 23, 4);
  1283. };
  1284. Buffer3.prototype.readDoubleLE = function readDoubleLE(offset, noAssert) {
  1285. offset = offset >>> 0;
  1286. if (!noAssert)
  1287. checkOffset(offset, 8, this.length);
  1288. return ieee754.read(this, offset, true, 52, 8);
  1289. };
  1290. Buffer3.prototype.readDoubleBE = function readDoubleBE(offset, noAssert) {
  1291. offset = offset >>> 0;
  1292. if (!noAssert)
  1293. checkOffset(offset, 8, this.length);
  1294. return ieee754.read(this, offset, false, 52, 8);
  1295. };
  1296. function checkInt(buf, value, offset, ext, max, min) {
  1297. if (!Buffer3.isBuffer(buf))
  1298. throw new TypeError('"buffer" argument must be a Buffer instance');
  1299. if (value > max || value < min)
  1300. throw new RangeError('"value" argument is out of bounds');
  1301. if (offset + ext > buf.length)
  1302. throw new RangeError("Index out of range");
  1303. }
  1304. Buffer3.prototype.writeUintLE = Buffer3.prototype.writeUIntLE = function writeUIntLE(value, offset, byteLength2, noAssert) {
  1305. value = +value;
  1306. offset = offset >>> 0;
  1307. byteLength2 = byteLength2 >>> 0;
  1308. if (!noAssert) {
  1309. const maxBytes = Math.pow(2, 8 * byteLength2) - 1;
  1310. checkInt(this, value, offset, byteLength2, maxBytes, 0);
  1311. }
  1312. let mul = 1;
  1313. let i = 0;
  1314. this[offset] = value & 255;
  1315. while (++i < byteLength2 && (mul *= 256)) {
  1316. this[offset + i] = value / mul & 255;
  1317. }
  1318. return offset + byteLength2;
  1319. };
  1320. Buffer3.prototype.writeUintBE = Buffer3.prototype.writeUIntBE = function writeUIntBE(value, offset, byteLength2, noAssert) {
  1321. value = +value;
  1322. offset = offset >>> 0;
  1323. byteLength2 = byteLength2 >>> 0;
  1324. if (!noAssert) {
  1325. const maxBytes = Math.pow(2, 8 * byteLength2) - 1;
  1326. checkInt(this, value, offset, byteLength2, maxBytes, 0);
  1327. }
  1328. let i = byteLength2 - 1;
  1329. let mul = 1;
  1330. this[offset + i] = value & 255;
  1331. while (--i >= 0 && (mul *= 256)) {
  1332. this[offset + i] = value / mul & 255;
  1333. }
  1334. return offset + byteLength2;
  1335. };
  1336. Buffer3.prototype.writeUint8 = Buffer3.prototype.writeUInt8 = function writeUInt8(value, offset, noAssert) {
  1337. value = +value;
  1338. offset = offset >>> 0;
  1339. if (!noAssert)
  1340. checkInt(this, value, offset, 1, 255, 0);
  1341. this[offset] = value & 255;
  1342. return offset + 1;
  1343. };
  1344. Buffer3.prototype.writeUint16LE = Buffer3.prototype.writeUInt16LE = function writeUInt16LE(value, offset, noAssert) {
  1345. value = +value;
  1346. offset = offset >>> 0;
  1347. if (!noAssert)
  1348. checkInt(this, value, offset, 2, 65535, 0);
  1349. this[offset] = value & 255;
  1350. this[offset + 1] = value >>> 8;
  1351. return offset + 2;
  1352. };
  1353. Buffer3.prototype.writeUint16BE = Buffer3.prototype.writeUInt16BE = function writeUInt16BE(value, offset, noAssert) {
  1354. value = +value;
  1355. offset = offset >>> 0;
  1356. if (!noAssert)
  1357. checkInt(this, value, offset, 2, 65535, 0);
  1358. this[offset] = value >>> 8;
  1359. this[offset + 1] = value & 255;
  1360. return offset + 2;
  1361. };
  1362. Buffer3.prototype.writeUint32LE = Buffer3.prototype.writeUInt32LE = function writeUInt32LE(value, offset, noAssert) {
  1363. value = +value;
  1364. offset = offset >>> 0;
  1365. if (!noAssert)
  1366. checkInt(this, value, offset, 4, 4294967295, 0);
  1367. this[offset + 3] = value >>> 24;
  1368. this[offset + 2] = value >>> 16;
  1369. this[offset + 1] = value >>> 8;
  1370. this[offset] = value & 255;
  1371. return offset + 4;
  1372. };
  1373. Buffer3.prototype.writeUint32BE = Buffer3.prototype.writeUInt32BE = function writeUInt32BE(value, offset, noAssert) {
  1374. value = +value;
  1375. offset = offset >>> 0;
  1376. if (!noAssert)
  1377. checkInt(this, value, offset, 4, 4294967295, 0);
  1378. this[offset] = value >>> 24;
  1379. this[offset + 1] = value >>> 16;
  1380. this[offset + 2] = value >>> 8;
  1381. this[offset + 3] = value & 255;
  1382. return offset + 4;
  1383. };
  1384. function wrtBigUInt64LE(buf, value, offset, min, max) {
  1385. checkIntBI(value, min, max, buf, offset, 7);
  1386. let lo = Number(value & BigInt(4294967295));
  1387. buf[offset++] = lo;
  1388. lo = lo >> 8;
  1389. buf[offset++] = lo;
  1390. lo = lo >> 8;
  1391. buf[offset++] = lo;
  1392. lo = lo >> 8;
  1393. buf[offset++] = lo;
  1394. let hi = Number(value >> BigInt(32) & BigInt(4294967295));
  1395. buf[offset++] = hi;
  1396. hi = hi >> 8;
  1397. buf[offset++] = hi;
  1398. hi = hi >> 8;
  1399. buf[offset++] = hi;
  1400. hi = hi >> 8;
  1401. buf[offset++] = hi;
  1402. return offset;
  1403. }
  1404. function wrtBigUInt64BE(buf, value, offset, min, max) {
  1405. checkIntBI(value, min, max, buf, offset, 7);
  1406. let lo = Number(value & BigInt(4294967295));
  1407. buf[offset + 7] = lo;
  1408. lo = lo >> 8;
  1409. buf[offset + 6] = lo;
  1410. lo = lo >> 8;
  1411. buf[offset + 5] = lo;
  1412. lo = lo >> 8;
  1413. buf[offset + 4] = lo;
  1414. let hi = Number(value >> BigInt(32) & BigInt(4294967295));
  1415. buf[offset + 3] = hi;
  1416. hi = hi >> 8;
  1417. buf[offset + 2] = hi;
  1418. hi = hi >> 8;
  1419. buf[offset + 1] = hi;
  1420. hi = hi >> 8;
  1421. buf[offset] = hi;
  1422. return offset + 8;
  1423. }
  1424. Buffer3.prototype.writeBigUInt64LE = defineBigIntMethod(function writeBigUInt64LE(value, offset = 0) {
  1425. return wrtBigUInt64LE(this, value, offset, BigInt(0), BigInt("0xffffffffffffffff"));
  1426. });
  1427. Buffer3.prototype.writeBigUInt64BE = defineBigIntMethod(function writeBigUInt64BE(value, offset = 0) {
  1428. return wrtBigUInt64BE(this, value, offset, BigInt(0), BigInt("0xffffffffffffffff"));
  1429. });
  1430. Buffer3.prototype.writeIntLE = function writeIntLE(value, offset, byteLength2, noAssert) {
  1431. value = +value;
  1432. offset = offset >>> 0;
  1433. if (!noAssert) {
  1434. const limit = Math.pow(2, 8 * byteLength2 - 1);
  1435. checkInt(this, value, offset, byteLength2, limit - 1, -limit);
  1436. }
  1437. let i = 0;
  1438. let mul = 1;
  1439. let sub = 0;
  1440. this[offset] = value & 255;
  1441. while (++i < byteLength2 && (mul *= 256)) {
  1442. if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
  1443. sub = 1;
  1444. }
  1445. this[offset + i] = (value / mul >> 0) - sub & 255;
  1446. }
  1447. return offset + byteLength2;
  1448. };
  1449. Buffer3.prototype.writeIntBE = function writeIntBE(value, offset, byteLength2, noAssert) {
  1450. value = +value;
  1451. offset = offset >>> 0;
  1452. if (!noAssert) {
  1453. const limit = Math.pow(2, 8 * byteLength2 - 1);
  1454. checkInt(this, value, offset, byteLength2, limit - 1, -limit);
  1455. }
  1456. let i = byteLength2 - 1;
  1457. let mul = 1;
  1458. let sub = 0;
  1459. this[offset + i] = value & 255;
  1460. while (--i >= 0 && (mul *= 256)) {
  1461. if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
  1462. sub = 1;
  1463. }
  1464. this[offset + i] = (value / mul >> 0) - sub & 255;
  1465. }
  1466. return offset + byteLength2;
  1467. };
  1468. Buffer3.prototype.writeInt8 = function writeInt8(value, offset, noAssert) {
  1469. value = +value;
  1470. offset = offset >>> 0;
  1471. if (!noAssert)
  1472. checkInt(this, value, offset, 1, 127, -128);
  1473. if (value < 0)
  1474. value = 255 + value + 1;
  1475. this[offset] = value & 255;
  1476. return offset + 1;
  1477. };
  1478. Buffer3.prototype.writeInt16LE = function writeInt16LE(value, offset, noAssert) {
  1479. value = +value;
  1480. offset = offset >>> 0;
  1481. if (!noAssert)
  1482. checkInt(this, value, offset, 2, 32767, -32768);
  1483. this[offset] = value & 255;
  1484. this[offset + 1] = value >>> 8;
  1485. return offset + 2;
  1486. };
  1487. Buffer3.prototype.writeInt16BE = function writeInt16BE(value, offset, noAssert) {
  1488. value = +value;
  1489. offset = offset >>> 0;
  1490. if (!noAssert)
  1491. checkInt(this, value, offset, 2, 32767, -32768);
  1492. this[offset] = value >>> 8;
  1493. this[offset + 1] = value & 255;
  1494. return offset + 2;
  1495. };
  1496. Buffer3.prototype.writeInt32LE = function writeInt32LE(value, offset, noAssert) {
  1497. value = +value;
  1498. offset = offset >>> 0;
  1499. if (!noAssert)
  1500. checkInt(this, value, offset, 4, 2147483647, -2147483648);
  1501. this[offset] = value & 255;
  1502. this[offset + 1] = value >>> 8;
  1503. this[offset + 2] = value >>> 16;
  1504. this[offset + 3] = value >>> 24;
  1505. return offset + 4;
  1506. };
  1507. Buffer3.prototype.writeInt32BE = function writeInt32BE(value, offset, noAssert) {
  1508. value = +value;
  1509. offset = offset >>> 0;
  1510. if (!noAssert)
  1511. checkInt(this, value, offset, 4, 2147483647, -2147483648);
  1512. if (value < 0)
  1513. value = 4294967295 + value + 1;
  1514. this[offset] = value >>> 24;
  1515. this[offset + 1] = value >>> 16;
  1516. this[offset + 2] = value >>> 8;
  1517. this[offset + 3] = value & 255;
  1518. return offset + 4;
  1519. };
  1520. Buffer3.prototype.writeBigInt64LE = defineBigIntMethod(function writeBigInt64LE(value, offset = 0) {
  1521. return wrtBigUInt64LE(this, value, offset, -BigInt("0x8000000000000000"), BigInt("0x7fffffffffffffff"));
  1522. });
  1523. Buffer3.prototype.writeBigInt64BE = defineBigIntMethod(function writeBigInt64BE(value, offset = 0) {
  1524. return wrtBigUInt64BE(this, value, offset, -BigInt("0x8000000000000000"), BigInt("0x7fffffffffffffff"));
  1525. });
  1526. function checkIEEE754(buf, value, offset, ext, max, min) {
  1527. if (offset + ext > buf.length)
  1528. throw new RangeError("Index out of range");
  1529. if (offset < 0)
  1530. throw new RangeError("Index out of range");
  1531. }
  1532. function writeFloat(buf, value, offset, littleEndian, noAssert) {
  1533. value = +value;
  1534. offset = offset >>> 0;
  1535. if (!noAssert) {
  1536. checkIEEE754(buf, value, offset, 4, 34028234663852886e22, -34028234663852886e22);
  1537. }
  1538. ieee754.write(buf, value, offset, littleEndian, 23, 4);
  1539. return offset + 4;
  1540. }
  1541. Buffer3.prototype.writeFloatLE = function writeFloatLE(value, offset, noAssert) {
  1542. return writeFloat(this, value, offset, true, noAssert);
  1543. };
  1544. Buffer3.prototype.writeFloatBE = function writeFloatBE(value, offset, noAssert) {
  1545. return writeFloat(this, value, offset, false, noAssert);
  1546. };
  1547. function writeDouble(buf, value, offset, littleEndian, noAssert) {
  1548. value = +value;
  1549. offset = offset >>> 0;
  1550. if (!noAssert) {
  1551. checkIEEE754(buf, value, offset, 8, 17976931348623157e292, -17976931348623157e292);
  1552. }
  1553. ieee754.write(buf, value, offset, littleEndian, 52, 8);
  1554. return offset + 8;
  1555. }
  1556. Buffer3.prototype.writeDoubleLE = function writeDoubleLE(value, offset, noAssert) {
  1557. return writeDouble(this, value, offset, true, noAssert);
  1558. };
  1559. Buffer3.prototype.writeDoubleBE = function writeDoubleBE(value, offset, noAssert) {
  1560. return writeDouble(this, value, offset, false, noAssert);
  1561. };
  1562. Buffer3.prototype.copy = function copy(target, targetStart, start, end) {
  1563. if (!Buffer3.isBuffer(target))
  1564. throw new TypeError("argument should be a Buffer");
  1565. if (!start)
  1566. start = 0;
  1567. if (!end && end !== 0)
  1568. end = this.length;
  1569. if (targetStart >= target.length)
  1570. targetStart = target.length;
  1571. if (!targetStart)
  1572. targetStart = 0;
  1573. if (end > 0 && end < start)
  1574. end = start;
  1575. if (end === start)
  1576. return 0;
  1577. if (target.length === 0 || this.length === 0)
  1578. return 0;
  1579. if (targetStart < 0) {
  1580. throw new RangeError("targetStart out of bounds");
  1581. }
  1582. if (start < 0 || start >= this.length)
  1583. throw new RangeError("Index out of range");
  1584. if (end < 0)
  1585. throw new RangeError("sourceEnd out of bounds");
  1586. if (end > this.length)
  1587. end = this.length;
  1588. if (target.length - targetStart < end - start) {
  1589. end = target.length - targetStart + start;
  1590. }
  1591. const len = end - start;
  1592. if (this === target && typeof Uint8Array.prototype.copyWithin === "function") {
  1593. this.copyWithin(targetStart, start, end);
  1594. } else {
  1595. Uint8Array.prototype.set.call(
  1596. target,
  1597. this.subarray(start, end),
  1598. targetStart
  1599. );
  1600. }
  1601. return len;
  1602. };
  1603. Buffer3.prototype.fill = function fill(val, start, end, encoding) {
  1604. if (typeof val === "string") {
  1605. if (typeof start === "string") {
  1606. encoding = start;
  1607. start = 0;
  1608. end = this.length;
  1609. } else if (typeof end === "string") {
  1610. encoding = end;
  1611. end = this.length;
  1612. }
  1613. if (encoding !== void 0 && typeof encoding !== "string") {
  1614. throw new TypeError("encoding must be a string");
  1615. }
  1616. if (typeof encoding === "string" && !Buffer3.isEncoding(encoding)) {
  1617. throw new TypeError("Unknown encoding: " + encoding);
  1618. }
  1619. if (val.length === 1) {
  1620. const code = val.charCodeAt(0);
  1621. if (encoding === "utf8" && code < 128 || encoding === "latin1") {
  1622. val = code;
  1623. }
  1624. }
  1625. } else if (typeof val === "number") {
  1626. val = val & 255;
  1627. } else if (typeof val === "boolean") {
  1628. val = Number(val);
  1629. }
  1630. if (start < 0 || this.length < start || this.length < end) {
  1631. throw new RangeError("Out of range index");
  1632. }
  1633. if (end <= start) {
  1634. return this;
  1635. }
  1636. start = start >>> 0;
  1637. end = end === void 0 ? this.length : end >>> 0;
  1638. if (!val)
  1639. val = 0;
  1640. let i;
  1641. if (typeof val === "number") {
  1642. for (i = start; i < end; ++i) {
  1643. this[i] = val;
  1644. }
  1645. } else {
  1646. const bytes = Buffer3.isBuffer(val) ? val : Buffer3.from(val, encoding);
  1647. const len = bytes.length;
  1648. if (len === 0) {
  1649. throw new TypeError('The value "' + val + '" is invalid for argument "value"');
  1650. }
  1651. for (i = 0; i < end - start; ++i) {
  1652. this[i + start] = bytes[i % len];
  1653. }
  1654. }
  1655. return this;
  1656. };
  1657. var errors = {};
  1658. function E(sym, getMessage, Base) {
  1659. errors[sym] = class NodeError extends Base {
  1660. constructor() {
  1661. super();
  1662. Object.defineProperty(this, "message", {
  1663. value: getMessage.apply(this, arguments),
  1664. writable: true,
  1665. configurable: true
  1666. });
  1667. this.name = `${this.name} [${sym}]`;
  1668. this.stack;
  1669. delete this.name;
  1670. }
  1671. get code() {
  1672. return sym;
  1673. }
  1674. set code(value) {
  1675. Object.defineProperty(this, "code", {
  1676. configurable: true,
  1677. enumerable: true,
  1678. value,
  1679. writable: true
  1680. });
  1681. }
  1682. toString() {
  1683. return `${this.name} [${sym}]: ${this.message}`;
  1684. }
  1685. };
  1686. }
  1687. E(
  1688. "ERR_BUFFER_OUT_OF_BOUNDS",
  1689. function(name) {
  1690. if (name) {
  1691. return `${name} is outside of buffer bounds`;
  1692. }
  1693. return "Attempt to access memory outside buffer bounds";
  1694. },
  1695. RangeError
  1696. );
  1697. E(
  1698. "ERR_INVALID_ARG_TYPE",
  1699. function(name, actual) {
  1700. return `The "${name}" argument must be of type number. Received type ${typeof actual}`;
  1701. },
  1702. TypeError
  1703. );
  1704. E(
  1705. "ERR_OUT_OF_RANGE",
  1706. function(str, range, input) {
  1707. let msg = `The value of "${str}" is out of range.`;
  1708. let received = input;
  1709. if (Number.isInteger(input) && Math.abs(input) > 2 ** 32) {
  1710. received = addNumericalSeparator(String(input));
  1711. } else if (typeof input === "bigint") {
  1712. received = String(input);
  1713. if (input > BigInt(2) ** BigInt(32) || input < -(BigInt(2) ** BigInt(32))) {
  1714. received = addNumericalSeparator(received);
  1715. }
  1716. received += "n";
  1717. }
  1718. msg += ` It must be ${range}. Received ${received}`;
  1719. return msg;
  1720. },
  1721. RangeError
  1722. );
  1723. function addNumericalSeparator(val) {
  1724. let res = "";
  1725. let i = val.length;
  1726. const start = val[0] === "-" ? 1 : 0;
  1727. for (; i >= start + 4; i -= 3) {
  1728. res = `_${val.slice(i - 3, i)}${res}`;
  1729. }
  1730. return `${val.slice(0, i)}${res}`;
  1731. }
  1732. function checkBounds(buf, offset, byteLength2) {
  1733. validateNumber(offset, "offset");
  1734. if (buf[offset] === void 0 || buf[offset + byteLength2] === void 0) {
  1735. boundsError(offset, buf.length - (byteLength2 + 1));
  1736. }
  1737. }
  1738. function checkIntBI(value, min, max, buf, offset, byteLength2) {
  1739. if (value > max || value < min) {
  1740. const n = typeof min === "bigint" ? "n" : "";
  1741. let range;
  1742. if (byteLength2 > 3) {
  1743. if (min === 0 || min === BigInt(0)) {
  1744. range = `>= 0${n} and < 2${n} ** ${(byteLength2 + 1) * 8}${n}`;
  1745. } else {
  1746. range = `>= -(2${n} ** ${(byteLength2 + 1) * 8 - 1}${n}) and < 2 ** ${(byteLength2 + 1) * 8 - 1}${n}`;
  1747. }
  1748. } else {
  1749. range = `>= ${min}${n} and <= ${max}${n}`;
  1750. }
  1751. throw new errors.ERR_OUT_OF_RANGE("value", range, value);
  1752. }
  1753. checkBounds(buf, offset, byteLength2);
  1754. }
  1755. function validateNumber(value, name) {
  1756. if (typeof value !== "number") {
  1757. throw new errors.ERR_INVALID_ARG_TYPE(name, "number", value);
  1758. }
  1759. }
  1760. function boundsError(value, length, type) {
  1761. if (Math.floor(value) !== value) {
  1762. validateNumber(value, type);
  1763. throw new errors.ERR_OUT_OF_RANGE(type || "offset", "an integer", value);
  1764. }
  1765. if (length < 0) {
  1766. throw new errors.ERR_BUFFER_OUT_OF_BOUNDS();
  1767. }
  1768. throw new errors.ERR_OUT_OF_RANGE(
  1769. type || "offset",
  1770. `>= ${type ? 1 : 0} and <= ${length}`,
  1771. value
  1772. );
  1773. }
  1774. var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g;
  1775. function base64clean(str) {
  1776. str = str.split("=")[0];
  1777. str = str.trim().replace(INVALID_BASE64_RE, "");
  1778. if (str.length < 2)
  1779. return "";
  1780. while (str.length % 4 !== 0) {
  1781. str = str + "=";
  1782. }
  1783. return str;
  1784. }
  1785. function utf8ToBytes(string, units) {
  1786. units = units || Infinity;
  1787. let codePoint;
  1788. const length = string.length;
  1789. let leadSurrogate = null;
  1790. const bytes = [];
  1791. for (let i = 0; i < length; ++i) {
  1792. codePoint = string.charCodeAt(i);
  1793. if (codePoint > 55295 && codePoint < 57344) {
  1794. if (!leadSurrogate) {
  1795. if (codePoint > 56319) {
  1796. if ((units -= 3) > -1)
  1797. bytes.push(239, 191, 189);
  1798. continue;
  1799. } else if (i + 1 === length) {
  1800. if ((units -= 3) > -1)
  1801. bytes.push(239, 191, 189);
  1802. continue;
  1803. }
  1804. leadSurrogate = codePoint;
  1805. continue;
  1806. }
  1807. if (codePoint < 56320) {
  1808. if ((units -= 3) > -1)
  1809. bytes.push(239, 191, 189);
  1810. leadSurrogate = codePoint;
  1811. continue;
  1812. }
  1813. codePoint = (leadSurrogate - 55296 << 10 | codePoint - 56320) + 65536;
  1814. } else if (leadSurrogate) {
  1815. if ((units -= 3) > -1)
  1816. bytes.push(239, 191, 189);
  1817. }
  1818. leadSurrogate = null;
  1819. if (codePoint < 128) {
  1820. if ((units -= 1) < 0)
  1821. break;
  1822. bytes.push(codePoint);
  1823. } else if (codePoint < 2048) {
  1824. if ((units -= 2) < 0)
  1825. break;
  1826. bytes.push(
  1827. codePoint >> 6 | 192,
  1828. codePoint & 63 | 128
  1829. );
  1830. } else if (codePoint < 65536) {
  1831. if ((units -= 3) < 0)
  1832. break;
  1833. bytes.push(
  1834. codePoint >> 12 | 224,
  1835. codePoint >> 6 & 63 | 128,
  1836. codePoint & 63 | 128
  1837. );
  1838. } else if (codePoint < 1114112) {
  1839. if ((units -= 4) < 0)
  1840. break;
  1841. bytes.push(
  1842. codePoint >> 18 | 240,
  1843. codePoint >> 12 & 63 | 128,
  1844. codePoint >> 6 & 63 | 128,
  1845. codePoint & 63 | 128
  1846. );
  1847. } else {
  1848. throw new Error("Invalid code point");
  1849. }
  1850. }
  1851. return bytes;
  1852. }
  1853. function asciiToBytes(str) {
  1854. const byteArray = [];
  1855. for (let i = 0; i < str.length; ++i) {
  1856. byteArray.push(str.charCodeAt(i) & 255);
  1857. }
  1858. return byteArray;
  1859. }
  1860. function utf16leToBytes(str, units) {
  1861. let c, hi, lo;
  1862. const byteArray = [];
  1863. for (let i = 0; i < str.length; ++i) {
  1864. if ((units -= 2) < 0)
  1865. break;
  1866. c = str.charCodeAt(i);
  1867. hi = c >> 8;
  1868. lo = c % 256;
  1869. byteArray.push(lo);
  1870. byteArray.push(hi);
  1871. }
  1872. return byteArray;
  1873. }
  1874. function base64ToBytes(str) {
  1875. return base64.toByteArray(base64clean(str));
  1876. }
  1877. function blitBuffer(src, dst, offset, length) {
  1878. let i;
  1879. for (i = 0; i < length; ++i) {
  1880. if (i + offset >= dst.length || i >= src.length)
  1881. break;
  1882. dst[i + offset] = src[i];
  1883. }
  1884. return i;
  1885. }
  1886. function isInstance(obj, type) {
  1887. return obj instanceof type || obj != null && obj.constructor != null && obj.constructor.name != null && obj.constructor.name === type.name;
  1888. }
  1889. function numberIsNaN(obj) {
  1890. return obj !== obj;
  1891. }
  1892. var hexSliceLookupTable = function() {
  1893. const alphabet = "0123456789abcdef";
  1894. const table = new Array(256);
  1895. for (let i = 0; i < 16; ++i) {
  1896. const i16 = i * 16;
  1897. for (let j = 0; j < 16; ++j) {
  1898. table[i16 + j] = alphabet[i] + alphabet[j];
  1899. }
  1900. }
  1901. return table;
  1902. }();
  1903. function defineBigIntMethod(fn) {
  1904. return typeof BigInt === "undefined" ? BufferBigIntNotDefined : fn;
  1905. }
  1906. function BufferBigIntNotDefined() {
  1907. throw new Error("BigInt not supported");
  1908. }
  1909. }
  1910. });
  1911. // routes-module:root.jsx?worker
  1912. var require_root = __commonJS({
  1913. "routes-module:root.jsx?worker"(exports, module) {
  1914. module.exports = {};
  1915. }
  1916. });
  1917. // routes-module:routes/manifest[.]webmanifest.ts?worker
  1918. var require_manifest_webmanifest = __commonJS({
  1919. "routes-module:routes/manifest[.]webmanifest.ts?worker"(exports, module) {
  1920. module.exports = {};
  1921. }
  1922. });
  1923. // node_modules/@remix-run/router/dist/router.js
  1924. var router_exports = {};
  1925. __export(router_exports, {
  1926. AbortedDeferredError: () => AbortedDeferredError,
  1927. Action: () => Action,
  1928. IDLE_BLOCKER: () => IDLE_BLOCKER,
  1929. IDLE_FETCHER: () => IDLE_FETCHER,
  1930. IDLE_NAVIGATION: () => IDLE_NAVIGATION,
  1931. UNSAFE_DEFERRED_SYMBOL: () => UNSAFE_DEFERRED_SYMBOL,
  1932. UNSAFE_DeferredData: () => DeferredData,
  1933. UNSAFE_ErrorResponseImpl: () => ErrorResponseImpl,
  1934. UNSAFE_convertRouteMatchToUiMatch: () => convertRouteMatchToUiMatch,
  1935. UNSAFE_convertRoutesToDataRoutes: () => convertRoutesToDataRoutes,
  1936. UNSAFE_getResolveToMatches: () => getResolveToMatches,
  1937. UNSAFE_invariant: () => invariant,
  1938. UNSAFE_warning: () => warning,
  1939. createBrowserHistory: () => createBrowserHistory,
  1940. createHashHistory: () => createHashHistory,
  1941. createMemoryHistory: () => createMemoryHistory,
  1942. createPath: () => createPath,
  1943. createRouter: () => createRouter,
  1944. createStaticHandler: () => createStaticHandler,
  1945. defer: () => defer,
  1946. generatePath: () => generatePath,
  1947. getStaticContextFromError: () => getStaticContextFromError,
  1948. getToPathname: () => getToPathname,
  1949. isDeferredData: () => isDeferredData,
  1950. isRouteErrorResponse: () => isRouteErrorResponse,
  1951. joinPaths: () => joinPaths,
  1952. json: () => json,
  1953. matchPath: () => matchPath,
  1954. matchRoutes: () => matchRoutes,
  1955. normalizePathname: () => normalizePathname,
  1956. parsePath: () => parsePath,
  1957. redirect: () => redirect,
  1958. redirectDocument: () => redirectDocument,
  1959. resolvePath: () => resolvePath,
  1960. resolveTo: () => resolveTo,
  1961. stripBasename: () => stripBasename
  1962. });
  1963. function _extends() {
  1964. _extends = Object.assign ? Object.assign.bind() : function(target) {
  1965. for (var i = 1; i < arguments.length; i++) {
  1966. var source = arguments[i];
  1967. for (var key in source) {
  1968. if (Object.prototype.hasOwnProperty.call(source, key)) {
  1969. target[key] = source[key];
  1970. }
  1971. }
  1972. }
  1973. return target;
  1974. };
  1975. return _extends.apply(this, arguments);
  1976. }
  1977. function createMemoryHistory(options) {
  1978. if (options === void 0) {
  1979. options = {};
  1980. }
  1981. let {
  1982. initialEntries = ["/"],
  1983. initialIndex,
  1984. v5Compat = false
  1985. } = options;
  1986. let entries;
  1987. entries = initialEntries.map((entry2, index2) => createMemoryLocation(entry2, typeof entry2 === "string" ? null : entry2.state, index2 === 0 ? "default" : void 0));
  1988. let index = clampIndex(initialIndex == null ? entries.length - 1 : initialIndex);
  1989. let action = Action.Pop;
  1990. let listener = null;
  1991. function clampIndex(n) {
  1992. return Math.min(Math.max(n, 0), entries.length - 1);
  1993. }
  1994. function getCurrentLocation() {
  1995. return entries[index];
  1996. }
  1997. function createMemoryLocation(to, state, key) {
  1998. if (state === void 0) {
  1999. state = null;
  2000. }
  2001. let location = createLocation(entries ? getCurrentLocation().pathname : "/", to, state, key);
  2002. warning(location.pathname.charAt(0) === "/", "relative pathnames are not supported in memory history: " + JSON.stringify(to));
  2003. return location;
  2004. }
  2005. function createHref(to) {
  2006. return typeof to === "string" ? to : createPath(to);
  2007. }
  2008. let history = {
  2009. get index() {
  2010. return index;
  2011. },
  2012. get action() {
  2013. return action;
  2014. },
  2015. get location() {
  2016. return getCurrentLocation();
  2017. },
  2018. createHref,
  2019. createURL(to) {
  2020. return new URL(createHref(to), "http://localhost");
  2021. },
  2022. encodeLocation(to) {
  2023. let path = typeof to === "string" ? parsePath(to) : to;
  2024. return {
  2025. pathname: path.pathname || "",
  2026. search: path.search || "",
  2027. hash: path.hash || ""
  2028. };
  2029. },
  2030. push(to, state) {
  2031. action = Action.Push;
  2032. let nextLocation = createMemoryLocation(to, state);
  2033. index += 1;
  2034. entries.splice(index, entries.length, nextLocation);
  2035. if (v5Compat && listener) {
  2036. listener({
  2037. action,
  2038. location: nextLocation,
  2039. delta: 1
  2040. });
  2041. }
  2042. },
  2043. replace(to, state) {
  2044. action = Action.Replace;
  2045. let nextLocation = createMemoryLocation(to, state);
  2046. entries[index] = nextLocation;
  2047. if (v5Compat && listener) {
  2048. listener({
  2049. action,
  2050. location: nextLocation,
  2051. delta: 0
  2052. });
  2053. }
  2054. },
  2055. go(delta) {
  2056. action = Action.Pop;
  2057. let nextIndex = clampIndex(index + delta);
  2058. let nextLocation = entries[nextIndex];
  2059. index = nextIndex;
  2060. if (listener) {
  2061. listener({
  2062. action,
  2063. location: nextLocation,
  2064. delta
  2065. });
  2066. }
  2067. },
  2068. listen(fn) {
  2069. listener = fn;
  2070. return () => {
  2071. listener = null;
  2072. };
  2073. }
  2074. };
  2075. return history;
  2076. }
  2077. function createBrowserHistory(options) {
  2078. if (options === void 0) {
  2079. options = {};
  2080. }
  2081. function createBrowserLocation(window2, globalHistory) {
  2082. let {
  2083. pathname,
  2084. search,
  2085. hash
  2086. } = window2.location;
  2087. return createLocation(
  2088. "",
  2089. {
  2090. pathname,
  2091. search,
  2092. hash
  2093. },
  2094. // state defaults to `null` because `window.history.state` does
  2095. globalHistory.state && globalHistory.state.usr || null,
  2096. globalHistory.state && globalHistory.state.key || "default"
  2097. );
  2098. }
  2099. function createBrowserHref(window2, to) {
  2100. return typeof to === "string" ? to : createPath(to);
  2101. }
  2102. return getUrlBasedHistory(createBrowserLocation, createBrowserHref, null, options);
  2103. }
  2104. function createHashHistory(options) {
  2105. if (options === void 0) {
  2106. options = {};
  2107. }
  2108. function createHashLocation(window2, globalHistory) {
  2109. let {
  2110. pathname = "/",
  2111. search = "",
  2112. hash = ""
  2113. } = parsePath(window2.location.hash.substr(1));
  2114. if (!pathname.startsWith("/") && !pathname.startsWith(".")) {
  2115. pathname = "/" + pathname;
  2116. }
  2117. return createLocation(
  2118. "",
  2119. {
  2120. pathname,
  2121. search,
  2122. hash
  2123. },
  2124. // state defaults to `null` because `window.history.state` does
  2125. globalHistory.state && globalHistory.state.usr || null,
  2126. globalHistory.state && globalHistory.state.key || "default"
  2127. );
  2128. }
  2129. function createHashHref(window2, to) {
  2130. let base = window2.document.querySelector("base");
  2131. let href = "";
  2132. if (base && base.getAttribute("href")) {
  2133. let url = window2.location.href;
  2134. let hashIndex = url.indexOf("#");
  2135. href = hashIndex === -1 ? url : url.slice(0, hashIndex);
  2136. }
  2137. return href + "#" + (typeof to === "string" ? to : createPath(to));
  2138. }
  2139. function validateHashLocation(location, to) {
  2140. warning(location.pathname.charAt(0) === "/", "relative pathnames are not supported in hash history.push(" + JSON.stringify(to) + ")");
  2141. }
  2142. return getUrlBasedHistory(createHashLocation, createHashHref, validateHashLocation, options);
  2143. }
  2144. function invariant(value, message) {
  2145. if (value === false || value === null || typeof value === "undefined") {
  2146. throw new Error(message);
  2147. }
  2148. }
  2149. function warning(cond, message) {
  2150. if (!cond) {
  2151. if (typeof console !== "undefined")
  2152. console.warn(message);
  2153. try {
  2154. throw new Error(message);
  2155. } catch (e) {
  2156. }
  2157. }
  2158. }
  2159. function createKey() {
  2160. return Math.random().toString(36).substr(2, 8);
  2161. }
  2162. function getHistoryState(location, index) {
  2163. return {
  2164. usr: location.state,
  2165. key: location.key,
  2166. idx: index
  2167. };
  2168. }
  2169. function createLocation(current, to, state, key) {
  2170. if (state === void 0) {
  2171. state = null;
  2172. }
  2173. let location = _extends({
  2174. pathname: typeof current === "string" ? current : current.pathname,
  2175. search: "",
  2176. hash: ""
  2177. }, typeof to === "string" ? parsePath(to) : to, {
  2178. state,
  2179. // TODO: This could be cleaned up. push/replace should probably just take
  2180. // full Locations now and avoid the need to run through this flow at all
  2181. // But that's a pretty big refactor to the current test suite so going to
  2182. // keep as is for the time being and just let any incoming keys take precedence
  2183. key: to && to.key || key || createKey()
  2184. });
  2185. return location;
  2186. }
  2187. function createPath(_ref) {
  2188. let {
  2189. pathname = "/",
  2190. search = "",
  2191. hash = ""
  2192. } = _ref;
  2193. if (search && search !== "?")
  2194. pathname += search.charAt(0) === "?" ? search : "?" + search;
  2195. if (hash && hash !== "#")
  2196. pathname += hash.charAt(0) === "#" ? hash : "#" + hash;
  2197. return pathname;
  2198. }
  2199. function parsePath(path) {
  2200. let parsedPath = {};
  2201. if (path) {
  2202. let hashIndex = path.indexOf("#");
  2203. if (hashIndex >= 0) {
  2204. parsedPath.hash = path.substr(hashIndex);
  2205. path = path.substr(0, hashIndex);
  2206. }
  2207. let searchIndex = path.indexOf("?");
  2208. if (searchIndex >= 0) {
  2209. parsedPath.search = path.substr(searchIndex);
  2210. path = path.substr(0, searchIndex);
  2211. }
  2212. if (path) {
  2213. parsedPath.pathname = path;
  2214. }
  2215. }
  2216. return parsedPath;
  2217. }
  2218. function getUrlBasedHistory(getLocation, createHref, validateLocation, options) {
  2219. if (options === void 0) {
  2220. options = {};
  2221. }
  2222. let {
  2223. window: window2 = document.defaultView,
  2224. v5Compat = false
  2225. } = options;
  2226. let globalHistory = window2.history;
  2227. let action = Action.Pop;
  2228. let listener = null;
  2229. let index = getIndex();
  2230. if (index == null) {
  2231. index = 0;
  2232. globalHistory.replaceState(_extends({}, globalHistory.state, {
  2233. idx: index
  2234. }), "");
  2235. }
  2236. function getIndex() {
  2237. let state = globalHistory.state || {
  2238. idx: null
  2239. };
  2240. return state.idx;
  2241. }
  2242. function handlePop() {
  2243. action = Action.Pop;
  2244. let nextIndex = getIndex();
  2245. let delta = nextIndex == null ? null : nextIndex - index;
  2246. index = nextIndex;
  2247. if (listener) {
  2248. listener({
  2249. action,
  2250. location: history.location,
  2251. delta
  2252. });
  2253. }
  2254. }
  2255. function push(to, state) {
  2256. action = Action.Push;
  2257. let location = createLocation(history.location, to, state);
  2258. if (validateLocation)
  2259. validateLocation(location, to);
  2260. index = getIndex() + 1;
  2261. let historyState = getHistoryState(location, index);
  2262. let url = history.createHref(location);
  2263. try {
  2264. globalHistory.pushState(historyState, "", url);
  2265. } catch (error) {
  2266. if (error instanceof DOMException && error.name === "DataCloneError") {
  2267. throw error;
  2268. }
  2269. window2.location.assign(url);
  2270. }
  2271. if (v5Compat && listener) {
  2272. listener({
  2273. action,
  2274. location: history.location,
  2275. delta: 1
  2276. });
  2277. }
  2278. }
  2279. function replace(to, state) {
  2280. action = Action.Replace;
  2281. let location = createLocation(history.location, to, state);
  2282. if (validateLocation)
  2283. validateLocation(location, to);
  2284. index = getIndex();
  2285. let historyState = getHistoryState(location, index);
  2286. let url = history.createHref(location);
  2287. globalHistory.replaceState(historyState, "", url);
  2288. if (v5Compat && listener) {
  2289. listener({
  2290. action,
  2291. location: history.location,
  2292. delta: 0
  2293. });
  2294. }
  2295. }
  2296. function createURL(to) {
  2297. let base = window2.location.origin !== "null" ? window2.location.origin : window2.location.href;
  2298. let href = typeof to === "string" ? to : createPath(to);
  2299. invariant(base, "No window.location.(origin|href) available to create URL for href: " + href);
  2300. return new URL(href, base);
  2301. }
  2302. let history = {
  2303. get action() {
  2304. return action;
  2305. },
  2306. get location() {
  2307. return getLocation(window2, globalHistory);
  2308. },
  2309. listen(fn) {
  2310. if (listener) {
  2311. throw new Error("A history only accepts one active listener");
  2312. }
  2313. window2.addEventListener(PopStateEventType, handlePop);
  2314. listener = fn;
  2315. return () => {
  2316. window2.removeEventListener(PopStateEventType, handlePop);
  2317. listener = null;
  2318. };
  2319. },
  2320. createHref(to) {
  2321. return createHref(window2, to);
  2322. },
  2323. createURL,
  2324. encodeLocation(to) {
  2325. let url = createURL(to);
  2326. return {
  2327. pathname: url.pathname,
  2328. search: url.search,
  2329. hash: url.hash
  2330. };
  2331. },
  2332. push,
  2333. replace,
  2334. go(n) {
  2335. return globalHistory.go(n);
  2336. }
  2337. };
  2338. return history;
  2339. }
  2340. function isIndexRoute(route) {
  2341. return route.index === true;
  2342. }
  2343. function convertRoutesToDataRoutes(routes2, mapRouteProperties, parentPath, manifest) {
  2344. if (parentPath === void 0) {
  2345. parentPath = [];
  2346. }
  2347. if (manifest === void 0) {
  2348. manifest = {};
  2349. }
  2350. return routes2.map((route, index) => {
  2351. let treePath = [...parentPath, index];
  2352. let id = typeof route.id === "string" ? route.id : treePath.join("-");
  2353. invariant(route.index !== true || !route.children, "Cannot specify children on an index route");
  2354. invariant(!manifest[id], 'Found a route id collision on id "' + id + `". Route id's must be globally unique within Data Router usages`);
  2355. if (isIndexRoute(route)) {
  2356. let indexRoute = _extends({}, route, mapRouteProperties(route), {
  2357. id
  2358. });
  2359. manifest[id] = indexRoute;
  2360. return indexRoute;
  2361. } else {
  2362. let pathOrLayoutRoute = _extends({}, route, mapRouteProperties(route), {
  2363. id,
  2364. children: void 0
  2365. });
  2366. manifest[id] = pathOrLayoutRoute;
  2367. if (route.children) {
  2368. pathOrLayoutRoute.children = convertRoutesToDataRoutes(route.children, mapRouteProperties, treePath, manifest);
  2369. }
  2370. return pathOrLayoutRoute;
  2371. }
  2372. });
  2373. }
  2374. function matchRoutes(routes2, locationArg, basename) {
  2375. if (basename === void 0) {
  2376. basename = "/";
  2377. }
  2378. let location = typeof locationArg === "string" ? parsePath(locationArg) : locationArg;
  2379. let pathname = stripBasename(location.pathname || "/", basename);
  2380. if (pathname == null) {
  2381. return null;
  2382. }
  2383. let branches = flattenRoutes(routes2);
  2384. rankRouteBranches(branches);
  2385. let matches = null;
  2386. for (let i = 0; matches == null && i < branches.length; ++i) {
  2387. matches = matchRouteBranch(
  2388. branches[i],
  2389. // Incoming pathnames are generally encoded from either window.location
  2390. // or from router.navigate, but we want to match against the unencoded
  2391. // paths in the route definitions. Memory router locations won't be
  2392. // encoded here but there also shouldn't be anything to decode so this
  2393. // should be a safe operation. This avoids needing matchRoutes to be
  2394. // history-aware.
  2395. safelyDecodeURI(pathname)
  2396. );
  2397. }
  2398. return matches;
  2399. }
  2400. function convertRouteMatchToUiMatch(match, loaderData) {
  2401. let {
  2402. route,
  2403. pathname,
  2404. params
  2405. } = match;
  2406. return {
  2407. id: route.id,
  2408. pathname,
  2409. params,
  2410. data: loaderData[route.id],
  2411. handle: route.handle
  2412. };
  2413. }
  2414. function flattenRoutes(routes2, branches, parentsMeta, parentPath) {
  2415. if (branches === void 0) {
  2416. branches = [];
  2417. }
  2418. if (parentsMeta === void 0) {
  2419. parentsMeta = [];
  2420. }
  2421. if (parentPath === void 0) {
  2422. parentPath = "";
  2423. }
  2424. let flattenRoute = (route, index, relativePath) => {
  2425. let meta = {
  2426. relativePath: relativePath === void 0 ? route.path || "" : relativePath,
  2427. caseSensitive: route.caseSensitive === true,
  2428. childrenIndex: index,
  2429. route
  2430. };
  2431. if (meta.relativePath.startsWith("/")) {
  2432. invariant(meta.relativePath.startsWith(parentPath), 'Absolute route path "' + meta.relativePath + '" nested under path ' + ('"' + parentPath + '" is not valid. An absolute child route path ') + "must start with the combined path of all its parent routes.");
  2433. meta.relativePath = meta.relativePath.slice(parentPath.length);
  2434. }
  2435. let path = joinPaths([parentPath, meta.relativePath]);
  2436. let routesMeta = parentsMeta.concat(meta);
  2437. if (route.children && route.children.length > 0) {
  2438. invariant(
  2439. // Our types know better, but runtime JS may not!
  2440. // @ts-expect-error
  2441. route.index !== true,
  2442. "Index routes must not have child routes. Please remove " + ('all child routes from route path "' + path + '".')
  2443. );
  2444. flattenRoutes(route.children, branches, routesMeta, path);
  2445. }
  2446. if (route.path == null && !route.index) {
  2447. return;
  2448. }
  2449. branches.push({
  2450. path,
  2451. score: computeScore(path, route.index),
  2452. routesMeta
  2453. });
  2454. };
  2455. routes2.forEach((route, index) => {
  2456. var _route$path;
  2457. if (route.path === "" || !((_route$path = route.path) != null && _route$path.includes("?"))) {
  2458. flattenRoute(route, index);
  2459. } else {
  2460. for (let exploded of explodeOptionalSegments(route.path)) {
  2461. flattenRoute(route, index, exploded);
  2462. }
  2463. }
  2464. });
  2465. return branches;
  2466. }
  2467. function explodeOptionalSegments(path) {
  2468. let segments = path.split("/");
  2469. if (segments.length === 0)
  2470. return [];
  2471. let [first, ...rest] = segments;
  2472. let isOptional = first.endsWith("?");
  2473. let required = first.replace(/\?$/, "");
  2474. if (rest.length === 0) {
  2475. return isOptional ? [required, ""] : [required];
  2476. }
  2477. let restExploded = explodeOptionalSegments(rest.join("/"));
  2478. let result = [];
  2479. result.push(...restExploded.map((subpath) => subpath === "" ? required : [required, subpath].join("/")));
  2480. if (isOptional) {
  2481. result.push(...restExploded);
  2482. }
  2483. return result.map((exploded) => path.startsWith("/") && exploded === "" ? "/" : exploded);
  2484. }
  2485. function rankRouteBranches(branches) {
  2486. branches.sort((a, b2) => a.score !== b2.score ? b2.score - a.score : compareIndexes(a.routesMeta.map((meta) => meta.childrenIndex), b2.routesMeta.map((meta) => meta.childrenIndex)));
  2487. }
  2488. function computeScore(path, index) {
  2489. let segments = path.split("/");
  2490. let initialScore = segments.length;
  2491. if (segments.some(isSplat)) {
  2492. initialScore += splatPenalty;
  2493. }
  2494. if (index) {
  2495. initialScore += indexRouteValue;
  2496. }
  2497. return segments.filter((s) => !isSplat(s)).reduce((score, segment) => score + (paramRe.test(segment) ? dynamicSegmentValue : segment === "" ? emptySegmentValue : staticSegmentValue), initialScore);
  2498. }
  2499. function compareIndexes(a, b2) {
  2500. let siblings = a.length === b2.length && a.slice(0, -1).every((n, i) => n === b2[i]);
  2501. return siblings ? (
  2502. // If two routes are siblings, we should try to match the earlier sibling
  2503. // first. This allows people to have fine-grained control over the matching
  2504. // behavior by simply putting routes with identical paths in the order they
  2505. // want them tried.
  2506. a[a.length - 1] - b2[b2.length - 1]
  2507. ) : (
  2508. // Otherwise, it doesn't really make sense to rank non-siblings by index,
  2509. // so they sort equally.
  2510. 0
  2511. );
  2512. }
  2513. function matchRouteBranch(branch, pathname) {
  2514. let {
  2515. routesMeta
  2516. } = branch;
  2517. let matchedParams = {};
  2518. let matchedPathname = "/";
  2519. let matches = [];
  2520. for (let i = 0; i < routesMeta.length; ++i) {
  2521. let meta = routesMeta[i];
  2522. let end = i === routesMeta.length - 1;
  2523. let remainingPathname = matchedPathname === "/" ? pathname : pathname.slice(matchedPathname.length) || "/";
  2524. let match = matchPath({
  2525. path: meta.relativePath,
  2526. caseSensitive: meta.caseSensitive,
  2527. end
  2528. }, remainingPathname);
  2529. if (!match)
  2530. return null;
  2531. Object.assign(matchedParams, match.params);
  2532. let route = meta.route;
  2533. matches.push({
  2534. // TODO: Can this as be avoided?
  2535. params: matchedParams,
  2536. pathname: joinPaths([matchedPathname, match.pathname]),
  2537. pathnameBase: normalizePathname(joinPaths([matchedPathname, match.pathnameBase])),
  2538. route
  2539. });
  2540. if (match.pathnameBase !== "/") {
  2541. matchedPathname = joinPaths([matchedPathname, match.pathnameBase]);
  2542. }
  2543. }
  2544. return matches;
  2545. }
  2546. function generatePath(originalPath, params) {
  2547. if (params === void 0) {
  2548. params = {};
  2549. }
  2550. let path = originalPath;
  2551. if (path.endsWith("*") && path !== "*" && !path.endsWith("/*")) {
  2552. warning(false, 'Route path "' + path + '" will be treated as if it were ' + ('"' + path.replace(/\*$/, "/*") + '" because the `*` character must ') + "always follow a `/` in the pattern. To get rid of this warning, " + ('please change the route path to "' + path.replace(/\*$/, "/*") + '".'));
  2553. path = path.replace(/\*$/, "/*");
  2554. }
  2555. const prefix = path.startsWith("/") ? "/" : "";
  2556. const stringify = (p) => p == null ? "" : typeof p === "string" ? p : String(p);
  2557. const segments = path.split(/\/+/).map((segment, index, array) => {
  2558. const isLastSegment = index === array.length - 1;
  2559. if (isLastSegment && segment === "*") {
  2560. const star = "*";
  2561. return stringify(params[star]);
  2562. }
  2563. const keyMatch = segment.match(/^:([\w-]+)(\??)$/);
  2564. if (keyMatch) {
  2565. const [, key, optional] = keyMatch;
  2566. let param = params[key];
  2567. invariant(optional === "?" || param != null, 'Missing ":' + key + '" param');
  2568. return stringify(param);
  2569. }
  2570. return segment.replace(/\?$/g, "");
  2571. }).filter((segment) => !!segment);
  2572. return prefix + segments.join("/");
  2573. }
  2574. function matchPath(pattern, pathname) {
  2575. if (typeof pattern === "string") {
  2576. pattern = {
  2577. path: pattern,
  2578. caseSensitive: false,
  2579. end: true
  2580. };
  2581. }
  2582. let [matcher, compiledParams] = compilePath(pattern.path, pattern.caseSensitive, pattern.end);
  2583. let match = pathname.match(matcher);
  2584. if (!match)
  2585. return null;
  2586. let matchedPathname = match[0];
  2587. let pathnameBase = matchedPathname.replace(/(.)\/+$/, "$1");
  2588. let captureGroups = match.slice(1);
  2589. let params = compiledParams.reduce((memo, _ref, index) => {
  2590. let {
  2591. paramName,
  2592. isOptional
  2593. } = _ref;
  2594. if (paramName === "*") {
  2595. let splatValue = captureGroups[index] || "";
  2596. pathnameBase = matchedPathname.slice(0, matchedPathname.length - splatValue.length).replace(/(.)\/+$/, "$1");
  2597. }
  2598. const value = captureGroups[index];
  2599. if (isOptional && !value) {
  2600. memo[paramName] = void 0;
  2601. } else {
  2602. memo[paramName] = safelyDecodeURIComponent(value || "", paramName);
  2603. }
  2604. return memo;
  2605. }, {});
  2606. return {
  2607. params,
  2608. pathname: matchedPathname,
  2609. pathnameBase,
  2610. pattern
  2611. };
  2612. }
  2613. function compilePath(path, caseSensitive, end) {
  2614. if (caseSensitive === void 0) {
  2615. caseSensitive = false;
  2616. }
  2617. if (end === void 0) {
  2618. end = true;
  2619. }
  2620. warning(path === "*" || !path.endsWith("*") || path.endsWith("/*"), 'Route path "' + path + '" will be treated as if it were ' + ('"' + path.replace(/\*$/, "/*") + '" because the `*` character must ') + "always follow a `/` in the pattern. To get rid of this warning, " + ('please change the route path to "' + path.replace(/\*$/, "/*") + '".'));
  2621. let params = [];
  2622. let regexpSource = "^" + path.replace(/\/*\*?$/, "").replace(/^\/*/, "/").replace(/[\\.*+^${}|()[\]]/g, "\\$&").replace(/\/:([\w-]+)(\?)?/g, (_, paramName, isOptional) => {
  2623. params.push({
  2624. paramName,
  2625. isOptional: isOptional != null
  2626. });
  2627. return isOptional ? "/?([^\\/]+)?" : "/([^\\/]+)";
  2628. });
  2629. if (path.endsWith("*")) {
  2630. params.push({
  2631. paramName: "*"
  2632. });
  2633. regexpSource += path === "*" || path === "/*" ? "(.*)$" : "(?:\\/(.+)|\\/*)$";
  2634. } else if (end) {
  2635. regexpSource += "\\/*$";
  2636. } else if (path !== "" && path !== "/") {
  2637. regexpSource += "(?:(?=\\/|$))";
  2638. } else
  2639. ;
  2640. let matcher = new RegExp(regexpSource, caseSensitive ? void 0 : "i");
  2641. return [matcher, params];
  2642. }
  2643. function safelyDecodeURI(value) {
  2644. try {
  2645. return decodeURI(value);
  2646. } catch (error) {
  2647. warning(false, 'The URL path "' + value + '" could not be decoded because it is is a malformed URL segment. This is probably due to a bad percent ' + ("encoding (" + error + ")."));
  2648. return value;
  2649. }
  2650. }
  2651. function safelyDecodeURIComponent(value, paramName) {
  2652. try {
  2653. return decodeURIComponent(value);
  2654. } catch (error) {
  2655. warning(false, 'The value for the URL param "' + paramName + '" will not be decoded because' + (' the string "' + value + '" is a malformed URL segment. This is probably') + (" due to a bad percent encoding (" + error + ")."));
  2656. return value;
  2657. }
  2658. }
  2659. function stripBasename(pathname, basename) {
  2660. if (basename === "/")
  2661. return pathname;
  2662. if (!pathname.toLowerCase().startsWith(basename.toLowerCase())) {
  2663. return null;
  2664. }
  2665. let startIndex = basename.endsWith("/") ? basename.length - 1 : basename.length;
  2666. let nextChar = pathname.charAt(startIndex);
  2667. if (nextChar && nextChar !== "/") {
  2668. return null;
  2669. }
  2670. return pathname.slice(startIndex) || "/";
  2671. }
  2672. function resolvePath(to, fromPathname) {
  2673. if (fromPathname === void 0) {
  2674. fromPathname = "/";
  2675. }
  2676. let {
  2677. pathname: toPathname,
  2678. search = "",
  2679. hash = ""
  2680. } = typeof to === "string" ? parsePath(to) : to;
  2681. let pathname = toPathname ? toPathname.startsWith("/") ? toPathname : resolvePathname(toPathname, fromPathname) : fromPathname;
  2682. return {
  2683. pathname,
  2684. search: normalizeSearch(search),
  2685. hash: normalizeHash(hash)
  2686. };
  2687. }
  2688. function resolvePathname(relativePath, fromPathname) {
  2689. let segments = fromPathname.replace(/\/+$/, "").split("/");
  2690. let relativeSegments = relativePath.split("/");
  2691. relativeSegments.forEach((segment) => {
  2692. if (segment === "..") {
  2693. if (segments.length > 1)
  2694. segments.pop();
  2695. } else if (segment !== ".") {
  2696. segments.push(segment);
  2697. }
  2698. });
  2699. return segments.length > 1 ? segments.join("/") : "/";
  2700. }
  2701. function getInvalidPathError(char, field, dest, path) {
  2702. return "Cannot include a '" + char + "' character in a manually specified " + ("`to." + field + "` field [" + JSON.stringify(path) + "]. Please separate it out to the ") + ("`to." + dest + "` field. Alternatively you may provide the full path as ") + 'a string in <Link to="..."> and the router will parse it for you.';
  2703. }
  2704. function getPathContributingMatches(matches) {
  2705. return matches.filter((match, index) => index === 0 || match.route.path && match.route.path.length > 0);
  2706. }
  2707. function getResolveToMatches(matches, v7_relativeSplatPath) {
  2708. let pathMatches = getPathContributingMatches(matches);
  2709. if (v7_relativeSplatPath) {
  2710. return pathMatches.map((match, idx) => idx === matches.length - 1 ? match.pathname : match.pathnameBase);
  2711. }
  2712. return pathMatches.map((match) => match.pathnameBase);
  2713. }
  2714. function resolveTo(toArg, routePathnames, locationPathname, isPathRelative) {
  2715. if (isPathRelative === void 0) {
  2716. isPathRelative = false;
  2717. }
  2718. let to;
  2719. if (typeof toArg === "string") {
  2720. to = parsePath(toArg);
  2721. } else {
  2722. to = _extends({}, toArg);
  2723. invariant(!to.pathname || !to.pathname.includes("?"), getInvalidPathError("?", "pathname", "search", to));
  2724. invariant(!to.pathname || !to.pathname.includes("#"), getInvalidPathError("#", "pathname", "hash", to));
  2725. invariant(!to.search || !to.search.includes("#"), getInvalidPathError("#", "search", "hash", to));
  2726. }
  2727. let isEmptyPath = toArg === "" || to.pathname === "";
  2728. let toPathname = isEmptyPath ? "/" : to.pathname;
  2729. let from;
  2730. if (toPathname == null) {
  2731. from = locationPathname;
  2732. } else {
  2733. let routePathnameIndex = routePathnames.length - 1;
  2734. if (!isPathRelative && toPathname.startsWith("..")) {
  2735. let toSegments = toPathname.split("/");
  2736. while (toSegments[0] === "..") {
  2737. toSegments.shift();
  2738. routePathnameIndex -= 1;
  2739. }
  2740. to.pathname = toSegments.join("/");
  2741. }
  2742. from = routePathnameIndex >= 0 ? routePathnames[routePathnameIndex] : "/";
  2743. }
  2744. let path = resolvePath(to, from);
  2745. let hasExplicitTrailingSlash = toPathname && toPathname !== "/" && toPathname.endsWith("/");
  2746. let hasCurrentTrailingSlash = (isEmptyPath || toPathname === ".") && locationPathname.endsWith("/");
  2747. if (!path.pathname.endsWith("/") && (hasExplicitTrailingSlash || hasCurrentTrailingSlash)) {
  2748. path.pathname += "/";
  2749. }
  2750. return path;
  2751. }
  2752. function getToPathname(to) {
  2753. return to === "" || to.pathname === "" ? "/" : typeof to === "string" ? parsePath(to).pathname : to.pathname;
  2754. }
  2755. function isTrackedPromise(value) {
  2756. return value instanceof Promise && value._tracked === true;
  2757. }
  2758. function unwrapTrackedPromise(value) {
  2759. if (!isTrackedPromise(value)) {
  2760. return value;
  2761. }
  2762. if (value._error) {
  2763. throw value._error;
  2764. }
  2765. return value._data;
  2766. }
  2767. function isRouteErrorResponse(error) {
  2768. return error != null && typeof error.status === "number" && typeof error.statusText === "string" && typeof error.internal === "boolean" && "data" in error;
  2769. }
  2770. function createRouter(init) {
  2771. const routerWindow = init.window ? init.window : typeof window !== "undefined" ? window : void 0;
  2772. const isBrowser = typeof routerWindow !== "undefined" && typeof routerWindow.document !== "undefined" && typeof routerWindow.document.createElement !== "undefined";
  2773. const isServer = !isBrowser;
  2774. invariant(init.routes.length > 0, "You must provide a non-empty routes array to createRouter");
  2775. let mapRouteProperties;
  2776. if (init.mapRouteProperties) {
  2777. mapRouteProperties = init.mapRouteProperties;
  2778. } else if (init.detectErrorBoundary) {
  2779. let detectErrorBoundary = init.detectErrorBoundary;
  2780. mapRouteProperties = (route) => ({
  2781. hasErrorBoundary: detectErrorBoundary(route)
  2782. });
  2783. } else {
  2784. mapRouteProperties = defaultMapRouteProperties;
  2785. }
  2786. let manifest = {};
  2787. let dataRoutes = convertRoutesToDataRoutes(init.routes, mapRouteProperties, void 0, manifest);
  2788. let inFlightDataRoutes;
  2789. let basename = init.basename || "/";
  2790. let future = _extends({
  2791. v7_fetcherPersist: false,
  2792. v7_normalizeFormMethod: false,
  2793. v7_partialHydration: false,
  2794. v7_prependBasename: false,
  2795. v7_relativeSplatPath: false
  2796. }, init.future);
  2797. let unlistenHistory = null;
  2798. let subscribers = /* @__PURE__ */ new Set();
  2799. let savedScrollPositions = null;
  2800. let getScrollRestorationKey = null;
  2801. let getScrollPosition = null;
  2802. let initialScrollRestored = init.hydrationData != null;
  2803. let initialMatches = matchRoutes(dataRoutes, init.history.location, basename);
  2804. let initialErrors = null;
  2805. if (initialMatches == null) {
  2806. let error = getInternalRouterError(404, {
  2807. pathname: init.history.location.pathname
  2808. });
  2809. let {
  2810. matches,
  2811. route
  2812. } = getShortCircuitMatches(dataRoutes);
  2813. initialMatches = matches;
  2814. initialErrors = {
  2815. [route.id]: error
  2816. };
  2817. }
  2818. let initialized;
  2819. let hasLazyRoutes = initialMatches.some((m) => m.route.lazy);
  2820. let hasLoaders = initialMatches.some((m) => m.route.loader);
  2821. if (hasLazyRoutes) {
  2822. initialized = false;
  2823. } else if (!hasLoaders) {
  2824. initialized = true;
  2825. } else if (future.v7_partialHydration) {
  2826. let loaderData = init.hydrationData ? init.hydrationData.loaderData : null;
  2827. let errors = init.hydrationData ? init.hydrationData.errors : null;
  2828. initialized = initialMatches.every((m) => m.route.loader && m.route.loader.hydrate !== true && (loaderData && loaderData[m.route.id] !== void 0 || errors && errors[m.route.id] !== void 0));
  2829. } else {
  2830. initialized = init.hydrationData != null;
  2831. }
  2832. let router;
  2833. let state = {
  2834. historyAction: init.history.action,
  2835. location: init.history.location,
  2836. matches: initialMatches,
  2837. initialized,
  2838. navigation: IDLE_NAVIGATION,
  2839. // Don't restore on initial updateState() if we were SSR'd
  2840. restoreScrollPosition: init.hydrationData != null ? false : null,
  2841. preventScrollReset: false,
  2842. revalidation: "idle",
  2843. loaderData: init.hydrationData && init.hydrationData.loaderData || {},
  2844. actionData: init.hydrationData && init.hydrationData.actionData || null,
  2845. errors: init.hydrationData && init.hydrationData.errors || initialErrors,
  2846. fetchers: /* @__PURE__ */ new Map(),
  2847. blockers: /* @__PURE__ */ new Map()
  2848. };
  2849. let pendingAction = Action.Pop;
  2850. let pendingPreventScrollReset = false;
  2851. let pendingNavigationController;
  2852. let pendingViewTransitionEnabled = false;
  2853. let appliedViewTransitions = /* @__PURE__ */ new Map();
  2854. let removePageHideEventListener = null;
  2855. let isUninterruptedRevalidation = false;
  2856. let isRevalidationRequired = false;
  2857. let cancelledDeferredRoutes = [];
  2858. let cancelledFetcherLoads = [];
  2859. let fetchControllers = /* @__PURE__ */ new Map();
  2860. let incrementingLoadId = 0;
  2861. let pendingNavigationLoadId = -1;
  2862. let fetchReloadIds = /* @__PURE__ */ new Map();
  2863. let fetchRedirectIds = /* @__PURE__ */ new Set();
  2864. let fetchLoadMatches = /* @__PURE__ */ new Map();
  2865. let activeFetchers = /* @__PURE__ */ new Map();
  2866. let deletedFetchers = /* @__PURE__ */ new Set();
  2867. let activeDeferreds = /* @__PURE__ */ new Map();
  2868. let blockerFunctions = /* @__PURE__ */ new Map();
  2869. let ignoreNextHistoryUpdate = false;
  2870. function initialize() {
  2871. unlistenHistory = init.history.listen((_ref) => {
  2872. let {
  2873. action: historyAction,
  2874. location,
  2875. delta
  2876. } = _ref;
  2877. if (ignoreNextHistoryUpdate) {
  2878. ignoreNextHistoryUpdate = false;
  2879. return;
  2880. }
  2881. warning(blockerFunctions.size === 0 || delta != null, "You are trying to use a blocker on a POP navigation to a location that was not created by @remix-run/router. This will fail silently in production. This can happen if you are navigating outside the router via `window.history.pushState`/`window.location.hash` instead of using router navigation APIs. This can also happen if you are using createHashRouter and the user manually changes the URL.");
  2882. let blockerKey = shouldBlockNavigation({
  2883. currentLocation: state.location,
  2884. nextLocation: location,
  2885. historyAction
  2886. });
  2887. if (blockerKey && delta != null) {
  2888. ignoreNextHistoryUpdate = true;
  2889. init.history.go(delta * -1);
  2890. updateBlocker(blockerKey, {
  2891. state: "blocked",
  2892. location,
  2893. proceed() {
  2894. updateBlocker(blockerKey, {
  2895. state: "proceeding",
  2896. proceed: void 0,
  2897. reset: void 0,
  2898. location
  2899. });
  2900. init.history.go(delta);
  2901. },
  2902. reset() {
  2903. let blockers = new Map(state.blockers);
  2904. blockers.set(blockerKey, IDLE_BLOCKER);
  2905. updateState({
  2906. blockers
  2907. });
  2908. }
  2909. });
  2910. return;
  2911. }
  2912. return startNavigation(historyAction, location);
  2913. });
  2914. if (isBrowser) {
  2915. restoreAppliedTransitions(routerWindow, appliedViewTransitions);
  2916. let _saveAppliedTransitions = () => persistAppliedTransitions(routerWindow, appliedViewTransitions);
  2917. routerWindow.addEventListener("pagehide", _saveAppliedTransitions);
  2918. removePageHideEventListener = () => routerWindow.removeEventListener("pagehide", _saveAppliedTransitions);
  2919. }
  2920. if (!state.initialized) {
  2921. startNavigation(Action.Pop, state.location, {
  2922. initialHydration: true
  2923. });
  2924. }
  2925. return router;
  2926. }
  2927. function dispose() {
  2928. if (unlistenHistory) {
  2929. unlistenHistory();
  2930. }
  2931. if (removePageHideEventListener) {
  2932. removePageHideEventListener();
  2933. }
  2934. subscribers.clear();
  2935. pendingNavigationController && pendingNavigationController.abort();
  2936. state.fetchers.forEach((_, key) => deleteFetcher(key));
  2937. state.blockers.forEach((_, key) => deleteBlocker(key));
  2938. }
  2939. function subscribe(fn) {
  2940. subscribers.add(fn);
  2941. return () => subscribers.delete(fn);
  2942. }
  2943. function updateState(newState, opts) {
  2944. if (opts === void 0) {
  2945. opts = {};
  2946. }
  2947. state = _extends({}, state, newState);
  2948. let completedFetchers = [];
  2949. let deletedFetchersKeys = [];
  2950. if (future.v7_fetcherPersist) {
  2951. state.fetchers.forEach((fetcher, key) => {
  2952. if (fetcher.state === "idle") {
  2953. if (deletedFetchers.has(key)) {
  2954. deletedFetchersKeys.push(key);
  2955. } else {
  2956. completedFetchers.push(key);
  2957. }
  2958. }
  2959. });
  2960. }
  2961. [...subscribers].forEach((subscriber) => subscriber(state, {
  2962. deletedFetchers: deletedFetchersKeys,
  2963. unstable_viewTransitionOpts: opts.viewTransitionOpts,
  2964. unstable_flushSync: opts.flushSync === true
  2965. }));
  2966. if (future.v7_fetcherPersist) {
  2967. completedFetchers.forEach((key) => state.fetchers.delete(key));
  2968. deletedFetchersKeys.forEach((key) => deleteFetcher(key));
  2969. }
  2970. }
  2971. function completeNavigation(location, newState, _temp) {
  2972. var _location$state, _location$state2;
  2973. let {
  2974. flushSync
  2975. } = _temp === void 0 ? {} : _temp;
  2976. let isActionReload = state.actionData != null && state.navigation.formMethod != null && isMutationMethod(state.navigation.formMethod) && state.navigation.state === "loading" && ((_location$state = location.state) == null ? void 0 : _location$state._isRedirect) !== true;
  2977. let actionData;
  2978. if (newState.actionData) {
  2979. if (Object.keys(newState.actionData).length > 0) {
  2980. actionData = newState.actionData;
  2981. } else {
  2982. actionData = null;
  2983. }
  2984. } else if (isActionReload) {
  2985. actionData = state.actionData;
  2986. } else {
  2987. actionData = null;
  2988. }
  2989. let loaderData = newState.loaderData ? mergeLoaderData(state.loaderData, newState.loaderData, newState.matches || [], newState.errors) : state.loaderData;
  2990. let blockers = state.blockers;
  2991. if (blockers.size > 0) {
  2992. blockers = new Map(blockers);
  2993. blockers.forEach((_, k2) => blockers.set(k2, IDLE_BLOCKER));
  2994. }
  2995. let preventScrollReset = pendingPreventScrollReset === true || state.navigation.formMethod != null && isMutationMethod(state.navigation.formMethod) && ((_location$state2 = location.state) == null ? void 0 : _location$state2._isRedirect) !== true;
  2996. if (inFlightDataRoutes) {
  2997. dataRoutes = inFlightDataRoutes;
  2998. inFlightDataRoutes = void 0;
  2999. }
  3000. if (isUninterruptedRevalidation)
  3001. ;
  3002. else if (pendingAction === Action.Pop)
  3003. ;
  3004. else if (pendingAction === Action.Push) {
  3005. init.history.push(location, location.state);
  3006. } else if (pendingAction === Action.Replace) {
  3007. init.history.replace(location, location.state);
  3008. }
  3009. let viewTransitionOpts;
  3010. if (pendingAction === Action.Pop) {
  3011. let priorPaths = appliedViewTransitions.get(state.location.pathname);
  3012. if (priorPaths && priorPaths.has(location.pathname)) {
  3013. viewTransitionOpts = {
  3014. currentLocation: state.location,
  3015. nextLocation: location
  3016. };
  3017. } else if (appliedViewTransitions.has(location.pathname)) {
  3018. viewTransitionOpts = {
  3019. currentLocation: location,
  3020. nextLocation: state.location
  3021. };
  3022. }
  3023. } else if (pendingViewTransitionEnabled) {
  3024. let toPaths = appliedViewTransitions.get(state.location.pathname);
  3025. if (toPaths) {
  3026. toPaths.add(location.pathname);
  3027. } else {
  3028. toPaths = /* @__PURE__ */ new Set([location.pathname]);
  3029. appliedViewTransitions.set(state.location.pathname, toPaths);
  3030. }
  3031. viewTransitionOpts = {
  3032. currentLocation: state.location,
  3033. nextLocation: location
  3034. };
  3035. }
  3036. updateState(_extends({}, newState, {
  3037. actionData,
  3038. loaderData,
  3039. historyAction: pendingAction,
  3040. location,
  3041. initialized: true,
  3042. navigation: IDLE_NAVIGATION,
  3043. revalidation: "idle",
  3044. restoreScrollPosition: getSavedScrollPosition(location, newState.matches || state.matches),
  3045. preventScrollReset,
  3046. blockers
  3047. }), {
  3048. viewTransitionOpts,
  3049. flushSync: flushSync === true
  3050. });
  3051. pendingAction = Action.Pop;
  3052. pendingPreventScrollReset = false;
  3053. pendingViewTransitionEnabled = false;
  3054. isUninterruptedRevalidation = false;
  3055. isRevalidationRequired = false;
  3056. cancelledDeferredRoutes = [];
  3057. cancelledFetcherLoads = [];
  3058. }
  3059. async function navigate(to, opts) {
  3060. if (typeof to === "number") {
  3061. init.history.go(to);
  3062. return;
  3063. }
  3064. let normalizedPath = normalizeTo(state.location, state.matches, basename, future.v7_prependBasename, to, future.v7_relativeSplatPath, opts == null ? void 0 : opts.fromRouteId, opts == null ? void 0 : opts.relative);
  3065. let {
  3066. path,
  3067. submission,
  3068. error
  3069. } = normalizeNavigateOptions(future.v7_normalizeFormMethod, false, normalizedPath, opts);
  3070. let currentLocation = state.location;
  3071. let nextLocation = createLocation(state.location, path, opts && opts.state);
  3072. nextLocation = _extends({}, nextLocation, init.history.encodeLocation(nextLocation));
  3073. let userReplace = opts && opts.replace != null ? opts.replace : void 0;
  3074. let historyAction = Action.Push;
  3075. if (userReplace === true) {
  3076. historyAction = Action.Replace;
  3077. } else if (userReplace === false)
  3078. ;
  3079. else if (submission != null && isMutationMethod(submission.formMethod) && submission.formAction === state.location.pathname + state.location.search) {
  3080. historyAction = Action.Replace;
  3081. }
  3082. let preventScrollReset = opts && "preventScrollReset" in opts ? opts.preventScrollReset === true : void 0;
  3083. let flushSync = (opts && opts.unstable_flushSync) === true;
  3084. let blockerKey = shouldBlockNavigation({
  3085. currentLocation,
  3086. nextLocation,
  3087. historyAction
  3088. });
  3089. if (blockerKey) {
  3090. updateBlocker(blockerKey, {
  3091. state: "blocked",
  3092. location: nextLocation,
  3093. proceed() {
  3094. updateBlocker(blockerKey, {
  3095. state: "proceeding",
  3096. proceed: void 0,
  3097. reset: void 0,
  3098. location: nextLocation
  3099. });
  3100. navigate(to, opts);
  3101. },
  3102. reset() {
  3103. let blockers = new Map(state.blockers);
  3104. blockers.set(blockerKey, IDLE_BLOCKER);
  3105. updateState({
  3106. blockers
  3107. });
  3108. }
  3109. });
  3110. return;
  3111. }
  3112. return await startNavigation(historyAction, nextLocation, {
  3113. submission,
  3114. // Send through the formData serialization error if we have one so we can
  3115. // render at the right error boundary after we match routes
  3116. pendingError: error,
  3117. preventScrollReset,
  3118. replace: opts && opts.replace,
  3119. enableViewTransition: opts && opts.unstable_viewTransition,
  3120. flushSync
  3121. });
  3122. }
  3123. function revalidate() {
  3124. interruptActiveLoads();
  3125. updateState({
  3126. revalidation: "loading"
  3127. });
  3128. if (state.navigation.state === "submitting") {
  3129. return;
  3130. }
  3131. if (state.navigation.state === "idle") {
  3132. startNavigation(state.historyAction, state.location, {
  3133. startUninterruptedRevalidation: true
  3134. });
  3135. return;
  3136. }
  3137. startNavigation(pendingAction || state.historyAction, state.navigation.location, {
  3138. overrideNavigation: state.navigation
  3139. });
  3140. }
  3141. async function startNavigation(historyAction, location, opts) {
  3142. pendingNavigationController && pendingNavigationController.abort();
  3143. pendingNavigationController = null;
  3144. pendingAction = historyAction;
  3145. isUninterruptedRevalidation = (opts && opts.startUninterruptedRevalidation) === true;
  3146. saveScrollPosition(state.location, state.matches);
  3147. pendingPreventScrollReset = (opts && opts.preventScrollReset) === true;
  3148. pendingViewTransitionEnabled = (opts && opts.enableViewTransition) === true;
  3149. let routesToUse = inFlightDataRoutes || dataRoutes;
  3150. let loadingNavigation = opts && opts.overrideNavigation;
  3151. let matches = matchRoutes(routesToUse, location, basename);
  3152. let flushSync = (opts && opts.flushSync) === true;
  3153. if (!matches) {
  3154. let error = getInternalRouterError(404, {
  3155. pathname: location.pathname
  3156. });
  3157. let {
  3158. matches: notFoundMatches,
  3159. route
  3160. } = getShortCircuitMatches(routesToUse);
  3161. cancelActiveDeferreds();
  3162. completeNavigation(location, {
  3163. matches: notFoundMatches,
  3164. loaderData: {},
  3165. errors: {
  3166. [route.id]: error
  3167. }
  3168. }, {
  3169. flushSync
  3170. });
  3171. return;
  3172. }
  3173. if (state.initialized && !isRevalidationRequired && isHashChangeOnly(state.location, location) && !(opts && opts.submission && isMutationMethod(opts.submission.formMethod))) {
  3174. completeNavigation(location, {
  3175. matches
  3176. }, {
  3177. flushSync
  3178. });
  3179. return;
  3180. }
  3181. pendingNavigationController = new AbortController();
  3182. let request = createClientSideRequest(init.history, location, pendingNavigationController.signal, opts && opts.submission);
  3183. let pendingActionData;
  3184. let pendingError;
  3185. if (opts && opts.pendingError) {
  3186. pendingError = {
  3187. [findNearestBoundary(matches).route.id]: opts.pendingError
  3188. };
  3189. } else if (opts && opts.submission && isMutationMethod(opts.submission.formMethod)) {
  3190. let actionOutput = await handleAction2(request, location, opts.submission, matches, {
  3191. replace: opts.replace,
  3192. flushSync
  3193. });
  3194. if (actionOutput.shortCircuited) {
  3195. return;
  3196. }
  3197. pendingActionData = actionOutput.pendingActionData;
  3198. pendingError = actionOutput.pendingActionError;
  3199. loadingNavigation = getLoadingNavigation(location, opts.submission);
  3200. flushSync = false;
  3201. request = new Request(request.url, {
  3202. signal: request.signal
  3203. });
  3204. }
  3205. let {
  3206. shortCircuited,
  3207. loaderData,
  3208. errors
  3209. } = await handleLoaders(request, location, matches, loadingNavigation, opts && opts.submission, opts && opts.fetcherSubmission, opts && opts.replace, opts && opts.initialHydration === true, flushSync, pendingActionData, pendingError);
  3210. if (shortCircuited) {
  3211. return;
  3212. }
  3213. pendingNavigationController = null;
  3214. completeNavigation(location, _extends({
  3215. matches
  3216. }, pendingActionData ? {
  3217. actionData: pendingActionData
  3218. } : {}, {
  3219. loaderData,
  3220. errors
  3221. }));
  3222. }
  3223. async function handleAction2(request, location, submission, matches, opts) {
  3224. if (opts === void 0) {
  3225. opts = {};
  3226. }
  3227. interruptActiveLoads();
  3228. let navigation = getSubmittingNavigation(location, submission);
  3229. updateState({
  3230. navigation
  3231. }, {
  3232. flushSync: opts.flushSync === true
  3233. });
  3234. let result;
  3235. let actionMatch = getTargetMatch(matches, location);
  3236. if (!actionMatch.route.action && !actionMatch.route.lazy) {
  3237. result = {
  3238. type: ResultType.error,
  3239. error: getInternalRouterError(405, {
  3240. method: request.method,
  3241. pathname: location.pathname,
  3242. routeId: actionMatch.route.id
  3243. })
  3244. };
  3245. } else {
  3246. result = await callLoaderOrAction("action", request, actionMatch, matches, manifest, mapRouteProperties, basename, future.v7_relativeSplatPath);
  3247. if (request.signal.aborted) {
  3248. return {
  3249. shortCircuited: true
  3250. };
  3251. }
  3252. }
  3253. if (isRedirectResult(result)) {
  3254. let replace;
  3255. if (opts && opts.replace != null) {
  3256. replace = opts.replace;
  3257. } else {
  3258. replace = result.location === state.location.pathname + state.location.search;
  3259. }
  3260. await startRedirectNavigation(state, result, {
  3261. submission,
  3262. replace
  3263. });
  3264. return {
  3265. shortCircuited: true
  3266. };
  3267. }
  3268. if (isErrorResult(result)) {
  3269. let boundaryMatch = findNearestBoundary(matches, actionMatch.route.id);
  3270. if ((opts && opts.replace) !== true) {
  3271. pendingAction = Action.Push;
  3272. }
  3273. return {
  3274. // Send back an empty object we can use to clear out any prior actionData
  3275. pendingActionData: {},
  3276. pendingActionError: {
  3277. [boundaryMatch.route.id]: result.error
  3278. }
  3279. };
  3280. }
  3281. if (isDeferredResult(result)) {
  3282. throw getInternalRouterError(400, {
  3283. type: "defer-action"
  3284. });
  3285. }
  3286. return {
  3287. pendingActionData: {
  3288. [actionMatch.route.id]: result.data
  3289. }
  3290. };
  3291. }
  3292. async function handleLoaders(request, location, matches, overrideNavigation, submission, fetcherSubmission, replace, initialHydration, flushSync, pendingActionData, pendingError) {
  3293. let loadingNavigation = overrideNavigation || getLoadingNavigation(location, submission);
  3294. let activeSubmission = submission || fetcherSubmission || getSubmissionFromNavigation(loadingNavigation);
  3295. let routesToUse = inFlightDataRoutes || dataRoutes;
  3296. let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(init.history, state, matches, activeSubmission, location, future.v7_partialHydration && initialHydration === true, isRevalidationRequired, cancelledDeferredRoutes, cancelledFetcherLoads, deletedFetchers, fetchLoadMatches, fetchRedirectIds, routesToUse, basename, pendingActionData, pendingError);
  3297. cancelActiveDeferreds((routeId) => !(matches && matches.some((m) => m.route.id === routeId)) || matchesToLoad && matchesToLoad.some((m) => m.route.id === routeId));
  3298. pendingNavigationLoadId = ++incrementingLoadId;
  3299. if (matchesToLoad.length === 0 && revalidatingFetchers.length === 0) {
  3300. let updatedFetchers2 = markFetchRedirectsDone();
  3301. completeNavigation(location, _extends({
  3302. matches,
  3303. loaderData: {},
  3304. // Commit pending error if we're short circuiting
  3305. errors: pendingError || null
  3306. }, pendingActionData ? {
  3307. actionData: pendingActionData
  3308. } : {}, updatedFetchers2 ? {
  3309. fetchers: new Map(state.fetchers)
  3310. } : {}), {
  3311. flushSync
  3312. });
  3313. return {
  3314. shortCircuited: true
  3315. };
  3316. }
  3317. if (!isUninterruptedRevalidation && (!future.v7_partialHydration || !initialHydration)) {
  3318. revalidatingFetchers.forEach((rf) => {
  3319. let fetcher = state.fetchers.get(rf.key);
  3320. let revalidatingFetcher = getLoadingFetcher(void 0, fetcher ? fetcher.data : void 0);
  3321. state.fetchers.set(rf.key, revalidatingFetcher);
  3322. });
  3323. let actionData = pendingActionData || state.actionData;
  3324. updateState(_extends({
  3325. navigation: loadingNavigation
  3326. }, actionData ? Object.keys(actionData).length === 0 ? {
  3327. actionData: null
  3328. } : {
  3329. actionData
  3330. } : {}, revalidatingFetchers.length > 0 ? {
  3331. fetchers: new Map(state.fetchers)
  3332. } : {}), {
  3333. flushSync
  3334. });
  3335. }
  3336. revalidatingFetchers.forEach((rf) => {
  3337. if (fetchControllers.has(rf.key)) {
  3338. abortFetcher(rf.key);
  3339. }
  3340. if (rf.controller) {
  3341. fetchControllers.set(rf.key, rf.controller);
  3342. }
  3343. });
  3344. let abortPendingFetchRevalidations = () => revalidatingFetchers.forEach((f2) => abortFetcher(f2.key));
  3345. if (pendingNavigationController) {
  3346. pendingNavigationController.signal.addEventListener("abort", abortPendingFetchRevalidations);
  3347. }
  3348. let {
  3349. results,
  3350. loaderResults,
  3351. fetcherResults
  3352. } = await callLoadersAndMaybeResolveData(state.matches, matches, matchesToLoad, revalidatingFetchers, request);
  3353. if (request.signal.aborted) {
  3354. return {
  3355. shortCircuited: true
  3356. };
  3357. }
  3358. if (pendingNavigationController) {
  3359. pendingNavigationController.signal.removeEventListener("abort", abortPendingFetchRevalidations);
  3360. }
  3361. revalidatingFetchers.forEach((rf) => fetchControllers.delete(rf.key));
  3362. let redirect4 = findRedirect(results);
  3363. if (redirect4) {
  3364. if (redirect4.idx >= matchesToLoad.length) {
  3365. let fetcherKey = revalidatingFetchers[redirect4.idx - matchesToLoad.length].key;
  3366. fetchRedirectIds.add(fetcherKey);
  3367. }
  3368. await startRedirectNavigation(state, redirect4.result, {
  3369. replace
  3370. });
  3371. return {
  3372. shortCircuited: true
  3373. };
  3374. }
  3375. let {
  3376. loaderData,
  3377. errors
  3378. } = processLoaderData(state, matches, matchesToLoad, loaderResults, pendingError, revalidatingFetchers, fetcherResults, activeDeferreds);
  3379. activeDeferreds.forEach((deferredData, routeId) => {
  3380. deferredData.subscribe((aborted) => {
  3381. if (aborted || deferredData.done) {
  3382. activeDeferreds.delete(routeId);
  3383. }
  3384. });
  3385. });
  3386. let updatedFetchers = markFetchRedirectsDone();
  3387. let didAbortFetchLoads = abortStaleFetchLoads(pendingNavigationLoadId);
  3388. let shouldUpdateFetchers = updatedFetchers || didAbortFetchLoads || revalidatingFetchers.length > 0;
  3389. return _extends({
  3390. loaderData,
  3391. errors
  3392. }, shouldUpdateFetchers ? {
  3393. fetchers: new Map(state.fetchers)
  3394. } : {});
  3395. }
  3396. function fetch2(key, routeId, href, opts) {
  3397. if (isServer) {
  3398. throw new Error("router.fetch() was called during the server render, but it shouldn't be. You are likely calling a useFetcher() method in the body of your component. Try moving it to a useEffect or a callback.");
  3399. }
  3400. if (fetchControllers.has(key))
  3401. abortFetcher(key);
  3402. let flushSync = (opts && opts.unstable_flushSync) === true;
  3403. let routesToUse = inFlightDataRoutes || dataRoutes;
  3404. let normalizedPath = normalizeTo(state.location, state.matches, basename, future.v7_prependBasename, href, future.v7_relativeSplatPath, routeId, opts == null ? void 0 : opts.relative);
  3405. let matches = matchRoutes(routesToUse, normalizedPath, basename);
  3406. if (!matches) {
  3407. setFetcherError(key, routeId, getInternalRouterError(404, {
  3408. pathname: normalizedPath
  3409. }), {
  3410. flushSync
  3411. });
  3412. return;
  3413. }
  3414. let {
  3415. path,
  3416. submission,
  3417. error
  3418. } = normalizeNavigateOptions(future.v7_normalizeFormMethod, true, normalizedPath, opts);
  3419. if (error) {
  3420. setFetcherError(key, routeId, error, {
  3421. flushSync
  3422. });
  3423. return;
  3424. }
  3425. let match = getTargetMatch(matches, path);
  3426. pendingPreventScrollReset = (opts && opts.preventScrollReset) === true;
  3427. if (submission && isMutationMethod(submission.formMethod)) {
  3428. handleFetcherAction(key, routeId, path, match, matches, flushSync, submission);
  3429. return;
  3430. }
  3431. fetchLoadMatches.set(key, {
  3432. routeId,
  3433. path
  3434. });
  3435. handleFetcherLoader(key, routeId, path, match, matches, flushSync, submission);
  3436. }
  3437. async function handleFetcherAction(key, routeId, path, match, requestMatches, flushSync, submission) {
  3438. interruptActiveLoads();
  3439. fetchLoadMatches.delete(key);
  3440. if (!match.route.action && !match.route.lazy) {
  3441. let error = getInternalRouterError(405, {
  3442. method: submission.formMethod,
  3443. pathname: path,
  3444. routeId
  3445. });
  3446. setFetcherError(key, routeId, error, {
  3447. flushSync
  3448. });
  3449. return;
  3450. }
  3451. let existingFetcher = state.fetchers.get(key);
  3452. updateFetcherState(key, getSubmittingFetcher(submission, existingFetcher), {
  3453. flushSync
  3454. });
  3455. let abortController = new AbortController();
  3456. let fetchRequest = createClientSideRequest(init.history, path, abortController.signal, submission);
  3457. fetchControllers.set(key, abortController);
  3458. let originatingLoadId = incrementingLoadId;
  3459. let actionResult = await callLoaderOrAction("action", fetchRequest, match, requestMatches, manifest, mapRouteProperties, basename, future.v7_relativeSplatPath);
  3460. if (fetchRequest.signal.aborted) {
  3461. if (fetchControllers.get(key) === abortController) {
  3462. fetchControllers.delete(key);
  3463. }
  3464. return;
  3465. }
  3466. if (future.v7_fetcherPersist && deletedFetchers.has(key)) {
  3467. if (isRedirectResult(actionResult) || isErrorResult(actionResult)) {
  3468. updateFetcherState(key, getDoneFetcher(void 0));
  3469. return;
  3470. }
  3471. } else {
  3472. if (isRedirectResult(actionResult)) {
  3473. fetchControllers.delete(key);
  3474. if (pendingNavigationLoadId > originatingLoadId) {
  3475. updateFetcherState(key, getDoneFetcher(void 0));
  3476. return;
  3477. } else {
  3478. fetchRedirectIds.add(key);
  3479. updateFetcherState(key, getLoadingFetcher(submission));
  3480. return startRedirectNavigation(state, actionResult, {
  3481. fetcherSubmission: submission
  3482. });
  3483. }
  3484. }
  3485. if (isErrorResult(actionResult)) {
  3486. setFetcherError(key, routeId, actionResult.error);
  3487. return;
  3488. }
  3489. }
  3490. if (isDeferredResult(actionResult)) {
  3491. throw getInternalRouterError(400, {
  3492. type: "defer-action"
  3493. });
  3494. }
  3495. let nextLocation = state.navigation.location || state.location;
  3496. let revalidationRequest = createClientSideRequest(init.history, nextLocation, abortController.signal);
  3497. let routesToUse = inFlightDataRoutes || dataRoutes;
  3498. let matches = state.navigation.state !== "idle" ? matchRoutes(routesToUse, state.navigation.location, basename) : state.matches;
  3499. invariant(matches, "Didn't find any matches after fetcher action");
  3500. let loadId = ++incrementingLoadId;
  3501. fetchReloadIds.set(key, loadId);
  3502. let loadFetcher = getLoadingFetcher(submission, actionResult.data);
  3503. state.fetchers.set(key, loadFetcher);
  3504. let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(
  3505. init.history,
  3506. state,
  3507. matches,
  3508. submission,
  3509. nextLocation,
  3510. false,
  3511. isRevalidationRequired,
  3512. cancelledDeferredRoutes,
  3513. cancelledFetcherLoads,
  3514. deletedFetchers,
  3515. fetchLoadMatches,
  3516. fetchRedirectIds,
  3517. routesToUse,
  3518. basename,
  3519. {
  3520. [match.route.id]: actionResult.data
  3521. },
  3522. void 0
  3523. // No need to send through errors since we short circuit above
  3524. );
  3525. revalidatingFetchers.filter((rf) => rf.key !== key).forEach((rf) => {
  3526. let staleKey = rf.key;
  3527. let existingFetcher2 = state.fetchers.get(staleKey);
  3528. let revalidatingFetcher = getLoadingFetcher(void 0, existingFetcher2 ? existingFetcher2.data : void 0);
  3529. state.fetchers.set(staleKey, revalidatingFetcher);
  3530. if (fetchControllers.has(staleKey)) {
  3531. abortFetcher(staleKey);
  3532. }
  3533. if (rf.controller) {
  3534. fetchControllers.set(staleKey, rf.controller);
  3535. }
  3536. });
  3537. updateState({
  3538. fetchers: new Map(state.fetchers)
  3539. });
  3540. let abortPendingFetchRevalidations = () => revalidatingFetchers.forEach((rf) => abortFetcher(rf.key));
  3541. abortController.signal.addEventListener("abort", abortPendingFetchRevalidations);
  3542. let {
  3543. results,
  3544. loaderResults,
  3545. fetcherResults
  3546. } = await callLoadersAndMaybeResolveData(state.matches, matches, matchesToLoad, revalidatingFetchers, revalidationRequest);
  3547. if (abortController.signal.aborted) {
  3548. return;
  3549. }
  3550. abortController.signal.removeEventListener("abort", abortPendingFetchRevalidations);
  3551. fetchReloadIds.delete(key);
  3552. fetchControllers.delete(key);
  3553. revalidatingFetchers.forEach((r) => fetchControllers.delete(r.key));
  3554. let redirect4 = findRedirect(results);
  3555. if (redirect4) {
  3556. if (redirect4.idx >= matchesToLoad.length) {
  3557. let fetcherKey = revalidatingFetchers[redirect4.idx - matchesToLoad.length].key;
  3558. fetchRedirectIds.add(fetcherKey);
  3559. }
  3560. return startRedirectNavigation(state, redirect4.result);
  3561. }
  3562. let {
  3563. loaderData,
  3564. errors
  3565. } = processLoaderData(state, state.matches, matchesToLoad, loaderResults, void 0, revalidatingFetchers, fetcherResults, activeDeferreds);
  3566. if (state.fetchers.has(key)) {
  3567. let doneFetcher = getDoneFetcher(actionResult.data);
  3568. state.fetchers.set(key, doneFetcher);
  3569. }
  3570. abortStaleFetchLoads(loadId);
  3571. if (state.navigation.state === "loading" && loadId > pendingNavigationLoadId) {
  3572. invariant(pendingAction, "Expected pending action");
  3573. pendingNavigationController && pendingNavigationController.abort();
  3574. completeNavigation(state.navigation.location, {
  3575. matches,
  3576. loaderData,
  3577. errors,
  3578. fetchers: new Map(state.fetchers)
  3579. });
  3580. } else {
  3581. updateState({
  3582. errors,
  3583. loaderData: mergeLoaderData(state.loaderData, loaderData, matches, errors),
  3584. fetchers: new Map(state.fetchers)
  3585. });
  3586. isRevalidationRequired = false;
  3587. }
  3588. }
  3589. async function handleFetcherLoader(key, routeId, path, match, matches, flushSync, submission) {
  3590. let existingFetcher = state.fetchers.get(key);
  3591. updateFetcherState(key, getLoadingFetcher(submission, existingFetcher ? existingFetcher.data : void 0), {
  3592. flushSync
  3593. });
  3594. let abortController = new AbortController();
  3595. let fetchRequest = createClientSideRequest(init.history, path, abortController.signal);
  3596. fetchControllers.set(key, abortController);
  3597. let originatingLoadId = incrementingLoadId;
  3598. let result = await callLoaderOrAction("loader", fetchRequest, match, matches, manifest, mapRouteProperties, basename, future.v7_relativeSplatPath);
  3599. if (isDeferredResult(result)) {
  3600. result = await resolveDeferredData(result, fetchRequest.signal, true) || result;
  3601. }
  3602. if (fetchControllers.get(key) === abortController) {
  3603. fetchControllers.delete(key);
  3604. }
  3605. if (fetchRequest.signal.aborted) {
  3606. return;
  3607. }
  3608. if (deletedFetchers.has(key)) {
  3609. updateFetcherState(key, getDoneFetcher(void 0));
  3610. return;
  3611. }
  3612. if (isRedirectResult(result)) {
  3613. if (pendingNavigationLoadId > originatingLoadId) {
  3614. updateFetcherState(key, getDoneFetcher(void 0));
  3615. return;
  3616. } else {
  3617. fetchRedirectIds.add(key);
  3618. await startRedirectNavigation(state, result);
  3619. return;
  3620. }
  3621. }
  3622. if (isErrorResult(result)) {
  3623. setFetcherError(key, routeId, result.error);
  3624. return;
  3625. }
  3626. invariant(!isDeferredResult(result), "Unhandled fetcher deferred data");
  3627. updateFetcherState(key, getDoneFetcher(result.data));
  3628. }
  3629. async function startRedirectNavigation(state2, redirect4, _temp2) {
  3630. let {
  3631. submission,
  3632. fetcherSubmission,
  3633. replace
  3634. } = _temp2 === void 0 ? {} : _temp2;
  3635. if (redirect4.revalidate) {
  3636. isRevalidationRequired = true;
  3637. }
  3638. let redirectLocation = createLocation(state2.location, redirect4.location, {
  3639. _isRedirect: true
  3640. });
  3641. invariant(redirectLocation, "Expected a location on the redirect navigation");
  3642. if (isBrowser) {
  3643. let isDocumentReload = false;
  3644. if (redirect4.reloadDocument) {
  3645. isDocumentReload = true;
  3646. } else if (ABSOLUTE_URL_REGEX.test(redirect4.location)) {
  3647. const url = init.history.createURL(redirect4.location);
  3648. isDocumentReload = // Hard reload if it's an absolute URL to a new origin
  3649. url.origin !== routerWindow.location.origin || // Hard reload if it's an absolute URL that does not match our basename
  3650. stripBasename(url.pathname, basename) == null;
  3651. }
  3652. if (isDocumentReload) {
  3653. if (replace) {
  3654. routerWindow.location.replace(redirect4.location);
  3655. } else {
  3656. routerWindow.location.assign(redirect4.location);
  3657. }
  3658. return;
  3659. }
  3660. }
  3661. pendingNavigationController = null;
  3662. let redirectHistoryAction = replace === true ? Action.Replace : Action.Push;
  3663. let {
  3664. formMethod,
  3665. formAction,
  3666. formEncType
  3667. } = state2.navigation;
  3668. if (!submission && !fetcherSubmission && formMethod && formAction && formEncType) {
  3669. submission = getSubmissionFromNavigation(state2.navigation);
  3670. }
  3671. let activeSubmission = submission || fetcherSubmission;
  3672. if (redirectPreserveMethodStatusCodes.has(redirect4.status) && activeSubmission && isMutationMethod(activeSubmission.formMethod)) {
  3673. await startNavigation(redirectHistoryAction, redirectLocation, {
  3674. submission: _extends({}, activeSubmission, {
  3675. formAction: redirect4.location
  3676. }),
  3677. // Preserve this flag across redirects
  3678. preventScrollReset: pendingPreventScrollReset
  3679. });
  3680. } else {
  3681. let overrideNavigation = getLoadingNavigation(redirectLocation, submission);
  3682. await startNavigation(redirectHistoryAction, redirectLocation, {
  3683. overrideNavigation,
  3684. // Send fetcher submissions through for shouldRevalidate
  3685. fetcherSubmission,
  3686. // Preserve this flag across redirects
  3687. preventScrollReset: pendingPreventScrollReset
  3688. });
  3689. }
  3690. }
  3691. async function callLoadersAndMaybeResolveData(currentMatches, matches, matchesToLoad, fetchersToLoad, request) {
  3692. let results = await Promise.all([...matchesToLoad.map((match) => callLoaderOrAction("loader", request, match, matches, manifest, mapRouteProperties, basename, future.v7_relativeSplatPath)), ...fetchersToLoad.map((f2) => {
  3693. if (f2.matches && f2.match && f2.controller) {
  3694. return callLoaderOrAction("loader", createClientSideRequest(init.history, f2.path, f2.controller.signal), f2.match, f2.matches, manifest, mapRouteProperties, basename, future.v7_relativeSplatPath);
  3695. } else {
  3696. let error = {
  3697. type: ResultType.error,
  3698. error: getInternalRouterError(404, {
  3699. pathname: f2.path
  3700. })
  3701. };
  3702. return error;
  3703. }
  3704. })]);
  3705. let loaderResults = results.slice(0, matchesToLoad.length);
  3706. let fetcherResults = results.slice(matchesToLoad.length);
  3707. await Promise.all([resolveDeferredResults(currentMatches, matchesToLoad, loaderResults, loaderResults.map(() => request.signal), false, state.loaderData), resolveDeferredResults(currentMatches, fetchersToLoad.map((f2) => f2.match), fetcherResults, fetchersToLoad.map((f2) => f2.controller ? f2.controller.signal : null), true)]);
  3708. return {
  3709. results,
  3710. loaderResults,
  3711. fetcherResults
  3712. };
  3713. }
  3714. function interruptActiveLoads() {
  3715. isRevalidationRequired = true;
  3716. cancelledDeferredRoutes.push(...cancelActiveDeferreds());
  3717. fetchLoadMatches.forEach((_, key) => {
  3718. if (fetchControllers.has(key)) {
  3719. cancelledFetcherLoads.push(key);
  3720. abortFetcher(key);
  3721. }
  3722. });
  3723. }
  3724. function updateFetcherState(key, fetcher, opts) {
  3725. if (opts === void 0) {
  3726. opts = {};
  3727. }
  3728. state.fetchers.set(key, fetcher);
  3729. updateState({
  3730. fetchers: new Map(state.fetchers)
  3731. }, {
  3732. flushSync: (opts && opts.flushSync) === true
  3733. });
  3734. }
  3735. function setFetcherError(key, routeId, error, opts) {
  3736. if (opts === void 0) {
  3737. opts = {};
  3738. }
  3739. let boundaryMatch = findNearestBoundary(state.matches, routeId);
  3740. deleteFetcher(key);
  3741. updateState({
  3742. errors: {
  3743. [boundaryMatch.route.id]: error
  3744. },
  3745. fetchers: new Map(state.fetchers)
  3746. }, {
  3747. flushSync: (opts && opts.flushSync) === true
  3748. });
  3749. }
  3750. function getFetcher(key) {
  3751. if (future.v7_fetcherPersist) {
  3752. activeFetchers.set(key, (activeFetchers.get(key) || 0) + 1);
  3753. if (deletedFetchers.has(key)) {
  3754. deletedFetchers.delete(key);
  3755. }
  3756. }
  3757. return state.fetchers.get(key) || IDLE_FETCHER;
  3758. }
  3759. function deleteFetcher(key) {
  3760. let fetcher = state.fetchers.get(key);
  3761. if (fetchControllers.has(key) && !(fetcher && fetcher.state === "loading" && fetchReloadIds.has(key))) {
  3762. abortFetcher(key);
  3763. }
  3764. fetchLoadMatches.delete(key);
  3765. fetchReloadIds.delete(key);
  3766. fetchRedirectIds.delete(key);
  3767. deletedFetchers.delete(key);
  3768. state.fetchers.delete(key);
  3769. }
  3770. function deleteFetcherAndUpdateState(key) {
  3771. if (future.v7_fetcherPersist) {
  3772. let count = (activeFetchers.get(key) || 0) - 1;
  3773. if (count <= 0) {
  3774. activeFetchers.delete(key);
  3775. deletedFetchers.add(key);
  3776. } else {
  3777. activeFetchers.set(key, count);
  3778. }
  3779. } else {
  3780. deleteFetcher(key);
  3781. }
  3782. updateState({
  3783. fetchers: new Map(state.fetchers)
  3784. });
  3785. }
  3786. function abortFetcher(key) {
  3787. let controller = fetchControllers.get(key);
  3788. invariant(controller, "Expected fetch controller: " + key);
  3789. controller.abort();
  3790. fetchControllers.delete(key);
  3791. }
  3792. function markFetchersDone(keys) {
  3793. for (let key of keys) {
  3794. let fetcher = getFetcher(key);
  3795. let doneFetcher = getDoneFetcher(fetcher.data);
  3796. state.fetchers.set(key, doneFetcher);
  3797. }
  3798. }
  3799. function markFetchRedirectsDone() {
  3800. let doneKeys = [];
  3801. let updatedFetchers = false;
  3802. for (let key of fetchRedirectIds) {
  3803. let fetcher = state.fetchers.get(key);
  3804. invariant(fetcher, "Expected fetcher: " + key);
  3805. if (fetcher.state === "loading") {
  3806. fetchRedirectIds.delete(key);
  3807. doneKeys.push(key);
  3808. updatedFetchers = true;
  3809. }
  3810. }
  3811. markFetchersDone(doneKeys);
  3812. return updatedFetchers;
  3813. }
  3814. function abortStaleFetchLoads(landedId) {
  3815. let yeetedKeys = [];
  3816. for (let [key, id] of fetchReloadIds) {
  3817. if (id < landedId) {
  3818. let fetcher = state.fetchers.get(key);
  3819. invariant(fetcher, "Expected fetcher: " + key);
  3820. if (fetcher.state === "loading") {
  3821. abortFetcher(key);
  3822. fetchReloadIds.delete(key);
  3823. yeetedKeys.push(key);
  3824. }
  3825. }
  3826. }
  3827. markFetchersDone(yeetedKeys);
  3828. return yeetedKeys.length > 0;
  3829. }
  3830. function getBlocker(key, fn) {
  3831. let blocker = state.blockers.get(key) || IDLE_BLOCKER;
  3832. if (blockerFunctions.get(key) !== fn) {
  3833. blockerFunctions.set(key, fn);
  3834. }
  3835. return blocker;
  3836. }
  3837. function deleteBlocker(key) {
  3838. state.blockers.delete(key);
  3839. blockerFunctions.delete(key);
  3840. }
  3841. function updateBlocker(key, newBlocker) {
  3842. let blocker = state.blockers.get(key) || IDLE_BLOCKER;
  3843. invariant(blocker.state === "unblocked" && newBlocker.state === "blocked" || blocker.state === "blocked" && newBlocker.state === "blocked" || blocker.state === "blocked" && newBlocker.state === "proceeding" || blocker.state === "blocked" && newBlocker.state === "unblocked" || blocker.state === "proceeding" && newBlocker.state === "unblocked", "Invalid blocker state transition: " + blocker.state + " -> " + newBlocker.state);
  3844. let blockers = new Map(state.blockers);
  3845. blockers.set(key, newBlocker);
  3846. updateState({
  3847. blockers
  3848. });
  3849. }
  3850. function shouldBlockNavigation(_ref2) {
  3851. let {
  3852. currentLocation,
  3853. nextLocation,
  3854. historyAction
  3855. } = _ref2;
  3856. if (blockerFunctions.size === 0) {
  3857. return;
  3858. }
  3859. if (blockerFunctions.size > 1) {
  3860. warning(false, "A router only supports one blocker at a time");
  3861. }
  3862. let entries = Array.from(blockerFunctions.entries());
  3863. let [blockerKey, blockerFunction] = entries[entries.length - 1];
  3864. let blocker = state.blockers.get(blockerKey);
  3865. if (blocker && blocker.state === "proceeding") {
  3866. return;
  3867. }
  3868. if (blockerFunction({
  3869. currentLocation,
  3870. nextLocation,
  3871. historyAction
  3872. })) {
  3873. return blockerKey;
  3874. }
  3875. }
  3876. function cancelActiveDeferreds(predicate) {
  3877. let cancelledRouteIds = [];
  3878. activeDeferreds.forEach((dfd, routeId) => {
  3879. if (!predicate || predicate(routeId)) {
  3880. dfd.cancel();
  3881. cancelledRouteIds.push(routeId);
  3882. activeDeferreds.delete(routeId);
  3883. }
  3884. });
  3885. return cancelledRouteIds;
  3886. }
  3887. function enableScrollRestoration(positions, getPosition, getKey) {
  3888. savedScrollPositions = positions;
  3889. getScrollPosition = getPosition;
  3890. getScrollRestorationKey = getKey || null;
  3891. if (!initialScrollRestored && state.navigation === IDLE_NAVIGATION) {
  3892. initialScrollRestored = true;
  3893. let y2 = getSavedScrollPosition(state.location, state.matches);
  3894. if (y2 != null) {
  3895. updateState({
  3896. restoreScrollPosition: y2
  3897. });
  3898. }
  3899. }
  3900. return () => {
  3901. savedScrollPositions = null;
  3902. getScrollPosition = null;
  3903. getScrollRestorationKey = null;
  3904. };
  3905. }
  3906. function getScrollKey(location, matches) {
  3907. if (getScrollRestorationKey) {
  3908. let key = getScrollRestorationKey(location, matches.map((m) => convertRouteMatchToUiMatch(m, state.loaderData)));
  3909. return key || location.key;
  3910. }
  3911. return location.key;
  3912. }
  3913. function saveScrollPosition(location, matches) {
  3914. if (savedScrollPositions && getScrollPosition) {
  3915. let key = getScrollKey(location, matches);
  3916. savedScrollPositions[key] = getScrollPosition();
  3917. }
  3918. }
  3919. function getSavedScrollPosition(location, matches) {
  3920. if (savedScrollPositions) {
  3921. let key = getScrollKey(location, matches);
  3922. let y2 = savedScrollPositions[key];
  3923. if (typeof y2 === "number") {
  3924. return y2;
  3925. }
  3926. }
  3927. return null;
  3928. }
  3929. function _internalSetRoutes(newRoutes) {
  3930. manifest = {};
  3931. inFlightDataRoutes = convertRoutesToDataRoutes(newRoutes, mapRouteProperties, void 0, manifest);
  3932. }
  3933. router = {
  3934. get basename() {
  3935. return basename;
  3936. },
  3937. get future() {
  3938. return future;
  3939. },
  3940. get state() {
  3941. return state;
  3942. },
  3943. get routes() {
  3944. return dataRoutes;
  3945. },
  3946. get window() {
  3947. return routerWindow;
  3948. },
  3949. initialize,
  3950. subscribe,
  3951. enableScrollRestoration,
  3952. navigate,
  3953. fetch: fetch2,
  3954. revalidate,
  3955. // Passthrough to history-aware createHref used by useHref so we get proper
  3956. // hash-aware URLs in DOM paths
  3957. createHref: (to) => init.history.createHref(to),
  3958. encodeLocation: (to) => init.history.encodeLocation(to),
  3959. getFetcher,
  3960. deleteFetcher: deleteFetcherAndUpdateState,
  3961. dispose,
  3962. getBlocker,
  3963. deleteBlocker,
  3964. _internalFetchControllers: fetchControllers,
  3965. _internalActiveDeferreds: activeDeferreds,
  3966. // TODO: Remove setRoutes, it's temporary to avoid dealing with
  3967. // updating the tree while validating the update algorithm.
  3968. _internalSetRoutes
  3969. };
  3970. return router;
  3971. }
  3972. function createStaticHandler(routes2, opts) {
  3973. invariant(routes2.length > 0, "You must provide a non-empty routes array to createStaticHandler");
  3974. let manifest = {};
  3975. let basename = (opts ? opts.basename : null) || "/";
  3976. let mapRouteProperties;
  3977. if (opts != null && opts.mapRouteProperties) {
  3978. mapRouteProperties = opts.mapRouteProperties;
  3979. } else if (opts != null && opts.detectErrorBoundary) {
  3980. let detectErrorBoundary = opts.detectErrorBoundary;
  3981. mapRouteProperties = (route) => ({
  3982. hasErrorBoundary: detectErrorBoundary(route)
  3983. });
  3984. } else {
  3985. mapRouteProperties = defaultMapRouteProperties;
  3986. }
  3987. let future = _extends({
  3988. v7_relativeSplatPath: false,
  3989. v7_throwAbortReason: false
  3990. }, opts ? opts.future : null);
  3991. let dataRoutes = convertRoutesToDataRoutes(routes2, mapRouteProperties, void 0, manifest);
  3992. async function query(request, _temp3) {
  3993. let {
  3994. requestContext
  3995. } = _temp3 === void 0 ? {} : _temp3;
  3996. let url = new URL(request.url);
  3997. let method = request.method;
  3998. let location = createLocation("", createPath(url), null, "default");
  3999. let matches = matchRoutes(dataRoutes, location, basename);
  4000. if (!isValidMethod(method) && method !== "HEAD") {
  4001. let error = getInternalRouterError(405, {
  4002. method
  4003. });
  4004. let {
  4005. matches: methodNotAllowedMatches,
  4006. route
  4007. } = getShortCircuitMatches(dataRoutes);
  4008. return {
  4009. basename,
  4010. location,
  4011. matches: methodNotAllowedMatches,
  4012. loaderData: {},
  4013. actionData: null,
  4014. errors: {
  4015. [route.id]: error
  4016. },
  4017. statusCode: error.status,
  4018. loaderHeaders: {},
  4019. actionHeaders: {},
  4020. activeDeferreds: null
  4021. };
  4022. } else if (!matches) {
  4023. let error = getInternalRouterError(404, {
  4024. pathname: location.pathname
  4025. });
  4026. let {
  4027. matches: notFoundMatches,
  4028. route
  4029. } = getShortCircuitMatches(dataRoutes);
  4030. return {
  4031. basename,
  4032. location,
  4033. matches: notFoundMatches,
  4034. loaderData: {},
  4035. actionData: null,
  4036. errors: {
  4037. [route.id]: error
  4038. },
  4039. statusCode: error.status,
  4040. loaderHeaders: {},
  4041. actionHeaders: {},
  4042. activeDeferreds: null
  4043. };
  4044. }
  4045. let result = await queryImpl(request, location, matches, requestContext);
  4046. if (isResponse(result)) {
  4047. return result;
  4048. }
  4049. return _extends({
  4050. location,
  4051. basename
  4052. }, result);
  4053. }
  4054. async function queryRoute(request, _temp4) {
  4055. let {
  4056. routeId,
  4057. requestContext
  4058. } = _temp4 === void 0 ? {} : _temp4;
  4059. let url = new URL(request.url);
  4060. let method = request.method;
  4061. let location = createLocation("", createPath(url), null, "default");
  4062. let matches = matchRoutes(dataRoutes, location, basename);
  4063. if (!isValidMethod(method) && method !== "HEAD" && method !== "OPTIONS") {
  4064. throw getInternalRouterError(405, {
  4065. method
  4066. });
  4067. } else if (!matches) {
  4068. throw getInternalRouterError(404, {
  4069. pathname: location.pathname
  4070. });
  4071. }
  4072. let match = routeId ? matches.find((m) => m.route.id === routeId) : getTargetMatch(matches, location);
  4073. if (routeId && !match) {
  4074. throw getInternalRouterError(403, {
  4075. pathname: location.pathname,
  4076. routeId
  4077. });
  4078. } else if (!match) {
  4079. throw getInternalRouterError(404, {
  4080. pathname: location.pathname
  4081. });
  4082. }
  4083. let result = await queryImpl(request, location, matches, requestContext, match);
  4084. if (isResponse(result)) {
  4085. return result;
  4086. }
  4087. let error = result.errors ? Object.values(result.errors)[0] : void 0;
  4088. if (error !== void 0) {
  4089. throw error;
  4090. }
  4091. if (result.actionData) {
  4092. return Object.values(result.actionData)[0];
  4093. }
  4094. if (result.loaderData) {
  4095. var _result$activeDeferre;
  4096. let data = Object.values(result.loaderData)[0];
  4097. if ((_result$activeDeferre = result.activeDeferreds) != null && _result$activeDeferre[match.route.id]) {
  4098. data[UNSAFE_DEFERRED_SYMBOL] = result.activeDeferreds[match.route.id];
  4099. }
  4100. return data;
  4101. }
  4102. return void 0;
  4103. }
  4104. async function queryImpl(request, location, matches, requestContext, routeMatch) {
  4105. invariant(request.signal, "query()/queryRoute() requests must contain an AbortController signal");
  4106. try {
  4107. if (isMutationMethod(request.method.toLowerCase())) {
  4108. let result2 = await submit(request, matches, routeMatch || getTargetMatch(matches, location), requestContext, routeMatch != null);
  4109. return result2;
  4110. }
  4111. let result = await loadRouteData(request, matches, requestContext, routeMatch);
  4112. return isResponse(result) ? result : _extends({}, result, {
  4113. actionData: null,
  4114. actionHeaders: {}
  4115. });
  4116. } catch (e) {
  4117. if (isQueryRouteResponse(e)) {
  4118. if (e.type === ResultType.error) {
  4119. throw e.response;
  4120. }
  4121. return e.response;
  4122. }
  4123. if (isRedirectResponse(e)) {
  4124. return e;
  4125. }
  4126. throw e;
  4127. }
  4128. }
  4129. async function submit(request, matches, actionMatch, requestContext, isRouteRequest) {
  4130. let result;
  4131. if (!actionMatch.route.action && !actionMatch.route.lazy) {
  4132. let error = getInternalRouterError(405, {
  4133. method: request.method,
  4134. pathname: new URL(request.url).pathname,
  4135. routeId: actionMatch.route.id
  4136. });
  4137. if (isRouteRequest) {
  4138. throw error;
  4139. }
  4140. result = {
  4141. type: ResultType.error,
  4142. error
  4143. };
  4144. } else {
  4145. result = await callLoaderOrAction("action", request, actionMatch, matches, manifest, mapRouteProperties, basename, future.v7_relativeSplatPath, {
  4146. isStaticRequest: true,
  4147. isRouteRequest,
  4148. requestContext
  4149. });
  4150. if (request.signal.aborted) {
  4151. throwStaticHandlerAbortedError(request, isRouteRequest, future);
  4152. }
  4153. }
  4154. if (isRedirectResult(result)) {
  4155. throw new Response(null, {
  4156. status: result.status,
  4157. headers: {
  4158. Location: result.location
  4159. }
  4160. });
  4161. }
  4162. if (isDeferredResult(result)) {
  4163. let error = getInternalRouterError(400, {
  4164. type: "defer-action"
  4165. });
  4166. if (isRouteRequest) {
  4167. throw error;
  4168. }
  4169. result = {
  4170. type: ResultType.error,
  4171. error
  4172. };
  4173. }
  4174. if (isRouteRequest) {
  4175. if (isErrorResult(result)) {
  4176. throw result.error;
  4177. }
  4178. return {
  4179. matches: [actionMatch],
  4180. loaderData: {},
  4181. actionData: {
  4182. [actionMatch.route.id]: result.data
  4183. },
  4184. errors: null,
  4185. // Note: statusCode + headers are unused here since queryRoute will
  4186. // return the raw Response or value
  4187. statusCode: 200,
  4188. loaderHeaders: {},
  4189. actionHeaders: {},
  4190. activeDeferreds: null
  4191. };
  4192. }
  4193. if (isErrorResult(result)) {
  4194. let boundaryMatch = findNearestBoundary(matches, actionMatch.route.id);
  4195. let context2 = await loadRouteData(request, matches, requestContext, void 0, {
  4196. [boundaryMatch.route.id]: result.error
  4197. });
  4198. return _extends({}, context2, {
  4199. statusCode: isRouteErrorResponse(result.error) ? result.error.status : 500,
  4200. actionData: null,
  4201. actionHeaders: _extends({}, result.headers ? {
  4202. [actionMatch.route.id]: result.headers
  4203. } : {})
  4204. });
  4205. }
  4206. let loaderRequest = new Request(request.url, {
  4207. headers: request.headers,
  4208. redirect: request.redirect,
  4209. signal: request.signal
  4210. });
  4211. let context = await loadRouteData(loaderRequest, matches, requestContext);
  4212. return _extends({}, context, result.statusCode ? {
  4213. statusCode: result.statusCode
  4214. } : {}, {
  4215. actionData: {
  4216. [actionMatch.route.id]: result.data
  4217. },
  4218. actionHeaders: _extends({}, result.headers ? {
  4219. [actionMatch.route.id]: result.headers
  4220. } : {})
  4221. });
  4222. }
  4223. async function loadRouteData(request, matches, requestContext, routeMatch, pendingActionError) {
  4224. let isRouteRequest = routeMatch != null;
  4225. if (isRouteRequest && !(routeMatch != null && routeMatch.route.loader) && !(routeMatch != null && routeMatch.route.lazy)) {
  4226. throw getInternalRouterError(400, {
  4227. method: request.method,
  4228. pathname: new URL(request.url).pathname,
  4229. routeId: routeMatch == null ? void 0 : routeMatch.route.id
  4230. });
  4231. }
  4232. let requestMatches = routeMatch ? [routeMatch] : getLoaderMatchesUntilBoundary(matches, Object.keys(pendingActionError || {})[0]);
  4233. let matchesToLoad = requestMatches.filter((m) => m.route.loader || m.route.lazy);
  4234. if (matchesToLoad.length === 0) {
  4235. return {
  4236. matches,
  4237. // Add a null for all matched routes for proper revalidation on the client
  4238. loaderData: matches.reduce((acc, m) => Object.assign(acc, {
  4239. [m.route.id]: null
  4240. }), {}),
  4241. errors: pendingActionError || null,
  4242. statusCode: 200,
  4243. loaderHeaders: {},
  4244. activeDeferreds: null
  4245. };
  4246. }
  4247. let results = await Promise.all([...matchesToLoad.map((match) => callLoaderOrAction("loader", request, match, matches, manifest, mapRouteProperties, basename, future.v7_relativeSplatPath, {
  4248. isStaticRequest: true,
  4249. isRouteRequest,
  4250. requestContext
  4251. }))]);
  4252. if (request.signal.aborted) {
  4253. throwStaticHandlerAbortedError(request, isRouteRequest, future);
  4254. }
  4255. let activeDeferreds = /* @__PURE__ */ new Map();
  4256. let context = processRouteLoaderData(matches, matchesToLoad, results, pendingActionError, activeDeferreds);
  4257. let executedLoaders = new Set(matchesToLoad.map((match) => match.route.id));
  4258. matches.forEach((match) => {
  4259. if (!executedLoaders.has(match.route.id)) {
  4260. context.loaderData[match.route.id] = null;
  4261. }
  4262. });
  4263. return _extends({}, context, {
  4264. matches,
  4265. activeDeferreds: activeDeferreds.size > 0 ? Object.fromEntries(activeDeferreds.entries()) : null
  4266. });
  4267. }
  4268. return {
  4269. dataRoutes,
  4270. query,
  4271. queryRoute
  4272. };
  4273. }
  4274. function getStaticContextFromError(routes2, context, error) {
  4275. let newContext = _extends({}, context, {
  4276. statusCode: isRouteErrorResponse(error) ? error.status : 500,
  4277. errors: {
  4278. [context._deepestRenderedBoundaryId || routes2[0].id]: error
  4279. }
  4280. });
  4281. return newContext;
  4282. }
  4283. function throwStaticHandlerAbortedError(request, isRouteRequest, future) {
  4284. if (future.v7_throwAbortReason && request.signal.reason !== void 0) {
  4285. throw request.signal.reason;
  4286. }
  4287. let method = isRouteRequest ? "queryRoute" : "query";
  4288. throw new Error(method + "() call aborted: " + request.method + " " + request.url);
  4289. }
  4290. function isSubmissionNavigation(opts) {
  4291. return opts != null && ("formData" in opts && opts.formData != null || "body" in opts && opts.body !== void 0);
  4292. }
  4293. function normalizeTo(location, matches, basename, prependBasename, to, v7_relativeSplatPath, fromRouteId, relative) {
  4294. let contextualMatches;
  4295. let activeRouteMatch;
  4296. if (fromRouteId) {
  4297. contextualMatches = [];
  4298. for (let match of matches) {
  4299. contextualMatches.push(match);
  4300. if (match.route.id === fromRouteId) {
  4301. activeRouteMatch = match;
  4302. break;
  4303. }
  4304. }
  4305. } else {
  4306. contextualMatches = matches;
  4307. activeRouteMatch = matches[matches.length - 1];
  4308. }
  4309. let path = resolveTo(to ? to : ".", getResolveToMatches(contextualMatches, v7_relativeSplatPath), stripBasename(location.pathname, basename) || location.pathname, relative === "path");
  4310. if (to == null) {
  4311. path.search = location.search;
  4312. path.hash = location.hash;
  4313. }
  4314. if ((to == null || to === "" || to === ".") && activeRouteMatch && activeRouteMatch.route.index && !hasNakedIndexQuery(path.search)) {
  4315. path.search = path.search ? path.search.replace(/^\?/, "?index&") : "?index";
  4316. }
  4317. if (prependBasename && basename !== "/") {
  4318. path.pathname = path.pathname === "/" ? basename : joinPaths([basename, path.pathname]);
  4319. }
  4320. return createPath(path);
  4321. }
  4322. function normalizeNavigateOptions(normalizeFormMethod, isFetcher, path, opts) {
  4323. if (!opts || !isSubmissionNavigation(opts)) {
  4324. return {
  4325. path
  4326. };
  4327. }
  4328. if (opts.formMethod && !isValidMethod(opts.formMethod)) {
  4329. return {
  4330. path,
  4331. error: getInternalRouterError(405, {
  4332. method: opts.formMethod
  4333. })
  4334. };
  4335. }
  4336. let getInvalidBodyError = () => ({
  4337. path,
  4338. error: getInternalRouterError(400, {
  4339. type: "invalid-body"
  4340. })
  4341. });
  4342. let rawFormMethod = opts.formMethod || "get";
  4343. let formMethod = normalizeFormMethod ? rawFormMethod.toUpperCase() : rawFormMethod.toLowerCase();
  4344. let formAction = stripHashFromPath(path);
  4345. if (opts.body !== void 0) {
  4346. if (opts.formEncType === "text/plain") {
  4347. if (!isMutationMethod(formMethod)) {
  4348. return getInvalidBodyError();
  4349. }
  4350. let text = typeof opts.body === "string" ? opts.body : opts.body instanceof FormData || opts.body instanceof URLSearchParams ? (
  4351. // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#plain-text-form-data
  4352. Array.from(opts.body.entries()).reduce((acc, _ref3) => {
  4353. let [name, value] = _ref3;
  4354. return "" + acc + name + "=" + value + "\n";
  4355. }, "")
  4356. ) : String(opts.body);
  4357. return {
  4358. path,
  4359. submission: {
  4360. formMethod,
  4361. formAction,
  4362. formEncType: opts.formEncType,
  4363. formData: void 0,
  4364. json: void 0,
  4365. text
  4366. }
  4367. };
  4368. } else if (opts.formEncType === "application/json") {
  4369. if (!isMutationMethod(formMethod)) {
  4370. return getInvalidBodyError();
  4371. }
  4372. try {
  4373. let json5 = typeof opts.body === "string" ? JSON.parse(opts.body) : opts.body;
  4374. return {
  4375. path,
  4376. submission: {
  4377. formMethod,
  4378. formAction,
  4379. formEncType: opts.formEncType,
  4380. formData: void 0,
  4381. json: json5,
  4382. text: void 0
  4383. }
  4384. };
  4385. } catch (e) {
  4386. return getInvalidBodyError();
  4387. }
  4388. }
  4389. }
  4390. invariant(typeof FormData === "function", "FormData is not available in this environment");
  4391. let searchParams;
  4392. let formData;
  4393. if (opts.formData) {
  4394. searchParams = convertFormDataToSearchParams(opts.formData);
  4395. formData = opts.formData;
  4396. } else if (opts.body instanceof FormData) {
  4397. searchParams = convertFormDataToSearchParams(opts.body);
  4398. formData = opts.body;
  4399. } else if (opts.body instanceof URLSearchParams) {
  4400. searchParams = opts.body;
  4401. formData = convertSearchParamsToFormData(searchParams);
  4402. } else if (opts.body == null) {
  4403. searchParams = new URLSearchParams();
  4404. formData = new FormData();
  4405. } else {
  4406. try {
  4407. searchParams = new URLSearchParams(opts.body);
  4408. formData = convertSearchParamsToFormData(searchParams);
  4409. } catch (e) {
  4410. return getInvalidBodyError();
  4411. }
  4412. }
  4413. let submission = {
  4414. formMethod,
  4415. formAction,
  4416. formEncType: opts && opts.formEncType || "application/x-www-form-urlencoded",
  4417. formData,
  4418. json: void 0,
  4419. text: void 0
  4420. };
  4421. if (isMutationMethod(submission.formMethod)) {
  4422. return {
  4423. path,
  4424. submission
  4425. };
  4426. }
  4427. let parsedPath = parsePath(path);
  4428. if (isFetcher && parsedPath.search && hasNakedIndexQuery(parsedPath.search)) {
  4429. searchParams.append("index", "");
  4430. }
  4431. parsedPath.search = "?" + searchParams;
  4432. return {
  4433. path: createPath(parsedPath),
  4434. submission
  4435. };
  4436. }
  4437. function getLoaderMatchesUntilBoundary(matches, boundaryId) {
  4438. let boundaryMatches = matches;
  4439. if (boundaryId) {
  4440. let index = matches.findIndex((m) => m.route.id === boundaryId);
  4441. if (index >= 0) {
  4442. boundaryMatches = matches.slice(0, index);
  4443. }
  4444. }
  4445. return boundaryMatches;
  4446. }
  4447. function getMatchesToLoad(history, state, matches, submission, location, isInitialLoad, isRevalidationRequired, cancelledDeferredRoutes, cancelledFetcherLoads, deletedFetchers, fetchLoadMatches, fetchRedirectIds, routesToUse, basename, pendingActionData, pendingError) {
  4448. let actionResult = pendingError ? Object.values(pendingError)[0] : pendingActionData ? Object.values(pendingActionData)[0] : void 0;
  4449. let currentUrl = history.createURL(state.location);
  4450. let nextUrl = history.createURL(location);
  4451. let boundaryId = pendingError ? Object.keys(pendingError)[0] : void 0;
  4452. let boundaryMatches = getLoaderMatchesUntilBoundary(matches, boundaryId);
  4453. let navigationMatches = boundaryMatches.filter((match, index) => {
  4454. let {
  4455. route
  4456. } = match;
  4457. if (route.lazy) {
  4458. return true;
  4459. }
  4460. if (route.loader == null) {
  4461. return false;
  4462. }
  4463. if (isInitialLoad) {
  4464. if (route.loader.hydrate) {
  4465. return true;
  4466. }
  4467. return state.loaderData[route.id] === void 0 && // Don't re-run if the loader ran and threw an error
  4468. (!state.errors || state.errors[route.id] === void 0);
  4469. }
  4470. if (isNewLoader(state.loaderData, state.matches[index], match) || cancelledDeferredRoutes.some((id) => id === match.route.id)) {
  4471. return true;
  4472. }
  4473. let currentRouteMatch = state.matches[index];
  4474. let nextRouteMatch = match;
  4475. return shouldRevalidateLoader(match, _extends({
  4476. currentUrl,
  4477. currentParams: currentRouteMatch.params,
  4478. nextUrl,
  4479. nextParams: nextRouteMatch.params
  4480. }, submission, {
  4481. actionResult,
  4482. defaultShouldRevalidate: (
  4483. // Forced revalidation due to submission, useRevalidator, or X-Remix-Revalidate
  4484. isRevalidationRequired || // Clicked the same link, resubmitted a GET form
  4485. currentUrl.pathname + currentUrl.search === nextUrl.pathname + nextUrl.search || // Search params affect all loaders
  4486. currentUrl.search !== nextUrl.search || isNewRouteInstance(currentRouteMatch, nextRouteMatch)
  4487. )
  4488. }));
  4489. });
  4490. let revalidatingFetchers = [];
  4491. fetchLoadMatches.forEach((f2, key) => {
  4492. if (isInitialLoad || !matches.some((m) => m.route.id === f2.routeId) || deletedFetchers.has(key)) {
  4493. return;
  4494. }
  4495. let fetcherMatches = matchRoutes(routesToUse, f2.path, basename);
  4496. if (!fetcherMatches) {
  4497. revalidatingFetchers.push({
  4498. key,
  4499. routeId: f2.routeId,
  4500. path: f2.path,
  4501. matches: null,
  4502. match: null,
  4503. controller: null
  4504. });
  4505. return;
  4506. }
  4507. let fetcher = state.fetchers.get(key);
  4508. let fetcherMatch = getTargetMatch(fetcherMatches, f2.path);
  4509. let shouldRevalidate = false;
  4510. if (fetchRedirectIds.has(key)) {
  4511. shouldRevalidate = false;
  4512. } else if (cancelledFetcherLoads.includes(key)) {
  4513. shouldRevalidate = true;
  4514. } else if (fetcher && fetcher.state !== "idle" && fetcher.data === void 0) {
  4515. shouldRevalidate = isRevalidationRequired;
  4516. } else {
  4517. shouldRevalidate = shouldRevalidateLoader(fetcherMatch, _extends({
  4518. currentUrl,
  4519. currentParams: state.matches[state.matches.length - 1].params,
  4520. nextUrl,
  4521. nextParams: matches[matches.length - 1].params
  4522. }, submission, {
  4523. actionResult,
  4524. defaultShouldRevalidate: isRevalidationRequired
  4525. }));
  4526. }
  4527. if (shouldRevalidate) {
  4528. revalidatingFetchers.push({
  4529. key,
  4530. routeId: f2.routeId,
  4531. path: f2.path,
  4532. matches: fetcherMatches,
  4533. match: fetcherMatch,
  4534. controller: new AbortController()
  4535. });
  4536. }
  4537. });
  4538. return [navigationMatches, revalidatingFetchers];
  4539. }
  4540. function isNewLoader(currentLoaderData, currentMatch, match) {
  4541. let isNew = (
  4542. // [a] -> [a, b]
  4543. !currentMatch || // [a, b] -> [a, c]
  4544. match.route.id !== currentMatch.route.id
  4545. );
  4546. let isMissingData = currentLoaderData[match.route.id] === void 0;
  4547. return isNew || isMissingData;
  4548. }
  4549. function isNewRouteInstance(currentMatch, match) {
  4550. let currentPath = currentMatch.route.path;
  4551. return (
  4552. // param change for this match, /users/123 -> /users/456
  4553. currentMatch.pathname !== match.pathname || // splat param changed, which is not present in match.path
  4554. // e.g. /files/images/avatar.jpg -> files/finances.xls
  4555. currentPath != null && currentPath.endsWith("*") && currentMatch.params["*"] !== match.params["*"]
  4556. );
  4557. }
  4558. function shouldRevalidateLoader(loaderMatch, arg) {
  4559. if (loaderMatch.route.shouldRevalidate) {
  4560. let routeChoice = loaderMatch.route.shouldRevalidate(arg);
  4561. if (typeof routeChoice === "boolean") {
  4562. return routeChoice;
  4563. }
  4564. }
  4565. return arg.defaultShouldRevalidate;
  4566. }
  4567. async function loadLazyRouteModule(route, mapRouteProperties, manifest) {
  4568. if (!route.lazy) {
  4569. return;
  4570. }
  4571. let lazyRoute = await route.lazy();
  4572. if (!route.lazy) {
  4573. return;
  4574. }
  4575. let routeToUpdate = manifest[route.id];
  4576. invariant(routeToUpdate, "No route found in manifest");
  4577. let routeUpdates = {};
  4578. for (let lazyRouteProperty in lazyRoute) {
  4579. let staticRouteValue = routeToUpdate[lazyRouteProperty];
  4580. let isPropertyStaticallyDefined = staticRouteValue !== void 0 && // This property isn't static since it should always be updated based
  4581. // on the route updates
  4582. lazyRouteProperty !== "hasErrorBoundary";
  4583. warning(!isPropertyStaticallyDefined, 'Route "' + routeToUpdate.id + '" has a static property "' + lazyRouteProperty + '" defined but its lazy function is also returning a value for this property. ' + ('The lazy route property "' + lazyRouteProperty + '" will be ignored.'));
  4584. if (!isPropertyStaticallyDefined && !immutableRouteKeys.has(lazyRouteProperty)) {
  4585. routeUpdates[lazyRouteProperty] = lazyRoute[lazyRouteProperty];
  4586. }
  4587. }
  4588. Object.assign(routeToUpdate, routeUpdates);
  4589. Object.assign(routeToUpdate, _extends({}, mapRouteProperties(routeToUpdate), {
  4590. lazy: void 0
  4591. }));
  4592. }
  4593. async function callLoaderOrAction(type, request, match, matches, manifest, mapRouteProperties, basename, v7_relativeSplatPath, opts) {
  4594. if (opts === void 0) {
  4595. opts = {};
  4596. }
  4597. let resultType;
  4598. let result;
  4599. let onReject;
  4600. let runHandler = (handler2) => {
  4601. let reject;
  4602. let abortPromise = new Promise((_, r) => reject = r);
  4603. onReject = () => reject();
  4604. request.signal.addEventListener("abort", onReject);
  4605. return Promise.race([handler2({
  4606. request,
  4607. params: match.params,
  4608. context: opts.requestContext
  4609. }), abortPromise]);
  4610. };
  4611. try {
  4612. let handler2 = match.route[type];
  4613. if (match.route.lazy) {
  4614. if (handler2) {
  4615. let handlerError;
  4616. let values = await Promise.all([
  4617. // If the handler throws, don't let it immediately bubble out,
  4618. // since we need to let the lazy() execution finish so we know if this
  4619. // route has a boundary that can handle the error
  4620. runHandler(handler2).catch((e) => {
  4621. handlerError = e;
  4622. }),
  4623. loadLazyRouteModule(match.route, mapRouteProperties, manifest)
  4624. ]);
  4625. if (handlerError) {
  4626. throw handlerError;
  4627. }
  4628. result = values[0];
  4629. } else {
  4630. await loadLazyRouteModule(match.route, mapRouteProperties, manifest);
  4631. handler2 = match.route[type];
  4632. if (handler2) {
  4633. result = await runHandler(handler2);
  4634. } else if (type === "action") {
  4635. let url = new URL(request.url);
  4636. let pathname = url.pathname + url.search;
  4637. throw getInternalRouterError(405, {
  4638. method: request.method,
  4639. pathname,
  4640. routeId: match.route.id
  4641. });
  4642. } else {
  4643. return {
  4644. type: ResultType.data,
  4645. data: void 0
  4646. };
  4647. }
  4648. }
  4649. } else if (!handler2) {
  4650. let url = new URL(request.url);
  4651. let pathname = url.pathname + url.search;
  4652. throw getInternalRouterError(404, {
  4653. pathname
  4654. });
  4655. } else {
  4656. result = await runHandler(handler2);
  4657. }
  4658. invariant(result !== void 0, "You defined " + (type === "action" ? "an action" : "a loader") + " for route " + ('"' + match.route.id + "\" but didn't return anything from your `" + type + "` ") + "function. Please return a value or `null`.");
  4659. } catch (e) {
  4660. resultType = ResultType.error;
  4661. result = e;
  4662. } finally {
  4663. if (onReject) {
  4664. request.signal.removeEventListener("abort", onReject);
  4665. }
  4666. }
  4667. if (isResponse(result)) {
  4668. let status = result.status;
  4669. if (redirectStatusCodes.has(status)) {
  4670. let location = result.headers.get("Location");
  4671. invariant(location, "Redirects returned/thrown from loaders/actions must have a Location header");
  4672. if (!ABSOLUTE_URL_REGEX.test(location)) {
  4673. location = normalizeTo(new URL(request.url), matches.slice(0, matches.indexOf(match) + 1), basename, true, location, v7_relativeSplatPath);
  4674. } else if (!opts.isStaticRequest) {
  4675. let currentUrl = new URL(request.url);
  4676. let url = location.startsWith("//") ? new URL(currentUrl.protocol + location) : new URL(location);
  4677. let isSameBasename = stripBasename(url.pathname, basename) != null;
  4678. if (url.origin === currentUrl.origin && isSameBasename) {
  4679. location = url.pathname + url.search + url.hash;
  4680. }
  4681. }
  4682. if (opts.isStaticRequest) {
  4683. result.headers.set("Location", location);
  4684. throw result;
  4685. }
  4686. return {
  4687. type: ResultType.redirect,
  4688. status,
  4689. location,
  4690. revalidate: result.headers.get("X-Remix-Revalidate") !== null,
  4691. reloadDocument: result.headers.get("X-Remix-Reload-Document") !== null
  4692. };
  4693. }
  4694. if (opts.isRouteRequest) {
  4695. let queryRouteResponse = {
  4696. type: resultType === ResultType.error ? ResultType.error : ResultType.data,
  4697. response: result
  4698. };
  4699. throw queryRouteResponse;
  4700. }
  4701. let data;
  4702. try {
  4703. let contentType = result.headers.get("Content-Type");
  4704. if (contentType && /\bapplication\/json\b/.test(contentType)) {
  4705. if (result.body == null) {
  4706. data = null;
  4707. } else {
  4708. data = await result.json();
  4709. }
  4710. } else {
  4711. data = await result.text();
  4712. }
  4713. } catch (e) {
  4714. return {
  4715. type: ResultType.error,
  4716. error: e
  4717. };
  4718. }
  4719. if (resultType === ResultType.error) {
  4720. return {
  4721. type: resultType,
  4722. error: new ErrorResponseImpl(status, result.statusText, data),
  4723. headers: result.headers
  4724. };
  4725. }
  4726. return {
  4727. type: ResultType.data,
  4728. data,
  4729. statusCode: result.status,
  4730. headers: result.headers
  4731. };
  4732. }
  4733. if (resultType === ResultType.error) {
  4734. return {
  4735. type: resultType,
  4736. error: result
  4737. };
  4738. }
  4739. if (isDeferredData(result)) {
  4740. var _result$init, _result$init2;
  4741. return {
  4742. type: ResultType.deferred,
  4743. deferredData: result,
  4744. statusCode: (_result$init = result.init) == null ? void 0 : _result$init.status,
  4745. headers: ((_result$init2 = result.init) == null ? void 0 : _result$init2.headers) && new Headers(result.init.headers)
  4746. };
  4747. }
  4748. return {
  4749. type: ResultType.data,
  4750. data: result
  4751. };
  4752. }
  4753. function createClientSideRequest(history, location, signal, submission) {
  4754. let url = history.createURL(stripHashFromPath(location)).toString();
  4755. let init = {
  4756. signal
  4757. };
  4758. if (submission && isMutationMethod(submission.formMethod)) {
  4759. let {
  4760. formMethod,
  4761. formEncType
  4762. } = submission;
  4763. init.method = formMethod.toUpperCase();
  4764. if (formEncType === "application/json") {
  4765. init.headers = new Headers({
  4766. "Content-Type": formEncType
  4767. });
  4768. init.body = JSON.stringify(submission.json);
  4769. } else if (formEncType === "text/plain") {
  4770. init.body = submission.text;
  4771. } else if (formEncType === "application/x-www-form-urlencoded" && submission.formData) {
  4772. init.body = convertFormDataToSearchParams(submission.formData);
  4773. } else {
  4774. init.body = submission.formData;
  4775. }
  4776. }
  4777. return new Request(url, init);
  4778. }
  4779. function convertFormDataToSearchParams(formData) {
  4780. let searchParams = new URLSearchParams();
  4781. for (let [key, value] of formData.entries()) {
  4782. searchParams.append(key, typeof value === "string" ? value : value.name);
  4783. }
  4784. return searchParams;
  4785. }
  4786. function convertSearchParamsToFormData(searchParams) {
  4787. let formData = new FormData();
  4788. for (let [key, value] of searchParams.entries()) {
  4789. formData.append(key, value);
  4790. }
  4791. return formData;
  4792. }
  4793. function processRouteLoaderData(matches, matchesToLoad, results, pendingError, activeDeferreds) {
  4794. let loaderData = {};
  4795. let errors = null;
  4796. let statusCode;
  4797. let foundError = false;
  4798. let loaderHeaders = {};
  4799. results.forEach((result, index) => {
  4800. let id = matchesToLoad[index].route.id;
  4801. invariant(!isRedirectResult(result), "Cannot handle redirect results in processLoaderData");
  4802. if (isErrorResult(result)) {
  4803. let boundaryMatch = findNearestBoundary(matches, id);
  4804. let error = result.error;
  4805. if (pendingError) {
  4806. error = Object.values(pendingError)[0];
  4807. pendingError = void 0;
  4808. }
  4809. errors = errors || {};
  4810. if (errors[boundaryMatch.route.id] == null) {
  4811. errors[boundaryMatch.route.id] = error;
  4812. }
  4813. loaderData[id] = void 0;
  4814. if (!foundError) {
  4815. foundError = true;
  4816. statusCode = isRouteErrorResponse(result.error) ? result.error.status : 500;
  4817. }
  4818. if (result.headers) {
  4819. loaderHeaders[id] = result.headers;
  4820. }
  4821. } else {
  4822. if (isDeferredResult(result)) {
  4823. activeDeferreds.set(id, result.deferredData);
  4824. loaderData[id] = result.deferredData.data;
  4825. } else {
  4826. loaderData[id] = result.data;
  4827. }
  4828. if (result.statusCode != null && result.statusCode !== 200 && !foundError) {
  4829. statusCode = result.statusCode;
  4830. }
  4831. if (result.headers) {
  4832. loaderHeaders[id] = result.headers;
  4833. }
  4834. }
  4835. });
  4836. if (pendingError) {
  4837. errors = pendingError;
  4838. loaderData[Object.keys(pendingError)[0]] = void 0;
  4839. }
  4840. return {
  4841. loaderData,
  4842. errors,
  4843. statusCode: statusCode || 200,
  4844. loaderHeaders
  4845. };
  4846. }
  4847. function processLoaderData(state, matches, matchesToLoad, results, pendingError, revalidatingFetchers, fetcherResults, activeDeferreds) {
  4848. let {
  4849. loaderData,
  4850. errors
  4851. } = processRouteLoaderData(matches, matchesToLoad, results, pendingError, activeDeferreds);
  4852. for (let index = 0; index < revalidatingFetchers.length; index++) {
  4853. let {
  4854. key,
  4855. match,
  4856. controller
  4857. } = revalidatingFetchers[index];
  4858. invariant(fetcherResults !== void 0 && fetcherResults[index] !== void 0, "Did not find corresponding fetcher result");
  4859. let result = fetcherResults[index];
  4860. if (controller && controller.signal.aborted) {
  4861. continue;
  4862. } else if (isErrorResult(result)) {
  4863. let boundaryMatch = findNearestBoundary(state.matches, match == null ? void 0 : match.route.id);
  4864. if (!(errors && errors[boundaryMatch.route.id])) {
  4865. errors = _extends({}, errors, {
  4866. [boundaryMatch.route.id]: result.error
  4867. });
  4868. }
  4869. state.fetchers.delete(key);
  4870. } else if (isRedirectResult(result)) {
  4871. invariant(false, "Unhandled fetcher revalidation redirect");
  4872. } else if (isDeferredResult(result)) {
  4873. invariant(false, "Unhandled fetcher deferred data");
  4874. } else {
  4875. let doneFetcher = getDoneFetcher(result.data);
  4876. state.fetchers.set(key, doneFetcher);
  4877. }
  4878. }
  4879. return {
  4880. loaderData,
  4881. errors
  4882. };
  4883. }
  4884. function mergeLoaderData(loaderData, newLoaderData, matches, errors) {
  4885. let mergedLoaderData = _extends({}, newLoaderData);
  4886. for (let match of matches) {
  4887. let id = match.route.id;
  4888. if (newLoaderData.hasOwnProperty(id)) {
  4889. if (newLoaderData[id] !== void 0) {
  4890. mergedLoaderData[id] = newLoaderData[id];
  4891. }
  4892. } else if (loaderData[id] !== void 0 && match.route.loader) {
  4893. mergedLoaderData[id] = loaderData[id];
  4894. }
  4895. if (errors && errors.hasOwnProperty(id)) {
  4896. break;
  4897. }
  4898. }
  4899. return mergedLoaderData;
  4900. }
  4901. function findNearestBoundary(matches, routeId) {
  4902. let eligibleMatches = routeId ? matches.slice(0, matches.findIndex((m) => m.route.id === routeId) + 1) : [...matches];
  4903. return eligibleMatches.reverse().find((m) => m.route.hasErrorBoundary === true) || matches[0];
  4904. }
  4905. function getShortCircuitMatches(routes2) {
  4906. let route = routes2.length === 1 ? routes2[0] : routes2.find((r) => r.index || !r.path || r.path === "/") || {
  4907. id: "__shim-error-route__"
  4908. };
  4909. return {
  4910. matches: [{
  4911. params: {},
  4912. pathname: "",
  4913. pathnameBase: "",
  4914. route
  4915. }],
  4916. route
  4917. };
  4918. }
  4919. function getInternalRouterError(status, _temp5) {
  4920. let {
  4921. pathname,
  4922. routeId,
  4923. method,
  4924. type
  4925. } = _temp5 === void 0 ? {} : _temp5;
  4926. let statusText = "Unknown Server Error";
  4927. let errorMessage = "Unknown @remix-run/router error";
  4928. if (status === 400) {
  4929. statusText = "Bad Request";
  4930. if (method && pathname && routeId) {
  4931. errorMessage = "You made a " + method + ' request to "' + pathname + '" but ' + ('did not provide a `loader` for route "' + routeId + '", ') + "so there is no way to handle the request.";
  4932. } else if (type === "defer-action") {
  4933. errorMessage = "defer() is not supported in actions";
  4934. } else if (type === "invalid-body") {
  4935. errorMessage = "Unable to encode submission body";
  4936. }
  4937. } else if (status === 403) {
  4938. statusText = "Forbidden";
  4939. errorMessage = 'Route "' + routeId + '" does not match URL "' + pathname + '"';
  4940. } else if (status === 404) {
  4941. statusText = "Not Found";
  4942. errorMessage = 'No route matches URL "' + pathname + '"';
  4943. } else if (status === 405) {
  4944. statusText = "Method Not Allowed";
  4945. if (method && pathname && routeId) {
  4946. errorMessage = "You made a " + method.toUpperCase() + ' request to "' + pathname + '" but ' + ('did not provide an `action` for route "' + routeId + '", ') + "so there is no way to handle the request.";
  4947. } else if (method) {
  4948. errorMessage = 'Invalid request method "' + method.toUpperCase() + '"';
  4949. }
  4950. }
  4951. return new ErrorResponseImpl(status || 500, statusText, new Error(errorMessage), true);
  4952. }
  4953. function findRedirect(results) {
  4954. for (let i = results.length - 1; i >= 0; i--) {
  4955. let result = results[i];
  4956. if (isRedirectResult(result)) {
  4957. return {
  4958. result,
  4959. idx: i
  4960. };
  4961. }
  4962. }
  4963. }
  4964. function stripHashFromPath(path) {
  4965. let parsedPath = typeof path === "string" ? parsePath(path) : path;
  4966. return createPath(_extends({}, parsedPath, {
  4967. hash: ""
  4968. }));
  4969. }
  4970. function isHashChangeOnly(a, b2) {
  4971. if (a.pathname !== b2.pathname || a.search !== b2.search) {
  4972. return false;
  4973. }
  4974. if (a.hash === "") {
  4975. return b2.hash !== "";
  4976. } else if (a.hash === b2.hash) {
  4977. return true;
  4978. } else if (b2.hash !== "") {
  4979. return true;
  4980. }
  4981. return false;
  4982. }
  4983. function isDeferredResult(result) {
  4984. return result.type === ResultType.deferred;
  4985. }
  4986. function isErrorResult(result) {
  4987. return result.type === ResultType.error;
  4988. }
  4989. function isRedirectResult(result) {
  4990. return (result && result.type) === ResultType.redirect;
  4991. }
  4992. function isDeferredData(value) {
  4993. let deferred = value;
  4994. return deferred && typeof deferred === "object" && typeof deferred.data === "object" && typeof deferred.subscribe === "function" && typeof deferred.cancel === "function" && typeof deferred.resolveData === "function";
  4995. }
  4996. function isResponse(value) {
  4997. return value != null && typeof value.status === "number" && typeof value.statusText === "string" && typeof value.headers === "object" && typeof value.body !== "undefined";
  4998. }
  4999. function isRedirectResponse(result) {
  5000. if (!isResponse(result)) {
  5001. return false;
  5002. }
  5003. let status = result.status;
  5004. let location = result.headers.get("Location");
  5005. return status >= 300 && status <= 399 && location != null;
  5006. }
  5007. function isQueryRouteResponse(obj) {
  5008. return obj && isResponse(obj.response) && (obj.type === ResultType.data || obj.type === ResultType.error);
  5009. }
  5010. function isValidMethod(method) {
  5011. return validRequestMethods.has(method.toLowerCase());
  5012. }
  5013. function isMutationMethod(method) {
  5014. return validMutationMethods.has(method.toLowerCase());
  5015. }
  5016. async function resolveDeferredResults(currentMatches, matchesToLoad, results, signals, isFetcher, currentLoaderData) {
  5017. for (let index = 0; index < results.length; index++) {
  5018. let result = results[index];
  5019. let match = matchesToLoad[index];
  5020. if (!match) {
  5021. continue;
  5022. }
  5023. let currentMatch = currentMatches.find((m) => m.route.id === match.route.id);
  5024. let isRevalidatingLoader = currentMatch != null && !isNewRouteInstance(currentMatch, match) && (currentLoaderData && currentLoaderData[match.route.id]) !== void 0;
  5025. if (isDeferredResult(result) && (isFetcher || isRevalidatingLoader)) {
  5026. let signal = signals[index];
  5027. invariant(signal, "Expected an AbortSignal for revalidating fetcher deferred result");
  5028. await resolveDeferredData(result, signal, isFetcher).then((result2) => {
  5029. if (result2) {
  5030. results[index] = result2 || results[index];
  5031. }
  5032. });
  5033. }
  5034. }
  5035. }
  5036. async function resolveDeferredData(result, signal, unwrap) {
  5037. if (unwrap === void 0) {
  5038. unwrap = false;
  5039. }
  5040. let aborted = await result.deferredData.resolveData(signal);
  5041. if (aborted) {
  5042. return;
  5043. }
  5044. if (unwrap) {
  5045. try {
  5046. return {
  5047. type: ResultType.data,
  5048. data: result.deferredData.unwrappedData
  5049. };
  5050. } catch (e) {
  5051. return {
  5052. type: ResultType.error,
  5053. error: e
  5054. };
  5055. }
  5056. }
  5057. return {
  5058. type: ResultType.data,
  5059. data: result.deferredData.data
  5060. };
  5061. }
  5062. function hasNakedIndexQuery(search) {
  5063. return new URLSearchParams(search).getAll("index").some((v) => v === "");
  5064. }
  5065. function getTargetMatch(matches, location) {
  5066. let search = typeof location === "string" ? parsePath(location).search : location.search;
  5067. if (matches[matches.length - 1].route.index && hasNakedIndexQuery(search || "")) {
  5068. return matches[matches.length - 1];
  5069. }
  5070. let pathMatches = getPathContributingMatches(matches);
  5071. return pathMatches[pathMatches.length - 1];
  5072. }
  5073. function getSubmissionFromNavigation(navigation) {
  5074. let {
  5075. formMethod,
  5076. formAction,
  5077. formEncType,
  5078. text,
  5079. formData,
  5080. json: json5
  5081. } = navigation;
  5082. if (!formMethod || !formAction || !formEncType) {
  5083. return;
  5084. }
  5085. if (text != null) {
  5086. return {
  5087. formMethod,
  5088. formAction,
  5089. formEncType,
  5090. formData: void 0,
  5091. json: void 0,
  5092. text
  5093. };
  5094. } else if (formData != null) {
  5095. return {
  5096. formMethod,
  5097. formAction,
  5098. formEncType,
  5099. formData,
  5100. json: void 0,
  5101. text: void 0
  5102. };
  5103. } else if (json5 !== void 0) {
  5104. return {
  5105. formMethod,
  5106. formAction,
  5107. formEncType,
  5108. formData: void 0,
  5109. json: json5,
  5110. text: void 0
  5111. };
  5112. }
  5113. }
  5114. function getLoadingNavigation(location, submission) {
  5115. if (submission) {
  5116. let navigation = {
  5117. state: "loading",
  5118. location,
  5119. formMethod: submission.formMethod,
  5120. formAction: submission.formAction,
  5121. formEncType: submission.formEncType,
  5122. formData: submission.formData,
  5123. json: submission.json,
  5124. text: submission.text
  5125. };
  5126. return navigation;
  5127. } else {
  5128. let navigation = {
  5129. state: "loading",
  5130. location,
  5131. formMethod: void 0,
  5132. formAction: void 0,
  5133. formEncType: void 0,
  5134. formData: void 0,
  5135. json: void 0,
  5136. text: void 0
  5137. };
  5138. return navigation;
  5139. }
  5140. }
  5141. function getSubmittingNavigation(location, submission) {
  5142. let navigation = {
  5143. state: "submitting",
  5144. location,
  5145. formMethod: submission.formMethod,
  5146. formAction: submission.formAction,
  5147. formEncType: submission.formEncType,
  5148. formData: submission.formData,
  5149. json: submission.json,
  5150. text: submission.text
  5151. };
  5152. return navigation;
  5153. }
  5154. function getLoadingFetcher(submission, data) {
  5155. if (submission) {
  5156. let fetcher = {
  5157. state: "loading",
  5158. formMethod: submission.formMethod,
  5159. formAction: submission.formAction,
  5160. formEncType: submission.formEncType,
  5161. formData: submission.formData,
  5162. json: submission.json,
  5163. text: submission.text,
  5164. data
  5165. };
  5166. return fetcher;
  5167. } else {
  5168. let fetcher = {
  5169. state: "loading",
  5170. formMethod: void 0,
  5171. formAction: void 0,
  5172. formEncType: void 0,
  5173. formData: void 0,
  5174. json: void 0,
  5175. text: void 0,
  5176. data
  5177. };
  5178. return fetcher;
  5179. }
  5180. }
  5181. function getSubmittingFetcher(submission, existingFetcher) {
  5182. let fetcher = {
  5183. state: "submitting",
  5184. formMethod: submission.formMethod,
  5185. formAction: submission.formAction,
  5186. formEncType: submission.formEncType,
  5187. formData: submission.formData,
  5188. json: submission.json,
  5189. text: submission.text,
  5190. data: existingFetcher ? existingFetcher.data : void 0
  5191. };
  5192. return fetcher;
  5193. }
  5194. function getDoneFetcher(data) {
  5195. let fetcher = {
  5196. state: "idle",
  5197. formMethod: void 0,
  5198. formAction: void 0,
  5199. formEncType: void 0,
  5200. formData: void 0,
  5201. json: void 0,
  5202. text: void 0,
  5203. data
  5204. };
  5205. return fetcher;
  5206. }
  5207. function restoreAppliedTransitions(_window, transitions) {
  5208. try {
  5209. let sessionPositions = _window.sessionStorage.getItem(TRANSITIONS_STORAGE_KEY);
  5210. if (sessionPositions) {
  5211. let json5 = JSON.parse(sessionPositions);
  5212. for (let [k2, v] of Object.entries(json5 || {})) {
  5213. if (v && Array.isArray(v)) {
  5214. transitions.set(k2, new Set(v || []));
  5215. }
  5216. }
  5217. }
  5218. } catch (e) {
  5219. }
  5220. }
  5221. function persistAppliedTransitions(_window, transitions) {
  5222. if (transitions.size > 0) {
  5223. let json5 = {};
  5224. for (let [k2, v] of transitions) {
  5225. json5[k2] = [...v];
  5226. }
  5227. try {
  5228. _window.sessionStorage.setItem(TRANSITIONS_STORAGE_KEY, JSON.stringify(json5));
  5229. } catch (error) {
  5230. warning(false, "Failed to save applied view transitions in sessionStorage (" + error + ").");
  5231. }
  5232. }
  5233. }
  5234. var Action, PopStateEventType, ResultType, immutableRouteKeys, paramRe, dynamicSegmentValue, indexRouteValue, emptySegmentValue, staticSegmentValue, splatPenalty, isSplat, joinPaths, normalizePathname, normalizeSearch, normalizeHash, json, AbortedDeferredError, DeferredData, defer, redirect, redirectDocument, ErrorResponseImpl, validMutationMethodsArr, validMutationMethods, validRequestMethodsArr, validRequestMethods, redirectStatusCodes, redirectPreserveMethodStatusCodes, IDLE_NAVIGATION, IDLE_FETCHER, IDLE_BLOCKER, ABSOLUTE_URL_REGEX, defaultMapRouteProperties, TRANSITIONS_STORAGE_KEY, UNSAFE_DEFERRED_SYMBOL;
  5235. var init_router = __esm({
  5236. "node_modules/@remix-run/router/dist/router.js"() {
  5237. (function(Action2) {
  5238. Action2["Pop"] = "POP";
  5239. Action2["Push"] = "PUSH";
  5240. Action2["Replace"] = "REPLACE";
  5241. })(Action || (Action = {}));
  5242. PopStateEventType = "popstate";
  5243. (function(ResultType2) {
  5244. ResultType2["data"] = "data";
  5245. ResultType2["deferred"] = "deferred";
  5246. ResultType2["redirect"] = "redirect";
  5247. ResultType2["error"] = "error";
  5248. })(ResultType || (ResultType = {}));
  5249. immutableRouteKeys = /* @__PURE__ */ new Set(["lazy", "caseSensitive", "path", "id", "index", "children"]);
  5250. paramRe = /^:[\w-]+$/;
  5251. dynamicSegmentValue = 3;
  5252. indexRouteValue = 2;
  5253. emptySegmentValue = 1;
  5254. staticSegmentValue = 10;
  5255. splatPenalty = -2;
  5256. isSplat = (s) => s === "*";
  5257. joinPaths = (paths) => paths.join("/").replace(/\/\/+/g, "/");
  5258. normalizePathname = (pathname) => pathname.replace(/\/+$/, "").replace(/^\/*/, "/");
  5259. normalizeSearch = (search) => !search || search === "?" ? "" : search.startsWith("?") ? search : "?" + search;
  5260. normalizeHash = (hash) => !hash || hash === "#" ? "" : hash.startsWith("#") ? hash : "#" + hash;
  5261. json = function json2(data, init) {
  5262. if (init === void 0) {
  5263. init = {};
  5264. }
  5265. let responseInit = typeof init === "number" ? {
  5266. status: init
  5267. } : init;
  5268. let headers = new Headers(responseInit.headers);
  5269. if (!headers.has("Content-Type")) {
  5270. headers.set("Content-Type", "application/json; charset=utf-8");
  5271. }
  5272. return new Response(JSON.stringify(data), _extends({}, responseInit, {
  5273. headers
  5274. }));
  5275. };
  5276. AbortedDeferredError = class extends Error {
  5277. };
  5278. DeferredData = class {
  5279. constructor(data, responseInit) {
  5280. this.pendingKeysSet = /* @__PURE__ */ new Set();
  5281. this.subscribers = /* @__PURE__ */ new Set();
  5282. this.deferredKeys = [];
  5283. invariant(data && typeof data === "object" && !Array.isArray(data), "defer() only accepts plain objects");
  5284. let reject;
  5285. this.abortPromise = new Promise((_, r) => reject = r);
  5286. this.controller = new AbortController();
  5287. let onAbort = () => reject(new AbortedDeferredError("Deferred data aborted"));
  5288. this.unlistenAbortSignal = () => this.controller.signal.removeEventListener("abort", onAbort);
  5289. this.controller.signal.addEventListener("abort", onAbort);
  5290. this.data = Object.entries(data).reduce((acc, _ref2) => {
  5291. let [key, value] = _ref2;
  5292. return Object.assign(acc, {
  5293. [key]: this.trackPromise(key, value)
  5294. });
  5295. }, {});
  5296. if (this.done) {
  5297. this.unlistenAbortSignal();
  5298. }
  5299. this.init = responseInit;
  5300. }
  5301. trackPromise(key, value) {
  5302. if (!(value instanceof Promise)) {
  5303. return value;
  5304. }
  5305. this.deferredKeys.push(key);
  5306. this.pendingKeysSet.add(key);
  5307. let promise = Promise.race([value, this.abortPromise]).then((data) => this.onSettle(promise, key, void 0, data), (error) => this.onSettle(promise, key, error));
  5308. promise.catch(() => {
  5309. });
  5310. Object.defineProperty(promise, "_tracked", {
  5311. get: () => true
  5312. });
  5313. return promise;
  5314. }
  5315. onSettle(promise, key, error, data) {
  5316. if (this.controller.signal.aborted && error instanceof AbortedDeferredError) {
  5317. this.unlistenAbortSignal();
  5318. Object.defineProperty(promise, "_error", {
  5319. get: () => error
  5320. });
  5321. return Promise.reject(error);
  5322. }
  5323. this.pendingKeysSet.delete(key);
  5324. if (this.done) {
  5325. this.unlistenAbortSignal();
  5326. }
  5327. if (error === void 0 && data === void 0) {
  5328. let undefinedError = new Error('Deferred data for key "' + key + '" resolved/rejected with `undefined`, you must resolve/reject with a value or `null`.');
  5329. Object.defineProperty(promise, "_error", {
  5330. get: () => undefinedError
  5331. });
  5332. this.emit(false, key);
  5333. return Promise.reject(undefinedError);
  5334. }
  5335. if (data === void 0) {
  5336. Object.defineProperty(promise, "_error", {
  5337. get: () => error
  5338. });
  5339. this.emit(false, key);
  5340. return Promise.reject(error);
  5341. }
  5342. Object.defineProperty(promise, "_data", {
  5343. get: () => data
  5344. });
  5345. this.emit(false, key);
  5346. return data;
  5347. }
  5348. emit(aborted, settledKey) {
  5349. this.subscribers.forEach((subscriber) => subscriber(aborted, settledKey));
  5350. }
  5351. subscribe(fn) {
  5352. this.subscribers.add(fn);
  5353. return () => this.subscribers.delete(fn);
  5354. }
  5355. cancel() {
  5356. this.controller.abort();
  5357. this.pendingKeysSet.forEach((v, k2) => this.pendingKeysSet.delete(k2));
  5358. this.emit(true);
  5359. }
  5360. async resolveData(signal) {
  5361. let aborted = false;
  5362. if (!this.done) {
  5363. let onAbort = () => this.cancel();
  5364. signal.addEventListener("abort", onAbort);
  5365. aborted = await new Promise((resolve) => {
  5366. this.subscribe((aborted2) => {
  5367. signal.removeEventListener("abort", onAbort);
  5368. if (aborted2 || this.done) {
  5369. resolve(aborted2);
  5370. }
  5371. });
  5372. });
  5373. }
  5374. return aborted;
  5375. }
  5376. get done() {
  5377. return this.pendingKeysSet.size === 0;
  5378. }
  5379. get unwrappedData() {
  5380. invariant(this.data !== null && this.done, "Can only unwrap data on initialized and settled deferreds");
  5381. return Object.entries(this.data).reduce((acc, _ref3) => {
  5382. let [key, value] = _ref3;
  5383. return Object.assign(acc, {
  5384. [key]: unwrapTrackedPromise(value)
  5385. });
  5386. }, {});
  5387. }
  5388. get pendingKeys() {
  5389. return Array.from(this.pendingKeysSet);
  5390. }
  5391. };
  5392. defer = function defer2(data, init) {
  5393. if (init === void 0) {
  5394. init = {};
  5395. }
  5396. let responseInit = typeof init === "number" ? {
  5397. status: init
  5398. } : init;
  5399. return new DeferredData(data, responseInit);
  5400. };
  5401. redirect = function redirect2(url, init) {
  5402. if (init === void 0) {
  5403. init = 302;
  5404. }
  5405. let responseInit = init;
  5406. if (typeof responseInit === "number") {
  5407. responseInit = {
  5408. status: responseInit
  5409. };
  5410. } else if (typeof responseInit.status === "undefined") {
  5411. responseInit.status = 302;
  5412. }
  5413. let headers = new Headers(responseInit.headers);
  5414. headers.set("Location", url);
  5415. return new Response(null, _extends({}, responseInit, {
  5416. headers
  5417. }));
  5418. };
  5419. redirectDocument = (url, init) => {
  5420. let response = redirect(url, init);
  5421. response.headers.set("X-Remix-Reload-Document", "true");
  5422. return response;
  5423. };
  5424. ErrorResponseImpl = class {
  5425. constructor(status, statusText, data, internal) {
  5426. if (internal === void 0) {
  5427. internal = false;
  5428. }
  5429. this.status = status;
  5430. this.statusText = statusText || "";
  5431. this.internal = internal;
  5432. if (data instanceof Error) {
  5433. this.data = data.toString();
  5434. this.error = data;
  5435. } else {
  5436. this.data = data;
  5437. }
  5438. }
  5439. };
  5440. validMutationMethodsArr = ["post", "put", "patch", "delete"];
  5441. validMutationMethods = new Set(validMutationMethodsArr);
  5442. validRequestMethodsArr = ["get", ...validMutationMethodsArr];
  5443. validRequestMethods = new Set(validRequestMethodsArr);
  5444. redirectStatusCodes = /* @__PURE__ */ new Set([301, 302, 303, 307, 308]);
  5445. redirectPreserveMethodStatusCodes = /* @__PURE__ */ new Set([307, 308]);
  5446. IDLE_NAVIGATION = {
  5447. state: "idle",
  5448. location: void 0,
  5449. formMethod: void 0,
  5450. formAction: void 0,
  5451. formEncType: void 0,
  5452. formData: void 0,
  5453. json: void 0,
  5454. text: void 0
  5455. };
  5456. IDLE_FETCHER = {
  5457. state: "idle",
  5458. data: void 0,
  5459. formMethod: void 0,
  5460. formAction: void 0,
  5461. formEncType: void 0,
  5462. formData: void 0,
  5463. json: void 0,
  5464. text: void 0
  5465. };
  5466. IDLE_BLOCKER = {
  5467. state: "unblocked",
  5468. proceed: void 0,
  5469. reset: void 0,
  5470. location: void 0
  5471. };
  5472. ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i;
  5473. defaultMapRouteProperties = (route) => ({
  5474. hasErrorBoundary: Boolean(route.hasErrorBoundary)
  5475. });
  5476. TRANSITIONS_STORAGE_KEY = "remix-router-transitions";
  5477. UNSAFE_DEFERRED_SYMBOL = Symbol("deferred");
  5478. }
  5479. });
  5480. // node_modules/@remix-run/server-runtime/dist/mode.js
  5481. var require_mode = __commonJS({
  5482. "node_modules/@remix-run/server-runtime/dist/mode.js"(exports) {
  5483. "use strict";
  5484. Object.defineProperty(exports, "__esModule", { value: true });
  5485. var ServerMode2 = /* @__PURE__ */ function(ServerMode3) {
  5486. ServerMode3["Development"] = "development";
  5487. ServerMode3["Production"] = "production";
  5488. ServerMode3["Test"] = "test";
  5489. return ServerMode3;
  5490. }({});
  5491. function isServerMode(value) {
  5492. return value === ServerMode2.Development || value === ServerMode2.Production || value === ServerMode2.Test;
  5493. }
  5494. exports.ServerMode = ServerMode2;
  5495. exports.isServerMode = isServerMode;
  5496. }
  5497. });
  5498. // node_modules/@remix-run/server-runtime/dist/errors.js
  5499. var require_errors = __commonJS({
  5500. "node_modules/@remix-run/server-runtime/dist/errors.js"(exports) {
  5501. "use strict";
  5502. Object.defineProperty(exports, "__esModule", { value: true });
  5503. var router = (init_router(), __toCommonJS(router_exports));
  5504. var mode = require_mode();
  5505. function sanitizeError(error, serverMode) {
  5506. if (error instanceof Error && serverMode !== mode.ServerMode.Development) {
  5507. let sanitized = new Error("Unexpected Server Error");
  5508. sanitized.stack = void 0;
  5509. return sanitized;
  5510. }
  5511. return error;
  5512. }
  5513. function sanitizeErrors(errors, serverMode) {
  5514. return Object.entries(errors).reduce((acc, [routeId, error]) => {
  5515. return Object.assign(acc, {
  5516. [routeId]: sanitizeError(error, serverMode)
  5517. });
  5518. }, {});
  5519. }
  5520. function serializeError(error, serverMode) {
  5521. let sanitized = sanitizeError(error, serverMode);
  5522. return {
  5523. message: sanitized.message,
  5524. stack: sanitized.stack
  5525. };
  5526. }
  5527. function serializeErrors(errors, serverMode) {
  5528. if (!errors)
  5529. return null;
  5530. let entries = Object.entries(errors);
  5531. let serialized = {};
  5532. for (let [key, val] of entries) {
  5533. if (router.isRouteErrorResponse(val)) {
  5534. serialized[key] = {
  5535. ...val,
  5536. __type: "RouteErrorResponse"
  5537. };
  5538. } else if (val instanceof Error) {
  5539. let sanitized = sanitizeError(val, serverMode);
  5540. serialized[key] = {
  5541. message: sanitized.message,
  5542. stack: sanitized.stack,
  5543. __type: "Error",
  5544. // If this is a subclass (i.e., ReferenceError), send up the type so we
  5545. // can re-create the same type during hydration. This will only apply
  5546. // in dev mode since all production errors are sanitized to normal
  5547. // Error instances
  5548. ...sanitized.name !== "Error" ? {
  5549. __subType: sanitized.name
  5550. } : {}
  5551. };
  5552. } else {
  5553. serialized[key] = val;
  5554. }
  5555. }
  5556. return serialized;
  5557. }
  5558. exports.sanitizeError = sanitizeError;
  5559. exports.sanitizeErrors = sanitizeErrors;
  5560. exports.serializeError = serializeError;
  5561. exports.serializeErrors = serializeErrors;
  5562. }
  5563. });
  5564. // node_modules/@remix-run/server-runtime/dist/responses.js
  5565. var require_responses = __commonJS({
  5566. "node_modules/@remix-run/server-runtime/dist/responses.js"(exports) {
  5567. "use strict";
  5568. Object.defineProperty(exports, "__esModule", { value: true });
  5569. var router = (init_router(), __toCommonJS(router_exports));
  5570. var errors = require_errors();
  5571. var json5 = (data, init = {}) => {
  5572. return router.json(data, init);
  5573. };
  5574. var defer3 = (data, init = {}) => {
  5575. return router.defer(data, init);
  5576. };
  5577. var redirect4 = (url, init = 302) => {
  5578. return router.redirect(url, init);
  5579. };
  5580. var redirectDocument2 = (url, init = 302) => {
  5581. return router.redirectDocument(url, init);
  5582. };
  5583. function isDeferredData3(value) {
  5584. let deferred = value;
  5585. return deferred && typeof deferred === "object" && typeof deferred.data === "object" && typeof deferred.subscribe === "function" && typeof deferred.cancel === "function" && typeof deferred.resolveData === "function";
  5586. }
  5587. function isResponse3(value) {
  5588. return value != null && typeof value.status === "number" && typeof value.statusText === "string" && typeof value.headers === "object" && typeof value.body !== "undefined";
  5589. }
  5590. var redirectStatusCodes2 = /* @__PURE__ */ new Set([301, 302, 303, 307, 308]);
  5591. function isRedirectStatusCode2(statusCode) {
  5592. return redirectStatusCodes2.has(statusCode);
  5593. }
  5594. function isRedirectResponse3(response) {
  5595. return isRedirectStatusCode2(response.status);
  5596. }
  5597. function isTrackedPromise2(value) {
  5598. return value != null && typeof value.then === "function" && value._tracked === true;
  5599. }
  5600. var DEFERRED_VALUE_PLACEHOLDER_PREFIX = "__deferred_promise:";
  5601. function createDeferredReadableStream2(deferredData, signal, serverMode) {
  5602. let encoder = new TextEncoder();
  5603. let stream = new ReadableStream({
  5604. async start(controller) {
  5605. let criticalData = {};
  5606. let preresolvedKeys = [];
  5607. for (let [key, value] of Object.entries(deferredData.data)) {
  5608. if (isTrackedPromise2(value)) {
  5609. criticalData[key] = `${DEFERRED_VALUE_PLACEHOLDER_PREFIX}${key}`;
  5610. if (typeof value._data !== "undefined" || typeof value._error !== "undefined") {
  5611. preresolvedKeys.push(key);
  5612. }
  5613. } else {
  5614. criticalData[key] = value;
  5615. }
  5616. }
  5617. controller.enqueue(encoder.encode(JSON.stringify(criticalData) + "\n\n"));
  5618. for (let preresolvedKey of preresolvedKeys) {
  5619. enqueueTrackedPromise(controller, encoder, preresolvedKey, deferredData.data[preresolvedKey], serverMode);
  5620. }
  5621. let unsubscribe = deferredData.subscribe((aborted, settledKey) => {
  5622. if (settledKey) {
  5623. enqueueTrackedPromise(controller, encoder, settledKey, deferredData.data[settledKey], serverMode);
  5624. }
  5625. });
  5626. await deferredData.resolveData(signal);
  5627. unsubscribe();
  5628. controller.close();
  5629. }
  5630. });
  5631. return stream;
  5632. }
  5633. function enqueueTrackedPromise(controller, encoder, settledKey, promise, serverMode) {
  5634. if ("_error" in promise) {
  5635. controller.enqueue(encoder.encode("error:" + JSON.stringify({
  5636. [settledKey]: promise._error instanceof Error ? errors.serializeError(promise._error, serverMode) : promise._error
  5637. }) + "\n\n"));
  5638. } else {
  5639. controller.enqueue(encoder.encode("data:" + JSON.stringify({
  5640. [settledKey]: promise._data ?? null
  5641. }) + "\n\n"));
  5642. }
  5643. }
  5644. exports.createDeferredReadableStream = createDeferredReadableStream2;
  5645. exports.defer = defer3;
  5646. exports.isDeferredData = isDeferredData3;
  5647. exports.isRedirectResponse = isRedirectResponse3;
  5648. exports.isRedirectStatusCode = isRedirectStatusCode2;
  5649. exports.isResponse = isResponse3;
  5650. exports.json = json5;
  5651. exports.redirect = redirect4;
  5652. exports.redirectDocument = redirectDocument2;
  5653. }
  5654. });
  5655. // app/entry.worker.ts
  5656. var entry_worker_exports = {};
  5657. __export(entry_worker_exports, {
  5658. defaultFetchHandler: () => defaultFetchHandler
  5659. });
  5660. // node_modules/cachified/dist/index.mjs
  5661. var k = Symbol();
  5662. var w = Symbol();
  5663. var f = Symbol();
  5664. // node_modules/@remix-pwa/cache/dist/src/cache.js
  5665. var B = __toESM(require_buffer(), 1);
  5666. // node_modules/@remix-pwa/cache/dist/src/utils.js
  5667. function mergeHeaders(...headers) {
  5668. const merged = new Headers();
  5669. for (const header of headers) {
  5670. if (!header)
  5671. continue;
  5672. for (const [key, value] of new Headers(header).entries()) {
  5673. merged.set(key, value);
  5674. }
  5675. }
  5676. return merged;
  5677. }
  5678. function omit(key, obj) {
  5679. const { [key]: omitted, ...rest } = obj;
  5680. return rest;
  5681. }
  5682. // node_modules/@remix-pwa/cache/dist/src/cache.js
  5683. var Strategy;
  5684. (function(Strategy2) {
  5685. Strategy2["CacheFirst"] = "cache-first";
  5686. Strategy2["NetworkFirst"] = "network-first";
  5687. Strategy2["CacheOnly"] = "cache-only";
  5688. Strategy2["NetworkOnly"] = "network-only";
  5689. Strategy2["StaleWhileRevalidate"] = "stale-while-revalidate";
  5690. })(Strategy || (Strategy = {}));
  5691. var RemixCache = class {
  5692. /**
  5693. * Create a new `RemixCache` instance. Don't invoke this directly! Use `RemixCacheStorage.open()` instead.
  5694. * @constructor
  5695. * @param {object} options - Options for the RemixCache instance.
  5696. */
  5697. constructor(options) {
  5698. this._ttl = Infinity;
  5699. this._strategy = Strategy.NetworkFirst;
  5700. this._maxItems = 100;
  5701. this.set = false;
  5702. this.name = options.name;
  5703. this._maxItems = options.maxItems || 100;
  5704. this._strategy = options.strategy || Strategy.NetworkFirst;
  5705. this._ttl = options.ttl || Infinity;
  5706. if (this._strategy === Strategy.NetworkOnly) {
  5707. this._ttl = -1;
  5708. }
  5709. if (options.maxItems || options.ttl || options.strategy) {
  5710. this.set = true;
  5711. } else {
  5712. this.set = false;
  5713. }
  5714. }
  5715. async _openCache() {
  5716. return await caches.open(`rp-${this.name}`);
  5717. }
  5718. async _getOrDeleteIfExpired(key, metadata) {
  5719. if (metadata.expiresAt === "Infinity") {
  5720. return false;
  5721. }
  5722. if (Number(metadata.expiresAt) <= Date.now()) {
  5723. return await this.delete(key);
  5724. }
  5725. return false;
  5726. }
  5727. async _lruCleanup() {
  5728. const isOverflowing = await this.length() >= this._maxItems;
  5729. if (isOverflowing) {
  5730. const cache = await this._openCache();
  5731. const keys = await cache.keys();
  5732. const values = await Promise.all(keys.map((key) => cache.match(key)));
  5733. const keyVal = keys.map((key, i) => ({ key, val: values[i] }));
  5734. const comparableArrayPromise = keyVal.map(async (val) => {
  5735. const { metadata } = await val.val.clone().json();
  5736. return {
  5737. metadata,
  5738. url: val.key.url
  5739. };
  5740. });
  5741. const comparableArray = await Promise.all(comparableArrayPromise);
  5742. const sortedArr = comparableArray.sort((a, b2) => {
  5743. return Number(a.metadata.accessedAt) - Number(b2.metadata.accessedAt);
  5744. });
  5745. const toBeDeletdItems = sortedArr.slice(0, sortedArr.length - this._maxItems + 1);
  5746. for (const deleted of toBeDeletdItems) {
  5747. await this.delete(deleted.url);
  5748. }
  5749. }
  5750. }
  5751. async _getResponseValue(request, response) {
  5752. const { metadata, value } = await response.clone().json();
  5753. const deleted = await this._getOrDeleteIfExpired(request, metadata);
  5754. const headers = new Headers(response.clone().headers);
  5755. if (!this.set) {
  5756. this.set = true;
  5757. this._ttl = metadata.cacheTtl;
  5758. this._maxItems = metadata.cacheMaxItems;
  5759. this._strategy = metadata.cacheStrategy;
  5760. }
  5761. const newHeader = new Headers(headers);
  5762. newHeader.set("X-Remix-PWA-TTL", metadata.expiresAt.toString());
  5763. newHeader.set("X-Remix-PWA-AccessTime", Date.now().toString());
  5764. newHeader.set("Content-Type", headers.get("X-Remix-PWA-Original-Content-Type") || "application/json");
  5765. const contentType = headers.get("X-Remix-PWA-Original-Content-Type") ?? "";
  5766. newHeader.delete("X-Remix-PWA-Original-Content-Type");
  5767. const responseOptions = {
  5768. status: response.status,
  5769. statusText: response.statusText,
  5770. headers: newHeader,
  5771. body: "null"
  5772. };
  5773. if (contentType.includes("application/json")) {
  5774. responseOptions.body = JSON.stringify(value);
  5775. } else if (contentType.includes("text")) {
  5776. responseOptions.body = value;
  5777. } else {
  5778. const buffer = B.Buffer.from(value, "base64");
  5779. responseOptions.body = new Uint8Array(buffer);
  5780. }
  5781. if (!deleted) {
  5782. const res = new Response(responseOptions.body, omit("body", responseOptions));
  5783. await this.put(request, res.clone(), void 0);
  5784. return res;
  5785. }
  5786. return void 0;
  5787. }
  5788. /**
  5789. * Delete an entry from the cache.
  5790. * Takes in the same parameters as `Cache.delete`.
  5791. * @param {RequestInfo | URL} request - The request to delete.
  5792. * @param {CacheQueryOptions} [options] - Options for the delete operation.
  5793. * @returns {Promise<boolean>} Returns `true` if an entry was deleted, otherwise `false`.
  5794. *
  5795. * @example
  5796. * ```js
  5797. * const cache = await initCache({ name: 'my-cache' });
  5798. *
  5799. * await cache.put('/hello-world', new Response('Hello World!'));
  5800. * await cache.delete('/hello-world');
  5801. * ```
  5802. *
  5803. * @see https://developer.mozilla.org/en-US/docs/Web/API/Cache/delete
  5804. */
  5805. async delete(request, options) {
  5806. return this._openCache().then((cache) => cache.delete(request, options));
  5807. }
  5808. /**
  5809. * Returns a Promise that resolves to the length of the Cache object.
  5810. *
  5811. * @returns {Promise<number>} The number of entries in the cache.
  5812. */
  5813. async length() {
  5814. const keys = await this.keys();
  5815. return keys.length;
  5816. }
  5817. /**
  5818. * Returns a `Promise` that resolves to an array of Cache keys.
  5819. *
  5820. * @returns {Promise<readonly Request[]>} An array of Cache keys.
  5821. */
  5822. async keys() {
  5823. const cache = await this._openCache();
  5824. return await cache.keys();
  5825. }
  5826. /**
  5827. * Return a `Promise` that resolves to an entry in the cache object. Accepts the
  5828. * same parameters as `Cache.match`.
  5829. *
  5830. * @param {RequestInfo | URL} request - The request to match.
  5831. * @param {CacheQueryOptions} [options] - Options for the match operation.
  5832. *
  5833. * @returns {Promise<Response | undefined>} A `Promise` that resolves to the response, or `undefined` if not found.
  5834. */
  5835. async match(request, options) {
  5836. const cache = await this._openCache();
  5837. if (request instanceof URL || typeof request === "string") {
  5838. request = new Request(request);
  5839. }
  5840. const response = await cache.match(request.clone(), options);
  5841. if (!response) {
  5842. return void 0;
  5843. }
  5844. return await this._getResponseValue(request, response.clone());
  5845. }
  5846. /**
  5847. * Add an entry to the cache.
  5848. * Takes in the same parameters as `Cache.put`.
  5849. *
  5850. * @param {RequestInfo | URL} request - The request to add.
  5851. * @param {Response} response - The response to add.
  5852. * @param {number | undefined} ttl - The time-to-live of the cache entry in ms. Defaults to cache ttl.
  5853. * @returns {Promise<void>} A `Promise` that resolves when the entry is added to the cache.
  5854. *
  5855. * @example
  5856. * ```js
  5857. * const cache = await initCache({ name: 'my-cache' });
  5858. *
  5859. * await cache.put('/hello-world', new Response('Hello World!'));
  5860. * ```
  5861. *
  5862. * @see https://developer.mozilla.org/en-US/docs/Web/API/Cache/put
  5863. */
  5864. async put(request, response, ttl = void 0) {
  5865. const cache = await this._openCache();
  5866. if (request instanceof URL || typeof request === "string") {
  5867. request = new Request(request);
  5868. }
  5869. if (this._ttl <= 0 || ttl && ttl <= 0)
  5870. return;
  5871. if (response === null || response.status === 204 || response.statusText.toLowerCase() === "no content") {
  5872. await this.delete(request);
  5873. return;
  5874. }
  5875. const contentType = response.headers.get("Content-Type");
  5876. let data;
  5877. if (contentType && contentType.includes("application/json")) {
  5878. data = await response.clone().json();
  5879. } else if (contentType && contentType.includes("text")) {
  5880. data = await response.clone().text();
  5881. } else {
  5882. const buffer = await response.clone().arrayBuffer();
  5883. data = B.Buffer.from(buffer).toString("base64");
  5884. }
  5885. if (!this.set) {
  5886. this.set = true;
  5887. const keys = await cache.keys();
  5888. const firstVal = await cache.match(keys[0]);
  5889. if (firstVal) {
  5890. const { metadata } = await firstVal.clone().json();
  5891. this._ttl = metadata.cacheTtl;
  5892. this._maxItems = metadata.cacheMaxItems;
  5893. this._strategy = metadata.cacheStrategy;
  5894. } else {
  5895. this._ttl = Infinity;
  5896. this._maxItems = 100;
  5897. this._strategy = Strategy.NetworkFirst;
  5898. }
  5899. }
  5900. const resHeaders = response.headers;
  5901. const expiresAt = resHeaders.get("X-Remix-PWA-TTL") || Date.now() + (ttl ?? this._ttl);
  5902. const accessedAt = resHeaders.get("X-Remix-PWA-AccessTime") || Date.now().toString();
  5903. const newHeaders = new Headers();
  5904. newHeaders.set("Content-Type", "application/json");
  5905. newHeaders.set("X-Remix-PWA-AccessTime", accessedAt);
  5906. newHeaders.set("X-Remix-PWA-Original-Content-Type", contentType || "text/plain");
  5907. newHeaders.set("X-Remix-PWA-TTL", expiresAt.toString());
  5908. const toBeCachedRes = new Response(JSON.stringify({
  5909. metadata: {
  5910. accessedAt,
  5911. // JSON can't store `Infinity`, so we store it as a string
  5912. expiresAt: expiresAt.toString(),
  5913. cacheTtl: this._ttl.toString(),
  5914. cacheMaxItems: this._maxItems,
  5915. cacheStrategy: this._strategy
  5916. },
  5917. value: data
  5918. }), {
  5919. status: response.status,
  5920. statusText: response.statusText,
  5921. headers: mergeHeaders(resHeaders, newHeaders)
  5922. });
  5923. Object.defineProperty(toBeCachedRes, "url", { value: response.url });
  5924. Object.defineProperty(toBeCachedRes, "type", { value: response.type });
  5925. Object.defineProperty(toBeCachedRes, "ok", { value: response.ok });
  5926. Object.defineProperty(toBeCachedRes, "redirected", { value: response.redirected });
  5927. try {
  5928. await this._lruCleanup();
  5929. return await cache.put(request, toBeCachedRes.clone());
  5930. } catch (error) {
  5931. if (true)
  5932. console.error("Failed to put to cache:", error);
  5933. }
  5934. }
  5935. async add(request) {
  5936. return (
  5937. /* await - should this be awaited? */
  5938. fetch(request).then((res) => {
  5939. if (!res.ok) {
  5940. throw new Error("Failed to fetch");
  5941. }
  5942. return this.put(request, res.clone());
  5943. })
  5944. );
  5945. }
  5946. get ttl() {
  5947. return this._ttl;
  5948. }
  5949. get strategy() {
  5950. return this._strategy;
  5951. }
  5952. };
  5953. // node_modules/@remix-pwa/cache/dist/src/storage.js
  5954. var RemixCacheStorage = class {
  5955. // eslint-disable-next-line no-useless-constructor
  5956. constructor() {
  5957. }
  5958. /**
  5959. * Initialize the Remix PWA Cache Storage. This will create a special cache for each
  5960. * existing cache in the browser or create a new map if none exist.
  5961. *
  5962. * Use in your service worker installation script. Make sure to call this before
  5963. * initializing any `RemixCache` instance.
  5964. *
  5965. * @example
  5966. * ```js
  5967. * import { RemixCacheStorage } from '@remix-run/cache';
  5968. *
  5969. * self.addEventListener('install', (event) => {
  5970. * event.waitUntil(Promise.all[
  5971. * RemixCacheStorage.init(),
  5972. * // other stuff
  5973. * ]);
  5974. * });
  5975. * ```
  5976. */
  5977. // static async init() {
  5978. // if (typeof caches === 'undefined') {
  5979. // throw new Error('Cache API is not available in this environment.');
  5980. // }
  5981. // if (this._instances.size > 0) {
  5982. // return;
  5983. // }
  5984. // const cachesNames = await caches.keys();
  5985. // for (const name of cachesNames) {
  5986. // if (name.startsWith('rp-')) {
  5987. // this._instances.set(name, new RemixCache({ name }));
  5988. // }
  5989. // }
  5990. // }
  5991. /**
  5992. * Create a custom cache that you can use across your application.
  5993. * Use this instead of initialising `RemixCache` directly.
  5994. */
  5995. static createCache(opts) {
  5996. const { name } = opts;
  5997. if (this._instances.has(name)) {
  5998. return this._instances.get(name);
  5999. }
  6000. const newCache = new RemixCache(opts);
  6001. this._instances.set(`${name}`, newCache);
  6002. caches.open(`rp-${name}`);
  6003. return newCache;
  6004. }
  6005. /**
  6006. * Check wether a cache with the given name exists.
  6007. *
  6008. * @param name
  6009. */
  6010. static has(name) {
  6011. return this._instances.has(name);
  6012. }
  6013. static async _get(name) {
  6014. const cache = this._instances.get(name);
  6015. if (!cache && await caches.has(`rp-${name}`)) {
  6016. this._instances.set(name, new RemixCache({ name }));
  6017. await this._instances.get(name)?.keys().then((keys) => {
  6018. if (keys.length > 0) {
  6019. caches.match(keys[0]);
  6020. }
  6021. });
  6022. }
  6023. return this._instances.get(name);
  6024. }
  6025. /**
  6026. * Get a cache by name. Returns `undefined` if no cache with the given name exists.
  6027. * Use `has` to check if a cache exists. Or `open` to create one automatically if non exists.
  6028. *
  6029. * @param name
  6030. * @returns {RemixCache | undefined}
  6031. *
  6032. * @example
  6033. * ```js
  6034. * import { Storage } from '@remix-run/cache';
  6035. *
  6036. * const cache = Storage.get('my-cache');
  6037. * ```
  6038. */
  6039. static async get(name) {
  6040. return await this._get(name);
  6041. }
  6042. /**
  6043. * Get a cache by name. If no cache with the given name exists, create one.
  6044. *
  6045. * @param name Name of the cache - **must be unique**
  6046. * @param opts Options to pass to the `RemixCache` constructor if the cache is getting created
  6047. * @returns {RemixCache}
  6048. *
  6049. * @example
  6050. * ```js
  6051. * import { Storage } from '@remix-run/cache';
  6052. *
  6053. * const cache = Storage.open('my-cache');
  6054. * ```
  6055. */
  6056. static open(name, opts) {
  6057. const cache = this._instances.get(name);
  6058. if (!cache) {
  6059. return this.createCache({ name, ...opts });
  6060. }
  6061. return cache;
  6062. }
  6063. /**
  6064. * Delete a cache by name.
  6065. *
  6066. * @param name
  6067. */
  6068. static delete(name) {
  6069. const cache = this._instances.get(name);
  6070. if (cache) {
  6071. caches.delete(`rp-${name}`);
  6072. this._instances.delete(name);
  6073. }
  6074. }
  6075. /**
  6076. * Delete all caches.
  6077. */
  6078. static clear() {
  6079. caches.keys().then((keys) => keys.forEach((key) => key.startsWith("rp-") ? caches.delete(key) : null));
  6080. this._instances = /* @__PURE__ */ new Map();
  6081. }
  6082. /**
  6083. * Get all caches. **Don't use this except you know what you are doing!**
  6084. *
  6085. * Which, frankly speaking, you probably don't. So shoo away!
  6086. */
  6087. static get instances() {
  6088. return this._instances;
  6089. }
  6090. /**
  6091. * Get the number of caches.
  6092. *
  6093. * Return the length of the `RemixCacheStorage` store.
  6094. */
  6095. static get _length() {
  6096. return this._instances.size;
  6097. }
  6098. /**
  6099. * Check if a request is stored as the key of a response in all caches.
  6100. *
  6101. * Experimental. Use at your own risk!
  6102. *
  6103. * @param {RequestInfo | URL} request The request to check.
  6104. * @param {CacheQueryOptions} [options] Options to pass to the `Cache.match` method.
  6105. * @returns {Promise<Response | undefined>} A promise that resolves to the response if found, otherwise `undefined`.
  6106. */
  6107. static _match(request, options) {
  6108. return caches.match(request, options);
  6109. }
  6110. };
  6111. RemixCacheStorage._instances = /* @__PURE__ */ new Map();
  6112. var Storage = RemixCacheStorage;
  6113. // node_modules/@remix-pwa/strategy/dist/src/utils.js
  6114. var isHttpRequest = (request) => {
  6115. if (request instanceof Request) {
  6116. return request.url.startsWith("http");
  6117. }
  6118. return request.toString().startsWith("http");
  6119. };
  6120. // node_modules/@remix-pwa/strategy/dist/src/cacheFirst.js
  6121. var cacheFirst = ({ cache: cacheName, cacheOptions, cacheQueryOptions, fetchDidFail = void 0 }) => {
  6122. return async (request) => {
  6123. if (!isHttpRequest(request)) {
  6124. return new Response("Not a HTTP request", { status: 403 });
  6125. }
  6126. let remixCache;
  6127. if (typeof cacheName === "string") {
  6128. remixCache = Storage.open(cacheName, cacheOptions);
  6129. } else {
  6130. remixCache = cacheName;
  6131. }
  6132. const response = await remixCache.match(request, cacheQueryOptions);
  6133. if (!response) {
  6134. try {
  6135. const networkResponse = await fetch(request);
  6136. remixCache.put(request, networkResponse.clone());
  6137. return networkResponse;
  6138. } catch (err) {
  6139. if (fetchDidFail) {
  6140. await Promise.all(fetchDidFail.map((cb) => cb()));
  6141. }
  6142. throw err;
  6143. }
  6144. }
  6145. return response;
  6146. };
  6147. };
  6148. // node_modules/@remix-pwa/strategy/dist/src/networkFirst.js
  6149. var networkFirst = ({ cache: cacheName, cacheOptions, cacheQueryOptions, fetchDidFail = void 0, fetchDidSucceed = void 0, networkTimeoutSeconds = 10 }) => {
  6150. return async (request) => {
  6151. if (!isHttpRequest(request)) {
  6152. return new Response("Not a HTTP request", { status: 403 });
  6153. }
  6154. let remixCache;
  6155. if (typeof cacheName === "string") {
  6156. remixCache = Storage.open(cacheName, cacheOptions);
  6157. } else {
  6158. remixCache = cacheName;
  6159. }
  6160. try {
  6161. const timeoutPromise = networkTimeoutSeconds !== Infinity ? new Promise((_resolve, reject) => {
  6162. setTimeout(() => {
  6163. reject(new Error(`Network timed out after ${networkTimeoutSeconds} seconds`));
  6164. }, networkTimeoutSeconds * 1e3);
  6165. }) : null;
  6166. const response = timeoutPromise ? await Promise.race([fetch(request), timeoutPromise]) : await fetch(request);
  6167. if (response) {
  6168. if (fetchDidSucceed) {
  6169. await Promise.all(fetchDidSucceed.map((cb) => cb()));
  6170. }
  6171. await remixCache.put(request, response.clone());
  6172. return response.clone();
  6173. }
  6174. } catch (error) {
  6175. if (fetchDidFail) {
  6176. await Promise.all(fetchDidFail.map((cb) => cb()));
  6177. }
  6178. const cachedResponse = await remixCache.match(request, cacheQueryOptions);
  6179. if (cachedResponse) {
  6180. return cachedResponse.clone();
  6181. }
  6182. return new Response(JSON.stringify({ message: "Network Error" }), {
  6183. status: 500
  6184. });
  6185. }
  6186. throw new Error("Failed to fetch. Network timed out.");
  6187. };
  6188. };
  6189. // node_modules/@remix-pwa/sw/dist/src/private/logger.js
  6190. var methodToColorMap = {
  6191. debug: `#7f8c8d`,
  6192. log: `#2ecc71`,
  6193. info: `#3498db`,
  6194. warn: `#f39c12`,
  6195. error: `#c0392b`,
  6196. groupCollapsed: `#3498db`,
  6197. groupEnd: null
  6198. // No colored prefix on groupEnd
  6199. };
  6200. var logger = false ? (() => {
  6201. const api = {};
  6202. const loggerMethods = Object.keys(methodToColorMap);
  6203. for (const key of loggerMethods) {
  6204. const method = key;
  6205. api[method] = () => {
  6206. };
  6207. }
  6208. return api;
  6209. })() : (() => {
  6210. let inGroup = false;
  6211. const print = function(method, args) {
  6212. if (self.__DISABLE_PWA_DEV_LOGS) {
  6213. return;
  6214. }
  6215. if (method === "debug" && self.__DISABLE_PWA_DEBUG_LOGS) {
  6216. return;
  6217. }
  6218. if (method === "info" && self.__DISABLE_PWA_INFO_LOGS) {
  6219. return;
  6220. }
  6221. if (method === "warn" && self.__DISABLE_PWA_WARN_LOGS) {
  6222. return;
  6223. }
  6224. if (method === "error" && self.__DISABLE_PWA_ERROR_LOGS) {
  6225. return;
  6226. }
  6227. if (method === "groupCollapsed") {
  6228. if (/^((?!chrome|android).)*safari/i.test(navigator.userAgent)) {
  6229. console[method](...args);
  6230. return;
  6231. }
  6232. }
  6233. const styles = [
  6234. `background: ${methodToColorMap[method]}`,
  6235. `border-radius: 0.5em`,
  6236. `color: white`,
  6237. `font-weight: bold`,
  6238. `padding: 2px 0.5em`
  6239. ];
  6240. const logPrefix = inGroup ? [] : ["%cremix-pwa", styles.join(";")];
  6241. console[method](...logPrefix, ...args);
  6242. if (method === "groupCollapsed") {
  6243. inGroup = true;
  6244. }
  6245. if (method === "groupEnd") {
  6246. inGroup = false;
  6247. }
  6248. };
  6249. const api = {};
  6250. const loggerMethods = Object.keys(methodToColorMap);
  6251. for (const key of loggerMethods) {
  6252. const method = key;
  6253. api[method] = (...args) => {
  6254. print(method, args);
  6255. };
  6256. }
  6257. return api;
  6258. })();
  6259. // node_modules/@remix-pwa/sw/dist/src/utils/worker.js
  6260. function isMethod(request, methods) {
  6261. return methods.includes(request.method.toLowerCase());
  6262. }
  6263. function isAssetRequest(request, assetUrls = ["/build/", "/icons"]) {
  6264. return isMethod(request, ["get"]) && assetUrls.some((publicPath) => request.url.includes(publicPath));
  6265. }
  6266. function isLoaderRequest(request) {
  6267. const url = new URL(request.url);
  6268. return isMethod(request, ["get"]) && url.searchParams.get("_data");
  6269. }
  6270. var matchRequest = (request, assetUrls = ["/build/", "/icons"]) => {
  6271. if (isAssetRequest(request, assetUrls)) {
  6272. return "asset";
  6273. } else if (isLoaderRequest(request)) {
  6274. return "loader";
  6275. } else {
  6276. return null;
  6277. }
  6278. };
  6279. // node_modules/@remix-pwa/sw/dist/src/message/message.js
  6280. var MessageHandler = class {
  6281. /**
  6282. * The plugins array is used to run plugins before and after the message handler.
  6283. * They are passed in when the handler is initialised.
  6284. */
  6285. plugins;
  6286. /**
  6287. * The state object is used to pass data between plugins.
  6288. */
  6289. state;
  6290. constructor({ plugins, state } = {}) {
  6291. this.plugins = plugins || [];
  6292. this.state = state || {};
  6293. }
  6294. /**
  6295. * The method that handles the message event.
  6296. *
  6297. * Takes in the MessageEvent as a mandatory argument as well as an optional
  6298. * object that can be used to pass further information/data.
  6299. */
  6300. async handle(event, state = {}) {
  6301. await this._handleMessage(event, state);
  6302. }
  6303. /**
  6304. * Runs the plugins that are passed in when the handler is initialised.
  6305. */
  6306. async runPlugins(hook, env) {
  6307. for (const plugin of this.plugins) {
  6308. if (plugin[hook]) {
  6309. plugin[hook](env);
  6310. }
  6311. }
  6312. }
  6313. };
  6314. // node_modules/@remix-pwa/sw/dist/src/message/remixNavigationHandler.js
  6315. var RemixNavigationHandler = class extends MessageHandler {
  6316. dataCacheName;
  6317. documentCacheName;
  6318. constructor({ dataCache: dataCache2, documentCache: documentCache2, plugins, state }) {
  6319. super({ plugins, state });
  6320. this.dataCacheName = dataCache2;
  6321. this.documentCacheName = documentCache2;
  6322. this._handleMessage = this._handleMessage.bind(this);
  6323. }
  6324. async _handleMessage(event) {
  6325. const { data } = event;
  6326. let dataCache2, documentCache2;
  6327. dataCache2 = this.dataCacheName;
  6328. documentCache2 = this.documentCacheName;
  6329. this.runPlugins("messageDidReceive", {
  6330. event
  6331. });
  6332. const cachePromises = /* @__PURE__ */ new Map();
  6333. if (data.type === "REMIX_NAVIGATION") {
  6334. const { isMount, location, manifest, matches } = data;
  6335. const documentUrl = location.pathname + location.search + location.hash;
  6336. if (typeof dataCache2 === "string") {
  6337. dataCache2 = Storage.open(dataCache2);
  6338. }
  6339. if (typeof documentCache2 === "string") {
  6340. documentCache2 = Storage.open(documentCache2);
  6341. }
  6342. const existingDocument = await Storage._match(documentUrl);
  6343. if (!existingDocument || !isMount) {
  6344. const response = await fetch(documentUrl);
  6345. cachePromises.set(documentUrl, documentCache2.put(documentUrl, response).catch((error) => {
  6346. if (true)
  6347. logger.error(`Failed to cache document for ${documentUrl}:`, error);
  6348. }));
  6349. }
  6350. if (isMount) {
  6351. for (const match of matches) {
  6352. if (manifest.routes[match.id].hasLoader) {
  6353. const params = new URLSearchParams(location.search);
  6354. params.set("_data", match.id);
  6355. let search = params.toString();
  6356. search = search ? `?${search}` : "";
  6357. const url = location.pathname + search + location.hash;
  6358. if (!cachePromises.has(url)) {
  6359. if (true)
  6360. logger.debug("Caching data for:", url);
  6361. const response = await fetch(url);
  6362. cachePromises.set(url, dataCache2.put(url, response).catch((error) => {
  6363. if (true)
  6364. logger.error(`Failed to cache data for ${url}:`, error);
  6365. }));
  6366. }
  6367. }
  6368. }
  6369. }
  6370. }
  6371. await Promise.all(cachePromises.values());
  6372. }
  6373. };
  6374. // app/entry.worker.ts
  6375. var PAGES = "page-cache";
  6376. var DATA = "data-cache";
  6377. var ASSETS = "assets-cache";
  6378. var dataCache = Storage.open(DATA, {
  6379. ttl: 60 * 60 * 24 * 7 * 1e3
  6380. // 7 days
  6381. });
  6382. var documentCache = Storage.open(PAGES);
  6383. var assetCache = Storage.open(ASSETS);
  6384. self.addEventListener("install", (event) => {
  6385. logger.log("Service worker installed");
  6386. event.waitUntil(self.skipWaiting());
  6387. });
  6388. self.addEventListener("activate", (event) => {
  6389. logger.log("Service worker activated");
  6390. event.waitUntil(self.clients.claim());
  6391. });
  6392. var dataHandler = networkFirst({
  6393. cache: dataCache
  6394. });
  6395. var assetsHandler = cacheFirst({
  6396. cache: assetCache,
  6397. cacheQueryOptions: {
  6398. ignoreSearch: true,
  6399. ignoreVary: true
  6400. }
  6401. });
  6402. var defaultFetchHandler = ({ context, request }) => {
  6403. const type = matchRequest(request);
  6404. if (type === "asset") {
  6405. return assetsHandler(context.event.request);
  6406. }
  6407. if (type === "loader") {
  6408. return dataHandler(context.event.request);
  6409. }
  6410. return context.fetchFromServer();
  6411. };
  6412. var handler = new RemixNavigationHandler({
  6413. dataCache,
  6414. documentCache
  6415. });
  6416. self.addEventListener("message", (event) => {
  6417. event.waitUntil(handler.handle(event));
  6418. });
  6419. // entry-module:@remix-pwa/build/magic
  6420. var route0 = __toESM(require_root());
  6421. var route1 = __toESM(require_manifest_webmanifest());
  6422. // assets-module:@remix-pwa/dev?assets
  6423. var assets = ["/build/root-A55XQRCR.js", "/build/manifest-1A1450D4.js", "/build/entry.client-QYHX7HDK.js", "/build/__remix_entry_dev-OJT2RCOT.js", "/build/routes/manifest[.]webmanifest-J3KYYY3Q.js", "/build/_shared/runtime-GC7QIU56.js", "/build/_shared/remix_hmr-H6NO35BI.js", "/build/_shared/react-dom-BEFB7ICU.js", "/build/_shared/react-3OYUNTOK.js", "/build/_shared/jsx-runtime-7NXSP56X.js", "/build/_shared/jsx-dev-runtime-RDH4Y5YT.js", "/build/_shared/esm-53CCV4U4.js", "/build/_shared/client-DFZR44C7.js", "/build/_shared/chunk-ZWGWGGVF.js", "/build/_shared/chunk-XU7DNSPJ.js", "/build/_shared/chunk-UWV35TSL.js", "/build/_shared/chunk-PNG5AS42.js", "/build/_shared/chunk-OJSEL2DI.js", "/build/_shared/chunk-KFYUZA3E.js", "/build/_shared/chunk-GIAAE3CH.js", "/build/_shared/chunk-BOXFZXVX.js"];
  6424. // entry-module:@remix-pwa/build/magic
  6425. var routes = {
  6426. "root": {
  6427. id: "root",
  6428. parentId: void 0,
  6429. path: "",
  6430. index: void 0,
  6431. caseSensitive: void 0,
  6432. module: route0
  6433. },
  6434. "routes/manifest[.]webmanifest": {
  6435. id: "routes/manifest[.]webmanifest",
  6436. parentId: "root",
  6437. path: "manifest.webmanifest",
  6438. index: void 0,
  6439. caseSensitive: void 0,
  6440. module: route1
  6441. }
  6442. };
  6443. var entry = { module: entry_worker_exports };
  6444. // node_modules/@remix-pwa/worker-runtime/dist/src/utils/handle-request.js
  6445. init_router();
  6446. var import_mode = __toESM(require_mode(), 1);
  6447. var import_responses2 = __toESM(require_responses(), 1);
  6448. // node_modules/@remix-pwa/worker-runtime/dist/src/utils/request.js
  6449. init_router();
  6450. function clone(_object) {
  6451. const init = {};
  6452. for (const property in _object) {
  6453. init[property] = _object[property];
  6454. }
  6455. return init;
  6456. }
  6457. function getURLParameters(request, path = "") {
  6458. const url = new URL(request.url);
  6459. const match = matchPath(path, url.pathname);
  6460. return {
  6461. ...Object.fromEntries(new URL(request.url).searchParams.entries()),
  6462. ...match?.params
  6463. };
  6464. }
  6465. function stripIndexParameter(request) {
  6466. const url = new URL(request.url);
  6467. const indexValues = url.searchParams.getAll("index");
  6468. const indexValuesToKeep = [];
  6469. url.searchParams.delete("index");
  6470. for (const indexValue of indexValues) {
  6471. if (indexValue) {
  6472. indexValuesToKeep.push(indexValue);
  6473. }
  6474. }
  6475. for (const toKeep of indexValuesToKeep) {
  6476. url.searchParams.append("index", toKeep);
  6477. }
  6478. return new Request(url.href, { ...clone(request), duplex: "half" });
  6479. }
  6480. function stripDataParameter(request) {
  6481. const url = new URL(request.url);
  6482. url.searchParams.delete("_data");
  6483. return new Request(url.href, { ...clone(request), duplex: "half" });
  6484. }
  6485. function createArgumentsFrom({ event, loadContext, path }) {
  6486. const request = stripDataParameter(stripIndexParameter(event.request.clone()));
  6487. const parameters = getURLParameters(request, path);
  6488. return {
  6489. request,
  6490. params: parameters,
  6491. context: loadContext
  6492. };
  6493. }
  6494. function isMethod2(request, methods) {
  6495. return methods.includes(request.method.toLowerCase());
  6496. }
  6497. function isActionRequest(request) {
  6498. const url = new URL(request.url);
  6499. return isMethod2(request, ["post", "delete", "put", "patch"]) && url.searchParams.get("_data");
  6500. }
  6501. function isLoaderRequest2(request) {
  6502. const url = new URL(request.url);
  6503. return isMethod2(request, ["get"]) && url.searchParams.get("_data");
  6504. }
  6505. // node_modules/@remix-pwa/worker-runtime/dist/src/utils/response.js
  6506. var import_responses = __toESM(require_responses(), 1);
  6507. function errorResponseToJson(errorResponse) {
  6508. return (0, import_responses.json)(errorResponse.error || { message: "Unexpected Server Error" }, {
  6509. status: errorResponse.status,
  6510. statusText: errorResponse.statusText,
  6511. headers: {
  6512. "X-Remix-Error": "yes"
  6513. }
  6514. });
  6515. }
  6516. function isRemixResponse(response) {
  6517. return Array.from(response.headers.keys()).some((key) => key.toLowerCase().startsWith("x-remix-"));
  6518. }
  6519. // node_modules/@remix-pwa/worker-runtime/dist/src/utils/handle-request.js
  6520. async function handleRequest({ defaultHandler: defaultHandler2, errorHandler, event, loadContext, routes: routes2 }) {
  6521. const url = new URL(event.request.url);
  6522. const routeId = url.searchParams.get("_data");
  6523. const route = routeId ? routes2[routeId] : void 0;
  6524. const _arguments = {
  6525. request: event.request,
  6526. params: getURLParameters(event.request, route?.path),
  6527. context: loadContext
  6528. };
  6529. try {
  6530. if (isLoaderRequest2(event.request) && route?.module.workerLoader) {
  6531. return await handleLoader({
  6532. event,
  6533. loader: route.module.workerLoader,
  6534. routeId: route.id,
  6535. routePath: route.path,
  6536. loadContext
  6537. }).then(responseHandler);
  6538. }
  6539. if (isActionRequest(event.request) && route?.module?.workerAction) {
  6540. return await handleAction({
  6541. event,
  6542. action: route.module.workerAction,
  6543. routeId: route.id,
  6544. routePath: route.path,
  6545. loadContext
  6546. }).then(responseHandler);
  6547. }
  6548. } catch (error) {
  6549. const handler2 = (error2) => errorHandler(error2, _arguments);
  6550. return _errorHandler({ error, handler: handler2 });
  6551. }
  6552. return defaultHandler2(_arguments);
  6553. }
  6554. async function handleLoader({ event, loadContext, loader, routeId, routePath }) {
  6555. const _arguments = createArgumentsFrom({ event, loadContext, path: routePath });
  6556. const result = await loader(_arguments);
  6557. if (result === void 0) {
  6558. throw new Error(`You defined a loader for route "${routeId}" but didn't return anything from your \`worker loader\` function. Please return a value or \`null\`.`);
  6559. }
  6560. if ((0, import_responses2.isDeferredData)(result)) {
  6561. if (result.init && (0, import_responses2.isRedirectStatusCode)(result.init.status || 200)) {
  6562. return (0, import_responses2.redirect)(new Headers(result.init.headers).get("Location"), result.init);
  6563. }
  6564. const body = (0, import_responses2.createDeferredReadableStream)(result, event.request.signal, import_mode.ServerMode.Production);
  6565. const init = result.init || {};
  6566. const headers = new Headers(init.headers);
  6567. headers.set("Content-Type", "text/remix-deferred");
  6568. init.headers = headers;
  6569. return new Response(body, init);
  6570. }
  6571. return (0, import_responses2.isResponse)(result) ? result : (0, import_responses2.json)(result);
  6572. }
  6573. async function handleAction({ action, event, loadContext, routeId, routePath }) {
  6574. const _arguments = createArgumentsFrom({ event, loadContext, path: routePath });
  6575. const result = await action(_arguments);
  6576. if (result === void 0) {
  6577. throw new Error(`You defined an action for route "${routeId}" but didn't return anything from your \`worker action\` function. Please return a value or \`null\`.`);
  6578. }
  6579. return (0, import_responses2.isResponse)(result) ? result : (0, import_responses2.json)(result);
  6580. }
  6581. function _errorHandler({ error, handler: handleError }) {
  6582. if ((0, import_responses2.isResponse)(error)) {
  6583. error.headers.set("X-Remix-Catch", "yes");
  6584. return error;
  6585. }
  6586. if (isRouteErrorResponse(error)) {
  6587. error.error && handleError(error.error);
  6588. return errorResponseToJson(error);
  6589. }
  6590. const errorInstance = error instanceof Error ? error : new Error("Unexpected Server Error");
  6591. handleError(errorInstance);
  6592. return (0, import_responses2.json)({ message: errorInstance.message }, {
  6593. status: 500,
  6594. headers: {
  6595. "X-Remix-Error": "yes"
  6596. }
  6597. });
  6598. }
  6599. function responseHandler(response) {
  6600. if ((0, import_responses2.isRedirectResponse)(response)) {
  6601. const headers = new Headers(response.headers);
  6602. headers.set("X-Remix-Redirect", headers.get("Location"));
  6603. headers.set("X-Remix-Status", String(response.status));
  6604. headers.delete("Location");
  6605. if (response.headers.get("Set-Cookie") !== null) {
  6606. headers.set("X-Remix-Revalidate", "yes");
  6607. }
  6608. return new Response(null, {
  6609. status: 204,
  6610. headers
  6611. });
  6612. }
  6613. !isRemixResponse(response) && response.headers.set("X-Remix-Response", "yes");
  6614. return response;
  6615. }
  6616. // node_modules/@remix-pwa/worker-runtime/dist/src/service-worker.internal.js
  6617. var _self = self;
  6618. function createContext(event) {
  6619. const context = entry.module.getLoadContext?.(event) || {};
  6620. return {
  6621. event,
  6622. fetchFromServer: () => fetch(event.request.clone()),
  6623. // NOTE: we want the user to override the above properties if needed.
  6624. ...context
  6625. };
  6626. }
  6627. var defaultHandler = entry.module.defaultFetchHandler || ((event) => fetch(event.request.clone()));
  6628. var defaultErrorHandler = entry.module.errorHandler || ((error, { request }) => {
  6629. if (!request.signal.aborted) {
  6630. console.error(error);
  6631. }
  6632. });
  6633. _self.__workerManifest = {
  6634. assets,
  6635. routes
  6636. };
  6637. _self.addEventListener(
  6638. "fetch",
  6639. /**
  6640. * The main fetch event listener callback.
  6641. */
  6642. (event) => {
  6643. const response = handleRequest({
  6644. event,
  6645. routes,
  6646. defaultHandler,
  6647. errorHandler: defaultErrorHandler,
  6648. loadContext: createContext(event)
  6649. });
  6650. return event.respondWith(response);
  6651. }
  6652. );
  6653. /*! Bundled license information:
  6654. ieee754/index.js:
  6655. (*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> *)
  6656. buffer/index.js:
  6657. (*!
  6658. * The buffer module from node.js, for the browser.
  6659. *
  6660. * @author Feross Aboukhadijeh <https://feross.org>
  6661. * @license MIT
  6662. *)
  6663. @remix-run/router/dist/router.js:
  6664. (**
  6665. * @remix-run/router v1.15.0
  6666. *
  6667. * Copyright (c) Remix Software Inc.
  6668. *
  6669. * This source code is licensed under the MIT license found in the
  6670. * LICENSE.md file in the root directory of this source tree.
  6671. *
  6672. * @license MIT
  6673. *)
  6674. @remix-run/server-runtime/dist/mode.js:
  6675. (**
  6676. * @remix-run/server-runtime v2.6.0
  6677. *
  6678. * Copyright (c) Remix Software Inc.
  6679. *
  6680. * This source code is licensed under the MIT license found in the
  6681. * LICENSE.md file in the root directory of this source tree.
  6682. *
  6683. * @license MIT
  6684. *)
  6685. @remix-run/server-runtime/dist/errors.js:
  6686. (**
  6687. * @remix-run/server-runtime v2.6.0
  6688. *
  6689. * Copyright (c) Remix Software Inc.
  6690. *
  6691. * This source code is licensed under the MIT license found in the
  6692. * LICENSE.md file in the root directory of this source tree.
  6693. *
  6694. * @license MIT
  6695. *)
  6696. @remix-run/server-runtime/dist/responses.js:
  6697. (**
  6698. * @remix-run/server-runtime v2.6.0
  6699. *
  6700. * Copyright (c) Remix Software Inc.
  6701. *
  6702. * This source code is licensed under the MIT license found in the
  6703. * LICENSE.md file in the root directory of this source tree.
  6704. *
  6705. * @license MIT
  6706. *)
  6707. */