react-router-dom.js 432 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641
  1. import {
  2. require_react_dom
  3. } from "./chunk-BANT3OPS.js";
  4. import {
  5. require_react
  6. } from "./chunk-QRULMDK5.js";
  7. import {
  8. __commonJS,
  9. __toESM
  10. } from "./chunk-G3PMV62Z.js";
  11. // node_modules/cookie/dist/index.js
  12. var require_dist = __commonJS({
  13. "node_modules/cookie/dist/index.js"(exports) {
  14. "use strict";
  15. Object.defineProperty(exports, "__esModule", { value: true });
  16. exports.parseCookie = parseCookie;
  17. exports.parse = parseCookie;
  18. exports.stringifyCookie = stringifyCookie;
  19. exports.stringifySetCookie = stringifySetCookie;
  20. exports.serialize = stringifySetCookie;
  21. exports.parseSetCookie = parseSetCookie;
  22. exports.stringifySetCookie = stringifySetCookie;
  23. exports.serialize = stringifySetCookie;
  24. var cookieNameRegExp = /^[\u0021-\u003A\u003C\u003E-\u007E]+$/;
  25. var cookieValueRegExp = /^[\u0021-\u003A\u003C-\u007E]*$/;
  26. var domainValueRegExp = /^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i;
  27. var pathValueRegExp = /^[\u0020-\u003A\u003D-\u007E]*$/;
  28. var maxAgeRegExp = /^-?\d+$/;
  29. var __toString = Object.prototype.toString;
  30. var NullObject = (() => {
  31. const C = function() {
  32. };
  33. C.prototype = /* @__PURE__ */ Object.create(null);
  34. return C;
  35. })();
  36. function parseCookie(str, options) {
  37. const obj = new NullObject();
  38. const len = str.length;
  39. if (len < 2)
  40. return obj;
  41. const dec = (options == null ? void 0 : options.decode) || decode2;
  42. let index = 0;
  43. do {
  44. const eqIdx = eqIndex(str, index, len);
  45. if (eqIdx === -1)
  46. break;
  47. const endIdx = endIndex(str, index, len);
  48. if (eqIdx > endIdx) {
  49. index = str.lastIndexOf(";", eqIdx - 1) + 1;
  50. continue;
  51. }
  52. const key = valueSlice(str, index, eqIdx);
  53. if (obj[key] === void 0) {
  54. obj[key] = dec(valueSlice(str, eqIdx + 1, endIdx));
  55. }
  56. index = endIdx + 1;
  57. } while (index < len);
  58. return obj;
  59. }
  60. function stringifyCookie(cookie, options) {
  61. const enc = (options == null ? void 0 : options.encode) || encodeURIComponent;
  62. const cookieStrings = [];
  63. for (const name of Object.keys(cookie)) {
  64. const val = cookie[name];
  65. if (val === void 0)
  66. continue;
  67. if (!cookieNameRegExp.test(name)) {
  68. throw new TypeError(`cookie name is invalid: ${name}`);
  69. }
  70. const value = enc(val);
  71. if (!cookieValueRegExp.test(value)) {
  72. throw new TypeError(`cookie val is invalid: ${val}`);
  73. }
  74. cookieStrings.push(`${name}=${value}`);
  75. }
  76. return cookieStrings.join("; ");
  77. }
  78. function stringifySetCookie(_name, _val, _opts) {
  79. const cookie = typeof _name === "object" ? _name : { ..._opts, name: _name, value: String(_val) };
  80. const options = typeof _val === "object" ? _val : _opts;
  81. const enc = (options == null ? void 0 : options.encode) || encodeURIComponent;
  82. if (!cookieNameRegExp.test(cookie.name)) {
  83. throw new TypeError(`argument name is invalid: ${cookie.name}`);
  84. }
  85. const value = cookie.value ? enc(cookie.value) : "";
  86. if (!cookieValueRegExp.test(value)) {
  87. throw new TypeError(`argument val is invalid: ${cookie.value}`);
  88. }
  89. let str = cookie.name + "=" + value;
  90. if (cookie.maxAge !== void 0) {
  91. if (!Number.isInteger(cookie.maxAge)) {
  92. throw new TypeError(`option maxAge is invalid: ${cookie.maxAge}`);
  93. }
  94. str += "; Max-Age=" + cookie.maxAge;
  95. }
  96. if (cookie.domain) {
  97. if (!domainValueRegExp.test(cookie.domain)) {
  98. throw new TypeError(`option domain is invalid: ${cookie.domain}`);
  99. }
  100. str += "; Domain=" + cookie.domain;
  101. }
  102. if (cookie.path) {
  103. if (!pathValueRegExp.test(cookie.path)) {
  104. throw new TypeError(`option path is invalid: ${cookie.path}`);
  105. }
  106. str += "; Path=" + cookie.path;
  107. }
  108. if (cookie.expires) {
  109. if (!isDate(cookie.expires) || !Number.isFinite(cookie.expires.valueOf())) {
  110. throw new TypeError(`option expires is invalid: ${cookie.expires}`);
  111. }
  112. str += "; Expires=" + cookie.expires.toUTCString();
  113. }
  114. if (cookie.httpOnly) {
  115. str += "; HttpOnly";
  116. }
  117. if (cookie.secure) {
  118. str += "; Secure";
  119. }
  120. if (cookie.partitioned) {
  121. str += "; Partitioned";
  122. }
  123. if (cookie.priority) {
  124. const priority = typeof cookie.priority === "string" ? cookie.priority.toLowerCase() : void 0;
  125. switch (priority) {
  126. case "low":
  127. str += "; Priority=Low";
  128. break;
  129. case "medium":
  130. str += "; Priority=Medium";
  131. break;
  132. case "high":
  133. str += "; Priority=High";
  134. break;
  135. default:
  136. throw new TypeError(`option priority is invalid: ${cookie.priority}`);
  137. }
  138. }
  139. if (cookie.sameSite) {
  140. const sameSite = typeof cookie.sameSite === "string" ? cookie.sameSite.toLowerCase() : cookie.sameSite;
  141. switch (sameSite) {
  142. case true:
  143. case "strict":
  144. str += "; SameSite=Strict";
  145. break;
  146. case "lax":
  147. str += "; SameSite=Lax";
  148. break;
  149. case "none":
  150. str += "; SameSite=None";
  151. break;
  152. default:
  153. throw new TypeError(`option sameSite is invalid: ${cookie.sameSite}`);
  154. }
  155. }
  156. return str;
  157. }
  158. function parseSetCookie(str, options) {
  159. const dec = (options == null ? void 0 : options.decode) || decode2;
  160. const len = str.length;
  161. const endIdx = endIndex(str, 0, len);
  162. const eqIdx = eqIndex(str, 0, endIdx);
  163. const setCookie = eqIdx === -1 ? { name: "", value: dec(valueSlice(str, 0, endIdx)) } : {
  164. name: valueSlice(str, 0, eqIdx),
  165. value: dec(valueSlice(str, eqIdx + 1, endIdx))
  166. };
  167. let index = endIdx + 1;
  168. while (index < len) {
  169. const endIdx2 = endIndex(str, index, len);
  170. const eqIdx2 = eqIndex(str, index, endIdx2);
  171. const attr = eqIdx2 === -1 ? valueSlice(str, index, endIdx2) : valueSlice(str, index, eqIdx2);
  172. const val = eqIdx2 === -1 ? void 0 : valueSlice(str, eqIdx2 + 1, endIdx2);
  173. switch (attr.toLowerCase()) {
  174. case "httponly":
  175. setCookie.httpOnly = true;
  176. break;
  177. case "secure":
  178. setCookie.secure = true;
  179. break;
  180. case "partitioned":
  181. setCookie.partitioned = true;
  182. break;
  183. case "domain":
  184. setCookie.domain = val;
  185. break;
  186. case "path":
  187. setCookie.path = val;
  188. break;
  189. case "max-age":
  190. if (val && maxAgeRegExp.test(val))
  191. setCookie.maxAge = Number(val);
  192. break;
  193. case "expires":
  194. if (!val)
  195. break;
  196. const date = new Date(val);
  197. if (Number.isFinite(date.valueOf()))
  198. setCookie.expires = date;
  199. break;
  200. case "priority":
  201. if (!val)
  202. break;
  203. const priority = val.toLowerCase();
  204. if (priority === "low" || priority === "medium" || priority === "high") {
  205. setCookie.priority = priority;
  206. }
  207. break;
  208. case "samesite":
  209. if (!val)
  210. break;
  211. const sameSite = val.toLowerCase();
  212. if (sameSite === "lax" || sameSite === "strict" || sameSite === "none") {
  213. setCookie.sameSite = sameSite;
  214. }
  215. break;
  216. }
  217. index = endIdx2 + 1;
  218. }
  219. return setCookie;
  220. }
  221. function endIndex(str, min, len) {
  222. const index = str.indexOf(";", min);
  223. return index === -1 ? len : index;
  224. }
  225. function eqIndex(str, min, max) {
  226. const index = str.indexOf("=", min);
  227. return index < max ? index : -1;
  228. }
  229. function valueSlice(str, min, max) {
  230. let start = min;
  231. let end = max;
  232. do {
  233. const code = str.charCodeAt(start);
  234. if (code !== 32 && code !== 9)
  235. break;
  236. } while (++start < end);
  237. while (end > start) {
  238. const code = str.charCodeAt(end - 1);
  239. if (code !== 32 && code !== 9)
  240. break;
  241. end--;
  242. }
  243. return str.slice(start, end);
  244. }
  245. function decode2(str) {
  246. if (str.indexOf("%") === -1)
  247. return str;
  248. try {
  249. return decodeURIComponent(str);
  250. } catch (e) {
  251. return str;
  252. }
  253. }
  254. function isDate(val) {
  255. return __toString.call(val) === "[object Date]";
  256. }
  257. }
  258. });
  259. // node_modules/set-cookie-parser/lib/set-cookie.js
  260. var require_set_cookie = __commonJS({
  261. "node_modules/set-cookie-parser/lib/set-cookie.js"(exports, module) {
  262. "use strict";
  263. var defaultParseOptions = {
  264. decodeValues: true,
  265. map: false,
  266. silent: false
  267. };
  268. function isForbiddenKey(key) {
  269. return typeof key !== "string" || key in {};
  270. }
  271. function createNullObj() {
  272. return /* @__PURE__ */ Object.create(null);
  273. }
  274. function isNonEmptyString(str) {
  275. return typeof str === "string" && !!str.trim();
  276. }
  277. function parseString(setCookieValue, options) {
  278. var parts = setCookieValue.split(";").filter(isNonEmptyString);
  279. var nameValuePairStr = parts.shift();
  280. var parsed = parseNameValuePair(nameValuePairStr);
  281. var name = parsed.name;
  282. var value = parsed.value;
  283. options = options ? Object.assign({}, defaultParseOptions, options) : defaultParseOptions;
  284. if (isForbiddenKey(name)) {
  285. return null;
  286. }
  287. try {
  288. value = options.decodeValues ? decodeURIComponent(value) : value;
  289. } catch (e) {
  290. console.error(
  291. "set-cookie-parser: failed to decode cookie value. Set options.decodeValues=false to disable decoding.",
  292. e
  293. );
  294. }
  295. var cookie = createNullObj();
  296. cookie.name = name;
  297. cookie.value = value;
  298. parts.forEach(function(part) {
  299. var sides = part.split("=");
  300. var key = sides.shift().trimLeft().toLowerCase();
  301. if (isForbiddenKey(key)) {
  302. return;
  303. }
  304. var value2 = sides.join("=");
  305. if (key === "expires") {
  306. cookie.expires = new Date(value2);
  307. } else if (key === "max-age") {
  308. var n = parseInt(value2, 10);
  309. if (!Number.isNaN(n)) cookie.maxAge = n;
  310. } else if (key === "secure") {
  311. cookie.secure = true;
  312. } else if (key === "httponly") {
  313. cookie.httpOnly = true;
  314. } else if (key === "samesite") {
  315. cookie.sameSite = value2;
  316. } else if (key === "partitioned") {
  317. cookie.partitioned = true;
  318. } else if (key) {
  319. cookie[key] = value2;
  320. }
  321. });
  322. return cookie;
  323. }
  324. function parseNameValuePair(nameValuePairStr) {
  325. var name = "";
  326. var value = "";
  327. var nameValueArr = nameValuePairStr.split("=");
  328. if (nameValueArr.length > 1) {
  329. name = nameValueArr.shift();
  330. value = nameValueArr.join("=");
  331. } else {
  332. value = nameValuePairStr;
  333. }
  334. return { name, value };
  335. }
  336. function parse2(input, options) {
  337. options = options ? Object.assign({}, defaultParseOptions, options) : defaultParseOptions;
  338. if (!input) {
  339. if (!options.map) {
  340. return [];
  341. } else {
  342. return createNullObj();
  343. }
  344. }
  345. if (input.headers) {
  346. if (typeof input.headers.getSetCookie === "function") {
  347. input = input.headers.getSetCookie();
  348. } else if (input.headers["set-cookie"]) {
  349. input = input.headers["set-cookie"];
  350. } else {
  351. var sch = input.headers[Object.keys(input.headers).find(function(key) {
  352. return key.toLowerCase() === "set-cookie";
  353. })];
  354. if (!sch && input.headers.cookie && !options.silent) {
  355. console.warn(
  356. "Warning: set-cookie-parser appears to have been called on a request object. It is designed to parse Set-Cookie headers from responses, not Cookie headers from requests. Set the option {silent: true} to suppress this warning."
  357. );
  358. }
  359. input = sch;
  360. }
  361. }
  362. if (!Array.isArray(input)) {
  363. input = [input];
  364. }
  365. if (!options.map) {
  366. return input.filter(isNonEmptyString).map(function(str) {
  367. return parseString(str, options);
  368. }).filter(Boolean);
  369. } else {
  370. var cookies = createNullObj();
  371. return input.filter(isNonEmptyString).reduce(function(cookies2, str) {
  372. var cookie = parseString(str, options);
  373. if (cookie && !isForbiddenKey(cookie.name)) {
  374. cookies2[cookie.name] = cookie;
  375. }
  376. return cookies2;
  377. }, cookies);
  378. }
  379. }
  380. function splitCookiesString2(cookiesString) {
  381. if (Array.isArray(cookiesString)) {
  382. return cookiesString;
  383. }
  384. if (typeof cookiesString !== "string") {
  385. return [];
  386. }
  387. var cookiesStrings = [];
  388. var pos = 0;
  389. var start;
  390. var ch;
  391. var lastComma;
  392. var nextStart;
  393. var cookiesSeparatorFound;
  394. function skipWhitespace() {
  395. while (pos < cookiesString.length && /\s/.test(cookiesString.charAt(pos))) {
  396. pos += 1;
  397. }
  398. return pos < cookiesString.length;
  399. }
  400. function notSpecialChar() {
  401. ch = cookiesString.charAt(pos);
  402. return ch !== "=" && ch !== ";" && ch !== ",";
  403. }
  404. while (pos < cookiesString.length) {
  405. start = pos;
  406. cookiesSeparatorFound = false;
  407. while (skipWhitespace()) {
  408. ch = cookiesString.charAt(pos);
  409. if (ch === ",") {
  410. lastComma = pos;
  411. pos += 1;
  412. skipWhitespace();
  413. nextStart = pos;
  414. while (pos < cookiesString.length && notSpecialChar()) {
  415. pos += 1;
  416. }
  417. if (pos < cookiesString.length && cookiesString.charAt(pos) === "=") {
  418. cookiesSeparatorFound = true;
  419. pos = nextStart;
  420. cookiesStrings.push(cookiesString.substring(start, lastComma));
  421. start = pos;
  422. } else {
  423. pos = lastComma + 1;
  424. }
  425. } else {
  426. pos += 1;
  427. }
  428. }
  429. if (!cookiesSeparatorFound || pos >= cookiesString.length) {
  430. cookiesStrings.push(cookiesString.substring(start, cookiesString.length));
  431. }
  432. }
  433. return cookiesStrings;
  434. }
  435. module.exports = parse2;
  436. module.exports.parse = parse2;
  437. module.exports.parseString = parseString;
  438. module.exports.splitCookiesString = splitCookiesString2;
  439. }
  440. });
  441. // node_modules/react-router/dist/development/chunk-WWGJGFF6.mjs
  442. var React = __toESM(require_react(), 1);
  443. var React2 = __toESM(require_react(), 1);
  444. var React3 = __toESM(require_react(), 1);
  445. var React4 = __toESM(require_react(), 1);
  446. var React9 = __toESM(require_react(), 1);
  447. var React8 = __toESM(require_react(), 1);
  448. var React7 = __toESM(require_react(), 1);
  449. var React6 = __toESM(require_react(), 1);
  450. var React5 = __toESM(require_react(), 1);
  451. var React10 = __toESM(require_react(), 1);
  452. var React11 = __toESM(require_react(), 1);
  453. var __typeError = (msg) => {
  454. throw TypeError(msg);
  455. };
  456. var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
  457. var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
  458. var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
  459. var Action = ((Action2) => {
  460. Action2["Pop"] = "POP";
  461. Action2["Push"] = "PUSH";
  462. Action2["Replace"] = "REPLACE";
  463. return Action2;
  464. })(Action || {});
  465. var PopStateEventType = "popstate";
  466. function createMemoryHistory(options = {}) {
  467. let { initialEntries = ["/"], initialIndex, v5Compat = false } = options;
  468. let entries;
  469. entries = initialEntries.map(
  470. (entry, index2) => createMemoryLocation(
  471. entry,
  472. typeof entry === "string" ? null : entry.state,
  473. index2 === 0 ? "default" : void 0
  474. )
  475. );
  476. let index = clampIndex(
  477. initialIndex == null ? entries.length - 1 : initialIndex
  478. );
  479. let action = "POP";
  480. let listener = null;
  481. function clampIndex(n) {
  482. return Math.min(Math.max(n, 0), entries.length - 1);
  483. }
  484. function getCurrentLocation() {
  485. return entries[index];
  486. }
  487. function createMemoryLocation(to, state = null, key) {
  488. let location2 = createLocation(
  489. entries ? getCurrentLocation().pathname : "/",
  490. to,
  491. state,
  492. key
  493. );
  494. warning(
  495. location2.pathname.charAt(0) === "/",
  496. `relative pathnames are not supported in memory history: ${JSON.stringify(
  497. to
  498. )}`
  499. );
  500. return location2;
  501. }
  502. function createHref2(to) {
  503. return typeof to === "string" ? to : createPath(to);
  504. }
  505. let history = {
  506. get index() {
  507. return index;
  508. },
  509. get action() {
  510. return action;
  511. },
  512. get location() {
  513. return getCurrentLocation();
  514. },
  515. createHref: createHref2,
  516. createURL(to) {
  517. return new URL(createHref2(to), "http://localhost");
  518. },
  519. encodeLocation(to) {
  520. let path = typeof to === "string" ? parsePath(to) : to;
  521. return {
  522. pathname: path.pathname || "",
  523. search: path.search || "",
  524. hash: path.hash || ""
  525. };
  526. },
  527. push(to, state) {
  528. action = "PUSH";
  529. let nextLocation = createMemoryLocation(to, state);
  530. index += 1;
  531. entries.splice(index, entries.length, nextLocation);
  532. if (v5Compat && listener) {
  533. listener({ action, location: nextLocation, delta: 1 });
  534. }
  535. },
  536. replace(to, state) {
  537. action = "REPLACE";
  538. let nextLocation = createMemoryLocation(to, state);
  539. entries[index] = nextLocation;
  540. if (v5Compat && listener) {
  541. listener({ action, location: nextLocation, delta: 0 });
  542. }
  543. },
  544. go(delta) {
  545. action = "POP";
  546. let nextIndex = clampIndex(index + delta);
  547. let nextLocation = entries[nextIndex];
  548. index = nextIndex;
  549. if (listener) {
  550. listener({ action, location: nextLocation, delta });
  551. }
  552. },
  553. listen(fn) {
  554. listener = fn;
  555. return () => {
  556. listener = null;
  557. };
  558. }
  559. };
  560. return history;
  561. }
  562. function createBrowserHistory(options = {}) {
  563. function createBrowserLocation(window2, globalHistory) {
  564. let { pathname, search, hash } = window2.location;
  565. return createLocation(
  566. "",
  567. { pathname, search, hash },
  568. // state defaults to `null` because `window.history.state` does
  569. globalHistory.state && globalHistory.state.usr || null,
  570. globalHistory.state && globalHistory.state.key || "default"
  571. );
  572. }
  573. function createBrowserHref(window2, to) {
  574. return typeof to === "string" ? to : createPath(to);
  575. }
  576. return getUrlBasedHistory(
  577. createBrowserLocation,
  578. createBrowserHref,
  579. null,
  580. options
  581. );
  582. }
  583. function createHashHistory(options = {}) {
  584. function createHashLocation(window2, globalHistory) {
  585. let {
  586. pathname = "/",
  587. search = "",
  588. hash = ""
  589. } = parsePath(window2.location.hash.substring(1));
  590. if (!pathname.startsWith("/") && !pathname.startsWith(".")) {
  591. pathname = "/" + pathname;
  592. }
  593. return createLocation(
  594. "",
  595. { pathname, search, hash },
  596. // state defaults to `null` because `window.history.state` does
  597. globalHistory.state && globalHistory.state.usr || null,
  598. globalHistory.state && globalHistory.state.key || "default"
  599. );
  600. }
  601. function createHashHref(window2, to) {
  602. let base = window2.document.querySelector("base");
  603. let href2 = "";
  604. if (base && base.getAttribute("href")) {
  605. let url = window2.location.href;
  606. let hashIndex = url.indexOf("#");
  607. href2 = hashIndex === -1 ? url : url.slice(0, hashIndex);
  608. }
  609. return href2 + "#" + (typeof to === "string" ? to : createPath(to));
  610. }
  611. function validateHashLocation(location2, to) {
  612. warning(
  613. location2.pathname.charAt(0) === "/",
  614. `relative pathnames are not supported in hash history.push(${JSON.stringify(
  615. to
  616. )})`
  617. );
  618. }
  619. return getUrlBasedHistory(
  620. createHashLocation,
  621. createHashHref,
  622. validateHashLocation,
  623. options
  624. );
  625. }
  626. function invariant(value, message) {
  627. if (value === false || value === null || typeof value === "undefined") {
  628. throw new Error(message);
  629. }
  630. }
  631. function warning(cond, message) {
  632. if (!cond) {
  633. if (typeof console !== "undefined") console.warn(message);
  634. try {
  635. throw new Error(message);
  636. } catch (e) {
  637. }
  638. }
  639. }
  640. function createKey() {
  641. return Math.random().toString(36).substring(2, 10);
  642. }
  643. function getHistoryState(location2, index) {
  644. return {
  645. usr: location2.state,
  646. key: location2.key,
  647. idx: index
  648. };
  649. }
  650. function createLocation(current, to, state = null, key) {
  651. let location2 = {
  652. pathname: typeof current === "string" ? current : current.pathname,
  653. search: "",
  654. hash: "",
  655. ...typeof to === "string" ? parsePath(to) : to,
  656. state,
  657. // TODO: This could be cleaned up. push/replace should probably just take
  658. // full Locations now and avoid the need to run through this flow at all
  659. // But that's a pretty big refactor to the current test suite so going to
  660. // keep as is for the time being and just let any incoming keys take precedence
  661. key: to && to.key || key || createKey()
  662. };
  663. return location2;
  664. }
  665. function createPath({
  666. pathname = "/",
  667. search = "",
  668. hash = ""
  669. }) {
  670. if (search && search !== "?")
  671. pathname += search.charAt(0) === "?" ? search : "?" + search;
  672. if (hash && hash !== "#")
  673. pathname += hash.charAt(0) === "#" ? hash : "#" + hash;
  674. return pathname;
  675. }
  676. function parsePath(path) {
  677. let parsedPath = {};
  678. if (path) {
  679. let hashIndex = path.indexOf("#");
  680. if (hashIndex >= 0) {
  681. parsedPath.hash = path.substring(hashIndex);
  682. path = path.substring(0, hashIndex);
  683. }
  684. let searchIndex = path.indexOf("?");
  685. if (searchIndex >= 0) {
  686. parsedPath.search = path.substring(searchIndex);
  687. path = path.substring(0, searchIndex);
  688. }
  689. if (path) {
  690. parsedPath.pathname = path;
  691. }
  692. }
  693. return parsedPath;
  694. }
  695. function getUrlBasedHistory(getLocation, createHref2, validateLocation, options = {}) {
  696. let { window: window2 = document.defaultView, v5Compat = false } = options;
  697. let globalHistory = window2.history;
  698. let action = "POP";
  699. let listener = null;
  700. let index = getIndex();
  701. if (index == null) {
  702. index = 0;
  703. globalHistory.replaceState({ ...globalHistory.state, idx: index }, "");
  704. }
  705. function getIndex() {
  706. let state = globalHistory.state || { idx: null };
  707. return state.idx;
  708. }
  709. function handlePop() {
  710. action = "POP";
  711. let nextIndex = getIndex();
  712. let delta = nextIndex == null ? null : nextIndex - index;
  713. index = nextIndex;
  714. if (listener) {
  715. listener({ action, location: history.location, delta });
  716. }
  717. }
  718. function push(to, state) {
  719. action = "PUSH";
  720. let location2 = createLocation(history.location, to, state);
  721. if (validateLocation) validateLocation(location2, to);
  722. index = getIndex() + 1;
  723. let historyState = getHistoryState(location2, index);
  724. let url = history.createHref(location2);
  725. try {
  726. globalHistory.pushState(historyState, "", url);
  727. } catch (error) {
  728. if (error instanceof DOMException && error.name === "DataCloneError") {
  729. throw error;
  730. }
  731. window2.location.assign(url);
  732. }
  733. if (v5Compat && listener) {
  734. listener({ action, location: history.location, delta: 1 });
  735. }
  736. }
  737. function replace2(to, state) {
  738. action = "REPLACE";
  739. let location2 = createLocation(history.location, to, state);
  740. if (validateLocation) validateLocation(location2, to);
  741. index = getIndex();
  742. let historyState = getHistoryState(location2, index);
  743. let url = history.createHref(location2);
  744. globalHistory.replaceState(historyState, "", url);
  745. if (v5Compat && listener) {
  746. listener({ action, location: history.location, delta: 0 });
  747. }
  748. }
  749. function createURL(to) {
  750. return createBrowserURLImpl(to);
  751. }
  752. let history = {
  753. get action() {
  754. return action;
  755. },
  756. get location() {
  757. return getLocation(window2, globalHistory);
  758. },
  759. listen(fn) {
  760. if (listener) {
  761. throw new Error("A history only accepts one active listener");
  762. }
  763. window2.addEventListener(PopStateEventType, handlePop);
  764. listener = fn;
  765. return () => {
  766. window2.removeEventListener(PopStateEventType, handlePop);
  767. listener = null;
  768. };
  769. },
  770. createHref(to) {
  771. return createHref2(window2, to);
  772. },
  773. createURL,
  774. encodeLocation(to) {
  775. let url = createURL(to);
  776. return {
  777. pathname: url.pathname,
  778. search: url.search,
  779. hash: url.hash
  780. };
  781. },
  782. push,
  783. replace: replace2,
  784. go(n) {
  785. return globalHistory.go(n);
  786. }
  787. };
  788. return history;
  789. }
  790. function createBrowserURLImpl(to, isAbsolute = false) {
  791. let base = "http://localhost";
  792. if (typeof window !== "undefined") {
  793. base = window.location.origin !== "null" ? window.location.origin : window.location.href;
  794. }
  795. invariant(base, "No window.location.(origin|href) available to create URL");
  796. let href2 = typeof to === "string" ? to : createPath(to);
  797. href2 = href2.replace(/ $/, "%20");
  798. if (!isAbsolute && href2.startsWith("//")) {
  799. href2 = base + href2;
  800. }
  801. return new URL(href2, base);
  802. }
  803. function createContext4(defaultValue) {
  804. return { defaultValue };
  805. }
  806. var _map;
  807. var RouterContextProvider = class {
  808. /**
  809. * Create a new `RouterContextProvider` instance
  810. * @param init An optional initial context map to populate the provider with
  811. */
  812. constructor(init) {
  813. __privateAdd(this, _map, /* @__PURE__ */ new Map());
  814. if (init) {
  815. for (let [context, value] of init) {
  816. this.set(context, value);
  817. }
  818. }
  819. }
  820. /**
  821. * Access a value from the context. If no value has been set for the context,
  822. * it will return the context's `defaultValue` if provided, or throw an error
  823. * if no `defaultValue` was set.
  824. * @param context The context to get the value for
  825. * @returns The value for the context, or the context's `defaultValue` if no
  826. * value was set
  827. */
  828. get(context) {
  829. if (__privateGet(this, _map).has(context)) {
  830. return __privateGet(this, _map).get(context);
  831. }
  832. if (context.defaultValue !== void 0) {
  833. return context.defaultValue;
  834. }
  835. throw new Error("No value found for context");
  836. }
  837. /**
  838. * Set a value for the context. If the context already has a value set, this
  839. * will overwrite it.
  840. *
  841. * @param context The context to set the value for
  842. * @param value The value to set for the context
  843. * @returns {void}
  844. */
  845. set(context, value) {
  846. __privateGet(this, _map).set(context, value);
  847. }
  848. };
  849. _map = /* @__PURE__ */ new WeakMap();
  850. var unsupportedLazyRouteObjectKeys = /* @__PURE__ */ new Set([
  851. "lazy",
  852. "caseSensitive",
  853. "path",
  854. "id",
  855. "index",
  856. "children"
  857. ]);
  858. function isUnsupportedLazyRouteObjectKey(key) {
  859. return unsupportedLazyRouteObjectKeys.has(
  860. key
  861. );
  862. }
  863. var unsupportedLazyRouteFunctionKeys = /* @__PURE__ */ new Set([
  864. "lazy",
  865. "caseSensitive",
  866. "path",
  867. "id",
  868. "index",
  869. "middleware",
  870. "children"
  871. ]);
  872. function isUnsupportedLazyRouteFunctionKey(key) {
  873. return unsupportedLazyRouteFunctionKeys.has(
  874. key
  875. );
  876. }
  877. function isIndexRoute(route) {
  878. return route.index === true;
  879. }
  880. function convertRoutesToDataRoutes(routes, mapRouteProperties2, parentPath = [], manifest = {}, allowInPlaceMutations = false) {
  881. return routes.map((route, index) => {
  882. let treePath = [...parentPath, String(index)];
  883. let id = typeof route.id === "string" ? route.id : treePath.join("-");
  884. invariant(
  885. route.index !== true || !route.children,
  886. `Cannot specify children on an index route`
  887. );
  888. invariant(
  889. allowInPlaceMutations || !manifest[id],
  890. `Found a route id collision on id "${id}". Route id's must be globally unique within Data Router usages`
  891. );
  892. if (isIndexRoute(route)) {
  893. let indexRoute = {
  894. ...route,
  895. id
  896. };
  897. manifest[id] = mergeRouteUpdates(
  898. indexRoute,
  899. mapRouteProperties2(indexRoute)
  900. );
  901. return indexRoute;
  902. } else {
  903. let pathOrLayoutRoute = {
  904. ...route,
  905. id,
  906. children: void 0
  907. };
  908. manifest[id] = mergeRouteUpdates(
  909. pathOrLayoutRoute,
  910. mapRouteProperties2(pathOrLayoutRoute)
  911. );
  912. if (route.children) {
  913. pathOrLayoutRoute.children = convertRoutesToDataRoutes(
  914. route.children,
  915. mapRouteProperties2,
  916. treePath,
  917. manifest,
  918. allowInPlaceMutations
  919. );
  920. }
  921. return pathOrLayoutRoute;
  922. }
  923. });
  924. }
  925. function mergeRouteUpdates(route, updates) {
  926. return Object.assign(route, {
  927. ...updates,
  928. ...typeof updates.lazy === "object" && updates.lazy != null ? {
  929. lazy: {
  930. ...route.lazy,
  931. ...updates.lazy
  932. }
  933. } : {}
  934. });
  935. }
  936. function matchRoutes(routes, locationArg, basename = "/") {
  937. return matchRoutesImpl(routes, locationArg, basename, false);
  938. }
  939. function matchRoutesImpl(routes, locationArg, basename, allowPartial) {
  940. let location2 = typeof locationArg === "string" ? parsePath(locationArg) : locationArg;
  941. let pathname = stripBasename(location2.pathname || "/", basename);
  942. if (pathname == null) {
  943. return null;
  944. }
  945. let branches = flattenRoutes(routes);
  946. rankRouteBranches(branches);
  947. let matches = null;
  948. for (let i = 0; matches == null && i < branches.length; ++i) {
  949. let decoded = decodePath(pathname);
  950. matches = matchRouteBranch(
  951. branches[i],
  952. decoded,
  953. allowPartial
  954. );
  955. }
  956. return matches;
  957. }
  958. function convertRouteMatchToUiMatch(match, loaderData) {
  959. let { route, pathname, params } = match;
  960. return {
  961. id: route.id,
  962. pathname,
  963. params,
  964. data: loaderData[route.id],
  965. loaderData: loaderData[route.id],
  966. handle: route.handle
  967. };
  968. }
  969. function flattenRoutes(routes, branches = [], parentsMeta = [], parentPath = "", _hasParentOptionalSegments = false) {
  970. let flattenRoute = (route, index, hasParentOptionalSegments = _hasParentOptionalSegments, relativePath) => {
  971. let meta = {
  972. relativePath: relativePath === void 0 ? route.path || "" : relativePath,
  973. caseSensitive: route.caseSensitive === true,
  974. childrenIndex: index,
  975. route
  976. };
  977. if (meta.relativePath.startsWith("/")) {
  978. if (!meta.relativePath.startsWith(parentPath) && hasParentOptionalSegments) {
  979. return;
  980. }
  981. invariant(
  982. meta.relativePath.startsWith(parentPath),
  983. `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.`
  984. );
  985. meta.relativePath = meta.relativePath.slice(parentPath.length);
  986. }
  987. let path = joinPaths([parentPath, meta.relativePath]);
  988. let routesMeta = parentsMeta.concat(meta);
  989. if (route.children && route.children.length > 0) {
  990. invariant(
  991. // Our types know better, but runtime JS may not!
  992. // @ts-expect-error
  993. route.index !== true,
  994. `Index routes must not have child routes. Please remove all child routes from route path "${path}".`
  995. );
  996. flattenRoutes(
  997. route.children,
  998. branches,
  999. routesMeta,
  1000. path,
  1001. hasParentOptionalSegments
  1002. );
  1003. }
  1004. if (route.path == null && !route.index) {
  1005. return;
  1006. }
  1007. branches.push({
  1008. path,
  1009. score: computeScore(path, route.index),
  1010. routesMeta
  1011. });
  1012. };
  1013. routes.forEach((route, index) => {
  1014. var _a;
  1015. if (route.path === "" || !((_a = route.path) == null ? void 0 : _a.includes("?"))) {
  1016. flattenRoute(route, index);
  1017. } else {
  1018. for (let exploded of explodeOptionalSegments(route.path)) {
  1019. flattenRoute(route, index, true, exploded);
  1020. }
  1021. }
  1022. });
  1023. return branches;
  1024. }
  1025. function explodeOptionalSegments(path) {
  1026. let segments = path.split("/");
  1027. if (segments.length === 0) return [];
  1028. let [first, ...rest] = segments;
  1029. let isOptional = first.endsWith("?");
  1030. let required = first.replace(/\?$/, "");
  1031. if (rest.length === 0) {
  1032. return isOptional ? [required, ""] : [required];
  1033. }
  1034. let restExploded = explodeOptionalSegments(rest.join("/"));
  1035. let result = [];
  1036. result.push(
  1037. ...restExploded.map(
  1038. (subpath) => subpath === "" ? required : [required, subpath].join("/")
  1039. )
  1040. );
  1041. if (isOptional) {
  1042. result.push(...restExploded);
  1043. }
  1044. return result.map(
  1045. (exploded) => path.startsWith("/") && exploded === "" ? "/" : exploded
  1046. );
  1047. }
  1048. function rankRouteBranches(branches) {
  1049. branches.sort(
  1050. (a, b) => a.score !== b.score ? b.score - a.score : compareIndexes(
  1051. a.routesMeta.map((meta) => meta.childrenIndex),
  1052. b.routesMeta.map((meta) => meta.childrenIndex)
  1053. )
  1054. );
  1055. }
  1056. var paramRe = /^:[\w-]+$/;
  1057. var dynamicSegmentValue = 3;
  1058. var indexRouteValue = 2;
  1059. var emptySegmentValue = 1;
  1060. var staticSegmentValue = 10;
  1061. var splatPenalty = -2;
  1062. var isSplat = (s) => s === "*";
  1063. function computeScore(path, index) {
  1064. let segments = path.split("/");
  1065. let initialScore = segments.length;
  1066. if (segments.some(isSplat)) {
  1067. initialScore += splatPenalty;
  1068. }
  1069. if (index) {
  1070. initialScore += indexRouteValue;
  1071. }
  1072. return segments.filter((s) => !isSplat(s)).reduce(
  1073. (score, segment) => score + (paramRe.test(segment) ? dynamicSegmentValue : segment === "" ? emptySegmentValue : staticSegmentValue),
  1074. initialScore
  1075. );
  1076. }
  1077. function compareIndexes(a, b) {
  1078. let siblings = a.length === b.length && a.slice(0, -1).every((n, i) => n === b[i]);
  1079. return siblings ? (
  1080. // If two routes are siblings, we should try to match the earlier sibling
  1081. // first. This allows people to have fine-grained control over the matching
  1082. // behavior by simply putting routes with identical paths in the order they
  1083. // want them tried.
  1084. a[a.length - 1] - b[b.length - 1]
  1085. ) : (
  1086. // Otherwise, it doesn't really make sense to rank non-siblings by index,
  1087. // so they sort equally.
  1088. 0
  1089. );
  1090. }
  1091. function matchRouteBranch(branch, pathname, allowPartial = false) {
  1092. let { routesMeta } = branch;
  1093. let matchedParams = {};
  1094. let matchedPathname = "/";
  1095. let matches = [];
  1096. for (let i = 0; i < routesMeta.length; ++i) {
  1097. let meta = routesMeta[i];
  1098. let end = i === routesMeta.length - 1;
  1099. let remainingPathname = matchedPathname === "/" ? pathname : pathname.slice(matchedPathname.length) || "/";
  1100. let match = matchPath(
  1101. { path: meta.relativePath, caseSensitive: meta.caseSensitive, end },
  1102. remainingPathname
  1103. );
  1104. let route = meta.route;
  1105. if (!match && end && allowPartial && !routesMeta[routesMeta.length - 1].route.index) {
  1106. match = matchPath(
  1107. {
  1108. path: meta.relativePath,
  1109. caseSensitive: meta.caseSensitive,
  1110. end: false
  1111. },
  1112. remainingPathname
  1113. );
  1114. }
  1115. if (!match) {
  1116. return null;
  1117. }
  1118. Object.assign(matchedParams, match.params);
  1119. matches.push({
  1120. // TODO: Can this as be avoided?
  1121. params: matchedParams,
  1122. pathname: joinPaths([matchedPathname, match.pathname]),
  1123. pathnameBase: normalizePathname(
  1124. joinPaths([matchedPathname, match.pathnameBase])
  1125. ),
  1126. route
  1127. });
  1128. if (match.pathnameBase !== "/") {
  1129. matchedPathname = joinPaths([matchedPathname, match.pathnameBase]);
  1130. }
  1131. }
  1132. return matches;
  1133. }
  1134. function generatePath(originalPath, params = {}) {
  1135. let path = originalPath;
  1136. if (path.endsWith("*") && path !== "*" && !path.endsWith("/*")) {
  1137. warning(
  1138. false,
  1139. `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(/\*$/, "/*")}".`
  1140. );
  1141. path = path.replace(/\*$/, "/*");
  1142. }
  1143. const prefix = path.startsWith("/") ? "/" : "";
  1144. const stringify2 = (p) => p == null ? "" : typeof p === "string" ? p : String(p);
  1145. const segments = path.split(/\/+/).map((segment, index, array) => {
  1146. const isLastSegment = index === array.length - 1;
  1147. if (isLastSegment && segment === "*") {
  1148. const star = "*";
  1149. return stringify2(params[star]);
  1150. }
  1151. const keyMatch = segment.match(/^:([\w-]+)(\??)$/);
  1152. if (keyMatch) {
  1153. const [, key, optional] = keyMatch;
  1154. let param = params[key];
  1155. invariant(optional === "?" || param != null, `Missing ":${key}" param`);
  1156. return encodeURIComponent(stringify2(param));
  1157. }
  1158. return segment.replace(/\?$/g, "");
  1159. }).filter((segment) => !!segment);
  1160. return prefix + segments.join("/");
  1161. }
  1162. function matchPath(pattern, pathname) {
  1163. if (typeof pattern === "string") {
  1164. pattern = { path: pattern, caseSensitive: false, end: true };
  1165. }
  1166. let [matcher, compiledParams] = compilePath(
  1167. pattern.path,
  1168. pattern.caseSensitive,
  1169. pattern.end
  1170. );
  1171. let match = pathname.match(matcher);
  1172. if (!match) return null;
  1173. let matchedPathname = match[0];
  1174. let pathnameBase = matchedPathname.replace(/(.)\/+$/, "$1");
  1175. let captureGroups = match.slice(1);
  1176. let params = compiledParams.reduce(
  1177. (memo2, { paramName, isOptional }, index) => {
  1178. if (paramName === "*") {
  1179. let splatValue = captureGroups[index] || "";
  1180. pathnameBase = matchedPathname.slice(0, matchedPathname.length - splatValue.length).replace(/(.)\/+$/, "$1");
  1181. }
  1182. const value = captureGroups[index];
  1183. if (isOptional && !value) {
  1184. memo2[paramName] = void 0;
  1185. } else {
  1186. memo2[paramName] = (value || "").replace(/%2F/g, "/");
  1187. }
  1188. return memo2;
  1189. },
  1190. {}
  1191. );
  1192. return {
  1193. params,
  1194. pathname: matchedPathname,
  1195. pathnameBase,
  1196. pattern
  1197. };
  1198. }
  1199. function compilePath(path, caseSensitive = false, end = true) {
  1200. warning(
  1201. path === "*" || !path.endsWith("*") || path.endsWith("/*"),
  1202. `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(/\*$/, "/*")}".`
  1203. );
  1204. let params = [];
  1205. let regexpSource = "^" + path.replace(/\/*\*?$/, "").replace(/^\/*/, "/").replace(/[\\.*+^${}|()[\]]/g, "\\$&").replace(
  1206. /\/:([\w-]+)(\?)?/g,
  1207. (_, paramName, isOptional) => {
  1208. params.push({ paramName, isOptional: isOptional != null });
  1209. return isOptional ? "/?([^\\/]+)?" : "/([^\\/]+)";
  1210. }
  1211. ).replace(/\/([\w-]+)\?(\/|$)/g, "(/$1)?$2");
  1212. if (path.endsWith("*")) {
  1213. params.push({ paramName: "*" });
  1214. regexpSource += path === "*" || path === "/*" ? "(.*)$" : "(?:\\/(.+)|\\/*)$";
  1215. } else if (end) {
  1216. regexpSource += "\\/*$";
  1217. } else if (path !== "" && path !== "/") {
  1218. regexpSource += "(?:(?=\\/|$))";
  1219. } else {
  1220. }
  1221. let matcher = new RegExp(regexpSource, caseSensitive ? void 0 : "i");
  1222. return [matcher, params];
  1223. }
  1224. function decodePath(value) {
  1225. try {
  1226. return value.split("/").map((v) => decodeURIComponent(v).replace(/\//g, "%2F")).join("/");
  1227. } catch (error) {
  1228. warning(
  1229. false,
  1230. `The URL path "${value}" could not be decoded because it is a malformed URL segment. This is probably due to a bad percent encoding (${error}).`
  1231. );
  1232. return value;
  1233. }
  1234. }
  1235. function stripBasename(pathname, basename) {
  1236. if (basename === "/") return pathname;
  1237. if (!pathname.toLowerCase().startsWith(basename.toLowerCase())) {
  1238. return null;
  1239. }
  1240. let startIndex = basename.endsWith("/") ? basename.length - 1 : basename.length;
  1241. let nextChar = pathname.charAt(startIndex);
  1242. if (nextChar && nextChar !== "/") {
  1243. return null;
  1244. }
  1245. return pathname.slice(startIndex) || "/";
  1246. }
  1247. function prependBasename({
  1248. basename,
  1249. pathname
  1250. }) {
  1251. return pathname === "/" ? basename : joinPaths([basename, pathname]);
  1252. }
  1253. var ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i;
  1254. var isAbsoluteUrl = (url) => ABSOLUTE_URL_REGEX.test(url);
  1255. function resolvePath(to, fromPathname = "/") {
  1256. let {
  1257. pathname: toPathname,
  1258. search = "",
  1259. hash = ""
  1260. } = typeof to === "string" ? parsePath(to) : to;
  1261. let pathname;
  1262. if (toPathname) {
  1263. if (isAbsoluteUrl(toPathname)) {
  1264. pathname = toPathname;
  1265. } else {
  1266. if (toPathname.includes("//")) {
  1267. let oldPathname = toPathname;
  1268. toPathname = toPathname.replace(/\/\/+/g, "/");
  1269. warning(
  1270. false,
  1271. `Pathnames cannot have embedded double slashes - normalizing ${oldPathname} -> ${toPathname}`
  1272. );
  1273. }
  1274. if (toPathname.startsWith("/")) {
  1275. pathname = resolvePathname(toPathname.substring(1), "/");
  1276. } else {
  1277. pathname = resolvePathname(toPathname, fromPathname);
  1278. }
  1279. }
  1280. } else {
  1281. pathname = fromPathname;
  1282. }
  1283. return {
  1284. pathname,
  1285. search: normalizeSearch(search),
  1286. hash: normalizeHash(hash)
  1287. };
  1288. }
  1289. function resolvePathname(relativePath, fromPathname) {
  1290. let segments = fromPathname.replace(/\/+$/, "").split("/");
  1291. let relativeSegments = relativePath.split("/");
  1292. relativeSegments.forEach((segment) => {
  1293. if (segment === "..") {
  1294. if (segments.length > 1) segments.pop();
  1295. } else if (segment !== ".") {
  1296. segments.push(segment);
  1297. }
  1298. });
  1299. return segments.length > 1 ? segments.join("/") : "/";
  1300. }
  1301. function getInvalidPathError(char, field, dest, path) {
  1302. return `Cannot include a '${char}' character in a manually specified \`to.${field}\` field [${JSON.stringify(
  1303. path
  1304. )}]. 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.`;
  1305. }
  1306. function getPathContributingMatches(matches) {
  1307. return matches.filter(
  1308. (match, index) => index === 0 || match.route.path && match.route.path.length > 0
  1309. );
  1310. }
  1311. function getResolveToMatches(matches) {
  1312. let pathMatches = getPathContributingMatches(matches);
  1313. return pathMatches.map(
  1314. (match, idx) => idx === pathMatches.length - 1 ? match.pathname : match.pathnameBase
  1315. );
  1316. }
  1317. function resolveTo(toArg, routePathnames, locationPathname, isPathRelative = false) {
  1318. let to;
  1319. if (typeof toArg === "string") {
  1320. to = parsePath(toArg);
  1321. } else {
  1322. to = { ...toArg };
  1323. invariant(
  1324. !to.pathname || !to.pathname.includes("?"),
  1325. getInvalidPathError("?", "pathname", "search", to)
  1326. );
  1327. invariant(
  1328. !to.pathname || !to.pathname.includes("#"),
  1329. getInvalidPathError("#", "pathname", "hash", to)
  1330. );
  1331. invariant(
  1332. !to.search || !to.search.includes("#"),
  1333. getInvalidPathError("#", "search", "hash", to)
  1334. );
  1335. }
  1336. let isEmptyPath = toArg === "" || to.pathname === "";
  1337. let toPathname = isEmptyPath ? "/" : to.pathname;
  1338. let from;
  1339. if (toPathname == null) {
  1340. from = locationPathname;
  1341. } else {
  1342. let routePathnameIndex = routePathnames.length - 1;
  1343. if (!isPathRelative && toPathname.startsWith("..")) {
  1344. let toSegments = toPathname.split("/");
  1345. while (toSegments[0] === "..") {
  1346. toSegments.shift();
  1347. routePathnameIndex -= 1;
  1348. }
  1349. to.pathname = toSegments.join("/");
  1350. }
  1351. from = routePathnameIndex >= 0 ? routePathnames[routePathnameIndex] : "/";
  1352. }
  1353. let path = resolvePath(to, from);
  1354. let hasExplicitTrailingSlash = toPathname && toPathname !== "/" && toPathname.endsWith("/");
  1355. let hasCurrentTrailingSlash = (isEmptyPath || toPathname === ".") && locationPathname.endsWith("/");
  1356. if (!path.pathname.endsWith("/") && (hasExplicitTrailingSlash || hasCurrentTrailingSlash)) {
  1357. path.pathname += "/";
  1358. }
  1359. return path;
  1360. }
  1361. var joinPaths = (paths) => paths.join("/").replace(/\/\/+/g, "/");
  1362. var normalizePathname = (pathname) => pathname.replace(/\/+$/, "").replace(/^\/*/, "/");
  1363. var normalizeSearch = (search) => !search || search === "?" ? "" : search.startsWith("?") ? search : "?" + search;
  1364. var normalizeHash = (hash) => !hash || hash === "#" ? "" : hash.startsWith("#") ? hash : "#" + hash;
  1365. var DataWithResponseInit = class {
  1366. constructor(data2, init) {
  1367. this.type = "DataWithResponseInit";
  1368. this.data = data2;
  1369. this.init = init || null;
  1370. }
  1371. };
  1372. function data(data2, init) {
  1373. return new DataWithResponseInit(
  1374. data2,
  1375. typeof init === "number" ? { status: init } : init
  1376. );
  1377. }
  1378. var redirect = (url, init = 302) => {
  1379. let responseInit = init;
  1380. if (typeof responseInit === "number") {
  1381. responseInit = { status: responseInit };
  1382. } else if (typeof responseInit.status === "undefined") {
  1383. responseInit.status = 302;
  1384. }
  1385. let headers = new Headers(responseInit.headers);
  1386. headers.set("Location", url);
  1387. return new Response(null, { ...responseInit, headers });
  1388. };
  1389. var redirectDocument = (url, init) => {
  1390. let response = redirect(url, init);
  1391. response.headers.set("X-Remix-Reload-Document", "true");
  1392. return response;
  1393. };
  1394. var replace = (url, init) => {
  1395. let response = redirect(url, init);
  1396. response.headers.set("X-Remix-Replace", "true");
  1397. return response;
  1398. };
  1399. var ErrorResponseImpl = class {
  1400. constructor(status, statusText, data2, internal = false) {
  1401. this.status = status;
  1402. this.statusText = statusText || "";
  1403. this.internal = internal;
  1404. if (data2 instanceof Error) {
  1405. this.data = data2.toString();
  1406. this.error = data2;
  1407. } else {
  1408. this.data = data2;
  1409. }
  1410. }
  1411. };
  1412. function isRouteErrorResponse(error) {
  1413. return error != null && typeof error.status === "number" && typeof error.statusText === "string" && typeof error.internal === "boolean" && "data" in error;
  1414. }
  1415. function getRoutePattern(matches) {
  1416. return matches.map((m) => m.route.path).filter(Boolean).join("/").replace(/\/\/*/g, "/") || "/";
  1417. }
  1418. var UninstrumentedSymbol = Symbol("Uninstrumented");
  1419. function getRouteInstrumentationUpdates(fns, route) {
  1420. let aggregated = {
  1421. lazy: [],
  1422. "lazy.loader": [],
  1423. "lazy.action": [],
  1424. "lazy.middleware": [],
  1425. middleware: [],
  1426. loader: [],
  1427. action: []
  1428. };
  1429. fns.forEach(
  1430. (fn) => fn({
  1431. id: route.id,
  1432. index: route.index,
  1433. path: route.path,
  1434. instrument(i) {
  1435. let keys = Object.keys(aggregated);
  1436. for (let key of keys) {
  1437. if (i[key]) {
  1438. aggregated[key].push(i[key]);
  1439. }
  1440. }
  1441. }
  1442. })
  1443. );
  1444. let updates = {};
  1445. if (typeof route.lazy === "function" && aggregated.lazy.length > 0) {
  1446. let instrumented = wrapImpl(aggregated.lazy, route.lazy, () => void 0);
  1447. if (instrumented) {
  1448. updates.lazy = instrumented;
  1449. }
  1450. }
  1451. if (typeof route.lazy === "object") {
  1452. let lazyObject = route.lazy;
  1453. ["middleware", "loader", "action"].forEach((key) => {
  1454. let lazyFn = lazyObject[key];
  1455. let instrumentations = aggregated[`lazy.${key}`];
  1456. if (typeof lazyFn === "function" && instrumentations.length > 0) {
  1457. let instrumented = wrapImpl(instrumentations, lazyFn, () => void 0);
  1458. if (instrumented) {
  1459. updates.lazy = Object.assign(updates.lazy || {}, {
  1460. [key]: instrumented
  1461. });
  1462. }
  1463. }
  1464. });
  1465. }
  1466. ["loader", "action"].forEach((key) => {
  1467. let handler = route[key];
  1468. if (typeof handler === "function" && aggregated[key].length > 0) {
  1469. let original = handler[UninstrumentedSymbol] ?? handler;
  1470. let instrumented = wrapImpl(
  1471. aggregated[key],
  1472. original,
  1473. (...args) => getHandlerInfo(args[0])
  1474. );
  1475. if (instrumented) {
  1476. instrumented[UninstrumentedSymbol] = original;
  1477. updates[key] = instrumented;
  1478. }
  1479. }
  1480. });
  1481. if (route.middleware && route.middleware.length > 0 && aggregated.middleware.length > 0) {
  1482. updates.middleware = route.middleware.map((middleware) => {
  1483. let original = middleware[UninstrumentedSymbol] ?? middleware;
  1484. let instrumented = wrapImpl(
  1485. aggregated.middleware,
  1486. original,
  1487. (...args) => getHandlerInfo(args[0])
  1488. );
  1489. if (instrumented) {
  1490. instrumented[UninstrumentedSymbol] = original;
  1491. return instrumented;
  1492. }
  1493. return middleware;
  1494. });
  1495. }
  1496. return updates;
  1497. }
  1498. function instrumentClientSideRouter(router2, fns) {
  1499. let aggregated = {
  1500. navigate: [],
  1501. fetch: []
  1502. };
  1503. fns.forEach(
  1504. (fn) => fn({
  1505. instrument(i) {
  1506. let keys = Object.keys(i);
  1507. for (let key of keys) {
  1508. if (i[key]) {
  1509. aggregated[key].push(i[key]);
  1510. }
  1511. }
  1512. }
  1513. })
  1514. );
  1515. if (aggregated.navigate.length > 0) {
  1516. let navigate = router2.navigate[UninstrumentedSymbol] ?? router2.navigate;
  1517. let instrumentedNavigate = wrapImpl(
  1518. aggregated.navigate,
  1519. navigate,
  1520. (...args) => {
  1521. let [to, opts] = args;
  1522. return {
  1523. to: typeof to === "number" || typeof to === "string" ? to : to ? createPath(to) : ".",
  1524. ...getRouterInfo(router2, opts ?? {})
  1525. };
  1526. }
  1527. );
  1528. if (instrumentedNavigate) {
  1529. instrumentedNavigate[UninstrumentedSymbol] = navigate;
  1530. router2.navigate = instrumentedNavigate;
  1531. }
  1532. }
  1533. if (aggregated.fetch.length > 0) {
  1534. let fetch2 = router2.fetch[UninstrumentedSymbol] ?? router2.fetch;
  1535. let instrumentedFetch = wrapImpl(aggregated.fetch, fetch2, (...args) => {
  1536. let [key, , href2, opts] = args;
  1537. return {
  1538. href: href2 ?? ".",
  1539. fetcherKey: key,
  1540. ...getRouterInfo(router2, opts ?? {})
  1541. };
  1542. });
  1543. if (instrumentedFetch) {
  1544. instrumentedFetch[UninstrumentedSymbol] = fetch2;
  1545. router2.fetch = instrumentedFetch;
  1546. }
  1547. }
  1548. return router2;
  1549. }
  1550. function instrumentHandler(handler, fns) {
  1551. let aggregated = {
  1552. request: []
  1553. };
  1554. fns.forEach(
  1555. (fn) => fn({
  1556. instrument(i) {
  1557. let keys = Object.keys(i);
  1558. for (let key of keys) {
  1559. if (i[key]) {
  1560. aggregated[key].push(i[key]);
  1561. }
  1562. }
  1563. }
  1564. })
  1565. );
  1566. let instrumentedHandler = handler;
  1567. if (aggregated.request.length > 0) {
  1568. instrumentedHandler = wrapImpl(aggregated.request, handler, (...args) => {
  1569. let [request, context] = args;
  1570. return {
  1571. request: getReadonlyRequest(request),
  1572. context: context != null ? getReadonlyContext(context) : context
  1573. };
  1574. });
  1575. }
  1576. return instrumentedHandler;
  1577. }
  1578. function wrapImpl(impls, handler, getInfo) {
  1579. if (impls.length === 0) {
  1580. return null;
  1581. }
  1582. return async (...args) => {
  1583. let result = await recurseRight(
  1584. impls,
  1585. getInfo(...args),
  1586. () => handler(...args),
  1587. impls.length - 1
  1588. );
  1589. if (result.type === "error") {
  1590. throw result.value;
  1591. }
  1592. return result.value;
  1593. };
  1594. }
  1595. async function recurseRight(impls, info, handler, index) {
  1596. let impl = impls[index];
  1597. let result;
  1598. if (!impl) {
  1599. try {
  1600. let value = await handler();
  1601. result = { type: "success", value };
  1602. } catch (e) {
  1603. result = { type: "error", value: e };
  1604. }
  1605. } else {
  1606. let handlerPromise = void 0;
  1607. let callHandler = async () => {
  1608. if (handlerPromise) {
  1609. console.error("You cannot call instrumented handlers more than once");
  1610. } else {
  1611. handlerPromise = recurseRight(impls, info, handler, index - 1);
  1612. }
  1613. result = await handlerPromise;
  1614. invariant(result, "Expected a result");
  1615. if (result.type === "error" && result.value instanceof Error) {
  1616. return { status: "error", error: result.value };
  1617. }
  1618. return { status: "success", error: void 0 };
  1619. };
  1620. try {
  1621. await impl(callHandler, info);
  1622. } catch (e) {
  1623. console.error("An instrumentation function threw an error:", e);
  1624. }
  1625. if (!handlerPromise) {
  1626. await callHandler();
  1627. }
  1628. await handlerPromise;
  1629. }
  1630. if (result) {
  1631. return result;
  1632. }
  1633. return {
  1634. type: "error",
  1635. value: new Error("No result assigned in instrumentation chain.")
  1636. };
  1637. }
  1638. function getHandlerInfo(args) {
  1639. let { request, context, params, unstable_pattern } = args;
  1640. return {
  1641. request: getReadonlyRequest(request),
  1642. params: { ...params },
  1643. unstable_pattern,
  1644. context: getReadonlyContext(context)
  1645. };
  1646. }
  1647. function getRouterInfo(router2, opts) {
  1648. return {
  1649. currentUrl: createPath(router2.state.location),
  1650. ..."formMethod" in opts ? { formMethod: opts.formMethod } : {},
  1651. ..."formEncType" in opts ? { formEncType: opts.formEncType } : {},
  1652. ..."formData" in opts ? { formData: opts.formData } : {},
  1653. ..."body" in opts ? { body: opts.body } : {}
  1654. };
  1655. }
  1656. function getReadonlyRequest(request) {
  1657. return {
  1658. method: request.method,
  1659. url: request.url,
  1660. headers: {
  1661. get: (...args) => request.headers.get(...args)
  1662. }
  1663. };
  1664. }
  1665. function getReadonlyContext(context) {
  1666. if (isPlainObject(context)) {
  1667. let frozen = { ...context };
  1668. Object.freeze(frozen);
  1669. return frozen;
  1670. } else {
  1671. return {
  1672. get: (ctx) => context.get(ctx)
  1673. };
  1674. }
  1675. }
  1676. var objectProtoNames = Object.getOwnPropertyNames(Object.prototype).sort().join("\0");
  1677. function isPlainObject(thing) {
  1678. if (thing === null || typeof thing !== "object") {
  1679. return false;
  1680. }
  1681. const proto = Object.getPrototypeOf(thing);
  1682. return proto === Object.prototype || proto === null || Object.getOwnPropertyNames(proto).sort().join("\0") === objectProtoNames;
  1683. }
  1684. var validMutationMethodsArr = [
  1685. "POST",
  1686. "PUT",
  1687. "PATCH",
  1688. "DELETE"
  1689. ];
  1690. var validMutationMethods = new Set(
  1691. validMutationMethodsArr
  1692. );
  1693. var validRequestMethodsArr = [
  1694. "GET",
  1695. ...validMutationMethodsArr
  1696. ];
  1697. var validRequestMethods = new Set(validRequestMethodsArr);
  1698. var redirectStatusCodes = /* @__PURE__ */ new Set([301, 302, 303, 307, 308]);
  1699. var redirectPreserveMethodStatusCodes = /* @__PURE__ */ new Set([307, 308]);
  1700. var IDLE_NAVIGATION = {
  1701. state: "idle",
  1702. location: void 0,
  1703. formMethod: void 0,
  1704. formAction: void 0,
  1705. formEncType: void 0,
  1706. formData: void 0,
  1707. json: void 0,
  1708. text: void 0
  1709. };
  1710. var IDLE_FETCHER = {
  1711. state: "idle",
  1712. data: void 0,
  1713. formMethod: void 0,
  1714. formAction: void 0,
  1715. formEncType: void 0,
  1716. formData: void 0,
  1717. json: void 0,
  1718. text: void 0
  1719. };
  1720. var IDLE_BLOCKER = {
  1721. state: "unblocked",
  1722. proceed: void 0,
  1723. reset: void 0,
  1724. location: void 0
  1725. };
  1726. var defaultMapRouteProperties = (route) => ({
  1727. hasErrorBoundary: Boolean(route.hasErrorBoundary)
  1728. });
  1729. var TRANSITIONS_STORAGE_KEY = "remix-router-transitions";
  1730. var ResetLoaderDataSymbol = Symbol("ResetLoaderData");
  1731. function createRouter(init) {
  1732. const routerWindow = init.window ? init.window : typeof window !== "undefined" ? window : void 0;
  1733. const isBrowser2 = typeof routerWindow !== "undefined" && typeof routerWindow.document !== "undefined" && typeof routerWindow.document.createElement !== "undefined";
  1734. invariant(
  1735. init.routes.length > 0,
  1736. "You must provide a non-empty routes array to createRouter"
  1737. );
  1738. let hydrationRouteProperties2 = init.hydrationRouteProperties || [];
  1739. let _mapRouteProperties = init.mapRouteProperties || defaultMapRouteProperties;
  1740. let mapRouteProperties2 = _mapRouteProperties;
  1741. if (init.unstable_instrumentations) {
  1742. let instrumentations = init.unstable_instrumentations;
  1743. mapRouteProperties2 = (route) => {
  1744. return {
  1745. ..._mapRouteProperties(route),
  1746. ...getRouteInstrumentationUpdates(
  1747. instrumentations.map((i) => i.route).filter(Boolean),
  1748. route
  1749. )
  1750. };
  1751. };
  1752. }
  1753. let manifest = {};
  1754. let dataRoutes = convertRoutesToDataRoutes(
  1755. init.routes,
  1756. mapRouteProperties2,
  1757. void 0,
  1758. manifest
  1759. );
  1760. let inFlightDataRoutes;
  1761. let basename = init.basename || "/";
  1762. if (!basename.startsWith("/")) {
  1763. basename = `/${basename}`;
  1764. }
  1765. let dataStrategyImpl = init.dataStrategy || defaultDataStrategyWithMiddleware;
  1766. let future = {
  1767. ...init.future
  1768. };
  1769. let unlistenHistory = null;
  1770. let subscribers = /* @__PURE__ */ new Set();
  1771. let savedScrollPositions2 = null;
  1772. let getScrollRestorationKey2 = null;
  1773. let getScrollPosition = null;
  1774. let initialScrollRestored = init.hydrationData != null;
  1775. let initialMatches = matchRoutes(dataRoutes, init.history.location, basename);
  1776. let initialMatchesIsFOW = false;
  1777. let initialErrors = null;
  1778. let initialized;
  1779. if (initialMatches == null && !init.patchRoutesOnNavigation) {
  1780. let error = getInternalRouterError(404, {
  1781. pathname: init.history.location.pathname
  1782. });
  1783. let { matches, route } = getShortCircuitMatches(dataRoutes);
  1784. initialized = true;
  1785. initialMatches = matches;
  1786. initialErrors = { [route.id]: error };
  1787. } else {
  1788. if (initialMatches && !init.hydrationData) {
  1789. let fogOfWar = checkFogOfWar(
  1790. initialMatches,
  1791. dataRoutes,
  1792. init.history.location.pathname
  1793. );
  1794. if (fogOfWar.active) {
  1795. initialMatches = null;
  1796. }
  1797. }
  1798. if (!initialMatches) {
  1799. initialized = false;
  1800. initialMatches = [];
  1801. let fogOfWar = checkFogOfWar(
  1802. null,
  1803. dataRoutes,
  1804. init.history.location.pathname
  1805. );
  1806. if (fogOfWar.active && fogOfWar.matches) {
  1807. initialMatchesIsFOW = true;
  1808. initialMatches = fogOfWar.matches;
  1809. }
  1810. } else if (initialMatches.some((m) => m.route.lazy)) {
  1811. initialized = false;
  1812. } else if (!initialMatches.some((m) => routeHasLoaderOrMiddleware(m.route))) {
  1813. initialized = true;
  1814. } else {
  1815. let loaderData = init.hydrationData ? init.hydrationData.loaderData : null;
  1816. let errors = init.hydrationData ? init.hydrationData.errors : null;
  1817. if (errors) {
  1818. let idx = initialMatches.findIndex(
  1819. (m) => errors[m.route.id] !== void 0
  1820. );
  1821. initialized = initialMatches.slice(0, idx + 1).every(
  1822. (m) => !shouldLoadRouteOnHydration(m.route, loaderData, errors)
  1823. );
  1824. } else {
  1825. initialized = initialMatches.every(
  1826. (m) => !shouldLoadRouteOnHydration(m.route, loaderData, errors)
  1827. );
  1828. }
  1829. }
  1830. }
  1831. let router2;
  1832. let state = {
  1833. historyAction: init.history.action,
  1834. location: init.history.location,
  1835. matches: initialMatches,
  1836. initialized,
  1837. navigation: IDLE_NAVIGATION,
  1838. // Don't restore on initial updateState() if we were SSR'd
  1839. restoreScrollPosition: init.hydrationData != null ? false : null,
  1840. preventScrollReset: false,
  1841. revalidation: "idle",
  1842. loaderData: init.hydrationData && init.hydrationData.loaderData || {},
  1843. actionData: init.hydrationData && init.hydrationData.actionData || null,
  1844. errors: init.hydrationData && init.hydrationData.errors || initialErrors,
  1845. fetchers: /* @__PURE__ */ new Map(),
  1846. blockers: /* @__PURE__ */ new Map()
  1847. };
  1848. let pendingAction = "POP";
  1849. let pendingPopstateNavigationDfd = null;
  1850. let pendingPreventScrollReset = false;
  1851. let pendingNavigationController;
  1852. let pendingViewTransitionEnabled = false;
  1853. let appliedViewTransitions = /* @__PURE__ */ new Map();
  1854. let removePageHideEventListener = null;
  1855. let isUninterruptedRevalidation = false;
  1856. let isRevalidationRequired = false;
  1857. let cancelledFetcherLoads = /* @__PURE__ */ new Set();
  1858. let fetchControllers = /* @__PURE__ */ new Map();
  1859. let incrementingLoadId = 0;
  1860. let pendingNavigationLoadId = -1;
  1861. let fetchReloadIds = /* @__PURE__ */ new Map();
  1862. let fetchRedirectIds = /* @__PURE__ */ new Set();
  1863. let fetchLoadMatches = /* @__PURE__ */ new Map();
  1864. let activeFetchers = /* @__PURE__ */ new Map();
  1865. let fetchersQueuedForDeletion = /* @__PURE__ */ new Set();
  1866. let blockerFunctions = /* @__PURE__ */ new Map();
  1867. let unblockBlockerHistoryUpdate = void 0;
  1868. let pendingRevalidationDfd = null;
  1869. function initialize() {
  1870. unlistenHistory = init.history.listen(
  1871. ({ action: historyAction, location: location2, delta }) => {
  1872. if (unblockBlockerHistoryUpdate) {
  1873. unblockBlockerHistoryUpdate();
  1874. unblockBlockerHistoryUpdate = void 0;
  1875. return;
  1876. }
  1877. warning(
  1878. blockerFunctions.size === 0 || delta != null,
  1879. "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."
  1880. );
  1881. let blockerKey = shouldBlockNavigation({
  1882. currentLocation: state.location,
  1883. nextLocation: location2,
  1884. historyAction
  1885. });
  1886. if (blockerKey && delta != null) {
  1887. let nextHistoryUpdatePromise = new Promise((resolve) => {
  1888. unblockBlockerHistoryUpdate = resolve;
  1889. });
  1890. init.history.go(delta * -1);
  1891. updateBlocker(blockerKey, {
  1892. state: "blocked",
  1893. location: location2,
  1894. proceed() {
  1895. updateBlocker(blockerKey, {
  1896. state: "proceeding",
  1897. proceed: void 0,
  1898. reset: void 0,
  1899. location: location2
  1900. });
  1901. nextHistoryUpdatePromise.then(() => init.history.go(delta));
  1902. },
  1903. reset() {
  1904. let blockers = new Map(state.blockers);
  1905. blockers.set(blockerKey, IDLE_BLOCKER);
  1906. updateState({ blockers });
  1907. }
  1908. });
  1909. pendingPopstateNavigationDfd == null ? void 0 : pendingPopstateNavigationDfd.resolve();
  1910. pendingPopstateNavigationDfd = null;
  1911. return;
  1912. }
  1913. return startNavigation(historyAction, location2);
  1914. }
  1915. );
  1916. if (isBrowser2) {
  1917. restoreAppliedTransitions(routerWindow, appliedViewTransitions);
  1918. let _saveAppliedTransitions = () => persistAppliedTransitions(routerWindow, appliedViewTransitions);
  1919. routerWindow.addEventListener("pagehide", _saveAppliedTransitions);
  1920. removePageHideEventListener = () => routerWindow.removeEventListener("pagehide", _saveAppliedTransitions);
  1921. }
  1922. if (!state.initialized) {
  1923. startNavigation("POP", state.location, {
  1924. initialHydration: true
  1925. });
  1926. }
  1927. return router2;
  1928. }
  1929. function dispose() {
  1930. if (unlistenHistory) {
  1931. unlistenHistory();
  1932. }
  1933. if (removePageHideEventListener) {
  1934. removePageHideEventListener();
  1935. }
  1936. subscribers.clear();
  1937. pendingNavigationController && pendingNavigationController.abort();
  1938. state.fetchers.forEach((_, key) => deleteFetcher(key));
  1939. state.blockers.forEach((_, key) => deleteBlocker(key));
  1940. }
  1941. function subscribe(fn) {
  1942. subscribers.add(fn);
  1943. return () => subscribers.delete(fn);
  1944. }
  1945. function updateState(newState, opts = {}) {
  1946. if (newState.matches) {
  1947. newState.matches = newState.matches.map((m) => {
  1948. let route = manifest[m.route.id];
  1949. let matchRoute = m.route;
  1950. if (matchRoute.element !== route.element || matchRoute.errorElement !== route.errorElement || matchRoute.hydrateFallbackElement !== route.hydrateFallbackElement) {
  1951. return {
  1952. ...m,
  1953. route
  1954. };
  1955. }
  1956. return m;
  1957. });
  1958. }
  1959. state = {
  1960. ...state,
  1961. ...newState
  1962. };
  1963. let unmountedFetchers = [];
  1964. let mountedFetchers = [];
  1965. state.fetchers.forEach((fetcher, key) => {
  1966. if (fetcher.state === "idle") {
  1967. if (fetchersQueuedForDeletion.has(key)) {
  1968. unmountedFetchers.push(key);
  1969. } else {
  1970. mountedFetchers.push(key);
  1971. }
  1972. }
  1973. });
  1974. fetchersQueuedForDeletion.forEach((key) => {
  1975. if (!state.fetchers.has(key) && !fetchControllers.has(key)) {
  1976. unmountedFetchers.push(key);
  1977. }
  1978. });
  1979. [...subscribers].forEach(
  1980. (subscriber) => subscriber(state, {
  1981. deletedFetchers: unmountedFetchers,
  1982. newErrors: newState.errors ?? null,
  1983. viewTransitionOpts: opts.viewTransitionOpts,
  1984. flushSync: opts.flushSync === true
  1985. })
  1986. );
  1987. unmountedFetchers.forEach((key) => deleteFetcher(key));
  1988. mountedFetchers.forEach((key) => state.fetchers.delete(key));
  1989. }
  1990. function completeNavigation(location2, newState, { flushSync: flushSync3 } = {}) {
  1991. var _a, _b;
  1992. let isActionReload = state.actionData != null && state.navigation.formMethod != null && isMutationMethod(state.navigation.formMethod) && state.navigation.state === "loading" && ((_a = location2.state) == null ? void 0 : _a._isRedirect) !== true;
  1993. let actionData;
  1994. if (newState.actionData) {
  1995. if (Object.keys(newState.actionData).length > 0) {
  1996. actionData = newState.actionData;
  1997. } else {
  1998. actionData = null;
  1999. }
  2000. } else if (isActionReload) {
  2001. actionData = state.actionData;
  2002. } else {
  2003. actionData = null;
  2004. }
  2005. let loaderData = newState.loaderData ? mergeLoaderData(
  2006. state.loaderData,
  2007. newState.loaderData,
  2008. newState.matches || [],
  2009. newState.errors
  2010. ) : state.loaderData;
  2011. let blockers = state.blockers;
  2012. if (blockers.size > 0) {
  2013. blockers = new Map(blockers);
  2014. blockers.forEach((_, k) => blockers.set(k, IDLE_BLOCKER));
  2015. }
  2016. let restoreScrollPosition = isUninterruptedRevalidation ? false : getSavedScrollPosition(location2, newState.matches || state.matches);
  2017. let preventScrollReset = pendingPreventScrollReset === true || state.navigation.formMethod != null && isMutationMethod(state.navigation.formMethod) && ((_b = location2.state) == null ? void 0 : _b._isRedirect) !== true;
  2018. if (inFlightDataRoutes) {
  2019. dataRoutes = inFlightDataRoutes;
  2020. inFlightDataRoutes = void 0;
  2021. }
  2022. if (isUninterruptedRevalidation) {
  2023. } else if (pendingAction === "POP") {
  2024. } else if (pendingAction === "PUSH") {
  2025. init.history.push(location2, location2.state);
  2026. } else if (pendingAction === "REPLACE") {
  2027. init.history.replace(location2, location2.state);
  2028. }
  2029. let viewTransitionOpts;
  2030. if (pendingAction === "POP") {
  2031. let priorPaths = appliedViewTransitions.get(state.location.pathname);
  2032. if (priorPaths && priorPaths.has(location2.pathname)) {
  2033. viewTransitionOpts = {
  2034. currentLocation: state.location,
  2035. nextLocation: location2
  2036. };
  2037. } else if (appliedViewTransitions.has(location2.pathname)) {
  2038. viewTransitionOpts = {
  2039. currentLocation: location2,
  2040. nextLocation: state.location
  2041. };
  2042. }
  2043. } else if (pendingViewTransitionEnabled) {
  2044. let toPaths = appliedViewTransitions.get(state.location.pathname);
  2045. if (toPaths) {
  2046. toPaths.add(location2.pathname);
  2047. } else {
  2048. toPaths = /* @__PURE__ */ new Set([location2.pathname]);
  2049. appliedViewTransitions.set(state.location.pathname, toPaths);
  2050. }
  2051. viewTransitionOpts = {
  2052. currentLocation: state.location,
  2053. nextLocation: location2
  2054. };
  2055. }
  2056. updateState(
  2057. {
  2058. ...newState,
  2059. // matches, errors, fetchers go through as-is
  2060. actionData,
  2061. loaderData,
  2062. historyAction: pendingAction,
  2063. location: location2,
  2064. initialized: true,
  2065. navigation: IDLE_NAVIGATION,
  2066. revalidation: "idle",
  2067. restoreScrollPosition,
  2068. preventScrollReset,
  2069. blockers
  2070. },
  2071. {
  2072. viewTransitionOpts,
  2073. flushSync: flushSync3 === true
  2074. }
  2075. );
  2076. pendingAction = "POP";
  2077. pendingPreventScrollReset = false;
  2078. pendingViewTransitionEnabled = false;
  2079. isUninterruptedRevalidation = false;
  2080. isRevalidationRequired = false;
  2081. pendingPopstateNavigationDfd == null ? void 0 : pendingPopstateNavigationDfd.resolve();
  2082. pendingPopstateNavigationDfd = null;
  2083. pendingRevalidationDfd == null ? void 0 : pendingRevalidationDfd.resolve();
  2084. pendingRevalidationDfd = null;
  2085. }
  2086. async function navigate(to, opts) {
  2087. pendingPopstateNavigationDfd == null ? void 0 : pendingPopstateNavigationDfd.resolve();
  2088. pendingPopstateNavigationDfd = null;
  2089. if (typeof to === "number") {
  2090. if (!pendingPopstateNavigationDfd) {
  2091. pendingPopstateNavigationDfd = createDeferred();
  2092. }
  2093. let promise = pendingPopstateNavigationDfd.promise;
  2094. init.history.go(to);
  2095. return promise;
  2096. }
  2097. let normalizedPath = normalizeTo(
  2098. state.location,
  2099. state.matches,
  2100. basename,
  2101. to,
  2102. opts == null ? void 0 : opts.fromRouteId,
  2103. opts == null ? void 0 : opts.relative
  2104. );
  2105. let { path, submission, error } = normalizeNavigateOptions(
  2106. false,
  2107. normalizedPath,
  2108. opts
  2109. );
  2110. let currentLocation = state.location;
  2111. let nextLocation = createLocation(state.location, path, opts && opts.state);
  2112. nextLocation = {
  2113. ...nextLocation,
  2114. ...init.history.encodeLocation(nextLocation)
  2115. };
  2116. let userReplace = opts && opts.replace != null ? opts.replace : void 0;
  2117. let historyAction = "PUSH";
  2118. if (userReplace === true) {
  2119. historyAction = "REPLACE";
  2120. } else if (userReplace === false) {
  2121. } else if (submission != null && isMutationMethod(submission.formMethod) && submission.formAction === state.location.pathname + state.location.search) {
  2122. historyAction = "REPLACE";
  2123. }
  2124. let preventScrollReset = opts && "preventScrollReset" in opts ? opts.preventScrollReset === true : void 0;
  2125. let flushSync3 = (opts && opts.flushSync) === true;
  2126. let blockerKey = shouldBlockNavigation({
  2127. currentLocation,
  2128. nextLocation,
  2129. historyAction
  2130. });
  2131. if (blockerKey) {
  2132. updateBlocker(blockerKey, {
  2133. state: "blocked",
  2134. location: nextLocation,
  2135. proceed() {
  2136. updateBlocker(blockerKey, {
  2137. state: "proceeding",
  2138. proceed: void 0,
  2139. reset: void 0,
  2140. location: nextLocation
  2141. });
  2142. navigate(to, opts);
  2143. },
  2144. reset() {
  2145. let blockers = new Map(state.blockers);
  2146. blockers.set(blockerKey, IDLE_BLOCKER);
  2147. updateState({ blockers });
  2148. }
  2149. });
  2150. return;
  2151. }
  2152. await startNavigation(historyAction, nextLocation, {
  2153. submission,
  2154. // Send through the formData serialization error if we have one so we can
  2155. // render at the right error boundary after we match routes
  2156. pendingError: error,
  2157. preventScrollReset,
  2158. replace: opts && opts.replace,
  2159. enableViewTransition: opts && opts.viewTransition,
  2160. flushSync: flushSync3
  2161. });
  2162. }
  2163. function revalidate() {
  2164. if (!pendingRevalidationDfd) {
  2165. pendingRevalidationDfd = createDeferred();
  2166. }
  2167. interruptActiveLoads();
  2168. updateState({ revalidation: "loading" });
  2169. let promise = pendingRevalidationDfd.promise;
  2170. if (state.navigation.state === "submitting") {
  2171. return promise;
  2172. }
  2173. if (state.navigation.state === "idle") {
  2174. startNavigation(state.historyAction, state.location, {
  2175. startUninterruptedRevalidation: true
  2176. });
  2177. return promise;
  2178. }
  2179. startNavigation(
  2180. pendingAction || state.historyAction,
  2181. state.navigation.location,
  2182. {
  2183. overrideNavigation: state.navigation,
  2184. // Proxy through any rending view transition
  2185. enableViewTransition: pendingViewTransitionEnabled === true
  2186. }
  2187. );
  2188. return promise;
  2189. }
  2190. async function startNavigation(historyAction, location2, opts) {
  2191. pendingNavigationController && pendingNavigationController.abort();
  2192. pendingNavigationController = null;
  2193. pendingAction = historyAction;
  2194. isUninterruptedRevalidation = (opts && opts.startUninterruptedRevalidation) === true;
  2195. saveScrollPosition(state.location, state.matches);
  2196. pendingPreventScrollReset = (opts && opts.preventScrollReset) === true;
  2197. pendingViewTransitionEnabled = (opts && opts.enableViewTransition) === true;
  2198. let routesToUse = inFlightDataRoutes || dataRoutes;
  2199. let loadingNavigation = opts && opts.overrideNavigation;
  2200. let matches = (opts == null ? void 0 : opts.initialHydration) && state.matches && state.matches.length > 0 && !initialMatchesIsFOW ? (
  2201. // `matchRoutes()` has already been called if we're in here via `router.initialize()`
  2202. state.matches
  2203. ) : matchRoutes(routesToUse, location2, basename);
  2204. let flushSync3 = (opts && opts.flushSync) === true;
  2205. if (matches && state.initialized && !isRevalidationRequired && isHashChangeOnly(state.location, location2) && !(opts && opts.submission && isMutationMethod(opts.submission.formMethod))) {
  2206. completeNavigation(location2, { matches }, { flushSync: flushSync3 });
  2207. return;
  2208. }
  2209. let fogOfWar = checkFogOfWar(matches, routesToUse, location2.pathname);
  2210. if (fogOfWar.active && fogOfWar.matches) {
  2211. matches = fogOfWar.matches;
  2212. }
  2213. if (!matches) {
  2214. let { error, notFoundMatches, route } = handleNavigational404(
  2215. location2.pathname
  2216. );
  2217. completeNavigation(
  2218. location2,
  2219. {
  2220. matches: notFoundMatches,
  2221. loaderData: {},
  2222. errors: {
  2223. [route.id]: error
  2224. }
  2225. },
  2226. { flushSync: flushSync3 }
  2227. );
  2228. return;
  2229. }
  2230. pendingNavigationController = new AbortController();
  2231. let request = createClientSideRequest(
  2232. init.history,
  2233. location2,
  2234. pendingNavigationController.signal,
  2235. opts && opts.submission
  2236. );
  2237. let scopedContext = init.getContext ? await init.getContext() : new RouterContextProvider();
  2238. let pendingActionResult;
  2239. if (opts && opts.pendingError) {
  2240. pendingActionResult = [
  2241. findNearestBoundary(matches).route.id,
  2242. { type: "error", error: opts.pendingError }
  2243. ];
  2244. } else if (opts && opts.submission && isMutationMethod(opts.submission.formMethod)) {
  2245. let actionResult = await handleAction(
  2246. request,
  2247. location2,
  2248. opts.submission,
  2249. matches,
  2250. scopedContext,
  2251. fogOfWar.active,
  2252. opts && opts.initialHydration === true,
  2253. { replace: opts.replace, flushSync: flushSync3 }
  2254. );
  2255. if (actionResult.shortCircuited) {
  2256. return;
  2257. }
  2258. if (actionResult.pendingActionResult) {
  2259. let [routeId, result] = actionResult.pendingActionResult;
  2260. if (isErrorResult(result) && isRouteErrorResponse(result.error) && result.error.status === 404) {
  2261. pendingNavigationController = null;
  2262. completeNavigation(location2, {
  2263. matches: actionResult.matches,
  2264. loaderData: {},
  2265. errors: {
  2266. [routeId]: result.error
  2267. }
  2268. });
  2269. return;
  2270. }
  2271. }
  2272. matches = actionResult.matches || matches;
  2273. pendingActionResult = actionResult.pendingActionResult;
  2274. loadingNavigation = getLoadingNavigation(location2, opts.submission);
  2275. flushSync3 = false;
  2276. fogOfWar.active = false;
  2277. request = createClientSideRequest(
  2278. init.history,
  2279. request.url,
  2280. request.signal
  2281. );
  2282. }
  2283. let {
  2284. shortCircuited,
  2285. matches: updatedMatches,
  2286. loaderData,
  2287. errors
  2288. } = await handleLoaders(
  2289. request,
  2290. location2,
  2291. matches,
  2292. scopedContext,
  2293. fogOfWar.active,
  2294. loadingNavigation,
  2295. opts && opts.submission,
  2296. opts && opts.fetcherSubmission,
  2297. opts && opts.replace,
  2298. opts && opts.initialHydration === true,
  2299. flushSync3,
  2300. pendingActionResult
  2301. );
  2302. if (shortCircuited) {
  2303. return;
  2304. }
  2305. pendingNavigationController = null;
  2306. completeNavigation(location2, {
  2307. matches: updatedMatches || matches,
  2308. ...getActionDataForCommit(pendingActionResult),
  2309. loaderData,
  2310. errors
  2311. });
  2312. }
  2313. async function handleAction(request, location2, submission, matches, scopedContext, isFogOfWar, initialHydration, opts = {}) {
  2314. interruptActiveLoads();
  2315. let navigation = getSubmittingNavigation(location2, submission);
  2316. updateState({ navigation }, { flushSync: opts.flushSync === true });
  2317. if (isFogOfWar) {
  2318. let discoverResult = await discoverRoutes(
  2319. matches,
  2320. location2.pathname,
  2321. request.signal
  2322. );
  2323. if (discoverResult.type === "aborted") {
  2324. return { shortCircuited: true };
  2325. } else if (discoverResult.type === "error") {
  2326. if (discoverResult.partialMatches.length === 0) {
  2327. let { matches: matches2, route } = getShortCircuitMatches(dataRoutes);
  2328. return {
  2329. matches: matches2,
  2330. pendingActionResult: [
  2331. route.id,
  2332. {
  2333. type: "error",
  2334. error: discoverResult.error
  2335. }
  2336. ]
  2337. };
  2338. }
  2339. let boundaryId = findNearestBoundary(discoverResult.partialMatches).route.id;
  2340. return {
  2341. matches: discoverResult.partialMatches,
  2342. pendingActionResult: [
  2343. boundaryId,
  2344. {
  2345. type: "error",
  2346. error: discoverResult.error
  2347. }
  2348. ]
  2349. };
  2350. } else if (!discoverResult.matches) {
  2351. let { notFoundMatches, error, route } = handleNavigational404(
  2352. location2.pathname
  2353. );
  2354. return {
  2355. matches: notFoundMatches,
  2356. pendingActionResult: [
  2357. route.id,
  2358. {
  2359. type: "error",
  2360. error
  2361. }
  2362. ]
  2363. };
  2364. } else {
  2365. matches = discoverResult.matches;
  2366. }
  2367. }
  2368. let result;
  2369. let actionMatch = getTargetMatch(matches, location2);
  2370. if (!actionMatch.route.action && !actionMatch.route.lazy) {
  2371. result = {
  2372. type: "error",
  2373. error: getInternalRouterError(405, {
  2374. method: request.method,
  2375. pathname: location2.pathname,
  2376. routeId: actionMatch.route.id
  2377. })
  2378. };
  2379. } else {
  2380. let dsMatches = getTargetedDataStrategyMatches(
  2381. mapRouteProperties2,
  2382. manifest,
  2383. request,
  2384. matches,
  2385. actionMatch,
  2386. initialHydration ? [] : hydrationRouteProperties2,
  2387. scopedContext
  2388. );
  2389. let results = await callDataStrategy(
  2390. request,
  2391. dsMatches,
  2392. scopedContext,
  2393. null
  2394. );
  2395. result = results[actionMatch.route.id];
  2396. if (!result) {
  2397. for (let match of matches) {
  2398. if (results[match.route.id]) {
  2399. result = results[match.route.id];
  2400. break;
  2401. }
  2402. }
  2403. }
  2404. if (request.signal.aborted) {
  2405. return { shortCircuited: true };
  2406. }
  2407. }
  2408. if (isRedirectResult(result)) {
  2409. let replace2;
  2410. if (opts && opts.replace != null) {
  2411. replace2 = opts.replace;
  2412. } else {
  2413. let location22 = normalizeRedirectLocation(
  2414. result.response.headers.get("Location"),
  2415. new URL(request.url),
  2416. basename
  2417. );
  2418. replace2 = location22 === state.location.pathname + state.location.search;
  2419. }
  2420. await startRedirectNavigation(request, result, true, {
  2421. submission,
  2422. replace: replace2
  2423. });
  2424. return { shortCircuited: true };
  2425. }
  2426. if (isErrorResult(result)) {
  2427. let boundaryMatch = findNearestBoundary(matches, actionMatch.route.id);
  2428. if ((opts && opts.replace) !== true) {
  2429. pendingAction = "PUSH";
  2430. }
  2431. return {
  2432. matches,
  2433. pendingActionResult: [
  2434. boundaryMatch.route.id,
  2435. result,
  2436. actionMatch.route.id
  2437. ]
  2438. };
  2439. }
  2440. return {
  2441. matches,
  2442. pendingActionResult: [actionMatch.route.id, result]
  2443. };
  2444. }
  2445. async function handleLoaders(request, location2, matches, scopedContext, isFogOfWar, overrideNavigation, submission, fetcherSubmission, replace2, initialHydration, flushSync3, pendingActionResult) {
  2446. let loadingNavigation = overrideNavigation || getLoadingNavigation(location2, submission);
  2447. let activeSubmission = submission || fetcherSubmission || getSubmissionFromNavigation(loadingNavigation);
  2448. let shouldUpdateNavigationState = !isUninterruptedRevalidation && !initialHydration;
  2449. if (isFogOfWar) {
  2450. if (shouldUpdateNavigationState) {
  2451. let actionData = getUpdatedActionData(pendingActionResult);
  2452. updateState(
  2453. {
  2454. navigation: loadingNavigation,
  2455. ...actionData !== void 0 ? { actionData } : {}
  2456. },
  2457. {
  2458. flushSync: flushSync3
  2459. }
  2460. );
  2461. }
  2462. let discoverResult = await discoverRoutes(
  2463. matches,
  2464. location2.pathname,
  2465. request.signal
  2466. );
  2467. if (discoverResult.type === "aborted") {
  2468. return { shortCircuited: true };
  2469. } else if (discoverResult.type === "error") {
  2470. if (discoverResult.partialMatches.length === 0) {
  2471. let { matches: matches2, route } = getShortCircuitMatches(dataRoutes);
  2472. return {
  2473. matches: matches2,
  2474. loaderData: {},
  2475. errors: {
  2476. [route.id]: discoverResult.error
  2477. }
  2478. };
  2479. }
  2480. let boundaryId = findNearestBoundary(discoverResult.partialMatches).route.id;
  2481. return {
  2482. matches: discoverResult.partialMatches,
  2483. loaderData: {},
  2484. errors: {
  2485. [boundaryId]: discoverResult.error
  2486. }
  2487. };
  2488. } else if (!discoverResult.matches) {
  2489. let { error, notFoundMatches, route } = handleNavigational404(
  2490. location2.pathname
  2491. );
  2492. return {
  2493. matches: notFoundMatches,
  2494. loaderData: {},
  2495. errors: {
  2496. [route.id]: error
  2497. }
  2498. };
  2499. } else {
  2500. matches = discoverResult.matches;
  2501. }
  2502. }
  2503. let routesToUse = inFlightDataRoutes || dataRoutes;
  2504. let { dsMatches, revalidatingFetchers } = getMatchesToLoad(
  2505. request,
  2506. scopedContext,
  2507. mapRouteProperties2,
  2508. manifest,
  2509. init.history,
  2510. state,
  2511. matches,
  2512. activeSubmission,
  2513. location2,
  2514. initialHydration ? [] : hydrationRouteProperties2,
  2515. initialHydration === true,
  2516. isRevalidationRequired,
  2517. cancelledFetcherLoads,
  2518. fetchersQueuedForDeletion,
  2519. fetchLoadMatches,
  2520. fetchRedirectIds,
  2521. routesToUse,
  2522. basename,
  2523. init.patchRoutesOnNavigation != null,
  2524. pendingActionResult
  2525. );
  2526. pendingNavigationLoadId = ++incrementingLoadId;
  2527. if (!init.dataStrategy && !dsMatches.some((m) => m.shouldLoad) && !dsMatches.some(
  2528. (m) => m.route.middleware && m.route.middleware.length > 0
  2529. ) && revalidatingFetchers.length === 0) {
  2530. let updatedFetchers2 = markFetchRedirectsDone();
  2531. completeNavigation(
  2532. location2,
  2533. {
  2534. matches,
  2535. loaderData: {},
  2536. // Commit pending error if we're short circuiting
  2537. errors: pendingActionResult && isErrorResult(pendingActionResult[1]) ? { [pendingActionResult[0]]: pendingActionResult[1].error } : null,
  2538. ...getActionDataForCommit(pendingActionResult),
  2539. ...updatedFetchers2 ? { fetchers: new Map(state.fetchers) } : {}
  2540. },
  2541. { flushSync: flushSync3 }
  2542. );
  2543. return { shortCircuited: true };
  2544. }
  2545. if (shouldUpdateNavigationState) {
  2546. let updates = {};
  2547. if (!isFogOfWar) {
  2548. updates.navigation = loadingNavigation;
  2549. let actionData = getUpdatedActionData(pendingActionResult);
  2550. if (actionData !== void 0) {
  2551. updates.actionData = actionData;
  2552. }
  2553. }
  2554. if (revalidatingFetchers.length > 0) {
  2555. updates.fetchers = getUpdatedRevalidatingFetchers(revalidatingFetchers);
  2556. }
  2557. updateState(updates, { flushSync: flushSync3 });
  2558. }
  2559. revalidatingFetchers.forEach((rf) => {
  2560. abortFetcher(rf.key);
  2561. if (rf.controller) {
  2562. fetchControllers.set(rf.key, rf.controller);
  2563. }
  2564. });
  2565. let abortPendingFetchRevalidations = () => revalidatingFetchers.forEach((f) => abortFetcher(f.key));
  2566. if (pendingNavigationController) {
  2567. pendingNavigationController.signal.addEventListener(
  2568. "abort",
  2569. abortPendingFetchRevalidations
  2570. );
  2571. }
  2572. let { loaderResults, fetcherResults } = await callLoadersAndMaybeResolveData(
  2573. dsMatches,
  2574. revalidatingFetchers,
  2575. request,
  2576. scopedContext
  2577. );
  2578. if (request.signal.aborted) {
  2579. return { shortCircuited: true };
  2580. }
  2581. if (pendingNavigationController) {
  2582. pendingNavigationController.signal.removeEventListener(
  2583. "abort",
  2584. abortPendingFetchRevalidations
  2585. );
  2586. }
  2587. revalidatingFetchers.forEach((rf) => fetchControllers.delete(rf.key));
  2588. let redirect2 = findRedirect(loaderResults);
  2589. if (redirect2) {
  2590. await startRedirectNavigation(request, redirect2.result, true, {
  2591. replace: replace2
  2592. });
  2593. return { shortCircuited: true };
  2594. }
  2595. redirect2 = findRedirect(fetcherResults);
  2596. if (redirect2) {
  2597. fetchRedirectIds.add(redirect2.key);
  2598. await startRedirectNavigation(request, redirect2.result, true, {
  2599. replace: replace2
  2600. });
  2601. return { shortCircuited: true };
  2602. }
  2603. let { loaderData, errors } = processLoaderData(
  2604. state,
  2605. matches,
  2606. loaderResults,
  2607. pendingActionResult,
  2608. revalidatingFetchers,
  2609. fetcherResults
  2610. );
  2611. if (initialHydration && state.errors) {
  2612. errors = { ...state.errors, ...errors };
  2613. }
  2614. let updatedFetchers = markFetchRedirectsDone();
  2615. let didAbortFetchLoads = abortStaleFetchLoads(pendingNavigationLoadId);
  2616. let shouldUpdateFetchers = updatedFetchers || didAbortFetchLoads || revalidatingFetchers.length > 0;
  2617. return {
  2618. matches,
  2619. loaderData,
  2620. errors,
  2621. ...shouldUpdateFetchers ? { fetchers: new Map(state.fetchers) } : {}
  2622. };
  2623. }
  2624. function getUpdatedActionData(pendingActionResult) {
  2625. if (pendingActionResult && !isErrorResult(pendingActionResult[1])) {
  2626. return {
  2627. [pendingActionResult[0]]: pendingActionResult[1].data
  2628. };
  2629. } else if (state.actionData) {
  2630. if (Object.keys(state.actionData).length === 0) {
  2631. return null;
  2632. } else {
  2633. return state.actionData;
  2634. }
  2635. }
  2636. }
  2637. function getUpdatedRevalidatingFetchers(revalidatingFetchers) {
  2638. revalidatingFetchers.forEach((rf) => {
  2639. let fetcher = state.fetchers.get(rf.key);
  2640. let revalidatingFetcher = getLoadingFetcher(
  2641. void 0,
  2642. fetcher ? fetcher.data : void 0
  2643. );
  2644. state.fetchers.set(rf.key, revalidatingFetcher);
  2645. });
  2646. return new Map(state.fetchers);
  2647. }
  2648. async function fetch2(key, routeId, href2, opts) {
  2649. abortFetcher(key);
  2650. let flushSync3 = (opts && opts.flushSync) === true;
  2651. let routesToUse = inFlightDataRoutes || dataRoutes;
  2652. let normalizedPath = normalizeTo(
  2653. state.location,
  2654. state.matches,
  2655. basename,
  2656. href2,
  2657. routeId,
  2658. opts == null ? void 0 : opts.relative
  2659. );
  2660. let matches = matchRoutes(routesToUse, normalizedPath, basename);
  2661. let fogOfWar = checkFogOfWar(matches, routesToUse, normalizedPath);
  2662. if (fogOfWar.active && fogOfWar.matches) {
  2663. matches = fogOfWar.matches;
  2664. }
  2665. if (!matches) {
  2666. setFetcherError(
  2667. key,
  2668. routeId,
  2669. getInternalRouterError(404, { pathname: normalizedPath }),
  2670. { flushSync: flushSync3 }
  2671. );
  2672. return;
  2673. }
  2674. let { path, submission, error } = normalizeNavigateOptions(
  2675. true,
  2676. normalizedPath,
  2677. opts
  2678. );
  2679. if (error) {
  2680. setFetcherError(key, routeId, error, { flushSync: flushSync3 });
  2681. return;
  2682. }
  2683. let scopedContext = init.getContext ? await init.getContext() : new RouterContextProvider();
  2684. let preventScrollReset = (opts && opts.preventScrollReset) === true;
  2685. if (submission && isMutationMethod(submission.formMethod)) {
  2686. await handleFetcherAction(
  2687. key,
  2688. routeId,
  2689. path,
  2690. matches,
  2691. scopedContext,
  2692. fogOfWar.active,
  2693. flushSync3,
  2694. preventScrollReset,
  2695. submission
  2696. );
  2697. return;
  2698. }
  2699. fetchLoadMatches.set(key, { routeId, path });
  2700. await handleFetcherLoader(
  2701. key,
  2702. routeId,
  2703. path,
  2704. matches,
  2705. scopedContext,
  2706. fogOfWar.active,
  2707. flushSync3,
  2708. preventScrollReset,
  2709. submission
  2710. );
  2711. }
  2712. async function handleFetcherAction(key, routeId, path, requestMatches, scopedContext, isFogOfWar, flushSync3, preventScrollReset, submission) {
  2713. interruptActiveLoads();
  2714. fetchLoadMatches.delete(key);
  2715. let existingFetcher = state.fetchers.get(key);
  2716. updateFetcherState(key, getSubmittingFetcher(submission, existingFetcher), {
  2717. flushSync: flushSync3
  2718. });
  2719. let abortController = new AbortController();
  2720. let fetchRequest = createClientSideRequest(
  2721. init.history,
  2722. path,
  2723. abortController.signal,
  2724. submission
  2725. );
  2726. if (isFogOfWar) {
  2727. let discoverResult = await discoverRoutes(
  2728. requestMatches,
  2729. new URL(fetchRequest.url).pathname,
  2730. fetchRequest.signal,
  2731. key
  2732. );
  2733. if (discoverResult.type === "aborted") {
  2734. return;
  2735. } else if (discoverResult.type === "error") {
  2736. setFetcherError(key, routeId, discoverResult.error, { flushSync: flushSync3 });
  2737. return;
  2738. } else if (!discoverResult.matches) {
  2739. setFetcherError(
  2740. key,
  2741. routeId,
  2742. getInternalRouterError(404, { pathname: path }),
  2743. { flushSync: flushSync3 }
  2744. );
  2745. return;
  2746. } else {
  2747. requestMatches = discoverResult.matches;
  2748. }
  2749. }
  2750. let match = getTargetMatch(requestMatches, path);
  2751. if (!match.route.action && !match.route.lazy) {
  2752. let error = getInternalRouterError(405, {
  2753. method: submission.formMethod,
  2754. pathname: path,
  2755. routeId
  2756. });
  2757. setFetcherError(key, routeId, error, { flushSync: flushSync3 });
  2758. return;
  2759. }
  2760. fetchControllers.set(key, abortController);
  2761. let originatingLoadId = incrementingLoadId;
  2762. let fetchMatches = getTargetedDataStrategyMatches(
  2763. mapRouteProperties2,
  2764. manifest,
  2765. fetchRequest,
  2766. requestMatches,
  2767. match,
  2768. hydrationRouteProperties2,
  2769. scopedContext
  2770. );
  2771. let actionResults = await callDataStrategy(
  2772. fetchRequest,
  2773. fetchMatches,
  2774. scopedContext,
  2775. key
  2776. );
  2777. let actionResult = actionResults[match.route.id];
  2778. if (!actionResult) {
  2779. for (let match2 of fetchMatches) {
  2780. if (actionResults[match2.route.id]) {
  2781. actionResult = actionResults[match2.route.id];
  2782. break;
  2783. }
  2784. }
  2785. }
  2786. if (fetchRequest.signal.aborted) {
  2787. if (fetchControllers.get(key) === abortController) {
  2788. fetchControllers.delete(key);
  2789. }
  2790. return;
  2791. }
  2792. if (fetchersQueuedForDeletion.has(key)) {
  2793. if (isRedirectResult(actionResult) || isErrorResult(actionResult)) {
  2794. updateFetcherState(key, getDoneFetcher(void 0));
  2795. return;
  2796. }
  2797. } else {
  2798. if (isRedirectResult(actionResult)) {
  2799. fetchControllers.delete(key);
  2800. if (pendingNavigationLoadId > originatingLoadId) {
  2801. updateFetcherState(key, getDoneFetcher(void 0));
  2802. return;
  2803. } else {
  2804. fetchRedirectIds.add(key);
  2805. updateFetcherState(key, getLoadingFetcher(submission));
  2806. return startRedirectNavigation(fetchRequest, actionResult, false, {
  2807. fetcherSubmission: submission,
  2808. preventScrollReset
  2809. });
  2810. }
  2811. }
  2812. if (isErrorResult(actionResult)) {
  2813. setFetcherError(key, routeId, actionResult.error);
  2814. return;
  2815. }
  2816. }
  2817. let nextLocation = state.navigation.location || state.location;
  2818. let revalidationRequest = createClientSideRequest(
  2819. init.history,
  2820. nextLocation,
  2821. abortController.signal
  2822. );
  2823. let routesToUse = inFlightDataRoutes || dataRoutes;
  2824. let matches = state.navigation.state !== "idle" ? matchRoutes(routesToUse, state.navigation.location, basename) : state.matches;
  2825. invariant(matches, "Didn't find any matches after fetcher action");
  2826. let loadId = ++incrementingLoadId;
  2827. fetchReloadIds.set(key, loadId);
  2828. let loadFetcher = getLoadingFetcher(submission, actionResult.data);
  2829. state.fetchers.set(key, loadFetcher);
  2830. let { dsMatches, revalidatingFetchers } = getMatchesToLoad(
  2831. revalidationRequest,
  2832. scopedContext,
  2833. mapRouteProperties2,
  2834. manifest,
  2835. init.history,
  2836. state,
  2837. matches,
  2838. submission,
  2839. nextLocation,
  2840. hydrationRouteProperties2,
  2841. false,
  2842. isRevalidationRequired,
  2843. cancelledFetcherLoads,
  2844. fetchersQueuedForDeletion,
  2845. fetchLoadMatches,
  2846. fetchRedirectIds,
  2847. routesToUse,
  2848. basename,
  2849. init.patchRoutesOnNavigation != null,
  2850. [match.route.id, actionResult]
  2851. );
  2852. revalidatingFetchers.filter((rf) => rf.key !== key).forEach((rf) => {
  2853. let staleKey = rf.key;
  2854. let existingFetcher2 = state.fetchers.get(staleKey);
  2855. let revalidatingFetcher = getLoadingFetcher(
  2856. void 0,
  2857. existingFetcher2 ? existingFetcher2.data : void 0
  2858. );
  2859. state.fetchers.set(staleKey, revalidatingFetcher);
  2860. abortFetcher(staleKey);
  2861. if (rf.controller) {
  2862. fetchControllers.set(staleKey, rf.controller);
  2863. }
  2864. });
  2865. updateState({ fetchers: new Map(state.fetchers) });
  2866. let abortPendingFetchRevalidations = () => revalidatingFetchers.forEach((rf) => abortFetcher(rf.key));
  2867. abortController.signal.addEventListener(
  2868. "abort",
  2869. abortPendingFetchRevalidations
  2870. );
  2871. let { loaderResults, fetcherResults } = await callLoadersAndMaybeResolveData(
  2872. dsMatches,
  2873. revalidatingFetchers,
  2874. revalidationRequest,
  2875. scopedContext
  2876. );
  2877. if (abortController.signal.aborted) {
  2878. return;
  2879. }
  2880. abortController.signal.removeEventListener(
  2881. "abort",
  2882. abortPendingFetchRevalidations
  2883. );
  2884. fetchReloadIds.delete(key);
  2885. fetchControllers.delete(key);
  2886. revalidatingFetchers.forEach((r) => fetchControllers.delete(r.key));
  2887. if (state.fetchers.has(key)) {
  2888. let doneFetcher = getDoneFetcher(actionResult.data);
  2889. state.fetchers.set(key, doneFetcher);
  2890. }
  2891. let redirect2 = findRedirect(loaderResults);
  2892. if (redirect2) {
  2893. return startRedirectNavigation(
  2894. revalidationRequest,
  2895. redirect2.result,
  2896. false,
  2897. { preventScrollReset }
  2898. );
  2899. }
  2900. redirect2 = findRedirect(fetcherResults);
  2901. if (redirect2) {
  2902. fetchRedirectIds.add(redirect2.key);
  2903. return startRedirectNavigation(
  2904. revalidationRequest,
  2905. redirect2.result,
  2906. false,
  2907. { preventScrollReset }
  2908. );
  2909. }
  2910. let { loaderData, errors } = processLoaderData(
  2911. state,
  2912. matches,
  2913. loaderResults,
  2914. void 0,
  2915. revalidatingFetchers,
  2916. fetcherResults
  2917. );
  2918. abortStaleFetchLoads(loadId);
  2919. if (state.navigation.state === "loading" && loadId > pendingNavigationLoadId) {
  2920. invariant(pendingAction, "Expected pending action");
  2921. pendingNavigationController && pendingNavigationController.abort();
  2922. completeNavigation(state.navigation.location, {
  2923. matches,
  2924. loaderData,
  2925. errors,
  2926. fetchers: new Map(state.fetchers)
  2927. });
  2928. } else {
  2929. updateState({
  2930. errors,
  2931. loaderData: mergeLoaderData(
  2932. state.loaderData,
  2933. loaderData,
  2934. matches,
  2935. errors
  2936. ),
  2937. fetchers: new Map(state.fetchers)
  2938. });
  2939. isRevalidationRequired = false;
  2940. }
  2941. }
  2942. async function handleFetcherLoader(key, routeId, path, matches, scopedContext, isFogOfWar, flushSync3, preventScrollReset, submission) {
  2943. let existingFetcher = state.fetchers.get(key);
  2944. updateFetcherState(
  2945. key,
  2946. getLoadingFetcher(
  2947. submission,
  2948. existingFetcher ? existingFetcher.data : void 0
  2949. ),
  2950. { flushSync: flushSync3 }
  2951. );
  2952. let abortController = new AbortController();
  2953. let fetchRequest = createClientSideRequest(
  2954. init.history,
  2955. path,
  2956. abortController.signal
  2957. );
  2958. if (isFogOfWar) {
  2959. let discoverResult = await discoverRoutes(
  2960. matches,
  2961. new URL(fetchRequest.url).pathname,
  2962. fetchRequest.signal,
  2963. key
  2964. );
  2965. if (discoverResult.type === "aborted") {
  2966. return;
  2967. } else if (discoverResult.type === "error") {
  2968. setFetcherError(key, routeId, discoverResult.error, { flushSync: flushSync3 });
  2969. return;
  2970. } else if (!discoverResult.matches) {
  2971. setFetcherError(
  2972. key,
  2973. routeId,
  2974. getInternalRouterError(404, { pathname: path }),
  2975. { flushSync: flushSync3 }
  2976. );
  2977. return;
  2978. } else {
  2979. matches = discoverResult.matches;
  2980. }
  2981. }
  2982. let match = getTargetMatch(matches, path);
  2983. fetchControllers.set(key, abortController);
  2984. let originatingLoadId = incrementingLoadId;
  2985. let dsMatches = getTargetedDataStrategyMatches(
  2986. mapRouteProperties2,
  2987. manifest,
  2988. fetchRequest,
  2989. matches,
  2990. match,
  2991. hydrationRouteProperties2,
  2992. scopedContext
  2993. );
  2994. let results = await callDataStrategy(
  2995. fetchRequest,
  2996. dsMatches,
  2997. scopedContext,
  2998. key
  2999. );
  3000. let result = results[match.route.id];
  3001. if (fetchControllers.get(key) === abortController) {
  3002. fetchControllers.delete(key);
  3003. }
  3004. if (fetchRequest.signal.aborted) {
  3005. return;
  3006. }
  3007. if (fetchersQueuedForDeletion.has(key)) {
  3008. updateFetcherState(key, getDoneFetcher(void 0));
  3009. return;
  3010. }
  3011. if (isRedirectResult(result)) {
  3012. if (pendingNavigationLoadId > originatingLoadId) {
  3013. updateFetcherState(key, getDoneFetcher(void 0));
  3014. return;
  3015. } else {
  3016. fetchRedirectIds.add(key);
  3017. await startRedirectNavigation(fetchRequest, result, false, {
  3018. preventScrollReset
  3019. });
  3020. return;
  3021. }
  3022. }
  3023. if (isErrorResult(result)) {
  3024. setFetcherError(key, routeId, result.error);
  3025. return;
  3026. }
  3027. updateFetcherState(key, getDoneFetcher(result.data));
  3028. }
  3029. async function startRedirectNavigation(request, redirect2, isNavigation, {
  3030. submission,
  3031. fetcherSubmission,
  3032. preventScrollReset,
  3033. replace: replace2
  3034. } = {}) {
  3035. if (!isNavigation) {
  3036. pendingPopstateNavigationDfd == null ? void 0 : pendingPopstateNavigationDfd.resolve();
  3037. pendingPopstateNavigationDfd = null;
  3038. }
  3039. if (redirect2.response.headers.has("X-Remix-Revalidate")) {
  3040. isRevalidationRequired = true;
  3041. }
  3042. let location2 = redirect2.response.headers.get("Location");
  3043. invariant(location2, "Expected a Location header on the redirect Response");
  3044. location2 = normalizeRedirectLocation(
  3045. location2,
  3046. new URL(request.url),
  3047. basename
  3048. );
  3049. let redirectLocation = createLocation(state.location, location2, {
  3050. _isRedirect: true
  3051. });
  3052. if (isBrowser2) {
  3053. let isDocumentReload = false;
  3054. if (redirect2.response.headers.has("X-Remix-Reload-Document")) {
  3055. isDocumentReload = true;
  3056. } else if (isAbsoluteUrl(location2)) {
  3057. const url = createBrowserURLImpl(location2, true);
  3058. isDocumentReload = // Hard reload if it's an absolute URL to a new origin
  3059. url.origin !== routerWindow.location.origin || // Hard reload if it's an absolute URL that does not match our basename
  3060. stripBasename(url.pathname, basename) == null;
  3061. }
  3062. if (isDocumentReload) {
  3063. if (replace2) {
  3064. routerWindow.location.replace(location2);
  3065. } else {
  3066. routerWindow.location.assign(location2);
  3067. }
  3068. return;
  3069. }
  3070. }
  3071. pendingNavigationController = null;
  3072. let redirectNavigationType = replace2 === true || redirect2.response.headers.has("X-Remix-Replace") ? "REPLACE" : "PUSH";
  3073. let { formMethod, formAction, formEncType } = state.navigation;
  3074. if (!submission && !fetcherSubmission && formMethod && formAction && formEncType) {
  3075. submission = getSubmissionFromNavigation(state.navigation);
  3076. }
  3077. let activeSubmission = submission || fetcherSubmission;
  3078. if (redirectPreserveMethodStatusCodes.has(redirect2.response.status) && activeSubmission && isMutationMethod(activeSubmission.formMethod)) {
  3079. await startNavigation(redirectNavigationType, redirectLocation, {
  3080. submission: {
  3081. ...activeSubmission,
  3082. formAction: location2
  3083. },
  3084. // Preserve these flags across redirects
  3085. preventScrollReset: preventScrollReset || pendingPreventScrollReset,
  3086. enableViewTransition: isNavigation ? pendingViewTransitionEnabled : void 0
  3087. });
  3088. } else {
  3089. let overrideNavigation = getLoadingNavigation(
  3090. redirectLocation,
  3091. submission
  3092. );
  3093. await startNavigation(redirectNavigationType, redirectLocation, {
  3094. overrideNavigation,
  3095. // Send fetcher submissions through for shouldRevalidate
  3096. fetcherSubmission,
  3097. // Preserve these flags across redirects
  3098. preventScrollReset: preventScrollReset || pendingPreventScrollReset,
  3099. enableViewTransition: isNavigation ? pendingViewTransitionEnabled : void 0
  3100. });
  3101. }
  3102. }
  3103. async function callDataStrategy(request, matches, scopedContext, fetcherKey) {
  3104. let results;
  3105. let dataResults = {};
  3106. try {
  3107. results = await callDataStrategyImpl(
  3108. dataStrategyImpl,
  3109. request,
  3110. matches,
  3111. fetcherKey,
  3112. scopedContext,
  3113. false
  3114. );
  3115. } catch (e) {
  3116. matches.filter((m) => m.shouldLoad).forEach((m) => {
  3117. dataResults[m.route.id] = {
  3118. type: "error",
  3119. error: e
  3120. };
  3121. });
  3122. return dataResults;
  3123. }
  3124. if (request.signal.aborted) {
  3125. return dataResults;
  3126. }
  3127. for (let [routeId, result] of Object.entries(results)) {
  3128. if (isRedirectDataStrategyResult(result)) {
  3129. let response = result.result;
  3130. dataResults[routeId] = {
  3131. type: "redirect",
  3132. response: normalizeRelativeRoutingRedirectResponse(
  3133. response,
  3134. request,
  3135. routeId,
  3136. matches,
  3137. basename
  3138. )
  3139. };
  3140. } else {
  3141. dataResults[routeId] = await convertDataStrategyResultToDataResult(result);
  3142. }
  3143. }
  3144. return dataResults;
  3145. }
  3146. async function callLoadersAndMaybeResolveData(matches, fetchersToLoad, request, scopedContext) {
  3147. let loaderResultsPromise = callDataStrategy(
  3148. request,
  3149. matches,
  3150. scopedContext,
  3151. null
  3152. );
  3153. let fetcherResultsPromise = Promise.all(
  3154. fetchersToLoad.map(async (f) => {
  3155. if (f.matches && f.match && f.request && f.controller) {
  3156. let results = await callDataStrategy(
  3157. f.request,
  3158. f.matches,
  3159. scopedContext,
  3160. f.key
  3161. );
  3162. let result = results[f.match.route.id];
  3163. return { [f.key]: result };
  3164. } else {
  3165. return Promise.resolve({
  3166. [f.key]: {
  3167. type: "error",
  3168. error: getInternalRouterError(404, {
  3169. pathname: f.path
  3170. })
  3171. }
  3172. });
  3173. }
  3174. })
  3175. );
  3176. let loaderResults = await loaderResultsPromise;
  3177. let fetcherResults = (await fetcherResultsPromise).reduce(
  3178. (acc, r) => Object.assign(acc, r),
  3179. {}
  3180. );
  3181. return {
  3182. loaderResults,
  3183. fetcherResults
  3184. };
  3185. }
  3186. function interruptActiveLoads() {
  3187. isRevalidationRequired = true;
  3188. fetchLoadMatches.forEach((_, key) => {
  3189. if (fetchControllers.has(key)) {
  3190. cancelledFetcherLoads.add(key);
  3191. }
  3192. abortFetcher(key);
  3193. });
  3194. }
  3195. function updateFetcherState(key, fetcher, opts = {}) {
  3196. state.fetchers.set(key, fetcher);
  3197. updateState(
  3198. { fetchers: new Map(state.fetchers) },
  3199. { flushSync: (opts && opts.flushSync) === true }
  3200. );
  3201. }
  3202. function setFetcherError(key, routeId, error, opts = {}) {
  3203. let boundaryMatch = findNearestBoundary(state.matches, routeId);
  3204. deleteFetcher(key);
  3205. updateState(
  3206. {
  3207. errors: {
  3208. [boundaryMatch.route.id]: error
  3209. },
  3210. fetchers: new Map(state.fetchers)
  3211. },
  3212. { flushSync: (opts && opts.flushSync) === true }
  3213. );
  3214. }
  3215. function getFetcher(key) {
  3216. activeFetchers.set(key, (activeFetchers.get(key) || 0) + 1);
  3217. if (fetchersQueuedForDeletion.has(key)) {
  3218. fetchersQueuedForDeletion.delete(key);
  3219. }
  3220. return state.fetchers.get(key) || IDLE_FETCHER;
  3221. }
  3222. function resetFetcher(key, opts) {
  3223. abortFetcher(key, opts == null ? void 0 : opts.reason);
  3224. updateFetcherState(key, getDoneFetcher(null));
  3225. }
  3226. function deleteFetcher(key) {
  3227. let fetcher = state.fetchers.get(key);
  3228. if (fetchControllers.has(key) && !(fetcher && fetcher.state === "loading" && fetchReloadIds.has(key))) {
  3229. abortFetcher(key);
  3230. }
  3231. fetchLoadMatches.delete(key);
  3232. fetchReloadIds.delete(key);
  3233. fetchRedirectIds.delete(key);
  3234. fetchersQueuedForDeletion.delete(key);
  3235. cancelledFetcherLoads.delete(key);
  3236. state.fetchers.delete(key);
  3237. }
  3238. function queueFetcherForDeletion(key) {
  3239. let count = (activeFetchers.get(key) || 0) - 1;
  3240. if (count <= 0) {
  3241. activeFetchers.delete(key);
  3242. fetchersQueuedForDeletion.add(key);
  3243. } else {
  3244. activeFetchers.set(key, count);
  3245. }
  3246. updateState({ fetchers: new Map(state.fetchers) });
  3247. }
  3248. function abortFetcher(key, reason) {
  3249. let controller = fetchControllers.get(key);
  3250. if (controller) {
  3251. controller.abort(reason);
  3252. fetchControllers.delete(key);
  3253. }
  3254. }
  3255. function markFetchersDone(keys) {
  3256. for (let key of keys) {
  3257. let fetcher = getFetcher(key);
  3258. let doneFetcher = getDoneFetcher(fetcher.data);
  3259. state.fetchers.set(key, doneFetcher);
  3260. }
  3261. }
  3262. function markFetchRedirectsDone() {
  3263. let doneKeys = [];
  3264. let updatedFetchers = false;
  3265. for (let key of fetchRedirectIds) {
  3266. let fetcher = state.fetchers.get(key);
  3267. invariant(fetcher, `Expected fetcher: ${key}`);
  3268. if (fetcher.state === "loading") {
  3269. fetchRedirectIds.delete(key);
  3270. doneKeys.push(key);
  3271. updatedFetchers = true;
  3272. }
  3273. }
  3274. markFetchersDone(doneKeys);
  3275. return updatedFetchers;
  3276. }
  3277. function abortStaleFetchLoads(landedId) {
  3278. let yeetedKeys = [];
  3279. for (let [key, id] of fetchReloadIds) {
  3280. if (id < landedId) {
  3281. let fetcher = state.fetchers.get(key);
  3282. invariant(fetcher, `Expected fetcher: ${key}`);
  3283. if (fetcher.state === "loading") {
  3284. abortFetcher(key);
  3285. fetchReloadIds.delete(key);
  3286. yeetedKeys.push(key);
  3287. }
  3288. }
  3289. }
  3290. markFetchersDone(yeetedKeys);
  3291. return yeetedKeys.length > 0;
  3292. }
  3293. function getBlocker(key, fn) {
  3294. let blocker = state.blockers.get(key) || IDLE_BLOCKER;
  3295. if (blockerFunctions.get(key) !== fn) {
  3296. blockerFunctions.set(key, fn);
  3297. }
  3298. return blocker;
  3299. }
  3300. function deleteBlocker(key) {
  3301. state.blockers.delete(key);
  3302. blockerFunctions.delete(key);
  3303. }
  3304. function updateBlocker(key, newBlocker) {
  3305. let blocker = state.blockers.get(key) || IDLE_BLOCKER;
  3306. invariant(
  3307. 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",
  3308. `Invalid blocker state transition: ${blocker.state} -> ${newBlocker.state}`
  3309. );
  3310. let blockers = new Map(state.blockers);
  3311. blockers.set(key, newBlocker);
  3312. updateState({ blockers });
  3313. }
  3314. function shouldBlockNavigation({
  3315. currentLocation,
  3316. nextLocation,
  3317. historyAction
  3318. }) {
  3319. if (blockerFunctions.size === 0) {
  3320. return;
  3321. }
  3322. if (blockerFunctions.size > 1) {
  3323. warning(false, "A router only supports one blocker at a time");
  3324. }
  3325. let entries = Array.from(blockerFunctions.entries());
  3326. let [blockerKey, blockerFunction] = entries[entries.length - 1];
  3327. let blocker = state.blockers.get(blockerKey);
  3328. if (blocker && blocker.state === "proceeding") {
  3329. return;
  3330. }
  3331. if (blockerFunction({ currentLocation, nextLocation, historyAction })) {
  3332. return blockerKey;
  3333. }
  3334. }
  3335. function handleNavigational404(pathname) {
  3336. let error = getInternalRouterError(404, { pathname });
  3337. let routesToUse = inFlightDataRoutes || dataRoutes;
  3338. let { matches, route } = getShortCircuitMatches(routesToUse);
  3339. return { notFoundMatches: matches, route, error };
  3340. }
  3341. function enableScrollRestoration(positions, getPosition, getKey) {
  3342. savedScrollPositions2 = positions;
  3343. getScrollPosition = getPosition;
  3344. getScrollRestorationKey2 = getKey || null;
  3345. if (!initialScrollRestored && state.navigation === IDLE_NAVIGATION) {
  3346. initialScrollRestored = true;
  3347. let y = getSavedScrollPosition(state.location, state.matches);
  3348. if (y != null) {
  3349. updateState({ restoreScrollPosition: y });
  3350. }
  3351. }
  3352. return () => {
  3353. savedScrollPositions2 = null;
  3354. getScrollPosition = null;
  3355. getScrollRestorationKey2 = null;
  3356. };
  3357. }
  3358. function getScrollKey(location2, matches) {
  3359. if (getScrollRestorationKey2) {
  3360. let key = getScrollRestorationKey2(
  3361. location2,
  3362. matches.map((m) => convertRouteMatchToUiMatch(m, state.loaderData))
  3363. );
  3364. return key || location2.key;
  3365. }
  3366. return location2.key;
  3367. }
  3368. function saveScrollPosition(location2, matches) {
  3369. if (savedScrollPositions2 && getScrollPosition) {
  3370. let key = getScrollKey(location2, matches);
  3371. savedScrollPositions2[key] = getScrollPosition();
  3372. }
  3373. }
  3374. function getSavedScrollPosition(location2, matches) {
  3375. if (savedScrollPositions2) {
  3376. let key = getScrollKey(location2, matches);
  3377. let y = savedScrollPositions2[key];
  3378. if (typeof y === "number") {
  3379. return y;
  3380. }
  3381. }
  3382. return null;
  3383. }
  3384. function checkFogOfWar(matches, routesToUse, pathname) {
  3385. if (init.patchRoutesOnNavigation) {
  3386. if (!matches) {
  3387. let fogMatches = matchRoutesImpl(
  3388. routesToUse,
  3389. pathname,
  3390. basename,
  3391. true
  3392. );
  3393. return { active: true, matches: fogMatches || [] };
  3394. } else {
  3395. if (Object.keys(matches[0].params).length > 0) {
  3396. let partialMatches = matchRoutesImpl(
  3397. routesToUse,
  3398. pathname,
  3399. basename,
  3400. true
  3401. );
  3402. return { active: true, matches: partialMatches };
  3403. }
  3404. }
  3405. }
  3406. return { active: false, matches: null };
  3407. }
  3408. async function discoverRoutes(matches, pathname, signal, fetcherKey) {
  3409. if (!init.patchRoutesOnNavigation) {
  3410. return { type: "success", matches };
  3411. }
  3412. let partialMatches = matches;
  3413. while (true) {
  3414. let isNonHMR = inFlightDataRoutes == null;
  3415. let routesToUse = inFlightDataRoutes || dataRoutes;
  3416. let localManifest = manifest;
  3417. try {
  3418. await init.patchRoutesOnNavigation({
  3419. signal,
  3420. path: pathname,
  3421. matches: partialMatches,
  3422. fetcherKey,
  3423. patch: (routeId, children) => {
  3424. if (signal.aborted) return;
  3425. patchRoutesImpl(
  3426. routeId,
  3427. children,
  3428. routesToUse,
  3429. localManifest,
  3430. mapRouteProperties2,
  3431. false
  3432. );
  3433. }
  3434. });
  3435. } catch (e) {
  3436. return { type: "error", error: e, partialMatches };
  3437. } finally {
  3438. if (isNonHMR && !signal.aborted) {
  3439. dataRoutes = [...dataRoutes];
  3440. }
  3441. }
  3442. if (signal.aborted) {
  3443. return { type: "aborted" };
  3444. }
  3445. let newMatches = matchRoutes(routesToUse, pathname, basename);
  3446. let newPartialMatches = null;
  3447. if (newMatches) {
  3448. if (Object.keys(newMatches[0].params).length === 0) {
  3449. return { type: "success", matches: newMatches };
  3450. } else {
  3451. newPartialMatches = matchRoutesImpl(
  3452. routesToUse,
  3453. pathname,
  3454. basename,
  3455. true
  3456. );
  3457. let matchedDeeper = newPartialMatches && partialMatches.length < newPartialMatches.length && compareMatches(
  3458. partialMatches,
  3459. newPartialMatches.slice(0, partialMatches.length)
  3460. );
  3461. if (!matchedDeeper) {
  3462. return { type: "success", matches: newMatches };
  3463. }
  3464. }
  3465. }
  3466. if (!newPartialMatches) {
  3467. newPartialMatches = matchRoutesImpl(
  3468. routesToUse,
  3469. pathname,
  3470. basename,
  3471. true
  3472. );
  3473. }
  3474. if (!newPartialMatches || compareMatches(partialMatches, newPartialMatches)) {
  3475. return { type: "success", matches: null };
  3476. }
  3477. partialMatches = newPartialMatches;
  3478. }
  3479. }
  3480. function compareMatches(a, b) {
  3481. return a.length === b.length && a.every((m, i) => m.route.id === b[i].route.id);
  3482. }
  3483. function _internalSetRoutes(newRoutes) {
  3484. manifest = {};
  3485. inFlightDataRoutes = convertRoutesToDataRoutes(
  3486. newRoutes,
  3487. mapRouteProperties2,
  3488. void 0,
  3489. manifest
  3490. );
  3491. }
  3492. function patchRoutes(routeId, children, unstable_allowElementMutations = false) {
  3493. let isNonHMR = inFlightDataRoutes == null;
  3494. let routesToUse = inFlightDataRoutes || dataRoutes;
  3495. patchRoutesImpl(
  3496. routeId,
  3497. children,
  3498. routesToUse,
  3499. manifest,
  3500. mapRouteProperties2,
  3501. unstable_allowElementMutations
  3502. );
  3503. if (isNonHMR) {
  3504. dataRoutes = [...dataRoutes];
  3505. updateState({});
  3506. }
  3507. }
  3508. router2 = {
  3509. get basename() {
  3510. return basename;
  3511. },
  3512. get future() {
  3513. return future;
  3514. },
  3515. get state() {
  3516. return state;
  3517. },
  3518. get routes() {
  3519. return dataRoutes;
  3520. },
  3521. get window() {
  3522. return routerWindow;
  3523. },
  3524. initialize,
  3525. subscribe,
  3526. enableScrollRestoration,
  3527. navigate,
  3528. fetch: fetch2,
  3529. revalidate,
  3530. // Passthrough to history-aware createHref used by useHref so we get proper
  3531. // hash-aware URLs in DOM paths
  3532. createHref: (to) => init.history.createHref(to),
  3533. encodeLocation: (to) => init.history.encodeLocation(to),
  3534. getFetcher,
  3535. resetFetcher,
  3536. deleteFetcher: queueFetcherForDeletion,
  3537. dispose,
  3538. getBlocker,
  3539. deleteBlocker,
  3540. patchRoutes,
  3541. _internalFetchControllers: fetchControllers,
  3542. // TODO: Remove setRoutes, it's temporary to avoid dealing with
  3543. // updating the tree while validating the update algorithm.
  3544. _internalSetRoutes,
  3545. _internalSetStateDoNotUseOrYouWillBreakYourApp(newState) {
  3546. updateState(newState);
  3547. }
  3548. };
  3549. if (init.unstable_instrumentations) {
  3550. router2 = instrumentClientSideRouter(
  3551. router2,
  3552. init.unstable_instrumentations.map((i) => i.router).filter(Boolean)
  3553. );
  3554. }
  3555. return router2;
  3556. }
  3557. function createStaticHandler(routes, opts) {
  3558. invariant(
  3559. routes.length > 0,
  3560. "You must provide a non-empty routes array to createStaticHandler"
  3561. );
  3562. let manifest = {};
  3563. let basename = (opts ? opts.basename : null) || "/";
  3564. let _mapRouteProperties = (opts == null ? void 0 : opts.mapRouteProperties) || defaultMapRouteProperties;
  3565. let mapRouteProperties2 = _mapRouteProperties;
  3566. if (opts == null ? void 0 : opts.unstable_instrumentations) {
  3567. let instrumentations = opts.unstable_instrumentations;
  3568. mapRouteProperties2 = (route) => {
  3569. return {
  3570. ..._mapRouteProperties(route),
  3571. ...getRouteInstrumentationUpdates(
  3572. instrumentations.map((i) => i.route).filter(Boolean),
  3573. route
  3574. )
  3575. };
  3576. };
  3577. }
  3578. let dataRoutes = convertRoutesToDataRoutes(
  3579. routes,
  3580. mapRouteProperties2,
  3581. void 0,
  3582. manifest
  3583. );
  3584. async function query(request, {
  3585. requestContext,
  3586. filterMatchesToLoad,
  3587. skipLoaderErrorBubbling,
  3588. skipRevalidation,
  3589. dataStrategy,
  3590. generateMiddlewareResponse
  3591. } = {}) {
  3592. let url = new URL(request.url);
  3593. let method = request.method;
  3594. let location2 = createLocation("", createPath(url), null, "default");
  3595. let matches = matchRoutes(dataRoutes, location2, basename);
  3596. requestContext = requestContext != null ? requestContext : new RouterContextProvider();
  3597. if (!isValidMethod(method) && method !== "HEAD") {
  3598. let error = getInternalRouterError(405, { method });
  3599. let { matches: methodNotAllowedMatches, route } = getShortCircuitMatches(dataRoutes);
  3600. let staticContext = {
  3601. basename,
  3602. location: location2,
  3603. matches: methodNotAllowedMatches,
  3604. loaderData: {},
  3605. actionData: null,
  3606. errors: {
  3607. [route.id]: error
  3608. },
  3609. statusCode: error.status,
  3610. loaderHeaders: {},
  3611. actionHeaders: {}
  3612. };
  3613. return generateMiddlewareResponse ? generateMiddlewareResponse(() => Promise.resolve(staticContext)) : staticContext;
  3614. } else if (!matches) {
  3615. let error = getInternalRouterError(404, { pathname: location2.pathname });
  3616. let { matches: notFoundMatches, route } = getShortCircuitMatches(dataRoutes);
  3617. let staticContext = {
  3618. basename,
  3619. location: location2,
  3620. matches: notFoundMatches,
  3621. loaderData: {},
  3622. actionData: null,
  3623. errors: {
  3624. [route.id]: error
  3625. },
  3626. statusCode: error.status,
  3627. loaderHeaders: {},
  3628. actionHeaders: {}
  3629. };
  3630. return generateMiddlewareResponse ? generateMiddlewareResponse(() => Promise.resolve(staticContext)) : staticContext;
  3631. }
  3632. if (generateMiddlewareResponse) {
  3633. invariant(
  3634. requestContext instanceof RouterContextProvider,
  3635. "When using middleware in `staticHandler.query()`, any provided `requestContext` must be an instance of `RouterContextProvider`"
  3636. );
  3637. try {
  3638. await loadLazyMiddlewareForMatches(
  3639. matches,
  3640. manifest,
  3641. mapRouteProperties2
  3642. );
  3643. let renderedStaticContext;
  3644. let response = await runServerMiddlewarePipeline(
  3645. {
  3646. request,
  3647. unstable_pattern: getRoutePattern(matches),
  3648. matches,
  3649. params: matches[0].params,
  3650. // If we're calling middleware then it must be enabled so we can cast
  3651. // this to the proper type knowing it's not an `AppLoadContext`
  3652. context: requestContext
  3653. },
  3654. async () => {
  3655. let res = await generateMiddlewareResponse(
  3656. async (revalidationRequest, opts2 = {}) => {
  3657. let result2 = await queryImpl(
  3658. revalidationRequest,
  3659. location2,
  3660. matches,
  3661. requestContext,
  3662. dataStrategy || null,
  3663. skipLoaderErrorBubbling === true,
  3664. null,
  3665. "filterMatchesToLoad" in opts2 ? opts2.filterMatchesToLoad ?? null : filterMatchesToLoad ?? null,
  3666. skipRevalidation === true
  3667. );
  3668. if (isResponse(result2)) {
  3669. return result2;
  3670. }
  3671. renderedStaticContext = { location: location2, basename, ...result2 };
  3672. return renderedStaticContext;
  3673. }
  3674. );
  3675. return res;
  3676. },
  3677. async (error, routeId) => {
  3678. var _a;
  3679. if (isRedirectResponse(error)) {
  3680. return error;
  3681. }
  3682. if (isResponse(error)) {
  3683. try {
  3684. error = new ErrorResponseImpl(
  3685. error.status,
  3686. error.statusText,
  3687. await parseResponseBody(error)
  3688. );
  3689. } catch (e) {
  3690. error = e;
  3691. }
  3692. }
  3693. if (isDataWithResponseInit(error)) {
  3694. error = dataWithResponseInitToErrorResponse(error);
  3695. }
  3696. if (renderedStaticContext) {
  3697. if (routeId in renderedStaticContext.loaderData) {
  3698. renderedStaticContext.loaderData[routeId] = void 0;
  3699. }
  3700. let staticContext = getStaticContextFromError(
  3701. dataRoutes,
  3702. renderedStaticContext,
  3703. error,
  3704. skipLoaderErrorBubbling ? routeId : findNearestBoundary(matches, routeId).route.id
  3705. );
  3706. return generateMiddlewareResponse(
  3707. () => Promise.resolve(staticContext)
  3708. );
  3709. } else {
  3710. let boundaryRouteId = skipLoaderErrorBubbling ? routeId : findNearestBoundary(
  3711. matches,
  3712. ((_a = matches.find(
  3713. (m) => m.route.id === routeId || m.route.loader
  3714. )) == null ? void 0 : _a.route.id) || routeId
  3715. ).route.id;
  3716. let staticContext = {
  3717. matches,
  3718. location: location2,
  3719. basename,
  3720. loaderData: {},
  3721. actionData: null,
  3722. errors: {
  3723. [boundaryRouteId]: error
  3724. },
  3725. statusCode: isRouteErrorResponse(error) ? error.status : 500,
  3726. actionHeaders: {},
  3727. loaderHeaders: {}
  3728. };
  3729. return generateMiddlewareResponse(
  3730. () => Promise.resolve(staticContext)
  3731. );
  3732. }
  3733. }
  3734. );
  3735. invariant(isResponse(response), "Expected a response in query()");
  3736. return response;
  3737. } catch (e) {
  3738. if (isResponse(e)) {
  3739. return e;
  3740. }
  3741. throw e;
  3742. }
  3743. }
  3744. let result = await queryImpl(
  3745. request,
  3746. location2,
  3747. matches,
  3748. requestContext,
  3749. dataStrategy || null,
  3750. skipLoaderErrorBubbling === true,
  3751. null,
  3752. filterMatchesToLoad || null,
  3753. skipRevalidation === true
  3754. );
  3755. if (isResponse(result)) {
  3756. return result;
  3757. }
  3758. return { location: location2, basename, ...result };
  3759. }
  3760. async function queryRoute(request, {
  3761. routeId,
  3762. requestContext,
  3763. dataStrategy,
  3764. generateMiddlewareResponse
  3765. } = {}) {
  3766. let url = new URL(request.url);
  3767. let method = request.method;
  3768. let location2 = createLocation("", createPath(url), null, "default");
  3769. let matches = matchRoutes(dataRoutes, location2, basename);
  3770. requestContext = requestContext != null ? requestContext : new RouterContextProvider();
  3771. if (!isValidMethod(method) && method !== "HEAD" && method !== "OPTIONS") {
  3772. throw getInternalRouterError(405, { method });
  3773. } else if (!matches) {
  3774. throw getInternalRouterError(404, { pathname: location2.pathname });
  3775. }
  3776. let match = routeId ? matches.find((m) => m.route.id === routeId) : getTargetMatch(matches, location2);
  3777. if (routeId && !match) {
  3778. throw getInternalRouterError(403, {
  3779. pathname: location2.pathname,
  3780. routeId
  3781. });
  3782. } else if (!match) {
  3783. throw getInternalRouterError(404, { pathname: location2.pathname });
  3784. }
  3785. if (generateMiddlewareResponse) {
  3786. invariant(
  3787. requestContext instanceof RouterContextProvider,
  3788. "When using middleware in `staticHandler.queryRoute()`, any provided `requestContext` must be an instance of `RouterContextProvider`"
  3789. );
  3790. await loadLazyMiddlewareForMatches(matches, manifest, mapRouteProperties2);
  3791. let response = await runServerMiddlewarePipeline(
  3792. {
  3793. request,
  3794. unstable_pattern: getRoutePattern(matches),
  3795. matches,
  3796. params: matches[0].params,
  3797. // If we're calling middleware then it must be enabled so we can cast
  3798. // this to the proper type knowing it's not an `AppLoadContext`
  3799. context: requestContext
  3800. },
  3801. async () => {
  3802. let res = await generateMiddlewareResponse(
  3803. async (innerRequest) => {
  3804. let result2 = await queryImpl(
  3805. innerRequest,
  3806. location2,
  3807. matches,
  3808. requestContext,
  3809. dataStrategy || null,
  3810. false,
  3811. match,
  3812. null,
  3813. false
  3814. );
  3815. let processed = handleQueryResult(result2);
  3816. return isResponse(processed) ? processed : typeof processed === "string" ? new Response(processed) : Response.json(processed);
  3817. }
  3818. );
  3819. return res;
  3820. },
  3821. (error) => {
  3822. if (isDataWithResponseInit(error)) {
  3823. return Promise.resolve(dataWithResponseInitToResponse(error));
  3824. }
  3825. if (isResponse(error)) {
  3826. return Promise.resolve(error);
  3827. }
  3828. throw error;
  3829. }
  3830. );
  3831. return response;
  3832. }
  3833. let result = await queryImpl(
  3834. request,
  3835. location2,
  3836. matches,
  3837. requestContext,
  3838. dataStrategy || null,
  3839. false,
  3840. match,
  3841. null,
  3842. false
  3843. );
  3844. return handleQueryResult(result);
  3845. function handleQueryResult(result2) {
  3846. if (isResponse(result2)) {
  3847. return result2;
  3848. }
  3849. let error = result2.errors ? Object.values(result2.errors)[0] : void 0;
  3850. if (error !== void 0) {
  3851. throw error;
  3852. }
  3853. if (result2.actionData) {
  3854. return Object.values(result2.actionData)[0];
  3855. }
  3856. if (result2.loaderData) {
  3857. return Object.values(result2.loaderData)[0];
  3858. }
  3859. return void 0;
  3860. }
  3861. }
  3862. async function queryImpl(request, location2, matches, requestContext, dataStrategy, skipLoaderErrorBubbling, routeMatch, filterMatchesToLoad, skipRevalidation) {
  3863. invariant(
  3864. request.signal,
  3865. "query()/queryRoute() requests must contain an AbortController signal"
  3866. );
  3867. try {
  3868. if (isMutationMethod(request.method)) {
  3869. let result2 = await submit(
  3870. request,
  3871. matches,
  3872. routeMatch || getTargetMatch(matches, location2),
  3873. requestContext,
  3874. dataStrategy,
  3875. skipLoaderErrorBubbling,
  3876. routeMatch != null,
  3877. filterMatchesToLoad,
  3878. skipRevalidation
  3879. );
  3880. return result2;
  3881. }
  3882. let result = await loadRouteData(
  3883. request,
  3884. matches,
  3885. requestContext,
  3886. dataStrategy,
  3887. skipLoaderErrorBubbling,
  3888. routeMatch,
  3889. filterMatchesToLoad
  3890. );
  3891. return isResponse(result) ? result : {
  3892. ...result,
  3893. actionData: null,
  3894. actionHeaders: {}
  3895. };
  3896. } catch (e) {
  3897. if (isDataStrategyResult(e) && isResponse(e.result)) {
  3898. if (e.type === "error") {
  3899. throw e.result;
  3900. }
  3901. return e.result;
  3902. }
  3903. if (isRedirectResponse(e)) {
  3904. return e;
  3905. }
  3906. throw e;
  3907. }
  3908. }
  3909. async function submit(request, matches, actionMatch, requestContext, dataStrategy, skipLoaderErrorBubbling, isRouteRequest, filterMatchesToLoad, skipRevalidation) {
  3910. let result;
  3911. if (!actionMatch.route.action && !actionMatch.route.lazy) {
  3912. let error = getInternalRouterError(405, {
  3913. method: request.method,
  3914. pathname: new URL(request.url).pathname,
  3915. routeId: actionMatch.route.id
  3916. });
  3917. if (isRouteRequest) {
  3918. throw error;
  3919. }
  3920. result = {
  3921. type: "error",
  3922. error
  3923. };
  3924. } else {
  3925. let dsMatches = getTargetedDataStrategyMatches(
  3926. mapRouteProperties2,
  3927. manifest,
  3928. request,
  3929. matches,
  3930. actionMatch,
  3931. [],
  3932. requestContext
  3933. );
  3934. let results = await callDataStrategy(
  3935. request,
  3936. dsMatches,
  3937. isRouteRequest,
  3938. requestContext,
  3939. dataStrategy
  3940. );
  3941. result = results[actionMatch.route.id];
  3942. if (request.signal.aborted) {
  3943. throwStaticHandlerAbortedError(request, isRouteRequest);
  3944. }
  3945. }
  3946. if (isRedirectResult(result)) {
  3947. throw new Response(null, {
  3948. status: result.response.status,
  3949. headers: {
  3950. Location: result.response.headers.get("Location")
  3951. }
  3952. });
  3953. }
  3954. if (isRouteRequest) {
  3955. if (isErrorResult(result)) {
  3956. throw result.error;
  3957. }
  3958. return {
  3959. matches: [actionMatch],
  3960. loaderData: {},
  3961. actionData: { [actionMatch.route.id]: result.data },
  3962. errors: null,
  3963. // Note: statusCode + headers are unused here since queryRoute will
  3964. // return the raw Response or value
  3965. statusCode: 200,
  3966. loaderHeaders: {},
  3967. actionHeaders: {}
  3968. };
  3969. }
  3970. if (skipRevalidation) {
  3971. if (isErrorResult(result)) {
  3972. let boundaryMatch = skipLoaderErrorBubbling ? actionMatch : findNearestBoundary(matches, actionMatch.route.id);
  3973. return {
  3974. statusCode: isRouteErrorResponse(result.error) ? result.error.status : result.statusCode != null ? result.statusCode : 500,
  3975. actionData: null,
  3976. actionHeaders: {
  3977. ...result.headers ? { [actionMatch.route.id]: result.headers } : {}
  3978. },
  3979. matches,
  3980. loaderData: {},
  3981. errors: {
  3982. [boundaryMatch.route.id]: result.error
  3983. },
  3984. loaderHeaders: {}
  3985. };
  3986. } else {
  3987. return {
  3988. actionData: {
  3989. [actionMatch.route.id]: result.data
  3990. },
  3991. actionHeaders: result.headers ? { [actionMatch.route.id]: result.headers } : {},
  3992. matches,
  3993. loaderData: {},
  3994. errors: null,
  3995. statusCode: result.statusCode || 200,
  3996. loaderHeaders: {}
  3997. };
  3998. }
  3999. }
  4000. let loaderRequest = new Request(request.url, {
  4001. headers: request.headers,
  4002. redirect: request.redirect,
  4003. signal: request.signal
  4004. });
  4005. if (isErrorResult(result)) {
  4006. let boundaryMatch = skipLoaderErrorBubbling ? actionMatch : findNearestBoundary(matches, actionMatch.route.id);
  4007. let handlerContext2 = await loadRouteData(
  4008. loaderRequest,
  4009. matches,
  4010. requestContext,
  4011. dataStrategy,
  4012. skipLoaderErrorBubbling,
  4013. null,
  4014. filterMatchesToLoad,
  4015. [boundaryMatch.route.id, result]
  4016. );
  4017. return {
  4018. ...handlerContext2,
  4019. statusCode: isRouteErrorResponse(result.error) ? result.error.status : result.statusCode != null ? result.statusCode : 500,
  4020. actionData: null,
  4021. actionHeaders: {
  4022. ...result.headers ? { [actionMatch.route.id]: result.headers } : {}
  4023. }
  4024. };
  4025. }
  4026. let handlerContext = await loadRouteData(
  4027. loaderRequest,
  4028. matches,
  4029. requestContext,
  4030. dataStrategy,
  4031. skipLoaderErrorBubbling,
  4032. null,
  4033. filterMatchesToLoad
  4034. );
  4035. return {
  4036. ...handlerContext,
  4037. actionData: {
  4038. [actionMatch.route.id]: result.data
  4039. },
  4040. // action status codes take precedence over loader status codes
  4041. ...result.statusCode ? { statusCode: result.statusCode } : {},
  4042. actionHeaders: result.headers ? { [actionMatch.route.id]: result.headers } : {}
  4043. };
  4044. }
  4045. async function loadRouteData(request, matches, requestContext, dataStrategy, skipLoaderErrorBubbling, routeMatch, filterMatchesToLoad, pendingActionResult) {
  4046. let isRouteRequest = routeMatch != null;
  4047. if (isRouteRequest && !(routeMatch == null ? void 0 : routeMatch.route.loader) && !(routeMatch == null ? void 0 : routeMatch.route.lazy)) {
  4048. throw getInternalRouterError(400, {
  4049. method: request.method,
  4050. pathname: new URL(request.url).pathname,
  4051. routeId: routeMatch == null ? void 0 : routeMatch.route.id
  4052. });
  4053. }
  4054. let dsMatches;
  4055. if (routeMatch) {
  4056. dsMatches = getTargetedDataStrategyMatches(
  4057. mapRouteProperties2,
  4058. manifest,
  4059. request,
  4060. matches,
  4061. routeMatch,
  4062. [],
  4063. requestContext
  4064. );
  4065. } else {
  4066. let maxIdx = pendingActionResult && isErrorResult(pendingActionResult[1]) ? (
  4067. // Up to but not including the boundary
  4068. matches.findIndex((m) => m.route.id === pendingActionResult[0]) - 1
  4069. ) : void 0;
  4070. let pattern = getRoutePattern(matches);
  4071. dsMatches = matches.map((match, index) => {
  4072. if (maxIdx != null && index > maxIdx) {
  4073. return getDataStrategyMatch(
  4074. mapRouteProperties2,
  4075. manifest,
  4076. request,
  4077. pattern,
  4078. match,
  4079. [],
  4080. requestContext,
  4081. false
  4082. );
  4083. }
  4084. return getDataStrategyMatch(
  4085. mapRouteProperties2,
  4086. manifest,
  4087. request,
  4088. pattern,
  4089. match,
  4090. [],
  4091. requestContext,
  4092. (match.route.loader || match.route.lazy) != null && (!filterMatchesToLoad || filterMatchesToLoad(match))
  4093. );
  4094. });
  4095. }
  4096. if (!dataStrategy && !dsMatches.some((m) => m.shouldLoad)) {
  4097. return {
  4098. matches,
  4099. loaderData: {},
  4100. errors: pendingActionResult && isErrorResult(pendingActionResult[1]) ? {
  4101. [pendingActionResult[0]]: pendingActionResult[1].error
  4102. } : null,
  4103. statusCode: 200,
  4104. loaderHeaders: {}
  4105. };
  4106. }
  4107. let results = await callDataStrategy(
  4108. request,
  4109. dsMatches,
  4110. isRouteRequest,
  4111. requestContext,
  4112. dataStrategy
  4113. );
  4114. if (request.signal.aborted) {
  4115. throwStaticHandlerAbortedError(request, isRouteRequest);
  4116. }
  4117. let handlerContext = processRouteLoaderData(
  4118. matches,
  4119. results,
  4120. pendingActionResult,
  4121. true,
  4122. skipLoaderErrorBubbling
  4123. );
  4124. return {
  4125. ...handlerContext,
  4126. matches
  4127. };
  4128. }
  4129. async function callDataStrategy(request, matches, isRouteRequest, requestContext, dataStrategy) {
  4130. let results = await callDataStrategyImpl(
  4131. dataStrategy || defaultDataStrategy,
  4132. request,
  4133. matches,
  4134. null,
  4135. requestContext,
  4136. true
  4137. );
  4138. let dataResults = {};
  4139. await Promise.all(
  4140. matches.map(async (match) => {
  4141. if (!(match.route.id in results)) {
  4142. return;
  4143. }
  4144. let result = results[match.route.id];
  4145. if (isRedirectDataStrategyResult(result)) {
  4146. let response = result.result;
  4147. throw normalizeRelativeRoutingRedirectResponse(
  4148. response,
  4149. request,
  4150. match.route.id,
  4151. matches,
  4152. basename
  4153. );
  4154. }
  4155. if (isRouteRequest) {
  4156. if (isResponse(result.result)) {
  4157. throw result;
  4158. } else if (isDataWithResponseInit(result.result)) {
  4159. throw dataWithResponseInitToResponse(result.result);
  4160. }
  4161. }
  4162. dataResults[match.route.id] = await convertDataStrategyResultToDataResult(result);
  4163. })
  4164. );
  4165. return dataResults;
  4166. }
  4167. return {
  4168. dataRoutes,
  4169. query,
  4170. queryRoute
  4171. };
  4172. }
  4173. function getStaticContextFromError(routes, handlerContext, error, boundaryId) {
  4174. let errorBoundaryId = boundaryId || handlerContext._deepestRenderedBoundaryId || routes[0].id;
  4175. return {
  4176. ...handlerContext,
  4177. statusCode: isRouteErrorResponse(error) ? error.status : 500,
  4178. errors: {
  4179. [errorBoundaryId]: error
  4180. }
  4181. };
  4182. }
  4183. function throwStaticHandlerAbortedError(request, isRouteRequest) {
  4184. if (request.signal.reason !== void 0) {
  4185. throw request.signal.reason;
  4186. }
  4187. let method = isRouteRequest ? "queryRoute" : "query";
  4188. throw new Error(
  4189. `${method}() call aborted without an \`AbortSignal.reason\`: ${request.method} ${request.url}`
  4190. );
  4191. }
  4192. function isSubmissionNavigation(opts) {
  4193. return opts != null && ("formData" in opts && opts.formData != null || "body" in opts && opts.body !== void 0);
  4194. }
  4195. function normalizeTo(location2, matches, basename, to, fromRouteId, relative) {
  4196. let contextualMatches;
  4197. let activeRouteMatch;
  4198. if (fromRouteId) {
  4199. contextualMatches = [];
  4200. for (let match of matches) {
  4201. contextualMatches.push(match);
  4202. if (match.route.id === fromRouteId) {
  4203. activeRouteMatch = match;
  4204. break;
  4205. }
  4206. }
  4207. } else {
  4208. contextualMatches = matches;
  4209. activeRouteMatch = matches[matches.length - 1];
  4210. }
  4211. let path = resolveTo(
  4212. to ? to : ".",
  4213. getResolveToMatches(contextualMatches),
  4214. stripBasename(location2.pathname, basename) || location2.pathname,
  4215. relative === "path"
  4216. );
  4217. if (to == null) {
  4218. path.search = location2.search;
  4219. path.hash = location2.hash;
  4220. }
  4221. if ((to == null || to === "" || to === ".") && activeRouteMatch) {
  4222. let nakedIndex = hasNakedIndexQuery(path.search);
  4223. if (activeRouteMatch.route.index && !nakedIndex) {
  4224. path.search = path.search ? path.search.replace(/^\?/, "?index&") : "?index";
  4225. } else if (!activeRouteMatch.route.index && nakedIndex) {
  4226. let params = new URLSearchParams(path.search);
  4227. let indexValues = params.getAll("index");
  4228. params.delete("index");
  4229. indexValues.filter((v) => v).forEach((v) => params.append("index", v));
  4230. let qs = params.toString();
  4231. path.search = qs ? `?${qs}` : "";
  4232. }
  4233. }
  4234. if (basename !== "/") {
  4235. path.pathname = prependBasename({ basename, pathname: path.pathname });
  4236. }
  4237. return createPath(path);
  4238. }
  4239. function normalizeNavigateOptions(isFetcher, path, opts) {
  4240. if (!opts || !isSubmissionNavigation(opts)) {
  4241. return { path };
  4242. }
  4243. if (opts.formMethod && !isValidMethod(opts.formMethod)) {
  4244. return {
  4245. path,
  4246. error: getInternalRouterError(405, { method: opts.formMethod })
  4247. };
  4248. }
  4249. let getInvalidBodyError = () => ({
  4250. path,
  4251. error: getInternalRouterError(400, { type: "invalid-body" })
  4252. });
  4253. let rawFormMethod = opts.formMethod || "get";
  4254. let formMethod = rawFormMethod.toUpperCase();
  4255. let formAction = stripHashFromPath(path);
  4256. if (opts.body !== void 0) {
  4257. if (opts.formEncType === "text/plain") {
  4258. if (!isMutationMethod(formMethod)) {
  4259. return getInvalidBodyError();
  4260. }
  4261. let text = typeof opts.body === "string" ? opts.body : opts.body instanceof FormData || opts.body instanceof URLSearchParams ? (
  4262. // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#plain-text-form-data
  4263. Array.from(opts.body.entries()).reduce(
  4264. (acc, [name, value]) => `${acc}${name}=${value}
  4265. `,
  4266. ""
  4267. )
  4268. ) : String(opts.body);
  4269. return {
  4270. path,
  4271. submission: {
  4272. formMethod,
  4273. formAction,
  4274. formEncType: opts.formEncType,
  4275. formData: void 0,
  4276. json: void 0,
  4277. text
  4278. }
  4279. };
  4280. } else if (opts.formEncType === "application/json") {
  4281. if (!isMutationMethod(formMethod)) {
  4282. return getInvalidBodyError();
  4283. }
  4284. try {
  4285. let json = typeof opts.body === "string" ? JSON.parse(opts.body) : opts.body;
  4286. return {
  4287. path,
  4288. submission: {
  4289. formMethod,
  4290. formAction,
  4291. formEncType: opts.formEncType,
  4292. formData: void 0,
  4293. json,
  4294. text: void 0
  4295. }
  4296. };
  4297. } catch (e) {
  4298. return getInvalidBodyError();
  4299. }
  4300. }
  4301. }
  4302. invariant(
  4303. typeof FormData === "function",
  4304. "FormData is not available in this environment"
  4305. );
  4306. let searchParams;
  4307. let formData;
  4308. if (opts.formData) {
  4309. searchParams = convertFormDataToSearchParams(opts.formData);
  4310. formData = opts.formData;
  4311. } else if (opts.body instanceof FormData) {
  4312. searchParams = convertFormDataToSearchParams(opts.body);
  4313. formData = opts.body;
  4314. } else if (opts.body instanceof URLSearchParams) {
  4315. searchParams = opts.body;
  4316. formData = convertSearchParamsToFormData(searchParams);
  4317. } else if (opts.body == null) {
  4318. searchParams = new URLSearchParams();
  4319. formData = new FormData();
  4320. } else {
  4321. try {
  4322. searchParams = new URLSearchParams(opts.body);
  4323. formData = convertSearchParamsToFormData(searchParams);
  4324. } catch (e) {
  4325. return getInvalidBodyError();
  4326. }
  4327. }
  4328. let submission = {
  4329. formMethod,
  4330. formAction,
  4331. formEncType: opts && opts.formEncType || "application/x-www-form-urlencoded",
  4332. formData,
  4333. json: void 0,
  4334. text: void 0
  4335. };
  4336. if (isMutationMethod(submission.formMethod)) {
  4337. return { path, submission };
  4338. }
  4339. let parsedPath = parsePath(path);
  4340. if (isFetcher && parsedPath.search && hasNakedIndexQuery(parsedPath.search)) {
  4341. searchParams.append("index", "");
  4342. }
  4343. parsedPath.search = `?${searchParams}`;
  4344. return { path: createPath(parsedPath), submission };
  4345. }
  4346. function getMatchesToLoad(request, scopedContext, mapRouteProperties2, manifest, history, state, matches, submission, location2, lazyRoutePropertiesToSkip, initialHydration, isRevalidationRequired, cancelledFetcherLoads, fetchersQueuedForDeletion, fetchLoadMatches, fetchRedirectIds, routesToUse, basename, hasPatchRoutesOnNavigation, pendingActionResult) {
  4347. var _a;
  4348. let actionResult = pendingActionResult ? isErrorResult(pendingActionResult[1]) ? pendingActionResult[1].error : pendingActionResult[1].data : void 0;
  4349. let currentUrl = history.createURL(state.location);
  4350. let nextUrl = history.createURL(location2);
  4351. let maxIdx;
  4352. if (initialHydration && state.errors) {
  4353. let boundaryId = Object.keys(state.errors)[0];
  4354. maxIdx = matches.findIndex((m) => m.route.id === boundaryId);
  4355. } else if (pendingActionResult && isErrorResult(pendingActionResult[1])) {
  4356. let boundaryId = pendingActionResult[0];
  4357. maxIdx = matches.findIndex((m) => m.route.id === boundaryId) - 1;
  4358. }
  4359. let actionStatus = pendingActionResult ? pendingActionResult[1].statusCode : void 0;
  4360. let shouldSkipRevalidation = actionStatus && actionStatus >= 400;
  4361. let baseShouldRevalidateArgs = {
  4362. currentUrl,
  4363. currentParams: ((_a = state.matches[0]) == null ? void 0 : _a.params) || {},
  4364. nextUrl,
  4365. nextParams: matches[0].params,
  4366. ...submission,
  4367. actionResult,
  4368. actionStatus
  4369. };
  4370. let pattern = getRoutePattern(matches);
  4371. let dsMatches = matches.map((match, index) => {
  4372. let { route } = match;
  4373. let forceShouldLoad = null;
  4374. if (maxIdx != null && index > maxIdx) {
  4375. forceShouldLoad = false;
  4376. } else if (route.lazy) {
  4377. forceShouldLoad = true;
  4378. } else if (!routeHasLoaderOrMiddleware(route)) {
  4379. forceShouldLoad = false;
  4380. } else if (initialHydration) {
  4381. forceShouldLoad = shouldLoadRouteOnHydration(
  4382. route,
  4383. state.loaderData,
  4384. state.errors
  4385. );
  4386. } else if (isNewLoader(state.loaderData, state.matches[index], match)) {
  4387. forceShouldLoad = true;
  4388. }
  4389. if (forceShouldLoad !== null) {
  4390. return getDataStrategyMatch(
  4391. mapRouteProperties2,
  4392. manifest,
  4393. request,
  4394. pattern,
  4395. match,
  4396. lazyRoutePropertiesToSkip,
  4397. scopedContext,
  4398. forceShouldLoad
  4399. );
  4400. }
  4401. let defaultShouldRevalidate = shouldSkipRevalidation ? false : (
  4402. // Forced revalidation due to submission, useRevalidator, or X-Remix-Revalidate
  4403. isRevalidationRequired || currentUrl.pathname + currentUrl.search === nextUrl.pathname + nextUrl.search || // Search params affect all loaders
  4404. currentUrl.search !== nextUrl.search || isNewRouteInstance(state.matches[index], match)
  4405. );
  4406. let shouldRevalidateArgs = {
  4407. ...baseShouldRevalidateArgs,
  4408. defaultShouldRevalidate
  4409. };
  4410. let shouldLoad = shouldRevalidateLoader(match, shouldRevalidateArgs);
  4411. return getDataStrategyMatch(
  4412. mapRouteProperties2,
  4413. manifest,
  4414. request,
  4415. pattern,
  4416. match,
  4417. lazyRoutePropertiesToSkip,
  4418. scopedContext,
  4419. shouldLoad,
  4420. shouldRevalidateArgs
  4421. );
  4422. });
  4423. let revalidatingFetchers = [];
  4424. fetchLoadMatches.forEach((f, key) => {
  4425. if (initialHydration || !matches.some((m) => m.route.id === f.routeId) || fetchersQueuedForDeletion.has(key)) {
  4426. return;
  4427. }
  4428. let fetcher = state.fetchers.get(key);
  4429. let isMidInitialLoad = fetcher && fetcher.state !== "idle" && fetcher.data === void 0;
  4430. let fetcherMatches = matchRoutes(routesToUse, f.path, basename);
  4431. if (!fetcherMatches) {
  4432. if (hasPatchRoutesOnNavigation && isMidInitialLoad) {
  4433. return;
  4434. }
  4435. revalidatingFetchers.push({
  4436. key,
  4437. routeId: f.routeId,
  4438. path: f.path,
  4439. matches: null,
  4440. match: null,
  4441. request: null,
  4442. controller: null
  4443. });
  4444. return;
  4445. }
  4446. if (fetchRedirectIds.has(key)) {
  4447. return;
  4448. }
  4449. let fetcherMatch = getTargetMatch(fetcherMatches, f.path);
  4450. let fetchController = new AbortController();
  4451. let fetchRequest = createClientSideRequest(
  4452. history,
  4453. f.path,
  4454. fetchController.signal
  4455. );
  4456. let fetcherDsMatches = null;
  4457. if (cancelledFetcherLoads.has(key)) {
  4458. cancelledFetcherLoads.delete(key);
  4459. fetcherDsMatches = getTargetedDataStrategyMatches(
  4460. mapRouteProperties2,
  4461. manifest,
  4462. fetchRequest,
  4463. fetcherMatches,
  4464. fetcherMatch,
  4465. lazyRoutePropertiesToSkip,
  4466. scopedContext
  4467. );
  4468. } else if (isMidInitialLoad) {
  4469. if (isRevalidationRequired) {
  4470. fetcherDsMatches = getTargetedDataStrategyMatches(
  4471. mapRouteProperties2,
  4472. manifest,
  4473. fetchRequest,
  4474. fetcherMatches,
  4475. fetcherMatch,
  4476. lazyRoutePropertiesToSkip,
  4477. scopedContext
  4478. );
  4479. }
  4480. } else {
  4481. let shouldRevalidateArgs = {
  4482. ...baseShouldRevalidateArgs,
  4483. defaultShouldRevalidate: shouldSkipRevalidation ? false : isRevalidationRequired
  4484. };
  4485. if (shouldRevalidateLoader(fetcherMatch, shouldRevalidateArgs)) {
  4486. fetcherDsMatches = getTargetedDataStrategyMatches(
  4487. mapRouteProperties2,
  4488. manifest,
  4489. fetchRequest,
  4490. fetcherMatches,
  4491. fetcherMatch,
  4492. lazyRoutePropertiesToSkip,
  4493. scopedContext,
  4494. shouldRevalidateArgs
  4495. );
  4496. }
  4497. }
  4498. if (fetcherDsMatches) {
  4499. revalidatingFetchers.push({
  4500. key,
  4501. routeId: f.routeId,
  4502. path: f.path,
  4503. matches: fetcherDsMatches,
  4504. match: fetcherMatch,
  4505. request: fetchRequest,
  4506. controller: fetchController
  4507. });
  4508. }
  4509. });
  4510. return { dsMatches, revalidatingFetchers };
  4511. }
  4512. function routeHasLoaderOrMiddleware(route) {
  4513. return route.loader != null || route.middleware != null && route.middleware.length > 0;
  4514. }
  4515. function shouldLoadRouteOnHydration(route, loaderData, errors) {
  4516. if (route.lazy) {
  4517. return true;
  4518. }
  4519. if (!routeHasLoaderOrMiddleware(route)) {
  4520. return false;
  4521. }
  4522. let hasData = loaderData != null && route.id in loaderData;
  4523. let hasError = errors != null && errors[route.id] !== void 0;
  4524. if (!hasData && hasError) {
  4525. return false;
  4526. }
  4527. if (typeof route.loader === "function" && route.loader.hydrate === true) {
  4528. return true;
  4529. }
  4530. return !hasData && !hasError;
  4531. }
  4532. function isNewLoader(currentLoaderData, currentMatch, match) {
  4533. let isNew = (
  4534. // [a] -> [a, b]
  4535. !currentMatch || // [a, b] -> [a, c]
  4536. match.route.id !== currentMatch.route.id
  4537. );
  4538. let isMissingData = !currentLoaderData.hasOwnProperty(match.route.id);
  4539. return isNew || isMissingData;
  4540. }
  4541. function isNewRouteInstance(currentMatch, match) {
  4542. let currentPath = currentMatch.route.path;
  4543. return (
  4544. // param change for this match, /users/123 -> /users/456
  4545. currentMatch.pathname !== match.pathname || // splat param changed, which is not present in match.path
  4546. // e.g. /files/images/avatar.jpg -> files/finances.xls
  4547. currentPath != null && currentPath.endsWith("*") && currentMatch.params["*"] !== match.params["*"]
  4548. );
  4549. }
  4550. function shouldRevalidateLoader(loaderMatch, arg) {
  4551. if (loaderMatch.route.shouldRevalidate) {
  4552. let routeChoice = loaderMatch.route.shouldRevalidate(arg);
  4553. if (typeof routeChoice === "boolean") {
  4554. return routeChoice;
  4555. }
  4556. }
  4557. return arg.defaultShouldRevalidate;
  4558. }
  4559. function patchRoutesImpl(routeId, children, routesToUse, manifest, mapRouteProperties2, allowElementMutations) {
  4560. let childrenToPatch;
  4561. if (routeId) {
  4562. let route = manifest[routeId];
  4563. invariant(
  4564. route,
  4565. `No route found to patch children into: routeId = ${routeId}`
  4566. );
  4567. if (!route.children) {
  4568. route.children = [];
  4569. }
  4570. childrenToPatch = route.children;
  4571. } else {
  4572. childrenToPatch = routesToUse;
  4573. }
  4574. let uniqueChildren = [];
  4575. let existingChildren = [];
  4576. children.forEach((newRoute) => {
  4577. let existingRoute = childrenToPatch.find(
  4578. (existingRoute2) => isSameRoute(newRoute, existingRoute2)
  4579. );
  4580. if (existingRoute) {
  4581. existingChildren.push({ existingRoute, newRoute });
  4582. } else {
  4583. uniqueChildren.push(newRoute);
  4584. }
  4585. });
  4586. if (uniqueChildren.length > 0) {
  4587. let newRoutes = convertRoutesToDataRoutes(
  4588. uniqueChildren,
  4589. mapRouteProperties2,
  4590. [routeId || "_", "patch", String((childrenToPatch == null ? void 0 : childrenToPatch.length) || "0")],
  4591. manifest
  4592. );
  4593. childrenToPatch.push(...newRoutes);
  4594. }
  4595. if (allowElementMutations && existingChildren.length > 0) {
  4596. for (let i = 0; i < existingChildren.length; i++) {
  4597. let { existingRoute, newRoute } = existingChildren[i];
  4598. let existingRouteTyped = existingRoute;
  4599. let [newRouteTyped] = convertRoutesToDataRoutes(
  4600. [newRoute],
  4601. mapRouteProperties2,
  4602. [],
  4603. // Doesn't matter for mutated routes since they already have an id
  4604. {},
  4605. // Don't touch the manifest here since we're updating in place
  4606. true
  4607. );
  4608. Object.assign(existingRouteTyped, {
  4609. element: newRouteTyped.element ? newRouteTyped.element : existingRouteTyped.element,
  4610. errorElement: newRouteTyped.errorElement ? newRouteTyped.errorElement : existingRouteTyped.errorElement,
  4611. hydrateFallbackElement: newRouteTyped.hydrateFallbackElement ? newRouteTyped.hydrateFallbackElement : existingRouteTyped.hydrateFallbackElement
  4612. });
  4613. }
  4614. }
  4615. }
  4616. function isSameRoute(newRoute, existingRoute) {
  4617. if ("id" in newRoute && "id" in existingRoute && newRoute.id === existingRoute.id) {
  4618. return true;
  4619. }
  4620. if (!(newRoute.index === existingRoute.index && newRoute.path === existingRoute.path && newRoute.caseSensitive === existingRoute.caseSensitive)) {
  4621. return false;
  4622. }
  4623. if ((!newRoute.children || newRoute.children.length === 0) && (!existingRoute.children || existingRoute.children.length === 0)) {
  4624. return true;
  4625. }
  4626. return newRoute.children.every(
  4627. (aChild, i) => {
  4628. var _a;
  4629. return (_a = existingRoute.children) == null ? void 0 : _a.some((bChild) => isSameRoute(aChild, bChild));
  4630. }
  4631. );
  4632. }
  4633. var lazyRoutePropertyCache = /* @__PURE__ */ new WeakMap();
  4634. var loadLazyRouteProperty = ({
  4635. key,
  4636. route,
  4637. manifest,
  4638. mapRouteProperties: mapRouteProperties2
  4639. }) => {
  4640. let routeToUpdate = manifest[route.id];
  4641. invariant(routeToUpdate, "No route found in manifest");
  4642. if (!routeToUpdate.lazy || typeof routeToUpdate.lazy !== "object") {
  4643. return;
  4644. }
  4645. let lazyFn = routeToUpdate.lazy[key];
  4646. if (!lazyFn) {
  4647. return;
  4648. }
  4649. let cache = lazyRoutePropertyCache.get(routeToUpdate);
  4650. if (!cache) {
  4651. cache = {};
  4652. lazyRoutePropertyCache.set(routeToUpdate, cache);
  4653. }
  4654. let cachedPromise = cache[key];
  4655. if (cachedPromise) {
  4656. return cachedPromise;
  4657. }
  4658. let propertyPromise = (async () => {
  4659. let isUnsupported = isUnsupportedLazyRouteObjectKey(key);
  4660. let staticRouteValue = routeToUpdate[key];
  4661. let isStaticallyDefined = staticRouteValue !== void 0 && key !== "hasErrorBoundary";
  4662. if (isUnsupported) {
  4663. warning(
  4664. !isUnsupported,
  4665. "Route property " + key + " is not a supported lazy route property. This property will be ignored."
  4666. );
  4667. cache[key] = Promise.resolve();
  4668. } else if (isStaticallyDefined) {
  4669. warning(
  4670. false,
  4671. `Route "${routeToUpdate.id}" has a static property "${key}" defined. The lazy property will be ignored.`
  4672. );
  4673. } else {
  4674. let value = await lazyFn();
  4675. if (value != null) {
  4676. Object.assign(routeToUpdate, { [key]: value });
  4677. Object.assign(routeToUpdate, mapRouteProperties2(routeToUpdate));
  4678. }
  4679. }
  4680. if (typeof routeToUpdate.lazy === "object") {
  4681. routeToUpdate.lazy[key] = void 0;
  4682. if (Object.values(routeToUpdate.lazy).every((value) => value === void 0)) {
  4683. routeToUpdate.lazy = void 0;
  4684. }
  4685. }
  4686. })();
  4687. cache[key] = propertyPromise;
  4688. return propertyPromise;
  4689. };
  4690. var lazyRouteFunctionCache = /* @__PURE__ */ new WeakMap();
  4691. function loadLazyRoute(route, type, manifest, mapRouteProperties2, lazyRoutePropertiesToSkip) {
  4692. let routeToUpdate = manifest[route.id];
  4693. invariant(routeToUpdate, "No route found in manifest");
  4694. if (!route.lazy) {
  4695. return {
  4696. lazyRoutePromise: void 0,
  4697. lazyHandlerPromise: void 0
  4698. };
  4699. }
  4700. if (typeof route.lazy === "function") {
  4701. let cachedPromise = lazyRouteFunctionCache.get(routeToUpdate);
  4702. if (cachedPromise) {
  4703. return {
  4704. lazyRoutePromise: cachedPromise,
  4705. lazyHandlerPromise: cachedPromise
  4706. };
  4707. }
  4708. let lazyRoutePromise2 = (async () => {
  4709. invariant(
  4710. typeof route.lazy === "function",
  4711. "No lazy route function found"
  4712. );
  4713. let lazyRoute = await route.lazy();
  4714. let routeUpdates = {};
  4715. for (let lazyRouteProperty in lazyRoute) {
  4716. let lazyValue = lazyRoute[lazyRouteProperty];
  4717. if (lazyValue === void 0) {
  4718. continue;
  4719. }
  4720. let isUnsupported = isUnsupportedLazyRouteFunctionKey(lazyRouteProperty);
  4721. let staticRouteValue = routeToUpdate[lazyRouteProperty];
  4722. let isStaticallyDefined = staticRouteValue !== void 0 && // This property isn't static since it should always be updated based
  4723. // on the route updates
  4724. lazyRouteProperty !== "hasErrorBoundary";
  4725. if (isUnsupported) {
  4726. warning(
  4727. !isUnsupported,
  4728. "Route property " + lazyRouteProperty + " is not a supported property to be returned from a lazy route function. This property will be ignored."
  4729. );
  4730. } else if (isStaticallyDefined) {
  4731. warning(
  4732. !isStaticallyDefined,
  4733. `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.`
  4734. );
  4735. } else {
  4736. routeUpdates[lazyRouteProperty] = lazyValue;
  4737. }
  4738. }
  4739. Object.assign(routeToUpdate, routeUpdates);
  4740. Object.assign(routeToUpdate, {
  4741. // To keep things framework agnostic, we use the provided `mapRouteProperties`
  4742. // function to set the framework-aware properties (`element`/`hasErrorBoundary`)
  4743. // since the logic will differ between frameworks.
  4744. ...mapRouteProperties2(routeToUpdate),
  4745. lazy: void 0
  4746. });
  4747. })();
  4748. lazyRouteFunctionCache.set(routeToUpdate, lazyRoutePromise2);
  4749. lazyRoutePromise2.catch(() => {
  4750. });
  4751. return {
  4752. lazyRoutePromise: lazyRoutePromise2,
  4753. lazyHandlerPromise: lazyRoutePromise2
  4754. };
  4755. }
  4756. let lazyKeys = Object.keys(route.lazy);
  4757. let lazyPropertyPromises = [];
  4758. let lazyHandlerPromise = void 0;
  4759. for (let key of lazyKeys) {
  4760. if (lazyRoutePropertiesToSkip && lazyRoutePropertiesToSkip.includes(key)) {
  4761. continue;
  4762. }
  4763. let promise = loadLazyRouteProperty({
  4764. key,
  4765. route,
  4766. manifest,
  4767. mapRouteProperties: mapRouteProperties2
  4768. });
  4769. if (promise) {
  4770. lazyPropertyPromises.push(promise);
  4771. if (key === type) {
  4772. lazyHandlerPromise = promise;
  4773. }
  4774. }
  4775. }
  4776. let lazyRoutePromise = lazyPropertyPromises.length > 0 ? Promise.all(lazyPropertyPromises).then(() => {
  4777. }) : void 0;
  4778. lazyRoutePromise == null ? void 0 : lazyRoutePromise.catch(() => {
  4779. });
  4780. lazyHandlerPromise == null ? void 0 : lazyHandlerPromise.catch(() => {
  4781. });
  4782. return {
  4783. lazyRoutePromise,
  4784. lazyHandlerPromise
  4785. };
  4786. }
  4787. function isNonNullable(value) {
  4788. return value !== void 0;
  4789. }
  4790. function loadLazyMiddlewareForMatches(matches, manifest, mapRouteProperties2) {
  4791. let promises = matches.map(({ route }) => {
  4792. if (typeof route.lazy !== "object" || !route.lazy.middleware) {
  4793. return void 0;
  4794. }
  4795. return loadLazyRouteProperty({
  4796. key: "middleware",
  4797. route,
  4798. manifest,
  4799. mapRouteProperties: mapRouteProperties2
  4800. });
  4801. }).filter(isNonNullable);
  4802. return promises.length > 0 ? Promise.all(promises) : void 0;
  4803. }
  4804. async function defaultDataStrategy(args) {
  4805. let matchesToLoad = args.matches.filter((m) => m.shouldLoad);
  4806. let keyedResults = {};
  4807. let results = await Promise.all(matchesToLoad.map((m) => m.resolve()));
  4808. results.forEach((result, i) => {
  4809. keyedResults[matchesToLoad[i].route.id] = result;
  4810. });
  4811. return keyedResults;
  4812. }
  4813. async function defaultDataStrategyWithMiddleware(args) {
  4814. if (!args.matches.some((m) => m.route.middleware)) {
  4815. return defaultDataStrategy(args);
  4816. }
  4817. return runClientMiddlewarePipeline(args, () => defaultDataStrategy(args));
  4818. }
  4819. function runServerMiddlewarePipeline(args, handler, errorHandler) {
  4820. return runMiddlewarePipeline(
  4821. args,
  4822. handler,
  4823. processResult,
  4824. isResponse,
  4825. errorHandler
  4826. );
  4827. function processResult(result) {
  4828. return isDataWithResponseInit(result) ? dataWithResponseInitToResponse(result) : result;
  4829. }
  4830. }
  4831. function runClientMiddlewarePipeline(args, handler) {
  4832. return runMiddlewarePipeline(
  4833. args,
  4834. handler,
  4835. (r) => r,
  4836. // No post-processing needed on the client
  4837. isDataStrategyResults,
  4838. errorHandler
  4839. );
  4840. function errorHandler(error, routeId, nextResult) {
  4841. if (nextResult) {
  4842. return Promise.resolve(
  4843. Object.assign(nextResult.value, {
  4844. [routeId]: { type: "error", result: error }
  4845. })
  4846. );
  4847. } else {
  4848. let { matches } = args;
  4849. let maxBoundaryIdx = Math.min(
  4850. // Throwing route
  4851. Math.max(
  4852. matches.findIndex((m) => m.route.id === routeId),
  4853. 0
  4854. ),
  4855. // or the shallowest route that needs to load data
  4856. Math.max(
  4857. matches.findIndex((m) => m.shouldCallHandler()),
  4858. 0
  4859. )
  4860. );
  4861. let boundaryRouteId = findNearestBoundary(
  4862. matches,
  4863. matches[maxBoundaryIdx].route.id
  4864. ).route.id;
  4865. return Promise.resolve({
  4866. [boundaryRouteId]: { type: "error", result: error }
  4867. });
  4868. }
  4869. }
  4870. }
  4871. async function runMiddlewarePipeline(args, handler, processResult, isResult, errorHandler) {
  4872. let { matches, request, params, context, unstable_pattern } = args;
  4873. let tuples = matches.flatMap(
  4874. (m) => m.route.middleware ? m.route.middleware.map((fn) => [m.route.id, fn]) : []
  4875. );
  4876. let result = await callRouteMiddleware(
  4877. {
  4878. request,
  4879. params,
  4880. context,
  4881. unstable_pattern
  4882. },
  4883. tuples,
  4884. handler,
  4885. processResult,
  4886. isResult,
  4887. errorHandler
  4888. );
  4889. return result;
  4890. }
  4891. async function callRouteMiddleware(args, middlewares, handler, processResult, isResult, errorHandler, idx = 0) {
  4892. let { request } = args;
  4893. if (request.signal.aborted) {
  4894. throw request.signal.reason ?? new Error(`Request aborted: ${request.method} ${request.url}`);
  4895. }
  4896. let tuple = middlewares[idx];
  4897. if (!tuple) {
  4898. let result = await handler();
  4899. return result;
  4900. }
  4901. let [routeId, middleware] = tuple;
  4902. let nextResult;
  4903. let next = async () => {
  4904. if (nextResult) {
  4905. throw new Error("You may only call `next()` once per middleware");
  4906. }
  4907. try {
  4908. let result = await callRouteMiddleware(
  4909. args,
  4910. middlewares,
  4911. handler,
  4912. processResult,
  4913. isResult,
  4914. errorHandler,
  4915. idx + 1
  4916. );
  4917. nextResult = { value: result };
  4918. return nextResult.value;
  4919. } catch (error) {
  4920. nextResult = { value: await errorHandler(error, routeId, nextResult) };
  4921. return nextResult.value;
  4922. }
  4923. };
  4924. try {
  4925. let value = await middleware(args, next);
  4926. let result = value != null ? processResult(value) : void 0;
  4927. if (isResult(result)) {
  4928. return result;
  4929. } else if (nextResult) {
  4930. return result ?? nextResult.value;
  4931. } else {
  4932. nextResult = { value: await next() };
  4933. return nextResult.value;
  4934. }
  4935. } catch (error) {
  4936. let response = await errorHandler(error, routeId, nextResult);
  4937. return response;
  4938. }
  4939. }
  4940. function getDataStrategyMatchLazyPromises(mapRouteProperties2, manifest, request, match, lazyRoutePropertiesToSkip) {
  4941. let lazyMiddlewarePromise = loadLazyRouteProperty({
  4942. key: "middleware",
  4943. route: match.route,
  4944. manifest,
  4945. mapRouteProperties: mapRouteProperties2
  4946. });
  4947. let lazyRoutePromises = loadLazyRoute(
  4948. match.route,
  4949. isMutationMethod(request.method) ? "action" : "loader",
  4950. manifest,
  4951. mapRouteProperties2,
  4952. lazyRoutePropertiesToSkip
  4953. );
  4954. return {
  4955. middleware: lazyMiddlewarePromise,
  4956. route: lazyRoutePromises.lazyRoutePromise,
  4957. handler: lazyRoutePromises.lazyHandlerPromise
  4958. };
  4959. }
  4960. function getDataStrategyMatch(mapRouteProperties2, manifest, request, unstable_pattern, match, lazyRoutePropertiesToSkip, scopedContext, shouldLoad, shouldRevalidateArgs = null) {
  4961. let isUsingNewApi = false;
  4962. let _lazyPromises = getDataStrategyMatchLazyPromises(
  4963. mapRouteProperties2,
  4964. manifest,
  4965. request,
  4966. match,
  4967. lazyRoutePropertiesToSkip
  4968. );
  4969. return {
  4970. ...match,
  4971. _lazyPromises,
  4972. shouldLoad,
  4973. shouldRevalidateArgs,
  4974. shouldCallHandler(defaultShouldRevalidate) {
  4975. isUsingNewApi = true;
  4976. if (!shouldRevalidateArgs) {
  4977. return shouldLoad;
  4978. }
  4979. if (typeof defaultShouldRevalidate === "boolean") {
  4980. return shouldRevalidateLoader(match, {
  4981. ...shouldRevalidateArgs,
  4982. defaultShouldRevalidate
  4983. });
  4984. }
  4985. return shouldRevalidateLoader(match, shouldRevalidateArgs);
  4986. },
  4987. resolve(handlerOverride) {
  4988. let { lazy, loader, middleware } = match.route;
  4989. let callHandler = isUsingNewApi || shouldLoad || handlerOverride && !isMutationMethod(request.method) && (lazy || loader);
  4990. let isMiddlewareOnlyRoute = middleware && middleware.length > 0 && !loader && !lazy;
  4991. if (callHandler && (isMutationMethod(request.method) || !isMiddlewareOnlyRoute)) {
  4992. return callLoaderOrAction({
  4993. request,
  4994. unstable_pattern,
  4995. match,
  4996. lazyHandlerPromise: _lazyPromises == null ? void 0 : _lazyPromises.handler,
  4997. lazyRoutePromise: _lazyPromises == null ? void 0 : _lazyPromises.route,
  4998. handlerOverride,
  4999. scopedContext
  5000. });
  5001. }
  5002. return Promise.resolve({ type: "data", result: void 0 });
  5003. }
  5004. };
  5005. }
  5006. function getTargetedDataStrategyMatches(mapRouteProperties2, manifest, request, matches, targetMatch, lazyRoutePropertiesToSkip, scopedContext, shouldRevalidateArgs = null) {
  5007. return matches.map((match) => {
  5008. if (match.route.id !== targetMatch.route.id) {
  5009. return {
  5010. ...match,
  5011. shouldLoad: false,
  5012. shouldRevalidateArgs,
  5013. shouldCallHandler: () => false,
  5014. _lazyPromises: getDataStrategyMatchLazyPromises(
  5015. mapRouteProperties2,
  5016. manifest,
  5017. request,
  5018. match,
  5019. lazyRoutePropertiesToSkip
  5020. ),
  5021. resolve: () => Promise.resolve({ type: "data", result: void 0 })
  5022. };
  5023. }
  5024. return getDataStrategyMatch(
  5025. mapRouteProperties2,
  5026. manifest,
  5027. request,
  5028. getRoutePattern(matches),
  5029. match,
  5030. lazyRoutePropertiesToSkip,
  5031. scopedContext,
  5032. true,
  5033. shouldRevalidateArgs
  5034. );
  5035. });
  5036. }
  5037. async function callDataStrategyImpl(dataStrategyImpl, request, matches, fetcherKey, scopedContext, isStaticHandler) {
  5038. if (matches.some((m) => {
  5039. var _a;
  5040. return (_a = m._lazyPromises) == null ? void 0 : _a.middleware;
  5041. })) {
  5042. await Promise.all(matches.map((m) => {
  5043. var _a;
  5044. return (_a = m._lazyPromises) == null ? void 0 : _a.middleware;
  5045. }));
  5046. }
  5047. let dataStrategyArgs = {
  5048. request,
  5049. unstable_pattern: getRoutePattern(matches),
  5050. params: matches[0].params,
  5051. context: scopedContext,
  5052. matches
  5053. };
  5054. let runClientMiddleware = isStaticHandler ? () => {
  5055. throw new Error(
  5056. "You cannot call `runClientMiddleware()` from a static handler `dataStrategy`. Middleware is run outside of `dataStrategy` during SSR in order to bubble up the Response. You can enable middleware via the `respond` API in `query`/`queryRoute`"
  5057. );
  5058. } : (cb) => {
  5059. let typedDataStrategyArgs = dataStrategyArgs;
  5060. return runClientMiddlewarePipeline(typedDataStrategyArgs, () => {
  5061. return cb({
  5062. ...typedDataStrategyArgs,
  5063. fetcherKey,
  5064. runClientMiddleware: () => {
  5065. throw new Error(
  5066. "Cannot call `runClientMiddleware()` from within an `runClientMiddleware` handler"
  5067. );
  5068. }
  5069. });
  5070. });
  5071. };
  5072. let results = await dataStrategyImpl({
  5073. ...dataStrategyArgs,
  5074. fetcherKey,
  5075. runClientMiddleware
  5076. });
  5077. try {
  5078. await Promise.all(
  5079. matches.flatMap((m) => {
  5080. var _a, _b;
  5081. return [
  5082. (_a = m._lazyPromises) == null ? void 0 : _a.handler,
  5083. (_b = m._lazyPromises) == null ? void 0 : _b.route
  5084. ];
  5085. })
  5086. );
  5087. } catch (e) {
  5088. }
  5089. return results;
  5090. }
  5091. async function callLoaderOrAction({
  5092. request,
  5093. unstable_pattern,
  5094. match,
  5095. lazyHandlerPromise,
  5096. lazyRoutePromise,
  5097. handlerOverride,
  5098. scopedContext
  5099. }) {
  5100. let result;
  5101. let onReject;
  5102. let isAction = isMutationMethod(request.method);
  5103. let type = isAction ? "action" : "loader";
  5104. let runHandler = (handler) => {
  5105. let reject;
  5106. let abortPromise = new Promise((_, r) => reject = r);
  5107. onReject = () => reject();
  5108. request.signal.addEventListener("abort", onReject);
  5109. let actualHandler = (ctx) => {
  5110. if (typeof handler !== "function") {
  5111. return Promise.reject(
  5112. new Error(
  5113. `You cannot call the handler for a route which defines a boolean "${type}" [routeId: ${match.route.id}]`
  5114. )
  5115. );
  5116. }
  5117. return handler(
  5118. {
  5119. request,
  5120. unstable_pattern,
  5121. params: match.params,
  5122. context: scopedContext
  5123. },
  5124. ...ctx !== void 0 ? [ctx] : []
  5125. );
  5126. };
  5127. let handlerPromise = (async () => {
  5128. try {
  5129. let val = await (handlerOverride ? handlerOverride((ctx) => actualHandler(ctx)) : actualHandler());
  5130. return { type: "data", result: val };
  5131. } catch (e) {
  5132. return { type: "error", result: e };
  5133. }
  5134. })();
  5135. return Promise.race([handlerPromise, abortPromise]);
  5136. };
  5137. try {
  5138. let handler = isAction ? match.route.action : match.route.loader;
  5139. if (lazyHandlerPromise || lazyRoutePromise) {
  5140. if (handler) {
  5141. let handlerError;
  5142. let [value] = await Promise.all([
  5143. // If the handler throws, don't let it immediately bubble out,
  5144. // since we need to let the lazy() execution finish so we know if this
  5145. // route has a boundary that can handle the error
  5146. runHandler(handler).catch((e) => {
  5147. handlerError = e;
  5148. }),
  5149. // Ensure all lazy route promises are resolved before continuing
  5150. lazyHandlerPromise,
  5151. lazyRoutePromise
  5152. ]);
  5153. if (handlerError !== void 0) {
  5154. throw handlerError;
  5155. }
  5156. result = value;
  5157. } else {
  5158. await lazyHandlerPromise;
  5159. let handler2 = isAction ? match.route.action : match.route.loader;
  5160. if (handler2) {
  5161. [result] = await Promise.all([runHandler(handler2), lazyRoutePromise]);
  5162. } else if (type === "action") {
  5163. let url = new URL(request.url);
  5164. let pathname = url.pathname + url.search;
  5165. throw getInternalRouterError(405, {
  5166. method: request.method,
  5167. pathname,
  5168. routeId: match.route.id
  5169. });
  5170. } else {
  5171. return { type: "data", result: void 0 };
  5172. }
  5173. }
  5174. } else if (!handler) {
  5175. let url = new URL(request.url);
  5176. let pathname = url.pathname + url.search;
  5177. throw getInternalRouterError(404, {
  5178. pathname
  5179. });
  5180. } else {
  5181. result = await runHandler(handler);
  5182. }
  5183. } catch (e) {
  5184. return { type: "error", result: e };
  5185. } finally {
  5186. if (onReject) {
  5187. request.signal.removeEventListener("abort", onReject);
  5188. }
  5189. }
  5190. return result;
  5191. }
  5192. async function parseResponseBody(response) {
  5193. let contentType = response.headers.get("Content-Type");
  5194. if (contentType && /\bapplication\/json\b/.test(contentType)) {
  5195. return response.body == null ? null : response.json();
  5196. }
  5197. return response.text();
  5198. }
  5199. async function convertDataStrategyResultToDataResult(dataStrategyResult) {
  5200. var _a, _b, _c, _d, _e;
  5201. let { result, type } = dataStrategyResult;
  5202. if (isResponse(result)) {
  5203. let data2;
  5204. try {
  5205. data2 = await parseResponseBody(result);
  5206. } catch (e) {
  5207. return { type: "error", error: e };
  5208. }
  5209. if (type === "error") {
  5210. return {
  5211. type: "error",
  5212. error: new ErrorResponseImpl(result.status, result.statusText, data2),
  5213. statusCode: result.status,
  5214. headers: result.headers
  5215. };
  5216. }
  5217. return {
  5218. type: "data",
  5219. data: data2,
  5220. statusCode: result.status,
  5221. headers: result.headers
  5222. };
  5223. }
  5224. if (type === "error") {
  5225. if (isDataWithResponseInit(result)) {
  5226. if (result.data instanceof Error) {
  5227. return {
  5228. type: "error",
  5229. error: result.data,
  5230. statusCode: (_a = result.init) == null ? void 0 : _a.status,
  5231. headers: ((_b = result.init) == null ? void 0 : _b.headers) ? new Headers(result.init.headers) : void 0
  5232. };
  5233. }
  5234. return {
  5235. type: "error",
  5236. error: dataWithResponseInitToErrorResponse(result),
  5237. statusCode: isRouteErrorResponse(result) ? result.status : void 0,
  5238. headers: ((_c = result.init) == null ? void 0 : _c.headers) ? new Headers(result.init.headers) : void 0
  5239. };
  5240. }
  5241. return {
  5242. type: "error",
  5243. error: result,
  5244. statusCode: isRouteErrorResponse(result) ? result.status : void 0
  5245. };
  5246. }
  5247. if (isDataWithResponseInit(result)) {
  5248. return {
  5249. type: "data",
  5250. data: result.data,
  5251. statusCode: (_d = result.init) == null ? void 0 : _d.status,
  5252. headers: ((_e = result.init) == null ? void 0 : _e.headers) ? new Headers(result.init.headers) : void 0
  5253. };
  5254. }
  5255. return { type: "data", data: result };
  5256. }
  5257. function normalizeRelativeRoutingRedirectResponse(response, request, routeId, matches, basename) {
  5258. let location2 = response.headers.get("Location");
  5259. invariant(
  5260. location2,
  5261. "Redirects returned/thrown from loaders/actions must have a Location header"
  5262. );
  5263. if (!isAbsoluteUrl(location2)) {
  5264. let trimmedMatches = matches.slice(
  5265. 0,
  5266. matches.findIndex((m) => m.route.id === routeId) + 1
  5267. );
  5268. location2 = normalizeTo(
  5269. new URL(request.url),
  5270. trimmedMatches,
  5271. basename,
  5272. location2
  5273. );
  5274. response.headers.set("Location", location2);
  5275. }
  5276. return response;
  5277. }
  5278. function normalizeRedirectLocation(location2, currentUrl, basename) {
  5279. if (isAbsoluteUrl(location2)) {
  5280. let normalizedLocation = location2;
  5281. let url = normalizedLocation.startsWith("//") ? new URL(currentUrl.protocol + normalizedLocation) : new URL(normalizedLocation);
  5282. let isSameBasename = stripBasename(url.pathname, basename) != null;
  5283. if (url.origin === currentUrl.origin && isSameBasename) {
  5284. return url.pathname + url.search + url.hash;
  5285. }
  5286. }
  5287. return location2;
  5288. }
  5289. function createClientSideRequest(history, location2, signal, submission) {
  5290. let url = history.createURL(stripHashFromPath(location2)).toString();
  5291. let init = { signal };
  5292. if (submission && isMutationMethod(submission.formMethod)) {
  5293. let { formMethod, formEncType } = submission;
  5294. init.method = formMethod.toUpperCase();
  5295. if (formEncType === "application/json") {
  5296. init.headers = new Headers({ "Content-Type": formEncType });
  5297. init.body = JSON.stringify(submission.json);
  5298. } else if (formEncType === "text/plain") {
  5299. init.body = submission.text;
  5300. } else if (formEncType === "application/x-www-form-urlencoded" && submission.formData) {
  5301. init.body = convertFormDataToSearchParams(submission.formData);
  5302. } else {
  5303. init.body = submission.formData;
  5304. }
  5305. }
  5306. return new Request(url, init);
  5307. }
  5308. function convertFormDataToSearchParams(formData) {
  5309. let searchParams = new URLSearchParams();
  5310. for (let [key, value] of formData.entries()) {
  5311. searchParams.append(key, typeof value === "string" ? value : value.name);
  5312. }
  5313. return searchParams;
  5314. }
  5315. function convertSearchParamsToFormData(searchParams) {
  5316. let formData = new FormData();
  5317. for (let [key, value] of searchParams.entries()) {
  5318. formData.append(key, value);
  5319. }
  5320. return formData;
  5321. }
  5322. function processRouteLoaderData(matches, results, pendingActionResult, isStaticHandler = false, skipLoaderErrorBubbling = false) {
  5323. let loaderData = {};
  5324. let errors = null;
  5325. let statusCode;
  5326. let foundError = false;
  5327. let loaderHeaders = {};
  5328. let pendingError = pendingActionResult && isErrorResult(pendingActionResult[1]) ? pendingActionResult[1].error : void 0;
  5329. matches.forEach((match) => {
  5330. if (!(match.route.id in results)) {
  5331. return;
  5332. }
  5333. let id = match.route.id;
  5334. let result = results[id];
  5335. invariant(
  5336. !isRedirectResult(result),
  5337. "Cannot handle redirect results in processLoaderData"
  5338. );
  5339. if (isErrorResult(result)) {
  5340. let error = result.error;
  5341. if (pendingError !== void 0) {
  5342. error = pendingError;
  5343. pendingError = void 0;
  5344. }
  5345. errors = errors || {};
  5346. if (skipLoaderErrorBubbling) {
  5347. errors[id] = error;
  5348. } else {
  5349. let boundaryMatch = findNearestBoundary(matches, id);
  5350. if (errors[boundaryMatch.route.id] == null) {
  5351. errors[boundaryMatch.route.id] = error;
  5352. }
  5353. }
  5354. if (!isStaticHandler) {
  5355. loaderData[id] = ResetLoaderDataSymbol;
  5356. }
  5357. if (!foundError) {
  5358. foundError = true;
  5359. statusCode = isRouteErrorResponse(result.error) ? result.error.status : 500;
  5360. }
  5361. if (result.headers) {
  5362. loaderHeaders[id] = result.headers;
  5363. }
  5364. } else {
  5365. loaderData[id] = result.data;
  5366. if (result.statusCode && result.statusCode !== 200 && !foundError) {
  5367. statusCode = result.statusCode;
  5368. }
  5369. if (result.headers) {
  5370. loaderHeaders[id] = result.headers;
  5371. }
  5372. }
  5373. });
  5374. if (pendingError !== void 0 && pendingActionResult) {
  5375. errors = { [pendingActionResult[0]]: pendingError };
  5376. if (pendingActionResult[2]) {
  5377. loaderData[pendingActionResult[2]] = void 0;
  5378. }
  5379. }
  5380. return {
  5381. loaderData,
  5382. errors,
  5383. statusCode: statusCode || 200,
  5384. loaderHeaders
  5385. };
  5386. }
  5387. function processLoaderData(state, matches, results, pendingActionResult, revalidatingFetchers, fetcherResults) {
  5388. let { loaderData, errors } = processRouteLoaderData(
  5389. matches,
  5390. results,
  5391. pendingActionResult
  5392. );
  5393. revalidatingFetchers.filter((f) => !f.matches || f.matches.some((m) => m.shouldLoad)).forEach((rf) => {
  5394. let { key, match, controller } = rf;
  5395. if (controller && controller.signal.aborted) {
  5396. return;
  5397. }
  5398. let result = fetcherResults[key];
  5399. invariant(result, "Did not find corresponding fetcher result");
  5400. if (isErrorResult(result)) {
  5401. let boundaryMatch = findNearestBoundary(state.matches, match == null ? void 0 : match.route.id);
  5402. if (!(errors && errors[boundaryMatch.route.id])) {
  5403. errors = {
  5404. ...errors,
  5405. [boundaryMatch.route.id]: result.error
  5406. };
  5407. }
  5408. state.fetchers.delete(key);
  5409. } else if (isRedirectResult(result)) {
  5410. invariant(false, "Unhandled fetcher revalidation redirect");
  5411. } else {
  5412. let doneFetcher = getDoneFetcher(result.data);
  5413. state.fetchers.set(key, doneFetcher);
  5414. }
  5415. });
  5416. return { loaderData, errors };
  5417. }
  5418. function mergeLoaderData(loaderData, newLoaderData, matches, errors) {
  5419. let mergedLoaderData = Object.entries(newLoaderData).filter(([, v]) => v !== ResetLoaderDataSymbol).reduce((merged, [k, v]) => {
  5420. merged[k] = v;
  5421. return merged;
  5422. }, {});
  5423. for (let match of matches) {
  5424. let id = match.route.id;
  5425. if (!newLoaderData.hasOwnProperty(id) && loaderData.hasOwnProperty(id) && match.route.loader) {
  5426. mergedLoaderData[id] = loaderData[id];
  5427. }
  5428. if (errors && errors.hasOwnProperty(id)) {
  5429. break;
  5430. }
  5431. }
  5432. return mergedLoaderData;
  5433. }
  5434. function getActionDataForCommit(pendingActionResult) {
  5435. if (!pendingActionResult) {
  5436. return {};
  5437. }
  5438. return isErrorResult(pendingActionResult[1]) ? {
  5439. // Clear out prior actionData on errors
  5440. actionData: {}
  5441. } : {
  5442. actionData: {
  5443. [pendingActionResult[0]]: pendingActionResult[1].data
  5444. }
  5445. };
  5446. }
  5447. function findNearestBoundary(matches, routeId) {
  5448. let eligibleMatches = routeId ? matches.slice(0, matches.findIndex((m) => m.route.id === routeId) + 1) : [...matches];
  5449. return eligibleMatches.reverse().find((m) => m.route.hasErrorBoundary === true) || matches[0];
  5450. }
  5451. function getShortCircuitMatches(routes) {
  5452. let route = routes.length === 1 ? routes[0] : routes.find((r) => r.index || !r.path || r.path === "/") || {
  5453. id: `__shim-error-route__`
  5454. };
  5455. return {
  5456. matches: [
  5457. {
  5458. params: {},
  5459. pathname: "",
  5460. pathnameBase: "",
  5461. route
  5462. }
  5463. ],
  5464. route
  5465. };
  5466. }
  5467. function getInternalRouterError(status, {
  5468. pathname,
  5469. routeId,
  5470. method,
  5471. type,
  5472. message
  5473. } = {}) {
  5474. let statusText = "Unknown Server Error";
  5475. let errorMessage = "Unknown @remix-run/router error";
  5476. if (status === 400) {
  5477. statusText = "Bad Request";
  5478. if (method && pathname && routeId) {
  5479. 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.`;
  5480. } else if (type === "invalid-body") {
  5481. errorMessage = "Unable to encode submission body";
  5482. }
  5483. } else if (status === 403) {
  5484. statusText = "Forbidden";
  5485. errorMessage = `Route "${routeId}" does not match URL "${pathname}"`;
  5486. } else if (status === 404) {
  5487. statusText = "Not Found";
  5488. errorMessage = `No route matches URL "${pathname}"`;
  5489. } else if (status === 405) {
  5490. statusText = "Method Not Allowed";
  5491. if (method && pathname && routeId) {
  5492. 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.`;
  5493. } else if (method) {
  5494. errorMessage = `Invalid request method "${method.toUpperCase()}"`;
  5495. }
  5496. }
  5497. return new ErrorResponseImpl(
  5498. status || 500,
  5499. statusText,
  5500. new Error(errorMessage),
  5501. true
  5502. );
  5503. }
  5504. function findRedirect(results) {
  5505. let entries = Object.entries(results);
  5506. for (let i = entries.length - 1; i >= 0; i--) {
  5507. let [key, result] = entries[i];
  5508. if (isRedirectResult(result)) {
  5509. return { key, result };
  5510. }
  5511. }
  5512. }
  5513. function stripHashFromPath(path) {
  5514. let parsedPath = typeof path === "string" ? parsePath(path) : path;
  5515. return createPath({ ...parsedPath, hash: "" });
  5516. }
  5517. function isHashChangeOnly(a, b) {
  5518. if (a.pathname !== b.pathname || a.search !== b.search) {
  5519. return false;
  5520. }
  5521. if (a.hash === "") {
  5522. return b.hash !== "";
  5523. } else if (a.hash === b.hash) {
  5524. return true;
  5525. } else if (b.hash !== "") {
  5526. return true;
  5527. }
  5528. return false;
  5529. }
  5530. function dataWithResponseInitToResponse(data2) {
  5531. return Response.json(data2.data, data2.init ?? void 0);
  5532. }
  5533. function dataWithResponseInitToErrorResponse(data2) {
  5534. var _a, _b;
  5535. return new ErrorResponseImpl(
  5536. ((_a = data2.init) == null ? void 0 : _a.status) ?? 500,
  5537. ((_b = data2.init) == null ? void 0 : _b.statusText) ?? "Internal Server Error",
  5538. data2.data
  5539. );
  5540. }
  5541. function isDataStrategyResults(result) {
  5542. return result != null && typeof result === "object" && Object.entries(result).every(
  5543. ([key, value]) => typeof key === "string" && isDataStrategyResult(value)
  5544. );
  5545. }
  5546. function isDataStrategyResult(result) {
  5547. return result != null && typeof result === "object" && "type" in result && "result" in result && (result.type === "data" || result.type === "error");
  5548. }
  5549. function isRedirectDataStrategyResult(result) {
  5550. return isResponse(result.result) && redirectStatusCodes.has(result.result.status);
  5551. }
  5552. function isErrorResult(result) {
  5553. return result.type === "error";
  5554. }
  5555. function isRedirectResult(result) {
  5556. return (result && result.type) === "redirect";
  5557. }
  5558. function isDataWithResponseInit(value) {
  5559. return typeof value === "object" && value != null && "type" in value && "data" in value && "init" in value && value.type === "DataWithResponseInit";
  5560. }
  5561. function isResponse(value) {
  5562. return value != null && typeof value.status === "number" && typeof value.statusText === "string" && typeof value.headers === "object" && typeof value.body !== "undefined";
  5563. }
  5564. function isRedirectStatusCode(statusCode) {
  5565. return redirectStatusCodes.has(statusCode);
  5566. }
  5567. function isRedirectResponse(result) {
  5568. return isResponse(result) && isRedirectStatusCode(result.status) && result.headers.has("Location");
  5569. }
  5570. function isValidMethod(method) {
  5571. return validRequestMethods.has(method.toUpperCase());
  5572. }
  5573. function isMutationMethod(method) {
  5574. return validMutationMethods.has(method.toUpperCase());
  5575. }
  5576. function hasNakedIndexQuery(search) {
  5577. return new URLSearchParams(search).getAll("index").some((v) => v === "");
  5578. }
  5579. function getTargetMatch(matches, location2) {
  5580. let search = typeof location2 === "string" ? parsePath(location2).search : location2.search;
  5581. if (matches[matches.length - 1].route.index && hasNakedIndexQuery(search || "")) {
  5582. return matches[matches.length - 1];
  5583. }
  5584. let pathMatches = getPathContributingMatches(matches);
  5585. return pathMatches[pathMatches.length - 1];
  5586. }
  5587. function getSubmissionFromNavigation(navigation) {
  5588. let { formMethod, formAction, formEncType, text, formData, json } = navigation;
  5589. if (!formMethod || !formAction || !formEncType) {
  5590. return;
  5591. }
  5592. if (text != null) {
  5593. return {
  5594. formMethod,
  5595. formAction,
  5596. formEncType,
  5597. formData: void 0,
  5598. json: void 0,
  5599. text
  5600. };
  5601. } else if (formData != null) {
  5602. return {
  5603. formMethod,
  5604. formAction,
  5605. formEncType,
  5606. formData,
  5607. json: void 0,
  5608. text: void 0
  5609. };
  5610. } else if (json !== void 0) {
  5611. return {
  5612. formMethod,
  5613. formAction,
  5614. formEncType,
  5615. formData: void 0,
  5616. json,
  5617. text: void 0
  5618. };
  5619. }
  5620. }
  5621. function getLoadingNavigation(location2, submission) {
  5622. if (submission) {
  5623. let navigation = {
  5624. state: "loading",
  5625. location: location2,
  5626. formMethod: submission.formMethod,
  5627. formAction: submission.formAction,
  5628. formEncType: submission.formEncType,
  5629. formData: submission.formData,
  5630. json: submission.json,
  5631. text: submission.text
  5632. };
  5633. return navigation;
  5634. } else {
  5635. let navigation = {
  5636. state: "loading",
  5637. location: location2,
  5638. formMethod: void 0,
  5639. formAction: void 0,
  5640. formEncType: void 0,
  5641. formData: void 0,
  5642. json: void 0,
  5643. text: void 0
  5644. };
  5645. return navigation;
  5646. }
  5647. }
  5648. function getSubmittingNavigation(location2, submission) {
  5649. let navigation = {
  5650. state: "submitting",
  5651. location: location2,
  5652. formMethod: submission.formMethod,
  5653. formAction: submission.formAction,
  5654. formEncType: submission.formEncType,
  5655. formData: submission.formData,
  5656. json: submission.json,
  5657. text: submission.text
  5658. };
  5659. return navigation;
  5660. }
  5661. function getLoadingFetcher(submission, data2) {
  5662. if (submission) {
  5663. let fetcher = {
  5664. state: "loading",
  5665. formMethod: submission.formMethod,
  5666. formAction: submission.formAction,
  5667. formEncType: submission.formEncType,
  5668. formData: submission.formData,
  5669. json: submission.json,
  5670. text: submission.text,
  5671. data: data2
  5672. };
  5673. return fetcher;
  5674. } else {
  5675. let fetcher = {
  5676. state: "loading",
  5677. formMethod: void 0,
  5678. formAction: void 0,
  5679. formEncType: void 0,
  5680. formData: void 0,
  5681. json: void 0,
  5682. text: void 0,
  5683. data: data2
  5684. };
  5685. return fetcher;
  5686. }
  5687. }
  5688. function getSubmittingFetcher(submission, existingFetcher) {
  5689. let fetcher = {
  5690. state: "submitting",
  5691. formMethod: submission.formMethod,
  5692. formAction: submission.formAction,
  5693. formEncType: submission.formEncType,
  5694. formData: submission.formData,
  5695. json: submission.json,
  5696. text: submission.text,
  5697. data: existingFetcher ? existingFetcher.data : void 0
  5698. };
  5699. return fetcher;
  5700. }
  5701. function getDoneFetcher(data2) {
  5702. let fetcher = {
  5703. state: "idle",
  5704. formMethod: void 0,
  5705. formAction: void 0,
  5706. formEncType: void 0,
  5707. formData: void 0,
  5708. json: void 0,
  5709. text: void 0,
  5710. data: data2
  5711. };
  5712. return fetcher;
  5713. }
  5714. function restoreAppliedTransitions(_window, transitions) {
  5715. try {
  5716. let sessionPositions = _window.sessionStorage.getItem(
  5717. TRANSITIONS_STORAGE_KEY
  5718. );
  5719. if (sessionPositions) {
  5720. let json = JSON.parse(sessionPositions);
  5721. for (let [k, v] of Object.entries(json || {})) {
  5722. if (v && Array.isArray(v)) {
  5723. transitions.set(k, new Set(v || []));
  5724. }
  5725. }
  5726. }
  5727. } catch (e) {
  5728. }
  5729. }
  5730. function persistAppliedTransitions(_window, transitions) {
  5731. if (transitions.size > 0) {
  5732. let json = {};
  5733. for (let [k, v] of transitions) {
  5734. json[k] = [...v];
  5735. }
  5736. try {
  5737. _window.sessionStorage.setItem(
  5738. TRANSITIONS_STORAGE_KEY,
  5739. JSON.stringify(json)
  5740. );
  5741. } catch (error) {
  5742. warning(
  5743. false,
  5744. `Failed to save applied view transitions in sessionStorage (${error}).`
  5745. );
  5746. }
  5747. }
  5748. }
  5749. function createDeferred() {
  5750. let resolve;
  5751. let reject;
  5752. let promise = new Promise((res, rej) => {
  5753. resolve = async (val) => {
  5754. res(val);
  5755. try {
  5756. await promise;
  5757. } catch (e) {
  5758. }
  5759. };
  5760. reject = async (error) => {
  5761. rej(error);
  5762. try {
  5763. await promise;
  5764. } catch (e) {
  5765. }
  5766. };
  5767. });
  5768. return {
  5769. promise,
  5770. //@ts-ignore
  5771. resolve,
  5772. //@ts-ignore
  5773. reject
  5774. };
  5775. }
  5776. var DataRouterContext = React.createContext(null);
  5777. DataRouterContext.displayName = "DataRouter";
  5778. var DataRouterStateContext = React.createContext(null);
  5779. DataRouterStateContext.displayName = "DataRouterState";
  5780. var RSCRouterContext = React.createContext(false);
  5781. function useIsRSCRouterContext() {
  5782. return React.useContext(RSCRouterContext);
  5783. }
  5784. var ViewTransitionContext = React.createContext({
  5785. isTransitioning: false
  5786. });
  5787. ViewTransitionContext.displayName = "ViewTransition";
  5788. var FetchersContext = React.createContext(
  5789. /* @__PURE__ */ new Map()
  5790. );
  5791. FetchersContext.displayName = "Fetchers";
  5792. var AwaitContext = React.createContext(null);
  5793. AwaitContext.displayName = "Await";
  5794. var AwaitContextProvider = (props) => React.createElement(AwaitContext.Provider, props);
  5795. var NavigationContext = React.createContext(
  5796. null
  5797. );
  5798. NavigationContext.displayName = "Navigation";
  5799. var LocationContext = React.createContext(
  5800. null
  5801. );
  5802. LocationContext.displayName = "Location";
  5803. var RouteContext = React.createContext({
  5804. outlet: null,
  5805. matches: [],
  5806. isDataRoute: false
  5807. });
  5808. RouteContext.displayName = "Route";
  5809. var RouteErrorContext = React.createContext(null);
  5810. RouteErrorContext.displayName = "RouteError";
  5811. var ENABLE_DEV_WARNINGS = true;
  5812. function useHref(to, { relative } = {}) {
  5813. invariant(
  5814. useInRouterContext(),
  5815. // TODO: This error is probably because they somehow have 2 versions of the
  5816. // router loaded. We can help them understand how to avoid that.
  5817. `useHref() may be used only in the context of a <Router> component.`
  5818. );
  5819. let { basename, navigator } = React2.useContext(NavigationContext);
  5820. let { hash, pathname, search } = useResolvedPath(to, { relative });
  5821. let joinedPathname = pathname;
  5822. if (basename !== "/") {
  5823. joinedPathname = pathname === "/" ? basename : joinPaths([basename, pathname]);
  5824. }
  5825. return navigator.createHref({ pathname: joinedPathname, search, hash });
  5826. }
  5827. function useInRouterContext() {
  5828. return React2.useContext(LocationContext) != null;
  5829. }
  5830. function useLocation() {
  5831. invariant(
  5832. useInRouterContext(),
  5833. // TODO: This error is probably because they somehow have 2 versions of the
  5834. // router loaded. We can help them understand how to avoid that.
  5835. `useLocation() may be used only in the context of a <Router> component.`
  5836. );
  5837. return React2.useContext(LocationContext).location;
  5838. }
  5839. function useNavigationType() {
  5840. return React2.useContext(LocationContext).navigationType;
  5841. }
  5842. function useMatch(pattern) {
  5843. invariant(
  5844. useInRouterContext(),
  5845. // TODO: This error is probably because they somehow have 2 versions of the
  5846. // router loaded. We can help them understand how to avoid that.
  5847. `useMatch() may be used only in the context of a <Router> component.`
  5848. );
  5849. let { pathname } = useLocation();
  5850. return React2.useMemo(
  5851. () => matchPath(pattern, decodePath(pathname)),
  5852. [pathname, pattern]
  5853. );
  5854. }
  5855. var navigateEffectWarning = `You should call navigate() in a React.useEffect(), not when your component is first rendered.`;
  5856. function useIsomorphicLayoutEffect(cb) {
  5857. let isStatic = React2.useContext(NavigationContext).static;
  5858. if (!isStatic) {
  5859. React2.useLayoutEffect(cb);
  5860. }
  5861. }
  5862. function useNavigate() {
  5863. let { isDataRoute } = React2.useContext(RouteContext);
  5864. return isDataRoute ? useNavigateStable() : useNavigateUnstable();
  5865. }
  5866. function useNavigateUnstable() {
  5867. invariant(
  5868. useInRouterContext(),
  5869. // TODO: This error is probably because they somehow have 2 versions of the
  5870. // router loaded. We can help them understand how to avoid that.
  5871. `useNavigate() may be used only in the context of a <Router> component.`
  5872. );
  5873. let dataRouterContext = React2.useContext(DataRouterContext);
  5874. let { basename, navigator } = React2.useContext(NavigationContext);
  5875. let { matches } = React2.useContext(RouteContext);
  5876. let { pathname: locationPathname } = useLocation();
  5877. let routePathnamesJson = JSON.stringify(getResolveToMatches(matches));
  5878. let activeRef = React2.useRef(false);
  5879. useIsomorphicLayoutEffect(() => {
  5880. activeRef.current = true;
  5881. });
  5882. let navigate = React2.useCallback(
  5883. (to, options = {}) => {
  5884. warning(activeRef.current, navigateEffectWarning);
  5885. if (!activeRef.current) return;
  5886. if (typeof to === "number") {
  5887. navigator.go(to);
  5888. return;
  5889. }
  5890. let path = resolveTo(
  5891. to,
  5892. JSON.parse(routePathnamesJson),
  5893. locationPathname,
  5894. options.relative === "path"
  5895. );
  5896. if (dataRouterContext == null && basename !== "/") {
  5897. path.pathname = path.pathname === "/" ? basename : joinPaths([basename, path.pathname]);
  5898. }
  5899. (!!options.replace ? navigator.replace : navigator.push)(
  5900. path,
  5901. options.state,
  5902. options
  5903. );
  5904. },
  5905. [
  5906. basename,
  5907. navigator,
  5908. routePathnamesJson,
  5909. locationPathname,
  5910. dataRouterContext
  5911. ]
  5912. );
  5913. return navigate;
  5914. }
  5915. var OutletContext = React2.createContext(null);
  5916. function useOutletContext() {
  5917. return React2.useContext(OutletContext);
  5918. }
  5919. function useOutlet(context) {
  5920. let outlet = React2.useContext(RouteContext).outlet;
  5921. return React2.useMemo(
  5922. () => outlet && React2.createElement(OutletContext.Provider, { value: context }, outlet),
  5923. [outlet, context]
  5924. );
  5925. }
  5926. function useParams() {
  5927. let { matches } = React2.useContext(RouteContext);
  5928. let routeMatch = matches[matches.length - 1];
  5929. return routeMatch ? routeMatch.params : {};
  5930. }
  5931. function useResolvedPath(to, { relative } = {}) {
  5932. let { matches } = React2.useContext(RouteContext);
  5933. let { pathname: locationPathname } = useLocation();
  5934. let routePathnamesJson = JSON.stringify(getResolveToMatches(matches));
  5935. return React2.useMemo(
  5936. () => resolveTo(
  5937. to,
  5938. JSON.parse(routePathnamesJson),
  5939. locationPathname,
  5940. relative === "path"
  5941. ),
  5942. [to, routePathnamesJson, locationPathname, relative]
  5943. );
  5944. }
  5945. function useRoutes(routes, locationArg) {
  5946. return useRoutesImpl(routes, locationArg);
  5947. }
  5948. function useRoutesImpl(routes, locationArg, dataRouterState, unstable_onError, future) {
  5949. var _a;
  5950. invariant(
  5951. useInRouterContext(),
  5952. // TODO: This error is probably because they somehow have 2 versions of the
  5953. // router loaded. We can help them understand how to avoid that.
  5954. `useRoutes() may be used only in the context of a <Router> component.`
  5955. );
  5956. let { navigator } = React2.useContext(NavigationContext);
  5957. let { matches: parentMatches } = React2.useContext(RouteContext);
  5958. let routeMatch = parentMatches[parentMatches.length - 1];
  5959. let parentParams = routeMatch ? routeMatch.params : {};
  5960. let parentPathname = routeMatch ? routeMatch.pathname : "/";
  5961. let parentPathnameBase = routeMatch ? routeMatch.pathnameBase : "/";
  5962. let parentRoute = routeMatch && routeMatch.route;
  5963. if (ENABLE_DEV_WARNINGS) {
  5964. let parentPath = parentRoute && parentRoute.path || "";
  5965. warningOnce(
  5966. parentPathname,
  5967. !parentRoute || parentPath.endsWith("*") || parentPath.endsWith("*?"),
  5968. `You rendered descendant <Routes> (or called \`useRoutes()\`) at "${parentPathname}" (under <Route path="${parentPath}">) but the parent route path has no trailing "*". This means if you navigate deeper, the parent won't match anymore and therefore the child routes will never render.
  5969. Please change the parent <Route path="${parentPath}"> to <Route path="${parentPath === "/" ? "*" : `${parentPath}/*`}">.`
  5970. );
  5971. }
  5972. let locationFromContext = useLocation();
  5973. let location2;
  5974. if (locationArg) {
  5975. let parsedLocationArg = typeof locationArg === "string" ? parsePath(locationArg) : locationArg;
  5976. invariant(
  5977. parentPathnameBase === "/" || ((_a = parsedLocationArg.pathname) == null ? void 0 : _a.startsWith(parentPathnameBase)),
  5978. `When overriding the location using \`<Routes location>\` or \`useRoutes(routes, location)\`, the location pathname must begin with the portion of the URL pathname that was matched by all parent routes. The current pathname base is "${parentPathnameBase}" but pathname "${parsedLocationArg.pathname}" was given in the \`location\` prop.`
  5979. );
  5980. location2 = parsedLocationArg;
  5981. } else {
  5982. location2 = locationFromContext;
  5983. }
  5984. let pathname = location2.pathname || "/";
  5985. let remainingPathname = pathname;
  5986. if (parentPathnameBase !== "/") {
  5987. let parentSegments = parentPathnameBase.replace(/^\//, "").split("/");
  5988. let segments = pathname.replace(/^\//, "").split("/");
  5989. remainingPathname = "/" + segments.slice(parentSegments.length).join("/");
  5990. }
  5991. let matches = matchRoutes(routes, { pathname: remainingPathname });
  5992. if (ENABLE_DEV_WARNINGS) {
  5993. warning(
  5994. parentRoute || matches != null,
  5995. `No routes matched location "${location2.pathname}${location2.search}${location2.hash}" `
  5996. );
  5997. warning(
  5998. matches == null || matches[matches.length - 1].route.element !== void 0 || matches[matches.length - 1].route.Component !== void 0 || matches[matches.length - 1].route.lazy !== void 0,
  5999. `Matched leaf route at location "${location2.pathname}${location2.search}${location2.hash}" does not have an element or Component. This means it will render an <Outlet /> with a null value by default resulting in an "empty" page.`
  6000. );
  6001. }
  6002. let renderedMatches = _renderMatches(
  6003. matches && matches.map(
  6004. (match) => Object.assign({}, match, {
  6005. params: Object.assign({}, parentParams, match.params),
  6006. pathname: joinPaths([
  6007. parentPathnameBase,
  6008. // Re-encode pathnames that were decoded inside matchRoutes.
  6009. // Pre-encode `?` and `#` ahead of `encodeLocation` because it uses
  6010. // `new URL()` internally and we need to prevent it from treating
  6011. // them as separators
  6012. navigator.encodeLocation ? navigator.encodeLocation(
  6013. match.pathname.replace(/\?/g, "%3F").replace(/#/g, "%23")
  6014. ).pathname : match.pathname
  6015. ]),
  6016. pathnameBase: match.pathnameBase === "/" ? parentPathnameBase : joinPaths([
  6017. parentPathnameBase,
  6018. // Re-encode pathnames that were decoded inside matchRoutes
  6019. // Pre-encode `?` and `#` ahead of `encodeLocation` because it uses
  6020. // `new URL()` internally and we need to prevent it from treating
  6021. // them as separators
  6022. navigator.encodeLocation ? navigator.encodeLocation(
  6023. match.pathnameBase.replace(/\?/g, "%3F").replace(/#/g, "%23")
  6024. ).pathname : match.pathnameBase
  6025. ])
  6026. })
  6027. ),
  6028. parentMatches,
  6029. dataRouterState,
  6030. unstable_onError,
  6031. future
  6032. );
  6033. if (locationArg && renderedMatches) {
  6034. return React2.createElement(
  6035. LocationContext.Provider,
  6036. {
  6037. value: {
  6038. location: {
  6039. pathname: "/",
  6040. search: "",
  6041. hash: "",
  6042. state: null,
  6043. key: "default",
  6044. ...location2
  6045. },
  6046. navigationType: "POP"
  6047. /* Pop */
  6048. }
  6049. },
  6050. renderedMatches
  6051. );
  6052. }
  6053. return renderedMatches;
  6054. }
  6055. function DefaultErrorComponent() {
  6056. let error = useRouteError();
  6057. let message = isRouteErrorResponse(error) ? `${error.status} ${error.statusText}` : error instanceof Error ? error.message : JSON.stringify(error);
  6058. let stack = error instanceof Error ? error.stack : null;
  6059. let lightgrey = "rgba(200,200,200, 0.5)";
  6060. let preStyles = { padding: "0.5rem", backgroundColor: lightgrey };
  6061. let codeStyles = { padding: "2px 4px", backgroundColor: lightgrey };
  6062. let devInfo = null;
  6063. if (ENABLE_DEV_WARNINGS) {
  6064. console.error(
  6065. "Error handled by React Router default ErrorBoundary:",
  6066. error
  6067. );
  6068. devInfo = React2.createElement(React2.Fragment, null, React2.createElement("p", null, "💿 Hey developer 👋"), React2.createElement("p", null, "You can provide a way better UX than this when your app throws errors by providing your own ", React2.createElement("code", { style: codeStyles }, "ErrorBoundary"), " or", " ", React2.createElement("code", { style: codeStyles }, "errorElement"), " prop on your route."));
  6069. }
  6070. return React2.createElement(React2.Fragment, null, React2.createElement("h2", null, "Unexpected Application Error!"), React2.createElement("h3", { style: { fontStyle: "italic" } }, message), stack ? React2.createElement("pre", { style: preStyles }, stack) : null, devInfo);
  6071. }
  6072. var defaultErrorElement = React2.createElement(DefaultErrorComponent, null);
  6073. var RenderErrorBoundary = class extends React2.Component {
  6074. constructor(props) {
  6075. super(props);
  6076. this.state = {
  6077. location: props.location,
  6078. revalidation: props.revalidation,
  6079. error: props.error
  6080. };
  6081. }
  6082. static getDerivedStateFromError(error) {
  6083. return { error };
  6084. }
  6085. static getDerivedStateFromProps(props, state) {
  6086. if (state.location !== props.location || state.revalidation !== "idle" && props.revalidation === "idle") {
  6087. return {
  6088. error: props.error,
  6089. location: props.location,
  6090. revalidation: props.revalidation
  6091. };
  6092. }
  6093. return {
  6094. error: props.error !== void 0 ? props.error : state.error,
  6095. location: state.location,
  6096. revalidation: props.revalidation || state.revalidation
  6097. };
  6098. }
  6099. componentDidCatch(error, errorInfo) {
  6100. if (this.props.onError) {
  6101. this.props.onError(error, errorInfo);
  6102. } else {
  6103. console.error(
  6104. "React Router caught the following error during render",
  6105. error
  6106. );
  6107. }
  6108. }
  6109. render() {
  6110. return this.state.error !== void 0 ? React2.createElement(RouteContext.Provider, { value: this.props.routeContext }, React2.createElement(
  6111. RouteErrorContext.Provider,
  6112. {
  6113. value: this.state.error,
  6114. children: this.props.component
  6115. }
  6116. )) : this.props.children;
  6117. }
  6118. };
  6119. function RenderedRoute({ routeContext, match, children }) {
  6120. let dataRouterContext = React2.useContext(DataRouterContext);
  6121. if (dataRouterContext && dataRouterContext.static && dataRouterContext.staticContext && (match.route.errorElement || match.route.ErrorBoundary)) {
  6122. dataRouterContext.staticContext._deepestRenderedBoundaryId = match.route.id;
  6123. }
  6124. return React2.createElement(RouteContext.Provider, { value: routeContext }, children);
  6125. }
  6126. function _renderMatches(matches, parentMatches = [], dataRouterState = null, unstable_onError = null, future = null) {
  6127. if (matches == null) {
  6128. if (!dataRouterState) {
  6129. return null;
  6130. }
  6131. if (dataRouterState.errors) {
  6132. matches = dataRouterState.matches;
  6133. } else if (parentMatches.length === 0 && !dataRouterState.initialized && dataRouterState.matches.length > 0) {
  6134. matches = dataRouterState.matches;
  6135. } else {
  6136. return null;
  6137. }
  6138. }
  6139. let renderedMatches = matches;
  6140. let errors = dataRouterState == null ? void 0 : dataRouterState.errors;
  6141. if (errors != null) {
  6142. let errorIndex = renderedMatches.findIndex(
  6143. (m) => m.route.id && (errors == null ? void 0 : errors[m.route.id]) !== void 0
  6144. );
  6145. invariant(
  6146. errorIndex >= 0,
  6147. `Could not find a matching route for errors on route IDs: ${Object.keys(
  6148. errors
  6149. ).join(",")}`
  6150. );
  6151. renderedMatches = renderedMatches.slice(
  6152. 0,
  6153. Math.min(renderedMatches.length, errorIndex + 1)
  6154. );
  6155. }
  6156. let renderFallback = false;
  6157. let fallbackIndex = -1;
  6158. if (dataRouterState) {
  6159. for (let i = 0; i < renderedMatches.length; i++) {
  6160. let match = renderedMatches[i];
  6161. if (match.route.HydrateFallback || match.route.hydrateFallbackElement) {
  6162. fallbackIndex = i;
  6163. }
  6164. if (match.route.id) {
  6165. let { loaderData, errors: errors2 } = dataRouterState;
  6166. let needsToRunLoader = match.route.loader && !loaderData.hasOwnProperty(match.route.id) && (!errors2 || errors2[match.route.id] === void 0);
  6167. if (match.route.lazy || needsToRunLoader) {
  6168. renderFallback = true;
  6169. if (fallbackIndex >= 0) {
  6170. renderedMatches = renderedMatches.slice(0, fallbackIndex + 1);
  6171. } else {
  6172. renderedMatches = [renderedMatches[0]];
  6173. }
  6174. break;
  6175. }
  6176. }
  6177. }
  6178. }
  6179. let onError = dataRouterState && unstable_onError ? (error, errorInfo) => {
  6180. var _a, _b;
  6181. unstable_onError(error, {
  6182. location: dataRouterState.location,
  6183. params: ((_b = (_a = dataRouterState.matches) == null ? void 0 : _a[0]) == null ? void 0 : _b.params) ?? {},
  6184. unstable_pattern: getRoutePattern(dataRouterState.matches),
  6185. errorInfo
  6186. });
  6187. } : void 0;
  6188. return renderedMatches.reduceRight(
  6189. (outlet, match, index) => {
  6190. let error;
  6191. let shouldRenderHydrateFallback = false;
  6192. let errorElement = null;
  6193. let hydrateFallbackElement = null;
  6194. if (dataRouterState) {
  6195. error = errors && match.route.id ? errors[match.route.id] : void 0;
  6196. errorElement = match.route.errorElement || defaultErrorElement;
  6197. if (renderFallback) {
  6198. if (fallbackIndex < 0 && index === 0) {
  6199. warningOnce(
  6200. "route-fallback",
  6201. false,
  6202. "No `HydrateFallback` element provided to render during initial hydration"
  6203. );
  6204. shouldRenderHydrateFallback = true;
  6205. hydrateFallbackElement = null;
  6206. } else if (fallbackIndex === index) {
  6207. shouldRenderHydrateFallback = true;
  6208. hydrateFallbackElement = match.route.hydrateFallbackElement || null;
  6209. }
  6210. }
  6211. }
  6212. let matches2 = parentMatches.concat(renderedMatches.slice(0, index + 1));
  6213. let getChildren = () => {
  6214. let children;
  6215. if (error) {
  6216. children = errorElement;
  6217. } else if (shouldRenderHydrateFallback) {
  6218. children = hydrateFallbackElement;
  6219. } else if (match.route.Component) {
  6220. children = React2.createElement(match.route.Component, null);
  6221. } else if (match.route.element) {
  6222. children = match.route.element;
  6223. } else {
  6224. children = outlet;
  6225. }
  6226. return React2.createElement(
  6227. RenderedRoute,
  6228. {
  6229. match,
  6230. routeContext: {
  6231. outlet,
  6232. matches: matches2,
  6233. isDataRoute: dataRouterState != null
  6234. },
  6235. children
  6236. }
  6237. );
  6238. };
  6239. return dataRouterState && (match.route.ErrorBoundary || match.route.errorElement || index === 0) ? React2.createElement(
  6240. RenderErrorBoundary,
  6241. {
  6242. location: dataRouterState.location,
  6243. revalidation: dataRouterState.revalidation,
  6244. component: errorElement,
  6245. error,
  6246. children: getChildren(),
  6247. routeContext: { outlet: null, matches: matches2, isDataRoute: true },
  6248. onError
  6249. }
  6250. ) : getChildren();
  6251. },
  6252. null
  6253. );
  6254. }
  6255. function getDataRouterConsoleError(hookName) {
  6256. return `${hookName} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`;
  6257. }
  6258. function useDataRouterContext(hookName) {
  6259. let ctx = React2.useContext(DataRouterContext);
  6260. invariant(ctx, getDataRouterConsoleError(hookName));
  6261. return ctx;
  6262. }
  6263. function useDataRouterState(hookName) {
  6264. let state = React2.useContext(DataRouterStateContext);
  6265. invariant(state, getDataRouterConsoleError(hookName));
  6266. return state;
  6267. }
  6268. function useRouteContext(hookName) {
  6269. let route = React2.useContext(RouteContext);
  6270. invariant(route, getDataRouterConsoleError(hookName));
  6271. return route;
  6272. }
  6273. function useCurrentRouteId(hookName) {
  6274. let route = useRouteContext(hookName);
  6275. let thisRoute = route.matches[route.matches.length - 1];
  6276. invariant(
  6277. thisRoute.route.id,
  6278. `${hookName} can only be used on routes that contain a unique "id"`
  6279. );
  6280. return thisRoute.route.id;
  6281. }
  6282. function useRouteId() {
  6283. return useCurrentRouteId(
  6284. "useRouteId"
  6285. /* UseRouteId */
  6286. );
  6287. }
  6288. function useNavigation() {
  6289. let state = useDataRouterState(
  6290. "useNavigation"
  6291. /* UseNavigation */
  6292. );
  6293. return state.navigation;
  6294. }
  6295. function useRevalidator() {
  6296. let dataRouterContext = useDataRouterContext(
  6297. "useRevalidator"
  6298. /* UseRevalidator */
  6299. );
  6300. let state = useDataRouterState(
  6301. "useRevalidator"
  6302. /* UseRevalidator */
  6303. );
  6304. let revalidate = React2.useCallback(async () => {
  6305. await dataRouterContext.router.revalidate();
  6306. }, [dataRouterContext.router]);
  6307. return React2.useMemo(
  6308. () => ({ revalidate, state: state.revalidation }),
  6309. [revalidate, state.revalidation]
  6310. );
  6311. }
  6312. function useMatches() {
  6313. let { matches, loaderData } = useDataRouterState(
  6314. "useMatches"
  6315. /* UseMatches */
  6316. );
  6317. return React2.useMemo(
  6318. () => matches.map((m) => convertRouteMatchToUiMatch(m, loaderData)),
  6319. [matches, loaderData]
  6320. );
  6321. }
  6322. function useLoaderData() {
  6323. let state = useDataRouterState(
  6324. "useLoaderData"
  6325. /* UseLoaderData */
  6326. );
  6327. let routeId = useCurrentRouteId(
  6328. "useLoaderData"
  6329. /* UseLoaderData */
  6330. );
  6331. return state.loaderData[routeId];
  6332. }
  6333. function useRouteLoaderData(routeId) {
  6334. let state = useDataRouterState(
  6335. "useRouteLoaderData"
  6336. /* UseRouteLoaderData */
  6337. );
  6338. return state.loaderData[routeId];
  6339. }
  6340. function useActionData() {
  6341. let state = useDataRouterState(
  6342. "useActionData"
  6343. /* UseActionData */
  6344. );
  6345. let routeId = useCurrentRouteId(
  6346. "useLoaderData"
  6347. /* UseLoaderData */
  6348. );
  6349. return state.actionData ? state.actionData[routeId] : void 0;
  6350. }
  6351. function useRouteError() {
  6352. var _a;
  6353. let error = React2.useContext(RouteErrorContext);
  6354. let state = useDataRouterState(
  6355. "useRouteError"
  6356. /* UseRouteError */
  6357. );
  6358. let routeId = useCurrentRouteId(
  6359. "useRouteError"
  6360. /* UseRouteError */
  6361. );
  6362. if (error !== void 0) {
  6363. return error;
  6364. }
  6365. return (_a = state.errors) == null ? void 0 : _a[routeId];
  6366. }
  6367. function useAsyncValue() {
  6368. let value = React2.useContext(AwaitContext);
  6369. return value == null ? void 0 : value._data;
  6370. }
  6371. function useAsyncError() {
  6372. let value = React2.useContext(AwaitContext);
  6373. return value == null ? void 0 : value._error;
  6374. }
  6375. var blockerId = 0;
  6376. function useBlocker(shouldBlock) {
  6377. let { router: router2, basename } = useDataRouterContext(
  6378. "useBlocker"
  6379. /* UseBlocker */
  6380. );
  6381. let state = useDataRouterState(
  6382. "useBlocker"
  6383. /* UseBlocker */
  6384. );
  6385. let [blockerKey, setBlockerKey] = React2.useState("");
  6386. let blockerFunction = React2.useCallback(
  6387. (arg) => {
  6388. if (typeof shouldBlock !== "function") {
  6389. return !!shouldBlock;
  6390. }
  6391. if (basename === "/") {
  6392. return shouldBlock(arg);
  6393. }
  6394. let { currentLocation, nextLocation, historyAction } = arg;
  6395. return shouldBlock({
  6396. currentLocation: {
  6397. ...currentLocation,
  6398. pathname: stripBasename(currentLocation.pathname, basename) || currentLocation.pathname
  6399. },
  6400. nextLocation: {
  6401. ...nextLocation,
  6402. pathname: stripBasename(nextLocation.pathname, basename) || nextLocation.pathname
  6403. },
  6404. historyAction
  6405. });
  6406. },
  6407. [basename, shouldBlock]
  6408. );
  6409. React2.useEffect(() => {
  6410. let key = String(++blockerId);
  6411. setBlockerKey(key);
  6412. return () => router2.deleteBlocker(key);
  6413. }, [router2]);
  6414. React2.useEffect(() => {
  6415. if (blockerKey !== "") {
  6416. router2.getBlocker(blockerKey, blockerFunction);
  6417. }
  6418. }, [router2, blockerKey, blockerFunction]);
  6419. return blockerKey && state.blockers.has(blockerKey) ? state.blockers.get(blockerKey) : IDLE_BLOCKER;
  6420. }
  6421. function useNavigateStable() {
  6422. let { router: router2 } = useDataRouterContext(
  6423. "useNavigate"
  6424. /* UseNavigateStable */
  6425. );
  6426. let id = useCurrentRouteId(
  6427. "useNavigate"
  6428. /* UseNavigateStable */
  6429. );
  6430. let activeRef = React2.useRef(false);
  6431. useIsomorphicLayoutEffect(() => {
  6432. activeRef.current = true;
  6433. });
  6434. let navigate = React2.useCallback(
  6435. async (to, options = {}) => {
  6436. warning(activeRef.current, navigateEffectWarning);
  6437. if (!activeRef.current) return;
  6438. if (typeof to === "number") {
  6439. await router2.navigate(to);
  6440. } else {
  6441. await router2.navigate(to, { fromRouteId: id, ...options });
  6442. }
  6443. },
  6444. [router2, id]
  6445. );
  6446. return navigate;
  6447. }
  6448. var alreadyWarned = {};
  6449. function warningOnce(key, cond, message) {
  6450. if (!cond && !alreadyWarned[key]) {
  6451. alreadyWarned[key] = true;
  6452. warning(false, message);
  6453. }
  6454. }
  6455. function useRoute(...args) {
  6456. var _a;
  6457. const currentRouteId = useCurrentRouteId(
  6458. "useRoute"
  6459. /* UseRoute */
  6460. );
  6461. const id = args[0] ?? currentRouteId;
  6462. const state = useDataRouterState(
  6463. "useRoute"
  6464. /* UseRoute */
  6465. );
  6466. const route = state.matches.find(({ route: route2 }) => route2.id === id);
  6467. if (route === void 0) return void 0;
  6468. return {
  6469. handle: route.route.handle,
  6470. loaderData: state.loaderData[id],
  6471. actionData: (_a = state.actionData) == null ? void 0 : _a[id]
  6472. };
  6473. }
  6474. var alreadyWarned2 = {};
  6475. function warnOnce(condition, message) {
  6476. if (!condition && !alreadyWarned2[message]) {
  6477. alreadyWarned2[message] = true;
  6478. console.warn(message);
  6479. }
  6480. }
  6481. var USE_OPTIMISTIC = "useOptimistic";
  6482. var useOptimisticImpl = React3[USE_OPTIMISTIC];
  6483. var stableUseOptimisticSetter = () => void 0;
  6484. function useOptimisticSafe(val) {
  6485. if (useOptimisticImpl) {
  6486. return useOptimisticImpl(val);
  6487. } else {
  6488. return [val, stableUseOptimisticSetter];
  6489. }
  6490. }
  6491. function mapRouteProperties(route) {
  6492. let updates = {
  6493. // Note: this check also occurs in createRoutesFromChildren so update
  6494. // there if you change this -- please and thank you!
  6495. hasErrorBoundary: route.hasErrorBoundary || route.ErrorBoundary != null || route.errorElement != null
  6496. };
  6497. if (route.Component) {
  6498. if (ENABLE_DEV_WARNINGS) {
  6499. if (route.element) {
  6500. warning(
  6501. false,
  6502. "You should not include both `Component` and `element` on your route - `Component` will be used."
  6503. );
  6504. }
  6505. }
  6506. Object.assign(updates, {
  6507. element: React3.createElement(route.Component),
  6508. Component: void 0
  6509. });
  6510. }
  6511. if (route.HydrateFallback) {
  6512. if (ENABLE_DEV_WARNINGS) {
  6513. if (route.hydrateFallbackElement) {
  6514. warning(
  6515. false,
  6516. "You should not include both `HydrateFallback` and `hydrateFallbackElement` on your route - `HydrateFallback` will be used."
  6517. );
  6518. }
  6519. }
  6520. Object.assign(updates, {
  6521. hydrateFallbackElement: React3.createElement(route.HydrateFallback),
  6522. HydrateFallback: void 0
  6523. });
  6524. }
  6525. if (route.ErrorBoundary) {
  6526. if (ENABLE_DEV_WARNINGS) {
  6527. if (route.errorElement) {
  6528. warning(
  6529. false,
  6530. "You should not include both `ErrorBoundary` and `errorElement` on your route - `ErrorBoundary` will be used."
  6531. );
  6532. }
  6533. }
  6534. Object.assign(updates, {
  6535. errorElement: React3.createElement(route.ErrorBoundary),
  6536. ErrorBoundary: void 0
  6537. });
  6538. }
  6539. return updates;
  6540. }
  6541. var hydrationRouteProperties = [
  6542. "HydrateFallback",
  6543. "hydrateFallbackElement"
  6544. ];
  6545. function createMemoryRouter(routes, opts) {
  6546. return createRouter({
  6547. basename: opts == null ? void 0 : opts.basename,
  6548. getContext: opts == null ? void 0 : opts.getContext,
  6549. future: opts == null ? void 0 : opts.future,
  6550. history: createMemoryHistory({
  6551. initialEntries: opts == null ? void 0 : opts.initialEntries,
  6552. initialIndex: opts == null ? void 0 : opts.initialIndex
  6553. }),
  6554. hydrationData: opts == null ? void 0 : opts.hydrationData,
  6555. routes,
  6556. hydrationRouteProperties,
  6557. mapRouteProperties,
  6558. dataStrategy: opts == null ? void 0 : opts.dataStrategy,
  6559. patchRoutesOnNavigation: opts == null ? void 0 : opts.patchRoutesOnNavigation,
  6560. unstable_instrumentations: opts == null ? void 0 : opts.unstable_instrumentations
  6561. }).initialize();
  6562. }
  6563. var Deferred = class {
  6564. constructor() {
  6565. this.status = "pending";
  6566. this.promise = new Promise((resolve, reject) => {
  6567. this.resolve = (value) => {
  6568. if (this.status === "pending") {
  6569. this.status = "resolved";
  6570. resolve(value);
  6571. }
  6572. };
  6573. this.reject = (reason) => {
  6574. if (this.status === "pending") {
  6575. this.status = "rejected";
  6576. reject(reason);
  6577. }
  6578. };
  6579. });
  6580. }
  6581. };
  6582. function RouterProvider({
  6583. router: router2,
  6584. flushSync: reactDomFlushSyncImpl,
  6585. unstable_onError,
  6586. unstable_useTransitions
  6587. }) {
  6588. let [_state, setStateImpl] = React3.useState(router2.state);
  6589. let [state, setOptimisticState] = useOptimisticSafe(_state);
  6590. let [pendingState, setPendingState] = React3.useState();
  6591. let [vtContext, setVtContext] = React3.useState({
  6592. isTransitioning: false
  6593. });
  6594. let [renderDfd, setRenderDfd] = React3.useState();
  6595. let [transition, setTransition] = React3.useState();
  6596. let [interruption, setInterruption] = React3.useState();
  6597. let fetcherData = React3.useRef(/* @__PURE__ */ new Map());
  6598. let setState = React3.useCallback(
  6599. (newState, { deletedFetchers, newErrors, flushSync: flushSync3, viewTransitionOpts }) => {
  6600. if (newErrors && unstable_onError) {
  6601. Object.values(newErrors).forEach(
  6602. (error) => {
  6603. var _a;
  6604. return unstable_onError(error, {
  6605. location: newState.location,
  6606. params: ((_a = newState.matches[0]) == null ? void 0 : _a.params) ?? {},
  6607. unstable_pattern: getRoutePattern(newState.matches)
  6608. });
  6609. }
  6610. );
  6611. }
  6612. newState.fetchers.forEach((fetcher, key) => {
  6613. if (fetcher.data !== void 0) {
  6614. fetcherData.current.set(key, fetcher.data);
  6615. }
  6616. });
  6617. deletedFetchers.forEach((key) => fetcherData.current.delete(key));
  6618. warnOnce(
  6619. flushSync3 === false || reactDomFlushSyncImpl != null,
  6620. 'You provided the `flushSync` option to a router update, but you are not using the `<RouterProvider>` from `react-router/dom` so `ReactDOM.flushSync()` is unavailable. Please update your app to `import { RouterProvider } from "react-router/dom"` and ensure you have `react-dom` installed as a dependency to use the `flushSync` option.'
  6621. );
  6622. let isViewTransitionAvailable = router2.window != null && router2.window.document != null && typeof router2.window.document.startViewTransition === "function";
  6623. warnOnce(
  6624. viewTransitionOpts == null || isViewTransitionAvailable,
  6625. "You provided the `viewTransition` option to a router update, but you do not appear to be running in a DOM environment as `window.startViewTransition` is not available."
  6626. );
  6627. if (!viewTransitionOpts || !isViewTransitionAvailable) {
  6628. if (reactDomFlushSyncImpl && flushSync3) {
  6629. reactDomFlushSyncImpl(() => setStateImpl(newState));
  6630. } else if (unstable_useTransitions === false) {
  6631. setStateImpl(newState);
  6632. } else {
  6633. React3.startTransition(() => {
  6634. if (unstable_useTransitions === true) {
  6635. setOptimisticState((s) => getOptimisticRouterState(s, newState));
  6636. }
  6637. setStateImpl(newState);
  6638. });
  6639. }
  6640. return;
  6641. }
  6642. if (reactDomFlushSyncImpl && flushSync3) {
  6643. reactDomFlushSyncImpl(() => {
  6644. if (transition) {
  6645. renderDfd == null ? void 0 : renderDfd.resolve();
  6646. transition.skipTransition();
  6647. }
  6648. setVtContext({
  6649. isTransitioning: true,
  6650. flushSync: true,
  6651. currentLocation: viewTransitionOpts.currentLocation,
  6652. nextLocation: viewTransitionOpts.nextLocation
  6653. });
  6654. });
  6655. let t = router2.window.document.startViewTransition(() => {
  6656. reactDomFlushSyncImpl(() => setStateImpl(newState));
  6657. });
  6658. t.finished.finally(() => {
  6659. reactDomFlushSyncImpl(() => {
  6660. setRenderDfd(void 0);
  6661. setTransition(void 0);
  6662. setPendingState(void 0);
  6663. setVtContext({ isTransitioning: false });
  6664. });
  6665. });
  6666. reactDomFlushSyncImpl(() => setTransition(t));
  6667. return;
  6668. }
  6669. if (transition) {
  6670. renderDfd == null ? void 0 : renderDfd.resolve();
  6671. transition.skipTransition();
  6672. setInterruption({
  6673. state: newState,
  6674. currentLocation: viewTransitionOpts.currentLocation,
  6675. nextLocation: viewTransitionOpts.nextLocation
  6676. });
  6677. } else {
  6678. setPendingState(newState);
  6679. setVtContext({
  6680. isTransitioning: true,
  6681. flushSync: false,
  6682. currentLocation: viewTransitionOpts.currentLocation,
  6683. nextLocation: viewTransitionOpts.nextLocation
  6684. });
  6685. }
  6686. },
  6687. [
  6688. router2.window,
  6689. reactDomFlushSyncImpl,
  6690. transition,
  6691. renderDfd,
  6692. unstable_useTransitions,
  6693. setOptimisticState,
  6694. unstable_onError
  6695. ]
  6696. );
  6697. React3.useLayoutEffect(() => router2.subscribe(setState), [router2, setState]);
  6698. React3.useEffect(() => {
  6699. if (vtContext.isTransitioning && !vtContext.flushSync) {
  6700. setRenderDfd(new Deferred());
  6701. }
  6702. }, [vtContext]);
  6703. React3.useEffect(() => {
  6704. if (renderDfd && pendingState && router2.window) {
  6705. let newState = pendingState;
  6706. let renderPromise = renderDfd.promise;
  6707. let transition2 = router2.window.document.startViewTransition(async () => {
  6708. if (unstable_useTransitions === false) {
  6709. setStateImpl(newState);
  6710. } else {
  6711. React3.startTransition(() => {
  6712. if (unstable_useTransitions === true) {
  6713. setOptimisticState((s) => getOptimisticRouterState(s, newState));
  6714. }
  6715. setStateImpl(newState);
  6716. });
  6717. }
  6718. await renderPromise;
  6719. });
  6720. transition2.finished.finally(() => {
  6721. setRenderDfd(void 0);
  6722. setTransition(void 0);
  6723. setPendingState(void 0);
  6724. setVtContext({ isTransitioning: false });
  6725. });
  6726. setTransition(transition2);
  6727. }
  6728. }, [
  6729. pendingState,
  6730. renderDfd,
  6731. router2.window,
  6732. unstable_useTransitions,
  6733. setOptimisticState
  6734. ]);
  6735. React3.useEffect(() => {
  6736. if (renderDfd && pendingState && state.location.key === pendingState.location.key) {
  6737. renderDfd.resolve();
  6738. }
  6739. }, [renderDfd, transition, state.location, pendingState]);
  6740. React3.useEffect(() => {
  6741. if (!vtContext.isTransitioning && interruption) {
  6742. setPendingState(interruption.state);
  6743. setVtContext({
  6744. isTransitioning: true,
  6745. flushSync: false,
  6746. currentLocation: interruption.currentLocation,
  6747. nextLocation: interruption.nextLocation
  6748. });
  6749. setInterruption(void 0);
  6750. }
  6751. }, [vtContext.isTransitioning, interruption]);
  6752. let navigator = React3.useMemo(() => {
  6753. return {
  6754. createHref: router2.createHref,
  6755. encodeLocation: router2.encodeLocation,
  6756. go: (n) => router2.navigate(n),
  6757. push: (to, state2, opts) => router2.navigate(to, {
  6758. state: state2,
  6759. preventScrollReset: opts == null ? void 0 : opts.preventScrollReset
  6760. }),
  6761. replace: (to, state2, opts) => router2.navigate(to, {
  6762. replace: true,
  6763. state: state2,
  6764. preventScrollReset: opts == null ? void 0 : opts.preventScrollReset
  6765. })
  6766. };
  6767. }, [router2]);
  6768. let basename = router2.basename || "/";
  6769. let dataRouterContext = React3.useMemo(
  6770. () => ({
  6771. router: router2,
  6772. navigator,
  6773. static: false,
  6774. basename,
  6775. unstable_onError
  6776. }),
  6777. [router2, navigator, basename, unstable_onError]
  6778. );
  6779. return React3.createElement(React3.Fragment, null, React3.createElement(DataRouterContext.Provider, { value: dataRouterContext }, React3.createElement(DataRouterStateContext.Provider, { value: state }, React3.createElement(FetchersContext.Provider, { value: fetcherData.current }, React3.createElement(ViewTransitionContext.Provider, { value: vtContext }, React3.createElement(
  6780. Router,
  6781. {
  6782. basename,
  6783. location: state.location,
  6784. navigationType: state.historyAction,
  6785. navigator,
  6786. unstable_useTransitions: unstable_useTransitions === true
  6787. },
  6788. React3.createElement(
  6789. MemoizedDataRoutes,
  6790. {
  6791. routes: router2.routes,
  6792. future: router2.future,
  6793. state,
  6794. unstable_onError
  6795. }
  6796. )
  6797. ))))), null);
  6798. }
  6799. function getOptimisticRouterState(currentState, newState) {
  6800. return {
  6801. // Don't surface "current location specific" stuff mid-navigation
  6802. // (historyAction, location, matches, loaderData, errors, initialized,
  6803. // restoreScroll, preventScrollReset, blockers, etc.)
  6804. ...currentState,
  6805. // Only surface "pending/in-flight stuff"
  6806. // (navigation, revalidation, actionData, fetchers, )
  6807. navigation: newState.navigation.state !== "idle" ? newState.navigation : currentState.navigation,
  6808. revalidation: newState.revalidation !== "idle" ? newState.revalidation : currentState.revalidation,
  6809. actionData: newState.navigation.state !== "submitting" ? newState.actionData : currentState.actionData,
  6810. fetchers: newState.fetchers
  6811. };
  6812. }
  6813. var MemoizedDataRoutes = React3.memo(DataRoutes);
  6814. function DataRoutes({
  6815. routes,
  6816. future,
  6817. state,
  6818. unstable_onError
  6819. }) {
  6820. return useRoutesImpl(routes, void 0, state, unstable_onError, future);
  6821. }
  6822. function MemoryRouter({
  6823. basename,
  6824. children,
  6825. initialEntries,
  6826. initialIndex,
  6827. unstable_useTransitions
  6828. }) {
  6829. let historyRef = React3.useRef();
  6830. if (historyRef.current == null) {
  6831. historyRef.current = createMemoryHistory({
  6832. initialEntries,
  6833. initialIndex,
  6834. v5Compat: true
  6835. });
  6836. }
  6837. let history = historyRef.current;
  6838. let [state, setStateImpl] = React3.useState({
  6839. action: history.action,
  6840. location: history.location
  6841. });
  6842. let setState = React3.useCallback(
  6843. (newState) => {
  6844. if (unstable_useTransitions === false) {
  6845. setStateImpl(newState);
  6846. } else {
  6847. React3.startTransition(() => setStateImpl(newState));
  6848. }
  6849. },
  6850. [unstable_useTransitions]
  6851. );
  6852. React3.useLayoutEffect(() => history.listen(setState), [history, setState]);
  6853. return React3.createElement(
  6854. Router,
  6855. {
  6856. basename,
  6857. children,
  6858. location: state.location,
  6859. navigationType: state.action,
  6860. navigator: history,
  6861. unstable_useTransitions: unstable_useTransitions === true
  6862. }
  6863. );
  6864. }
  6865. function Navigate({
  6866. to,
  6867. replace: replace2,
  6868. state,
  6869. relative
  6870. }) {
  6871. invariant(
  6872. useInRouterContext(),
  6873. // TODO: This error is probably because they somehow have 2 versions of
  6874. // the router loaded. We can help them understand how to avoid that.
  6875. `<Navigate> may be used only in the context of a <Router> component.`
  6876. );
  6877. let { static: isStatic } = React3.useContext(NavigationContext);
  6878. warning(
  6879. !isStatic,
  6880. `<Navigate> must not be used on the initial render in a <StaticRouter>. This is a no-op, but you should modify your code so the <Navigate> is only ever rendered in response to some user interaction or state change.`
  6881. );
  6882. let { matches } = React3.useContext(RouteContext);
  6883. let { pathname: locationPathname } = useLocation();
  6884. let navigate = useNavigate();
  6885. let path = resolveTo(
  6886. to,
  6887. getResolveToMatches(matches),
  6888. locationPathname,
  6889. relative === "path"
  6890. );
  6891. let jsonPath = JSON.stringify(path);
  6892. React3.useEffect(() => {
  6893. navigate(JSON.parse(jsonPath), { replace: replace2, state, relative });
  6894. }, [navigate, jsonPath, relative, replace2, state]);
  6895. return null;
  6896. }
  6897. function Outlet(props) {
  6898. return useOutlet(props.context);
  6899. }
  6900. function Route(props) {
  6901. invariant(
  6902. false,
  6903. `A <Route> is only ever to be used as the child of <Routes> element, never rendered directly. Please wrap your <Route> in a <Routes>.`
  6904. );
  6905. }
  6906. function Router({
  6907. basename: basenameProp = "/",
  6908. children = null,
  6909. location: locationProp,
  6910. navigationType = "POP",
  6911. navigator,
  6912. static: staticProp = false,
  6913. unstable_useTransitions
  6914. }) {
  6915. invariant(
  6916. !useInRouterContext(),
  6917. `You cannot render a <Router> inside another <Router>. You should never have more than one in your app.`
  6918. );
  6919. let basename = basenameProp.replace(/^\/*/, "/");
  6920. let navigationContext = React3.useMemo(
  6921. () => ({
  6922. basename,
  6923. navigator,
  6924. static: staticProp,
  6925. unstable_useTransitions,
  6926. future: {}
  6927. }),
  6928. [basename, navigator, staticProp, unstable_useTransitions]
  6929. );
  6930. if (typeof locationProp === "string") {
  6931. locationProp = parsePath(locationProp);
  6932. }
  6933. let {
  6934. pathname = "/",
  6935. search = "",
  6936. hash = "",
  6937. state = null,
  6938. key = "default"
  6939. } = locationProp;
  6940. let locationContext = React3.useMemo(() => {
  6941. let trailingPathname = stripBasename(pathname, basename);
  6942. if (trailingPathname == null) {
  6943. return null;
  6944. }
  6945. return {
  6946. location: {
  6947. pathname: trailingPathname,
  6948. search,
  6949. hash,
  6950. state,
  6951. key
  6952. },
  6953. navigationType
  6954. };
  6955. }, [basename, pathname, search, hash, state, key, navigationType]);
  6956. warning(
  6957. locationContext != null,
  6958. `<Router basename="${basename}"> is not able to match the URL "${pathname}${search}${hash}" because it does not start with the basename, so the <Router> won't render anything.`
  6959. );
  6960. if (locationContext == null) {
  6961. return null;
  6962. }
  6963. return React3.createElement(NavigationContext.Provider, { value: navigationContext }, React3.createElement(LocationContext.Provider, { children, value: locationContext }));
  6964. }
  6965. function Routes({
  6966. children,
  6967. location: location2
  6968. }) {
  6969. return useRoutes(createRoutesFromChildren(children), location2);
  6970. }
  6971. function Await({
  6972. children,
  6973. errorElement,
  6974. resolve
  6975. }) {
  6976. let dataRouterContext = React3.useContext(DataRouterContext);
  6977. let dataRouterStateContext = React3.useContext(DataRouterStateContext);
  6978. let onError = React3.useCallback(
  6979. (error, errorInfo) => {
  6980. var _a;
  6981. if (dataRouterContext && dataRouterContext.unstable_onError && dataRouterStateContext) {
  6982. dataRouterContext.unstable_onError(error, {
  6983. location: dataRouterStateContext.location,
  6984. params: ((_a = dataRouterStateContext.matches[0]) == null ? void 0 : _a.params) || {},
  6985. unstable_pattern: getRoutePattern(dataRouterStateContext.matches),
  6986. errorInfo
  6987. });
  6988. }
  6989. },
  6990. [dataRouterContext, dataRouterStateContext]
  6991. );
  6992. return React3.createElement(
  6993. AwaitErrorBoundary,
  6994. {
  6995. resolve,
  6996. errorElement,
  6997. onError
  6998. },
  6999. React3.createElement(ResolveAwait, null, children)
  7000. );
  7001. }
  7002. var AwaitErrorBoundary = class extends React3.Component {
  7003. constructor(props) {
  7004. super(props);
  7005. this.state = { error: null };
  7006. }
  7007. static getDerivedStateFromError(error) {
  7008. return { error };
  7009. }
  7010. componentDidCatch(error, errorInfo) {
  7011. if (this.props.onError) {
  7012. this.props.onError(error, errorInfo);
  7013. } else {
  7014. console.error(
  7015. "<Await> caught the following error during render",
  7016. error,
  7017. errorInfo
  7018. );
  7019. }
  7020. }
  7021. render() {
  7022. let { children, errorElement, resolve } = this.props;
  7023. let promise = null;
  7024. let status = 0;
  7025. if (!(resolve instanceof Promise)) {
  7026. status = 1;
  7027. promise = Promise.resolve();
  7028. Object.defineProperty(promise, "_tracked", { get: () => true });
  7029. Object.defineProperty(promise, "_data", { get: () => resolve });
  7030. } else if (this.state.error) {
  7031. status = 2;
  7032. let renderError = this.state.error;
  7033. promise = Promise.reject().catch(() => {
  7034. });
  7035. Object.defineProperty(promise, "_tracked", { get: () => true });
  7036. Object.defineProperty(promise, "_error", { get: () => renderError });
  7037. } else if (resolve._tracked) {
  7038. promise = resolve;
  7039. status = "_error" in promise ? 2 : "_data" in promise ? 1 : 0;
  7040. } else {
  7041. status = 0;
  7042. Object.defineProperty(resolve, "_tracked", { get: () => true });
  7043. promise = resolve.then(
  7044. (data2) => Object.defineProperty(resolve, "_data", { get: () => data2 }),
  7045. (error) => {
  7046. var _a, _b;
  7047. (_b = (_a = this.props).onError) == null ? void 0 : _b.call(_a, error);
  7048. Object.defineProperty(resolve, "_error", { get: () => error });
  7049. }
  7050. );
  7051. }
  7052. if (status === 2 && !errorElement) {
  7053. throw promise._error;
  7054. }
  7055. if (status === 2) {
  7056. return React3.createElement(AwaitContext.Provider, { value: promise, children: errorElement });
  7057. }
  7058. if (status === 1) {
  7059. return React3.createElement(AwaitContext.Provider, { value: promise, children });
  7060. }
  7061. throw promise;
  7062. }
  7063. };
  7064. function ResolveAwait({
  7065. children
  7066. }) {
  7067. let data2 = useAsyncValue();
  7068. let toRender = typeof children === "function" ? children(data2) : children;
  7069. return React3.createElement(React3.Fragment, null, toRender);
  7070. }
  7071. function createRoutesFromChildren(children, parentPath = []) {
  7072. let routes = [];
  7073. React3.Children.forEach(children, (element, index) => {
  7074. if (!React3.isValidElement(element)) {
  7075. return;
  7076. }
  7077. let treePath = [...parentPath, index];
  7078. if (element.type === React3.Fragment) {
  7079. routes.push.apply(
  7080. routes,
  7081. createRoutesFromChildren(element.props.children, treePath)
  7082. );
  7083. return;
  7084. }
  7085. invariant(
  7086. element.type === Route,
  7087. `[${typeof element.type === "string" ? element.type : element.type.name}] is not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment>`
  7088. );
  7089. invariant(
  7090. !element.props.index || !element.props.children,
  7091. "An index route cannot have child routes."
  7092. );
  7093. let route = {
  7094. id: element.props.id || treePath.join("-"),
  7095. caseSensitive: element.props.caseSensitive,
  7096. element: element.props.element,
  7097. Component: element.props.Component,
  7098. index: element.props.index,
  7099. path: element.props.path,
  7100. middleware: element.props.middleware,
  7101. loader: element.props.loader,
  7102. action: element.props.action,
  7103. hydrateFallbackElement: element.props.hydrateFallbackElement,
  7104. HydrateFallback: element.props.HydrateFallback,
  7105. errorElement: element.props.errorElement,
  7106. ErrorBoundary: element.props.ErrorBoundary,
  7107. hasErrorBoundary: element.props.hasErrorBoundary === true || element.props.ErrorBoundary != null || element.props.errorElement != null,
  7108. shouldRevalidate: element.props.shouldRevalidate,
  7109. handle: element.props.handle,
  7110. lazy: element.props.lazy
  7111. };
  7112. if (element.props.children) {
  7113. route.children = createRoutesFromChildren(
  7114. element.props.children,
  7115. treePath
  7116. );
  7117. }
  7118. routes.push(route);
  7119. });
  7120. return routes;
  7121. }
  7122. var createRoutesFromElements = createRoutesFromChildren;
  7123. function renderMatches(matches) {
  7124. return _renderMatches(matches);
  7125. }
  7126. function useRouteComponentProps() {
  7127. return {
  7128. params: useParams(),
  7129. loaderData: useLoaderData(),
  7130. actionData: useActionData(),
  7131. matches: useMatches()
  7132. };
  7133. }
  7134. function WithComponentProps({
  7135. children
  7136. }) {
  7137. const props = useRouteComponentProps();
  7138. return React3.cloneElement(children, props);
  7139. }
  7140. function withComponentProps(Component4) {
  7141. return function WithComponentProps2() {
  7142. const props = useRouteComponentProps();
  7143. return React3.createElement(Component4, props);
  7144. };
  7145. }
  7146. function useHydrateFallbackProps() {
  7147. return {
  7148. params: useParams(),
  7149. loaderData: useLoaderData(),
  7150. actionData: useActionData()
  7151. };
  7152. }
  7153. function WithHydrateFallbackProps({
  7154. children
  7155. }) {
  7156. const props = useHydrateFallbackProps();
  7157. return React3.cloneElement(children, props);
  7158. }
  7159. function withHydrateFallbackProps(HydrateFallback) {
  7160. return function WithHydrateFallbackProps2() {
  7161. const props = useHydrateFallbackProps();
  7162. return React3.createElement(HydrateFallback, props);
  7163. };
  7164. }
  7165. function useErrorBoundaryProps() {
  7166. return {
  7167. params: useParams(),
  7168. loaderData: useLoaderData(),
  7169. actionData: useActionData(),
  7170. error: useRouteError()
  7171. };
  7172. }
  7173. function WithErrorBoundaryProps({
  7174. children
  7175. }) {
  7176. const props = useErrorBoundaryProps();
  7177. return React3.cloneElement(children, props);
  7178. }
  7179. function withErrorBoundaryProps(ErrorBoundary) {
  7180. return function WithErrorBoundaryProps2() {
  7181. const props = useErrorBoundaryProps();
  7182. return React3.createElement(ErrorBoundary, props);
  7183. };
  7184. }
  7185. var defaultMethod = "get";
  7186. var defaultEncType = "application/x-www-form-urlencoded";
  7187. function isHtmlElement(object) {
  7188. return typeof HTMLElement !== "undefined" && object instanceof HTMLElement;
  7189. }
  7190. function isButtonElement(object) {
  7191. return isHtmlElement(object) && object.tagName.toLowerCase() === "button";
  7192. }
  7193. function isFormElement(object) {
  7194. return isHtmlElement(object) && object.tagName.toLowerCase() === "form";
  7195. }
  7196. function isInputElement(object) {
  7197. return isHtmlElement(object) && object.tagName.toLowerCase() === "input";
  7198. }
  7199. function isModifiedEvent(event) {
  7200. return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey);
  7201. }
  7202. function shouldProcessLinkClick(event, target) {
  7203. return event.button === 0 && // Ignore everything but left clicks
  7204. (!target || target === "_self") && // Let browser handle "target=_blank" etc.
  7205. !isModifiedEvent(event);
  7206. }
  7207. function createSearchParams(init = "") {
  7208. return new URLSearchParams(
  7209. typeof init === "string" || Array.isArray(init) || init instanceof URLSearchParams ? init : Object.keys(init).reduce((memo2, key) => {
  7210. let value = init[key];
  7211. return memo2.concat(
  7212. Array.isArray(value) ? value.map((v) => [key, v]) : [[key, value]]
  7213. );
  7214. }, [])
  7215. );
  7216. }
  7217. function getSearchParamsForLocation(locationSearch, defaultSearchParams) {
  7218. let searchParams = createSearchParams(locationSearch);
  7219. if (defaultSearchParams) {
  7220. defaultSearchParams.forEach((_, key) => {
  7221. if (!searchParams.has(key)) {
  7222. defaultSearchParams.getAll(key).forEach((value) => {
  7223. searchParams.append(key, value);
  7224. });
  7225. }
  7226. });
  7227. }
  7228. return searchParams;
  7229. }
  7230. var _formDataSupportsSubmitter = null;
  7231. function isFormDataSubmitterSupported() {
  7232. if (_formDataSupportsSubmitter === null) {
  7233. try {
  7234. new FormData(
  7235. document.createElement("form"),
  7236. // @ts-expect-error if FormData supports the submitter parameter, this will throw
  7237. 0
  7238. );
  7239. _formDataSupportsSubmitter = false;
  7240. } catch (e) {
  7241. _formDataSupportsSubmitter = true;
  7242. }
  7243. }
  7244. return _formDataSupportsSubmitter;
  7245. }
  7246. var supportedFormEncTypes = /* @__PURE__ */ new Set([
  7247. "application/x-www-form-urlencoded",
  7248. "multipart/form-data",
  7249. "text/plain"
  7250. ]);
  7251. function getFormEncType(encType) {
  7252. if (encType != null && !supportedFormEncTypes.has(encType)) {
  7253. warning(
  7254. false,
  7255. `"${encType}" is not a valid \`encType\` for \`<Form>\`/\`<fetcher.Form>\` and will default to "${defaultEncType}"`
  7256. );
  7257. return null;
  7258. }
  7259. return encType;
  7260. }
  7261. function getFormSubmissionInfo(target, basename) {
  7262. let method;
  7263. let action;
  7264. let encType;
  7265. let formData;
  7266. let body;
  7267. if (isFormElement(target)) {
  7268. let attr = target.getAttribute("action");
  7269. action = attr ? stripBasename(attr, basename) : null;
  7270. method = target.getAttribute("method") || defaultMethod;
  7271. encType = getFormEncType(target.getAttribute("enctype")) || defaultEncType;
  7272. formData = new FormData(target);
  7273. } else if (isButtonElement(target) || isInputElement(target) && (target.type === "submit" || target.type === "image")) {
  7274. let form = target.form;
  7275. if (form == null) {
  7276. throw new Error(
  7277. `Cannot submit a <button> or <input type="submit"> without a <form>`
  7278. );
  7279. }
  7280. let attr = target.getAttribute("formaction") || form.getAttribute("action");
  7281. action = attr ? stripBasename(attr, basename) : null;
  7282. method = target.getAttribute("formmethod") || form.getAttribute("method") || defaultMethod;
  7283. encType = getFormEncType(target.getAttribute("formenctype")) || getFormEncType(form.getAttribute("enctype")) || defaultEncType;
  7284. formData = new FormData(form, target);
  7285. if (!isFormDataSubmitterSupported()) {
  7286. let { name, type, value } = target;
  7287. if (type === "image") {
  7288. let prefix = name ? `${name}.` : "";
  7289. formData.append(`${prefix}x`, "0");
  7290. formData.append(`${prefix}y`, "0");
  7291. } else if (name) {
  7292. formData.append(name, value);
  7293. }
  7294. }
  7295. } else if (isHtmlElement(target)) {
  7296. throw new Error(
  7297. `Cannot submit element that is not <form>, <button>, or <input type="submit|image">`
  7298. );
  7299. } else {
  7300. method = defaultMethod;
  7301. action = null;
  7302. encType = defaultEncType;
  7303. body = target;
  7304. }
  7305. if (formData && encType === "text/plain") {
  7306. body = formData;
  7307. formData = void 0;
  7308. }
  7309. return { action, method: method.toLowerCase(), encType, formData, body };
  7310. }
  7311. var HOLE = -1;
  7312. var NAN = -2;
  7313. var NEGATIVE_INFINITY = -3;
  7314. var NEGATIVE_ZERO = -4;
  7315. var NULL = -5;
  7316. var POSITIVE_INFINITY = -6;
  7317. var UNDEFINED = -7;
  7318. var TYPE_BIGINT = "B";
  7319. var TYPE_DATE = "D";
  7320. var TYPE_ERROR = "E";
  7321. var TYPE_MAP = "M";
  7322. var TYPE_NULL_OBJECT = "N";
  7323. var TYPE_PROMISE = "P";
  7324. var TYPE_REGEXP = "R";
  7325. var TYPE_SET = "S";
  7326. var TYPE_SYMBOL = "Y";
  7327. var TYPE_URL = "U";
  7328. var TYPE_PREVIOUS_RESOLVED = "Z";
  7329. var Deferred2 = class {
  7330. constructor() {
  7331. this.promise = new Promise((resolve, reject) => {
  7332. this.resolve = resolve;
  7333. this.reject = reject;
  7334. });
  7335. }
  7336. };
  7337. function createLineSplittingTransform() {
  7338. const decoder = new TextDecoder();
  7339. let leftover = "";
  7340. return new TransformStream({
  7341. transform(chunk, controller) {
  7342. const str = decoder.decode(chunk, { stream: true });
  7343. const parts = (leftover + str).split("\n");
  7344. leftover = parts.pop() || "";
  7345. for (const part of parts) {
  7346. controller.enqueue(part);
  7347. }
  7348. },
  7349. flush(controller) {
  7350. if (leftover) {
  7351. controller.enqueue(leftover);
  7352. }
  7353. }
  7354. });
  7355. }
  7356. function flatten(input) {
  7357. const { indices } = this;
  7358. const existing = indices.get(input);
  7359. if (existing) return [existing];
  7360. if (input === void 0) return UNDEFINED;
  7361. if (input === null) return NULL;
  7362. if (Number.isNaN(input)) return NAN;
  7363. if (input === Number.POSITIVE_INFINITY) return POSITIVE_INFINITY;
  7364. if (input === Number.NEGATIVE_INFINITY) return NEGATIVE_INFINITY;
  7365. if (input === 0 && 1 / input < 0) return NEGATIVE_ZERO;
  7366. const index = this.index++;
  7367. indices.set(input, index);
  7368. stringify.call(this, input, index);
  7369. return index;
  7370. }
  7371. function stringify(input, index) {
  7372. const { deferred, plugins, postPlugins } = this;
  7373. const str = this.stringified;
  7374. const stack = [[input, index]];
  7375. while (stack.length > 0) {
  7376. const [input2, index2] = stack.pop();
  7377. const partsForObj = (obj) => Object.keys(obj).map((k) => `"_${flatten.call(this, k)}":${flatten.call(this, obj[k])}`).join(",");
  7378. let error = null;
  7379. switch (typeof input2) {
  7380. case "boolean":
  7381. case "number":
  7382. case "string":
  7383. str[index2] = JSON.stringify(input2);
  7384. break;
  7385. case "bigint":
  7386. str[index2] = `["${TYPE_BIGINT}","${input2}"]`;
  7387. break;
  7388. case "symbol": {
  7389. const keyFor = Symbol.keyFor(input2);
  7390. if (!keyFor) {
  7391. error = new Error(
  7392. "Cannot encode symbol unless created with Symbol.for()"
  7393. );
  7394. } else {
  7395. str[index2] = `["${TYPE_SYMBOL}",${JSON.stringify(keyFor)}]`;
  7396. }
  7397. break;
  7398. }
  7399. case "object": {
  7400. if (!input2) {
  7401. str[index2] = `${NULL}`;
  7402. break;
  7403. }
  7404. const isArray = Array.isArray(input2);
  7405. let pluginHandled = false;
  7406. if (!isArray && plugins) {
  7407. for (const plugin of plugins) {
  7408. const pluginResult = plugin(input2);
  7409. if (Array.isArray(pluginResult)) {
  7410. pluginHandled = true;
  7411. const [pluginIdentifier, ...rest] = pluginResult;
  7412. str[index2] = `[${JSON.stringify(pluginIdentifier)}`;
  7413. if (rest.length > 0) {
  7414. str[index2] += `,${rest.map((v) => flatten.call(this, v)).join(",")}`;
  7415. }
  7416. str[index2] += "]";
  7417. break;
  7418. }
  7419. }
  7420. }
  7421. if (!pluginHandled) {
  7422. let result = isArray ? "[" : "{";
  7423. if (isArray) {
  7424. for (let i = 0; i < input2.length; i++)
  7425. result += (i ? "," : "") + (i in input2 ? flatten.call(this, input2[i]) : HOLE);
  7426. str[index2] = `${result}]`;
  7427. } else if (input2 instanceof Date) {
  7428. const dateTime = input2.getTime();
  7429. str[index2] = `["${TYPE_DATE}",${Number.isNaN(dateTime) ? JSON.stringify("invalid") : dateTime}]`;
  7430. } else if (input2 instanceof URL) {
  7431. str[index2] = `["${TYPE_URL}",${JSON.stringify(input2.href)}]`;
  7432. } else if (input2 instanceof RegExp) {
  7433. str[index2] = `["${TYPE_REGEXP}",${JSON.stringify(
  7434. input2.source
  7435. )},${JSON.stringify(input2.flags)}]`;
  7436. } else if (input2 instanceof Set) {
  7437. if (input2.size > 0) {
  7438. str[index2] = `["${TYPE_SET}",${[...input2].map((val) => flatten.call(this, val)).join(",")}]`;
  7439. } else {
  7440. str[index2] = `["${TYPE_SET}"]`;
  7441. }
  7442. } else if (input2 instanceof Map) {
  7443. if (input2.size > 0) {
  7444. str[index2] = `["${TYPE_MAP}",${[...input2].flatMap(([k, v]) => [
  7445. flatten.call(this, k),
  7446. flatten.call(this, v)
  7447. ]).join(",")}]`;
  7448. } else {
  7449. str[index2] = `["${TYPE_MAP}"]`;
  7450. }
  7451. } else if (input2 instanceof Promise) {
  7452. str[index2] = `["${TYPE_PROMISE}",${index2}]`;
  7453. deferred[index2] = input2;
  7454. } else if (input2 instanceof Error) {
  7455. str[index2] = `["${TYPE_ERROR}",${JSON.stringify(input2.message)}`;
  7456. if (input2.name !== "Error") {
  7457. str[index2] += `,${JSON.stringify(input2.name)}`;
  7458. }
  7459. str[index2] += "]";
  7460. } else if (Object.getPrototypeOf(input2) === null) {
  7461. str[index2] = `["${TYPE_NULL_OBJECT}",{${partsForObj(input2)}}]`;
  7462. } else if (isPlainObject2(input2)) {
  7463. str[index2] = `{${partsForObj(input2)}}`;
  7464. } else {
  7465. error = new Error("Cannot encode object with prototype");
  7466. }
  7467. }
  7468. break;
  7469. }
  7470. default: {
  7471. const isArray = Array.isArray(input2);
  7472. let pluginHandled = false;
  7473. if (!isArray && plugins) {
  7474. for (const plugin of plugins) {
  7475. const pluginResult = plugin(input2);
  7476. if (Array.isArray(pluginResult)) {
  7477. pluginHandled = true;
  7478. const [pluginIdentifier, ...rest] = pluginResult;
  7479. str[index2] = `[${JSON.stringify(pluginIdentifier)}`;
  7480. if (rest.length > 0) {
  7481. str[index2] += `,${rest.map((v) => flatten.call(this, v)).join(",")}`;
  7482. }
  7483. str[index2] += "]";
  7484. break;
  7485. }
  7486. }
  7487. }
  7488. if (!pluginHandled) {
  7489. error = new Error("Cannot encode function or unexpected type");
  7490. }
  7491. }
  7492. }
  7493. if (error) {
  7494. let pluginHandled = false;
  7495. if (postPlugins) {
  7496. for (const plugin of postPlugins) {
  7497. const pluginResult = plugin(input2);
  7498. if (Array.isArray(pluginResult)) {
  7499. pluginHandled = true;
  7500. const [pluginIdentifier, ...rest] = pluginResult;
  7501. str[index2] = `[${JSON.stringify(pluginIdentifier)}`;
  7502. if (rest.length > 0) {
  7503. str[index2] += `,${rest.map((v) => flatten.call(this, v)).join(",")}`;
  7504. }
  7505. str[index2] += "]";
  7506. break;
  7507. }
  7508. }
  7509. }
  7510. if (!pluginHandled) {
  7511. throw error;
  7512. }
  7513. }
  7514. }
  7515. }
  7516. var objectProtoNames2 = Object.getOwnPropertyNames(Object.prototype).sort().join("\0");
  7517. function isPlainObject2(thing) {
  7518. const proto = Object.getPrototypeOf(thing);
  7519. return proto === Object.prototype || proto === null || Object.getOwnPropertyNames(proto).sort().join("\0") === objectProtoNames2;
  7520. }
  7521. var globalObj = typeof window !== "undefined" ? window : typeof globalThis !== "undefined" ? globalThis : void 0;
  7522. function unflatten(parsed) {
  7523. const { hydrated, values } = this;
  7524. if (typeof parsed === "number") return hydrate.call(this, parsed);
  7525. if (!Array.isArray(parsed) || !parsed.length) throw new SyntaxError();
  7526. const startIndex = values.length;
  7527. for (const value of parsed) {
  7528. values.push(value);
  7529. }
  7530. hydrated.length = values.length;
  7531. return hydrate.call(this, startIndex);
  7532. }
  7533. function hydrate(index) {
  7534. const { hydrated, values, deferred, plugins } = this;
  7535. let result;
  7536. const stack = [
  7537. [
  7538. index,
  7539. (v) => {
  7540. result = v;
  7541. }
  7542. ]
  7543. ];
  7544. let postRun = [];
  7545. while (stack.length > 0) {
  7546. const [index2, set] = stack.pop();
  7547. switch (index2) {
  7548. case UNDEFINED:
  7549. set(void 0);
  7550. continue;
  7551. case NULL:
  7552. set(null);
  7553. continue;
  7554. case NAN:
  7555. set(NaN);
  7556. continue;
  7557. case POSITIVE_INFINITY:
  7558. set(Infinity);
  7559. continue;
  7560. case NEGATIVE_INFINITY:
  7561. set(-Infinity);
  7562. continue;
  7563. case NEGATIVE_ZERO:
  7564. set(-0);
  7565. continue;
  7566. }
  7567. if (hydrated[index2]) {
  7568. set(hydrated[index2]);
  7569. continue;
  7570. }
  7571. const value = values[index2];
  7572. if (!value || typeof value !== "object") {
  7573. hydrated[index2] = value;
  7574. set(value);
  7575. continue;
  7576. }
  7577. if (Array.isArray(value)) {
  7578. if (typeof value[0] === "string") {
  7579. const [type, b, c] = value;
  7580. switch (type) {
  7581. case TYPE_DATE:
  7582. set(hydrated[index2] = new Date(b));
  7583. continue;
  7584. case TYPE_URL:
  7585. set(hydrated[index2] = new URL(b));
  7586. continue;
  7587. case TYPE_BIGINT:
  7588. set(hydrated[index2] = BigInt(b));
  7589. continue;
  7590. case TYPE_REGEXP:
  7591. set(hydrated[index2] = new RegExp(b, c));
  7592. continue;
  7593. case TYPE_SYMBOL:
  7594. set(hydrated[index2] = Symbol.for(b));
  7595. continue;
  7596. case TYPE_SET:
  7597. const newSet = /* @__PURE__ */ new Set();
  7598. hydrated[index2] = newSet;
  7599. for (let i = value.length - 1; i > 0; i--)
  7600. stack.push([
  7601. value[i],
  7602. (v) => {
  7603. newSet.add(v);
  7604. }
  7605. ]);
  7606. set(newSet);
  7607. continue;
  7608. case TYPE_MAP:
  7609. const map = /* @__PURE__ */ new Map();
  7610. hydrated[index2] = map;
  7611. for (let i = value.length - 2; i > 0; i -= 2) {
  7612. const r = [];
  7613. stack.push([
  7614. value[i + 1],
  7615. (v) => {
  7616. r[1] = v;
  7617. }
  7618. ]);
  7619. stack.push([
  7620. value[i],
  7621. (k) => {
  7622. r[0] = k;
  7623. }
  7624. ]);
  7625. postRun.push(() => {
  7626. map.set(r[0], r[1]);
  7627. });
  7628. }
  7629. set(map);
  7630. continue;
  7631. case TYPE_NULL_OBJECT:
  7632. const obj = /* @__PURE__ */ Object.create(null);
  7633. hydrated[index2] = obj;
  7634. for (const key of Object.keys(b).reverse()) {
  7635. const r = [];
  7636. stack.push([
  7637. b[key],
  7638. (v) => {
  7639. r[1] = v;
  7640. }
  7641. ]);
  7642. stack.push([
  7643. Number(key.slice(1)),
  7644. (k) => {
  7645. r[0] = k;
  7646. }
  7647. ]);
  7648. postRun.push(() => {
  7649. obj[r[0]] = r[1];
  7650. });
  7651. }
  7652. set(obj);
  7653. continue;
  7654. case TYPE_PROMISE:
  7655. if (hydrated[b]) {
  7656. set(hydrated[index2] = hydrated[b]);
  7657. } else {
  7658. const d = new Deferred2();
  7659. deferred[b] = d;
  7660. set(hydrated[index2] = d.promise);
  7661. }
  7662. continue;
  7663. case TYPE_ERROR:
  7664. const [, message, errorType] = value;
  7665. let error = errorType && globalObj && globalObj[errorType] ? new globalObj[errorType](message) : new Error(message);
  7666. hydrated[index2] = error;
  7667. set(error);
  7668. continue;
  7669. case TYPE_PREVIOUS_RESOLVED:
  7670. set(hydrated[index2] = hydrated[b]);
  7671. continue;
  7672. default:
  7673. if (Array.isArray(plugins)) {
  7674. const r = [];
  7675. const vals = value.slice(1);
  7676. for (let i = 0; i < vals.length; i++) {
  7677. const v = vals[i];
  7678. stack.push([
  7679. v,
  7680. (v2) => {
  7681. r[i] = v2;
  7682. }
  7683. ]);
  7684. }
  7685. postRun.push(() => {
  7686. for (const plugin of plugins) {
  7687. const result2 = plugin(value[0], ...r);
  7688. if (result2) {
  7689. set(hydrated[index2] = result2.value);
  7690. return;
  7691. }
  7692. }
  7693. throw new SyntaxError();
  7694. });
  7695. continue;
  7696. }
  7697. throw new SyntaxError();
  7698. }
  7699. } else {
  7700. const array = [];
  7701. hydrated[index2] = array;
  7702. for (let i = 0; i < value.length; i++) {
  7703. const n = value[i];
  7704. if (n !== HOLE) {
  7705. stack.push([
  7706. n,
  7707. (v) => {
  7708. array[i] = v;
  7709. }
  7710. ]);
  7711. }
  7712. }
  7713. set(array);
  7714. continue;
  7715. }
  7716. } else {
  7717. const object = {};
  7718. hydrated[index2] = object;
  7719. for (const key of Object.keys(value).reverse()) {
  7720. const r = [];
  7721. stack.push([
  7722. value[key],
  7723. (v) => {
  7724. r[1] = v;
  7725. }
  7726. ]);
  7727. stack.push([
  7728. Number(key.slice(1)),
  7729. (k) => {
  7730. r[0] = k;
  7731. }
  7732. ]);
  7733. postRun.push(() => {
  7734. object[r[0]] = r[1];
  7735. });
  7736. }
  7737. set(object);
  7738. continue;
  7739. }
  7740. }
  7741. while (postRun.length > 0) {
  7742. postRun.pop()();
  7743. }
  7744. return result;
  7745. }
  7746. async function decode(readable, options) {
  7747. const { plugins } = options ?? {};
  7748. const done = new Deferred2();
  7749. const reader = readable.pipeThrough(createLineSplittingTransform()).getReader();
  7750. const decoder = {
  7751. values: [],
  7752. hydrated: [],
  7753. deferred: {},
  7754. plugins
  7755. };
  7756. const decoded = await decodeInitial.call(decoder, reader);
  7757. let donePromise = done.promise;
  7758. if (decoded.done) {
  7759. done.resolve();
  7760. } else {
  7761. donePromise = decodeDeferred.call(decoder, reader).then(done.resolve).catch((reason) => {
  7762. for (const deferred of Object.values(decoder.deferred)) {
  7763. deferred.reject(reason);
  7764. }
  7765. done.reject(reason);
  7766. });
  7767. }
  7768. return {
  7769. done: donePromise.then(() => reader.closed),
  7770. value: decoded.value
  7771. };
  7772. }
  7773. async function decodeInitial(reader) {
  7774. const read = await reader.read();
  7775. if (!read.value) {
  7776. throw new SyntaxError();
  7777. }
  7778. let line;
  7779. try {
  7780. line = JSON.parse(read.value);
  7781. } catch (reason) {
  7782. throw new SyntaxError();
  7783. }
  7784. return {
  7785. done: read.done,
  7786. value: unflatten.call(this, line)
  7787. };
  7788. }
  7789. async function decodeDeferred(reader) {
  7790. let read = await reader.read();
  7791. while (!read.done) {
  7792. if (!read.value) continue;
  7793. const line = read.value;
  7794. switch (line[0]) {
  7795. case TYPE_PROMISE: {
  7796. const colonIndex = line.indexOf(":");
  7797. const deferredId = Number(line.slice(1, colonIndex));
  7798. const deferred = this.deferred[deferredId];
  7799. if (!deferred) {
  7800. throw new Error(`Deferred ID ${deferredId} not found in stream`);
  7801. }
  7802. const lineData = line.slice(colonIndex + 1);
  7803. let jsonLine;
  7804. try {
  7805. jsonLine = JSON.parse(lineData);
  7806. } catch (reason) {
  7807. throw new SyntaxError();
  7808. }
  7809. const value = unflatten.call(this, jsonLine);
  7810. deferred.resolve(value);
  7811. break;
  7812. }
  7813. case TYPE_ERROR: {
  7814. const colonIndex = line.indexOf(":");
  7815. const deferredId = Number(line.slice(1, colonIndex));
  7816. const deferred = this.deferred[deferredId];
  7817. if (!deferred) {
  7818. throw new Error(`Deferred ID ${deferredId} not found in stream`);
  7819. }
  7820. const lineData = line.slice(colonIndex + 1);
  7821. let jsonLine;
  7822. try {
  7823. jsonLine = JSON.parse(lineData);
  7824. } catch (reason) {
  7825. throw new SyntaxError();
  7826. }
  7827. const value = unflatten.call(this, jsonLine);
  7828. deferred.reject(value);
  7829. break;
  7830. }
  7831. default:
  7832. throw new SyntaxError();
  7833. }
  7834. read = await reader.read();
  7835. }
  7836. }
  7837. function encode(input, options) {
  7838. const { plugins, postPlugins, signal } = options ?? {};
  7839. const encoder3 = {
  7840. deferred: {},
  7841. index: 0,
  7842. indices: /* @__PURE__ */ new Map(),
  7843. stringified: [],
  7844. plugins,
  7845. postPlugins,
  7846. signal
  7847. };
  7848. const textEncoder = new TextEncoder();
  7849. let lastSentIndex = 0;
  7850. const readable = new ReadableStream({
  7851. async start(controller) {
  7852. const id = flatten.call(encoder3, input);
  7853. if (Array.isArray(id)) {
  7854. throw new Error("This should never happen");
  7855. }
  7856. if (id < 0) {
  7857. controller.enqueue(textEncoder.encode(`${id}
  7858. `));
  7859. } else {
  7860. controller.enqueue(
  7861. textEncoder.encode(`[${encoder3.stringified.join(",")}]
  7862. `)
  7863. );
  7864. lastSentIndex = encoder3.stringified.length - 1;
  7865. }
  7866. const seenPromises = /* @__PURE__ */ new WeakSet();
  7867. if (Object.keys(encoder3.deferred).length) {
  7868. let raceDone;
  7869. const racePromise = new Promise((resolve, reject) => {
  7870. raceDone = resolve;
  7871. if (signal) {
  7872. const rejectPromise = () => reject(signal.reason || new Error("Signal was aborted."));
  7873. if (signal.aborted) {
  7874. rejectPromise();
  7875. } else {
  7876. signal.addEventListener("abort", (event) => {
  7877. rejectPromise();
  7878. });
  7879. }
  7880. }
  7881. });
  7882. while (Object.keys(encoder3.deferred).length > 0) {
  7883. for (const [deferredId, deferred] of Object.entries(
  7884. encoder3.deferred
  7885. )) {
  7886. if (seenPromises.has(deferred)) continue;
  7887. seenPromises.add(
  7888. // biome-ignore lint/suspicious/noAssignInExpressions: <explanation>
  7889. encoder3.deferred[Number(deferredId)] = Promise.race([
  7890. racePromise,
  7891. deferred
  7892. ]).then(
  7893. (resolved) => {
  7894. const id2 = flatten.call(encoder3, resolved);
  7895. if (Array.isArray(id2)) {
  7896. controller.enqueue(
  7897. textEncoder.encode(
  7898. `${TYPE_PROMISE}${deferredId}:[["${TYPE_PREVIOUS_RESOLVED}",${id2[0]}]]
  7899. `
  7900. )
  7901. );
  7902. encoder3.index++;
  7903. lastSentIndex++;
  7904. } else if (id2 < 0) {
  7905. controller.enqueue(
  7906. textEncoder.encode(
  7907. `${TYPE_PROMISE}${deferredId}:${id2}
  7908. `
  7909. )
  7910. );
  7911. } else {
  7912. const values = encoder3.stringified.slice(lastSentIndex + 1).join(",");
  7913. controller.enqueue(
  7914. textEncoder.encode(
  7915. `${TYPE_PROMISE}${deferredId}:[${values}]
  7916. `
  7917. )
  7918. );
  7919. lastSentIndex = encoder3.stringified.length - 1;
  7920. }
  7921. },
  7922. (reason) => {
  7923. if (!reason || typeof reason !== "object" || !(reason instanceof Error)) {
  7924. reason = new Error("An unknown error occurred");
  7925. }
  7926. const id2 = flatten.call(encoder3, reason);
  7927. if (Array.isArray(id2)) {
  7928. controller.enqueue(
  7929. textEncoder.encode(
  7930. `${TYPE_ERROR}${deferredId}:[["${TYPE_PREVIOUS_RESOLVED}",${id2[0]}]]
  7931. `
  7932. )
  7933. );
  7934. encoder3.index++;
  7935. lastSentIndex++;
  7936. } else if (id2 < 0) {
  7937. controller.enqueue(
  7938. textEncoder.encode(
  7939. `${TYPE_ERROR}${deferredId}:${id2}
  7940. `
  7941. )
  7942. );
  7943. } else {
  7944. const values = encoder3.stringified.slice(lastSentIndex + 1).join(",");
  7945. controller.enqueue(
  7946. textEncoder.encode(
  7947. `${TYPE_ERROR}${deferredId}:[${values}]
  7948. `
  7949. )
  7950. );
  7951. lastSentIndex = encoder3.stringified.length - 1;
  7952. }
  7953. }
  7954. ).finally(() => {
  7955. delete encoder3.deferred[Number(deferredId)];
  7956. })
  7957. );
  7958. }
  7959. await Promise.race(Object.values(encoder3.deferred));
  7960. }
  7961. raceDone();
  7962. }
  7963. await Promise.all(Object.values(encoder3.deferred));
  7964. controller.close();
  7965. }
  7966. });
  7967. return readable;
  7968. }
  7969. async function createRequestInit(request) {
  7970. let init = { signal: request.signal };
  7971. if (request.method !== "GET") {
  7972. init.method = request.method;
  7973. let contentType = request.headers.get("Content-Type");
  7974. if (contentType && /\bapplication\/json\b/.test(contentType)) {
  7975. init.headers = { "Content-Type": contentType };
  7976. init.body = JSON.stringify(await request.json());
  7977. } else if (contentType && /\btext\/plain\b/.test(contentType)) {
  7978. init.headers = { "Content-Type": contentType };
  7979. init.body = await request.text();
  7980. } else if (contentType && /\bapplication\/x-www-form-urlencoded\b/.test(contentType)) {
  7981. init.body = new URLSearchParams(await request.text());
  7982. } else {
  7983. init.body = await request.formData();
  7984. }
  7985. }
  7986. return init;
  7987. }
  7988. var ESCAPE_LOOKUP = {
  7989. "&": "\\u0026",
  7990. ">": "\\u003e",
  7991. "<": "\\u003c",
  7992. "\u2028": "\\u2028",
  7993. "\u2029": "\\u2029"
  7994. };
  7995. var ESCAPE_REGEX = /[&><\u2028\u2029]/g;
  7996. function escapeHtml(html) {
  7997. return html.replace(ESCAPE_REGEX, (match) => ESCAPE_LOOKUP[match]);
  7998. }
  7999. function invariant2(value, message) {
  8000. if (value === false || value === null || typeof value === "undefined") {
  8001. throw new Error(message);
  8002. }
  8003. }
  8004. var SingleFetchRedirectSymbol = Symbol("SingleFetchRedirect");
  8005. var SingleFetchNoResultError = class extends Error {
  8006. };
  8007. var SINGLE_FETCH_REDIRECT_STATUS = 202;
  8008. var NO_BODY_STATUS_CODES = /* @__PURE__ */ new Set([100, 101, 204, 205]);
  8009. function StreamTransfer({
  8010. context,
  8011. identifier,
  8012. reader,
  8013. textDecoder,
  8014. nonce
  8015. }) {
  8016. if (!context.renderMeta || !context.renderMeta.didRenderScripts) {
  8017. return null;
  8018. }
  8019. if (!context.renderMeta.streamCache) {
  8020. context.renderMeta.streamCache = {};
  8021. }
  8022. let { streamCache } = context.renderMeta;
  8023. let promise = streamCache[identifier];
  8024. if (!promise) {
  8025. promise = streamCache[identifier] = reader.read().then((result) => {
  8026. streamCache[identifier].result = {
  8027. done: result.done,
  8028. value: textDecoder.decode(result.value, { stream: true })
  8029. };
  8030. }).catch((e) => {
  8031. streamCache[identifier].error = e;
  8032. });
  8033. }
  8034. if (promise.error) {
  8035. throw promise.error;
  8036. }
  8037. if (promise.result === void 0) {
  8038. throw promise;
  8039. }
  8040. let { done, value } = promise.result;
  8041. let scriptTag = value ? React4.createElement(
  8042. "script",
  8043. {
  8044. nonce,
  8045. dangerouslySetInnerHTML: {
  8046. __html: `window.__reactRouterContext.streamController.enqueue(${escapeHtml(
  8047. JSON.stringify(value)
  8048. )});`
  8049. }
  8050. }
  8051. ) : null;
  8052. if (done) {
  8053. return React4.createElement(React4.Fragment, null, scriptTag, React4.createElement(
  8054. "script",
  8055. {
  8056. nonce,
  8057. dangerouslySetInnerHTML: {
  8058. __html: `window.__reactRouterContext.streamController.close();`
  8059. }
  8060. }
  8061. ));
  8062. } else {
  8063. return React4.createElement(React4.Fragment, null, scriptTag, React4.createElement(React4.Suspense, null, React4.createElement(
  8064. StreamTransfer,
  8065. {
  8066. context,
  8067. identifier: identifier + 1,
  8068. reader,
  8069. textDecoder,
  8070. nonce
  8071. }
  8072. )));
  8073. }
  8074. }
  8075. function getTurboStreamSingleFetchDataStrategy(getRouter, manifest, routeModules, ssr, basename) {
  8076. let dataStrategy = getSingleFetchDataStrategyImpl(
  8077. getRouter,
  8078. (match) => {
  8079. let manifestRoute = manifest.routes[match.route.id];
  8080. invariant2(manifestRoute, "Route not found in manifest");
  8081. let routeModule = routeModules[match.route.id];
  8082. return {
  8083. hasLoader: manifestRoute.hasLoader,
  8084. hasClientLoader: manifestRoute.hasClientLoader,
  8085. hasShouldRevalidate: Boolean(routeModule == null ? void 0 : routeModule.shouldRevalidate)
  8086. };
  8087. },
  8088. fetchAndDecodeViaTurboStream,
  8089. ssr,
  8090. basename
  8091. );
  8092. return async (args) => args.runClientMiddleware(dataStrategy);
  8093. }
  8094. function getSingleFetchDataStrategyImpl(getRouter, getRouteInfo, fetchAndDecode, ssr, basename, shouldAllowOptOut = () => true) {
  8095. return async (args) => {
  8096. let { request, matches, fetcherKey } = args;
  8097. let router2 = getRouter();
  8098. if (request.method !== "GET") {
  8099. return singleFetchActionStrategy(args, fetchAndDecode, basename);
  8100. }
  8101. let foundRevalidatingServerLoader = matches.some((m) => {
  8102. let { hasLoader, hasClientLoader } = getRouteInfo(m);
  8103. return m.shouldCallHandler() && hasLoader && !hasClientLoader;
  8104. });
  8105. if (!ssr && !foundRevalidatingServerLoader) {
  8106. return nonSsrStrategy(args, getRouteInfo, fetchAndDecode, basename);
  8107. }
  8108. if (fetcherKey) {
  8109. return singleFetchLoaderFetcherStrategy(args, fetchAndDecode, basename);
  8110. }
  8111. return singleFetchLoaderNavigationStrategy(
  8112. args,
  8113. router2,
  8114. getRouteInfo,
  8115. fetchAndDecode,
  8116. ssr,
  8117. basename,
  8118. shouldAllowOptOut
  8119. );
  8120. };
  8121. }
  8122. async function singleFetchActionStrategy(args, fetchAndDecode, basename) {
  8123. let actionMatch = args.matches.find((m) => m.shouldCallHandler());
  8124. invariant2(actionMatch, "No action match found");
  8125. let actionStatus = void 0;
  8126. let result = await actionMatch.resolve(async (handler) => {
  8127. let result2 = await handler(async () => {
  8128. let { data: data2, status } = await fetchAndDecode(args, basename, [
  8129. actionMatch.route.id
  8130. ]);
  8131. actionStatus = status;
  8132. return unwrapSingleFetchResult(data2, actionMatch.route.id);
  8133. });
  8134. return result2;
  8135. });
  8136. if (isResponse(result.result) || isRouteErrorResponse(result.result) || isDataWithResponseInit(result.result)) {
  8137. return { [actionMatch.route.id]: result };
  8138. }
  8139. return {
  8140. [actionMatch.route.id]: {
  8141. type: result.type,
  8142. result: data(result.result, actionStatus)
  8143. }
  8144. };
  8145. }
  8146. async function nonSsrStrategy(args, getRouteInfo, fetchAndDecode, basename) {
  8147. let matchesToLoad = args.matches.filter((m) => m.shouldCallHandler());
  8148. let results = {};
  8149. await Promise.all(
  8150. matchesToLoad.map(
  8151. (m) => m.resolve(async (handler) => {
  8152. try {
  8153. let { hasClientLoader } = getRouteInfo(m);
  8154. let routeId = m.route.id;
  8155. let result = hasClientLoader ? await handler(async () => {
  8156. let { data: data2 } = await fetchAndDecode(args, basename, [routeId]);
  8157. return unwrapSingleFetchResult(data2, routeId);
  8158. }) : await handler();
  8159. results[m.route.id] = { type: "data", result };
  8160. } catch (e) {
  8161. results[m.route.id] = { type: "error", result: e };
  8162. }
  8163. })
  8164. )
  8165. );
  8166. return results;
  8167. }
  8168. async function singleFetchLoaderNavigationStrategy(args, router2, getRouteInfo, fetchAndDecode, ssr, basename, shouldAllowOptOut = () => true) {
  8169. let routesParams = /* @__PURE__ */ new Set();
  8170. let foundOptOutRoute = false;
  8171. let routeDfds = args.matches.map(() => createDeferred2());
  8172. let singleFetchDfd = createDeferred2();
  8173. let results = {};
  8174. let resolvePromise = Promise.all(
  8175. args.matches.map(
  8176. async (m, i) => m.resolve(async (handler) => {
  8177. routeDfds[i].resolve();
  8178. let routeId = m.route.id;
  8179. let { hasLoader, hasClientLoader, hasShouldRevalidate } = getRouteInfo(m);
  8180. let defaultShouldRevalidate = !m.shouldRevalidateArgs || m.shouldRevalidateArgs.actionStatus == null || m.shouldRevalidateArgs.actionStatus < 400;
  8181. let shouldCall = m.shouldCallHandler(defaultShouldRevalidate);
  8182. if (!shouldCall) {
  8183. foundOptOutRoute || (foundOptOutRoute = m.shouldRevalidateArgs != null && // This is a revalidation,
  8184. hasLoader && // for a route with a server loader,
  8185. hasShouldRevalidate === true);
  8186. return;
  8187. }
  8188. if (shouldAllowOptOut(m) && hasClientLoader) {
  8189. if (hasLoader) {
  8190. foundOptOutRoute = true;
  8191. }
  8192. try {
  8193. let result = await handler(async () => {
  8194. let { data: data2 } = await fetchAndDecode(args, basename, [routeId]);
  8195. return unwrapSingleFetchResult(data2, routeId);
  8196. });
  8197. results[routeId] = { type: "data", result };
  8198. } catch (e) {
  8199. results[routeId] = { type: "error", result: e };
  8200. }
  8201. return;
  8202. }
  8203. if (hasLoader) {
  8204. routesParams.add(routeId);
  8205. }
  8206. try {
  8207. let result = await handler(async () => {
  8208. let data2 = await singleFetchDfd.promise;
  8209. return unwrapSingleFetchResult(data2, routeId);
  8210. });
  8211. results[routeId] = { type: "data", result };
  8212. } catch (e) {
  8213. results[routeId] = { type: "error", result: e };
  8214. }
  8215. })
  8216. )
  8217. );
  8218. await Promise.all(routeDfds.map((d) => d.promise));
  8219. let isInitialLoad = !router2.state.initialized && router2.state.navigation.state === "idle";
  8220. if ((isInitialLoad || routesParams.size === 0) && !window.__reactRouterHdrActive) {
  8221. singleFetchDfd.resolve({ routes: {} });
  8222. } else {
  8223. let targetRoutes = ssr && foundOptOutRoute && routesParams.size > 0 ? [...routesParams.keys()] : void 0;
  8224. try {
  8225. let data2 = await fetchAndDecode(args, basename, targetRoutes);
  8226. singleFetchDfd.resolve(data2.data);
  8227. } catch (e) {
  8228. singleFetchDfd.reject(e);
  8229. }
  8230. }
  8231. await resolvePromise;
  8232. await bubbleMiddlewareErrors(
  8233. singleFetchDfd.promise,
  8234. args.matches,
  8235. routesParams,
  8236. results
  8237. );
  8238. return results;
  8239. }
  8240. async function bubbleMiddlewareErrors(singleFetchPromise, matches, routesParams, results) {
  8241. var _a;
  8242. try {
  8243. let middlewareError;
  8244. let fetchedData = await singleFetchPromise;
  8245. if ("routes" in fetchedData) {
  8246. for (let match of matches) {
  8247. if (match.route.id in fetchedData.routes) {
  8248. let routeResult = fetchedData.routes[match.route.id];
  8249. if ("error" in routeResult) {
  8250. middlewareError = routeResult.error;
  8251. if (((_a = results[match.route.id]) == null ? void 0 : _a.result) == null) {
  8252. results[match.route.id] = {
  8253. type: "error",
  8254. result: middlewareError
  8255. };
  8256. }
  8257. break;
  8258. }
  8259. }
  8260. }
  8261. }
  8262. if (middlewareError !== void 0) {
  8263. Array.from(routesParams.values()).forEach((routeId) => {
  8264. if (results[routeId].result instanceof SingleFetchNoResultError) {
  8265. results[routeId].result = middlewareError;
  8266. }
  8267. });
  8268. }
  8269. } catch (e) {
  8270. }
  8271. }
  8272. async function singleFetchLoaderFetcherStrategy(args, fetchAndDecode, basename) {
  8273. let fetcherMatch = args.matches.find((m) => m.shouldCallHandler());
  8274. invariant2(fetcherMatch, "No fetcher match found");
  8275. let routeId = fetcherMatch.route.id;
  8276. let result = await fetcherMatch.resolve(
  8277. async (handler) => handler(async () => {
  8278. let { data: data2 } = await fetchAndDecode(args, basename, [routeId]);
  8279. return unwrapSingleFetchResult(data2, routeId);
  8280. })
  8281. );
  8282. return { [fetcherMatch.route.id]: result };
  8283. }
  8284. function stripIndexParam(url) {
  8285. let indexValues = url.searchParams.getAll("index");
  8286. url.searchParams.delete("index");
  8287. let indexValuesToKeep = [];
  8288. for (let indexValue of indexValues) {
  8289. if (indexValue) {
  8290. indexValuesToKeep.push(indexValue);
  8291. }
  8292. }
  8293. for (let toKeep of indexValuesToKeep) {
  8294. url.searchParams.append("index", toKeep);
  8295. }
  8296. return url;
  8297. }
  8298. function singleFetchUrl(reqUrl, basename, extension) {
  8299. let url = typeof reqUrl === "string" ? new URL(
  8300. reqUrl,
  8301. // This can be called during the SSR flow via PrefetchPageLinksImpl so
  8302. // don't assume window is available
  8303. typeof window === "undefined" ? "server://singlefetch/" : window.location.origin
  8304. ) : reqUrl;
  8305. if (url.pathname === "/") {
  8306. url.pathname = `_root.${extension}`;
  8307. } else if (basename && stripBasename(url.pathname, basename) === "/") {
  8308. url.pathname = `${basename.replace(/\/$/, "")}/_root.${extension}`;
  8309. } else {
  8310. url.pathname = `${url.pathname.replace(/\/$/, "")}.${extension}`;
  8311. }
  8312. return url;
  8313. }
  8314. async function fetchAndDecodeViaTurboStream(args, basename, targetRoutes) {
  8315. let { request } = args;
  8316. let url = singleFetchUrl(request.url, basename, "data");
  8317. if (request.method === "GET") {
  8318. url = stripIndexParam(url);
  8319. if (targetRoutes) {
  8320. url.searchParams.set("_routes", targetRoutes.join(","));
  8321. }
  8322. }
  8323. let res = await fetch(url, await createRequestInit(request));
  8324. if (res.status >= 400 && !res.headers.has("X-Remix-Response")) {
  8325. throw new ErrorResponseImpl(res.status, res.statusText, await res.text());
  8326. }
  8327. if (res.status === 204 && res.headers.has("X-Remix-Redirect")) {
  8328. return {
  8329. status: SINGLE_FETCH_REDIRECT_STATUS,
  8330. data: {
  8331. redirect: {
  8332. redirect: res.headers.get("X-Remix-Redirect"),
  8333. status: Number(res.headers.get("X-Remix-Status") || "302"),
  8334. revalidate: res.headers.get("X-Remix-Revalidate") === "true",
  8335. reload: res.headers.get("X-Remix-Reload-Document") === "true",
  8336. replace: res.headers.get("X-Remix-Replace") === "true"
  8337. }
  8338. }
  8339. };
  8340. }
  8341. if (NO_BODY_STATUS_CODES.has(res.status)) {
  8342. let routes = {};
  8343. if (targetRoutes && request.method !== "GET") {
  8344. routes[targetRoutes[0]] = { data: void 0 };
  8345. }
  8346. return {
  8347. status: res.status,
  8348. data: { routes }
  8349. };
  8350. }
  8351. invariant2(res.body, "No response body to decode");
  8352. try {
  8353. let decoded = await decodeViaTurboStream(res.body, window);
  8354. let data2;
  8355. if (request.method === "GET") {
  8356. let typed = decoded.value;
  8357. if (SingleFetchRedirectSymbol in typed) {
  8358. data2 = { redirect: typed[SingleFetchRedirectSymbol] };
  8359. } else {
  8360. data2 = { routes: typed };
  8361. }
  8362. } else {
  8363. let typed = decoded.value;
  8364. let routeId = targetRoutes == null ? void 0 : targetRoutes[0];
  8365. invariant2(routeId, "No routeId found for single fetch call decoding");
  8366. if ("redirect" in typed) {
  8367. data2 = { redirect: typed };
  8368. } else {
  8369. data2 = { routes: { [routeId]: typed } };
  8370. }
  8371. }
  8372. return { status: res.status, data: data2 };
  8373. } catch (e) {
  8374. throw new Error("Unable to decode turbo-stream response");
  8375. }
  8376. }
  8377. function decodeViaTurboStream(body, global2) {
  8378. return decode(body, {
  8379. plugins: [
  8380. (type, ...rest) => {
  8381. if (type === "SanitizedError") {
  8382. let [name, message, stack] = rest;
  8383. let Constructor = Error;
  8384. if (name && name in global2 && typeof global2[name] === "function") {
  8385. Constructor = global2[name];
  8386. }
  8387. let error = new Constructor(message);
  8388. error.stack = stack;
  8389. return { value: error };
  8390. }
  8391. if (type === "ErrorResponse") {
  8392. let [data2, status, statusText] = rest;
  8393. return {
  8394. value: new ErrorResponseImpl(status, statusText, data2)
  8395. };
  8396. }
  8397. if (type === "SingleFetchRedirect") {
  8398. return { value: { [SingleFetchRedirectSymbol]: rest[0] } };
  8399. }
  8400. if (type === "SingleFetchClassInstance") {
  8401. return { value: rest[0] };
  8402. }
  8403. if (type === "SingleFetchFallback") {
  8404. return { value: void 0 };
  8405. }
  8406. }
  8407. ]
  8408. });
  8409. }
  8410. function unwrapSingleFetchResult(result, routeId) {
  8411. if ("redirect" in result) {
  8412. let {
  8413. redirect: location2,
  8414. revalidate,
  8415. reload,
  8416. replace: replace2,
  8417. status
  8418. } = result.redirect;
  8419. throw redirect(location2, {
  8420. status,
  8421. headers: {
  8422. // Three R's of redirecting (lol Veep)
  8423. ...revalidate ? { "X-Remix-Revalidate": "yes" } : null,
  8424. ...reload ? { "X-Remix-Reload-Document": "yes" } : null,
  8425. ...replace2 ? { "X-Remix-Replace": "yes" } : null
  8426. }
  8427. });
  8428. }
  8429. let routeResult = result.routes[routeId];
  8430. if (routeResult == null) {
  8431. throw new SingleFetchNoResultError(
  8432. `No result found for routeId "${routeId}"`
  8433. );
  8434. } else if ("error" in routeResult) {
  8435. throw routeResult.error;
  8436. } else if ("data" in routeResult) {
  8437. return routeResult.data;
  8438. } else {
  8439. throw new Error(`Invalid response found for routeId "${routeId}"`);
  8440. }
  8441. }
  8442. function createDeferred2() {
  8443. let resolve;
  8444. let reject;
  8445. let promise = new Promise((res, rej) => {
  8446. resolve = async (val) => {
  8447. res(val);
  8448. try {
  8449. await promise;
  8450. } catch (e) {
  8451. }
  8452. };
  8453. reject = async (error) => {
  8454. rej(error);
  8455. try {
  8456. await promise;
  8457. } catch (e) {
  8458. }
  8459. };
  8460. });
  8461. return {
  8462. promise,
  8463. //@ts-ignore
  8464. resolve,
  8465. //@ts-ignore
  8466. reject
  8467. };
  8468. }
  8469. async function loadRouteModule(route, routeModulesCache) {
  8470. if (route.id in routeModulesCache) {
  8471. return routeModulesCache[route.id];
  8472. }
  8473. try {
  8474. let routeModule = await import(
  8475. /* @vite-ignore */
  8476. /* webpackIgnore: true */
  8477. route.module
  8478. );
  8479. routeModulesCache[route.id] = routeModule;
  8480. return routeModule;
  8481. } catch (error) {
  8482. console.error(
  8483. `Error loading route module \`${route.module}\`, reloading page...`
  8484. );
  8485. console.error(error);
  8486. if (window.__reactRouterContext && window.__reactRouterContext.isSpaMode && // @ts-expect-error
  8487. import.meta.hot) {
  8488. throw error;
  8489. }
  8490. window.location.reload();
  8491. return new Promise(() => {
  8492. });
  8493. }
  8494. }
  8495. function getKeyedLinksForMatches(matches, routeModules, manifest) {
  8496. let descriptors = matches.map((match) => {
  8497. var _a;
  8498. let module = routeModules[match.route.id];
  8499. let route = manifest.routes[match.route.id];
  8500. return [
  8501. route && route.css ? route.css.map((href2) => ({ rel: "stylesheet", href: href2 })) : [],
  8502. ((_a = module == null ? void 0 : module.links) == null ? void 0 : _a.call(module)) || []
  8503. ];
  8504. }).flat(2);
  8505. let preloads = getModuleLinkHrefs(matches, manifest);
  8506. return dedupeLinkDescriptors(descriptors, preloads);
  8507. }
  8508. function getRouteCssDescriptors(route) {
  8509. if (!route.css) return [];
  8510. return route.css.map((href2) => ({ rel: "stylesheet", href: href2 }));
  8511. }
  8512. async function prefetchRouteCss(route) {
  8513. if (!route.css) return;
  8514. let descriptors = getRouteCssDescriptors(route);
  8515. await Promise.all(descriptors.map(prefetchStyleLink));
  8516. }
  8517. async function prefetchStyleLinks(route, routeModule) {
  8518. if (!route.css && !routeModule.links || !isPreloadSupported()) return;
  8519. let descriptors = [];
  8520. if (route.css) {
  8521. descriptors.push(...getRouteCssDescriptors(route));
  8522. }
  8523. if (routeModule.links) {
  8524. descriptors.push(...routeModule.links());
  8525. }
  8526. if (descriptors.length === 0) return;
  8527. let styleLinks = [];
  8528. for (let descriptor of descriptors) {
  8529. if (!isPageLinkDescriptor(descriptor) && descriptor.rel === "stylesheet") {
  8530. styleLinks.push({
  8531. ...descriptor,
  8532. rel: "preload",
  8533. as: "style"
  8534. });
  8535. }
  8536. }
  8537. await Promise.all(styleLinks.map(prefetchStyleLink));
  8538. }
  8539. async function prefetchStyleLink(descriptor) {
  8540. return new Promise((resolve) => {
  8541. if (descriptor.media && !window.matchMedia(descriptor.media).matches || document.querySelector(
  8542. `link[rel="stylesheet"][href="${descriptor.href}"]`
  8543. )) {
  8544. return resolve();
  8545. }
  8546. let link = document.createElement("link");
  8547. Object.assign(link, descriptor);
  8548. function removeLink() {
  8549. if (document.head.contains(link)) {
  8550. document.head.removeChild(link);
  8551. }
  8552. }
  8553. link.onload = () => {
  8554. removeLink();
  8555. resolve();
  8556. };
  8557. link.onerror = () => {
  8558. removeLink();
  8559. resolve();
  8560. };
  8561. document.head.appendChild(link);
  8562. });
  8563. }
  8564. function isPageLinkDescriptor(object) {
  8565. return object != null && typeof object.page === "string";
  8566. }
  8567. function isHtmlLinkDescriptor(object) {
  8568. if (object == null) {
  8569. return false;
  8570. }
  8571. if (object.href == null) {
  8572. return object.rel === "preload" && typeof object.imageSrcSet === "string" && typeof object.imageSizes === "string";
  8573. }
  8574. return typeof object.rel === "string" && typeof object.href === "string";
  8575. }
  8576. async function getKeyedPrefetchLinks(matches, manifest, routeModules) {
  8577. let links = await Promise.all(
  8578. matches.map(async (match) => {
  8579. let route = manifest.routes[match.route.id];
  8580. if (route) {
  8581. let mod = await loadRouteModule(route, routeModules);
  8582. return mod.links ? mod.links() : [];
  8583. }
  8584. return [];
  8585. })
  8586. );
  8587. return dedupeLinkDescriptors(
  8588. links.flat(1).filter(isHtmlLinkDescriptor).filter((link) => link.rel === "stylesheet" || link.rel === "preload").map(
  8589. (link) => link.rel === "stylesheet" ? { ...link, rel: "prefetch", as: "style" } : { ...link, rel: "prefetch" }
  8590. )
  8591. );
  8592. }
  8593. function getNewMatchesForLinks(page, nextMatches, currentMatches, manifest, location2, mode) {
  8594. let isNew = (match, index) => {
  8595. if (!currentMatches[index]) return true;
  8596. return match.route.id !== currentMatches[index].route.id;
  8597. };
  8598. let matchPathChanged = (match, index) => {
  8599. var _a;
  8600. return (
  8601. // param change, /users/123 -> /users/456
  8602. currentMatches[index].pathname !== match.pathname || // splat param changed, which is not present in match.path
  8603. // e.g. /files/images/avatar.jpg -> files/finances.xls
  8604. ((_a = currentMatches[index].route.path) == null ? void 0 : _a.endsWith("*")) && currentMatches[index].params["*"] !== match.params["*"]
  8605. );
  8606. };
  8607. if (mode === "assets") {
  8608. return nextMatches.filter(
  8609. (match, index) => isNew(match, index) || matchPathChanged(match, index)
  8610. );
  8611. }
  8612. if (mode === "data") {
  8613. return nextMatches.filter((match, index) => {
  8614. var _a;
  8615. let manifestRoute = manifest.routes[match.route.id];
  8616. if (!manifestRoute || !manifestRoute.hasLoader) {
  8617. return false;
  8618. }
  8619. if (isNew(match, index) || matchPathChanged(match, index)) {
  8620. return true;
  8621. }
  8622. if (match.route.shouldRevalidate) {
  8623. let routeChoice = match.route.shouldRevalidate({
  8624. currentUrl: new URL(
  8625. location2.pathname + location2.search + location2.hash,
  8626. window.origin
  8627. ),
  8628. currentParams: ((_a = currentMatches[0]) == null ? void 0 : _a.params) || {},
  8629. nextUrl: new URL(page, window.origin),
  8630. nextParams: match.params,
  8631. defaultShouldRevalidate: true
  8632. });
  8633. if (typeof routeChoice === "boolean") {
  8634. return routeChoice;
  8635. }
  8636. }
  8637. return true;
  8638. });
  8639. }
  8640. return [];
  8641. }
  8642. function getModuleLinkHrefs(matches, manifest, { includeHydrateFallback } = {}) {
  8643. return dedupeHrefs(
  8644. matches.map((match) => {
  8645. let route = manifest.routes[match.route.id];
  8646. if (!route) return [];
  8647. let hrefs = [route.module];
  8648. if (route.clientActionModule) {
  8649. hrefs = hrefs.concat(route.clientActionModule);
  8650. }
  8651. if (route.clientLoaderModule) {
  8652. hrefs = hrefs.concat(route.clientLoaderModule);
  8653. }
  8654. if (includeHydrateFallback && route.hydrateFallbackModule) {
  8655. hrefs = hrefs.concat(route.hydrateFallbackModule);
  8656. }
  8657. if (route.imports) {
  8658. hrefs = hrefs.concat(route.imports);
  8659. }
  8660. return hrefs;
  8661. }).flat(1)
  8662. );
  8663. }
  8664. function dedupeHrefs(hrefs) {
  8665. return [...new Set(hrefs)];
  8666. }
  8667. function sortKeys(obj) {
  8668. let sorted = {};
  8669. let keys = Object.keys(obj).sort();
  8670. for (let key of keys) {
  8671. sorted[key] = obj[key];
  8672. }
  8673. return sorted;
  8674. }
  8675. function dedupeLinkDescriptors(descriptors, preloads) {
  8676. let set = /* @__PURE__ */ new Set();
  8677. let preloadsSet = new Set(preloads);
  8678. return descriptors.reduce((deduped, descriptor) => {
  8679. let alreadyModulePreload = preloads && !isPageLinkDescriptor(descriptor) && descriptor.as === "script" && descriptor.href && preloadsSet.has(descriptor.href);
  8680. if (alreadyModulePreload) {
  8681. return deduped;
  8682. }
  8683. let key = JSON.stringify(sortKeys(descriptor));
  8684. if (!set.has(key)) {
  8685. set.add(key);
  8686. deduped.push({ key, link: descriptor });
  8687. }
  8688. return deduped;
  8689. }, []);
  8690. }
  8691. var _isPreloadSupported;
  8692. function isPreloadSupported() {
  8693. if (_isPreloadSupported !== void 0) {
  8694. return _isPreloadSupported;
  8695. }
  8696. let el = document.createElement("link");
  8697. _isPreloadSupported = el.relList.supports("preload");
  8698. el = null;
  8699. return _isPreloadSupported;
  8700. }
  8701. function RemixRootDefaultHydrateFallback() {
  8702. return React5.createElement(BoundaryShell, { title: "Loading...", renderScripts: true }, ENABLE_DEV_WARNINGS ? React5.createElement(
  8703. "script",
  8704. {
  8705. dangerouslySetInnerHTML: {
  8706. __html: `
  8707. console.log(
  8708. "💿 Hey developer 👋. You can provide a way better UX than this " +
  8709. "when your app is loading JS modules and/or running \`clientLoader\` " +
  8710. "functions. Check out https://reactrouter.com/start/framework/route-module#hydratefallback " +
  8711. "for more information."
  8712. );
  8713. `
  8714. }
  8715. }
  8716. ) : null);
  8717. }
  8718. function groupRoutesByParentId(manifest) {
  8719. let routes = {};
  8720. Object.values(manifest).forEach((route) => {
  8721. if (route) {
  8722. let parentId = route.parentId || "";
  8723. if (!routes[parentId]) {
  8724. routes[parentId] = [];
  8725. }
  8726. routes[parentId].push(route);
  8727. }
  8728. });
  8729. return routes;
  8730. }
  8731. function getRouteComponents(route, routeModule, isSpaMode) {
  8732. let Component4 = getRouteModuleComponent(routeModule);
  8733. let HydrateFallback = routeModule.HydrateFallback && (!isSpaMode || route.id === "root") ? routeModule.HydrateFallback : route.id === "root" ? RemixRootDefaultHydrateFallback : void 0;
  8734. let ErrorBoundary = routeModule.ErrorBoundary ? routeModule.ErrorBoundary : route.id === "root" ? () => React6.createElement(RemixRootDefaultErrorBoundary, { error: useRouteError() }) : void 0;
  8735. if (route.id === "root" && routeModule.Layout) {
  8736. return {
  8737. ...Component4 ? {
  8738. element: React6.createElement(routeModule.Layout, null, React6.createElement(Component4, null))
  8739. } : { Component: Component4 },
  8740. ...ErrorBoundary ? {
  8741. errorElement: React6.createElement(routeModule.Layout, null, React6.createElement(ErrorBoundary, null))
  8742. } : { ErrorBoundary },
  8743. ...HydrateFallback ? {
  8744. hydrateFallbackElement: React6.createElement(routeModule.Layout, null, React6.createElement(HydrateFallback, null))
  8745. } : { HydrateFallback }
  8746. };
  8747. }
  8748. return { Component: Component4, ErrorBoundary, HydrateFallback };
  8749. }
  8750. function createServerRoutes(manifest, routeModules, future, isSpaMode, parentId = "", routesByParentId = groupRoutesByParentId(manifest), spaModeLazyPromise = Promise.resolve({ Component: () => null })) {
  8751. return (routesByParentId[parentId] || []).map((route) => {
  8752. let routeModule = routeModules[route.id];
  8753. invariant2(
  8754. routeModule,
  8755. "No `routeModule` available to create server routes"
  8756. );
  8757. let dataRoute = {
  8758. ...getRouteComponents(route, routeModule, isSpaMode),
  8759. caseSensitive: route.caseSensitive,
  8760. id: route.id,
  8761. index: route.index,
  8762. path: route.path,
  8763. handle: routeModule.handle,
  8764. // For SPA Mode, all routes are lazy except root. However we tell the
  8765. // router root is also lazy here too since we don't need a full
  8766. // implementation - we just need a `lazy` prop to tell the RR rendering
  8767. // where to stop which is always at the root route in SPA mode
  8768. lazy: isSpaMode ? () => spaModeLazyPromise : void 0,
  8769. // For partial hydration rendering, we need to indicate when the route
  8770. // has a loader/clientLoader, but it won't ever be called during the static
  8771. // render, so just give it a no-op function so we can render down to the
  8772. // proper fallback
  8773. loader: route.hasLoader || route.hasClientLoader ? () => null : void 0
  8774. // We don't need middleware/action/shouldRevalidate on these routes since
  8775. // they're for a static render
  8776. };
  8777. let children = createServerRoutes(
  8778. manifest,
  8779. routeModules,
  8780. future,
  8781. isSpaMode,
  8782. route.id,
  8783. routesByParentId,
  8784. spaModeLazyPromise
  8785. );
  8786. if (children.length > 0) dataRoute.children = children;
  8787. return dataRoute;
  8788. });
  8789. }
  8790. function createClientRoutesWithHMRRevalidationOptOut(needsRevalidation, manifest, routeModulesCache, initialState, ssr, isSpaMode) {
  8791. return createClientRoutes(
  8792. manifest,
  8793. routeModulesCache,
  8794. initialState,
  8795. ssr,
  8796. isSpaMode,
  8797. "",
  8798. groupRoutesByParentId(manifest),
  8799. needsRevalidation
  8800. );
  8801. }
  8802. function preventInvalidServerHandlerCall(type, route) {
  8803. if (type === "loader" && !route.hasLoader || type === "action" && !route.hasAction) {
  8804. let fn = type === "action" ? "serverAction()" : "serverLoader()";
  8805. let msg = `You are trying to call ${fn} on a route that does not have a server ${type} (routeId: "${route.id}")`;
  8806. console.error(msg);
  8807. throw new ErrorResponseImpl(400, "Bad Request", new Error(msg), true);
  8808. }
  8809. }
  8810. function noActionDefinedError(type, routeId) {
  8811. let article = type === "clientAction" ? "a" : "an";
  8812. let msg = `Route "${routeId}" does not have ${article} ${type}, but you are trying to submit to it. To fix this, please add ${article} \`${type}\` function to the route`;
  8813. console.error(msg);
  8814. throw new ErrorResponseImpl(405, "Method Not Allowed", new Error(msg), true);
  8815. }
  8816. function createClientRoutes(manifest, routeModulesCache, initialState, ssr, isSpaMode, parentId = "", routesByParentId = groupRoutesByParentId(manifest), needsRevalidation) {
  8817. return (routesByParentId[parentId] || []).map((route) => {
  8818. var _a, _b, _c;
  8819. let routeModule = routeModulesCache[route.id];
  8820. function fetchServerHandler(singleFetch) {
  8821. invariant2(
  8822. typeof singleFetch === "function",
  8823. "No single fetch function available for route handler"
  8824. );
  8825. return singleFetch();
  8826. }
  8827. function fetchServerLoader(singleFetch) {
  8828. if (!route.hasLoader) return Promise.resolve(null);
  8829. return fetchServerHandler(singleFetch);
  8830. }
  8831. function fetchServerAction(singleFetch) {
  8832. if (!route.hasAction) {
  8833. throw noActionDefinedError("action", route.id);
  8834. }
  8835. return fetchServerHandler(singleFetch);
  8836. }
  8837. function prefetchModule(modulePath) {
  8838. import(
  8839. /* @vite-ignore */
  8840. /* webpackIgnore: true */
  8841. modulePath
  8842. );
  8843. }
  8844. function prefetchRouteModuleChunks(route2) {
  8845. if (route2.clientActionModule) {
  8846. prefetchModule(route2.clientActionModule);
  8847. }
  8848. if (route2.clientLoaderModule) {
  8849. prefetchModule(route2.clientLoaderModule);
  8850. }
  8851. }
  8852. async function prefetchStylesAndCallHandler(handler) {
  8853. let cachedModule = routeModulesCache[route.id];
  8854. let linkPrefetchPromise = cachedModule ? prefetchStyleLinks(route, cachedModule) : Promise.resolve();
  8855. try {
  8856. return handler();
  8857. } finally {
  8858. await linkPrefetchPromise;
  8859. }
  8860. }
  8861. let dataRoute = {
  8862. id: route.id,
  8863. index: route.index,
  8864. path: route.path
  8865. };
  8866. if (routeModule) {
  8867. Object.assign(dataRoute, {
  8868. ...dataRoute,
  8869. ...getRouteComponents(route, routeModule, isSpaMode),
  8870. middleware: routeModule.clientMiddleware,
  8871. handle: routeModule.handle,
  8872. shouldRevalidate: getShouldRevalidateFunction(
  8873. dataRoute.path,
  8874. routeModule,
  8875. route,
  8876. ssr,
  8877. needsRevalidation
  8878. )
  8879. });
  8880. let hasInitialData = initialState && initialState.loaderData && route.id in initialState.loaderData;
  8881. let initialData = hasInitialData ? (_a = initialState == null ? void 0 : initialState.loaderData) == null ? void 0 : _a[route.id] : void 0;
  8882. let hasInitialError = initialState && initialState.errors && route.id in initialState.errors;
  8883. let initialError = hasInitialError ? (_b = initialState == null ? void 0 : initialState.errors) == null ? void 0 : _b[route.id] : void 0;
  8884. let isHydrationRequest = needsRevalidation == null && (((_c = routeModule.clientLoader) == null ? void 0 : _c.hydrate) === true || !route.hasLoader);
  8885. dataRoute.loader = async ({ request, params, context, unstable_pattern }, singleFetch) => {
  8886. try {
  8887. let result = await prefetchStylesAndCallHandler(async () => {
  8888. invariant2(
  8889. routeModule,
  8890. "No `routeModule` available for critical-route loader"
  8891. );
  8892. if (!routeModule.clientLoader) {
  8893. return fetchServerLoader(singleFetch);
  8894. }
  8895. return routeModule.clientLoader({
  8896. request,
  8897. params,
  8898. context,
  8899. unstable_pattern,
  8900. async serverLoader() {
  8901. preventInvalidServerHandlerCall("loader", route);
  8902. if (isHydrationRequest) {
  8903. if (hasInitialData) {
  8904. return initialData;
  8905. }
  8906. if (hasInitialError) {
  8907. throw initialError;
  8908. }
  8909. }
  8910. return fetchServerLoader(singleFetch);
  8911. }
  8912. });
  8913. });
  8914. return result;
  8915. } finally {
  8916. isHydrationRequest = false;
  8917. }
  8918. };
  8919. dataRoute.loader.hydrate = shouldHydrateRouteLoader(
  8920. route.id,
  8921. routeModule.clientLoader,
  8922. route.hasLoader,
  8923. isSpaMode
  8924. );
  8925. dataRoute.action = ({ request, params, context, unstable_pattern }, singleFetch) => {
  8926. return prefetchStylesAndCallHandler(async () => {
  8927. invariant2(
  8928. routeModule,
  8929. "No `routeModule` available for critical-route action"
  8930. );
  8931. if (!routeModule.clientAction) {
  8932. if (isSpaMode) {
  8933. throw noActionDefinedError("clientAction", route.id);
  8934. }
  8935. return fetchServerAction(singleFetch);
  8936. }
  8937. return routeModule.clientAction({
  8938. request,
  8939. params,
  8940. context,
  8941. unstable_pattern,
  8942. async serverAction() {
  8943. preventInvalidServerHandlerCall("action", route);
  8944. return fetchServerAction(singleFetch);
  8945. }
  8946. });
  8947. });
  8948. };
  8949. } else {
  8950. if (!route.hasClientLoader) {
  8951. dataRoute.loader = (_, singleFetch) => prefetchStylesAndCallHandler(() => {
  8952. return fetchServerLoader(singleFetch);
  8953. });
  8954. }
  8955. if (!route.hasClientAction) {
  8956. dataRoute.action = (_, singleFetch) => prefetchStylesAndCallHandler(() => {
  8957. if (isSpaMode) {
  8958. throw noActionDefinedError("clientAction", route.id);
  8959. }
  8960. return fetchServerAction(singleFetch);
  8961. });
  8962. }
  8963. let lazyRoutePromise;
  8964. async function getLazyRoute() {
  8965. if (lazyRoutePromise) {
  8966. return await lazyRoutePromise;
  8967. }
  8968. lazyRoutePromise = (async () => {
  8969. if (route.clientLoaderModule || route.clientActionModule) {
  8970. await new Promise((resolve) => setTimeout(resolve, 0));
  8971. }
  8972. let routeModulePromise = loadRouteModuleWithBlockingLinks(
  8973. route,
  8974. routeModulesCache
  8975. );
  8976. prefetchRouteModuleChunks(route);
  8977. return await routeModulePromise;
  8978. })();
  8979. return await lazyRoutePromise;
  8980. }
  8981. dataRoute.lazy = {
  8982. loader: route.hasClientLoader ? async () => {
  8983. let { clientLoader } = route.clientLoaderModule ? await import(
  8984. /* @vite-ignore */
  8985. /* webpackIgnore: true */
  8986. route.clientLoaderModule
  8987. ) : await getLazyRoute();
  8988. invariant2(clientLoader, "No `clientLoader` export found");
  8989. return (args, singleFetch) => clientLoader({
  8990. ...args,
  8991. async serverLoader() {
  8992. preventInvalidServerHandlerCall("loader", route);
  8993. return fetchServerLoader(singleFetch);
  8994. }
  8995. });
  8996. } : void 0,
  8997. action: route.hasClientAction ? async () => {
  8998. let clientActionPromise = route.clientActionModule ? import(
  8999. /* @vite-ignore */
  9000. /* webpackIgnore: true */
  9001. route.clientActionModule
  9002. ) : getLazyRoute();
  9003. prefetchRouteModuleChunks(route);
  9004. let { clientAction } = await clientActionPromise;
  9005. invariant2(clientAction, "No `clientAction` export found");
  9006. return (args, singleFetch) => clientAction({
  9007. ...args,
  9008. async serverAction() {
  9009. preventInvalidServerHandlerCall("action", route);
  9010. return fetchServerAction(singleFetch);
  9011. }
  9012. });
  9013. } : void 0,
  9014. middleware: route.hasClientMiddleware ? async () => {
  9015. let { clientMiddleware } = route.clientMiddlewareModule ? await import(
  9016. /* @vite-ignore */
  9017. /* webpackIgnore: true */
  9018. route.clientMiddlewareModule
  9019. ) : await getLazyRoute();
  9020. invariant2(clientMiddleware, "No `clientMiddleware` export found");
  9021. return clientMiddleware;
  9022. } : void 0,
  9023. shouldRevalidate: async () => {
  9024. let lazyRoute = await getLazyRoute();
  9025. return getShouldRevalidateFunction(
  9026. dataRoute.path,
  9027. lazyRoute,
  9028. route,
  9029. ssr,
  9030. needsRevalidation
  9031. );
  9032. },
  9033. handle: async () => (await getLazyRoute()).handle,
  9034. // No need to wrap these in layout since the root route is never
  9035. // loaded via route.lazy()
  9036. Component: async () => (await getLazyRoute()).Component,
  9037. ErrorBoundary: route.hasErrorBoundary ? async () => (await getLazyRoute()).ErrorBoundary : void 0
  9038. };
  9039. }
  9040. let children = createClientRoutes(
  9041. manifest,
  9042. routeModulesCache,
  9043. initialState,
  9044. ssr,
  9045. isSpaMode,
  9046. route.id,
  9047. routesByParentId,
  9048. needsRevalidation
  9049. );
  9050. if (children.length > 0) dataRoute.children = children;
  9051. return dataRoute;
  9052. });
  9053. }
  9054. function getShouldRevalidateFunction(path, route, manifestRoute, ssr, needsRevalidation) {
  9055. if (needsRevalidation) {
  9056. return wrapShouldRevalidateForHdr(
  9057. manifestRoute.id,
  9058. route.shouldRevalidate,
  9059. needsRevalidation
  9060. );
  9061. }
  9062. if (!ssr && manifestRoute.hasLoader && !manifestRoute.hasClientLoader) {
  9063. let myParams = path ? compilePath(path)[1].map((p) => p.paramName) : [];
  9064. const didParamsChange = (opts) => myParams.some((p) => opts.currentParams[p] !== opts.nextParams[p]);
  9065. if (route.shouldRevalidate) {
  9066. let fn = route.shouldRevalidate;
  9067. return (opts) => fn({
  9068. ...opts,
  9069. defaultShouldRevalidate: didParamsChange(opts)
  9070. });
  9071. } else {
  9072. return (opts) => didParamsChange(opts);
  9073. }
  9074. }
  9075. return route.shouldRevalidate;
  9076. }
  9077. function wrapShouldRevalidateForHdr(routeId, routeShouldRevalidate, needsRevalidation) {
  9078. let handledRevalidation = false;
  9079. return (arg) => {
  9080. if (!handledRevalidation) {
  9081. handledRevalidation = true;
  9082. return needsRevalidation.has(routeId);
  9083. }
  9084. return routeShouldRevalidate ? routeShouldRevalidate(arg) : arg.defaultShouldRevalidate;
  9085. };
  9086. }
  9087. async function loadRouteModuleWithBlockingLinks(route, routeModules) {
  9088. let routeModulePromise = loadRouteModule(route, routeModules);
  9089. let prefetchRouteCssPromise = prefetchRouteCss(route);
  9090. let routeModule = await routeModulePromise;
  9091. await Promise.all([
  9092. prefetchRouteCssPromise,
  9093. prefetchStyleLinks(route, routeModule)
  9094. ]);
  9095. return {
  9096. Component: getRouteModuleComponent(routeModule),
  9097. ErrorBoundary: routeModule.ErrorBoundary,
  9098. clientMiddleware: routeModule.clientMiddleware,
  9099. clientAction: routeModule.clientAction,
  9100. clientLoader: routeModule.clientLoader,
  9101. handle: routeModule.handle,
  9102. links: routeModule.links,
  9103. meta: routeModule.meta,
  9104. shouldRevalidate: routeModule.shouldRevalidate
  9105. };
  9106. }
  9107. function getRouteModuleComponent(routeModule) {
  9108. if (routeModule.default == null) return void 0;
  9109. let isEmptyObject = typeof routeModule.default === "object" && Object.keys(routeModule.default).length === 0;
  9110. if (!isEmptyObject) {
  9111. return routeModule.default;
  9112. }
  9113. }
  9114. function shouldHydrateRouteLoader(routeId, clientLoader, hasLoader, isSpaMode) {
  9115. return isSpaMode && routeId !== "root" || clientLoader != null && (clientLoader.hydrate === true || hasLoader !== true);
  9116. }
  9117. var nextPaths = /* @__PURE__ */ new Set();
  9118. var discoveredPathsMaxSize = 1e3;
  9119. var discoveredPaths = /* @__PURE__ */ new Set();
  9120. var URL_LIMIT = 7680;
  9121. function isFogOfWarEnabled(routeDiscovery, ssr) {
  9122. return routeDiscovery.mode === "lazy" && ssr === true;
  9123. }
  9124. function getPartialManifest({ sri, ...manifest }, router2) {
  9125. let routeIds = new Set(router2.state.matches.map((m) => m.route.id));
  9126. let segments = router2.state.location.pathname.split("/").filter(Boolean);
  9127. let paths = ["/"];
  9128. segments.pop();
  9129. while (segments.length > 0) {
  9130. paths.push(`/${segments.join("/")}`);
  9131. segments.pop();
  9132. }
  9133. paths.forEach((path) => {
  9134. let matches = matchRoutes(router2.routes, path, router2.basename);
  9135. if (matches) {
  9136. matches.forEach((m) => routeIds.add(m.route.id));
  9137. }
  9138. });
  9139. let initialRoutes = [...routeIds].reduce(
  9140. (acc, id) => Object.assign(acc, { [id]: manifest.routes[id] }),
  9141. {}
  9142. );
  9143. return {
  9144. ...manifest,
  9145. routes: initialRoutes,
  9146. sri: sri ? true : void 0
  9147. };
  9148. }
  9149. function getPatchRoutesOnNavigationFunction(manifest, routeModules, ssr, routeDiscovery, isSpaMode, basename) {
  9150. if (!isFogOfWarEnabled(routeDiscovery, ssr)) {
  9151. return void 0;
  9152. }
  9153. return async ({ path, patch, signal, fetcherKey }) => {
  9154. if (discoveredPaths.has(path)) {
  9155. return;
  9156. }
  9157. await fetchAndApplyManifestPatches(
  9158. [path],
  9159. fetcherKey ? window.location.href : path,
  9160. manifest,
  9161. routeModules,
  9162. ssr,
  9163. isSpaMode,
  9164. basename,
  9165. routeDiscovery.manifestPath,
  9166. patch,
  9167. signal
  9168. );
  9169. };
  9170. }
  9171. function useFogOFWarDiscovery(router2, manifest, routeModules, ssr, routeDiscovery, isSpaMode) {
  9172. React7.useEffect(() => {
  9173. var _a, _b;
  9174. if (!isFogOfWarEnabled(routeDiscovery, ssr) || // @ts-expect-error - TS doesn't know about this yet
  9175. ((_b = (_a = window.navigator) == null ? void 0 : _a.connection) == null ? void 0 : _b.saveData) === true) {
  9176. return;
  9177. }
  9178. function registerElement(el) {
  9179. let path = el.tagName === "FORM" ? el.getAttribute("action") : el.getAttribute("href");
  9180. if (!path) {
  9181. return;
  9182. }
  9183. let pathname = el.tagName === "A" ? el.pathname : new URL(path, window.location.origin).pathname;
  9184. if (!discoveredPaths.has(pathname)) {
  9185. nextPaths.add(pathname);
  9186. }
  9187. }
  9188. async function fetchPatches() {
  9189. document.querySelectorAll("a[data-discover], form[data-discover]").forEach(registerElement);
  9190. let lazyPaths = Array.from(nextPaths.keys()).filter((path) => {
  9191. if (discoveredPaths.has(path)) {
  9192. nextPaths.delete(path);
  9193. return false;
  9194. }
  9195. return true;
  9196. });
  9197. if (lazyPaths.length === 0) {
  9198. return;
  9199. }
  9200. try {
  9201. await fetchAndApplyManifestPatches(
  9202. lazyPaths,
  9203. null,
  9204. manifest,
  9205. routeModules,
  9206. ssr,
  9207. isSpaMode,
  9208. router2.basename,
  9209. routeDiscovery.manifestPath,
  9210. router2.patchRoutes
  9211. );
  9212. } catch (e) {
  9213. console.error("Failed to fetch manifest patches", e);
  9214. }
  9215. }
  9216. let debouncedFetchPatches = debounce(fetchPatches, 100);
  9217. fetchPatches();
  9218. let observer = new MutationObserver(() => debouncedFetchPatches());
  9219. observer.observe(document.documentElement, {
  9220. subtree: true,
  9221. childList: true,
  9222. attributes: true,
  9223. attributeFilter: ["data-discover", "href", "action"]
  9224. });
  9225. return () => observer.disconnect();
  9226. }, [ssr, isSpaMode, manifest, routeModules, router2, routeDiscovery]);
  9227. }
  9228. function getManifestPath(_manifestPath, basename) {
  9229. let manifestPath = _manifestPath || "/__manifest";
  9230. if (basename == null) {
  9231. return manifestPath;
  9232. }
  9233. return `${basename}${manifestPath}`.replace(/\/+/g, "/");
  9234. }
  9235. var MANIFEST_VERSION_STORAGE_KEY = "react-router-manifest-version";
  9236. async function fetchAndApplyManifestPatches(paths, errorReloadPath, manifest, routeModules, ssr, isSpaMode, basename, manifestPath, patchRoutes, signal) {
  9237. const searchParams = new URLSearchParams();
  9238. searchParams.set("paths", paths.sort().join(","));
  9239. searchParams.set("version", manifest.version);
  9240. let url = new URL(
  9241. getManifestPath(manifestPath, basename),
  9242. window.location.origin
  9243. );
  9244. url.search = searchParams.toString();
  9245. if (url.toString().length > URL_LIMIT) {
  9246. nextPaths.clear();
  9247. return;
  9248. }
  9249. let serverPatches;
  9250. try {
  9251. let res = await fetch(url, { signal });
  9252. if (!res.ok) {
  9253. throw new Error(`${res.status} ${res.statusText}`);
  9254. } else if (res.status === 204 && res.headers.has("X-Remix-Reload-Document")) {
  9255. if (!errorReloadPath) {
  9256. console.warn(
  9257. "Detected a manifest version mismatch during eager route discovery. The next navigation/fetch to an undiscovered route will result in a new document navigation to sync up with the latest manifest."
  9258. );
  9259. return;
  9260. }
  9261. try {
  9262. if (sessionStorage.getItem(MANIFEST_VERSION_STORAGE_KEY) === manifest.version) {
  9263. console.error(
  9264. "Unable to discover routes due to manifest version mismatch."
  9265. );
  9266. return;
  9267. }
  9268. sessionStorage.setItem(MANIFEST_VERSION_STORAGE_KEY, manifest.version);
  9269. } catch {
  9270. }
  9271. window.location.href = errorReloadPath;
  9272. console.warn("Detected manifest version mismatch, reloading...");
  9273. await new Promise(() => {
  9274. });
  9275. } else if (res.status >= 400) {
  9276. throw new Error(await res.text());
  9277. }
  9278. try {
  9279. sessionStorage.removeItem(MANIFEST_VERSION_STORAGE_KEY);
  9280. } catch {
  9281. }
  9282. serverPatches = await res.json();
  9283. } catch (e) {
  9284. if (signal == null ? void 0 : signal.aborted) return;
  9285. throw e;
  9286. }
  9287. let knownRoutes = new Set(Object.keys(manifest.routes));
  9288. let patches = Object.values(serverPatches).reduce((acc, route) => {
  9289. if (route && !knownRoutes.has(route.id)) {
  9290. acc[route.id] = route;
  9291. }
  9292. return acc;
  9293. }, {});
  9294. Object.assign(manifest.routes, patches);
  9295. paths.forEach((p) => addToFifoQueue(p, discoveredPaths));
  9296. let parentIds = /* @__PURE__ */ new Set();
  9297. Object.values(patches).forEach((patch) => {
  9298. if (patch && (!patch.parentId || !patches[patch.parentId])) {
  9299. parentIds.add(patch.parentId);
  9300. }
  9301. });
  9302. parentIds.forEach(
  9303. (parentId) => patchRoutes(
  9304. parentId || null,
  9305. createClientRoutes(patches, routeModules, null, ssr, isSpaMode, parentId)
  9306. )
  9307. );
  9308. }
  9309. function addToFifoQueue(path, queue) {
  9310. if (queue.size >= discoveredPathsMaxSize) {
  9311. let first = queue.values().next().value;
  9312. queue.delete(first);
  9313. }
  9314. queue.add(path);
  9315. }
  9316. function debounce(callback, wait) {
  9317. let timeoutId;
  9318. return (...args) => {
  9319. window.clearTimeout(timeoutId);
  9320. timeoutId = window.setTimeout(() => callback(...args), wait);
  9321. };
  9322. }
  9323. function useDataRouterContext2() {
  9324. let context = React8.useContext(DataRouterContext);
  9325. invariant2(
  9326. context,
  9327. "You must render this element inside a <DataRouterContext.Provider> element"
  9328. );
  9329. return context;
  9330. }
  9331. function useDataRouterStateContext() {
  9332. let context = React8.useContext(DataRouterStateContext);
  9333. invariant2(
  9334. context,
  9335. "You must render this element inside a <DataRouterStateContext.Provider> element"
  9336. );
  9337. return context;
  9338. }
  9339. var FrameworkContext = React8.createContext(void 0);
  9340. FrameworkContext.displayName = "FrameworkContext";
  9341. function useFrameworkContext() {
  9342. let context = React8.useContext(FrameworkContext);
  9343. invariant2(
  9344. context,
  9345. "You must render this element inside a <HydratedRouter> element"
  9346. );
  9347. return context;
  9348. }
  9349. function usePrefetchBehavior(prefetch, theirElementProps) {
  9350. let frameworkContext = React8.useContext(FrameworkContext);
  9351. let [maybePrefetch, setMaybePrefetch] = React8.useState(false);
  9352. let [shouldPrefetch, setShouldPrefetch] = React8.useState(false);
  9353. let { onFocus, onBlur, onMouseEnter, onMouseLeave, onTouchStart } = theirElementProps;
  9354. let ref = React8.useRef(null);
  9355. React8.useEffect(() => {
  9356. if (prefetch === "render") {
  9357. setShouldPrefetch(true);
  9358. }
  9359. if (prefetch === "viewport") {
  9360. let callback = (entries) => {
  9361. entries.forEach((entry) => {
  9362. setShouldPrefetch(entry.isIntersecting);
  9363. });
  9364. };
  9365. let observer = new IntersectionObserver(callback, { threshold: 0.5 });
  9366. if (ref.current) observer.observe(ref.current);
  9367. return () => {
  9368. observer.disconnect();
  9369. };
  9370. }
  9371. }, [prefetch]);
  9372. React8.useEffect(() => {
  9373. if (maybePrefetch) {
  9374. let id = setTimeout(() => {
  9375. setShouldPrefetch(true);
  9376. }, 100);
  9377. return () => {
  9378. clearTimeout(id);
  9379. };
  9380. }
  9381. }, [maybePrefetch]);
  9382. let setIntent = () => {
  9383. setMaybePrefetch(true);
  9384. };
  9385. let cancelIntent = () => {
  9386. setMaybePrefetch(false);
  9387. setShouldPrefetch(false);
  9388. };
  9389. if (!frameworkContext) {
  9390. return [false, ref, {}];
  9391. }
  9392. if (prefetch !== "intent") {
  9393. return [shouldPrefetch, ref, {}];
  9394. }
  9395. return [
  9396. shouldPrefetch,
  9397. ref,
  9398. {
  9399. onFocus: composeEventHandlers(onFocus, setIntent),
  9400. onBlur: composeEventHandlers(onBlur, cancelIntent),
  9401. onMouseEnter: composeEventHandlers(onMouseEnter, setIntent),
  9402. onMouseLeave: composeEventHandlers(onMouseLeave, cancelIntent),
  9403. onTouchStart: composeEventHandlers(onTouchStart, setIntent)
  9404. }
  9405. ];
  9406. }
  9407. function composeEventHandlers(theirHandler, ourHandler) {
  9408. return (event) => {
  9409. theirHandler && theirHandler(event);
  9410. if (!event.defaultPrevented) {
  9411. ourHandler(event);
  9412. }
  9413. };
  9414. }
  9415. function getActiveMatches(matches, errors, isSpaMode) {
  9416. if (isSpaMode && !isHydrated) {
  9417. return [matches[0]];
  9418. }
  9419. if (errors) {
  9420. let errorIdx = matches.findIndex((m) => errors[m.route.id] !== void 0);
  9421. return matches.slice(0, errorIdx + 1);
  9422. }
  9423. return matches;
  9424. }
  9425. var CRITICAL_CSS_DATA_ATTRIBUTE = "data-react-router-critical-css";
  9426. function Links({ nonce }) {
  9427. let { isSpaMode, manifest, routeModules, criticalCss } = useFrameworkContext();
  9428. let { errors, matches: routerMatches } = useDataRouterStateContext();
  9429. let matches = getActiveMatches(routerMatches, errors, isSpaMode);
  9430. let keyedLinks = React8.useMemo(
  9431. () => getKeyedLinksForMatches(matches, routeModules, manifest),
  9432. [matches, routeModules, manifest]
  9433. );
  9434. return React8.createElement(React8.Fragment, null, typeof criticalCss === "string" ? React8.createElement(
  9435. "style",
  9436. {
  9437. ...{ [CRITICAL_CSS_DATA_ATTRIBUTE]: "" },
  9438. dangerouslySetInnerHTML: { __html: criticalCss }
  9439. }
  9440. ) : null, typeof criticalCss === "object" ? React8.createElement(
  9441. "link",
  9442. {
  9443. ...{ [CRITICAL_CSS_DATA_ATTRIBUTE]: "" },
  9444. rel: "stylesheet",
  9445. href: criticalCss.href,
  9446. nonce
  9447. }
  9448. ) : null, keyedLinks.map(
  9449. ({ key, link }) => isPageLinkDescriptor(link) ? React8.createElement(PrefetchPageLinks, { key, nonce, ...link }) : React8.createElement("link", { key, nonce, ...link })
  9450. ));
  9451. }
  9452. function PrefetchPageLinks({ page, ...linkProps }) {
  9453. let { router: router2 } = useDataRouterContext2();
  9454. let matches = React8.useMemo(
  9455. () => matchRoutes(router2.routes, page, router2.basename),
  9456. [router2.routes, page, router2.basename]
  9457. );
  9458. if (!matches) {
  9459. return null;
  9460. }
  9461. return React8.createElement(PrefetchPageLinksImpl, { page, matches, ...linkProps });
  9462. }
  9463. function useKeyedPrefetchLinks(matches) {
  9464. let { manifest, routeModules } = useFrameworkContext();
  9465. let [keyedPrefetchLinks, setKeyedPrefetchLinks] = React8.useState([]);
  9466. React8.useEffect(() => {
  9467. let interrupted = false;
  9468. void getKeyedPrefetchLinks(matches, manifest, routeModules).then(
  9469. (links) => {
  9470. if (!interrupted) {
  9471. setKeyedPrefetchLinks(links);
  9472. }
  9473. }
  9474. );
  9475. return () => {
  9476. interrupted = true;
  9477. };
  9478. }, [matches, manifest, routeModules]);
  9479. return keyedPrefetchLinks;
  9480. }
  9481. function PrefetchPageLinksImpl({
  9482. page,
  9483. matches: nextMatches,
  9484. ...linkProps
  9485. }) {
  9486. let location2 = useLocation();
  9487. let { manifest, routeModules } = useFrameworkContext();
  9488. let { basename } = useDataRouterContext2();
  9489. let { loaderData, matches } = useDataRouterStateContext();
  9490. let newMatchesForData = React8.useMemo(
  9491. () => getNewMatchesForLinks(
  9492. page,
  9493. nextMatches,
  9494. matches,
  9495. manifest,
  9496. location2,
  9497. "data"
  9498. ),
  9499. [page, nextMatches, matches, manifest, location2]
  9500. );
  9501. let newMatchesForAssets = React8.useMemo(
  9502. () => getNewMatchesForLinks(
  9503. page,
  9504. nextMatches,
  9505. matches,
  9506. manifest,
  9507. location2,
  9508. "assets"
  9509. ),
  9510. [page, nextMatches, matches, manifest, location2]
  9511. );
  9512. let dataHrefs = React8.useMemo(() => {
  9513. if (page === location2.pathname + location2.search + location2.hash) {
  9514. return [];
  9515. }
  9516. let routesParams = /* @__PURE__ */ new Set();
  9517. let foundOptOutRoute = false;
  9518. nextMatches.forEach((m) => {
  9519. var _a;
  9520. let manifestRoute = manifest.routes[m.route.id];
  9521. if (!manifestRoute || !manifestRoute.hasLoader) {
  9522. return;
  9523. }
  9524. if (!newMatchesForData.some((m2) => m2.route.id === m.route.id) && m.route.id in loaderData && ((_a = routeModules[m.route.id]) == null ? void 0 : _a.shouldRevalidate)) {
  9525. foundOptOutRoute = true;
  9526. } else if (manifestRoute.hasClientLoader) {
  9527. foundOptOutRoute = true;
  9528. } else {
  9529. routesParams.add(m.route.id);
  9530. }
  9531. });
  9532. if (routesParams.size === 0) {
  9533. return [];
  9534. }
  9535. let url = singleFetchUrl(page, basename, "data");
  9536. if (foundOptOutRoute && routesParams.size > 0) {
  9537. url.searchParams.set(
  9538. "_routes",
  9539. nextMatches.filter((m) => routesParams.has(m.route.id)).map((m) => m.route.id).join(",")
  9540. );
  9541. }
  9542. return [url.pathname + url.search];
  9543. }, [
  9544. basename,
  9545. loaderData,
  9546. location2,
  9547. manifest,
  9548. newMatchesForData,
  9549. nextMatches,
  9550. page,
  9551. routeModules
  9552. ]);
  9553. let moduleHrefs = React8.useMemo(
  9554. () => getModuleLinkHrefs(newMatchesForAssets, manifest),
  9555. [newMatchesForAssets, manifest]
  9556. );
  9557. let keyedPrefetchLinks = useKeyedPrefetchLinks(newMatchesForAssets);
  9558. return React8.createElement(React8.Fragment, null, dataHrefs.map((href2) => React8.createElement("link", { key: href2, rel: "prefetch", as: "fetch", href: href2, ...linkProps })), moduleHrefs.map((href2) => React8.createElement("link", { key: href2, rel: "modulepreload", href: href2, ...linkProps })), keyedPrefetchLinks.map(({ key, link }) => (
  9559. // these don't spread `linkProps` because they are full link descriptors
  9560. // already with their own props
  9561. React8.createElement("link", { key, nonce: linkProps.nonce, ...link })
  9562. )));
  9563. }
  9564. function Meta() {
  9565. let { isSpaMode, routeModules } = useFrameworkContext();
  9566. let {
  9567. errors,
  9568. matches: routerMatches,
  9569. loaderData
  9570. } = useDataRouterStateContext();
  9571. let location2 = useLocation();
  9572. let _matches = getActiveMatches(routerMatches, errors, isSpaMode);
  9573. let error = null;
  9574. if (errors) {
  9575. error = errors[_matches[_matches.length - 1].route.id];
  9576. }
  9577. let meta = [];
  9578. let leafMeta = null;
  9579. let matches = [];
  9580. for (let i = 0; i < _matches.length; i++) {
  9581. let _match = _matches[i];
  9582. let routeId = _match.route.id;
  9583. let data2 = loaderData[routeId];
  9584. let params = _match.params;
  9585. let routeModule = routeModules[routeId];
  9586. let routeMeta = [];
  9587. let match = {
  9588. id: routeId,
  9589. data: data2,
  9590. loaderData: data2,
  9591. meta: [],
  9592. params: _match.params,
  9593. pathname: _match.pathname,
  9594. handle: _match.route.handle,
  9595. error
  9596. };
  9597. matches[i] = match;
  9598. if (routeModule == null ? void 0 : routeModule.meta) {
  9599. routeMeta = typeof routeModule.meta === "function" ? routeModule.meta({
  9600. data: data2,
  9601. loaderData: data2,
  9602. params,
  9603. location: location2,
  9604. matches,
  9605. error
  9606. }) : Array.isArray(routeModule.meta) ? [...routeModule.meta] : routeModule.meta;
  9607. } else if (leafMeta) {
  9608. routeMeta = [...leafMeta];
  9609. }
  9610. routeMeta = routeMeta || [];
  9611. if (!Array.isArray(routeMeta)) {
  9612. throw new Error(
  9613. "The route at " + _match.route.path + " returns an invalid value. All route meta functions must return an array of meta objects.\n\nTo reference the meta function API, see https://remix.run/route/meta"
  9614. );
  9615. }
  9616. match.meta = routeMeta;
  9617. matches[i] = match;
  9618. meta = [...routeMeta];
  9619. leafMeta = meta;
  9620. }
  9621. return React8.createElement(React8.Fragment, null, meta.flat().map((metaProps) => {
  9622. if (!metaProps) {
  9623. return null;
  9624. }
  9625. if ("tagName" in metaProps) {
  9626. let { tagName, ...rest } = metaProps;
  9627. if (!isValidMetaTag(tagName)) {
  9628. console.warn(
  9629. `A meta object uses an invalid tagName: ${tagName}. Expected either 'link' or 'meta'`
  9630. );
  9631. return null;
  9632. }
  9633. let Comp = tagName;
  9634. return React8.createElement(Comp, { key: JSON.stringify(rest), ...rest });
  9635. }
  9636. if ("title" in metaProps) {
  9637. return React8.createElement("title", { key: "title" }, String(metaProps.title));
  9638. }
  9639. if ("charset" in metaProps) {
  9640. metaProps.charSet ?? (metaProps.charSet = metaProps.charset);
  9641. delete metaProps.charset;
  9642. }
  9643. if ("charSet" in metaProps && metaProps.charSet != null) {
  9644. return typeof metaProps.charSet === "string" ? React8.createElement("meta", { key: "charSet", charSet: metaProps.charSet }) : null;
  9645. }
  9646. if ("script:ld+json" in metaProps) {
  9647. try {
  9648. let json = JSON.stringify(metaProps["script:ld+json"]);
  9649. return React8.createElement(
  9650. "script",
  9651. {
  9652. key: `script:ld+json:${json}`,
  9653. type: "application/ld+json",
  9654. dangerouslySetInnerHTML: { __html: escapeHtml(json) }
  9655. }
  9656. );
  9657. } catch (err) {
  9658. return null;
  9659. }
  9660. }
  9661. return React8.createElement("meta", { key: JSON.stringify(metaProps), ...metaProps });
  9662. }));
  9663. }
  9664. function isValidMetaTag(tagName) {
  9665. return typeof tagName === "string" && /^(meta|link)$/.test(tagName);
  9666. }
  9667. var isHydrated = false;
  9668. function setIsHydrated() {
  9669. isHydrated = true;
  9670. }
  9671. function Scripts(scriptProps) {
  9672. let {
  9673. manifest,
  9674. serverHandoffString,
  9675. isSpaMode,
  9676. renderMeta,
  9677. routeDiscovery,
  9678. ssr
  9679. } = useFrameworkContext();
  9680. let { router: router2, static: isStatic, staticContext } = useDataRouterContext2();
  9681. let { matches: routerMatches } = useDataRouterStateContext();
  9682. let isRSCRouterContext = useIsRSCRouterContext();
  9683. let enableFogOfWar = isFogOfWarEnabled(routeDiscovery, ssr);
  9684. if (renderMeta) {
  9685. renderMeta.didRenderScripts = true;
  9686. }
  9687. let matches = getActiveMatches(routerMatches, null, isSpaMode);
  9688. React8.useEffect(() => {
  9689. setIsHydrated();
  9690. }, []);
  9691. let initialScripts = React8.useMemo(() => {
  9692. var _a;
  9693. if (isRSCRouterContext) {
  9694. return null;
  9695. }
  9696. let streamScript = "window.__reactRouterContext.stream = new ReadableStream({start(controller){window.__reactRouterContext.streamController = controller;}}).pipeThrough(new TextEncoderStream());";
  9697. let contextScript = staticContext ? `window.__reactRouterContext = ${serverHandoffString};${streamScript}` : " ";
  9698. let routeModulesScript = !isStatic ? " " : `${((_a = manifest.hmr) == null ? void 0 : _a.runtime) ? `import ${JSON.stringify(manifest.hmr.runtime)};` : ""}${!enableFogOfWar ? `import ${JSON.stringify(manifest.url)}` : ""};
  9699. ${matches.map((match, routeIndex) => {
  9700. let routeVarName = `route${routeIndex}`;
  9701. let manifestEntry = manifest.routes[match.route.id];
  9702. invariant2(manifestEntry, `Route ${match.route.id} not found in manifest`);
  9703. let {
  9704. clientActionModule,
  9705. clientLoaderModule,
  9706. clientMiddlewareModule,
  9707. hydrateFallbackModule,
  9708. module
  9709. } = manifestEntry;
  9710. let chunks = [
  9711. ...clientActionModule ? [
  9712. {
  9713. module: clientActionModule,
  9714. varName: `${routeVarName}_clientAction`
  9715. }
  9716. ] : [],
  9717. ...clientLoaderModule ? [
  9718. {
  9719. module: clientLoaderModule,
  9720. varName: `${routeVarName}_clientLoader`
  9721. }
  9722. ] : [],
  9723. ...clientMiddlewareModule ? [
  9724. {
  9725. module: clientMiddlewareModule,
  9726. varName: `${routeVarName}_clientMiddleware`
  9727. }
  9728. ] : [],
  9729. ...hydrateFallbackModule ? [
  9730. {
  9731. module: hydrateFallbackModule,
  9732. varName: `${routeVarName}_HydrateFallback`
  9733. }
  9734. ] : [],
  9735. { module, varName: `${routeVarName}_main` }
  9736. ];
  9737. if (chunks.length === 1) {
  9738. return `import * as ${routeVarName} from ${JSON.stringify(module)};`;
  9739. }
  9740. let chunkImportsSnippet = chunks.map((chunk) => `import * as ${chunk.varName} from "${chunk.module}";`).join("\n");
  9741. let mergedChunksSnippet = `const ${routeVarName} = {${chunks.map((chunk) => `...${chunk.varName}`).join(",")}};`;
  9742. return [chunkImportsSnippet, mergedChunksSnippet].join("\n");
  9743. }).join("\n")}
  9744. ${enableFogOfWar ? (
  9745. // Inline a minimal manifest with the SSR matches
  9746. `window.__reactRouterManifest = ${JSON.stringify(
  9747. getPartialManifest(manifest, router2),
  9748. null,
  9749. 2
  9750. )};`
  9751. ) : ""}
  9752. window.__reactRouterRouteModules = {${matches.map((match, index) => `${JSON.stringify(match.route.id)}:route${index}`).join(",")}};
  9753. import(${JSON.stringify(manifest.entry.module)});`;
  9754. return React8.createElement(React8.Fragment, null, React8.createElement(
  9755. "script",
  9756. {
  9757. ...scriptProps,
  9758. suppressHydrationWarning: true,
  9759. dangerouslySetInnerHTML: { __html: contextScript },
  9760. type: void 0
  9761. }
  9762. ), React8.createElement(
  9763. "script",
  9764. {
  9765. ...scriptProps,
  9766. suppressHydrationWarning: true,
  9767. dangerouslySetInnerHTML: { __html: routeModulesScript },
  9768. type: "module",
  9769. async: true
  9770. }
  9771. ));
  9772. }, []);
  9773. let preloads = isHydrated || isRSCRouterContext ? [] : dedupe(
  9774. manifest.entry.imports.concat(
  9775. getModuleLinkHrefs(matches, manifest, {
  9776. includeHydrateFallback: true
  9777. })
  9778. )
  9779. );
  9780. let sri = typeof manifest.sri === "object" ? manifest.sri : {};
  9781. warnOnce(
  9782. !isRSCRouterContext,
  9783. "The <Scripts /> element is a no-op when using RSC and can be safely removed."
  9784. );
  9785. return isHydrated || isRSCRouterContext ? null : React8.createElement(React8.Fragment, null, typeof manifest.sri === "object" ? React8.createElement(
  9786. "script",
  9787. {
  9788. "rr-importmap": "",
  9789. type: "importmap",
  9790. suppressHydrationWarning: true,
  9791. dangerouslySetInnerHTML: {
  9792. __html: JSON.stringify({
  9793. integrity: sri
  9794. })
  9795. }
  9796. }
  9797. ) : null, !enableFogOfWar ? React8.createElement(
  9798. "link",
  9799. {
  9800. rel: "modulepreload",
  9801. href: manifest.url,
  9802. crossOrigin: scriptProps.crossOrigin,
  9803. integrity: sri[manifest.url],
  9804. suppressHydrationWarning: true
  9805. }
  9806. ) : null, React8.createElement(
  9807. "link",
  9808. {
  9809. rel: "modulepreload",
  9810. href: manifest.entry.module,
  9811. crossOrigin: scriptProps.crossOrigin,
  9812. integrity: sri[manifest.entry.module],
  9813. suppressHydrationWarning: true
  9814. }
  9815. ), preloads.map((path) => React8.createElement(
  9816. "link",
  9817. {
  9818. key: path,
  9819. rel: "modulepreload",
  9820. href: path,
  9821. crossOrigin: scriptProps.crossOrigin,
  9822. integrity: sri[path],
  9823. suppressHydrationWarning: true
  9824. }
  9825. )), initialScripts);
  9826. }
  9827. function dedupe(array) {
  9828. return [...new Set(array)];
  9829. }
  9830. function mergeRefs(...refs) {
  9831. return (value) => {
  9832. refs.forEach((ref) => {
  9833. if (typeof ref === "function") {
  9834. ref(value);
  9835. } else if (ref != null) {
  9836. ref.current = value;
  9837. }
  9838. });
  9839. };
  9840. }
  9841. var RemixErrorBoundary = class extends React9.Component {
  9842. constructor(props) {
  9843. super(props);
  9844. this.state = { error: props.error || null, location: props.location };
  9845. }
  9846. static getDerivedStateFromError(error) {
  9847. return { error };
  9848. }
  9849. static getDerivedStateFromProps(props, state) {
  9850. if (state.location !== props.location) {
  9851. return { error: props.error || null, location: props.location };
  9852. }
  9853. return { error: props.error || state.error, location: state.location };
  9854. }
  9855. render() {
  9856. if (this.state.error) {
  9857. return React9.createElement(
  9858. RemixRootDefaultErrorBoundary,
  9859. {
  9860. error: this.state.error,
  9861. isOutsideRemixApp: true
  9862. }
  9863. );
  9864. } else {
  9865. return this.props.children;
  9866. }
  9867. }
  9868. };
  9869. function RemixRootDefaultErrorBoundary({
  9870. error,
  9871. isOutsideRemixApp
  9872. }) {
  9873. console.error(error);
  9874. let heyDeveloper = React9.createElement(
  9875. "script",
  9876. {
  9877. dangerouslySetInnerHTML: {
  9878. __html: `
  9879. console.log(
  9880. "💿 Hey developer 👋. You can provide a way better UX than this when your app throws errors. Check out https://reactrouter.com/how-to/error-boundary for more information."
  9881. );
  9882. `
  9883. }
  9884. }
  9885. );
  9886. if (isRouteErrorResponse(error)) {
  9887. return React9.createElement(BoundaryShell, { title: "Unhandled Thrown Response!" }, React9.createElement("h1", { style: { fontSize: "24px" } }, error.status, " ", error.statusText), ENABLE_DEV_WARNINGS ? heyDeveloper : null);
  9888. }
  9889. let errorInstance;
  9890. if (error instanceof Error) {
  9891. errorInstance = error;
  9892. } else {
  9893. let errorString = error == null ? "Unknown Error" : typeof error === "object" && "toString" in error ? error.toString() : JSON.stringify(error);
  9894. errorInstance = new Error(errorString);
  9895. }
  9896. return React9.createElement(
  9897. BoundaryShell,
  9898. {
  9899. title: "Application Error!",
  9900. isOutsideRemixApp
  9901. },
  9902. React9.createElement("h1", { style: { fontSize: "24px" } }, "Application Error"),
  9903. React9.createElement(
  9904. "pre",
  9905. {
  9906. style: {
  9907. padding: "2rem",
  9908. background: "hsla(10, 50%, 50%, 0.1)",
  9909. color: "red",
  9910. overflow: "auto"
  9911. }
  9912. },
  9913. errorInstance.stack
  9914. ),
  9915. heyDeveloper
  9916. );
  9917. }
  9918. function BoundaryShell({
  9919. title,
  9920. renderScripts,
  9921. isOutsideRemixApp,
  9922. children
  9923. }) {
  9924. var _a;
  9925. let { routeModules } = useFrameworkContext();
  9926. if (((_a = routeModules.root) == null ? void 0 : _a.Layout) && !isOutsideRemixApp) {
  9927. return children;
  9928. }
  9929. return React9.createElement("html", { lang: "en" }, React9.createElement("head", null, React9.createElement("meta", { charSet: "utf-8" }), React9.createElement(
  9930. "meta",
  9931. {
  9932. name: "viewport",
  9933. content: "width=device-width,initial-scale=1,viewport-fit=cover"
  9934. }
  9935. ), React9.createElement("title", null, title)), React9.createElement("body", null, React9.createElement("main", { style: { fontFamily: "system-ui, sans-serif", padding: "2rem" } }, children, renderScripts ? React9.createElement(Scripts, null) : null)));
  9936. }
  9937. var isBrowser = typeof window !== "undefined" && typeof window.document !== "undefined" && typeof window.document.createElement !== "undefined";
  9938. try {
  9939. if (isBrowser) {
  9940. window.__reactRouterVersion = // @ts-expect-error
  9941. "7.10.1";
  9942. }
  9943. } catch (e) {
  9944. }
  9945. function createBrowserRouter(routes, opts) {
  9946. return createRouter({
  9947. basename: opts == null ? void 0 : opts.basename,
  9948. getContext: opts == null ? void 0 : opts.getContext,
  9949. future: opts == null ? void 0 : opts.future,
  9950. history: createBrowserHistory({ window: opts == null ? void 0 : opts.window }),
  9951. hydrationData: (opts == null ? void 0 : opts.hydrationData) || parseHydrationData(),
  9952. routes,
  9953. mapRouteProperties,
  9954. hydrationRouteProperties,
  9955. dataStrategy: opts == null ? void 0 : opts.dataStrategy,
  9956. patchRoutesOnNavigation: opts == null ? void 0 : opts.patchRoutesOnNavigation,
  9957. window: opts == null ? void 0 : opts.window,
  9958. unstable_instrumentations: opts == null ? void 0 : opts.unstable_instrumentations
  9959. }).initialize();
  9960. }
  9961. function createHashRouter(routes, opts) {
  9962. return createRouter({
  9963. basename: opts == null ? void 0 : opts.basename,
  9964. getContext: opts == null ? void 0 : opts.getContext,
  9965. future: opts == null ? void 0 : opts.future,
  9966. history: createHashHistory({ window: opts == null ? void 0 : opts.window }),
  9967. hydrationData: (opts == null ? void 0 : opts.hydrationData) || parseHydrationData(),
  9968. routes,
  9969. mapRouteProperties,
  9970. hydrationRouteProperties,
  9971. dataStrategy: opts == null ? void 0 : opts.dataStrategy,
  9972. patchRoutesOnNavigation: opts == null ? void 0 : opts.patchRoutesOnNavigation,
  9973. window: opts == null ? void 0 : opts.window,
  9974. unstable_instrumentations: opts == null ? void 0 : opts.unstable_instrumentations
  9975. }).initialize();
  9976. }
  9977. function parseHydrationData() {
  9978. let state = window == null ? void 0 : window.__staticRouterHydrationData;
  9979. if (state && state.errors) {
  9980. state = {
  9981. ...state,
  9982. errors: deserializeErrors(state.errors)
  9983. };
  9984. }
  9985. return state;
  9986. }
  9987. function deserializeErrors(errors) {
  9988. if (!errors) return null;
  9989. let entries = Object.entries(errors);
  9990. let serialized = {};
  9991. for (let [key, val] of entries) {
  9992. if (val && val.__type === "RouteErrorResponse") {
  9993. serialized[key] = new ErrorResponseImpl(
  9994. val.status,
  9995. val.statusText,
  9996. val.data,
  9997. val.internal === true
  9998. );
  9999. } else if (val && val.__type === "Error") {
  10000. if (val.__subType) {
  10001. let ErrorConstructor = window[val.__subType];
  10002. if (typeof ErrorConstructor === "function") {
  10003. try {
  10004. let error = new ErrorConstructor(val.message);
  10005. error.stack = "";
  10006. serialized[key] = error;
  10007. } catch (e) {
  10008. }
  10009. }
  10010. }
  10011. if (serialized[key] == null) {
  10012. let error = new Error(val.message);
  10013. error.stack = "";
  10014. serialized[key] = error;
  10015. }
  10016. } else {
  10017. serialized[key] = val;
  10018. }
  10019. }
  10020. return serialized;
  10021. }
  10022. function BrowserRouter({
  10023. basename,
  10024. children,
  10025. unstable_useTransitions,
  10026. window: window2
  10027. }) {
  10028. let historyRef = React10.useRef();
  10029. if (historyRef.current == null) {
  10030. historyRef.current = createBrowserHistory({ window: window2, v5Compat: true });
  10031. }
  10032. let history = historyRef.current;
  10033. let [state, setStateImpl] = React10.useState({
  10034. action: history.action,
  10035. location: history.location
  10036. });
  10037. let setState = React10.useCallback(
  10038. (newState) => {
  10039. if (unstable_useTransitions === false) {
  10040. setStateImpl(newState);
  10041. } else {
  10042. React10.startTransition(() => setStateImpl(newState));
  10043. }
  10044. },
  10045. [unstable_useTransitions]
  10046. );
  10047. React10.useLayoutEffect(() => history.listen(setState), [history, setState]);
  10048. return React10.createElement(
  10049. Router,
  10050. {
  10051. basename,
  10052. children,
  10053. location: state.location,
  10054. navigationType: state.action,
  10055. navigator: history,
  10056. unstable_useTransitions: unstable_useTransitions === true
  10057. }
  10058. );
  10059. }
  10060. function HashRouter({
  10061. basename,
  10062. children,
  10063. unstable_useTransitions,
  10064. window: window2
  10065. }) {
  10066. let historyRef = React10.useRef();
  10067. if (historyRef.current == null) {
  10068. historyRef.current = createHashHistory({ window: window2, v5Compat: true });
  10069. }
  10070. let history = historyRef.current;
  10071. let [state, setStateImpl] = React10.useState({
  10072. action: history.action,
  10073. location: history.location
  10074. });
  10075. let setState = React10.useCallback(
  10076. (newState) => {
  10077. if (unstable_useTransitions === false) {
  10078. setStateImpl(newState);
  10079. } else {
  10080. React10.startTransition(() => setStateImpl(newState));
  10081. }
  10082. },
  10083. [unstable_useTransitions]
  10084. );
  10085. React10.useLayoutEffect(() => history.listen(setState), [history, setState]);
  10086. return React10.createElement(
  10087. Router,
  10088. {
  10089. basename,
  10090. children,
  10091. location: state.location,
  10092. navigationType: state.action,
  10093. navigator: history,
  10094. unstable_useTransitions: unstable_useTransitions === true
  10095. }
  10096. );
  10097. }
  10098. function HistoryRouter({
  10099. basename,
  10100. children,
  10101. history,
  10102. unstable_useTransitions
  10103. }) {
  10104. let [state, setStateImpl] = React10.useState({
  10105. action: history.action,
  10106. location: history.location
  10107. });
  10108. let setState = React10.useCallback(
  10109. (newState) => {
  10110. if (unstable_useTransitions === false) {
  10111. setStateImpl(newState);
  10112. } else {
  10113. React10.startTransition(() => setStateImpl(newState));
  10114. }
  10115. },
  10116. [unstable_useTransitions]
  10117. );
  10118. React10.useLayoutEffect(() => history.listen(setState), [history, setState]);
  10119. return React10.createElement(
  10120. Router,
  10121. {
  10122. basename,
  10123. children,
  10124. location: state.location,
  10125. navigationType: state.action,
  10126. navigator: history,
  10127. unstable_useTransitions: unstable_useTransitions === true
  10128. }
  10129. );
  10130. }
  10131. HistoryRouter.displayName = "unstable_HistoryRouter";
  10132. var ABSOLUTE_URL_REGEX2 = /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i;
  10133. var Link = React10.forwardRef(
  10134. function LinkWithRef({
  10135. onClick,
  10136. discover = "render",
  10137. prefetch = "none",
  10138. relative,
  10139. reloadDocument,
  10140. replace: replace2,
  10141. state,
  10142. target,
  10143. to,
  10144. preventScrollReset,
  10145. viewTransition,
  10146. ...rest
  10147. }, forwardedRef) {
  10148. let { basename, unstable_useTransitions } = React10.useContext(NavigationContext);
  10149. let isAbsolute = typeof to === "string" && ABSOLUTE_URL_REGEX2.test(to);
  10150. let absoluteHref;
  10151. let isExternal = false;
  10152. if (typeof to === "string" && isAbsolute) {
  10153. absoluteHref = to;
  10154. if (isBrowser) {
  10155. try {
  10156. let currentUrl = new URL(window.location.href);
  10157. let targetUrl = to.startsWith("//") ? new URL(currentUrl.protocol + to) : new URL(to);
  10158. let path = stripBasename(targetUrl.pathname, basename);
  10159. if (targetUrl.origin === currentUrl.origin && path != null) {
  10160. to = path + targetUrl.search + targetUrl.hash;
  10161. } else {
  10162. isExternal = true;
  10163. }
  10164. } catch (e) {
  10165. warning(
  10166. false,
  10167. `<Link to="${to}"> contains an invalid URL which will probably break when clicked - please update to a valid URL path.`
  10168. );
  10169. }
  10170. }
  10171. }
  10172. let href2 = useHref(to, { relative });
  10173. let [shouldPrefetch, prefetchRef, prefetchHandlers] = usePrefetchBehavior(
  10174. prefetch,
  10175. rest
  10176. );
  10177. let internalOnClick = useLinkClickHandler(to, {
  10178. replace: replace2,
  10179. state,
  10180. target,
  10181. preventScrollReset,
  10182. relative,
  10183. viewTransition,
  10184. unstable_useTransitions
  10185. });
  10186. function handleClick(event) {
  10187. if (onClick) onClick(event);
  10188. if (!event.defaultPrevented) {
  10189. internalOnClick(event);
  10190. }
  10191. }
  10192. let link = (
  10193. // eslint-disable-next-line jsx-a11y/anchor-has-content
  10194. React10.createElement(
  10195. "a",
  10196. {
  10197. ...rest,
  10198. ...prefetchHandlers,
  10199. href: absoluteHref || href2,
  10200. onClick: isExternal || reloadDocument ? onClick : handleClick,
  10201. ref: mergeRefs(forwardedRef, prefetchRef),
  10202. target,
  10203. "data-discover": !isAbsolute && discover === "render" ? "true" : void 0
  10204. }
  10205. )
  10206. );
  10207. return shouldPrefetch && !isAbsolute ? React10.createElement(React10.Fragment, null, link, React10.createElement(PrefetchPageLinks, { page: href2 })) : link;
  10208. }
  10209. );
  10210. Link.displayName = "Link";
  10211. var NavLink = React10.forwardRef(
  10212. function NavLinkWithRef({
  10213. "aria-current": ariaCurrentProp = "page",
  10214. caseSensitive = false,
  10215. className: classNameProp = "",
  10216. end = false,
  10217. style: styleProp,
  10218. to,
  10219. viewTransition,
  10220. children,
  10221. ...rest
  10222. }, ref) {
  10223. let path = useResolvedPath(to, { relative: rest.relative });
  10224. let location2 = useLocation();
  10225. let routerState = React10.useContext(DataRouterStateContext);
  10226. let { navigator, basename } = React10.useContext(NavigationContext);
  10227. let isTransitioning = routerState != null && // Conditional usage is OK here because the usage of a data router is static
  10228. // eslint-disable-next-line react-hooks/rules-of-hooks
  10229. useViewTransitionState(path) && viewTransition === true;
  10230. let toPathname = navigator.encodeLocation ? navigator.encodeLocation(path).pathname : path.pathname;
  10231. let locationPathname = location2.pathname;
  10232. let nextLocationPathname = routerState && routerState.navigation && routerState.navigation.location ? routerState.navigation.location.pathname : null;
  10233. if (!caseSensitive) {
  10234. locationPathname = locationPathname.toLowerCase();
  10235. nextLocationPathname = nextLocationPathname ? nextLocationPathname.toLowerCase() : null;
  10236. toPathname = toPathname.toLowerCase();
  10237. }
  10238. if (nextLocationPathname && basename) {
  10239. nextLocationPathname = stripBasename(nextLocationPathname, basename) || nextLocationPathname;
  10240. }
  10241. const endSlashPosition = toPathname !== "/" && toPathname.endsWith("/") ? toPathname.length - 1 : toPathname.length;
  10242. let isActive = locationPathname === toPathname || !end && locationPathname.startsWith(toPathname) && locationPathname.charAt(endSlashPosition) === "/";
  10243. let isPending = nextLocationPathname != null && (nextLocationPathname === toPathname || !end && nextLocationPathname.startsWith(toPathname) && nextLocationPathname.charAt(toPathname.length) === "/");
  10244. let renderProps = {
  10245. isActive,
  10246. isPending,
  10247. isTransitioning
  10248. };
  10249. let ariaCurrent = isActive ? ariaCurrentProp : void 0;
  10250. let className;
  10251. if (typeof classNameProp === "function") {
  10252. className = classNameProp(renderProps);
  10253. } else {
  10254. className = [
  10255. classNameProp,
  10256. isActive ? "active" : null,
  10257. isPending ? "pending" : null,
  10258. isTransitioning ? "transitioning" : null
  10259. ].filter(Boolean).join(" ");
  10260. }
  10261. let style = typeof styleProp === "function" ? styleProp(renderProps) : styleProp;
  10262. return React10.createElement(
  10263. Link,
  10264. {
  10265. ...rest,
  10266. "aria-current": ariaCurrent,
  10267. className,
  10268. ref,
  10269. style,
  10270. to,
  10271. viewTransition
  10272. },
  10273. typeof children === "function" ? children(renderProps) : children
  10274. );
  10275. }
  10276. );
  10277. NavLink.displayName = "NavLink";
  10278. var Form = React10.forwardRef(
  10279. ({
  10280. discover = "render",
  10281. fetcherKey,
  10282. navigate,
  10283. reloadDocument,
  10284. replace: replace2,
  10285. state,
  10286. method = defaultMethod,
  10287. action,
  10288. onSubmit,
  10289. relative,
  10290. preventScrollReset,
  10291. viewTransition,
  10292. ...props
  10293. }, forwardedRef) => {
  10294. let { unstable_useTransitions } = React10.useContext(NavigationContext);
  10295. let submit = useSubmit();
  10296. let formAction = useFormAction(action, { relative });
  10297. let formMethod = method.toLowerCase() === "get" ? "get" : "post";
  10298. let isAbsolute = typeof action === "string" && ABSOLUTE_URL_REGEX2.test(action);
  10299. let submitHandler = (event) => {
  10300. onSubmit && onSubmit(event);
  10301. if (event.defaultPrevented) return;
  10302. event.preventDefault();
  10303. let submitter = event.nativeEvent.submitter;
  10304. let submitMethod = (submitter == null ? void 0 : submitter.getAttribute("formmethod")) || method;
  10305. let doSubmit = () => submit(submitter || event.currentTarget, {
  10306. fetcherKey,
  10307. method: submitMethod,
  10308. navigate,
  10309. replace: replace2,
  10310. state,
  10311. relative,
  10312. preventScrollReset,
  10313. viewTransition
  10314. });
  10315. if (unstable_useTransitions && navigate !== false) {
  10316. React10.startTransition(() => doSubmit());
  10317. } else {
  10318. doSubmit();
  10319. }
  10320. };
  10321. return React10.createElement(
  10322. "form",
  10323. {
  10324. ref: forwardedRef,
  10325. method: formMethod,
  10326. action: formAction,
  10327. onSubmit: reloadDocument ? onSubmit : submitHandler,
  10328. ...props,
  10329. "data-discover": !isAbsolute && discover === "render" ? "true" : void 0
  10330. }
  10331. );
  10332. }
  10333. );
  10334. Form.displayName = "Form";
  10335. function ScrollRestoration({
  10336. getKey,
  10337. storageKey,
  10338. ...props
  10339. }) {
  10340. let remixContext = React10.useContext(FrameworkContext);
  10341. let { basename } = React10.useContext(NavigationContext);
  10342. let location2 = useLocation();
  10343. let matches = useMatches();
  10344. useScrollRestoration({ getKey, storageKey });
  10345. let ssrKey = React10.useMemo(
  10346. () => {
  10347. if (!remixContext || !getKey) return null;
  10348. let userKey = getScrollRestorationKey(
  10349. location2,
  10350. matches,
  10351. basename,
  10352. getKey
  10353. );
  10354. return userKey !== location2.key ? userKey : null;
  10355. },
  10356. // Nah, we only need this the first time for the SSR render
  10357. // eslint-disable-next-line react-hooks/exhaustive-deps
  10358. []
  10359. );
  10360. if (!remixContext || remixContext.isSpaMode) {
  10361. return null;
  10362. }
  10363. let restoreScroll = ((storageKey2, restoreKey) => {
  10364. if (!window.history.state || !window.history.state.key) {
  10365. let key = Math.random().toString(32).slice(2);
  10366. window.history.replaceState({ key }, "");
  10367. }
  10368. try {
  10369. let positions = JSON.parse(sessionStorage.getItem(storageKey2) || "{}");
  10370. let storedY = positions[restoreKey || window.history.state.key];
  10371. if (typeof storedY === "number") {
  10372. window.scrollTo(0, storedY);
  10373. }
  10374. } catch (error) {
  10375. console.error(error);
  10376. sessionStorage.removeItem(storageKey2);
  10377. }
  10378. }).toString();
  10379. return React10.createElement(
  10380. "script",
  10381. {
  10382. ...props,
  10383. suppressHydrationWarning: true,
  10384. dangerouslySetInnerHTML: {
  10385. __html: `(${restoreScroll})(${JSON.stringify(
  10386. storageKey || SCROLL_RESTORATION_STORAGE_KEY
  10387. )}, ${JSON.stringify(ssrKey)})`
  10388. }
  10389. }
  10390. );
  10391. }
  10392. ScrollRestoration.displayName = "ScrollRestoration";
  10393. function getDataRouterConsoleError2(hookName) {
  10394. return `${hookName} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`;
  10395. }
  10396. function useDataRouterContext3(hookName) {
  10397. let ctx = React10.useContext(DataRouterContext);
  10398. invariant(ctx, getDataRouterConsoleError2(hookName));
  10399. return ctx;
  10400. }
  10401. function useDataRouterState2(hookName) {
  10402. let state = React10.useContext(DataRouterStateContext);
  10403. invariant(state, getDataRouterConsoleError2(hookName));
  10404. return state;
  10405. }
  10406. function useLinkClickHandler(to, {
  10407. target,
  10408. replace: replaceProp,
  10409. state,
  10410. preventScrollReset,
  10411. relative,
  10412. viewTransition,
  10413. unstable_useTransitions
  10414. } = {}) {
  10415. let navigate = useNavigate();
  10416. let location2 = useLocation();
  10417. let path = useResolvedPath(to, { relative });
  10418. return React10.useCallback(
  10419. (event) => {
  10420. if (shouldProcessLinkClick(event, target)) {
  10421. event.preventDefault();
  10422. let replace2 = replaceProp !== void 0 ? replaceProp : createPath(location2) === createPath(path);
  10423. let doNavigate = () => navigate(to, {
  10424. replace: replace2,
  10425. state,
  10426. preventScrollReset,
  10427. relative,
  10428. viewTransition
  10429. });
  10430. if (unstable_useTransitions) {
  10431. React10.startTransition(() => doNavigate());
  10432. } else {
  10433. doNavigate();
  10434. }
  10435. }
  10436. },
  10437. [
  10438. location2,
  10439. navigate,
  10440. path,
  10441. replaceProp,
  10442. state,
  10443. target,
  10444. to,
  10445. preventScrollReset,
  10446. relative,
  10447. viewTransition,
  10448. unstable_useTransitions
  10449. ]
  10450. );
  10451. }
  10452. function useSearchParams(defaultInit) {
  10453. warning(
  10454. typeof URLSearchParams !== "undefined",
  10455. `You cannot use the \`useSearchParams\` hook in a browser that does not support the URLSearchParams API. If you need to support Internet Explorer 11, we recommend you load a polyfill such as https://github.com/ungap/url-search-params.`
  10456. );
  10457. let defaultSearchParamsRef = React10.useRef(createSearchParams(defaultInit));
  10458. let hasSetSearchParamsRef = React10.useRef(false);
  10459. let location2 = useLocation();
  10460. let searchParams = React10.useMemo(
  10461. () => (
  10462. // Only merge in the defaults if we haven't yet called setSearchParams.
  10463. // Once we call that we want those to take precedence, otherwise you can't
  10464. // remove a param with setSearchParams({}) if it has an initial value
  10465. getSearchParamsForLocation(
  10466. location2.search,
  10467. hasSetSearchParamsRef.current ? null : defaultSearchParamsRef.current
  10468. )
  10469. ),
  10470. [location2.search]
  10471. );
  10472. let navigate = useNavigate();
  10473. let setSearchParams = React10.useCallback(
  10474. (nextInit, navigateOptions) => {
  10475. const newSearchParams = createSearchParams(
  10476. typeof nextInit === "function" ? nextInit(new URLSearchParams(searchParams)) : nextInit
  10477. );
  10478. hasSetSearchParamsRef.current = true;
  10479. navigate("?" + newSearchParams, navigateOptions);
  10480. },
  10481. [navigate, searchParams]
  10482. );
  10483. return [searchParams, setSearchParams];
  10484. }
  10485. var fetcherId = 0;
  10486. var getUniqueFetcherId = () => `__${String(++fetcherId)}__`;
  10487. function useSubmit() {
  10488. let { router: router2 } = useDataRouterContext3(
  10489. "useSubmit"
  10490. /* UseSubmit */
  10491. );
  10492. let { basename } = React10.useContext(NavigationContext);
  10493. let currentRouteId = useRouteId();
  10494. let routerFetch = router2.fetch;
  10495. let routerNavigate = router2.navigate;
  10496. return React10.useCallback(
  10497. async (target, options = {}) => {
  10498. let { action, method, encType, formData, body } = getFormSubmissionInfo(
  10499. target,
  10500. basename
  10501. );
  10502. if (options.navigate === false) {
  10503. let key = options.fetcherKey || getUniqueFetcherId();
  10504. await routerFetch(key, currentRouteId, options.action || action, {
  10505. preventScrollReset: options.preventScrollReset,
  10506. formData,
  10507. body,
  10508. formMethod: options.method || method,
  10509. formEncType: options.encType || encType,
  10510. flushSync: options.flushSync
  10511. });
  10512. } else {
  10513. await routerNavigate(options.action || action, {
  10514. preventScrollReset: options.preventScrollReset,
  10515. formData,
  10516. body,
  10517. formMethod: options.method || method,
  10518. formEncType: options.encType || encType,
  10519. replace: options.replace,
  10520. state: options.state,
  10521. fromRouteId: currentRouteId,
  10522. flushSync: options.flushSync,
  10523. viewTransition: options.viewTransition
  10524. });
  10525. }
  10526. },
  10527. [routerFetch, routerNavigate, basename, currentRouteId]
  10528. );
  10529. }
  10530. function useFormAction(action, { relative } = {}) {
  10531. let { basename } = React10.useContext(NavigationContext);
  10532. let routeContext = React10.useContext(RouteContext);
  10533. invariant(routeContext, "useFormAction must be used inside a RouteContext");
  10534. let [match] = routeContext.matches.slice(-1);
  10535. let path = { ...useResolvedPath(action ? action : ".", { relative }) };
  10536. let location2 = useLocation();
  10537. if (action == null) {
  10538. path.search = location2.search;
  10539. let params = new URLSearchParams(path.search);
  10540. let indexValues = params.getAll("index");
  10541. let hasNakedIndexParam = indexValues.some((v) => v === "");
  10542. if (hasNakedIndexParam) {
  10543. params.delete("index");
  10544. indexValues.filter((v) => v).forEach((v) => params.append("index", v));
  10545. let qs = params.toString();
  10546. path.search = qs ? `?${qs}` : "";
  10547. }
  10548. }
  10549. if ((!action || action === ".") && match.route.index) {
  10550. path.search = path.search ? path.search.replace(/^\?/, "?index&") : "?index";
  10551. }
  10552. if (basename !== "/") {
  10553. path.pathname = path.pathname === "/" ? basename : joinPaths([basename, path.pathname]);
  10554. }
  10555. return createPath(path);
  10556. }
  10557. function useFetcher({
  10558. key
  10559. } = {}) {
  10560. var _a;
  10561. let { router: router2 } = useDataRouterContext3(
  10562. "useFetcher"
  10563. /* UseFetcher */
  10564. );
  10565. let state = useDataRouterState2(
  10566. "useFetcher"
  10567. /* UseFetcher */
  10568. );
  10569. let fetcherData = React10.useContext(FetchersContext);
  10570. let route = React10.useContext(RouteContext);
  10571. let routeId = (_a = route.matches[route.matches.length - 1]) == null ? void 0 : _a.route.id;
  10572. invariant(fetcherData, `useFetcher must be used inside a FetchersContext`);
  10573. invariant(route, `useFetcher must be used inside a RouteContext`);
  10574. invariant(
  10575. routeId != null,
  10576. `useFetcher can only be used on routes that contain a unique "id"`
  10577. );
  10578. let defaultKey = React10.useId();
  10579. let [fetcherKey, setFetcherKey] = React10.useState(key || defaultKey);
  10580. if (key && key !== fetcherKey) {
  10581. setFetcherKey(key);
  10582. }
  10583. let { deleteFetcher, getFetcher, resetFetcher, fetch: routerFetch } = router2;
  10584. React10.useEffect(() => {
  10585. getFetcher(fetcherKey);
  10586. return () => deleteFetcher(fetcherKey);
  10587. }, [deleteFetcher, getFetcher, fetcherKey]);
  10588. let load = React10.useCallback(
  10589. async (href2, opts) => {
  10590. invariant(routeId, "No routeId available for fetcher.load()");
  10591. await routerFetch(fetcherKey, routeId, href2, opts);
  10592. },
  10593. [fetcherKey, routeId, routerFetch]
  10594. );
  10595. let submitImpl = useSubmit();
  10596. let submit = React10.useCallback(
  10597. async (target, opts) => {
  10598. await submitImpl(target, {
  10599. ...opts,
  10600. navigate: false,
  10601. fetcherKey
  10602. });
  10603. },
  10604. [fetcherKey, submitImpl]
  10605. );
  10606. let reset = React10.useCallback(
  10607. (opts) => resetFetcher(fetcherKey, opts),
  10608. [resetFetcher, fetcherKey]
  10609. );
  10610. let FetcherForm = React10.useMemo(() => {
  10611. let FetcherForm2 = React10.forwardRef(
  10612. (props, ref) => {
  10613. return React10.createElement(Form, { ...props, navigate: false, fetcherKey, ref });
  10614. }
  10615. );
  10616. FetcherForm2.displayName = "fetcher.Form";
  10617. return FetcherForm2;
  10618. }, [fetcherKey]);
  10619. let fetcher = state.fetchers.get(fetcherKey) || IDLE_FETCHER;
  10620. let data2 = fetcherData.get(fetcherKey);
  10621. let fetcherWithComponents = React10.useMemo(
  10622. () => ({
  10623. Form: FetcherForm,
  10624. submit,
  10625. load,
  10626. reset,
  10627. ...fetcher,
  10628. data: data2
  10629. }),
  10630. [FetcherForm, submit, load, reset, fetcher, data2]
  10631. );
  10632. return fetcherWithComponents;
  10633. }
  10634. function useFetchers() {
  10635. let state = useDataRouterState2(
  10636. "useFetchers"
  10637. /* UseFetchers */
  10638. );
  10639. return Array.from(state.fetchers.entries()).map(([key, fetcher]) => ({
  10640. ...fetcher,
  10641. key
  10642. }));
  10643. }
  10644. var SCROLL_RESTORATION_STORAGE_KEY = "react-router-scroll-positions";
  10645. var savedScrollPositions = {};
  10646. function getScrollRestorationKey(location2, matches, basename, getKey) {
  10647. let key = null;
  10648. if (getKey) {
  10649. if (basename !== "/") {
  10650. key = getKey(
  10651. {
  10652. ...location2,
  10653. pathname: stripBasename(location2.pathname, basename) || location2.pathname
  10654. },
  10655. matches
  10656. );
  10657. } else {
  10658. key = getKey(location2, matches);
  10659. }
  10660. }
  10661. if (key == null) {
  10662. key = location2.key;
  10663. }
  10664. return key;
  10665. }
  10666. function useScrollRestoration({
  10667. getKey,
  10668. storageKey
  10669. } = {}) {
  10670. let { router: router2 } = useDataRouterContext3(
  10671. "useScrollRestoration"
  10672. /* UseScrollRestoration */
  10673. );
  10674. let { restoreScrollPosition, preventScrollReset } = useDataRouterState2(
  10675. "useScrollRestoration"
  10676. /* UseScrollRestoration */
  10677. );
  10678. let { basename } = React10.useContext(NavigationContext);
  10679. let location2 = useLocation();
  10680. let matches = useMatches();
  10681. let navigation = useNavigation();
  10682. React10.useEffect(() => {
  10683. window.history.scrollRestoration = "manual";
  10684. return () => {
  10685. window.history.scrollRestoration = "auto";
  10686. };
  10687. }, []);
  10688. usePageHide(
  10689. React10.useCallback(() => {
  10690. if (navigation.state === "idle") {
  10691. let key = getScrollRestorationKey(location2, matches, basename, getKey);
  10692. savedScrollPositions[key] = window.scrollY;
  10693. }
  10694. try {
  10695. sessionStorage.setItem(
  10696. storageKey || SCROLL_RESTORATION_STORAGE_KEY,
  10697. JSON.stringify(savedScrollPositions)
  10698. );
  10699. } catch (error) {
  10700. warning(
  10701. false,
  10702. `Failed to save scroll positions in sessionStorage, <ScrollRestoration /> will not work properly (${error}).`
  10703. );
  10704. }
  10705. window.history.scrollRestoration = "auto";
  10706. }, [navigation.state, getKey, basename, location2, matches, storageKey])
  10707. );
  10708. if (typeof document !== "undefined") {
  10709. React10.useLayoutEffect(() => {
  10710. try {
  10711. let sessionPositions = sessionStorage.getItem(
  10712. storageKey || SCROLL_RESTORATION_STORAGE_KEY
  10713. );
  10714. if (sessionPositions) {
  10715. savedScrollPositions = JSON.parse(sessionPositions);
  10716. }
  10717. } catch (e) {
  10718. }
  10719. }, [storageKey]);
  10720. React10.useLayoutEffect(() => {
  10721. let disableScrollRestoration = router2 == null ? void 0 : router2.enableScrollRestoration(
  10722. savedScrollPositions,
  10723. () => window.scrollY,
  10724. getKey ? (location22, matches2) => getScrollRestorationKey(location22, matches2, basename, getKey) : void 0
  10725. );
  10726. return () => disableScrollRestoration && disableScrollRestoration();
  10727. }, [router2, basename, getKey]);
  10728. React10.useLayoutEffect(() => {
  10729. if (restoreScrollPosition === false) {
  10730. return;
  10731. }
  10732. if (typeof restoreScrollPosition === "number") {
  10733. window.scrollTo(0, restoreScrollPosition);
  10734. return;
  10735. }
  10736. try {
  10737. if (location2.hash) {
  10738. let el = document.getElementById(
  10739. decodeURIComponent(location2.hash.slice(1))
  10740. );
  10741. if (el) {
  10742. el.scrollIntoView();
  10743. return;
  10744. }
  10745. }
  10746. } catch {
  10747. warning(
  10748. false,
  10749. `"${location2.hash.slice(
  10750. 1
  10751. )}" is not a decodable element ID. The view will not scroll to it.`
  10752. );
  10753. }
  10754. if (preventScrollReset === true) {
  10755. return;
  10756. }
  10757. window.scrollTo(0, 0);
  10758. }, [location2, restoreScrollPosition, preventScrollReset]);
  10759. }
  10760. }
  10761. function useBeforeUnload(callback, options) {
  10762. let { capture } = options || {};
  10763. React10.useEffect(() => {
  10764. let opts = capture != null ? { capture } : void 0;
  10765. window.addEventListener("beforeunload", callback, opts);
  10766. return () => {
  10767. window.removeEventListener("beforeunload", callback, opts);
  10768. };
  10769. }, [callback, capture]);
  10770. }
  10771. function usePageHide(callback, options) {
  10772. let { capture } = options || {};
  10773. React10.useEffect(() => {
  10774. let opts = capture != null ? { capture } : void 0;
  10775. window.addEventListener("pagehide", callback, opts);
  10776. return () => {
  10777. window.removeEventListener("pagehide", callback, opts);
  10778. };
  10779. }, [callback, capture]);
  10780. }
  10781. function usePrompt({
  10782. when,
  10783. message
  10784. }) {
  10785. let blocker = useBlocker(when);
  10786. React10.useEffect(() => {
  10787. if (blocker.state === "blocked") {
  10788. let proceed = window.confirm(message);
  10789. if (proceed) {
  10790. setTimeout(blocker.proceed, 0);
  10791. } else {
  10792. blocker.reset();
  10793. }
  10794. }
  10795. }, [blocker, message]);
  10796. React10.useEffect(() => {
  10797. if (blocker.state === "blocked" && !when) {
  10798. blocker.reset();
  10799. }
  10800. }, [blocker, when]);
  10801. }
  10802. function useViewTransitionState(to, { relative } = {}) {
  10803. let vtContext = React10.useContext(ViewTransitionContext);
  10804. invariant(
  10805. vtContext != null,
  10806. "`useViewTransitionState` must be used within `react-router-dom`'s `RouterProvider`. Did you accidentally import `RouterProvider` from `react-router`?"
  10807. );
  10808. let { basename } = useDataRouterContext3(
  10809. "useViewTransitionState"
  10810. /* useViewTransitionState */
  10811. );
  10812. let path = useResolvedPath(to, { relative });
  10813. if (!vtContext.isTransitioning) {
  10814. return false;
  10815. }
  10816. let currentPath = stripBasename(vtContext.currentLocation.pathname, basename) || vtContext.currentLocation.pathname;
  10817. let nextPath = stripBasename(vtContext.nextLocation.pathname, basename) || vtContext.nextLocation.pathname;
  10818. return matchPath(path.pathname, nextPath) != null || matchPath(path.pathname, currentPath) != null;
  10819. }
  10820. function StaticRouter({
  10821. basename,
  10822. children,
  10823. location: locationProp = "/"
  10824. }) {
  10825. if (typeof locationProp === "string") {
  10826. locationProp = parsePath(locationProp);
  10827. }
  10828. let action = "POP";
  10829. let location2 = {
  10830. pathname: locationProp.pathname || "/",
  10831. search: locationProp.search || "",
  10832. hash: locationProp.hash || "",
  10833. state: locationProp.state != null ? locationProp.state : null,
  10834. key: locationProp.key || "default"
  10835. };
  10836. let staticNavigator = getStatelessNavigator();
  10837. return React11.createElement(
  10838. Router,
  10839. {
  10840. basename,
  10841. children,
  10842. location: location2,
  10843. navigationType: action,
  10844. navigator: staticNavigator,
  10845. static: true,
  10846. unstable_useTransitions: false
  10847. }
  10848. );
  10849. }
  10850. function StaticRouterProvider({
  10851. context,
  10852. router: router2,
  10853. hydrate: hydrate2 = true,
  10854. nonce
  10855. }) {
  10856. invariant(
  10857. router2 && context,
  10858. "You must provide `router` and `context` to <StaticRouterProvider>"
  10859. );
  10860. let dataRouterContext = {
  10861. router: router2,
  10862. navigator: getStatelessNavigator(),
  10863. static: true,
  10864. staticContext: context,
  10865. basename: context.basename || "/"
  10866. };
  10867. let fetchersContext = /* @__PURE__ */ new Map();
  10868. let hydrateScript = "";
  10869. if (hydrate2 !== false) {
  10870. let data2 = {
  10871. loaderData: context.loaderData,
  10872. actionData: context.actionData,
  10873. errors: serializeErrors(context.errors)
  10874. };
  10875. let json = htmlEscape(JSON.stringify(JSON.stringify(data2)));
  10876. hydrateScript = `window.__staticRouterHydrationData = JSON.parse(${json});`;
  10877. }
  10878. let { state } = dataRouterContext.router;
  10879. return React11.createElement(React11.Fragment, null, React11.createElement(DataRouterContext.Provider, { value: dataRouterContext }, React11.createElement(DataRouterStateContext.Provider, { value: state }, React11.createElement(FetchersContext.Provider, { value: fetchersContext }, React11.createElement(ViewTransitionContext.Provider, { value: { isTransitioning: false } }, React11.createElement(
  10880. Router,
  10881. {
  10882. basename: dataRouterContext.basename,
  10883. location: state.location,
  10884. navigationType: state.historyAction,
  10885. navigator: dataRouterContext.navigator,
  10886. static: dataRouterContext.static,
  10887. unstable_useTransitions: false
  10888. },
  10889. React11.createElement(
  10890. DataRoutes2,
  10891. {
  10892. routes: router2.routes,
  10893. future: router2.future,
  10894. state
  10895. }
  10896. )
  10897. ))))), hydrateScript ? React11.createElement(
  10898. "script",
  10899. {
  10900. suppressHydrationWarning: true,
  10901. nonce,
  10902. dangerouslySetInnerHTML: { __html: hydrateScript }
  10903. }
  10904. ) : null);
  10905. }
  10906. function DataRoutes2({
  10907. routes,
  10908. future,
  10909. state
  10910. }) {
  10911. return useRoutesImpl(routes, void 0, state, void 0, future);
  10912. }
  10913. function serializeErrors(errors) {
  10914. if (!errors) return null;
  10915. let entries = Object.entries(errors);
  10916. let serialized = {};
  10917. for (let [key, val] of entries) {
  10918. if (isRouteErrorResponse(val)) {
  10919. serialized[key] = { ...val, __type: "RouteErrorResponse" };
  10920. } else if (val instanceof Error) {
  10921. serialized[key] = {
  10922. message: val.message,
  10923. __type: "Error",
  10924. // If this is a subclass (i.e., ReferenceError), send up the type so we
  10925. // can re-create the same type during hydration.
  10926. ...val.name !== "Error" ? {
  10927. __subType: val.name
  10928. } : {}
  10929. };
  10930. } else {
  10931. serialized[key] = val;
  10932. }
  10933. }
  10934. return serialized;
  10935. }
  10936. function getStatelessNavigator() {
  10937. return {
  10938. createHref,
  10939. encodeLocation,
  10940. push(to) {
  10941. throw new Error(
  10942. `You cannot use navigator.push() on the server because it is a stateless environment. This error was probably triggered when you did a \`navigate(${JSON.stringify(to)})\` somewhere in your app.`
  10943. );
  10944. },
  10945. replace(to) {
  10946. throw new Error(
  10947. `You cannot use navigator.replace() on the server because it is a stateless environment. This error was probably triggered when you did a \`navigate(${JSON.stringify(to)}, { replace: true })\` somewhere in your app.`
  10948. );
  10949. },
  10950. go(delta) {
  10951. throw new Error(
  10952. `You cannot use navigator.go() on the server because it is a stateless environment. This error was probably triggered when you did a \`navigate(${delta})\` somewhere in your app.`
  10953. );
  10954. },
  10955. back() {
  10956. throw new Error(
  10957. `You cannot use navigator.back() on the server because it is a stateless environment.`
  10958. );
  10959. },
  10960. forward() {
  10961. throw new Error(
  10962. `You cannot use navigator.forward() on the server because it is a stateless environment.`
  10963. );
  10964. }
  10965. };
  10966. }
  10967. function createStaticHandler2(routes, opts) {
  10968. return createStaticHandler(routes, {
  10969. ...opts,
  10970. mapRouteProperties
  10971. });
  10972. }
  10973. function createStaticRouter(routes, context, opts = {}) {
  10974. let manifest = {};
  10975. let dataRoutes = convertRoutesToDataRoutes(
  10976. routes,
  10977. mapRouteProperties,
  10978. void 0,
  10979. manifest
  10980. );
  10981. let matches = context.matches.map((match) => {
  10982. let route = manifest[match.route.id] || match.route;
  10983. return {
  10984. ...match,
  10985. route
  10986. };
  10987. });
  10988. let msg = (method) => `You cannot use router.${method}() on the server because it is a stateless environment`;
  10989. return {
  10990. get basename() {
  10991. return context.basename;
  10992. },
  10993. get future() {
  10994. return {
  10995. v8_middleware: false,
  10996. ...opts == null ? void 0 : opts.future
  10997. };
  10998. },
  10999. get state() {
  11000. return {
  11001. historyAction: "POP",
  11002. location: context.location,
  11003. matches,
  11004. loaderData: context.loaderData,
  11005. actionData: context.actionData,
  11006. errors: context.errors,
  11007. initialized: true,
  11008. navigation: IDLE_NAVIGATION,
  11009. restoreScrollPosition: null,
  11010. preventScrollReset: false,
  11011. revalidation: "idle",
  11012. fetchers: /* @__PURE__ */ new Map(),
  11013. blockers: /* @__PURE__ */ new Map()
  11014. };
  11015. },
  11016. get routes() {
  11017. return dataRoutes;
  11018. },
  11019. get window() {
  11020. return void 0;
  11021. },
  11022. initialize() {
  11023. throw msg("initialize");
  11024. },
  11025. subscribe() {
  11026. throw msg("subscribe");
  11027. },
  11028. enableScrollRestoration() {
  11029. throw msg("enableScrollRestoration");
  11030. },
  11031. navigate() {
  11032. throw msg("navigate");
  11033. },
  11034. fetch() {
  11035. throw msg("fetch");
  11036. },
  11037. revalidate() {
  11038. throw msg("revalidate");
  11039. },
  11040. createHref,
  11041. encodeLocation,
  11042. getFetcher() {
  11043. return IDLE_FETCHER;
  11044. },
  11045. deleteFetcher() {
  11046. throw msg("deleteFetcher");
  11047. },
  11048. resetFetcher() {
  11049. throw msg("resetFetcher");
  11050. },
  11051. dispose() {
  11052. throw msg("dispose");
  11053. },
  11054. getBlocker() {
  11055. return IDLE_BLOCKER;
  11056. },
  11057. deleteBlocker() {
  11058. throw msg("deleteBlocker");
  11059. },
  11060. patchRoutes() {
  11061. throw msg("patchRoutes");
  11062. },
  11063. _internalFetchControllers: /* @__PURE__ */ new Map(),
  11064. _internalSetRoutes() {
  11065. throw msg("_internalSetRoutes");
  11066. },
  11067. _internalSetStateDoNotUseOrYouWillBreakYourApp() {
  11068. throw msg("_internalSetStateDoNotUseOrYouWillBreakYourApp");
  11069. }
  11070. };
  11071. }
  11072. function createHref(to) {
  11073. return typeof to === "string" ? to : createPath(to);
  11074. }
  11075. function encodeLocation(to) {
  11076. let href2 = typeof to === "string" ? to : createPath(to);
  11077. href2 = href2.replace(/ $/, "%20");
  11078. let encoded = ABSOLUTE_URL_REGEX3.test(href2) ? new URL(href2) : new URL(href2, "http://localhost");
  11079. return {
  11080. pathname: encoded.pathname,
  11081. search: encoded.search,
  11082. hash: encoded.hash
  11083. };
  11084. }
  11085. var ABSOLUTE_URL_REGEX3 = /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i;
  11086. var ESCAPE_LOOKUP2 = {
  11087. "&": "\\u0026",
  11088. ">": "\\u003e",
  11089. "<": "\\u003c",
  11090. "\u2028": "\\u2028",
  11091. "\u2029": "\\u2029"
  11092. };
  11093. var ESCAPE_REGEX2 = /[&><\u2028\u2029]/g;
  11094. function htmlEscape(str) {
  11095. return str.replace(ESCAPE_REGEX2, (match) => ESCAPE_LOOKUP2[match]);
  11096. }
  11097. // node_modules/react-router/dist/development/chunk-PMGK554W.mjs
  11098. var React12 = __toESM(require_react(), 1);
  11099. var React22 = __toESM(require_react(), 1);
  11100. var import_cookie = __toESM(require_dist(), 1);
  11101. var import_set_cookie_parser = __toESM(require_set_cookie(), 1);
  11102. var React42 = __toESM(require_react(), 1);
  11103. var import_react = __toESM(require_react(), 1);
  11104. function ServerRouter({
  11105. context,
  11106. url,
  11107. nonce
  11108. }) {
  11109. if (typeof url === "string") {
  11110. url = new URL(url);
  11111. }
  11112. let { manifest, routeModules, criticalCss, serverHandoffString } = context;
  11113. let routes = createServerRoutes(
  11114. manifest.routes,
  11115. routeModules,
  11116. context.future,
  11117. context.isSpaMode
  11118. );
  11119. context.staticHandlerContext.loaderData = {
  11120. ...context.staticHandlerContext.loaderData
  11121. };
  11122. for (let match of context.staticHandlerContext.matches) {
  11123. let routeId = match.route.id;
  11124. let route = routeModules[routeId];
  11125. let manifestRoute = context.manifest.routes[routeId];
  11126. if (route && manifestRoute && shouldHydrateRouteLoader(
  11127. routeId,
  11128. route.clientLoader,
  11129. manifestRoute.hasLoader,
  11130. context.isSpaMode
  11131. ) && (route.HydrateFallback || !manifestRoute.hasLoader)) {
  11132. delete context.staticHandlerContext.loaderData[routeId];
  11133. }
  11134. }
  11135. let router2 = createStaticRouter(routes, context.staticHandlerContext);
  11136. return React12.createElement(React12.Fragment, null, React12.createElement(
  11137. FrameworkContext.Provider,
  11138. {
  11139. value: {
  11140. manifest,
  11141. routeModules,
  11142. criticalCss,
  11143. serverHandoffString,
  11144. future: context.future,
  11145. ssr: context.ssr,
  11146. isSpaMode: context.isSpaMode,
  11147. routeDiscovery: context.routeDiscovery,
  11148. serializeError: context.serializeError,
  11149. renderMeta: context.renderMeta
  11150. }
  11151. },
  11152. React12.createElement(RemixErrorBoundary, { location: router2.state.location }, React12.createElement(
  11153. StaticRouterProvider,
  11154. {
  11155. router: router2,
  11156. context: context.staticHandlerContext,
  11157. hydrate: false
  11158. }
  11159. ))
  11160. ), context.serverHandoffStream ? React12.createElement(React12.Suspense, null, React12.createElement(
  11161. StreamTransfer,
  11162. {
  11163. context,
  11164. identifier: 0,
  11165. reader: context.serverHandoffStream.getReader(),
  11166. textDecoder: new TextDecoder(),
  11167. nonce
  11168. }
  11169. )) : null);
  11170. }
  11171. function createRoutesStub(routes, _context) {
  11172. return function RoutesTestStub({
  11173. initialEntries,
  11174. initialIndex,
  11175. hydrationData,
  11176. future
  11177. }) {
  11178. let routerRef = React22.useRef();
  11179. let frameworkContextRef = React22.useRef();
  11180. if (routerRef.current == null) {
  11181. frameworkContextRef.current = {
  11182. future: {
  11183. unstable_subResourceIntegrity: (future == null ? void 0 : future.unstable_subResourceIntegrity) === true,
  11184. v8_middleware: (future == null ? void 0 : future.v8_middleware) === true
  11185. },
  11186. manifest: {
  11187. routes: {},
  11188. entry: { imports: [], module: "" },
  11189. url: "",
  11190. version: ""
  11191. },
  11192. routeModules: {},
  11193. ssr: false,
  11194. isSpaMode: false,
  11195. routeDiscovery: { mode: "lazy", manifestPath: "/__manifest" }
  11196. };
  11197. let patched = processRoutes(
  11198. // @ts-expect-error `StubRouteObject` is stricter about `loader`/`action`
  11199. // types compared to `AgnosticRouteObject`
  11200. convertRoutesToDataRoutes(routes, (r) => r),
  11201. _context !== void 0 ? _context : (future == null ? void 0 : future.v8_middleware) ? new RouterContextProvider() : {},
  11202. frameworkContextRef.current.manifest,
  11203. frameworkContextRef.current.routeModules
  11204. );
  11205. routerRef.current = createMemoryRouter(patched, {
  11206. initialEntries,
  11207. initialIndex,
  11208. hydrationData
  11209. });
  11210. }
  11211. return React22.createElement(FrameworkContext.Provider, { value: frameworkContextRef.current }, React22.createElement(RouterProvider, { router: routerRef.current }));
  11212. };
  11213. }
  11214. function processRoutes(routes, context, manifest, routeModules, parentId) {
  11215. return routes.map((route) => {
  11216. if (!route.id) {
  11217. throw new Error(
  11218. "Expected a route.id in react-router processRoutes() function"
  11219. );
  11220. }
  11221. let newRoute = {
  11222. id: route.id,
  11223. path: route.path,
  11224. index: route.index,
  11225. Component: route.Component ? withComponentProps(route.Component) : void 0,
  11226. HydrateFallback: route.HydrateFallback ? withHydrateFallbackProps(route.HydrateFallback) : void 0,
  11227. ErrorBoundary: route.ErrorBoundary ? withErrorBoundaryProps(route.ErrorBoundary) : void 0,
  11228. action: route.action ? (args) => route.action({ ...args, context }) : void 0,
  11229. loader: route.loader ? (args) => route.loader({ ...args, context }) : void 0,
  11230. middleware: route.middleware ? route.middleware.map(
  11231. (mw) => (...args) => mw(
  11232. { ...args[0], context },
  11233. args[1]
  11234. )
  11235. ) : void 0,
  11236. handle: route.handle,
  11237. shouldRevalidate: route.shouldRevalidate
  11238. };
  11239. let entryRoute = {
  11240. id: route.id,
  11241. path: route.path,
  11242. index: route.index,
  11243. parentId,
  11244. hasAction: route.action != null,
  11245. hasLoader: route.loader != null,
  11246. // When testing routes, you should be stubbing loader/action/middleware,
  11247. // not trying to re-implement the full loader/clientLoader/SSR/hydration
  11248. // flow. That is better tested via E2E tests.
  11249. hasClientAction: false,
  11250. hasClientLoader: false,
  11251. hasClientMiddleware: false,
  11252. hasErrorBoundary: route.ErrorBoundary != null,
  11253. // any need for these?
  11254. module: "build/stub-path-to-module.js",
  11255. clientActionModule: void 0,
  11256. clientLoaderModule: void 0,
  11257. clientMiddlewareModule: void 0,
  11258. hydrateFallbackModule: void 0
  11259. };
  11260. manifest.routes[newRoute.id] = entryRoute;
  11261. routeModules[route.id] = {
  11262. default: newRoute.Component || Outlet,
  11263. ErrorBoundary: newRoute.ErrorBoundary || void 0,
  11264. handle: route.handle,
  11265. links: route.links,
  11266. meta: route.meta,
  11267. shouldRevalidate: route.shouldRevalidate
  11268. };
  11269. if (route.children) {
  11270. newRoute.children = processRoutes(
  11271. route.children,
  11272. context,
  11273. manifest,
  11274. routeModules,
  11275. newRoute.id
  11276. );
  11277. }
  11278. return newRoute;
  11279. });
  11280. }
  11281. var encoder = new TextEncoder();
  11282. var sign = async (value, secret) => {
  11283. let data2 = encoder.encode(value);
  11284. let key = await createKey2(secret, ["sign"]);
  11285. let signature = await crypto.subtle.sign("HMAC", key, data2);
  11286. let hash = btoa(String.fromCharCode(...new Uint8Array(signature))).replace(
  11287. /=+$/,
  11288. ""
  11289. );
  11290. return value + "." + hash;
  11291. };
  11292. var unsign = async (cookie, secret) => {
  11293. let index = cookie.lastIndexOf(".");
  11294. let value = cookie.slice(0, index);
  11295. let hash = cookie.slice(index + 1);
  11296. let data2 = encoder.encode(value);
  11297. let key = await createKey2(secret, ["verify"]);
  11298. try {
  11299. let signature = byteStringToUint8Array(atob(hash));
  11300. let valid = await crypto.subtle.verify("HMAC", key, signature, data2);
  11301. return valid ? value : false;
  11302. } catch (error) {
  11303. return false;
  11304. }
  11305. };
  11306. var createKey2 = async (secret, usages) => crypto.subtle.importKey(
  11307. "raw",
  11308. encoder.encode(secret),
  11309. { name: "HMAC", hash: "SHA-256" },
  11310. false,
  11311. usages
  11312. );
  11313. function byteStringToUint8Array(byteString) {
  11314. let array = new Uint8Array(byteString.length);
  11315. for (let i = 0; i < byteString.length; i++) {
  11316. array[i] = byteString.charCodeAt(i);
  11317. }
  11318. return array;
  11319. }
  11320. var createCookie = (name, cookieOptions = {}) => {
  11321. let { secrets = [], ...options } = {
  11322. path: "/",
  11323. sameSite: "lax",
  11324. ...cookieOptions
  11325. };
  11326. warnOnceAboutExpiresCookie(name, options.expires);
  11327. return {
  11328. get name() {
  11329. return name;
  11330. },
  11331. get isSigned() {
  11332. return secrets.length > 0;
  11333. },
  11334. get expires() {
  11335. return typeof options.maxAge !== "undefined" ? new Date(Date.now() + options.maxAge * 1e3) : options.expires;
  11336. },
  11337. async parse(cookieHeader, parseOptions) {
  11338. if (!cookieHeader) return null;
  11339. let cookies = (0, import_cookie.parse)(cookieHeader, { ...options, ...parseOptions });
  11340. if (name in cookies) {
  11341. let value = cookies[name];
  11342. if (typeof value === "string" && value !== "") {
  11343. let decoded = await decodeCookieValue(value, secrets);
  11344. return decoded;
  11345. } else {
  11346. return "";
  11347. }
  11348. } else {
  11349. return null;
  11350. }
  11351. },
  11352. async serialize(value, serializeOptions) {
  11353. return (0, import_cookie.serialize)(
  11354. name,
  11355. value === "" ? "" : await encodeCookieValue(value, secrets),
  11356. {
  11357. ...options,
  11358. ...serializeOptions
  11359. }
  11360. );
  11361. }
  11362. };
  11363. };
  11364. var isCookie = (object) => {
  11365. return object != null && typeof object.name === "string" && typeof object.isSigned === "boolean" && typeof object.parse === "function" && typeof object.serialize === "function";
  11366. };
  11367. async function encodeCookieValue(value, secrets) {
  11368. let encoded = encodeData(value);
  11369. if (secrets.length > 0) {
  11370. encoded = await sign(encoded, secrets[0]);
  11371. }
  11372. return encoded;
  11373. }
  11374. async function decodeCookieValue(value, secrets) {
  11375. if (secrets.length > 0) {
  11376. for (let secret of secrets) {
  11377. let unsignedValue = await unsign(value, secret);
  11378. if (unsignedValue !== false) {
  11379. return decodeData(unsignedValue);
  11380. }
  11381. }
  11382. return null;
  11383. }
  11384. return decodeData(value);
  11385. }
  11386. function encodeData(value) {
  11387. return btoa(myUnescape(encodeURIComponent(JSON.stringify(value))));
  11388. }
  11389. function decodeData(value) {
  11390. try {
  11391. return JSON.parse(decodeURIComponent(myEscape(atob(value))));
  11392. } catch (error) {
  11393. return {};
  11394. }
  11395. }
  11396. function myEscape(value) {
  11397. let str = value.toString();
  11398. let result = "";
  11399. let index = 0;
  11400. let chr, code;
  11401. while (index < str.length) {
  11402. chr = str.charAt(index++);
  11403. if (/[\w*+\-./@]/.exec(chr)) {
  11404. result += chr;
  11405. } else {
  11406. code = chr.charCodeAt(0);
  11407. if (code < 256) {
  11408. result += "%" + hex(code, 2);
  11409. } else {
  11410. result += "%u" + hex(code, 4).toUpperCase();
  11411. }
  11412. }
  11413. }
  11414. return result;
  11415. }
  11416. function hex(code, length) {
  11417. let result = code.toString(16);
  11418. while (result.length < length) result = "0" + result;
  11419. return result;
  11420. }
  11421. function myUnescape(value) {
  11422. let str = value.toString();
  11423. let result = "";
  11424. let index = 0;
  11425. let chr, part;
  11426. while (index < str.length) {
  11427. chr = str.charAt(index++);
  11428. if (chr === "%") {
  11429. if (str.charAt(index) === "u") {
  11430. part = str.slice(index + 1, index + 5);
  11431. if (/^[\da-f]{4}$/i.exec(part)) {
  11432. result += String.fromCharCode(parseInt(part, 16));
  11433. index += 5;
  11434. continue;
  11435. }
  11436. } else {
  11437. part = str.slice(index, index + 2);
  11438. if (/^[\da-f]{2}$/i.exec(part)) {
  11439. result += String.fromCharCode(parseInt(part, 16));
  11440. index += 2;
  11441. continue;
  11442. }
  11443. }
  11444. }
  11445. result += chr;
  11446. }
  11447. return result;
  11448. }
  11449. function warnOnceAboutExpiresCookie(name, expires) {
  11450. warnOnce(
  11451. !expires,
  11452. `The "${name}" cookie has an "expires" property set. This will cause the expires value to not be updated when the session is committed. Instead, you should set the expires value when serializing the cookie. You can use \`commitSession(session, { expires })\` if using a session storage object, or \`cookie.serialize("value", { expires })\` if you're using the cookie directly.`
  11453. );
  11454. }
  11455. function createEntryRouteModules(manifest) {
  11456. return Object.keys(manifest).reduce((memo2, routeId) => {
  11457. let route = manifest[routeId];
  11458. if (route) {
  11459. memo2[routeId] = route.module;
  11460. }
  11461. return memo2;
  11462. }, {});
  11463. }
  11464. var ServerMode = ((ServerMode2) => {
  11465. ServerMode2["Development"] = "development";
  11466. ServerMode2["Production"] = "production";
  11467. ServerMode2["Test"] = "test";
  11468. return ServerMode2;
  11469. })(ServerMode || {});
  11470. function isServerMode(value) {
  11471. return value === "development" || value === "production" || value === "test";
  11472. }
  11473. function sanitizeError(error, serverMode) {
  11474. if (error instanceof Error && serverMode !== "development") {
  11475. let sanitized = new Error("Unexpected Server Error");
  11476. sanitized.stack = void 0;
  11477. return sanitized;
  11478. }
  11479. return error;
  11480. }
  11481. function sanitizeErrors(errors, serverMode) {
  11482. return Object.entries(errors).reduce((acc, [routeId, error]) => {
  11483. return Object.assign(acc, { [routeId]: sanitizeError(error, serverMode) });
  11484. }, {});
  11485. }
  11486. function serializeError(error, serverMode) {
  11487. let sanitized = sanitizeError(error, serverMode);
  11488. return {
  11489. message: sanitized.message,
  11490. stack: sanitized.stack
  11491. };
  11492. }
  11493. function serializeErrors2(errors, serverMode) {
  11494. if (!errors) return null;
  11495. let entries = Object.entries(errors);
  11496. let serialized = {};
  11497. for (let [key, val] of entries) {
  11498. if (isRouteErrorResponse(val)) {
  11499. serialized[key] = { ...val, __type: "RouteErrorResponse" };
  11500. } else if (val instanceof Error) {
  11501. let sanitized = sanitizeError(val, serverMode);
  11502. serialized[key] = {
  11503. message: sanitized.message,
  11504. stack: sanitized.stack,
  11505. __type: "Error",
  11506. // If this is a subclass (i.e., ReferenceError), send up the type so we
  11507. // can re-create the same type during hydration. This will only apply
  11508. // in dev mode since all production errors are sanitized to normal
  11509. // Error instances
  11510. ...sanitized.name !== "Error" ? {
  11511. __subType: sanitized.name
  11512. } : {}
  11513. };
  11514. } else {
  11515. serialized[key] = val;
  11516. }
  11517. }
  11518. return serialized;
  11519. }
  11520. function matchServerRoutes(routes, pathname, basename) {
  11521. let matches = matchRoutes(
  11522. routes,
  11523. pathname,
  11524. basename
  11525. );
  11526. if (!matches) return null;
  11527. return matches.map((match) => ({
  11528. params: match.params,
  11529. pathname: match.pathname,
  11530. route: match.route
  11531. }));
  11532. }
  11533. async function callRouteHandler(handler, args) {
  11534. let result = await handler({
  11535. request: stripRoutesParam(stripIndexParam2(args.request)),
  11536. params: args.params,
  11537. context: args.context,
  11538. unstable_pattern: args.unstable_pattern
  11539. });
  11540. if (isDataWithResponseInit(result) && result.init && result.init.status && isRedirectStatusCode(result.init.status)) {
  11541. throw new Response(null, result.init);
  11542. }
  11543. return result;
  11544. }
  11545. function stripIndexParam2(request) {
  11546. let url = new URL(request.url);
  11547. let indexValues = url.searchParams.getAll("index");
  11548. url.searchParams.delete("index");
  11549. let indexValuesToKeep = [];
  11550. for (let indexValue of indexValues) {
  11551. if (indexValue) {
  11552. indexValuesToKeep.push(indexValue);
  11553. }
  11554. }
  11555. for (let toKeep of indexValuesToKeep) {
  11556. url.searchParams.append("index", toKeep);
  11557. }
  11558. let init = {
  11559. method: request.method,
  11560. body: request.body,
  11561. headers: request.headers,
  11562. signal: request.signal
  11563. };
  11564. if (init.body) {
  11565. init.duplex = "half";
  11566. }
  11567. return new Request(url.href, init);
  11568. }
  11569. function stripRoutesParam(request) {
  11570. let url = new URL(request.url);
  11571. url.searchParams.delete("_routes");
  11572. let init = {
  11573. method: request.method,
  11574. body: request.body,
  11575. headers: request.headers,
  11576. signal: request.signal
  11577. };
  11578. if (init.body) {
  11579. init.duplex = "half";
  11580. }
  11581. return new Request(url.href, init);
  11582. }
  11583. function invariant3(value, message) {
  11584. if (value === false || value === null || typeof value === "undefined") {
  11585. console.error(
  11586. "The following error is a bug in React Router; please open an issue! https://github.com/remix-run/react-router/issues/new/choose"
  11587. );
  11588. throw new Error(message);
  11589. }
  11590. }
  11591. var globalDevServerHooksKey = "__reactRouterDevServerHooks";
  11592. function setDevServerHooks(devServerHooks) {
  11593. globalThis[globalDevServerHooksKey] = devServerHooks;
  11594. }
  11595. function getDevServerHooks() {
  11596. return globalThis[globalDevServerHooksKey];
  11597. }
  11598. function getBuildTimeHeader(request, headerName) {
  11599. var _a;
  11600. if (typeof process !== "undefined") {
  11601. try {
  11602. if (((_a = process.env) == null ? void 0 : _a.IS_RR_BUILD_REQUEST) === "yes") {
  11603. return request.headers.get(headerName);
  11604. }
  11605. } catch (e) {
  11606. }
  11607. }
  11608. return null;
  11609. }
  11610. function groupRoutesByParentId2(manifest) {
  11611. let routes = {};
  11612. Object.values(manifest).forEach((route) => {
  11613. if (route) {
  11614. let parentId = route.parentId || "";
  11615. if (!routes[parentId]) {
  11616. routes[parentId] = [];
  11617. }
  11618. routes[parentId].push(route);
  11619. }
  11620. });
  11621. return routes;
  11622. }
  11623. function createRoutes(manifest, parentId = "", routesByParentId = groupRoutesByParentId2(manifest)) {
  11624. return (routesByParentId[parentId] || []).map((route) => ({
  11625. ...route,
  11626. children: createRoutes(manifest, route.id, routesByParentId)
  11627. }));
  11628. }
  11629. function createStaticHandlerDataRoutes(manifest, future, parentId = "", routesByParentId = groupRoutesByParentId2(manifest)) {
  11630. return (routesByParentId[parentId] || []).map((route) => {
  11631. let commonRoute = {
  11632. // Always include root due to default boundaries
  11633. hasErrorBoundary: route.id === "root" || route.module.ErrorBoundary != null,
  11634. id: route.id,
  11635. path: route.path,
  11636. middleware: route.module.middleware,
  11637. // Need to use RR's version in the param typed here to permit the optional
  11638. // context even though we know it'll always be provided in remix
  11639. loader: route.module.loader ? async (args) => {
  11640. let preRenderedData = getBuildTimeHeader(
  11641. args.request,
  11642. "X-React-Router-Prerender-Data"
  11643. );
  11644. if (preRenderedData != null) {
  11645. let encoded = preRenderedData ? decodeURI(preRenderedData) : preRenderedData;
  11646. invariant3(encoded, "Missing prerendered data for route");
  11647. let uint8array = new TextEncoder().encode(encoded);
  11648. let stream = new ReadableStream({
  11649. start(controller) {
  11650. controller.enqueue(uint8array);
  11651. controller.close();
  11652. }
  11653. });
  11654. let decoded = await decodeViaTurboStream(stream, global);
  11655. let data2 = decoded.value;
  11656. if (data2 && SingleFetchRedirectSymbol in data2) {
  11657. let result = data2[SingleFetchRedirectSymbol];
  11658. let init = { status: result.status };
  11659. if (result.reload) {
  11660. throw redirectDocument(result.redirect, init);
  11661. } else if (result.replace) {
  11662. throw replace(result.redirect, init);
  11663. } else {
  11664. throw redirect(result.redirect, init);
  11665. }
  11666. } else {
  11667. invariant3(
  11668. data2 && route.id in data2,
  11669. "Unable to decode prerendered data"
  11670. );
  11671. let result = data2[route.id];
  11672. invariant3(
  11673. "data" in result,
  11674. "Unable to process prerendered data"
  11675. );
  11676. return result.data;
  11677. }
  11678. }
  11679. let val = await callRouteHandler(route.module.loader, args);
  11680. return val;
  11681. } : void 0,
  11682. action: route.module.action ? (args) => callRouteHandler(route.module.action, args) : void 0,
  11683. handle: route.module.handle
  11684. };
  11685. return route.index ? {
  11686. index: true,
  11687. ...commonRoute
  11688. } : {
  11689. caseSensitive: route.caseSensitive,
  11690. children: createStaticHandlerDataRoutes(
  11691. manifest,
  11692. future,
  11693. route.id,
  11694. routesByParentId
  11695. ),
  11696. ...commonRoute
  11697. };
  11698. });
  11699. }
  11700. function createServerHandoffString(serverHandoff) {
  11701. return escapeHtml(JSON.stringify(serverHandoff));
  11702. }
  11703. function getDocumentHeaders(context, build) {
  11704. return getDocumentHeadersImpl(context, (m) => {
  11705. let route = build.routes[m.route.id];
  11706. invariant3(route, `Route with id "${m.route.id}" not found in build`);
  11707. return route.module.headers;
  11708. });
  11709. }
  11710. function getDocumentHeadersImpl(context, getRouteHeadersFn, _defaultHeaders) {
  11711. let boundaryIdx = context.errors ? context.matches.findIndex((m) => context.errors[m.route.id]) : -1;
  11712. let matches = boundaryIdx >= 0 ? context.matches.slice(0, boundaryIdx + 1) : context.matches;
  11713. let errorHeaders;
  11714. if (boundaryIdx >= 0) {
  11715. let { actionHeaders, actionData, loaderHeaders, loaderData } = context;
  11716. context.matches.slice(boundaryIdx).some((match) => {
  11717. let id = match.route.id;
  11718. if (actionHeaders[id] && (!actionData || !actionData.hasOwnProperty(id))) {
  11719. errorHeaders = actionHeaders[id];
  11720. } else if (loaderHeaders[id] && !loaderData.hasOwnProperty(id)) {
  11721. errorHeaders = loaderHeaders[id];
  11722. }
  11723. return errorHeaders != null;
  11724. });
  11725. }
  11726. const defaultHeaders = new Headers(_defaultHeaders);
  11727. return matches.reduce((parentHeaders, match, idx) => {
  11728. let { id } = match.route;
  11729. let loaderHeaders = context.loaderHeaders[id] || new Headers();
  11730. let actionHeaders = context.actionHeaders[id] || new Headers();
  11731. let includeErrorHeaders = errorHeaders != null && idx === matches.length - 1;
  11732. let includeErrorCookies = includeErrorHeaders && errorHeaders !== loaderHeaders && errorHeaders !== actionHeaders;
  11733. let headersFn = getRouteHeadersFn(match);
  11734. if (headersFn == null) {
  11735. let headers2 = new Headers(parentHeaders);
  11736. if (includeErrorCookies) {
  11737. prependCookies(errorHeaders, headers2);
  11738. }
  11739. prependCookies(actionHeaders, headers2);
  11740. prependCookies(loaderHeaders, headers2);
  11741. return headers2;
  11742. }
  11743. let headers = new Headers(
  11744. typeof headersFn === "function" ? headersFn({
  11745. loaderHeaders,
  11746. parentHeaders,
  11747. actionHeaders,
  11748. errorHeaders: includeErrorHeaders ? errorHeaders : void 0
  11749. }) : headersFn
  11750. );
  11751. if (includeErrorCookies) {
  11752. prependCookies(errorHeaders, headers);
  11753. }
  11754. prependCookies(actionHeaders, headers);
  11755. prependCookies(loaderHeaders, headers);
  11756. prependCookies(parentHeaders, headers);
  11757. return headers;
  11758. }, new Headers(defaultHeaders));
  11759. }
  11760. function prependCookies(parentHeaders, childHeaders) {
  11761. let parentSetCookieString = parentHeaders.get("Set-Cookie");
  11762. if (parentSetCookieString) {
  11763. let cookies = (0, import_set_cookie_parser.splitCookiesString)(parentSetCookieString);
  11764. let childCookies = new Set(childHeaders.getSetCookie());
  11765. cookies.forEach((cookie) => {
  11766. if (!childCookies.has(cookie)) {
  11767. childHeaders.append("Set-Cookie", cookie);
  11768. }
  11769. });
  11770. }
  11771. }
  11772. var SERVER_NO_BODY_STATUS_CODES = /* @__PURE__ */ new Set([
  11773. ...NO_BODY_STATUS_CODES,
  11774. 304
  11775. ]);
  11776. async function singleFetchAction(build, serverMode, staticHandler, request, handlerUrl, loadContext, handleError) {
  11777. try {
  11778. let handlerRequest = new Request(handlerUrl, {
  11779. method: request.method,
  11780. body: request.body,
  11781. headers: request.headers,
  11782. signal: request.signal,
  11783. ...request.body ? { duplex: "half" } : void 0
  11784. });
  11785. let result = await staticHandler.query(handlerRequest, {
  11786. requestContext: loadContext,
  11787. skipLoaderErrorBubbling: true,
  11788. skipRevalidation: true,
  11789. generateMiddlewareResponse: build.future.v8_middleware ? async (query) => {
  11790. try {
  11791. let innerResult = await query(handlerRequest);
  11792. return handleQueryResult(innerResult);
  11793. } catch (error) {
  11794. return handleQueryError(error);
  11795. }
  11796. } : void 0
  11797. });
  11798. return handleQueryResult(result);
  11799. } catch (error) {
  11800. return handleQueryError(error);
  11801. }
  11802. function handleQueryResult(result) {
  11803. return isResponse(result) ? result : staticContextToResponse(result);
  11804. }
  11805. function handleQueryError(error) {
  11806. handleError(error);
  11807. return generateSingleFetchResponse(request, build, serverMode, {
  11808. result: { error },
  11809. headers: new Headers(),
  11810. status: 500
  11811. });
  11812. }
  11813. function staticContextToResponse(context) {
  11814. let headers = getDocumentHeaders(context, build);
  11815. if (isRedirectStatusCode(context.statusCode) && headers.has("Location")) {
  11816. return new Response(null, { status: context.statusCode, headers });
  11817. }
  11818. if (context.errors) {
  11819. Object.values(context.errors).forEach((err) => {
  11820. if (!isRouteErrorResponse(err) || err.error) {
  11821. handleError(err);
  11822. }
  11823. });
  11824. context.errors = sanitizeErrors(context.errors, serverMode);
  11825. }
  11826. let singleFetchResult;
  11827. if (context.errors) {
  11828. singleFetchResult = { error: Object.values(context.errors)[0] };
  11829. } else {
  11830. singleFetchResult = {
  11831. data: Object.values(context.actionData || {})[0]
  11832. };
  11833. }
  11834. return generateSingleFetchResponse(request, build, serverMode, {
  11835. result: singleFetchResult,
  11836. headers,
  11837. status: context.statusCode
  11838. });
  11839. }
  11840. }
  11841. async function singleFetchLoaders(build, serverMode, staticHandler, request, handlerUrl, loadContext, handleError) {
  11842. let routesParam = new URL(request.url).searchParams.get("_routes");
  11843. let loadRouteIds = routesParam ? new Set(routesParam.split(",")) : null;
  11844. try {
  11845. let handlerRequest = new Request(handlerUrl, {
  11846. headers: request.headers,
  11847. signal: request.signal
  11848. });
  11849. let result = await staticHandler.query(handlerRequest, {
  11850. requestContext: loadContext,
  11851. filterMatchesToLoad: (m) => !loadRouteIds || loadRouteIds.has(m.route.id),
  11852. skipLoaderErrorBubbling: true,
  11853. generateMiddlewareResponse: build.future.v8_middleware ? async (query) => {
  11854. try {
  11855. let innerResult = await query(handlerRequest);
  11856. return handleQueryResult(innerResult);
  11857. } catch (error) {
  11858. return handleQueryError(error);
  11859. }
  11860. } : void 0
  11861. });
  11862. return handleQueryResult(result);
  11863. } catch (error) {
  11864. return handleQueryError(error);
  11865. }
  11866. function handleQueryResult(result) {
  11867. return isResponse(result) ? result : staticContextToResponse(result);
  11868. }
  11869. function handleQueryError(error) {
  11870. handleError(error);
  11871. return generateSingleFetchResponse(request, build, serverMode, {
  11872. result: { error },
  11873. headers: new Headers(),
  11874. status: 500
  11875. });
  11876. }
  11877. function staticContextToResponse(context) {
  11878. let headers = getDocumentHeaders(context, build);
  11879. if (isRedirectStatusCode(context.statusCode) && headers.has("Location")) {
  11880. return new Response(null, { status: context.statusCode, headers });
  11881. }
  11882. if (context.errors) {
  11883. Object.values(context.errors).forEach((err) => {
  11884. if (!isRouteErrorResponse(err) || err.error) {
  11885. handleError(err);
  11886. }
  11887. });
  11888. context.errors = sanitizeErrors(context.errors, serverMode);
  11889. }
  11890. let results = {};
  11891. let loadedMatches = new Set(
  11892. context.matches.filter(
  11893. (m) => loadRouteIds ? loadRouteIds.has(m.route.id) : m.route.loader != null
  11894. ).map((m) => m.route.id)
  11895. );
  11896. if (context.errors) {
  11897. for (let [id, error] of Object.entries(context.errors)) {
  11898. results[id] = { error };
  11899. }
  11900. }
  11901. for (let [id, data2] of Object.entries(context.loaderData)) {
  11902. if (!(id in results) && loadedMatches.has(id)) {
  11903. results[id] = { data: data2 };
  11904. }
  11905. }
  11906. return generateSingleFetchResponse(request, build, serverMode, {
  11907. result: results,
  11908. headers,
  11909. status: context.statusCode
  11910. });
  11911. }
  11912. }
  11913. function generateSingleFetchResponse(request, build, serverMode, {
  11914. result,
  11915. headers,
  11916. status
  11917. }) {
  11918. let resultHeaders = new Headers(headers);
  11919. resultHeaders.set("X-Remix-Response", "yes");
  11920. if (SERVER_NO_BODY_STATUS_CODES.has(status)) {
  11921. return new Response(null, { status, headers: resultHeaders });
  11922. }
  11923. resultHeaders.set("Content-Type", "text/x-script");
  11924. resultHeaders.delete("Content-Length");
  11925. return new Response(
  11926. encodeViaTurboStream(
  11927. result,
  11928. request.signal,
  11929. build.entry.module.streamTimeout,
  11930. serverMode
  11931. ),
  11932. {
  11933. status: status || 200,
  11934. headers: resultHeaders
  11935. }
  11936. );
  11937. }
  11938. function generateSingleFetchRedirectResponse(redirectResponse, request, build, serverMode) {
  11939. let redirect2 = getSingleFetchRedirect(
  11940. redirectResponse.status,
  11941. redirectResponse.headers,
  11942. build.basename
  11943. );
  11944. let headers = new Headers(redirectResponse.headers);
  11945. headers.delete("Location");
  11946. headers.set("Content-Type", "text/x-script");
  11947. return generateSingleFetchResponse(request, build, serverMode, {
  11948. result: request.method === "GET" ? { [SingleFetchRedirectSymbol]: redirect2 } : redirect2,
  11949. headers,
  11950. status: SINGLE_FETCH_REDIRECT_STATUS
  11951. });
  11952. }
  11953. function getSingleFetchRedirect(status, headers, basename) {
  11954. let redirect2 = headers.get("Location");
  11955. if (basename) {
  11956. redirect2 = stripBasename(redirect2, basename) || redirect2;
  11957. }
  11958. return {
  11959. redirect: redirect2,
  11960. status,
  11961. revalidate: (
  11962. // Technically X-Remix-Revalidate isn't needed here - that was an implementation
  11963. // detail of ?_data requests as our way to tell the front end to revalidate when
  11964. // we didn't have a response body to include that information in.
  11965. // With single fetch, we tell the front end via this revalidate boolean field.
  11966. // However, we're respecting it for now because it may be something folks have
  11967. // used in their own responses
  11968. // TODO(v3): Consider removing or making this official public API
  11969. headers.has("X-Remix-Revalidate") || headers.has("Set-Cookie")
  11970. ),
  11971. reload: headers.has("X-Remix-Reload-Document"),
  11972. replace: headers.has("X-Remix-Replace")
  11973. };
  11974. }
  11975. function encodeViaTurboStream(data2, requestSignal, streamTimeout, serverMode) {
  11976. let controller = new AbortController();
  11977. let timeoutId = setTimeout(
  11978. () => controller.abort(new Error("Server Timeout")),
  11979. typeof streamTimeout === "number" ? streamTimeout : 4950
  11980. );
  11981. requestSignal.addEventListener("abort", () => clearTimeout(timeoutId));
  11982. return encode(data2, {
  11983. signal: controller.signal,
  11984. plugins: [
  11985. (value) => {
  11986. if (value instanceof Error) {
  11987. let { name, message, stack } = serverMode === "production" ? sanitizeError(value, serverMode) : value;
  11988. return ["SanitizedError", name, message, stack];
  11989. }
  11990. if (value instanceof ErrorResponseImpl) {
  11991. let { data: data3, status, statusText } = value;
  11992. return ["ErrorResponse", data3, status, statusText];
  11993. }
  11994. if (value && typeof value === "object" && SingleFetchRedirectSymbol in value) {
  11995. return ["SingleFetchRedirect", value[SingleFetchRedirectSymbol]];
  11996. }
  11997. }
  11998. ],
  11999. postPlugins: [
  12000. (value) => {
  12001. if (!value) return;
  12002. if (typeof value !== "object") return;
  12003. return [
  12004. "SingleFetchClassInstance",
  12005. Object.fromEntries(Object.entries(value))
  12006. ];
  12007. },
  12008. () => ["SingleFetchFallback"]
  12009. ]
  12010. });
  12011. }
  12012. function derive(build, mode) {
  12013. let routes = createRoutes(build.routes);
  12014. let dataRoutes = createStaticHandlerDataRoutes(build.routes, build.future);
  12015. let serverMode = isServerMode(mode) ? mode : "production";
  12016. let staticHandler = createStaticHandler(dataRoutes, {
  12017. basename: build.basename,
  12018. unstable_instrumentations: build.entry.module.unstable_instrumentations
  12019. });
  12020. let errorHandler = build.entry.module.handleError || ((error, { request }) => {
  12021. if (serverMode !== "test" && !request.signal.aborted) {
  12022. console.error(
  12023. // @ts-expect-error This is "private" from users but intended for internal use
  12024. isRouteErrorResponse(error) && error.error ? error.error : error
  12025. );
  12026. }
  12027. });
  12028. let requestHandler = async (request, initialContext) => {
  12029. var _a, _b, _c;
  12030. let params = {};
  12031. let loadContext;
  12032. let handleError = (error) => {
  12033. var _a2, _b2;
  12034. if (mode === "development") {
  12035. (_b2 = (_a2 = getDevServerHooks()) == null ? void 0 : _a2.processRequestError) == null ? void 0 : _b2.call(_a2, error);
  12036. }
  12037. errorHandler(error, {
  12038. context: loadContext,
  12039. params,
  12040. request
  12041. });
  12042. };
  12043. if (build.future.v8_middleware) {
  12044. if (initialContext && !(initialContext instanceof RouterContextProvider)) {
  12045. let error = new Error(
  12046. "Invalid `context` value provided to `handleRequest`. When middleware is enabled you must return an instance of `RouterContextProvider` from your `getLoadContext` function."
  12047. );
  12048. handleError(error);
  12049. return returnLastResortErrorResponse(error, serverMode);
  12050. }
  12051. loadContext = initialContext || new RouterContextProvider();
  12052. } else {
  12053. loadContext = initialContext || {};
  12054. }
  12055. let url = new URL(request.url);
  12056. let normalizedBasename = build.basename || "/";
  12057. let normalizedPath = url.pathname;
  12058. if (stripBasename(normalizedPath, normalizedBasename) === "/_root.data") {
  12059. normalizedPath = normalizedBasename;
  12060. } else if (normalizedPath.endsWith(".data")) {
  12061. normalizedPath = normalizedPath.replace(/\.data$/, "");
  12062. }
  12063. if (stripBasename(normalizedPath, normalizedBasename) !== "/" && normalizedPath.endsWith("/")) {
  12064. normalizedPath = normalizedPath.slice(0, -1);
  12065. }
  12066. let isSpaMode = getBuildTimeHeader(request, "X-React-Router-SPA-Mode") === "yes";
  12067. if (!build.ssr) {
  12068. let decodedPath = decodeURI(normalizedPath);
  12069. if (normalizedBasename !== "/") {
  12070. let strippedPath = stripBasename(decodedPath, normalizedBasename);
  12071. if (strippedPath == null) {
  12072. errorHandler(
  12073. new ErrorResponseImpl(
  12074. 404,
  12075. "Not Found",
  12076. `Refusing to prerender the \`${decodedPath}\` path because it does not start with the basename \`${normalizedBasename}\``
  12077. ),
  12078. {
  12079. context: loadContext,
  12080. params,
  12081. request
  12082. }
  12083. );
  12084. return new Response("Not Found", {
  12085. status: 404,
  12086. statusText: "Not Found"
  12087. });
  12088. }
  12089. decodedPath = strippedPath;
  12090. }
  12091. if (build.prerender.length === 0) {
  12092. isSpaMode = true;
  12093. } else if (!build.prerender.includes(decodedPath) && !build.prerender.includes(decodedPath + "/")) {
  12094. if (url.pathname.endsWith(".data")) {
  12095. errorHandler(
  12096. new ErrorResponseImpl(
  12097. 404,
  12098. "Not Found",
  12099. `Refusing to SSR the path \`${decodedPath}\` because \`ssr:false\` is set and the path is not included in the \`prerender\` config, so in production the path will be a 404.`
  12100. ),
  12101. {
  12102. context: loadContext,
  12103. params,
  12104. request
  12105. }
  12106. );
  12107. return new Response("Not Found", {
  12108. status: 404,
  12109. statusText: "Not Found"
  12110. });
  12111. } else {
  12112. isSpaMode = true;
  12113. }
  12114. }
  12115. }
  12116. let manifestUrl = getManifestPath(
  12117. build.routeDiscovery.manifestPath,
  12118. normalizedBasename
  12119. );
  12120. if (url.pathname === manifestUrl) {
  12121. try {
  12122. let res = await handleManifestRequest(build, routes, url);
  12123. return res;
  12124. } catch (e) {
  12125. handleError(e);
  12126. return new Response("Unknown Server Error", { status: 500 });
  12127. }
  12128. }
  12129. let matches = matchServerRoutes(routes, normalizedPath, build.basename);
  12130. if (matches && matches.length > 0) {
  12131. Object.assign(params, matches[0].params);
  12132. }
  12133. let response;
  12134. if (url.pathname.endsWith(".data")) {
  12135. let handlerUrl = new URL(request.url);
  12136. handlerUrl.pathname = normalizedPath;
  12137. let singleFetchMatches = matchServerRoutes(
  12138. routes,
  12139. handlerUrl.pathname,
  12140. build.basename
  12141. );
  12142. response = await handleSingleFetchRequest(
  12143. serverMode,
  12144. build,
  12145. staticHandler,
  12146. request,
  12147. handlerUrl,
  12148. loadContext,
  12149. handleError
  12150. );
  12151. if (isRedirectResponse(response)) {
  12152. response = generateSingleFetchRedirectResponse(
  12153. response,
  12154. request,
  12155. build,
  12156. serverMode
  12157. );
  12158. }
  12159. if (build.entry.module.handleDataRequest) {
  12160. response = await build.entry.module.handleDataRequest(response, {
  12161. context: loadContext,
  12162. params: singleFetchMatches ? singleFetchMatches[0].params : {},
  12163. request
  12164. });
  12165. if (isRedirectResponse(response)) {
  12166. response = generateSingleFetchRedirectResponse(
  12167. response,
  12168. request,
  12169. build,
  12170. serverMode
  12171. );
  12172. }
  12173. }
  12174. } else if (!isSpaMode && matches && matches[matches.length - 1].route.module.default == null && matches[matches.length - 1].route.module.ErrorBoundary == null) {
  12175. response = await handleResourceRequest(
  12176. serverMode,
  12177. build,
  12178. staticHandler,
  12179. matches.slice(-1)[0].route.id,
  12180. request,
  12181. loadContext,
  12182. handleError
  12183. );
  12184. } else {
  12185. let { pathname } = url;
  12186. let criticalCss = void 0;
  12187. if (build.unstable_getCriticalCss) {
  12188. criticalCss = await build.unstable_getCriticalCss({ pathname });
  12189. } else if (mode === "development" && ((_a = getDevServerHooks()) == null ? void 0 : _a.getCriticalCss)) {
  12190. criticalCss = await ((_c = (_b = getDevServerHooks()) == null ? void 0 : _b.getCriticalCss) == null ? void 0 : _c.call(_b, pathname));
  12191. }
  12192. response = await handleDocumentRequest(
  12193. serverMode,
  12194. build,
  12195. staticHandler,
  12196. request,
  12197. loadContext,
  12198. handleError,
  12199. isSpaMode,
  12200. criticalCss
  12201. );
  12202. }
  12203. if (request.method === "HEAD") {
  12204. return new Response(null, {
  12205. headers: response.headers,
  12206. status: response.status,
  12207. statusText: response.statusText
  12208. });
  12209. }
  12210. return response;
  12211. };
  12212. if (build.entry.module.unstable_instrumentations) {
  12213. requestHandler = instrumentHandler(
  12214. requestHandler,
  12215. build.entry.module.unstable_instrumentations.map((i) => i.handler).filter(Boolean)
  12216. );
  12217. }
  12218. return {
  12219. routes,
  12220. dataRoutes,
  12221. serverMode,
  12222. staticHandler,
  12223. errorHandler,
  12224. requestHandler
  12225. };
  12226. }
  12227. var createRequestHandler = (build, mode) => {
  12228. let _build;
  12229. let routes;
  12230. let serverMode;
  12231. let staticHandler;
  12232. let errorHandler;
  12233. let _requestHandler;
  12234. return async function requestHandler(request, initialContext) {
  12235. _build = typeof build === "function" ? await build() : build;
  12236. if (typeof build === "function") {
  12237. let derived = derive(_build, mode);
  12238. routes = derived.routes;
  12239. serverMode = derived.serverMode;
  12240. staticHandler = derived.staticHandler;
  12241. errorHandler = derived.errorHandler;
  12242. _requestHandler = derived.requestHandler;
  12243. } else if (!routes || !serverMode || !staticHandler || !errorHandler || !_requestHandler) {
  12244. let derived = derive(_build, mode);
  12245. routes = derived.routes;
  12246. serverMode = derived.serverMode;
  12247. staticHandler = derived.staticHandler;
  12248. errorHandler = derived.errorHandler;
  12249. _requestHandler = derived.requestHandler;
  12250. }
  12251. return _requestHandler(request, initialContext);
  12252. };
  12253. };
  12254. async function handleManifestRequest(build, routes, url) {
  12255. if (build.assets.version !== url.searchParams.get("version")) {
  12256. return new Response(null, {
  12257. status: 204,
  12258. headers: {
  12259. "X-Remix-Reload-Document": "true"
  12260. }
  12261. });
  12262. }
  12263. let patches = {};
  12264. if (url.searchParams.has("paths")) {
  12265. let paths = /* @__PURE__ */ new Set();
  12266. let pathParam = url.searchParams.get("paths") || "";
  12267. let requestedPaths = pathParam.split(",").filter(Boolean);
  12268. requestedPaths.forEach((path) => {
  12269. if (!path.startsWith("/")) {
  12270. path = `/${path}`;
  12271. }
  12272. let segments = path.split("/").slice(1);
  12273. segments.forEach((_, i) => {
  12274. let partialPath = segments.slice(0, i + 1).join("/");
  12275. paths.add(`/${partialPath}`);
  12276. });
  12277. });
  12278. for (let path of paths) {
  12279. let matches = matchServerRoutes(routes, path, build.basename);
  12280. if (matches) {
  12281. for (let match of matches) {
  12282. let routeId = match.route.id;
  12283. let route = build.assets.routes[routeId];
  12284. if (route) {
  12285. patches[routeId] = route;
  12286. }
  12287. }
  12288. }
  12289. }
  12290. return Response.json(patches, {
  12291. headers: {
  12292. "Cache-Control": "public, max-age=31536000, immutable"
  12293. }
  12294. });
  12295. }
  12296. return new Response("Invalid Request", { status: 400 });
  12297. }
  12298. async function handleSingleFetchRequest(serverMode, build, staticHandler, request, handlerUrl, loadContext, handleError) {
  12299. let response = request.method !== "GET" ? await singleFetchAction(
  12300. build,
  12301. serverMode,
  12302. staticHandler,
  12303. request,
  12304. handlerUrl,
  12305. loadContext,
  12306. handleError
  12307. ) : await singleFetchLoaders(
  12308. build,
  12309. serverMode,
  12310. staticHandler,
  12311. request,
  12312. handlerUrl,
  12313. loadContext,
  12314. handleError
  12315. );
  12316. return response;
  12317. }
  12318. async function handleDocumentRequest(serverMode, build, staticHandler, request, loadContext, handleError, isSpaMode, criticalCss) {
  12319. try {
  12320. let result = await staticHandler.query(request, {
  12321. requestContext: loadContext,
  12322. generateMiddlewareResponse: build.future.v8_middleware ? async (query) => {
  12323. try {
  12324. let innerResult = await query(request);
  12325. if (!isResponse(innerResult)) {
  12326. innerResult = await renderHtml(innerResult, isSpaMode);
  12327. }
  12328. return innerResult;
  12329. } catch (error) {
  12330. handleError(error);
  12331. return new Response(null, { status: 500 });
  12332. }
  12333. } : void 0
  12334. });
  12335. if (!isResponse(result)) {
  12336. result = await renderHtml(result, isSpaMode);
  12337. }
  12338. return result;
  12339. } catch (error) {
  12340. handleError(error);
  12341. return new Response(null, { status: 500 });
  12342. }
  12343. async function renderHtml(context, isSpaMode2) {
  12344. let headers = getDocumentHeaders(context, build);
  12345. if (SERVER_NO_BODY_STATUS_CODES.has(context.statusCode)) {
  12346. return new Response(null, { status: context.statusCode, headers });
  12347. }
  12348. if (context.errors) {
  12349. Object.values(context.errors).forEach((err) => {
  12350. if (!isRouteErrorResponse(err) || err.error) {
  12351. handleError(err);
  12352. }
  12353. });
  12354. context.errors = sanitizeErrors(context.errors, serverMode);
  12355. }
  12356. let state = {
  12357. loaderData: context.loaderData,
  12358. actionData: context.actionData,
  12359. errors: serializeErrors2(context.errors, serverMode)
  12360. };
  12361. let baseServerHandoff = {
  12362. basename: build.basename,
  12363. future: build.future,
  12364. routeDiscovery: build.routeDiscovery,
  12365. ssr: build.ssr,
  12366. isSpaMode: isSpaMode2
  12367. };
  12368. let entryContext = {
  12369. manifest: build.assets,
  12370. routeModules: createEntryRouteModules(build.routes),
  12371. staticHandlerContext: context,
  12372. criticalCss,
  12373. serverHandoffString: createServerHandoffString({
  12374. ...baseServerHandoff,
  12375. criticalCss
  12376. }),
  12377. serverHandoffStream: encodeViaTurboStream(
  12378. state,
  12379. request.signal,
  12380. build.entry.module.streamTimeout,
  12381. serverMode
  12382. ),
  12383. renderMeta: {},
  12384. future: build.future,
  12385. ssr: build.ssr,
  12386. routeDiscovery: build.routeDiscovery,
  12387. isSpaMode: isSpaMode2,
  12388. serializeError: (err) => serializeError(err, serverMode)
  12389. };
  12390. let handleDocumentRequestFunction = build.entry.module.default;
  12391. try {
  12392. return await handleDocumentRequestFunction(
  12393. request,
  12394. context.statusCode,
  12395. headers,
  12396. entryContext,
  12397. loadContext
  12398. );
  12399. } catch (error) {
  12400. handleError(error);
  12401. let errorForSecondRender = error;
  12402. if (isResponse(error)) {
  12403. try {
  12404. let data2 = await unwrapResponse(error);
  12405. errorForSecondRender = new ErrorResponseImpl(
  12406. error.status,
  12407. error.statusText,
  12408. data2
  12409. );
  12410. } catch (e) {
  12411. }
  12412. }
  12413. context = getStaticContextFromError(
  12414. staticHandler.dataRoutes,
  12415. context,
  12416. errorForSecondRender
  12417. );
  12418. if (context.errors) {
  12419. context.errors = sanitizeErrors(context.errors, serverMode);
  12420. }
  12421. let state2 = {
  12422. loaderData: context.loaderData,
  12423. actionData: context.actionData,
  12424. errors: serializeErrors2(context.errors, serverMode)
  12425. };
  12426. entryContext = {
  12427. ...entryContext,
  12428. staticHandlerContext: context,
  12429. serverHandoffString: createServerHandoffString(baseServerHandoff),
  12430. serverHandoffStream: encodeViaTurboStream(
  12431. state2,
  12432. request.signal,
  12433. build.entry.module.streamTimeout,
  12434. serverMode
  12435. ),
  12436. renderMeta: {}
  12437. };
  12438. try {
  12439. return await handleDocumentRequestFunction(
  12440. request,
  12441. context.statusCode,
  12442. headers,
  12443. entryContext,
  12444. loadContext
  12445. );
  12446. } catch (error2) {
  12447. handleError(error2);
  12448. return returnLastResortErrorResponse(error2, serverMode);
  12449. }
  12450. }
  12451. }
  12452. }
  12453. async function handleResourceRequest(serverMode, build, staticHandler, routeId, request, loadContext, handleError) {
  12454. try {
  12455. let result = await staticHandler.queryRoute(request, {
  12456. routeId,
  12457. requestContext: loadContext,
  12458. generateMiddlewareResponse: build.future.v8_middleware ? async (queryRoute) => {
  12459. try {
  12460. let innerResult = await queryRoute(request);
  12461. return handleQueryRouteResult(innerResult);
  12462. } catch (error) {
  12463. return handleQueryRouteError(error);
  12464. }
  12465. } : void 0
  12466. });
  12467. return handleQueryRouteResult(result);
  12468. } catch (error) {
  12469. return handleQueryRouteError(error);
  12470. }
  12471. function handleQueryRouteResult(result) {
  12472. if (isResponse(result)) {
  12473. return result;
  12474. }
  12475. if (typeof result === "string") {
  12476. return new Response(result);
  12477. }
  12478. return Response.json(result);
  12479. }
  12480. function handleQueryRouteError(error) {
  12481. if (isResponse(error)) {
  12482. return error;
  12483. }
  12484. if (isRouteErrorResponse(error)) {
  12485. handleError(error);
  12486. return errorResponseToJson(error, serverMode);
  12487. }
  12488. if (error instanceof Error && error.message === "Expected a response from queryRoute") {
  12489. let newError = new Error(
  12490. "Expected a Response to be returned from resource route handler"
  12491. );
  12492. handleError(newError);
  12493. return returnLastResortErrorResponse(newError, serverMode);
  12494. }
  12495. handleError(error);
  12496. return returnLastResortErrorResponse(error, serverMode);
  12497. }
  12498. }
  12499. function errorResponseToJson(errorResponse, serverMode) {
  12500. return Response.json(
  12501. serializeError(
  12502. // @ts-expect-error This is "private" from users but intended for internal use
  12503. errorResponse.error || new Error("Unexpected Server Error"),
  12504. serverMode
  12505. ),
  12506. {
  12507. status: errorResponse.status,
  12508. statusText: errorResponse.statusText
  12509. }
  12510. );
  12511. }
  12512. function returnLastResortErrorResponse(error, serverMode) {
  12513. let message = "Unexpected Server Error";
  12514. if (serverMode !== "production") {
  12515. message += `
  12516. ${String(error)}`;
  12517. }
  12518. return new Response(message, {
  12519. status: 500,
  12520. headers: {
  12521. "Content-Type": "text/plain"
  12522. }
  12523. });
  12524. }
  12525. function unwrapResponse(response) {
  12526. let contentType = response.headers.get("Content-Type");
  12527. return contentType && /\bapplication\/json\b/.test(contentType) ? response.body == null ? null : response.json() : response.text();
  12528. }
  12529. function flash(name) {
  12530. return `__flash_${name}__`;
  12531. }
  12532. var createSession = (initialData = {}, id = "") => {
  12533. let map = new Map(Object.entries(initialData));
  12534. return {
  12535. get id() {
  12536. return id;
  12537. },
  12538. get data() {
  12539. return Object.fromEntries(map);
  12540. },
  12541. has(name) {
  12542. return map.has(name) || map.has(flash(name));
  12543. },
  12544. get(name) {
  12545. if (map.has(name)) return map.get(name);
  12546. let flashName = flash(name);
  12547. if (map.has(flashName)) {
  12548. let value = map.get(flashName);
  12549. map.delete(flashName);
  12550. return value;
  12551. }
  12552. return void 0;
  12553. },
  12554. set(name, value) {
  12555. map.set(name, value);
  12556. },
  12557. flash(name, value) {
  12558. map.set(flash(name), value);
  12559. },
  12560. unset(name) {
  12561. map.delete(name);
  12562. }
  12563. };
  12564. };
  12565. var isSession = (object) => {
  12566. return object != null && typeof object.id === "string" && typeof object.data !== "undefined" && typeof object.has === "function" && typeof object.get === "function" && typeof object.set === "function" && typeof object.flash === "function" && typeof object.unset === "function";
  12567. };
  12568. function createSessionStorage({
  12569. cookie: cookieArg,
  12570. createData,
  12571. readData,
  12572. updateData,
  12573. deleteData
  12574. }) {
  12575. let cookie = isCookie(cookieArg) ? cookieArg : createCookie((cookieArg == null ? void 0 : cookieArg.name) || "__session", cookieArg);
  12576. warnOnceAboutSigningSessionCookie(cookie);
  12577. return {
  12578. async getSession(cookieHeader, options) {
  12579. let id = cookieHeader && await cookie.parse(cookieHeader, options);
  12580. let data2 = id && await readData(id);
  12581. return createSession(data2 || {}, id || "");
  12582. },
  12583. async commitSession(session, options) {
  12584. let { id, data: data2 } = session;
  12585. let expires = (options == null ? void 0 : options.maxAge) != null ? new Date(Date.now() + options.maxAge * 1e3) : (options == null ? void 0 : options.expires) != null ? options.expires : cookie.expires;
  12586. if (id) {
  12587. await updateData(id, data2, expires);
  12588. } else {
  12589. id = await createData(data2, expires);
  12590. }
  12591. return cookie.serialize(id, options);
  12592. },
  12593. async destroySession(session, options) {
  12594. await deleteData(session.id);
  12595. return cookie.serialize("", {
  12596. ...options,
  12597. maxAge: void 0,
  12598. expires: /* @__PURE__ */ new Date(0)
  12599. });
  12600. }
  12601. };
  12602. }
  12603. function warnOnceAboutSigningSessionCookie(cookie) {
  12604. warnOnce(
  12605. cookie.isSigned,
  12606. `The "${cookie.name}" cookie is not signed, but session cookies should be signed to prevent tampering on the client before they are sent back to the server. See https://reactrouter.com/explanation/sessions-and-cookies#signing-cookies for more information.`
  12607. );
  12608. }
  12609. function createCookieSessionStorage({ cookie: cookieArg } = {}) {
  12610. let cookie = isCookie(cookieArg) ? cookieArg : createCookie((cookieArg == null ? void 0 : cookieArg.name) || "__session", cookieArg);
  12611. warnOnceAboutSigningSessionCookie(cookie);
  12612. return {
  12613. async getSession(cookieHeader, options) {
  12614. return createSession(
  12615. cookieHeader && await cookie.parse(cookieHeader, options) || {}
  12616. );
  12617. },
  12618. async commitSession(session, options) {
  12619. let serializedCookie = await cookie.serialize(session.data, options);
  12620. if (serializedCookie.length > 4096) {
  12621. throw new Error(
  12622. "Cookie length will exceed browser maximum. Length: " + serializedCookie.length
  12623. );
  12624. }
  12625. return serializedCookie;
  12626. },
  12627. async destroySession(_session, options) {
  12628. return cookie.serialize("", {
  12629. ...options,
  12630. maxAge: void 0,
  12631. expires: /* @__PURE__ */ new Date(0)
  12632. });
  12633. }
  12634. };
  12635. }
  12636. function createMemorySessionStorage({ cookie } = {}) {
  12637. let map = /* @__PURE__ */ new Map();
  12638. return createSessionStorage({
  12639. cookie,
  12640. async createData(data2, expires) {
  12641. let id = Math.random().toString(36).substring(2, 10);
  12642. map.set(id, { data: data2, expires });
  12643. return id;
  12644. },
  12645. async readData(id) {
  12646. if (map.has(id)) {
  12647. let { data: data2, expires } = map.get(id);
  12648. if (!expires || expires > /* @__PURE__ */ new Date()) {
  12649. return data2;
  12650. }
  12651. if (expires) map.delete(id);
  12652. }
  12653. return null;
  12654. },
  12655. async updateData(id, data2, expires) {
  12656. map.set(id, { data: data2, expires });
  12657. },
  12658. async deleteData(id) {
  12659. map.delete(id);
  12660. }
  12661. });
  12662. }
  12663. function href(path, ...args) {
  12664. let params = args[0];
  12665. let result = trimTrailingSplat(path).replace(
  12666. /\/:([\w-]+)(\?)?/g,
  12667. // same regex as in .\router\utils.ts: compilePath().
  12668. (_, param, questionMark) => {
  12669. const isRequired = questionMark === void 0;
  12670. const value = params == null ? void 0 : params[param];
  12671. if (isRequired && value === void 0) {
  12672. throw new Error(
  12673. `Path '${path}' requires param '${param}' but it was not provided`
  12674. );
  12675. }
  12676. return value === void 0 ? "" : "/" + value;
  12677. }
  12678. );
  12679. if (path.endsWith("*")) {
  12680. const value = params == null ? void 0 : params["*"];
  12681. if (value !== void 0) {
  12682. result += "/" + value;
  12683. }
  12684. }
  12685. return result || "/";
  12686. }
  12687. function trimTrailingSplat(path) {
  12688. let i = path.length - 1;
  12689. let char = path[i];
  12690. if (char !== "*" && char !== "/") return path;
  12691. i--;
  12692. for (; i >= 0; i--) {
  12693. if (path[i] !== "/") break;
  12694. }
  12695. return path.slice(0, i + 1);
  12696. }
  12697. var encoder2 = new TextEncoder();
  12698. var trailer = "</body></html>";
  12699. function injectRSCPayload(rscStream) {
  12700. let decoder = new TextDecoder();
  12701. let resolveFlightDataPromise;
  12702. let flightDataPromise = new Promise(
  12703. (resolve) => resolveFlightDataPromise = resolve
  12704. );
  12705. let startedRSC = false;
  12706. let buffered = [];
  12707. let timeout = null;
  12708. function flushBufferedChunks(controller) {
  12709. for (let chunk of buffered) {
  12710. let buf = decoder.decode(chunk, { stream: true });
  12711. if (buf.endsWith(trailer)) {
  12712. buf = buf.slice(0, -trailer.length);
  12713. }
  12714. controller.enqueue(encoder2.encode(buf));
  12715. }
  12716. buffered.length = 0;
  12717. timeout = null;
  12718. }
  12719. return new TransformStream({
  12720. transform(chunk, controller) {
  12721. buffered.push(chunk);
  12722. if (timeout) {
  12723. return;
  12724. }
  12725. timeout = setTimeout(async () => {
  12726. flushBufferedChunks(controller);
  12727. if (!startedRSC) {
  12728. startedRSC = true;
  12729. writeRSCStream(rscStream, controller).catch((err) => controller.error(err)).then(resolveFlightDataPromise);
  12730. }
  12731. }, 0);
  12732. },
  12733. async flush(controller) {
  12734. await flightDataPromise;
  12735. if (timeout) {
  12736. clearTimeout(timeout);
  12737. flushBufferedChunks(controller);
  12738. }
  12739. controller.enqueue(encoder2.encode("</body></html>"));
  12740. }
  12741. });
  12742. }
  12743. async function writeRSCStream(rscStream, controller) {
  12744. let decoder = new TextDecoder("utf-8", { fatal: true });
  12745. const reader = rscStream.getReader();
  12746. try {
  12747. let read;
  12748. while ((read = await reader.read()) && !read.done) {
  12749. const chunk = read.value;
  12750. try {
  12751. writeChunk(
  12752. JSON.stringify(decoder.decode(chunk, { stream: true })),
  12753. controller
  12754. );
  12755. } catch (err) {
  12756. let base64 = JSON.stringify(btoa(String.fromCodePoint(...chunk)));
  12757. writeChunk(
  12758. `Uint8Array.from(atob(${base64}), m => m.codePointAt(0))`,
  12759. controller
  12760. );
  12761. }
  12762. }
  12763. } finally {
  12764. reader.releaseLock();
  12765. }
  12766. let remaining = decoder.decode();
  12767. if (remaining.length) {
  12768. writeChunk(JSON.stringify(remaining), controller);
  12769. }
  12770. }
  12771. function writeChunk(chunk, controller) {
  12772. controller.enqueue(
  12773. encoder2.encode(
  12774. `<script>${escapeScript(
  12775. `(self.__FLIGHT_DATA||=[]).push(${chunk})`
  12776. )}<\/script>`
  12777. )
  12778. );
  12779. }
  12780. function escapeScript(script) {
  12781. return script.replace(/<!--/g, "<\\!--").replace(/<\/(script)/gi, "</\\$1");
  12782. }
  12783. var RSCRouterGlobalErrorBoundary = class extends import_react.default.Component {
  12784. constructor(props) {
  12785. super(props);
  12786. this.state = { error: null, location: props.location };
  12787. }
  12788. static getDerivedStateFromError(error) {
  12789. return { error };
  12790. }
  12791. static getDerivedStateFromProps(props, state) {
  12792. if (state.location !== props.location) {
  12793. return { error: null, location: props.location };
  12794. }
  12795. return { error: state.error, location: state.location };
  12796. }
  12797. render() {
  12798. if (this.state.error) {
  12799. return import_react.default.createElement(
  12800. RSCDefaultRootErrorBoundaryImpl,
  12801. {
  12802. error: this.state.error,
  12803. renderAppShell: true
  12804. }
  12805. );
  12806. } else {
  12807. return this.props.children;
  12808. }
  12809. }
  12810. };
  12811. function ErrorWrapper({
  12812. renderAppShell,
  12813. title,
  12814. children
  12815. }) {
  12816. if (!renderAppShell) {
  12817. return children;
  12818. }
  12819. return import_react.default.createElement("html", { lang: "en" }, import_react.default.createElement("head", null, import_react.default.createElement("meta", { charSet: "utf-8" }), import_react.default.createElement(
  12820. "meta",
  12821. {
  12822. name: "viewport",
  12823. content: "width=device-width,initial-scale=1,viewport-fit=cover"
  12824. }
  12825. ), import_react.default.createElement("title", null, title)), import_react.default.createElement("body", null, import_react.default.createElement("main", { style: { fontFamily: "system-ui, sans-serif", padding: "2rem" } }, children)));
  12826. }
  12827. function RSCDefaultRootErrorBoundaryImpl({
  12828. error,
  12829. renderAppShell
  12830. }) {
  12831. console.error(error);
  12832. let heyDeveloper = import_react.default.createElement(
  12833. "script",
  12834. {
  12835. dangerouslySetInnerHTML: {
  12836. __html: `
  12837. console.log(
  12838. "💿 Hey developer 👋. You can provide a way better UX than this when your app throws errors. Check out https://reactrouter.com/how-to/error-boundary for more information."
  12839. );
  12840. `
  12841. }
  12842. }
  12843. );
  12844. if (isRouteErrorResponse(error)) {
  12845. return import_react.default.createElement(
  12846. ErrorWrapper,
  12847. {
  12848. renderAppShell,
  12849. title: "Unhandled Thrown Response!"
  12850. },
  12851. import_react.default.createElement("h1", { style: { fontSize: "24px" } }, error.status, " ", error.statusText),
  12852. ENABLE_DEV_WARNINGS ? heyDeveloper : null
  12853. );
  12854. }
  12855. let errorInstance;
  12856. if (error instanceof Error) {
  12857. errorInstance = error;
  12858. } else {
  12859. let errorString = error == null ? "Unknown Error" : typeof error === "object" && "toString" in error ? error.toString() : JSON.stringify(error);
  12860. errorInstance = new Error(errorString);
  12861. }
  12862. return import_react.default.createElement(ErrorWrapper, { renderAppShell, title: "Application Error!" }, import_react.default.createElement("h1", { style: { fontSize: "24px" } }, "Application Error"), import_react.default.createElement(
  12863. "pre",
  12864. {
  12865. style: {
  12866. padding: "2rem",
  12867. background: "hsla(10, 50%, 50%, 0.1)",
  12868. color: "red",
  12869. overflow: "auto"
  12870. }
  12871. },
  12872. errorInstance.stack
  12873. ), heyDeveloper);
  12874. }
  12875. function RSCDefaultRootErrorBoundary({
  12876. hasRootLayout
  12877. }) {
  12878. let error = useRouteError();
  12879. if (hasRootLayout === void 0) {
  12880. throw new Error("Missing 'hasRootLayout' prop");
  12881. }
  12882. return import_react.default.createElement(
  12883. RSCDefaultRootErrorBoundaryImpl,
  12884. {
  12885. renderAppShell: !hasRootLayout,
  12886. error
  12887. }
  12888. );
  12889. }
  12890. function createRSCRouteModules(payload) {
  12891. const routeModules = {};
  12892. for (const match of payload.matches) {
  12893. populateRSCRouteModules(routeModules, match);
  12894. }
  12895. return routeModules;
  12896. }
  12897. function populateRSCRouteModules(routeModules, matches) {
  12898. matches = Array.isArray(matches) ? matches : [matches];
  12899. for (const match of matches) {
  12900. routeModules[match.id] = {
  12901. links: match.links,
  12902. meta: match.meta,
  12903. default: noopComponent
  12904. };
  12905. }
  12906. }
  12907. var noopComponent = () => null;
  12908. var REACT_USE = "use";
  12909. var useImpl = React42[REACT_USE];
  12910. function useSafe(promise) {
  12911. if (useImpl) {
  12912. return useImpl(promise);
  12913. }
  12914. throw new Error("React Router v7 requires React 19+ for RSC features.");
  12915. }
  12916. async function routeRSCServerRequest({
  12917. request,
  12918. fetchServer,
  12919. createFromReadableStream,
  12920. renderHTML,
  12921. hydrate: hydrate2 = true
  12922. }) {
  12923. const url = new URL(request.url);
  12924. const isDataRequest = isReactServerRequest(url);
  12925. const respondWithRSCPayload = isDataRequest || isManifestRequest(url) || request.headers.has("rsc-action-id");
  12926. const serverResponse = await fetchServer(request);
  12927. if (respondWithRSCPayload || serverResponse.headers.get("React-Router-Resource") === "true") {
  12928. return serverResponse;
  12929. }
  12930. if (!serverResponse.body) {
  12931. throw new Error("Missing body in server response");
  12932. }
  12933. const detectRedirectResponse = serverResponse.clone();
  12934. let serverResponseB = null;
  12935. if (hydrate2) {
  12936. serverResponseB = serverResponse.clone();
  12937. }
  12938. const body = serverResponse.body;
  12939. let buffer;
  12940. let streamControllers = [];
  12941. const createStream = () => {
  12942. if (!buffer) {
  12943. buffer = [];
  12944. return body.pipeThrough(
  12945. new TransformStream({
  12946. transform(chunk, controller) {
  12947. buffer.push(chunk);
  12948. controller.enqueue(chunk);
  12949. streamControllers.forEach((c) => c.enqueue(chunk));
  12950. },
  12951. flush() {
  12952. streamControllers.forEach((c) => c.close());
  12953. streamControllers = [];
  12954. }
  12955. })
  12956. );
  12957. }
  12958. return new ReadableStream({
  12959. start(controller) {
  12960. buffer.forEach((chunk) => controller.enqueue(chunk));
  12961. streamControllers.push(controller);
  12962. }
  12963. });
  12964. };
  12965. let deepestRenderedBoundaryId = null;
  12966. const getPayload = () => {
  12967. const payloadPromise = Promise.resolve(
  12968. createFromReadableStream(createStream())
  12969. );
  12970. return Object.defineProperties(payloadPromise, {
  12971. _deepestRenderedBoundaryId: {
  12972. get() {
  12973. return deepestRenderedBoundaryId;
  12974. },
  12975. set(boundaryId) {
  12976. deepestRenderedBoundaryId = boundaryId;
  12977. }
  12978. },
  12979. formState: {
  12980. get() {
  12981. return payloadPromise.then(
  12982. (payload) => payload.type === "render" ? payload.formState : void 0
  12983. );
  12984. }
  12985. }
  12986. });
  12987. };
  12988. try {
  12989. if (!detectRedirectResponse.body) {
  12990. throw new Error("Failed to clone server response");
  12991. }
  12992. const payload = await createFromReadableStream(
  12993. detectRedirectResponse.body
  12994. );
  12995. if (serverResponse.status === SINGLE_FETCH_REDIRECT_STATUS && payload.type === "redirect") {
  12996. const headers2 = new Headers(serverResponse.headers);
  12997. headers2.delete("Content-Encoding");
  12998. headers2.delete("Content-Length");
  12999. headers2.delete("Content-Type");
  13000. headers2.delete("X-Remix-Response");
  13001. headers2.set("Location", payload.location);
  13002. return new Response((serverResponseB == null ? void 0 : serverResponseB.body) || "", {
  13003. headers: headers2,
  13004. status: payload.status,
  13005. statusText: serverResponse.statusText
  13006. });
  13007. }
  13008. const html = await renderHTML(getPayload);
  13009. const headers = new Headers(serverResponse.headers);
  13010. headers.set("Content-Type", "text/html; charset=utf-8");
  13011. if (!hydrate2) {
  13012. return new Response(html, {
  13013. status: serverResponse.status,
  13014. headers
  13015. });
  13016. }
  13017. if (!(serverResponseB == null ? void 0 : serverResponseB.body)) {
  13018. throw new Error("Failed to clone server response");
  13019. }
  13020. const body2 = html.pipeThrough(injectRSCPayload(serverResponseB.body));
  13021. return new Response(body2, {
  13022. status: serverResponse.status,
  13023. headers
  13024. });
  13025. } catch (reason) {
  13026. if (reason instanceof Response) {
  13027. return reason;
  13028. }
  13029. try {
  13030. const status = isRouteErrorResponse(reason) ? reason.status : 500;
  13031. const html = await renderHTML(() => {
  13032. const decoded = Promise.resolve(
  13033. createFromReadableStream(createStream())
  13034. );
  13035. const payloadPromise = decoded.then(
  13036. (payload) => Object.assign(payload, {
  13037. status,
  13038. errors: deepestRenderedBoundaryId ? {
  13039. [deepestRenderedBoundaryId]: reason
  13040. } : {}
  13041. })
  13042. );
  13043. return Object.defineProperties(payloadPromise, {
  13044. _deepestRenderedBoundaryId: {
  13045. get() {
  13046. return deepestRenderedBoundaryId;
  13047. },
  13048. set(boundaryId) {
  13049. deepestRenderedBoundaryId = boundaryId;
  13050. }
  13051. },
  13052. formState: {
  13053. get() {
  13054. return payloadPromise.then(
  13055. (payload) => payload.type === "render" ? payload.formState : void 0
  13056. );
  13057. }
  13058. }
  13059. });
  13060. });
  13061. const headers = new Headers(serverResponse.headers);
  13062. headers.set("Content-Type", "text/html");
  13063. if (!hydrate2) {
  13064. return new Response(html, {
  13065. status,
  13066. headers
  13067. });
  13068. }
  13069. if (!(serverResponseB == null ? void 0 : serverResponseB.body)) {
  13070. throw new Error("Failed to clone server response");
  13071. }
  13072. const body2 = html.pipeThrough(injectRSCPayload(serverResponseB.body));
  13073. return new Response(body2, {
  13074. status,
  13075. headers
  13076. });
  13077. } catch {
  13078. }
  13079. throw reason;
  13080. }
  13081. }
  13082. function RSCStaticRouter({ getPayload }) {
  13083. const decoded = getPayload();
  13084. const payload = useSafe(decoded);
  13085. if (payload.type === "redirect") {
  13086. throw new Response(null, {
  13087. status: payload.status,
  13088. headers: {
  13089. Location: payload.location
  13090. }
  13091. });
  13092. }
  13093. if (payload.type !== "render") return null;
  13094. let patchedLoaderData = { ...payload.loaderData };
  13095. for (const match of payload.matches) {
  13096. if (shouldHydrateRouteLoader(
  13097. match.id,
  13098. match.clientLoader,
  13099. match.hasLoader,
  13100. false
  13101. ) && (match.hydrateFallbackElement || !match.hasLoader)) {
  13102. delete patchedLoaderData[match.id];
  13103. }
  13104. }
  13105. const context = {
  13106. get _deepestRenderedBoundaryId() {
  13107. return decoded._deepestRenderedBoundaryId ?? null;
  13108. },
  13109. set _deepestRenderedBoundaryId(boundaryId) {
  13110. decoded._deepestRenderedBoundaryId = boundaryId;
  13111. },
  13112. actionData: payload.actionData,
  13113. actionHeaders: {},
  13114. basename: payload.basename,
  13115. errors: payload.errors,
  13116. loaderData: patchedLoaderData,
  13117. loaderHeaders: {},
  13118. location: payload.location,
  13119. statusCode: 200,
  13120. matches: payload.matches.map((match) => ({
  13121. params: match.params,
  13122. pathname: match.pathname,
  13123. pathnameBase: match.pathnameBase,
  13124. route: {
  13125. id: match.id,
  13126. action: match.hasAction || !!match.clientAction,
  13127. handle: match.handle,
  13128. hasErrorBoundary: match.hasErrorBoundary,
  13129. loader: match.hasLoader || !!match.clientLoader,
  13130. index: match.index,
  13131. path: match.path,
  13132. shouldRevalidate: match.shouldRevalidate
  13133. }
  13134. }))
  13135. };
  13136. const router2 = createStaticRouter(
  13137. payload.matches.reduceRight((previous, match) => {
  13138. const route = {
  13139. id: match.id,
  13140. action: match.hasAction || !!match.clientAction,
  13141. element: match.element,
  13142. errorElement: match.errorElement,
  13143. handle: match.handle,
  13144. hasErrorBoundary: !!match.errorElement,
  13145. hydrateFallbackElement: match.hydrateFallbackElement,
  13146. index: match.index,
  13147. loader: match.hasLoader || !!match.clientLoader,
  13148. path: match.path,
  13149. shouldRevalidate: match.shouldRevalidate
  13150. };
  13151. if (previous.length > 0) {
  13152. route.children = previous;
  13153. }
  13154. return [route];
  13155. }, []),
  13156. context
  13157. );
  13158. const frameworkContext = {
  13159. future: {
  13160. // These flags have no runtime impact so can always be false. If we add
  13161. // flags that drive runtime behavior they'll need to be proxied through.
  13162. v8_middleware: false,
  13163. unstable_subResourceIntegrity: false
  13164. },
  13165. isSpaMode: false,
  13166. ssr: true,
  13167. criticalCss: "",
  13168. manifest: {
  13169. routes: {},
  13170. version: "1",
  13171. url: "",
  13172. entry: {
  13173. module: "",
  13174. imports: []
  13175. }
  13176. },
  13177. routeDiscovery: { mode: "lazy", manifestPath: "/__manifest" },
  13178. routeModules: createRSCRouteModules(payload)
  13179. };
  13180. return React42.createElement(RSCRouterContext.Provider, { value: true }, React42.createElement(RSCRouterGlobalErrorBoundary, { location: payload.location }, React42.createElement(FrameworkContext.Provider, { value: frameworkContext }, React42.createElement(
  13181. StaticRouterProvider,
  13182. {
  13183. context,
  13184. router: router2,
  13185. hydrate: false,
  13186. nonce: payload.nonce
  13187. }
  13188. ))));
  13189. }
  13190. function isReactServerRequest(url) {
  13191. return url.pathname.endsWith(".rsc");
  13192. }
  13193. function isManifestRequest(url) {
  13194. return url.pathname.endsWith(".manifest");
  13195. }
  13196. function deserializeErrors2(errors) {
  13197. if (!errors) return null;
  13198. let entries = Object.entries(errors);
  13199. let serialized = {};
  13200. for (let [key, val] of entries) {
  13201. if (val && val.__type === "RouteErrorResponse") {
  13202. serialized[key] = new ErrorResponseImpl(
  13203. val.status,
  13204. val.statusText,
  13205. val.data,
  13206. val.internal === true
  13207. );
  13208. } else if (val && val.__type === "Error") {
  13209. if (val.__subType) {
  13210. let ErrorConstructor = window[val.__subType];
  13211. if (typeof ErrorConstructor === "function") {
  13212. try {
  13213. let error = new ErrorConstructor(val.message);
  13214. error.stack = val.stack;
  13215. serialized[key] = error;
  13216. } catch (e) {
  13217. }
  13218. }
  13219. }
  13220. if (serialized[key] == null) {
  13221. let error = new Error(val.message);
  13222. error.stack = val.stack;
  13223. serialized[key] = error;
  13224. }
  13225. } else {
  13226. serialized[key] = val;
  13227. }
  13228. }
  13229. return serialized;
  13230. }
  13231. function getHydrationData({
  13232. state,
  13233. routes,
  13234. getRouteInfo,
  13235. location: location2,
  13236. basename,
  13237. isSpaMode
  13238. }) {
  13239. let hydrationData = {
  13240. ...state,
  13241. loaderData: { ...state.loaderData }
  13242. };
  13243. let initialMatches = matchRoutes(routes, location2, basename);
  13244. if (initialMatches) {
  13245. for (let match of initialMatches) {
  13246. let routeId = match.route.id;
  13247. let routeInfo = getRouteInfo(routeId);
  13248. if (shouldHydrateRouteLoader(
  13249. routeId,
  13250. routeInfo.clientLoader,
  13251. routeInfo.hasLoader,
  13252. isSpaMode
  13253. ) && (routeInfo.hasHydrateFallback || !routeInfo.hasLoader)) {
  13254. delete hydrationData.loaderData[routeId];
  13255. } else if (!routeInfo.hasLoader) {
  13256. hydrationData.loaderData[routeId] = null;
  13257. }
  13258. }
  13259. }
  13260. return hydrationData;
  13261. }
  13262. // node_modules/react-router/dist/development/dom-export.mjs
  13263. var React13 = __toESM(require_react(), 1);
  13264. var ReactDOM = __toESM(require_react_dom(), 1);
  13265. var React23 = __toESM(require_react(), 1);
  13266. var React33 = __toESM(require_react(), 1);
  13267. var ReactDOM2 = __toESM(require_react_dom(), 1);
  13268. function RouterProvider2(props) {
  13269. return React13.createElement(RouterProvider, { flushSync: ReactDOM.flushSync, ...props });
  13270. }
  13271. var ssrInfo = null;
  13272. var router = null;
  13273. function initSsrInfo() {
  13274. if (!ssrInfo && window.__reactRouterContext && window.__reactRouterManifest && window.__reactRouterRouteModules) {
  13275. if (window.__reactRouterManifest.sri === true) {
  13276. const importMap = document.querySelector("script[rr-importmap]");
  13277. if (importMap == null ? void 0 : importMap.textContent) {
  13278. try {
  13279. window.__reactRouterManifest.sri = JSON.parse(
  13280. importMap.textContent
  13281. ).integrity;
  13282. } catch (err) {
  13283. console.error("Failed to parse import map", err);
  13284. }
  13285. }
  13286. }
  13287. ssrInfo = {
  13288. context: window.__reactRouterContext,
  13289. manifest: window.__reactRouterManifest,
  13290. routeModules: window.__reactRouterRouteModules,
  13291. stateDecodingPromise: void 0,
  13292. router: void 0,
  13293. routerInitialized: false
  13294. };
  13295. }
  13296. }
  13297. function createHydratedRouter({
  13298. getContext,
  13299. unstable_instrumentations
  13300. }) {
  13301. var _a, _b;
  13302. initSsrInfo();
  13303. if (!ssrInfo) {
  13304. throw new Error(
  13305. "You must be using the SSR features of React Router in order to skip passing a `router` prop to `<RouterProvider>`"
  13306. );
  13307. }
  13308. let localSsrInfo = ssrInfo;
  13309. if (!ssrInfo.stateDecodingPromise) {
  13310. let stream = ssrInfo.context.stream;
  13311. invariant(stream, "No stream found for single fetch decoding");
  13312. ssrInfo.context.stream = void 0;
  13313. ssrInfo.stateDecodingPromise = decodeViaTurboStream(stream, window).then((value) => {
  13314. ssrInfo.context.state = value.value;
  13315. localSsrInfo.stateDecodingPromise.value = true;
  13316. }).catch((e) => {
  13317. localSsrInfo.stateDecodingPromise.error = e;
  13318. });
  13319. }
  13320. if (ssrInfo.stateDecodingPromise.error) {
  13321. throw ssrInfo.stateDecodingPromise.error;
  13322. }
  13323. if (!ssrInfo.stateDecodingPromise.value) {
  13324. throw ssrInfo.stateDecodingPromise;
  13325. }
  13326. let routes = createClientRoutes(
  13327. ssrInfo.manifest.routes,
  13328. ssrInfo.routeModules,
  13329. ssrInfo.context.state,
  13330. ssrInfo.context.ssr,
  13331. ssrInfo.context.isSpaMode
  13332. );
  13333. let hydrationData = void 0;
  13334. if (ssrInfo.context.isSpaMode) {
  13335. let { loaderData } = ssrInfo.context.state;
  13336. if (((_a = ssrInfo.manifest.routes.root) == null ? void 0 : _a.hasLoader) && loaderData && "root" in loaderData) {
  13337. hydrationData = {
  13338. loaderData: {
  13339. root: loaderData.root
  13340. }
  13341. };
  13342. }
  13343. } else {
  13344. hydrationData = getHydrationData({
  13345. state: ssrInfo.context.state,
  13346. routes,
  13347. getRouteInfo: (routeId) => {
  13348. var _a2, _b2, _c;
  13349. return {
  13350. clientLoader: (_a2 = ssrInfo.routeModules[routeId]) == null ? void 0 : _a2.clientLoader,
  13351. hasLoader: ((_b2 = ssrInfo.manifest.routes[routeId]) == null ? void 0 : _b2.hasLoader) === true,
  13352. hasHydrateFallback: ((_c = ssrInfo.routeModules[routeId]) == null ? void 0 : _c.HydrateFallback) != null
  13353. };
  13354. },
  13355. location: window.location,
  13356. basename: (_b = window.__reactRouterContext) == null ? void 0 : _b.basename,
  13357. isSpaMode: ssrInfo.context.isSpaMode
  13358. });
  13359. if (hydrationData && hydrationData.errors) {
  13360. hydrationData.errors = deserializeErrors2(hydrationData.errors);
  13361. }
  13362. }
  13363. let router2 = createRouter({
  13364. routes,
  13365. history: createBrowserHistory(),
  13366. basename: ssrInfo.context.basename,
  13367. getContext,
  13368. hydrationData,
  13369. hydrationRouteProperties,
  13370. unstable_instrumentations,
  13371. mapRouteProperties,
  13372. future: {
  13373. middleware: ssrInfo.context.future.v8_middleware
  13374. },
  13375. dataStrategy: getTurboStreamSingleFetchDataStrategy(
  13376. () => router2,
  13377. ssrInfo.manifest,
  13378. ssrInfo.routeModules,
  13379. ssrInfo.context.ssr,
  13380. ssrInfo.context.basename
  13381. ),
  13382. patchRoutesOnNavigation: getPatchRoutesOnNavigationFunction(
  13383. ssrInfo.manifest,
  13384. ssrInfo.routeModules,
  13385. ssrInfo.context.ssr,
  13386. ssrInfo.context.routeDiscovery,
  13387. ssrInfo.context.isSpaMode,
  13388. ssrInfo.context.basename
  13389. )
  13390. });
  13391. ssrInfo.router = router2;
  13392. if (router2.state.initialized) {
  13393. ssrInfo.routerInitialized = true;
  13394. router2.initialize();
  13395. }
  13396. router2.createRoutesForHMR = /* spacer so ts-ignore does not affect the right hand of the assignment */
  13397. createClientRoutesWithHMRRevalidationOptOut;
  13398. window.__reactRouterDataRouter = router2;
  13399. return router2;
  13400. }
  13401. function HydratedRouter(props) {
  13402. if (!router) {
  13403. router = createHydratedRouter({
  13404. getContext: props.getContext,
  13405. unstable_instrumentations: props.unstable_instrumentations
  13406. });
  13407. }
  13408. let [criticalCss, setCriticalCss] = React23.useState(
  13409. true ? ssrInfo == null ? void 0 : ssrInfo.context.criticalCss : void 0
  13410. );
  13411. React23.useEffect(() => {
  13412. if (true) {
  13413. setCriticalCss(void 0);
  13414. }
  13415. }, []);
  13416. React23.useEffect(() => {
  13417. if (criticalCss === void 0) {
  13418. document.querySelectorAll(`[${CRITICAL_CSS_DATA_ATTRIBUTE}]`).forEach((element) => element.remove());
  13419. }
  13420. }, [criticalCss]);
  13421. let [location2, setLocation] = React23.useState(router.state.location);
  13422. React23.useLayoutEffect(() => {
  13423. if (ssrInfo && ssrInfo.router && !ssrInfo.routerInitialized) {
  13424. ssrInfo.routerInitialized = true;
  13425. ssrInfo.router.initialize();
  13426. }
  13427. }, []);
  13428. React23.useLayoutEffect(() => {
  13429. if (ssrInfo && ssrInfo.router) {
  13430. return ssrInfo.router.subscribe((newState) => {
  13431. if (newState.location !== location2) {
  13432. setLocation(newState.location);
  13433. }
  13434. });
  13435. }
  13436. }, [location2]);
  13437. invariant(ssrInfo, "ssrInfo unavailable for HydratedRouter");
  13438. useFogOFWarDiscovery(
  13439. router,
  13440. ssrInfo.manifest,
  13441. ssrInfo.routeModules,
  13442. ssrInfo.context.ssr,
  13443. ssrInfo.context.routeDiscovery,
  13444. ssrInfo.context.isSpaMode
  13445. );
  13446. return (
  13447. // This fragment is important to ensure we match the <ServerRouter> JSX
  13448. // structure so that useId values hydrate correctly
  13449. React23.createElement(React23.Fragment, null, React23.createElement(
  13450. FrameworkContext.Provider,
  13451. {
  13452. value: {
  13453. manifest: ssrInfo.manifest,
  13454. routeModules: ssrInfo.routeModules,
  13455. future: ssrInfo.context.future,
  13456. criticalCss,
  13457. ssr: ssrInfo.context.ssr,
  13458. isSpaMode: ssrInfo.context.isSpaMode,
  13459. routeDiscovery: ssrInfo.context.routeDiscovery
  13460. }
  13461. },
  13462. React23.createElement(RemixErrorBoundary, { location: location2 }, React23.createElement(
  13463. RouterProvider2,
  13464. {
  13465. router,
  13466. unstable_useTransitions: props.unstable_useTransitions,
  13467. unstable_onError: props.unstable_onError
  13468. }
  13469. ))
  13470. ), React23.createElement(React23.Fragment, null))
  13471. );
  13472. }
  13473. var renderedRoutesContext = createContext4();
  13474. export {
  13475. Await,
  13476. BrowserRouter,
  13477. Form,
  13478. HashRouter,
  13479. HydratedRouter,
  13480. IDLE_BLOCKER,
  13481. IDLE_FETCHER,
  13482. IDLE_NAVIGATION,
  13483. Link,
  13484. Links,
  13485. MemoryRouter,
  13486. Meta,
  13487. NavLink,
  13488. Navigate,
  13489. Action as NavigationType,
  13490. Outlet,
  13491. PrefetchPageLinks,
  13492. Route,
  13493. Router,
  13494. RouterContextProvider,
  13495. RouterProvider2 as RouterProvider,
  13496. Routes,
  13497. Scripts,
  13498. ScrollRestoration,
  13499. ServerRouter,
  13500. StaticRouter,
  13501. StaticRouterProvider,
  13502. AwaitContextProvider as UNSAFE_AwaitContextProvider,
  13503. DataRouterContext as UNSAFE_DataRouterContext,
  13504. DataRouterStateContext as UNSAFE_DataRouterStateContext,
  13505. ErrorResponseImpl as UNSAFE_ErrorResponseImpl,
  13506. FetchersContext as UNSAFE_FetchersContext,
  13507. FrameworkContext as UNSAFE_FrameworkContext,
  13508. LocationContext as UNSAFE_LocationContext,
  13509. NavigationContext as UNSAFE_NavigationContext,
  13510. RSCDefaultRootErrorBoundary as UNSAFE_RSCDefaultRootErrorBoundary,
  13511. RemixErrorBoundary as UNSAFE_RemixErrorBoundary,
  13512. RouteContext as UNSAFE_RouteContext,
  13513. ServerMode as UNSAFE_ServerMode,
  13514. SingleFetchRedirectSymbol as UNSAFE_SingleFetchRedirectSymbol,
  13515. ViewTransitionContext as UNSAFE_ViewTransitionContext,
  13516. WithComponentProps as UNSAFE_WithComponentProps,
  13517. WithErrorBoundaryProps as UNSAFE_WithErrorBoundaryProps,
  13518. WithHydrateFallbackProps as UNSAFE_WithHydrateFallbackProps,
  13519. createBrowserHistory as UNSAFE_createBrowserHistory,
  13520. createClientRoutes as UNSAFE_createClientRoutes,
  13521. createClientRoutesWithHMRRevalidationOptOut as UNSAFE_createClientRoutesWithHMRRevalidationOptOut,
  13522. createRouter as UNSAFE_createRouter,
  13523. decodeViaTurboStream as UNSAFE_decodeViaTurboStream,
  13524. deserializeErrors2 as UNSAFE_deserializeErrors,
  13525. getHydrationData as UNSAFE_getHydrationData,
  13526. getPatchRoutesOnNavigationFunction as UNSAFE_getPatchRoutesOnNavigationFunction,
  13527. getTurboStreamSingleFetchDataStrategy as UNSAFE_getTurboStreamSingleFetchDataStrategy,
  13528. hydrationRouteProperties as UNSAFE_hydrationRouteProperties,
  13529. invariant as UNSAFE_invariant,
  13530. mapRouteProperties as UNSAFE_mapRouteProperties,
  13531. shouldHydrateRouteLoader as UNSAFE_shouldHydrateRouteLoader,
  13532. useFogOFWarDiscovery as UNSAFE_useFogOFWarDiscovery,
  13533. useScrollRestoration as UNSAFE_useScrollRestoration,
  13534. withComponentProps as UNSAFE_withComponentProps,
  13535. withErrorBoundaryProps as UNSAFE_withErrorBoundaryProps,
  13536. withHydrateFallbackProps as UNSAFE_withHydrateFallbackProps,
  13537. createBrowserRouter,
  13538. createContext4 as createContext,
  13539. createCookie,
  13540. createCookieSessionStorage,
  13541. createHashRouter,
  13542. createMemoryRouter,
  13543. createMemorySessionStorage,
  13544. createPath,
  13545. createRequestHandler,
  13546. createRoutesFromChildren,
  13547. createRoutesFromElements,
  13548. createRoutesStub,
  13549. createSearchParams,
  13550. createSession,
  13551. createSessionStorage,
  13552. createStaticHandler2 as createStaticHandler,
  13553. createStaticRouter,
  13554. data,
  13555. generatePath,
  13556. href,
  13557. isCookie,
  13558. isRouteErrorResponse,
  13559. isSession,
  13560. matchPath,
  13561. matchRoutes,
  13562. parsePath,
  13563. redirect,
  13564. redirectDocument,
  13565. renderMatches,
  13566. replace,
  13567. resolvePath,
  13568. HistoryRouter as unstable_HistoryRouter,
  13569. RSCStaticRouter as unstable_RSCStaticRouter,
  13570. routeRSCServerRequest as unstable_routeRSCServerRequest,
  13571. setDevServerHooks as unstable_setDevServerHooks,
  13572. usePrompt as unstable_usePrompt,
  13573. useRoute as unstable_useRoute,
  13574. useActionData,
  13575. useAsyncError,
  13576. useAsyncValue,
  13577. useBeforeUnload,
  13578. useBlocker,
  13579. useFetcher,
  13580. useFetchers,
  13581. useFormAction,
  13582. useHref,
  13583. useInRouterContext,
  13584. useLinkClickHandler,
  13585. useLoaderData,
  13586. useLocation,
  13587. useMatch,
  13588. useMatches,
  13589. useNavigate,
  13590. useNavigation,
  13591. useNavigationType,
  13592. useOutlet,
  13593. useOutletContext,
  13594. useParams,
  13595. useResolvedPath,
  13596. useRevalidator,
  13597. useRouteError,
  13598. useRouteLoaderData,
  13599. useRoutes,
  13600. useSearchParams,
  13601. useSubmit,
  13602. useViewTransitionState
  13603. };
  13604. /*! Bundled license information:
  13605. react-router/dist/development/chunk-WWGJGFF6.mjs:
  13606. react-router/dist/development/chunk-PMGK554W.mjs:
  13607. react-router/dist/development/dom-export.mjs:
  13608. react-router/dist/development/index.mjs:
  13609. (**
  13610. * react-router v7.10.1
  13611. *
  13612. * Copyright (c) Remix Software Inc.
  13613. *
  13614. * This source code is licensed under the MIT license found in the
  13615. * LICENSE.md file in the root directory of this source tree.
  13616. *
  13617. * @license MIT
  13618. *)
  13619. react-router-dom/dist/index.mjs:
  13620. (**
  13621. * react-router-dom v7.10.1
  13622. *
  13623. * Copyright (c) Remix Software Inc.
  13624. *
  13625. * This source code is licensed under the MIT license found in the
  13626. * LICENSE.md file in the root directory of this source tree.
  13627. *
  13628. * @license MIT
  13629. *)
  13630. */
  13631. //# sourceMappingURL=react-router-dom.js.map