react-router-dom.js 205 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078
  1. import {
  2. require_react_dom
  3. } from "./chunk-2RADP4CJ.js";
  4. import {
  5. require_react
  6. } from "./chunk-6KCF6AHO.js";
  7. import {
  8. __toESM
  9. } from "./chunk-DC5AMYBS.js";
  10. // node_modules/react-router-dom/dist/index.js
  11. var React2 = __toESM(require_react());
  12. var ReactDOM = __toESM(require_react_dom());
  13. // node_modules/react-router/dist/index.js
  14. var React = __toESM(require_react());
  15. // node_modules/@remix-run/router/dist/router.js
  16. function _extends() {
  17. _extends = Object.assign ? Object.assign.bind() : function(target) {
  18. for (var i = 1; i < arguments.length; i++) {
  19. var source = arguments[i];
  20. for (var key in source) {
  21. if (Object.prototype.hasOwnProperty.call(source, key)) {
  22. target[key] = source[key];
  23. }
  24. }
  25. }
  26. return target;
  27. };
  28. return _extends.apply(this, arguments);
  29. }
  30. var Action;
  31. (function(Action2) {
  32. Action2["Pop"] = "POP";
  33. Action2["Push"] = "PUSH";
  34. Action2["Replace"] = "REPLACE";
  35. })(Action || (Action = {}));
  36. var PopStateEventType = "popstate";
  37. function createMemoryHistory(options) {
  38. if (options === void 0) {
  39. options = {};
  40. }
  41. let {
  42. initialEntries = ["/"],
  43. initialIndex,
  44. v5Compat = false
  45. } = options;
  46. let entries;
  47. entries = initialEntries.map((entry, index2) => createMemoryLocation(entry, typeof entry === "string" ? null : entry.state, index2 === 0 ? "default" : void 0));
  48. let index = clampIndex(initialIndex == null ? entries.length - 1 : initialIndex);
  49. let action = Action.Pop;
  50. let listener = null;
  51. function clampIndex(n) {
  52. return Math.min(Math.max(n, 0), entries.length - 1);
  53. }
  54. function getCurrentLocation() {
  55. return entries[index];
  56. }
  57. function createMemoryLocation(to, state, key) {
  58. if (state === void 0) {
  59. state = null;
  60. }
  61. let location = createLocation(entries ? getCurrentLocation().pathname : "/", to, state, key);
  62. warning(location.pathname.charAt(0) === "/", "relative pathnames are not supported in memory history: " + JSON.stringify(to));
  63. return location;
  64. }
  65. function createHref(to) {
  66. return typeof to === "string" ? to : createPath(to);
  67. }
  68. let history = {
  69. get index() {
  70. return index;
  71. },
  72. get action() {
  73. return action;
  74. },
  75. get location() {
  76. return getCurrentLocation();
  77. },
  78. createHref,
  79. createURL(to) {
  80. return new URL(createHref(to), "http://localhost");
  81. },
  82. encodeLocation(to) {
  83. let path = typeof to === "string" ? parsePath(to) : to;
  84. return {
  85. pathname: path.pathname || "",
  86. search: path.search || "",
  87. hash: path.hash || ""
  88. };
  89. },
  90. push(to, state) {
  91. action = Action.Push;
  92. let nextLocation = createMemoryLocation(to, state);
  93. index += 1;
  94. entries.splice(index, entries.length, nextLocation);
  95. if (v5Compat && listener) {
  96. listener({
  97. action,
  98. location: nextLocation,
  99. delta: 1
  100. });
  101. }
  102. },
  103. replace(to, state) {
  104. action = Action.Replace;
  105. let nextLocation = createMemoryLocation(to, state);
  106. entries[index] = nextLocation;
  107. if (v5Compat && listener) {
  108. listener({
  109. action,
  110. location: nextLocation,
  111. delta: 0
  112. });
  113. }
  114. },
  115. go(delta) {
  116. action = Action.Pop;
  117. let nextIndex = clampIndex(index + delta);
  118. let nextLocation = entries[nextIndex];
  119. index = nextIndex;
  120. if (listener) {
  121. listener({
  122. action,
  123. location: nextLocation,
  124. delta
  125. });
  126. }
  127. },
  128. listen(fn) {
  129. listener = fn;
  130. return () => {
  131. listener = null;
  132. };
  133. }
  134. };
  135. return history;
  136. }
  137. function createBrowserHistory(options) {
  138. if (options === void 0) {
  139. options = {};
  140. }
  141. function createBrowserLocation(window2, globalHistory) {
  142. let {
  143. pathname,
  144. search,
  145. hash
  146. } = window2.location;
  147. return createLocation(
  148. "",
  149. {
  150. pathname,
  151. search,
  152. hash
  153. },
  154. // state defaults to `null` because `window.history.state` does
  155. globalHistory.state && globalHistory.state.usr || null,
  156. globalHistory.state && globalHistory.state.key || "default"
  157. );
  158. }
  159. function createBrowserHref(window2, to) {
  160. return typeof to === "string" ? to : createPath(to);
  161. }
  162. return getUrlBasedHistory(createBrowserLocation, createBrowserHref, null, options);
  163. }
  164. function createHashHistory(options) {
  165. if (options === void 0) {
  166. options = {};
  167. }
  168. function createHashLocation(window2, globalHistory) {
  169. let {
  170. pathname = "/",
  171. search = "",
  172. hash = ""
  173. } = parsePath(window2.location.hash.substr(1));
  174. if (!pathname.startsWith("/") && !pathname.startsWith(".")) {
  175. pathname = "/" + pathname;
  176. }
  177. return createLocation(
  178. "",
  179. {
  180. pathname,
  181. search,
  182. hash
  183. },
  184. // state defaults to `null` because `window.history.state` does
  185. globalHistory.state && globalHistory.state.usr || null,
  186. globalHistory.state && globalHistory.state.key || "default"
  187. );
  188. }
  189. function createHashHref(window2, to) {
  190. let base = window2.document.querySelector("base");
  191. let href = "";
  192. if (base && base.getAttribute("href")) {
  193. let url = window2.location.href;
  194. let hashIndex = url.indexOf("#");
  195. href = hashIndex === -1 ? url : url.slice(0, hashIndex);
  196. }
  197. return href + "#" + (typeof to === "string" ? to : createPath(to));
  198. }
  199. function validateHashLocation(location, to) {
  200. warning(location.pathname.charAt(0) === "/", "relative pathnames are not supported in hash history.push(" + JSON.stringify(to) + ")");
  201. }
  202. return getUrlBasedHistory(createHashLocation, createHashHref, validateHashLocation, options);
  203. }
  204. function invariant(value, message) {
  205. if (value === false || value === null || typeof value === "undefined") {
  206. throw new Error(message);
  207. }
  208. }
  209. function warning(cond, message) {
  210. if (!cond) {
  211. if (typeof console !== "undefined") console.warn(message);
  212. try {
  213. throw new Error(message);
  214. } catch (e) {
  215. }
  216. }
  217. }
  218. function createKey() {
  219. return Math.random().toString(36).substr(2, 8);
  220. }
  221. function getHistoryState(location, index) {
  222. return {
  223. usr: location.state,
  224. key: location.key,
  225. idx: index
  226. };
  227. }
  228. function createLocation(current, to, state, key) {
  229. if (state === void 0) {
  230. state = null;
  231. }
  232. let location = _extends({
  233. pathname: typeof current === "string" ? current : current.pathname,
  234. search: "",
  235. hash: ""
  236. }, typeof to === "string" ? parsePath(to) : to, {
  237. state,
  238. // TODO: This could be cleaned up. push/replace should probably just take
  239. // full Locations now and avoid the need to run through this flow at all
  240. // But that's a pretty big refactor to the current test suite so going to
  241. // keep as is for the time being and just let any incoming keys take precedence
  242. key: to && to.key || key || createKey()
  243. });
  244. return location;
  245. }
  246. function createPath(_ref) {
  247. let {
  248. pathname = "/",
  249. search = "",
  250. hash = ""
  251. } = _ref;
  252. if (search && search !== "?") pathname += search.charAt(0) === "?" ? search : "?" + search;
  253. if (hash && hash !== "#") pathname += hash.charAt(0) === "#" ? hash : "#" + hash;
  254. return pathname;
  255. }
  256. function parsePath(path) {
  257. let parsedPath = {};
  258. if (path) {
  259. let hashIndex = path.indexOf("#");
  260. if (hashIndex >= 0) {
  261. parsedPath.hash = path.substr(hashIndex);
  262. path = path.substr(0, hashIndex);
  263. }
  264. let searchIndex = path.indexOf("?");
  265. if (searchIndex >= 0) {
  266. parsedPath.search = path.substr(searchIndex);
  267. path = path.substr(0, searchIndex);
  268. }
  269. if (path) {
  270. parsedPath.pathname = path;
  271. }
  272. }
  273. return parsedPath;
  274. }
  275. function getUrlBasedHistory(getLocation, createHref, validateLocation, options) {
  276. if (options === void 0) {
  277. options = {};
  278. }
  279. let {
  280. window: window2 = document.defaultView,
  281. v5Compat = false
  282. } = options;
  283. let globalHistory = window2.history;
  284. let action = Action.Pop;
  285. let listener = null;
  286. let index = getIndex();
  287. if (index == null) {
  288. index = 0;
  289. globalHistory.replaceState(_extends({}, globalHistory.state, {
  290. idx: index
  291. }), "");
  292. }
  293. function getIndex() {
  294. let state = globalHistory.state || {
  295. idx: null
  296. };
  297. return state.idx;
  298. }
  299. function handlePop() {
  300. action = Action.Pop;
  301. let nextIndex = getIndex();
  302. let delta = nextIndex == null ? null : nextIndex - index;
  303. index = nextIndex;
  304. if (listener) {
  305. listener({
  306. action,
  307. location: history.location,
  308. delta
  309. });
  310. }
  311. }
  312. function push(to, state) {
  313. action = Action.Push;
  314. let location = createLocation(history.location, to, state);
  315. if (validateLocation) validateLocation(location, to);
  316. index = getIndex() + 1;
  317. let historyState = getHistoryState(location, index);
  318. let url = history.createHref(location);
  319. try {
  320. globalHistory.pushState(historyState, "", url);
  321. } catch (error) {
  322. if (error instanceof DOMException && error.name === "DataCloneError") {
  323. throw error;
  324. }
  325. window2.location.assign(url);
  326. }
  327. if (v5Compat && listener) {
  328. listener({
  329. action,
  330. location: history.location,
  331. delta: 1
  332. });
  333. }
  334. }
  335. function replace2(to, state) {
  336. action = Action.Replace;
  337. let location = createLocation(history.location, to, state);
  338. if (validateLocation) validateLocation(location, to);
  339. index = getIndex();
  340. let historyState = getHistoryState(location, index);
  341. let url = history.createHref(location);
  342. globalHistory.replaceState(historyState, "", url);
  343. if (v5Compat && listener) {
  344. listener({
  345. action,
  346. location: history.location,
  347. delta: 0
  348. });
  349. }
  350. }
  351. function createURL(to) {
  352. let base = window2.location.origin !== "null" ? window2.location.origin : window2.location.href;
  353. let href = typeof to === "string" ? to : createPath(to);
  354. href = href.replace(/ $/, "%20");
  355. invariant(base, "No window.location.(origin|href) available to create URL for href: " + href);
  356. return new URL(href, base);
  357. }
  358. let history = {
  359. get action() {
  360. return action;
  361. },
  362. get location() {
  363. return getLocation(window2, globalHistory);
  364. },
  365. listen(fn) {
  366. if (listener) {
  367. throw new Error("A history only accepts one active listener");
  368. }
  369. window2.addEventListener(PopStateEventType, handlePop);
  370. listener = fn;
  371. return () => {
  372. window2.removeEventListener(PopStateEventType, handlePop);
  373. listener = null;
  374. };
  375. },
  376. createHref(to) {
  377. return createHref(window2, to);
  378. },
  379. createURL,
  380. encodeLocation(to) {
  381. let url = createURL(to);
  382. return {
  383. pathname: url.pathname,
  384. search: url.search,
  385. hash: url.hash
  386. };
  387. },
  388. push,
  389. replace: replace2,
  390. go(n) {
  391. return globalHistory.go(n);
  392. }
  393. };
  394. return history;
  395. }
  396. var ResultType;
  397. (function(ResultType2) {
  398. ResultType2["data"] = "data";
  399. ResultType2["deferred"] = "deferred";
  400. ResultType2["redirect"] = "redirect";
  401. ResultType2["error"] = "error";
  402. })(ResultType || (ResultType = {}));
  403. var immutableRouteKeys = /* @__PURE__ */ new Set(["lazy", "caseSensitive", "path", "id", "index", "children"]);
  404. function isIndexRoute(route) {
  405. return route.index === true;
  406. }
  407. function convertRoutesToDataRoutes(routes, mapRouteProperties2, parentPath, manifest) {
  408. if (parentPath === void 0) {
  409. parentPath = [];
  410. }
  411. if (manifest === void 0) {
  412. manifest = {};
  413. }
  414. return routes.map((route, index) => {
  415. let treePath = [...parentPath, String(index)];
  416. let id = typeof route.id === "string" ? route.id : treePath.join("-");
  417. invariant(route.index !== true || !route.children, "Cannot specify children on an index route");
  418. invariant(!manifest[id], 'Found a route id collision on id "' + id + `". Route id's must be globally unique within Data Router usages`);
  419. if (isIndexRoute(route)) {
  420. let indexRoute = _extends({}, route, mapRouteProperties2(route), {
  421. id
  422. });
  423. manifest[id] = indexRoute;
  424. return indexRoute;
  425. } else {
  426. let pathOrLayoutRoute = _extends({}, route, mapRouteProperties2(route), {
  427. id,
  428. children: void 0
  429. });
  430. manifest[id] = pathOrLayoutRoute;
  431. if (route.children) {
  432. pathOrLayoutRoute.children = convertRoutesToDataRoutes(route.children, mapRouteProperties2, treePath, manifest);
  433. }
  434. return pathOrLayoutRoute;
  435. }
  436. });
  437. }
  438. function matchRoutes(routes, locationArg, basename) {
  439. if (basename === void 0) {
  440. basename = "/";
  441. }
  442. return matchRoutesImpl(routes, locationArg, basename, false);
  443. }
  444. function matchRoutesImpl(routes, locationArg, basename, allowPartial) {
  445. let location = typeof locationArg === "string" ? parsePath(locationArg) : locationArg;
  446. let pathname = stripBasename(location.pathname || "/", basename);
  447. if (pathname == null) {
  448. return null;
  449. }
  450. let branches = flattenRoutes(routes);
  451. rankRouteBranches(branches);
  452. let matches = null;
  453. for (let i = 0; matches == null && i < branches.length; ++i) {
  454. let decoded = decodePath(pathname);
  455. matches = matchRouteBranch(branches[i], decoded, allowPartial);
  456. }
  457. return matches;
  458. }
  459. function convertRouteMatchToUiMatch(match, loaderData) {
  460. let {
  461. route,
  462. pathname,
  463. params
  464. } = match;
  465. return {
  466. id: route.id,
  467. pathname,
  468. params,
  469. data: loaderData[route.id],
  470. handle: route.handle
  471. };
  472. }
  473. function flattenRoutes(routes, branches, parentsMeta, parentPath) {
  474. if (branches === void 0) {
  475. branches = [];
  476. }
  477. if (parentsMeta === void 0) {
  478. parentsMeta = [];
  479. }
  480. if (parentPath === void 0) {
  481. parentPath = "";
  482. }
  483. let flattenRoute = (route, index, relativePath) => {
  484. let meta = {
  485. relativePath: relativePath === void 0 ? route.path || "" : relativePath,
  486. caseSensitive: route.caseSensitive === true,
  487. childrenIndex: index,
  488. route
  489. };
  490. if (meta.relativePath.startsWith("/")) {
  491. invariant(meta.relativePath.startsWith(parentPath), 'Absolute route path "' + meta.relativePath + '" nested under path ' + ('"' + parentPath + '" is not valid. An absolute child route path ') + "must start with the combined path of all its parent routes.");
  492. meta.relativePath = meta.relativePath.slice(parentPath.length);
  493. }
  494. let path = joinPaths([parentPath, meta.relativePath]);
  495. let routesMeta = parentsMeta.concat(meta);
  496. if (route.children && route.children.length > 0) {
  497. invariant(
  498. // Our types know better, but runtime JS may not!
  499. // @ts-expect-error
  500. route.index !== true,
  501. "Index routes must not have child routes. Please remove " + ('all child routes from route path "' + path + '".')
  502. );
  503. flattenRoutes(route.children, branches, routesMeta, path);
  504. }
  505. if (route.path == null && !route.index) {
  506. return;
  507. }
  508. branches.push({
  509. path,
  510. score: computeScore(path, route.index),
  511. routesMeta
  512. });
  513. };
  514. routes.forEach((route, index) => {
  515. var _route$path;
  516. if (route.path === "" || !((_route$path = route.path) != null && _route$path.includes("?"))) {
  517. flattenRoute(route, index);
  518. } else {
  519. for (let exploded of explodeOptionalSegments(route.path)) {
  520. flattenRoute(route, index, exploded);
  521. }
  522. }
  523. });
  524. return branches;
  525. }
  526. function explodeOptionalSegments(path) {
  527. let segments = path.split("/");
  528. if (segments.length === 0) return [];
  529. let [first, ...rest] = segments;
  530. let isOptional = first.endsWith("?");
  531. let required = first.replace(/\?$/, "");
  532. if (rest.length === 0) {
  533. return isOptional ? [required, ""] : [required];
  534. }
  535. let restExploded = explodeOptionalSegments(rest.join("/"));
  536. let result = [];
  537. result.push(...restExploded.map((subpath) => subpath === "" ? required : [required, subpath].join("/")));
  538. if (isOptional) {
  539. result.push(...restExploded);
  540. }
  541. return result.map((exploded) => path.startsWith("/") && exploded === "" ? "/" : exploded);
  542. }
  543. function rankRouteBranches(branches) {
  544. branches.sort((a, b) => a.score !== b.score ? b.score - a.score : compareIndexes(a.routesMeta.map((meta) => meta.childrenIndex), b.routesMeta.map((meta) => meta.childrenIndex)));
  545. }
  546. var paramRe = /^:[\w-]+$/;
  547. var dynamicSegmentValue = 3;
  548. var indexRouteValue = 2;
  549. var emptySegmentValue = 1;
  550. var staticSegmentValue = 10;
  551. var splatPenalty = -2;
  552. var isSplat = (s) => s === "*";
  553. function computeScore(path, index) {
  554. let segments = path.split("/");
  555. let initialScore = segments.length;
  556. if (segments.some(isSplat)) {
  557. initialScore += splatPenalty;
  558. }
  559. if (index) {
  560. initialScore += indexRouteValue;
  561. }
  562. return segments.filter((s) => !isSplat(s)).reduce((score, segment) => score + (paramRe.test(segment) ? dynamicSegmentValue : segment === "" ? emptySegmentValue : staticSegmentValue), initialScore);
  563. }
  564. function compareIndexes(a, b) {
  565. let siblings = a.length === b.length && a.slice(0, -1).every((n, i) => n === b[i]);
  566. return siblings ? (
  567. // If two routes are siblings, we should try to match the earlier sibling
  568. // first. This allows people to have fine-grained control over the matching
  569. // behavior by simply putting routes with identical paths in the order they
  570. // want them tried.
  571. a[a.length - 1] - b[b.length - 1]
  572. ) : (
  573. // Otherwise, it doesn't really make sense to rank non-siblings by index,
  574. // so they sort equally.
  575. 0
  576. );
  577. }
  578. function matchRouteBranch(branch, pathname, allowPartial) {
  579. if (allowPartial === void 0) {
  580. allowPartial = false;
  581. }
  582. let {
  583. routesMeta
  584. } = branch;
  585. let matchedParams = {};
  586. let matchedPathname = "/";
  587. let matches = [];
  588. for (let i = 0; i < routesMeta.length; ++i) {
  589. let meta = routesMeta[i];
  590. let end = i === routesMeta.length - 1;
  591. let remainingPathname = matchedPathname === "/" ? pathname : pathname.slice(matchedPathname.length) || "/";
  592. let match = matchPath({
  593. path: meta.relativePath,
  594. caseSensitive: meta.caseSensitive,
  595. end
  596. }, remainingPathname);
  597. let route = meta.route;
  598. if (!match && end && allowPartial && !routesMeta[routesMeta.length - 1].route.index) {
  599. match = matchPath({
  600. path: meta.relativePath,
  601. caseSensitive: meta.caseSensitive,
  602. end: false
  603. }, remainingPathname);
  604. }
  605. if (!match) {
  606. return null;
  607. }
  608. Object.assign(matchedParams, match.params);
  609. matches.push({
  610. // TODO: Can this as be avoided?
  611. params: matchedParams,
  612. pathname: joinPaths([matchedPathname, match.pathname]),
  613. pathnameBase: normalizePathname(joinPaths([matchedPathname, match.pathnameBase])),
  614. route
  615. });
  616. if (match.pathnameBase !== "/") {
  617. matchedPathname = joinPaths([matchedPathname, match.pathnameBase]);
  618. }
  619. }
  620. return matches;
  621. }
  622. function generatePath(originalPath, params) {
  623. if (params === void 0) {
  624. params = {};
  625. }
  626. let path = originalPath;
  627. if (path.endsWith("*") && path !== "*" && !path.endsWith("/*")) {
  628. warning(false, 'Route path "' + path + '" will be treated as if it were ' + ('"' + path.replace(/\*$/, "/*") + '" because the `*` character must ') + "always follow a `/` in the pattern. To get rid of this warning, " + ('please change the route path to "' + path.replace(/\*$/, "/*") + '".'));
  629. path = path.replace(/\*$/, "/*");
  630. }
  631. const prefix = path.startsWith("/") ? "/" : "";
  632. const stringify = (p) => p == null ? "" : typeof p === "string" ? p : String(p);
  633. const segments = path.split(/\/+/).map((segment, index, array) => {
  634. const isLastSegment = index === array.length - 1;
  635. if (isLastSegment && segment === "*") {
  636. const star = "*";
  637. return stringify(params[star]);
  638. }
  639. const keyMatch = segment.match(/^:([\w-]+)(\??)$/);
  640. if (keyMatch) {
  641. const [, key, optional] = keyMatch;
  642. let param = params[key];
  643. invariant(optional === "?" || param != null, 'Missing ":' + key + '" param');
  644. return stringify(param);
  645. }
  646. return segment.replace(/\?$/g, "");
  647. }).filter((segment) => !!segment);
  648. return prefix + segments.join("/");
  649. }
  650. function matchPath(pattern, pathname) {
  651. if (typeof pattern === "string") {
  652. pattern = {
  653. path: pattern,
  654. caseSensitive: false,
  655. end: true
  656. };
  657. }
  658. let [matcher, compiledParams] = compilePath(pattern.path, pattern.caseSensitive, pattern.end);
  659. let match = pathname.match(matcher);
  660. if (!match) return null;
  661. let matchedPathname = match[0];
  662. let pathnameBase = matchedPathname.replace(/(.)\/+$/, "$1");
  663. let captureGroups = match.slice(1);
  664. let params = compiledParams.reduce((memo2, _ref, index) => {
  665. let {
  666. paramName,
  667. isOptional
  668. } = _ref;
  669. if (paramName === "*") {
  670. let splatValue = captureGroups[index] || "";
  671. pathnameBase = matchedPathname.slice(0, matchedPathname.length - splatValue.length).replace(/(.)\/+$/, "$1");
  672. }
  673. const value = captureGroups[index];
  674. if (isOptional && !value) {
  675. memo2[paramName] = void 0;
  676. } else {
  677. memo2[paramName] = (value || "").replace(/%2F/g, "/");
  678. }
  679. return memo2;
  680. }, {});
  681. return {
  682. params,
  683. pathname: matchedPathname,
  684. pathnameBase,
  685. pattern
  686. };
  687. }
  688. function compilePath(path, caseSensitive, end) {
  689. if (caseSensitive === void 0) {
  690. caseSensitive = false;
  691. }
  692. if (end === void 0) {
  693. end = true;
  694. }
  695. warning(path === "*" || !path.endsWith("*") || path.endsWith("/*"), 'Route path "' + path + '" will be treated as if it were ' + ('"' + path.replace(/\*$/, "/*") + '" because the `*` character must ') + "always follow a `/` in the pattern. To get rid of this warning, " + ('please change the route path to "' + path.replace(/\*$/, "/*") + '".'));
  696. let params = [];
  697. let regexpSource = "^" + path.replace(/\/*\*?$/, "").replace(/^\/*/, "/").replace(/[\\.*+^${}|()[\]]/g, "\\$&").replace(/\/:([\w-]+)(\?)?/g, (_, paramName, isOptional) => {
  698. params.push({
  699. paramName,
  700. isOptional: isOptional != null
  701. });
  702. return isOptional ? "/?([^\\/]+)?" : "/([^\\/]+)";
  703. });
  704. if (path.endsWith("*")) {
  705. params.push({
  706. paramName: "*"
  707. });
  708. regexpSource += path === "*" || path === "/*" ? "(.*)$" : "(?:\\/(.+)|\\/*)$";
  709. } else if (end) {
  710. regexpSource += "\\/*$";
  711. } else if (path !== "" && path !== "/") {
  712. regexpSource += "(?:(?=\\/|$))";
  713. } else ;
  714. let matcher = new RegExp(regexpSource, caseSensitive ? void 0 : "i");
  715. return [matcher, params];
  716. }
  717. function decodePath(value) {
  718. try {
  719. return value.split("/").map((v) => decodeURIComponent(v).replace(/\//g, "%2F")).join("/");
  720. } catch (error) {
  721. warning(false, 'The URL path "' + value + '" could not be decoded because it is is a malformed URL segment. This is probably due to a bad percent ' + ("encoding (" + error + ")."));
  722. return value;
  723. }
  724. }
  725. function stripBasename(pathname, basename) {
  726. if (basename === "/") return pathname;
  727. if (!pathname.toLowerCase().startsWith(basename.toLowerCase())) {
  728. return null;
  729. }
  730. let startIndex = basename.endsWith("/") ? basename.length - 1 : basename.length;
  731. let nextChar = pathname.charAt(startIndex);
  732. if (nextChar && nextChar !== "/") {
  733. return null;
  734. }
  735. return pathname.slice(startIndex) || "/";
  736. }
  737. var ABSOLUTE_URL_REGEX$1 = /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i;
  738. var isAbsoluteUrl = (url) => ABSOLUTE_URL_REGEX$1.test(url);
  739. function resolvePath(to, fromPathname) {
  740. if (fromPathname === void 0) {
  741. fromPathname = "/";
  742. }
  743. let {
  744. pathname: toPathname,
  745. search = "",
  746. hash = ""
  747. } = typeof to === "string" ? parsePath(to) : to;
  748. let pathname;
  749. if (toPathname) {
  750. if (isAbsoluteUrl(toPathname)) {
  751. pathname = toPathname;
  752. } else {
  753. if (toPathname.includes("//")) {
  754. let oldPathname = toPathname;
  755. toPathname = toPathname.replace(/\/\/+/g, "/");
  756. warning(false, "Pathnames cannot have embedded double slashes - normalizing " + (oldPathname + " -> " + toPathname));
  757. }
  758. if (toPathname.startsWith("/")) {
  759. pathname = resolvePathname(toPathname.substring(1), "/");
  760. } else {
  761. pathname = resolvePathname(toPathname, fromPathname);
  762. }
  763. }
  764. } else {
  765. pathname = fromPathname;
  766. }
  767. return {
  768. pathname,
  769. search: normalizeSearch(search),
  770. hash: normalizeHash(hash)
  771. };
  772. }
  773. function resolvePathname(relativePath, fromPathname) {
  774. let segments = fromPathname.replace(/\/+$/, "").split("/");
  775. let relativeSegments = relativePath.split("/");
  776. relativeSegments.forEach((segment) => {
  777. if (segment === "..") {
  778. if (segments.length > 1) segments.pop();
  779. } else if (segment !== ".") {
  780. segments.push(segment);
  781. }
  782. });
  783. return segments.length > 1 ? segments.join("/") : "/";
  784. }
  785. function getInvalidPathError(char, field, dest, path) {
  786. return "Cannot include a '" + char + "' character in a manually specified " + ("`to." + field + "` field [" + JSON.stringify(path) + "]. Please separate it out to the ") + ("`to." + dest + "` field. Alternatively you may provide the full path as ") + 'a string in <Link to="..."> and the router will parse it for you.';
  787. }
  788. function getPathContributingMatches(matches) {
  789. return matches.filter((match, index) => index === 0 || match.route.path && match.route.path.length > 0);
  790. }
  791. function getResolveToMatches(matches, v7_relativeSplatPath) {
  792. let pathMatches = getPathContributingMatches(matches);
  793. if (v7_relativeSplatPath) {
  794. return pathMatches.map((match, idx) => idx === pathMatches.length - 1 ? match.pathname : match.pathnameBase);
  795. }
  796. return pathMatches.map((match) => match.pathnameBase);
  797. }
  798. function resolveTo(toArg, routePathnames, locationPathname, isPathRelative) {
  799. if (isPathRelative === void 0) {
  800. isPathRelative = false;
  801. }
  802. let to;
  803. if (typeof toArg === "string") {
  804. to = parsePath(toArg);
  805. } else {
  806. to = _extends({}, toArg);
  807. invariant(!to.pathname || !to.pathname.includes("?"), getInvalidPathError("?", "pathname", "search", to));
  808. invariant(!to.pathname || !to.pathname.includes("#"), getInvalidPathError("#", "pathname", "hash", to));
  809. invariant(!to.search || !to.search.includes("#"), getInvalidPathError("#", "search", "hash", to));
  810. }
  811. let isEmptyPath = toArg === "" || to.pathname === "";
  812. let toPathname = isEmptyPath ? "/" : to.pathname;
  813. let from;
  814. if (toPathname == null) {
  815. from = locationPathname;
  816. } else {
  817. let routePathnameIndex = routePathnames.length - 1;
  818. if (!isPathRelative && toPathname.startsWith("..")) {
  819. let toSegments = toPathname.split("/");
  820. while (toSegments[0] === "..") {
  821. toSegments.shift();
  822. routePathnameIndex -= 1;
  823. }
  824. to.pathname = toSegments.join("/");
  825. }
  826. from = routePathnameIndex >= 0 ? routePathnames[routePathnameIndex] : "/";
  827. }
  828. let path = resolvePath(to, from);
  829. let hasExplicitTrailingSlash = toPathname && toPathname !== "/" && toPathname.endsWith("/");
  830. let hasCurrentTrailingSlash = (isEmptyPath || toPathname === ".") && locationPathname.endsWith("/");
  831. if (!path.pathname.endsWith("/") && (hasExplicitTrailingSlash || hasCurrentTrailingSlash)) {
  832. path.pathname += "/";
  833. }
  834. return path;
  835. }
  836. var joinPaths = (paths) => paths.join("/").replace(/\/\/+/g, "/");
  837. var normalizePathname = (pathname) => pathname.replace(/\/+$/, "").replace(/^\/*/, "/");
  838. var normalizeSearch = (search) => !search || search === "?" ? "" : search.startsWith("?") ? search : "?" + search;
  839. var normalizeHash = (hash) => !hash || hash === "#" ? "" : hash.startsWith("#") ? hash : "#" + hash;
  840. var json = function json2(data, init) {
  841. if (init === void 0) {
  842. init = {};
  843. }
  844. let responseInit = typeof init === "number" ? {
  845. status: init
  846. } : init;
  847. let headers = new Headers(responseInit.headers);
  848. if (!headers.has("Content-Type")) {
  849. headers.set("Content-Type", "application/json; charset=utf-8");
  850. }
  851. return new Response(JSON.stringify(data), _extends({}, responseInit, {
  852. headers
  853. }));
  854. };
  855. var AbortedDeferredError = class extends Error {
  856. };
  857. var DeferredData = class {
  858. constructor(data, responseInit) {
  859. this.pendingKeysSet = /* @__PURE__ */ new Set();
  860. this.subscribers = /* @__PURE__ */ new Set();
  861. this.deferredKeys = [];
  862. invariant(data && typeof data === "object" && !Array.isArray(data), "defer() only accepts plain objects");
  863. let reject;
  864. this.abortPromise = new Promise((_, r) => reject = r);
  865. this.controller = new AbortController();
  866. let onAbort = () => reject(new AbortedDeferredError("Deferred data aborted"));
  867. this.unlistenAbortSignal = () => this.controller.signal.removeEventListener("abort", onAbort);
  868. this.controller.signal.addEventListener("abort", onAbort);
  869. this.data = Object.entries(data).reduce((acc, _ref2) => {
  870. let [key, value] = _ref2;
  871. return Object.assign(acc, {
  872. [key]: this.trackPromise(key, value)
  873. });
  874. }, {});
  875. if (this.done) {
  876. this.unlistenAbortSignal();
  877. }
  878. this.init = responseInit;
  879. }
  880. trackPromise(key, value) {
  881. if (!(value instanceof Promise)) {
  882. return value;
  883. }
  884. this.deferredKeys.push(key);
  885. this.pendingKeysSet.add(key);
  886. let promise = Promise.race([value, this.abortPromise]).then((data) => this.onSettle(promise, key, void 0, data), (error) => this.onSettle(promise, key, error));
  887. promise.catch(() => {
  888. });
  889. Object.defineProperty(promise, "_tracked", {
  890. get: () => true
  891. });
  892. return promise;
  893. }
  894. onSettle(promise, key, error, data) {
  895. if (this.controller.signal.aborted && error instanceof AbortedDeferredError) {
  896. this.unlistenAbortSignal();
  897. Object.defineProperty(promise, "_error", {
  898. get: () => error
  899. });
  900. return Promise.reject(error);
  901. }
  902. this.pendingKeysSet.delete(key);
  903. if (this.done) {
  904. this.unlistenAbortSignal();
  905. }
  906. if (error === void 0 && data === void 0) {
  907. let undefinedError = new Error('Deferred data for key "' + key + '" resolved/rejected with `undefined`, you must resolve/reject with a value or `null`.');
  908. Object.defineProperty(promise, "_error", {
  909. get: () => undefinedError
  910. });
  911. this.emit(false, key);
  912. return Promise.reject(undefinedError);
  913. }
  914. if (data === void 0) {
  915. Object.defineProperty(promise, "_error", {
  916. get: () => error
  917. });
  918. this.emit(false, key);
  919. return Promise.reject(error);
  920. }
  921. Object.defineProperty(promise, "_data", {
  922. get: () => data
  923. });
  924. this.emit(false, key);
  925. return data;
  926. }
  927. emit(aborted, settledKey) {
  928. this.subscribers.forEach((subscriber) => subscriber(aborted, settledKey));
  929. }
  930. subscribe(fn) {
  931. this.subscribers.add(fn);
  932. return () => this.subscribers.delete(fn);
  933. }
  934. cancel() {
  935. this.controller.abort();
  936. this.pendingKeysSet.forEach((v, k) => this.pendingKeysSet.delete(k));
  937. this.emit(true);
  938. }
  939. async resolveData(signal) {
  940. let aborted = false;
  941. if (!this.done) {
  942. let onAbort = () => this.cancel();
  943. signal.addEventListener("abort", onAbort);
  944. aborted = await new Promise((resolve) => {
  945. this.subscribe((aborted2) => {
  946. signal.removeEventListener("abort", onAbort);
  947. if (aborted2 || this.done) {
  948. resolve(aborted2);
  949. }
  950. });
  951. });
  952. }
  953. return aborted;
  954. }
  955. get done() {
  956. return this.pendingKeysSet.size === 0;
  957. }
  958. get unwrappedData() {
  959. invariant(this.data !== null && this.done, "Can only unwrap data on initialized and settled deferreds");
  960. return Object.entries(this.data).reduce((acc, _ref3) => {
  961. let [key, value] = _ref3;
  962. return Object.assign(acc, {
  963. [key]: unwrapTrackedPromise(value)
  964. });
  965. }, {});
  966. }
  967. get pendingKeys() {
  968. return Array.from(this.pendingKeysSet);
  969. }
  970. };
  971. function isTrackedPromise(value) {
  972. return value instanceof Promise && value._tracked === true;
  973. }
  974. function unwrapTrackedPromise(value) {
  975. if (!isTrackedPromise(value)) {
  976. return value;
  977. }
  978. if (value._error) {
  979. throw value._error;
  980. }
  981. return value._data;
  982. }
  983. var defer = function defer2(data, init) {
  984. if (init === void 0) {
  985. init = {};
  986. }
  987. let responseInit = typeof init === "number" ? {
  988. status: init
  989. } : init;
  990. return new DeferredData(data, responseInit);
  991. };
  992. var redirect = function redirect2(url, init) {
  993. if (init === void 0) {
  994. init = 302;
  995. }
  996. let responseInit = init;
  997. if (typeof responseInit === "number") {
  998. responseInit = {
  999. status: responseInit
  1000. };
  1001. } else if (typeof responseInit.status === "undefined") {
  1002. responseInit.status = 302;
  1003. }
  1004. let headers = new Headers(responseInit.headers);
  1005. headers.set("Location", url);
  1006. return new Response(null, _extends({}, responseInit, {
  1007. headers
  1008. }));
  1009. };
  1010. var redirectDocument = (url, init) => {
  1011. let response = redirect(url, init);
  1012. response.headers.set("X-Remix-Reload-Document", "true");
  1013. return response;
  1014. };
  1015. var replace = (url, init) => {
  1016. let response = redirect(url, init);
  1017. response.headers.set("X-Remix-Replace", "true");
  1018. return response;
  1019. };
  1020. var ErrorResponseImpl = class {
  1021. constructor(status, statusText, data, internal) {
  1022. if (internal === void 0) {
  1023. internal = false;
  1024. }
  1025. this.status = status;
  1026. this.statusText = statusText || "";
  1027. this.internal = internal;
  1028. if (data instanceof Error) {
  1029. this.data = data.toString();
  1030. this.error = data;
  1031. } else {
  1032. this.data = data;
  1033. }
  1034. }
  1035. };
  1036. function isRouteErrorResponse(error) {
  1037. return error != null && typeof error.status === "number" && typeof error.statusText === "string" && typeof error.internal === "boolean" && "data" in error;
  1038. }
  1039. var validMutationMethodsArr = ["post", "put", "patch", "delete"];
  1040. var validMutationMethods = new Set(validMutationMethodsArr);
  1041. var validRequestMethodsArr = ["get", ...validMutationMethodsArr];
  1042. var validRequestMethods = new Set(validRequestMethodsArr);
  1043. var redirectStatusCodes = /* @__PURE__ */ new Set([301, 302, 303, 307, 308]);
  1044. var redirectPreserveMethodStatusCodes = /* @__PURE__ */ new Set([307, 308]);
  1045. var IDLE_NAVIGATION = {
  1046. state: "idle",
  1047. location: void 0,
  1048. formMethod: void 0,
  1049. formAction: void 0,
  1050. formEncType: void 0,
  1051. formData: void 0,
  1052. json: void 0,
  1053. text: void 0
  1054. };
  1055. var IDLE_FETCHER = {
  1056. state: "idle",
  1057. data: void 0,
  1058. formMethod: void 0,
  1059. formAction: void 0,
  1060. formEncType: void 0,
  1061. formData: void 0,
  1062. json: void 0,
  1063. text: void 0
  1064. };
  1065. var IDLE_BLOCKER = {
  1066. state: "unblocked",
  1067. proceed: void 0,
  1068. reset: void 0,
  1069. location: void 0
  1070. };
  1071. var ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i;
  1072. var defaultMapRouteProperties = (route) => ({
  1073. hasErrorBoundary: Boolean(route.hasErrorBoundary)
  1074. });
  1075. var TRANSITIONS_STORAGE_KEY = "remix-router-transitions";
  1076. function createRouter(init) {
  1077. const routerWindow = init.window ? init.window : typeof window !== "undefined" ? window : void 0;
  1078. const isBrowser2 = typeof routerWindow !== "undefined" && typeof routerWindow.document !== "undefined" && typeof routerWindow.document.createElement !== "undefined";
  1079. const isServer = !isBrowser2;
  1080. invariant(init.routes.length > 0, "You must provide a non-empty routes array to createRouter");
  1081. let mapRouteProperties2;
  1082. if (init.mapRouteProperties) {
  1083. mapRouteProperties2 = init.mapRouteProperties;
  1084. } else if (init.detectErrorBoundary) {
  1085. let detectErrorBoundary = init.detectErrorBoundary;
  1086. mapRouteProperties2 = (route) => ({
  1087. hasErrorBoundary: detectErrorBoundary(route)
  1088. });
  1089. } else {
  1090. mapRouteProperties2 = defaultMapRouteProperties;
  1091. }
  1092. let manifest = {};
  1093. let dataRoutes = convertRoutesToDataRoutes(init.routes, mapRouteProperties2, void 0, manifest);
  1094. let inFlightDataRoutes;
  1095. let basename = init.basename || "/";
  1096. let dataStrategyImpl = init.dataStrategy || defaultDataStrategy;
  1097. let patchRoutesOnNavigationImpl = init.patchRoutesOnNavigation;
  1098. let future = _extends({
  1099. v7_fetcherPersist: false,
  1100. v7_normalizeFormMethod: false,
  1101. v7_partialHydration: false,
  1102. v7_prependBasename: false,
  1103. v7_relativeSplatPath: false,
  1104. v7_skipActionErrorRevalidation: false
  1105. }, init.future);
  1106. let unlistenHistory = null;
  1107. let subscribers = /* @__PURE__ */ new Set();
  1108. let savedScrollPositions2 = null;
  1109. let getScrollRestorationKey = null;
  1110. let getScrollPosition = null;
  1111. let initialScrollRestored = init.hydrationData != null;
  1112. let initialMatches = matchRoutes(dataRoutes, init.history.location, basename);
  1113. let initialMatchesIsFOW = false;
  1114. let initialErrors = null;
  1115. if (initialMatches == null && !patchRoutesOnNavigationImpl) {
  1116. let error = getInternalRouterError(404, {
  1117. pathname: init.history.location.pathname
  1118. });
  1119. let {
  1120. matches,
  1121. route
  1122. } = getShortCircuitMatches(dataRoutes);
  1123. initialMatches = matches;
  1124. initialErrors = {
  1125. [route.id]: error
  1126. };
  1127. }
  1128. if (initialMatches && !init.hydrationData) {
  1129. let fogOfWar = checkFogOfWar(initialMatches, dataRoutes, init.history.location.pathname);
  1130. if (fogOfWar.active) {
  1131. initialMatches = null;
  1132. }
  1133. }
  1134. let initialized;
  1135. if (!initialMatches) {
  1136. initialized = false;
  1137. initialMatches = [];
  1138. if (future.v7_partialHydration) {
  1139. let fogOfWar = checkFogOfWar(null, dataRoutes, init.history.location.pathname);
  1140. if (fogOfWar.active && fogOfWar.matches) {
  1141. initialMatchesIsFOW = true;
  1142. initialMatches = fogOfWar.matches;
  1143. }
  1144. }
  1145. } else if (initialMatches.some((m) => m.route.lazy)) {
  1146. initialized = false;
  1147. } else if (!initialMatches.some((m) => m.route.loader)) {
  1148. initialized = true;
  1149. } else if (future.v7_partialHydration) {
  1150. let loaderData = init.hydrationData ? init.hydrationData.loaderData : null;
  1151. let errors = init.hydrationData ? init.hydrationData.errors : null;
  1152. if (errors) {
  1153. let idx = initialMatches.findIndex((m) => errors[m.route.id] !== void 0);
  1154. initialized = initialMatches.slice(0, idx + 1).every((m) => !shouldLoadRouteOnHydration(m.route, loaderData, errors));
  1155. } else {
  1156. initialized = initialMatches.every((m) => !shouldLoadRouteOnHydration(m.route, loaderData, errors));
  1157. }
  1158. } else {
  1159. initialized = init.hydrationData != null;
  1160. }
  1161. let router;
  1162. let state = {
  1163. historyAction: init.history.action,
  1164. location: init.history.location,
  1165. matches: initialMatches,
  1166. initialized,
  1167. navigation: IDLE_NAVIGATION,
  1168. // Don't restore on initial updateState() if we were SSR'd
  1169. restoreScrollPosition: init.hydrationData != null ? false : null,
  1170. preventScrollReset: false,
  1171. revalidation: "idle",
  1172. loaderData: init.hydrationData && init.hydrationData.loaderData || {},
  1173. actionData: init.hydrationData && init.hydrationData.actionData || null,
  1174. errors: init.hydrationData && init.hydrationData.errors || initialErrors,
  1175. fetchers: /* @__PURE__ */ new Map(),
  1176. blockers: /* @__PURE__ */ new Map()
  1177. };
  1178. let pendingAction = Action.Pop;
  1179. let pendingPreventScrollReset = false;
  1180. let pendingNavigationController;
  1181. let pendingViewTransitionEnabled = false;
  1182. let appliedViewTransitions = /* @__PURE__ */ new Map();
  1183. let removePageHideEventListener = null;
  1184. let isUninterruptedRevalidation = false;
  1185. let isRevalidationRequired = false;
  1186. let cancelledDeferredRoutes = [];
  1187. let cancelledFetcherLoads = /* @__PURE__ */ new Set();
  1188. let fetchControllers = /* @__PURE__ */ new Map();
  1189. let incrementingLoadId = 0;
  1190. let pendingNavigationLoadId = -1;
  1191. let fetchReloadIds = /* @__PURE__ */ new Map();
  1192. let fetchRedirectIds = /* @__PURE__ */ new Set();
  1193. let fetchLoadMatches = /* @__PURE__ */ new Map();
  1194. let activeFetchers = /* @__PURE__ */ new Map();
  1195. let deletedFetchers = /* @__PURE__ */ new Set();
  1196. let activeDeferreds = /* @__PURE__ */ new Map();
  1197. let blockerFunctions = /* @__PURE__ */ new Map();
  1198. let unblockBlockerHistoryUpdate = void 0;
  1199. function initialize() {
  1200. unlistenHistory = init.history.listen((_ref) => {
  1201. let {
  1202. action: historyAction,
  1203. location,
  1204. delta
  1205. } = _ref;
  1206. if (unblockBlockerHistoryUpdate) {
  1207. unblockBlockerHistoryUpdate();
  1208. unblockBlockerHistoryUpdate = void 0;
  1209. return;
  1210. }
  1211. warning(blockerFunctions.size === 0 || delta != null, "You are trying to use a blocker on a POP navigation to a location that was not created by @remix-run/router. This will fail silently in production. This can happen if you are navigating outside the router via `window.history.pushState`/`window.location.hash` instead of using router navigation APIs. This can also happen if you are using createHashRouter and the user manually changes the URL.");
  1212. let blockerKey = shouldBlockNavigation({
  1213. currentLocation: state.location,
  1214. nextLocation: location,
  1215. historyAction
  1216. });
  1217. if (blockerKey && delta != null) {
  1218. let nextHistoryUpdatePromise = new Promise((resolve) => {
  1219. unblockBlockerHistoryUpdate = resolve;
  1220. });
  1221. init.history.go(delta * -1);
  1222. updateBlocker(blockerKey, {
  1223. state: "blocked",
  1224. location,
  1225. proceed() {
  1226. updateBlocker(blockerKey, {
  1227. state: "proceeding",
  1228. proceed: void 0,
  1229. reset: void 0,
  1230. location
  1231. });
  1232. nextHistoryUpdatePromise.then(() => init.history.go(delta));
  1233. },
  1234. reset() {
  1235. let blockers = new Map(state.blockers);
  1236. blockers.set(blockerKey, IDLE_BLOCKER);
  1237. updateState({
  1238. blockers
  1239. });
  1240. }
  1241. });
  1242. return;
  1243. }
  1244. return startNavigation(historyAction, location);
  1245. });
  1246. if (isBrowser2) {
  1247. restoreAppliedTransitions(routerWindow, appliedViewTransitions);
  1248. let _saveAppliedTransitions = () => persistAppliedTransitions(routerWindow, appliedViewTransitions);
  1249. routerWindow.addEventListener("pagehide", _saveAppliedTransitions);
  1250. removePageHideEventListener = () => routerWindow.removeEventListener("pagehide", _saveAppliedTransitions);
  1251. }
  1252. if (!state.initialized) {
  1253. startNavigation(Action.Pop, state.location, {
  1254. initialHydration: true
  1255. });
  1256. }
  1257. return router;
  1258. }
  1259. function dispose() {
  1260. if (unlistenHistory) {
  1261. unlistenHistory();
  1262. }
  1263. if (removePageHideEventListener) {
  1264. removePageHideEventListener();
  1265. }
  1266. subscribers.clear();
  1267. pendingNavigationController && pendingNavigationController.abort();
  1268. state.fetchers.forEach((_, key) => deleteFetcher(key));
  1269. state.blockers.forEach((_, key) => deleteBlocker(key));
  1270. }
  1271. function subscribe(fn) {
  1272. subscribers.add(fn);
  1273. return () => subscribers.delete(fn);
  1274. }
  1275. function updateState(newState, opts) {
  1276. if (opts === void 0) {
  1277. opts = {};
  1278. }
  1279. state = _extends({}, state, newState);
  1280. let completedFetchers = [];
  1281. let deletedFetchersKeys = [];
  1282. if (future.v7_fetcherPersist) {
  1283. state.fetchers.forEach((fetcher, key) => {
  1284. if (fetcher.state === "idle") {
  1285. if (deletedFetchers.has(key)) {
  1286. deletedFetchersKeys.push(key);
  1287. } else {
  1288. completedFetchers.push(key);
  1289. }
  1290. }
  1291. });
  1292. }
  1293. deletedFetchers.forEach((key) => {
  1294. if (!state.fetchers.has(key) && !fetchControllers.has(key)) {
  1295. deletedFetchersKeys.push(key);
  1296. }
  1297. });
  1298. [...subscribers].forEach((subscriber) => subscriber(state, {
  1299. deletedFetchers: deletedFetchersKeys,
  1300. viewTransitionOpts: opts.viewTransitionOpts,
  1301. flushSync: opts.flushSync === true
  1302. }));
  1303. if (future.v7_fetcherPersist) {
  1304. completedFetchers.forEach((key) => state.fetchers.delete(key));
  1305. deletedFetchersKeys.forEach((key) => deleteFetcher(key));
  1306. } else {
  1307. deletedFetchersKeys.forEach((key) => deletedFetchers.delete(key));
  1308. }
  1309. }
  1310. function completeNavigation(location, newState, _temp) {
  1311. var _location$state, _location$state2;
  1312. let {
  1313. flushSync
  1314. } = _temp === void 0 ? {} : _temp;
  1315. let isActionReload = state.actionData != null && state.navigation.formMethod != null && isMutationMethod(state.navigation.formMethod) && state.navigation.state === "loading" && ((_location$state = location.state) == null ? void 0 : _location$state._isRedirect) !== true;
  1316. let actionData;
  1317. if (newState.actionData) {
  1318. if (Object.keys(newState.actionData).length > 0) {
  1319. actionData = newState.actionData;
  1320. } else {
  1321. actionData = null;
  1322. }
  1323. } else if (isActionReload) {
  1324. actionData = state.actionData;
  1325. } else {
  1326. actionData = null;
  1327. }
  1328. let loaderData = newState.loaderData ? mergeLoaderData(state.loaderData, newState.loaderData, newState.matches || [], newState.errors) : state.loaderData;
  1329. let blockers = state.blockers;
  1330. if (blockers.size > 0) {
  1331. blockers = new Map(blockers);
  1332. blockers.forEach((_, k) => blockers.set(k, IDLE_BLOCKER));
  1333. }
  1334. let preventScrollReset = pendingPreventScrollReset === true || state.navigation.formMethod != null && isMutationMethod(state.navigation.formMethod) && ((_location$state2 = location.state) == null ? void 0 : _location$state2._isRedirect) !== true;
  1335. if (inFlightDataRoutes) {
  1336. dataRoutes = inFlightDataRoutes;
  1337. inFlightDataRoutes = void 0;
  1338. }
  1339. if (isUninterruptedRevalidation) ;
  1340. else if (pendingAction === Action.Pop) ;
  1341. else if (pendingAction === Action.Push) {
  1342. init.history.push(location, location.state);
  1343. } else if (pendingAction === Action.Replace) {
  1344. init.history.replace(location, location.state);
  1345. }
  1346. let viewTransitionOpts;
  1347. if (pendingAction === Action.Pop) {
  1348. let priorPaths = appliedViewTransitions.get(state.location.pathname);
  1349. if (priorPaths && priorPaths.has(location.pathname)) {
  1350. viewTransitionOpts = {
  1351. currentLocation: state.location,
  1352. nextLocation: location
  1353. };
  1354. } else if (appliedViewTransitions.has(location.pathname)) {
  1355. viewTransitionOpts = {
  1356. currentLocation: location,
  1357. nextLocation: state.location
  1358. };
  1359. }
  1360. } else if (pendingViewTransitionEnabled) {
  1361. let toPaths = appliedViewTransitions.get(state.location.pathname);
  1362. if (toPaths) {
  1363. toPaths.add(location.pathname);
  1364. } else {
  1365. toPaths = /* @__PURE__ */ new Set([location.pathname]);
  1366. appliedViewTransitions.set(state.location.pathname, toPaths);
  1367. }
  1368. viewTransitionOpts = {
  1369. currentLocation: state.location,
  1370. nextLocation: location
  1371. };
  1372. }
  1373. updateState(_extends({}, newState, {
  1374. actionData,
  1375. loaderData,
  1376. historyAction: pendingAction,
  1377. location,
  1378. initialized: true,
  1379. navigation: IDLE_NAVIGATION,
  1380. revalidation: "idle",
  1381. restoreScrollPosition: getSavedScrollPosition(location, newState.matches || state.matches),
  1382. preventScrollReset,
  1383. blockers
  1384. }), {
  1385. viewTransitionOpts,
  1386. flushSync: flushSync === true
  1387. });
  1388. pendingAction = Action.Pop;
  1389. pendingPreventScrollReset = false;
  1390. pendingViewTransitionEnabled = false;
  1391. isUninterruptedRevalidation = false;
  1392. isRevalidationRequired = false;
  1393. cancelledDeferredRoutes = [];
  1394. }
  1395. async function navigate(to, opts) {
  1396. if (typeof to === "number") {
  1397. init.history.go(to);
  1398. return;
  1399. }
  1400. let normalizedPath = normalizeTo(state.location, state.matches, basename, future.v7_prependBasename, to, future.v7_relativeSplatPath, opts == null ? void 0 : opts.fromRouteId, opts == null ? void 0 : opts.relative);
  1401. let {
  1402. path,
  1403. submission,
  1404. error
  1405. } = normalizeNavigateOptions(future.v7_normalizeFormMethod, false, normalizedPath, opts);
  1406. let currentLocation = state.location;
  1407. let nextLocation = createLocation(state.location, path, opts && opts.state);
  1408. nextLocation = _extends({}, nextLocation, init.history.encodeLocation(nextLocation));
  1409. let userReplace = opts && opts.replace != null ? opts.replace : void 0;
  1410. let historyAction = Action.Push;
  1411. if (userReplace === true) {
  1412. historyAction = Action.Replace;
  1413. } else if (userReplace === false) ;
  1414. else if (submission != null && isMutationMethod(submission.formMethod) && submission.formAction === state.location.pathname + state.location.search) {
  1415. historyAction = Action.Replace;
  1416. }
  1417. let preventScrollReset = opts && "preventScrollReset" in opts ? opts.preventScrollReset === true : void 0;
  1418. let flushSync = (opts && opts.flushSync) === true;
  1419. let blockerKey = shouldBlockNavigation({
  1420. currentLocation,
  1421. nextLocation,
  1422. historyAction
  1423. });
  1424. if (blockerKey) {
  1425. updateBlocker(blockerKey, {
  1426. state: "blocked",
  1427. location: nextLocation,
  1428. proceed() {
  1429. updateBlocker(blockerKey, {
  1430. state: "proceeding",
  1431. proceed: void 0,
  1432. reset: void 0,
  1433. location: nextLocation
  1434. });
  1435. navigate(to, opts);
  1436. },
  1437. reset() {
  1438. let blockers = new Map(state.blockers);
  1439. blockers.set(blockerKey, IDLE_BLOCKER);
  1440. updateState({
  1441. blockers
  1442. });
  1443. }
  1444. });
  1445. return;
  1446. }
  1447. return await startNavigation(historyAction, nextLocation, {
  1448. submission,
  1449. // Send through the formData serialization error if we have one so we can
  1450. // render at the right error boundary after we match routes
  1451. pendingError: error,
  1452. preventScrollReset,
  1453. replace: opts && opts.replace,
  1454. enableViewTransition: opts && opts.viewTransition,
  1455. flushSync
  1456. });
  1457. }
  1458. function revalidate() {
  1459. interruptActiveLoads();
  1460. updateState({
  1461. revalidation: "loading"
  1462. });
  1463. if (state.navigation.state === "submitting") {
  1464. return;
  1465. }
  1466. if (state.navigation.state === "idle") {
  1467. startNavigation(state.historyAction, state.location, {
  1468. startUninterruptedRevalidation: true
  1469. });
  1470. return;
  1471. }
  1472. startNavigation(pendingAction || state.historyAction, state.navigation.location, {
  1473. overrideNavigation: state.navigation,
  1474. // Proxy through any rending view transition
  1475. enableViewTransition: pendingViewTransitionEnabled === true
  1476. });
  1477. }
  1478. async function startNavigation(historyAction, location, opts) {
  1479. pendingNavigationController && pendingNavigationController.abort();
  1480. pendingNavigationController = null;
  1481. pendingAction = historyAction;
  1482. isUninterruptedRevalidation = (opts && opts.startUninterruptedRevalidation) === true;
  1483. saveScrollPosition(state.location, state.matches);
  1484. pendingPreventScrollReset = (opts && opts.preventScrollReset) === true;
  1485. pendingViewTransitionEnabled = (opts && opts.enableViewTransition) === true;
  1486. let routesToUse = inFlightDataRoutes || dataRoutes;
  1487. let loadingNavigation = opts && opts.overrideNavigation;
  1488. let matches = opts != null && opts.initialHydration && state.matches && state.matches.length > 0 && !initialMatchesIsFOW ? (
  1489. // `matchRoutes()` has already been called if we're in here via `router.initialize()`
  1490. state.matches
  1491. ) : matchRoutes(routesToUse, location, basename);
  1492. let flushSync = (opts && opts.flushSync) === true;
  1493. if (matches && state.initialized && !isRevalidationRequired && isHashChangeOnly(state.location, location) && !(opts && opts.submission && isMutationMethod(opts.submission.formMethod))) {
  1494. completeNavigation(location, {
  1495. matches
  1496. }, {
  1497. flushSync
  1498. });
  1499. return;
  1500. }
  1501. let fogOfWar = checkFogOfWar(matches, routesToUse, location.pathname);
  1502. if (fogOfWar.active && fogOfWar.matches) {
  1503. matches = fogOfWar.matches;
  1504. }
  1505. if (!matches) {
  1506. let {
  1507. error,
  1508. notFoundMatches,
  1509. route
  1510. } = handleNavigational404(location.pathname);
  1511. completeNavigation(location, {
  1512. matches: notFoundMatches,
  1513. loaderData: {},
  1514. errors: {
  1515. [route.id]: error
  1516. }
  1517. }, {
  1518. flushSync
  1519. });
  1520. return;
  1521. }
  1522. pendingNavigationController = new AbortController();
  1523. let request = createClientSideRequest(init.history, location, pendingNavigationController.signal, opts && opts.submission);
  1524. let pendingActionResult;
  1525. if (opts && opts.pendingError) {
  1526. pendingActionResult = [findNearestBoundary(matches).route.id, {
  1527. type: ResultType.error,
  1528. error: opts.pendingError
  1529. }];
  1530. } else if (opts && opts.submission && isMutationMethod(opts.submission.formMethod)) {
  1531. let actionResult = await handleAction(request, location, opts.submission, matches, fogOfWar.active, {
  1532. replace: opts.replace,
  1533. flushSync
  1534. });
  1535. if (actionResult.shortCircuited) {
  1536. return;
  1537. }
  1538. if (actionResult.pendingActionResult) {
  1539. let [routeId, result] = actionResult.pendingActionResult;
  1540. if (isErrorResult(result) && isRouteErrorResponse(result.error) && result.error.status === 404) {
  1541. pendingNavigationController = null;
  1542. completeNavigation(location, {
  1543. matches: actionResult.matches,
  1544. loaderData: {},
  1545. errors: {
  1546. [routeId]: result.error
  1547. }
  1548. });
  1549. return;
  1550. }
  1551. }
  1552. matches = actionResult.matches || matches;
  1553. pendingActionResult = actionResult.pendingActionResult;
  1554. loadingNavigation = getLoadingNavigation(location, opts.submission);
  1555. flushSync = false;
  1556. fogOfWar.active = false;
  1557. request = createClientSideRequest(init.history, request.url, request.signal);
  1558. }
  1559. let {
  1560. shortCircuited,
  1561. matches: updatedMatches,
  1562. loaderData,
  1563. errors
  1564. } = await handleLoaders(request, location, matches, fogOfWar.active, loadingNavigation, opts && opts.submission, opts && opts.fetcherSubmission, opts && opts.replace, opts && opts.initialHydration === true, flushSync, pendingActionResult);
  1565. if (shortCircuited) {
  1566. return;
  1567. }
  1568. pendingNavigationController = null;
  1569. completeNavigation(location, _extends({
  1570. matches: updatedMatches || matches
  1571. }, getActionDataForCommit(pendingActionResult), {
  1572. loaderData,
  1573. errors
  1574. }));
  1575. }
  1576. async function handleAction(request, location, submission, matches, isFogOfWar, opts) {
  1577. if (opts === void 0) {
  1578. opts = {};
  1579. }
  1580. interruptActiveLoads();
  1581. let navigation = getSubmittingNavigation(location, submission);
  1582. updateState({
  1583. navigation
  1584. }, {
  1585. flushSync: opts.flushSync === true
  1586. });
  1587. if (isFogOfWar) {
  1588. let discoverResult = await discoverRoutes(matches, location.pathname, request.signal);
  1589. if (discoverResult.type === "aborted") {
  1590. return {
  1591. shortCircuited: true
  1592. };
  1593. } else if (discoverResult.type === "error") {
  1594. let boundaryId = findNearestBoundary(discoverResult.partialMatches).route.id;
  1595. return {
  1596. matches: discoverResult.partialMatches,
  1597. pendingActionResult: [boundaryId, {
  1598. type: ResultType.error,
  1599. error: discoverResult.error
  1600. }]
  1601. };
  1602. } else if (!discoverResult.matches) {
  1603. let {
  1604. notFoundMatches,
  1605. error,
  1606. route
  1607. } = handleNavigational404(location.pathname);
  1608. return {
  1609. matches: notFoundMatches,
  1610. pendingActionResult: [route.id, {
  1611. type: ResultType.error,
  1612. error
  1613. }]
  1614. };
  1615. } else {
  1616. matches = discoverResult.matches;
  1617. }
  1618. }
  1619. let result;
  1620. let actionMatch = getTargetMatch(matches, location);
  1621. if (!actionMatch.route.action && !actionMatch.route.lazy) {
  1622. result = {
  1623. type: ResultType.error,
  1624. error: getInternalRouterError(405, {
  1625. method: request.method,
  1626. pathname: location.pathname,
  1627. routeId: actionMatch.route.id
  1628. })
  1629. };
  1630. } else {
  1631. let results = await callDataStrategy("action", state, request, [actionMatch], matches, null);
  1632. result = results[actionMatch.route.id];
  1633. if (request.signal.aborted) {
  1634. return {
  1635. shortCircuited: true
  1636. };
  1637. }
  1638. }
  1639. if (isRedirectResult(result)) {
  1640. let replace2;
  1641. if (opts && opts.replace != null) {
  1642. replace2 = opts.replace;
  1643. } else {
  1644. let location2 = normalizeRedirectLocation(result.response.headers.get("Location"), new URL(request.url), basename, init.history);
  1645. replace2 = location2 === state.location.pathname + state.location.search;
  1646. }
  1647. await startRedirectNavigation(request, result, true, {
  1648. submission,
  1649. replace: replace2
  1650. });
  1651. return {
  1652. shortCircuited: true
  1653. };
  1654. }
  1655. if (isDeferredResult(result)) {
  1656. throw getInternalRouterError(400, {
  1657. type: "defer-action"
  1658. });
  1659. }
  1660. if (isErrorResult(result)) {
  1661. let boundaryMatch = findNearestBoundary(matches, actionMatch.route.id);
  1662. if ((opts && opts.replace) !== true) {
  1663. pendingAction = Action.Push;
  1664. }
  1665. return {
  1666. matches,
  1667. pendingActionResult: [boundaryMatch.route.id, result]
  1668. };
  1669. }
  1670. return {
  1671. matches,
  1672. pendingActionResult: [actionMatch.route.id, result]
  1673. };
  1674. }
  1675. async function handleLoaders(request, location, matches, isFogOfWar, overrideNavigation, submission, fetcherSubmission, replace2, initialHydration, flushSync, pendingActionResult) {
  1676. let loadingNavigation = overrideNavigation || getLoadingNavigation(location, submission);
  1677. let activeSubmission = submission || fetcherSubmission || getSubmissionFromNavigation(loadingNavigation);
  1678. let shouldUpdateNavigationState = !isUninterruptedRevalidation && (!future.v7_partialHydration || !initialHydration);
  1679. if (isFogOfWar) {
  1680. if (shouldUpdateNavigationState) {
  1681. let actionData = getUpdatedActionData(pendingActionResult);
  1682. updateState(_extends({
  1683. navigation: loadingNavigation
  1684. }, actionData !== void 0 ? {
  1685. actionData
  1686. } : {}), {
  1687. flushSync
  1688. });
  1689. }
  1690. let discoverResult = await discoverRoutes(matches, location.pathname, request.signal);
  1691. if (discoverResult.type === "aborted") {
  1692. return {
  1693. shortCircuited: true
  1694. };
  1695. } else if (discoverResult.type === "error") {
  1696. let boundaryId = findNearestBoundary(discoverResult.partialMatches).route.id;
  1697. return {
  1698. matches: discoverResult.partialMatches,
  1699. loaderData: {},
  1700. errors: {
  1701. [boundaryId]: discoverResult.error
  1702. }
  1703. };
  1704. } else if (!discoverResult.matches) {
  1705. let {
  1706. error,
  1707. notFoundMatches,
  1708. route
  1709. } = handleNavigational404(location.pathname);
  1710. return {
  1711. matches: notFoundMatches,
  1712. loaderData: {},
  1713. errors: {
  1714. [route.id]: error
  1715. }
  1716. };
  1717. } else {
  1718. matches = discoverResult.matches;
  1719. }
  1720. }
  1721. let routesToUse = inFlightDataRoutes || dataRoutes;
  1722. let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(init.history, state, matches, activeSubmission, location, future.v7_partialHydration && initialHydration === true, future.v7_skipActionErrorRevalidation, isRevalidationRequired, cancelledDeferredRoutes, cancelledFetcherLoads, deletedFetchers, fetchLoadMatches, fetchRedirectIds, routesToUse, basename, pendingActionResult);
  1723. cancelActiveDeferreds((routeId) => !(matches && matches.some((m) => m.route.id === routeId)) || matchesToLoad && matchesToLoad.some((m) => m.route.id === routeId));
  1724. pendingNavigationLoadId = ++incrementingLoadId;
  1725. if (matchesToLoad.length === 0 && revalidatingFetchers.length === 0) {
  1726. let updatedFetchers2 = markFetchRedirectsDone();
  1727. completeNavigation(location, _extends({
  1728. matches,
  1729. loaderData: {},
  1730. // Commit pending error if we're short circuiting
  1731. errors: pendingActionResult && isErrorResult(pendingActionResult[1]) ? {
  1732. [pendingActionResult[0]]: pendingActionResult[1].error
  1733. } : null
  1734. }, getActionDataForCommit(pendingActionResult), updatedFetchers2 ? {
  1735. fetchers: new Map(state.fetchers)
  1736. } : {}), {
  1737. flushSync
  1738. });
  1739. return {
  1740. shortCircuited: true
  1741. };
  1742. }
  1743. if (shouldUpdateNavigationState) {
  1744. let updates = {};
  1745. if (!isFogOfWar) {
  1746. updates.navigation = loadingNavigation;
  1747. let actionData = getUpdatedActionData(pendingActionResult);
  1748. if (actionData !== void 0) {
  1749. updates.actionData = actionData;
  1750. }
  1751. }
  1752. if (revalidatingFetchers.length > 0) {
  1753. updates.fetchers = getUpdatedRevalidatingFetchers(revalidatingFetchers);
  1754. }
  1755. updateState(updates, {
  1756. flushSync
  1757. });
  1758. }
  1759. revalidatingFetchers.forEach((rf) => {
  1760. abortFetcher(rf.key);
  1761. if (rf.controller) {
  1762. fetchControllers.set(rf.key, rf.controller);
  1763. }
  1764. });
  1765. let abortPendingFetchRevalidations = () => revalidatingFetchers.forEach((f) => abortFetcher(f.key));
  1766. if (pendingNavigationController) {
  1767. pendingNavigationController.signal.addEventListener("abort", abortPendingFetchRevalidations);
  1768. }
  1769. let {
  1770. loaderResults,
  1771. fetcherResults
  1772. } = await callLoadersAndMaybeResolveData(state, matches, matchesToLoad, revalidatingFetchers, request);
  1773. if (request.signal.aborted) {
  1774. return {
  1775. shortCircuited: true
  1776. };
  1777. }
  1778. if (pendingNavigationController) {
  1779. pendingNavigationController.signal.removeEventListener("abort", abortPendingFetchRevalidations);
  1780. }
  1781. revalidatingFetchers.forEach((rf) => fetchControllers.delete(rf.key));
  1782. let redirect3 = findRedirect(loaderResults);
  1783. if (redirect3) {
  1784. await startRedirectNavigation(request, redirect3.result, true, {
  1785. replace: replace2
  1786. });
  1787. return {
  1788. shortCircuited: true
  1789. };
  1790. }
  1791. redirect3 = findRedirect(fetcherResults);
  1792. if (redirect3) {
  1793. fetchRedirectIds.add(redirect3.key);
  1794. await startRedirectNavigation(request, redirect3.result, true, {
  1795. replace: replace2
  1796. });
  1797. return {
  1798. shortCircuited: true
  1799. };
  1800. }
  1801. let {
  1802. loaderData,
  1803. errors
  1804. } = processLoaderData(state, matches, loaderResults, pendingActionResult, revalidatingFetchers, fetcherResults, activeDeferreds);
  1805. activeDeferreds.forEach((deferredData, routeId) => {
  1806. deferredData.subscribe((aborted) => {
  1807. if (aborted || deferredData.done) {
  1808. activeDeferreds.delete(routeId);
  1809. }
  1810. });
  1811. });
  1812. if (future.v7_partialHydration && initialHydration && state.errors) {
  1813. errors = _extends({}, state.errors, errors);
  1814. }
  1815. let updatedFetchers = markFetchRedirectsDone();
  1816. let didAbortFetchLoads = abortStaleFetchLoads(pendingNavigationLoadId);
  1817. let shouldUpdateFetchers = updatedFetchers || didAbortFetchLoads || revalidatingFetchers.length > 0;
  1818. return _extends({
  1819. matches,
  1820. loaderData,
  1821. errors
  1822. }, shouldUpdateFetchers ? {
  1823. fetchers: new Map(state.fetchers)
  1824. } : {});
  1825. }
  1826. function getUpdatedActionData(pendingActionResult) {
  1827. if (pendingActionResult && !isErrorResult(pendingActionResult[1])) {
  1828. return {
  1829. [pendingActionResult[0]]: pendingActionResult[1].data
  1830. };
  1831. } else if (state.actionData) {
  1832. if (Object.keys(state.actionData).length === 0) {
  1833. return null;
  1834. } else {
  1835. return state.actionData;
  1836. }
  1837. }
  1838. }
  1839. function getUpdatedRevalidatingFetchers(revalidatingFetchers) {
  1840. revalidatingFetchers.forEach((rf) => {
  1841. let fetcher = state.fetchers.get(rf.key);
  1842. let revalidatingFetcher = getLoadingFetcher(void 0, fetcher ? fetcher.data : void 0);
  1843. state.fetchers.set(rf.key, revalidatingFetcher);
  1844. });
  1845. return new Map(state.fetchers);
  1846. }
  1847. function fetch(key, routeId, href, opts) {
  1848. if (isServer) {
  1849. throw new Error("router.fetch() was called during the server render, but it shouldn't be. You are likely calling a useFetcher() method in the body of your component. Try moving it to a useEffect or a callback.");
  1850. }
  1851. abortFetcher(key);
  1852. let flushSync = (opts && opts.flushSync) === true;
  1853. let routesToUse = inFlightDataRoutes || dataRoutes;
  1854. let normalizedPath = normalizeTo(state.location, state.matches, basename, future.v7_prependBasename, href, future.v7_relativeSplatPath, routeId, opts == null ? void 0 : opts.relative);
  1855. let matches = matchRoutes(routesToUse, normalizedPath, basename);
  1856. let fogOfWar = checkFogOfWar(matches, routesToUse, normalizedPath);
  1857. if (fogOfWar.active && fogOfWar.matches) {
  1858. matches = fogOfWar.matches;
  1859. }
  1860. if (!matches) {
  1861. setFetcherError(key, routeId, getInternalRouterError(404, {
  1862. pathname: normalizedPath
  1863. }), {
  1864. flushSync
  1865. });
  1866. return;
  1867. }
  1868. let {
  1869. path,
  1870. submission,
  1871. error
  1872. } = normalizeNavigateOptions(future.v7_normalizeFormMethod, true, normalizedPath, opts);
  1873. if (error) {
  1874. setFetcherError(key, routeId, error, {
  1875. flushSync
  1876. });
  1877. return;
  1878. }
  1879. let match = getTargetMatch(matches, path);
  1880. let preventScrollReset = (opts && opts.preventScrollReset) === true;
  1881. if (submission && isMutationMethod(submission.formMethod)) {
  1882. handleFetcherAction(key, routeId, path, match, matches, fogOfWar.active, flushSync, preventScrollReset, submission);
  1883. return;
  1884. }
  1885. fetchLoadMatches.set(key, {
  1886. routeId,
  1887. path
  1888. });
  1889. handleFetcherLoader(key, routeId, path, match, matches, fogOfWar.active, flushSync, preventScrollReset, submission);
  1890. }
  1891. async function handleFetcherAction(key, routeId, path, match, requestMatches, isFogOfWar, flushSync, preventScrollReset, submission) {
  1892. interruptActiveLoads();
  1893. fetchLoadMatches.delete(key);
  1894. function detectAndHandle405Error(m) {
  1895. if (!m.route.action && !m.route.lazy) {
  1896. let error = getInternalRouterError(405, {
  1897. method: submission.formMethod,
  1898. pathname: path,
  1899. routeId
  1900. });
  1901. setFetcherError(key, routeId, error, {
  1902. flushSync
  1903. });
  1904. return true;
  1905. }
  1906. return false;
  1907. }
  1908. if (!isFogOfWar && detectAndHandle405Error(match)) {
  1909. return;
  1910. }
  1911. let existingFetcher = state.fetchers.get(key);
  1912. updateFetcherState(key, getSubmittingFetcher(submission, existingFetcher), {
  1913. flushSync
  1914. });
  1915. let abortController = new AbortController();
  1916. let fetchRequest = createClientSideRequest(init.history, path, abortController.signal, submission);
  1917. if (isFogOfWar) {
  1918. let discoverResult = await discoverRoutes(requestMatches, new URL(fetchRequest.url).pathname, fetchRequest.signal, key);
  1919. if (discoverResult.type === "aborted") {
  1920. return;
  1921. } else if (discoverResult.type === "error") {
  1922. setFetcherError(key, routeId, discoverResult.error, {
  1923. flushSync
  1924. });
  1925. return;
  1926. } else if (!discoverResult.matches) {
  1927. setFetcherError(key, routeId, getInternalRouterError(404, {
  1928. pathname: path
  1929. }), {
  1930. flushSync
  1931. });
  1932. return;
  1933. } else {
  1934. requestMatches = discoverResult.matches;
  1935. match = getTargetMatch(requestMatches, path);
  1936. if (detectAndHandle405Error(match)) {
  1937. return;
  1938. }
  1939. }
  1940. }
  1941. fetchControllers.set(key, abortController);
  1942. let originatingLoadId = incrementingLoadId;
  1943. let actionResults = await callDataStrategy("action", state, fetchRequest, [match], requestMatches, key);
  1944. let actionResult = actionResults[match.route.id];
  1945. if (fetchRequest.signal.aborted) {
  1946. if (fetchControllers.get(key) === abortController) {
  1947. fetchControllers.delete(key);
  1948. }
  1949. return;
  1950. }
  1951. if (future.v7_fetcherPersist && deletedFetchers.has(key)) {
  1952. if (isRedirectResult(actionResult) || isErrorResult(actionResult)) {
  1953. updateFetcherState(key, getDoneFetcher(void 0));
  1954. return;
  1955. }
  1956. } else {
  1957. if (isRedirectResult(actionResult)) {
  1958. fetchControllers.delete(key);
  1959. if (pendingNavigationLoadId > originatingLoadId) {
  1960. updateFetcherState(key, getDoneFetcher(void 0));
  1961. return;
  1962. } else {
  1963. fetchRedirectIds.add(key);
  1964. updateFetcherState(key, getLoadingFetcher(submission));
  1965. return startRedirectNavigation(fetchRequest, actionResult, false, {
  1966. fetcherSubmission: submission,
  1967. preventScrollReset
  1968. });
  1969. }
  1970. }
  1971. if (isErrorResult(actionResult)) {
  1972. setFetcherError(key, routeId, actionResult.error);
  1973. return;
  1974. }
  1975. }
  1976. if (isDeferredResult(actionResult)) {
  1977. throw getInternalRouterError(400, {
  1978. type: "defer-action"
  1979. });
  1980. }
  1981. let nextLocation = state.navigation.location || state.location;
  1982. let revalidationRequest = createClientSideRequest(init.history, nextLocation, abortController.signal);
  1983. let routesToUse = inFlightDataRoutes || dataRoutes;
  1984. let matches = state.navigation.state !== "idle" ? matchRoutes(routesToUse, state.navigation.location, basename) : state.matches;
  1985. invariant(matches, "Didn't find any matches after fetcher action");
  1986. let loadId = ++incrementingLoadId;
  1987. fetchReloadIds.set(key, loadId);
  1988. let loadFetcher = getLoadingFetcher(submission, actionResult.data);
  1989. state.fetchers.set(key, loadFetcher);
  1990. let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(init.history, state, matches, submission, nextLocation, false, future.v7_skipActionErrorRevalidation, isRevalidationRequired, cancelledDeferredRoutes, cancelledFetcherLoads, deletedFetchers, fetchLoadMatches, fetchRedirectIds, routesToUse, basename, [match.route.id, actionResult]);
  1991. revalidatingFetchers.filter((rf) => rf.key !== key).forEach((rf) => {
  1992. let staleKey = rf.key;
  1993. let existingFetcher2 = state.fetchers.get(staleKey);
  1994. let revalidatingFetcher = getLoadingFetcher(void 0, existingFetcher2 ? existingFetcher2.data : void 0);
  1995. state.fetchers.set(staleKey, revalidatingFetcher);
  1996. abortFetcher(staleKey);
  1997. if (rf.controller) {
  1998. fetchControllers.set(staleKey, rf.controller);
  1999. }
  2000. });
  2001. updateState({
  2002. fetchers: new Map(state.fetchers)
  2003. });
  2004. let abortPendingFetchRevalidations = () => revalidatingFetchers.forEach((rf) => abortFetcher(rf.key));
  2005. abortController.signal.addEventListener("abort", abortPendingFetchRevalidations);
  2006. let {
  2007. loaderResults,
  2008. fetcherResults
  2009. } = await callLoadersAndMaybeResolveData(state, matches, matchesToLoad, revalidatingFetchers, revalidationRequest);
  2010. if (abortController.signal.aborted) {
  2011. return;
  2012. }
  2013. abortController.signal.removeEventListener("abort", abortPendingFetchRevalidations);
  2014. fetchReloadIds.delete(key);
  2015. fetchControllers.delete(key);
  2016. revalidatingFetchers.forEach((r) => fetchControllers.delete(r.key));
  2017. let redirect3 = findRedirect(loaderResults);
  2018. if (redirect3) {
  2019. return startRedirectNavigation(revalidationRequest, redirect3.result, false, {
  2020. preventScrollReset
  2021. });
  2022. }
  2023. redirect3 = findRedirect(fetcherResults);
  2024. if (redirect3) {
  2025. fetchRedirectIds.add(redirect3.key);
  2026. return startRedirectNavigation(revalidationRequest, redirect3.result, false, {
  2027. preventScrollReset
  2028. });
  2029. }
  2030. let {
  2031. loaderData,
  2032. errors
  2033. } = processLoaderData(state, matches, loaderResults, void 0, revalidatingFetchers, fetcherResults, activeDeferreds);
  2034. if (state.fetchers.has(key)) {
  2035. let doneFetcher = getDoneFetcher(actionResult.data);
  2036. state.fetchers.set(key, doneFetcher);
  2037. }
  2038. abortStaleFetchLoads(loadId);
  2039. if (state.navigation.state === "loading" && loadId > pendingNavigationLoadId) {
  2040. invariant(pendingAction, "Expected pending action");
  2041. pendingNavigationController && pendingNavigationController.abort();
  2042. completeNavigation(state.navigation.location, {
  2043. matches,
  2044. loaderData,
  2045. errors,
  2046. fetchers: new Map(state.fetchers)
  2047. });
  2048. } else {
  2049. updateState({
  2050. errors,
  2051. loaderData: mergeLoaderData(state.loaderData, loaderData, matches, errors),
  2052. fetchers: new Map(state.fetchers)
  2053. });
  2054. isRevalidationRequired = false;
  2055. }
  2056. }
  2057. async function handleFetcherLoader(key, routeId, path, match, matches, isFogOfWar, flushSync, preventScrollReset, submission) {
  2058. let existingFetcher = state.fetchers.get(key);
  2059. updateFetcherState(key, getLoadingFetcher(submission, existingFetcher ? existingFetcher.data : void 0), {
  2060. flushSync
  2061. });
  2062. let abortController = new AbortController();
  2063. let fetchRequest = createClientSideRequest(init.history, path, abortController.signal);
  2064. if (isFogOfWar) {
  2065. let discoverResult = await discoverRoutes(matches, new URL(fetchRequest.url).pathname, fetchRequest.signal, key);
  2066. if (discoverResult.type === "aborted") {
  2067. return;
  2068. } else if (discoverResult.type === "error") {
  2069. setFetcherError(key, routeId, discoverResult.error, {
  2070. flushSync
  2071. });
  2072. return;
  2073. } else if (!discoverResult.matches) {
  2074. setFetcherError(key, routeId, getInternalRouterError(404, {
  2075. pathname: path
  2076. }), {
  2077. flushSync
  2078. });
  2079. return;
  2080. } else {
  2081. matches = discoverResult.matches;
  2082. match = getTargetMatch(matches, path);
  2083. }
  2084. }
  2085. fetchControllers.set(key, abortController);
  2086. let originatingLoadId = incrementingLoadId;
  2087. let results = await callDataStrategy("loader", state, fetchRequest, [match], matches, key);
  2088. let result = results[match.route.id];
  2089. if (isDeferredResult(result)) {
  2090. result = await resolveDeferredData(result, fetchRequest.signal, true) || result;
  2091. }
  2092. if (fetchControllers.get(key) === abortController) {
  2093. fetchControllers.delete(key);
  2094. }
  2095. if (fetchRequest.signal.aborted) {
  2096. return;
  2097. }
  2098. if (deletedFetchers.has(key)) {
  2099. updateFetcherState(key, getDoneFetcher(void 0));
  2100. return;
  2101. }
  2102. if (isRedirectResult(result)) {
  2103. if (pendingNavigationLoadId > originatingLoadId) {
  2104. updateFetcherState(key, getDoneFetcher(void 0));
  2105. return;
  2106. } else {
  2107. fetchRedirectIds.add(key);
  2108. await startRedirectNavigation(fetchRequest, result, false, {
  2109. preventScrollReset
  2110. });
  2111. return;
  2112. }
  2113. }
  2114. if (isErrorResult(result)) {
  2115. setFetcherError(key, routeId, result.error);
  2116. return;
  2117. }
  2118. invariant(!isDeferredResult(result), "Unhandled fetcher deferred data");
  2119. updateFetcherState(key, getDoneFetcher(result.data));
  2120. }
  2121. async function startRedirectNavigation(request, redirect3, isNavigation, _temp2) {
  2122. let {
  2123. submission,
  2124. fetcherSubmission,
  2125. preventScrollReset,
  2126. replace: replace2
  2127. } = _temp2 === void 0 ? {} : _temp2;
  2128. if (redirect3.response.headers.has("X-Remix-Revalidate")) {
  2129. isRevalidationRequired = true;
  2130. }
  2131. let location = redirect3.response.headers.get("Location");
  2132. invariant(location, "Expected a Location header on the redirect Response");
  2133. location = normalizeRedirectLocation(location, new URL(request.url), basename, init.history);
  2134. let redirectLocation = createLocation(state.location, location, {
  2135. _isRedirect: true
  2136. });
  2137. if (isBrowser2) {
  2138. let isDocumentReload = false;
  2139. if (redirect3.response.headers.has("X-Remix-Reload-Document")) {
  2140. isDocumentReload = true;
  2141. } else if (ABSOLUTE_URL_REGEX.test(location)) {
  2142. const url = init.history.createURL(location);
  2143. isDocumentReload = // Hard reload if it's an absolute URL to a new origin
  2144. url.origin !== routerWindow.location.origin || // Hard reload if it's an absolute URL that does not match our basename
  2145. stripBasename(url.pathname, basename) == null;
  2146. }
  2147. if (isDocumentReload) {
  2148. if (replace2) {
  2149. routerWindow.location.replace(location);
  2150. } else {
  2151. routerWindow.location.assign(location);
  2152. }
  2153. return;
  2154. }
  2155. }
  2156. pendingNavigationController = null;
  2157. let redirectHistoryAction = replace2 === true || redirect3.response.headers.has("X-Remix-Replace") ? Action.Replace : Action.Push;
  2158. let {
  2159. formMethod,
  2160. formAction,
  2161. formEncType
  2162. } = state.navigation;
  2163. if (!submission && !fetcherSubmission && formMethod && formAction && formEncType) {
  2164. submission = getSubmissionFromNavigation(state.navigation);
  2165. }
  2166. let activeSubmission = submission || fetcherSubmission;
  2167. if (redirectPreserveMethodStatusCodes.has(redirect3.response.status) && activeSubmission && isMutationMethod(activeSubmission.formMethod)) {
  2168. await startNavigation(redirectHistoryAction, redirectLocation, {
  2169. submission: _extends({}, activeSubmission, {
  2170. formAction: location
  2171. }),
  2172. // Preserve these flags across redirects
  2173. preventScrollReset: preventScrollReset || pendingPreventScrollReset,
  2174. enableViewTransition: isNavigation ? pendingViewTransitionEnabled : void 0
  2175. });
  2176. } else {
  2177. let overrideNavigation = getLoadingNavigation(redirectLocation, submission);
  2178. await startNavigation(redirectHistoryAction, redirectLocation, {
  2179. overrideNavigation,
  2180. // Send fetcher submissions through for shouldRevalidate
  2181. fetcherSubmission,
  2182. // Preserve these flags across redirects
  2183. preventScrollReset: preventScrollReset || pendingPreventScrollReset,
  2184. enableViewTransition: isNavigation ? pendingViewTransitionEnabled : void 0
  2185. });
  2186. }
  2187. }
  2188. async function callDataStrategy(type, state2, request, matchesToLoad, matches, fetcherKey) {
  2189. let results;
  2190. let dataResults = {};
  2191. try {
  2192. results = await callDataStrategyImpl(dataStrategyImpl, type, state2, request, matchesToLoad, matches, fetcherKey, manifest, mapRouteProperties2);
  2193. } catch (e) {
  2194. matchesToLoad.forEach((m) => {
  2195. dataResults[m.route.id] = {
  2196. type: ResultType.error,
  2197. error: e
  2198. };
  2199. });
  2200. return dataResults;
  2201. }
  2202. for (let [routeId, result] of Object.entries(results)) {
  2203. if (isRedirectDataStrategyResultResult(result)) {
  2204. let response = result.result;
  2205. dataResults[routeId] = {
  2206. type: ResultType.redirect,
  2207. response: normalizeRelativeRoutingRedirectResponse(response, request, routeId, matches, basename, future.v7_relativeSplatPath)
  2208. };
  2209. } else {
  2210. dataResults[routeId] = await convertDataStrategyResultToDataResult(result);
  2211. }
  2212. }
  2213. return dataResults;
  2214. }
  2215. async function callLoadersAndMaybeResolveData(state2, matches, matchesToLoad, fetchersToLoad, request) {
  2216. let currentMatches = state2.matches;
  2217. let loaderResultsPromise = callDataStrategy("loader", state2, request, matchesToLoad, matches, null);
  2218. let fetcherResultsPromise = Promise.all(fetchersToLoad.map(async (f) => {
  2219. if (f.matches && f.match && f.controller) {
  2220. let results = await callDataStrategy("loader", state2, createClientSideRequest(init.history, f.path, f.controller.signal), [f.match], f.matches, f.key);
  2221. let result = results[f.match.route.id];
  2222. return {
  2223. [f.key]: result
  2224. };
  2225. } else {
  2226. return Promise.resolve({
  2227. [f.key]: {
  2228. type: ResultType.error,
  2229. error: getInternalRouterError(404, {
  2230. pathname: f.path
  2231. })
  2232. }
  2233. });
  2234. }
  2235. }));
  2236. let loaderResults = await loaderResultsPromise;
  2237. let fetcherResults = (await fetcherResultsPromise).reduce((acc, r) => Object.assign(acc, r), {});
  2238. await Promise.all([resolveNavigationDeferredResults(matches, loaderResults, request.signal, currentMatches, state2.loaderData), resolveFetcherDeferredResults(matches, fetcherResults, fetchersToLoad)]);
  2239. return {
  2240. loaderResults,
  2241. fetcherResults
  2242. };
  2243. }
  2244. function interruptActiveLoads() {
  2245. isRevalidationRequired = true;
  2246. cancelledDeferredRoutes.push(...cancelActiveDeferreds());
  2247. fetchLoadMatches.forEach((_, key) => {
  2248. if (fetchControllers.has(key)) {
  2249. cancelledFetcherLoads.add(key);
  2250. }
  2251. abortFetcher(key);
  2252. });
  2253. }
  2254. function updateFetcherState(key, fetcher, opts) {
  2255. if (opts === void 0) {
  2256. opts = {};
  2257. }
  2258. state.fetchers.set(key, fetcher);
  2259. updateState({
  2260. fetchers: new Map(state.fetchers)
  2261. }, {
  2262. flushSync: (opts && opts.flushSync) === true
  2263. });
  2264. }
  2265. function setFetcherError(key, routeId, error, opts) {
  2266. if (opts === void 0) {
  2267. opts = {};
  2268. }
  2269. let boundaryMatch = findNearestBoundary(state.matches, routeId);
  2270. deleteFetcher(key);
  2271. updateState({
  2272. errors: {
  2273. [boundaryMatch.route.id]: error
  2274. },
  2275. fetchers: new Map(state.fetchers)
  2276. }, {
  2277. flushSync: (opts && opts.flushSync) === true
  2278. });
  2279. }
  2280. function getFetcher(key) {
  2281. activeFetchers.set(key, (activeFetchers.get(key) || 0) + 1);
  2282. if (deletedFetchers.has(key)) {
  2283. deletedFetchers.delete(key);
  2284. }
  2285. return state.fetchers.get(key) || IDLE_FETCHER;
  2286. }
  2287. function deleteFetcher(key) {
  2288. let fetcher = state.fetchers.get(key);
  2289. if (fetchControllers.has(key) && !(fetcher && fetcher.state === "loading" && fetchReloadIds.has(key))) {
  2290. abortFetcher(key);
  2291. }
  2292. fetchLoadMatches.delete(key);
  2293. fetchReloadIds.delete(key);
  2294. fetchRedirectIds.delete(key);
  2295. if (future.v7_fetcherPersist) {
  2296. deletedFetchers.delete(key);
  2297. }
  2298. cancelledFetcherLoads.delete(key);
  2299. state.fetchers.delete(key);
  2300. }
  2301. function deleteFetcherAndUpdateState(key) {
  2302. let count = (activeFetchers.get(key) || 0) - 1;
  2303. if (count <= 0) {
  2304. activeFetchers.delete(key);
  2305. deletedFetchers.add(key);
  2306. if (!future.v7_fetcherPersist) {
  2307. deleteFetcher(key);
  2308. }
  2309. } else {
  2310. activeFetchers.set(key, count);
  2311. }
  2312. updateState({
  2313. fetchers: new Map(state.fetchers)
  2314. });
  2315. }
  2316. function abortFetcher(key) {
  2317. let controller = fetchControllers.get(key);
  2318. if (controller) {
  2319. controller.abort();
  2320. fetchControllers.delete(key);
  2321. }
  2322. }
  2323. function markFetchersDone(keys) {
  2324. for (let key of keys) {
  2325. let fetcher = getFetcher(key);
  2326. let doneFetcher = getDoneFetcher(fetcher.data);
  2327. state.fetchers.set(key, doneFetcher);
  2328. }
  2329. }
  2330. function markFetchRedirectsDone() {
  2331. let doneKeys = [];
  2332. let updatedFetchers = false;
  2333. for (let key of fetchRedirectIds) {
  2334. let fetcher = state.fetchers.get(key);
  2335. invariant(fetcher, "Expected fetcher: " + key);
  2336. if (fetcher.state === "loading") {
  2337. fetchRedirectIds.delete(key);
  2338. doneKeys.push(key);
  2339. updatedFetchers = true;
  2340. }
  2341. }
  2342. markFetchersDone(doneKeys);
  2343. return updatedFetchers;
  2344. }
  2345. function abortStaleFetchLoads(landedId) {
  2346. let yeetedKeys = [];
  2347. for (let [key, id] of fetchReloadIds) {
  2348. if (id < landedId) {
  2349. let fetcher = state.fetchers.get(key);
  2350. invariant(fetcher, "Expected fetcher: " + key);
  2351. if (fetcher.state === "loading") {
  2352. abortFetcher(key);
  2353. fetchReloadIds.delete(key);
  2354. yeetedKeys.push(key);
  2355. }
  2356. }
  2357. }
  2358. markFetchersDone(yeetedKeys);
  2359. return yeetedKeys.length > 0;
  2360. }
  2361. function getBlocker(key, fn) {
  2362. let blocker = state.blockers.get(key) || IDLE_BLOCKER;
  2363. if (blockerFunctions.get(key) !== fn) {
  2364. blockerFunctions.set(key, fn);
  2365. }
  2366. return blocker;
  2367. }
  2368. function deleteBlocker(key) {
  2369. state.blockers.delete(key);
  2370. blockerFunctions.delete(key);
  2371. }
  2372. function updateBlocker(key, newBlocker) {
  2373. let blocker = state.blockers.get(key) || IDLE_BLOCKER;
  2374. invariant(blocker.state === "unblocked" && newBlocker.state === "blocked" || blocker.state === "blocked" && newBlocker.state === "blocked" || blocker.state === "blocked" && newBlocker.state === "proceeding" || blocker.state === "blocked" && newBlocker.state === "unblocked" || blocker.state === "proceeding" && newBlocker.state === "unblocked", "Invalid blocker state transition: " + blocker.state + " -> " + newBlocker.state);
  2375. let blockers = new Map(state.blockers);
  2376. blockers.set(key, newBlocker);
  2377. updateState({
  2378. blockers
  2379. });
  2380. }
  2381. function shouldBlockNavigation(_ref2) {
  2382. let {
  2383. currentLocation,
  2384. nextLocation,
  2385. historyAction
  2386. } = _ref2;
  2387. if (blockerFunctions.size === 0) {
  2388. return;
  2389. }
  2390. if (blockerFunctions.size > 1) {
  2391. warning(false, "A router only supports one blocker at a time");
  2392. }
  2393. let entries = Array.from(blockerFunctions.entries());
  2394. let [blockerKey, blockerFunction] = entries[entries.length - 1];
  2395. let blocker = state.blockers.get(blockerKey);
  2396. if (blocker && blocker.state === "proceeding") {
  2397. return;
  2398. }
  2399. if (blockerFunction({
  2400. currentLocation,
  2401. nextLocation,
  2402. historyAction
  2403. })) {
  2404. return blockerKey;
  2405. }
  2406. }
  2407. function handleNavigational404(pathname) {
  2408. let error = getInternalRouterError(404, {
  2409. pathname
  2410. });
  2411. let routesToUse = inFlightDataRoutes || dataRoutes;
  2412. let {
  2413. matches,
  2414. route
  2415. } = getShortCircuitMatches(routesToUse);
  2416. cancelActiveDeferreds();
  2417. return {
  2418. notFoundMatches: matches,
  2419. route,
  2420. error
  2421. };
  2422. }
  2423. function cancelActiveDeferreds(predicate) {
  2424. let cancelledRouteIds = [];
  2425. activeDeferreds.forEach((dfd, routeId) => {
  2426. if (!predicate || predicate(routeId)) {
  2427. dfd.cancel();
  2428. cancelledRouteIds.push(routeId);
  2429. activeDeferreds.delete(routeId);
  2430. }
  2431. });
  2432. return cancelledRouteIds;
  2433. }
  2434. function enableScrollRestoration(positions, getPosition, getKey) {
  2435. savedScrollPositions2 = positions;
  2436. getScrollPosition = getPosition;
  2437. getScrollRestorationKey = getKey || null;
  2438. if (!initialScrollRestored && state.navigation === IDLE_NAVIGATION) {
  2439. initialScrollRestored = true;
  2440. let y = getSavedScrollPosition(state.location, state.matches);
  2441. if (y != null) {
  2442. updateState({
  2443. restoreScrollPosition: y
  2444. });
  2445. }
  2446. }
  2447. return () => {
  2448. savedScrollPositions2 = null;
  2449. getScrollPosition = null;
  2450. getScrollRestorationKey = null;
  2451. };
  2452. }
  2453. function getScrollKey(location, matches) {
  2454. if (getScrollRestorationKey) {
  2455. let key = getScrollRestorationKey(location, matches.map((m) => convertRouteMatchToUiMatch(m, state.loaderData)));
  2456. return key || location.key;
  2457. }
  2458. return location.key;
  2459. }
  2460. function saveScrollPosition(location, matches) {
  2461. if (savedScrollPositions2 && getScrollPosition) {
  2462. let key = getScrollKey(location, matches);
  2463. savedScrollPositions2[key] = getScrollPosition();
  2464. }
  2465. }
  2466. function getSavedScrollPosition(location, matches) {
  2467. if (savedScrollPositions2) {
  2468. let key = getScrollKey(location, matches);
  2469. let y = savedScrollPositions2[key];
  2470. if (typeof y === "number") {
  2471. return y;
  2472. }
  2473. }
  2474. return null;
  2475. }
  2476. function checkFogOfWar(matches, routesToUse, pathname) {
  2477. if (patchRoutesOnNavigationImpl) {
  2478. if (!matches) {
  2479. let fogMatches = matchRoutesImpl(routesToUse, pathname, basename, true);
  2480. return {
  2481. active: true,
  2482. matches: fogMatches || []
  2483. };
  2484. } else {
  2485. if (Object.keys(matches[0].params).length > 0) {
  2486. let partialMatches = matchRoutesImpl(routesToUse, pathname, basename, true);
  2487. return {
  2488. active: true,
  2489. matches: partialMatches
  2490. };
  2491. }
  2492. }
  2493. }
  2494. return {
  2495. active: false,
  2496. matches: null
  2497. };
  2498. }
  2499. async function discoverRoutes(matches, pathname, signal, fetcherKey) {
  2500. if (!patchRoutesOnNavigationImpl) {
  2501. return {
  2502. type: "success",
  2503. matches
  2504. };
  2505. }
  2506. let partialMatches = matches;
  2507. while (true) {
  2508. let isNonHMR = inFlightDataRoutes == null;
  2509. let routesToUse = inFlightDataRoutes || dataRoutes;
  2510. let localManifest = manifest;
  2511. try {
  2512. await patchRoutesOnNavigationImpl({
  2513. signal,
  2514. path: pathname,
  2515. matches: partialMatches,
  2516. fetcherKey,
  2517. patch: (routeId, children) => {
  2518. if (signal.aborted) return;
  2519. patchRoutesImpl(routeId, children, routesToUse, localManifest, mapRouteProperties2);
  2520. }
  2521. });
  2522. } catch (e) {
  2523. return {
  2524. type: "error",
  2525. error: e,
  2526. partialMatches
  2527. };
  2528. } finally {
  2529. if (isNonHMR && !signal.aborted) {
  2530. dataRoutes = [...dataRoutes];
  2531. }
  2532. }
  2533. if (signal.aborted) {
  2534. return {
  2535. type: "aborted"
  2536. };
  2537. }
  2538. let newMatches = matchRoutes(routesToUse, pathname, basename);
  2539. if (newMatches) {
  2540. return {
  2541. type: "success",
  2542. matches: newMatches
  2543. };
  2544. }
  2545. let newPartialMatches = matchRoutesImpl(routesToUse, pathname, basename, true);
  2546. if (!newPartialMatches || partialMatches.length === newPartialMatches.length && partialMatches.every((m, i) => m.route.id === newPartialMatches[i].route.id)) {
  2547. return {
  2548. type: "success",
  2549. matches: null
  2550. };
  2551. }
  2552. partialMatches = newPartialMatches;
  2553. }
  2554. }
  2555. function _internalSetRoutes(newRoutes) {
  2556. manifest = {};
  2557. inFlightDataRoutes = convertRoutesToDataRoutes(newRoutes, mapRouteProperties2, void 0, manifest);
  2558. }
  2559. function patchRoutes(routeId, children) {
  2560. let isNonHMR = inFlightDataRoutes == null;
  2561. let routesToUse = inFlightDataRoutes || dataRoutes;
  2562. patchRoutesImpl(routeId, children, routesToUse, manifest, mapRouteProperties2);
  2563. if (isNonHMR) {
  2564. dataRoutes = [...dataRoutes];
  2565. updateState({});
  2566. }
  2567. }
  2568. router = {
  2569. get basename() {
  2570. return basename;
  2571. },
  2572. get future() {
  2573. return future;
  2574. },
  2575. get state() {
  2576. return state;
  2577. },
  2578. get routes() {
  2579. return dataRoutes;
  2580. },
  2581. get window() {
  2582. return routerWindow;
  2583. },
  2584. initialize,
  2585. subscribe,
  2586. enableScrollRestoration,
  2587. navigate,
  2588. fetch,
  2589. revalidate,
  2590. // Passthrough to history-aware createHref used by useHref so we get proper
  2591. // hash-aware URLs in DOM paths
  2592. createHref: (to) => init.history.createHref(to),
  2593. encodeLocation: (to) => init.history.encodeLocation(to),
  2594. getFetcher,
  2595. deleteFetcher: deleteFetcherAndUpdateState,
  2596. dispose,
  2597. getBlocker,
  2598. deleteBlocker,
  2599. patchRoutes,
  2600. _internalFetchControllers: fetchControllers,
  2601. _internalActiveDeferreds: activeDeferreds,
  2602. // TODO: Remove setRoutes, it's temporary to avoid dealing with
  2603. // updating the tree while validating the update algorithm.
  2604. _internalSetRoutes
  2605. };
  2606. return router;
  2607. }
  2608. var UNSAFE_DEFERRED_SYMBOL = Symbol("deferred");
  2609. function isSubmissionNavigation(opts) {
  2610. return opts != null && ("formData" in opts && opts.formData != null || "body" in opts && opts.body !== void 0);
  2611. }
  2612. function normalizeTo(location, matches, basename, prependBasename, to, v7_relativeSplatPath, fromRouteId, relative) {
  2613. let contextualMatches;
  2614. let activeRouteMatch;
  2615. if (fromRouteId) {
  2616. contextualMatches = [];
  2617. for (let match of matches) {
  2618. contextualMatches.push(match);
  2619. if (match.route.id === fromRouteId) {
  2620. activeRouteMatch = match;
  2621. break;
  2622. }
  2623. }
  2624. } else {
  2625. contextualMatches = matches;
  2626. activeRouteMatch = matches[matches.length - 1];
  2627. }
  2628. let path = resolveTo(to ? to : ".", getResolveToMatches(contextualMatches, v7_relativeSplatPath), stripBasename(location.pathname, basename) || location.pathname, relative === "path");
  2629. if (to == null) {
  2630. path.search = location.search;
  2631. path.hash = location.hash;
  2632. }
  2633. if ((to == null || to === "" || to === ".") && activeRouteMatch) {
  2634. let nakedIndex = hasNakedIndexQuery(path.search);
  2635. if (activeRouteMatch.route.index && !nakedIndex) {
  2636. path.search = path.search ? path.search.replace(/^\?/, "?index&") : "?index";
  2637. } else if (!activeRouteMatch.route.index && nakedIndex) {
  2638. let params = new URLSearchParams(path.search);
  2639. let indexValues = params.getAll("index");
  2640. params.delete("index");
  2641. indexValues.filter((v) => v).forEach((v) => params.append("index", v));
  2642. let qs = params.toString();
  2643. path.search = qs ? "?" + qs : "";
  2644. }
  2645. }
  2646. if (prependBasename && basename !== "/") {
  2647. path.pathname = path.pathname === "/" ? basename : joinPaths([basename, path.pathname]);
  2648. }
  2649. return createPath(path);
  2650. }
  2651. function normalizeNavigateOptions(normalizeFormMethod, isFetcher, path, opts) {
  2652. if (!opts || !isSubmissionNavigation(opts)) {
  2653. return {
  2654. path
  2655. };
  2656. }
  2657. if (opts.formMethod && !isValidMethod(opts.formMethod)) {
  2658. return {
  2659. path,
  2660. error: getInternalRouterError(405, {
  2661. method: opts.formMethod
  2662. })
  2663. };
  2664. }
  2665. let getInvalidBodyError = () => ({
  2666. path,
  2667. error: getInternalRouterError(400, {
  2668. type: "invalid-body"
  2669. })
  2670. });
  2671. let rawFormMethod = opts.formMethod || "get";
  2672. let formMethod = normalizeFormMethod ? rawFormMethod.toUpperCase() : rawFormMethod.toLowerCase();
  2673. let formAction = stripHashFromPath(path);
  2674. if (opts.body !== void 0) {
  2675. if (opts.formEncType === "text/plain") {
  2676. if (!isMutationMethod(formMethod)) {
  2677. return getInvalidBodyError();
  2678. }
  2679. let text = typeof opts.body === "string" ? opts.body : opts.body instanceof FormData || opts.body instanceof URLSearchParams ? (
  2680. // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#plain-text-form-data
  2681. Array.from(opts.body.entries()).reduce((acc, _ref3) => {
  2682. let [name, value] = _ref3;
  2683. return "" + acc + name + "=" + value + "\n";
  2684. }, "")
  2685. ) : String(opts.body);
  2686. return {
  2687. path,
  2688. submission: {
  2689. formMethod,
  2690. formAction,
  2691. formEncType: opts.formEncType,
  2692. formData: void 0,
  2693. json: void 0,
  2694. text
  2695. }
  2696. };
  2697. } else if (opts.formEncType === "application/json") {
  2698. if (!isMutationMethod(formMethod)) {
  2699. return getInvalidBodyError();
  2700. }
  2701. try {
  2702. let json3 = typeof opts.body === "string" ? JSON.parse(opts.body) : opts.body;
  2703. return {
  2704. path,
  2705. submission: {
  2706. formMethod,
  2707. formAction,
  2708. formEncType: opts.formEncType,
  2709. formData: void 0,
  2710. json: json3,
  2711. text: void 0
  2712. }
  2713. };
  2714. } catch (e) {
  2715. return getInvalidBodyError();
  2716. }
  2717. }
  2718. }
  2719. invariant(typeof FormData === "function", "FormData is not available in this environment");
  2720. let searchParams;
  2721. let formData;
  2722. if (opts.formData) {
  2723. searchParams = convertFormDataToSearchParams(opts.formData);
  2724. formData = opts.formData;
  2725. } else if (opts.body instanceof FormData) {
  2726. searchParams = convertFormDataToSearchParams(opts.body);
  2727. formData = opts.body;
  2728. } else if (opts.body instanceof URLSearchParams) {
  2729. searchParams = opts.body;
  2730. formData = convertSearchParamsToFormData(searchParams);
  2731. } else if (opts.body == null) {
  2732. searchParams = new URLSearchParams();
  2733. formData = new FormData();
  2734. } else {
  2735. try {
  2736. searchParams = new URLSearchParams(opts.body);
  2737. formData = convertSearchParamsToFormData(searchParams);
  2738. } catch (e) {
  2739. return getInvalidBodyError();
  2740. }
  2741. }
  2742. let submission = {
  2743. formMethod,
  2744. formAction,
  2745. formEncType: opts && opts.formEncType || "application/x-www-form-urlencoded",
  2746. formData,
  2747. json: void 0,
  2748. text: void 0
  2749. };
  2750. if (isMutationMethod(submission.formMethod)) {
  2751. return {
  2752. path,
  2753. submission
  2754. };
  2755. }
  2756. let parsedPath = parsePath(path);
  2757. if (isFetcher && parsedPath.search && hasNakedIndexQuery(parsedPath.search)) {
  2758. searchParams.append("index", "");
  2759. }
  2760. parsedPath.search = "?" + searchParams;
  2761. return {
  2762. path: createPath(parsedPath),
  2763. submission
  2764. };
  2765. }
  2766. function getLoaderMatchesUntilBoundary(matches, boundaryId, includeBoundary) {
  2767. if (includeBoundary === void 0) {
  2768. includeBoundary = false;
  2769. }
  2770. let index = matches.findIndex((m) => m.route.id === boundaryId);
  2771. if (index >= 0) {
  2772. return matches.slice(0, includeBoundary ? index + 1 : index);
  2773. }
  2774. return matches;
  2775. }
  2776. function getMatchesToLoad(history, state, matches, submission, location, initialHydration, skipActionErrorRevalidation, isRevalidationRequired, cancelledDeferredRoutes, cancelledFetcherLoads, deletedFetchers, fetchLoadMatches, fetchRedirectIds, routesToUse, basename, pendingActionResult) {
  2777. let actionResult = pendingActionResult ? isErrorResult(pendingActionResult[1]) ? pendingActionResult[1].error : pendingActionResult[1].data : void 0;
  2778. let currentUrl = history.createURL(state.location);
  2779. let nextUrl = history.createURL(location);
  2780. let boundaryMatches = matches;
  2781. if (initialHydration && state.errors) {
  2782. boundaryMatches = getLoaderMatchesUntilBoundary(matches, Object.keys(state.errors)[0], true);
  2783. } else if (pendingActionResult && isErrorResult(pendingActionResult[1])) {
  2784. boundaryMatches = getLoaderMatchesUntilBoundary(matches, pendingActionResult[0]);
  2785. }
  2786. let actionStatus = pendingActionResult ? pendingActionResult[1].statusCode : void 0;
  2787. let shouldSkipRevalidation = skipActionErrorRevalidation && actionStatus && actionStatus >= 400;
  2788. let navigationMatches = boundaryMatches.filter((match, index) => {
  2789. let {
  2790. route
  2791. } = match;
  2792. if (route.lazy) {
  2793. return true;
  2794. }
  2795. if (route.loader == null) {
  2796. return false;
  2797. }
  2798. if (initialHydration) {
  2799. return shouldLoadRouteOnHydration(route, state.loaderData, state.errors);
  2800. }
  2801. if (isNewLoader(state.loaderData, state.matches[index], match) || cancelledDeferredRoutes.some((id) => id === match.route.id)) {
  2802. return true;
  2803. }
  2804. let currentRouteMatch = state.matches[index];
  2805. let nextRouteMatch = match;
  2806. return shouldRevalidateLoader(match, _extends({
  2807. currentUrl,
  2808. currentParams: currentRouteMatch.params,
  2809. nextUrl,
  2810. nextParams: nextRouteMatch.params
  2811. }, submission, {
  2812. actionResult,
  2813. actionStatus,
  2814. defaultShouldRevalidate: shouldSkipRevalidation ? false : (
  2815. // Forced revalidation due to submission, useRevalidator, or X-Remix-Revalidate
  2816. isRevalidationRequired || currentUrl.pathname + currentUrl.search === nextUrl.pathname + nextUrl.search || // Search params affect all loaders
  2817. currentUrl.search !== nextUrl.search || isNewRouteInstance(currentRouteMatch, nextRouteMatch)
  2818. )
  2819. }));
  2820. });
  2821. let revalidatingFetchers = [];
  2822. fetchLoadMatches.forEach((f, key) => {
  2823. if (initialHydration || !matches.some((m) => m.route.id === f.routeId) || deletedFetchers.has(key)) {
  2824. return;
  2825. }
  2826. let fetcherMatches = matchRoutes(routesToUse, f.path, basename);
  2827. if (!fetcherMatches) {
  2828. revalidatingFetchers.push({
  2829. key,
  2830. routeId: f.routeId,
  2831. path: f.path,
  2832. matches: null,
  2833. match: null,
  2834. controller: null
  2835. });
  2836. return;
  2837. }
  2838. let fetcher = state.fetchers.get(key);
  2839. let fetcherMatch = getTargetMatch(fetcherMatches, f.path);
  2840. let shouldRevalidate = false;
  2841. if (fetchRedirectIds.has(key)) {
  2842. shouldRevalidate = false;
  2843. } else if (cancelledFetcherLoads.has(key)) {
  2844. cancelledFetcherLoads.delete(key);
  2845. shouldRevalidate = true;
  2846. } else if (fetcher && fetcher.state !== "idle" && fetcher.data === void 0) {
  2847. shouldRevalidate = isRevalidationRequired;
  2848. } else {
  2849. shouldRevalidate = shouldRevalidateLoader(fetcherMatch, _extends({
  2850. currentUrl,
  2851. currentParams: state.matches[state.matches.length - 1].params,
  2852. nextUrl,
  2853. nextParams: matches[matches.length - 1].params
  2854. }, submission, {
  2855. actionResult,
  2856. actionStatus,
  2857. defaultShouldRevalidate: shouldSkipRevalidation ? false : isRevalidationRequired
  2858. }));
  2859. }
  2860. if (shouldRevalidate) {
  2861. revalidatingFetchers.push({
  2862. key,
  2863. routeId: f.routeId,
  2864. path: f.path,
  2865. matches: fetcherMatches,
  2866. match: fetcherMatch,
  2867. controller: new AbortController()
  2868. });
  2869. }
  2870. });
  2871. return [navigationMatches, revalidatingFetchers];
  2872. }
  2873. function shouldLoadRouteOnHydration(route, loaderData, errors) {
  2874. if (route.lazy) {
  2875. return true;
  2876. }
  2877. if (!route.loader) {
  2878. return false;
  2879. }
  2880. let hasData = loaderData != null && loaderData[route.id] !== void 0;
  2881. let hasError = errors != null && errors[route.id] !== void 0;
  2882. if (!hasData && hasError) {
  2883. return false;
  2884. }
  2885. if (typeof route.loader === "function" && route.loader.hydrate === true) {
  2886. return true;
  2887. }
  2888. return !hasData && !hasError;
  2889. }
  2890. function isNewLoader(currentLoaderData, currentMatch, match) {
  2891. let isNew = (
  2892. // [a] -> [a, b]
  2893. !currentMatch || // [a, b] -> [a, c]
  2894. match.route.id !== currentMatch.route.id
  2895. );
  2896. let isMissingData = currentLoaderData[match.route.id] === void 0;
  2897. return isNew || isMissingData;
  2898. }
  2899. function isNewRouteInstance(currentMatch, match) {
  2900. let currentPath = currentMatch.route.path;
  2901. return (
  2902. // param change for this match, /users/123 -> /users/456
  2903. currentMatch.pathname !== match.pathname || // splat param changed, which is not present in match.path
  2904. // e.g. /files/images/avatar.jpg -> files/finances.xls
  2905. currentPath != null && currentPath.endsWith("*") && currentMatch.params["*"] !== match.params["*"]
  2906. );
  2907. }
  2908. function shouldRevalidateLoader(loaderMatch, arg) {
  2909. if (loaderMatch.route.shouldRevalidate) {
  2910. let routeChoice = loaderMatch.route.shouldRevalidate(arg);
  2911. if (typeof routeChoice === "boolean") {
  2912. return routeChoice;
  2913. }
  2914. }
  2915. return arg.defaultShouldRevalidate;
  2916. }
  2917. function patchRoutesImpl(routeId, children, routesToUse, manifest, mapRouteProperties2) {
  2918. var _childrenToPatch;
  2919. let childrenToPatch;
  2920. if (routeId) {
  2921. let route = manifest[routeId];
  2922. invariant(route, "No route found to patch children into: routeId = " + routeId);
  2923. if (!route.children) {
  2924. route.children = [];
  2925. }
  2926. childrenToPatch = route.children;
  2927. } else {
  2928. childrenToPatch = routesToUse;
  2929. }
  2930. let uniqueChildren = children.filter((newRoute) => !childrenToPatch.some((existingRoute) => isSameRoute(newRoute, existingRoute)));
  2931. let newRoutes = convertRoutesToDataRoutes(uniqueChildren, mapRouteProperties2, [routeId || "_", "patch", String(((_childrenToPatch = childrenToPatch) == null ? void 0 : _childrenToPatch.length) || "0")], manifest);
  2932. childrenToPatch.push(...newRoutes);
  2933. }
  2934. function isSameRoute(newRoute, existingRoute) {
  2935. if ("id" in newRoute && "id" in existingRoute && newRoute.id === existingRoute.id) {
  2936. return true;
  2937. }
  2938. if (!(newRoute.index === existingRoute.index && newRoute.path === existingRoute.path && newRoute.caseSensitive === existingRoute.caseSensitive)) {
  2939. return false;
  2940. }
  2941. if ((!newRoute.children || newRoute.children.length === 0) && (!existingRoute.children || existingRoute.children.length === 0)) {
  2942. return true;
  2943. }
  2944. return newRoute.children.every((aChild, i) => {
  2945. var _existingRoute$childr;
  2946. return (_existingRoute$childr = existingRoute.children) == null ? void 0 : _existingRoute$childr.some((bChild) => isSameRoute(aChild, bChild));
  2947. });
  2948. }
  2949. async function loadLazyRouteModule(route, mapRouteProperties2, manifest) {
  2950. if (!route.lazy) {
  2951. return;
  2952. }
  2953. let lazyRoute = await route.lazy();
  2954. if (!route.lazy) {
  2955. return;
  2956. }
  2957. let routeToUpdate = manifest[route.id];
  2958. invariant(routeToUpdate, "No route found in manifest");
  2959. let routeUpdates = {};
  2960. for (let lazyRouteProperty in lazyRoute) {
  2961. let staticRouteValue = routeToUpdate[lazyRouteProperty];
  2962. let isPropertyStaticallyDefined = staticRouteValue !== void 0 && // This property isn't static since it should always be updated based
  2963. // on the route updates
  2964. lazyRouteProperty !== "hasErrorBoundary";
  2965. warning(!isPropertyStaticallyDefined, 'Route "' + routeToUpdate.id + '" has a static property "' + lazyRouteProperty + '" defined but its lazy function is also returning a value for this property. ' + ('The lazy route property "' + lazyRouteProperty + '" will be ignored.'));
  2966. if (!isPropertyStaticallyDefined && !immutableRouteKeys.has(lazyRouteProperty)) {
  2967. routeUpdates[lazyRouteProperty] = lazyRoute[lazyRouteProperty];
  2968. }
  2969. }
  2970. Object.assign(routeToUpdate, routeUpdates);
  2971. Object.assign(routeToUpdate, _extends({}, mapRouteProperties2(routeToUpdate), {
  2972. lazy: void 0
  2973. }));
  2974. }
  2975. async function defaultDataStrategy(_ref4) {
  2976. let {
  2977. matches
  2978. } = _ref4;
  2979. let matchesToLoad = matches.filter((m) => m.shouldLoad);
  2980. let results = await Promise.all(matchesToLoad.map((m) => m.resolve()));
  2981. return results.reduce((acc, result, i) => Object.assign(acc, {
  2982. [matchesToLoad[i].route.id]: result
  2983. }), {});
  2984. }
  2985. async function callDataStrategyImpl(dataStrategyImpl, type, state, request, matchesToLoad, matches, fetcherKey, manifest, mapRouteProperties2, requestContext) {
  2986. let loadRouteDefinitionsPromises = matches.map((m) => m.route.lazy ? loadLazyRouteModule(m.route, mapRouteProperties2, manifest) : void 0);
  2987. let dsMatches = matches.map((match, i) => {
  2988. let loadRoutePromise = loadRouteDefinitionsPromises[i];
  2989. let shouldLoad = matchesToLoad.some((m) => m.route.id === match.route.id);
  2990. let resolve = async (handlerOverride) => {
  2991. if (handlerOverride && request.method === "GET" && (match.route.lazy || match.route.loader)) {
  2992. shouldLoad = true;
  2993. }
  2994. return shouldLoad ? callLoaderOrAction(type, request, match, loadRoutePromise, handlerOverride, requestContext) : Promise.resolve({
  2995. type: ResultType.data,
  2996. result: void 0
  2997. });
  2998. };
  2999. return _extends({}, match, {
  3000. shouldLoad,
  3001. resolve
  3002. });
  3003. });
  3004. let results = await dataStrategyImpl({
  3005. matches: dsMatches,
  3006. request,
  3007. params: matches[0].params,
  3008. fetcherKey,
  3009. context: requestContext
  3010. });
  3011. try {
  3012. await Promise.all(loadRouteDefinitionsPromises);
  3013. } catch (e) {
  3014. }
  3015. return results;
  3016. }
  3017. async function callLoaderOrAction(type, request, match, loadRoutePromise, handlerOverride, staticContext) {
  3018. let result;
  3019. let onReject;
  3020. let runHandler = (handler) => {
  3021. let reject;
  3022. let abortPromise = new Promise((_, r) => reject = r);
  3023. onReject = () => reject();
  3024. request.signal.addEventListener("abort", onReject);
  3025. let actualHandler = (ctx) => {
  3026. if (typeof handler !== "function") {
  3027. return Promise.reject(new Error("You cannot call the handler for a route which defines a boolean " + ('"' + type + '" [routeId: ' + match.route.id + "]")));
  3028. }
  3029. return handler({
  3030. request,
  3031. params: match.params,
  3032. context: staticContext
  3033. }, ...ctx !== void 0 ? [ctx] : []);
  3034. };
  3035. let handlerPromise = (async () => {
  3036. try {
  3037. let val = await (handlerOverride ? handlerOverride((ctx) => actualHandler(ctx)) : actualHandler());
  3038. return {
  3039. type: "data",
  3040. result: val
  3041. };
  3042. } catch (e) {
  3043. return {
  3044. type: "error",
  3045. result: e
  3046. };
  3047. }
  3048. })();
  3049. return Promise.race([handlerPromise, abortPromise]);
  3050. };
  3051. try {
  3052. let handler = match.route[type];
  3053. if (loadRoutePromise) {
  3054. if (handler) {
  3055. let handlerError;
  3056. let [value] = await Promise.all([
  3057. // If the handler throws, don't let it immediately bubble out,
  3058. // since we need to let the lazy() execution finish so we know if this
  3059. // route has a boundary that can handle the error
  3060. runHandler(handler).catch((e) => {
  3061. handlerError = e;
  3062. }),
  3063. loadRoutePromise
  3064. ]);
  3065. if (handlerError !== void 0) {
  3066. throw handlerError;
  3067. }
  3068. result = value;
  3069. } else {
  3070. await loadRoutePromise;
  3071. handler = match.route[type];
  3072. if (handler) {
  3073. result = await runHandler(handler);
  3074. } else if (type === "action") {
  3075. let url = new URL(request.url);
  3076. let pathname = url.pathname + url.search;
  3077. throw getInternalRouterError(405, {
  3078. method: request.method,
  3079. pathname,
  3080. routeId: match.route.id
  3081. });
  3082. } else {
  3083. return {
  3084. type: ResultType.data,
  3085. result: void 0
  3086. };
  3087. }
  3088. }
  3089. } else if (!handler) {
  3090. let url = new URL(request.url);
  3091. let pathname = url.pathname + url.search;
  3092. throw getInternalRouterError(404, {
  3093. pathname
  3094. });
  3095. } else {
  3096. result = await runHandler(handler);
  3097. }
  3098. invariant(result.result !== void 0, "You defined " + (type === "action" ? "an action" : "a loader") + " for route " + ('"' + match.route.id + "\" but didn't return anything from your `" + type + "` ") + "function. Please return a value or `null`.");
  3099. } catch (e) {
  3100. return {
  3101. type: ResultType.error,
  3102. result: e
  3103. };
  3104. } finally {
  3105. if (onReject) {
  3106. request.signal.removeEventListener("abort", onReject);
  3107. }
  3108. }
  3109. return result;
  3110. }
  3111. async function convertDataStrategyResultToDataResult(dataStrategyResult) {
  3112. let {
  3113. result,
  3114. type
  3115. } = dataStrategyResult;
  3116. if (isResponse(result)) {
  3117. let data;
  3118. try {
  3119. let contentType = result.headers.get("Content-Type");
  3120. if (contentType && /\bapplication\/json\b/.test(contentType)) {
  3121. if (result.body == null) {
  3122. data = null;
  3123. } else {
  3124. data = await result.json();
  3125. }
  3126. } else {
  3127. data = await result.text();
  3128. }
  3129. } catch (e) {
  3130. return {
  3131. type: ResultType.error,
  3132. error: e
  3133. };
  3134. }
  3135. if (type === ResultType.error) {
  3136. return {
  3137. type: ResultType.error,
  3138. error: new ErrorResponseImpl(result.status, result.statusText, data),
  3139. statusCode: result.status,
  3140. headers: result.headers
  3141. };
  3142. }
  3143. return {
  3144. type: ResultType.data,
  3145. data,
  3146. statusCode: result.status,
  3147. headers: result.headers
  3148. };
  3149. }
  3150. if (type === ResultType.error) {
  3151. if (isDataWithResponseInit(result)) {
  3152. var _result$init3, _result$init4;
  3153. if (result.data instanceof Error) {
  3154. var _result$init, _result$init2;
  3155. return {
  3156. type: ResultType.error,
  3157. error: result.data,
  3158. statusCode: (_result$init = result.init) == null ? void 0 : _result$init.status,
  3159. headers: (_result$init2 = result.init) != null && _result$init2.headers ? new Headers(result.init.headers) : void 0
  3160. };
  3161. }
  3162. return {
  3163. type: ResultType.error,
  3164. error: new ErrorResponseImpl(((_result$init3 = result.init) == null ? void 0 : _result$init3.status) || 500, void 0, result.data),
  3165. statusCode: isRouteErrorResponse(result) ? result.status : void 0,
  3166. headers: (_result$init4 = result.init) != null && _result$init4.headers ? new Headers(result.init.headers) : void 0
  3167. };
  3168. }
  3169. return {
  3170. type: ResultType.error,
  3171. error: result,
  3172. statusCode: isRouteErrorResponse(result) ? result.status : void 0
  3173. };
  3174. }
  3175. if (isDeferredData(result)) {
  3176. var _result$init5, _result$init6;
  3177. return {
  3178. type: ResultType.deferred,
  3179. deferredData: result,
  3180. statusCode: (_result$init5 = result.init) == null ? void 0 : _result$init5.status,
  3181. headers: ((_result$init6 = result.init) == null ? void 0 : _result$init6.headers) && new Headers(result.init.headers)
  3182. };
  3183. }
  3184. if (isDataWithResponseInit(result)) {
  3185. var _result$init7, _result$init8;
  3186. return {
  3187. type: ResultType.data,
  3188. data: result.data,
  3189. statusCode: (_result$init7 = result.init) == null ? void 0 : _result$init7.status,
  3190. headers: (_result$init8 = result.init) != null && _result$init8.headers ? new Headers(result.init.headers) : void 0
  3191. };
  3192. }
  3193. return {
  3194. type: ResultType.data,
  3195. data: result
  3196. };
  3197. }
  3198. function normalizeRelativeRoutingRedirectResponse(response, request, routeId, matches, basename, v7_relativeSplatPath) {
  3199. let location = response.headers.get("Location");
  3200. invariant(location, "Redirects returned/thrown from loaders/actions must have a Location header");
  3201. if (!ABSOLUTE_URL_REGEX.test(location)) {
  3202. let trimmedMatches = matches.slice(0, matches.findIndex((m) => m.route.id === routeId) + 1);
  3203. location = normalizeTo(new URL(request.url), trimmedMatches, basename, true, location, v7_relativeSplatPath);
  3204. response.headers.set("Location", location);
  3205. }
  3206. return response;
  3207. }
  3208. function normalizeRedirectLocation(location, currentUrl, basename, historyInstance) {
  3209. let invalidProtocols = [
  3210. "about:",
  3211. "blob:",
  3212. "chrome:",
  3213. "chrome-untrusted:",
  3214. "content:",
  3215. "data:",
  3216. "devtools:",
  3217. "file:",
  3218. "filesystem:",
  3219. // eslint-disable-next-line no-script-url
  3220. "javascript:"
  3221. ];
  3222. if (ABSOLUTE_URL_REGEX.test(location)) {
  3223. let normalizedLocation = location;
  3224. let url = normalizedLocation.startsWith("//") ? new URL(currentUrl.protocol + normalizedLocation) : new URL(normalizedLocation);
  3225. if (invalidProtocols.includes(url.protocol)) {
  3226. throw new Error("Invalid redirect location");
  3227. }
  3228. let isSameBasename = stripBasename(url.pathname, basename) != null;
  3229. if (url.origin === currentUrl.origin && isSameBasename) {
  3230. return url.pathname + url.search + url.hash;
  3231. }
  3232. }
  3233. try {
  3234. let url = historyInstance.createURL(location);
  3235. if (invalidProtocols.includes(url.protocol)) {
  3236. throw new Error("Invalid redirect location");
  3237. }
  3238. } catch (e) {
  3239. }
  3240. return location;
  3241. }
  3242. function createClientSideRequest(history, location, signal, submission) {
  3243. let url = history.createURL(stripHashFromPath(location)).toString();
  3244. let init = {
  3245. signal
  3246. };
  3247. if (submission && isMutationMethod(submission.formMethod)) {
  3248. let {
  3249. formMethod,
  3250. formEncType
  3251. } = submission;
  3252. init.method = formMethod.toUpperCase();
  3253. if (formEncType === "application/json") {
  3254. init.headers = new Headers({
  3255. "Content-Type": formEncType
  3256. });
  3257. init.body = JSON.stringify(submission.json);
  3258. } else if (formEncType === "text/plain") {
  3259. init.body = submission.text;
  3260. } else if (formEncType === "application/x-www-form-urlencoded" && submission.formData) {
  3261. init.body = convertFormDataToSearchParams(submission.formData);
  3262. } else {
  3263. init.body = submission.formData;
  3264. }
  3265. }
  3266. return new Request(url, init);
  3267. }
  3268. function convertFormDataToSearchParams(formData) {
  3269. let searchParams = new URLSearchParams();
  3270. for (let [key, value] of formData.entries()) {
  3271. searchParams.append(key, typeof value === "string" ? value : value.name);
  3272. }
  3273. return searchParams;
  3274. }
  3275. function convertSearchParamsToFormData(searchParams) {
  3276. let formData = new FormData();
  3277. for (let [key, value] of searchParams.entries()) {
  3278. formData.append(key, value);
  3279. }
  3280. return formData;
  3281. }
  3282. function processRouteLoaderData(matches, results, pendingActionResult, activeDeferreds, skipLoaderErrorBubbling) {
  3283. let loaderData = {};
  3284. let errors = null;
  3285. let statusCode;
  3286. let foundError = false;
  3287. let loaderHeaders = {};
  3288. let pendingError = pendingActionResult && isErrorResult(pendingActionResult[1]) ? pendingActionResult[1].error : void 0;
  3289. matches.forEach((match) => {
  3290. if (!(match.route.id in results)) {
  3291. return;
  3292. }
  3293. let id = match.route.id;
  3294. let result = results[id];
  3295. invariant(!isRedirectResult(result), "Cannot handle redirect results in processLoaderData");
  3296. if (isErrorResult(result)) {
  3297. let error = result.error;
  3298. if (pendingError !== void 0) {
  3299. error = pendingError;
  3300. pendingError = void 0;
  3301. }
  3302. errors = errors || {};
  3303. if (skipLoaderErrorBubbling) {
  3304. errors[id] = error;
  3305. } else {
  3306. let boundaryMatch = findNearestBoundary(matches, id);
  3307. if (errors[boundaryMatch.route.id] == null) {
  3308. errors[boundaryMatch.route.id] = error;
  3309. }
  3310. }
  3311. loaderData[id] = void 0;
  3312. if (!foundError) {
  3313. foundError = true;
  3314. statusCode = isRouteErrorResponse(result.error) ? result.error.status : 500;
  3315. }
  3316. if (result.headers) {
  3317. loaderHeaders[id] = result.headers;
  3318. }
  3319. } else {
  3320. if (isDeferredResult(result)) {
  3321. activeDeferreds.set(id, result.deferredData);
  3322. loaderData[id] = result.deferredData.data;
  3323. if (result.statusCode != null && result.statusCode !== 200 && !foundError) {
  3324. statusCode = result.statusCode;
  3325. }
  3326. if (result.headers) {
  3327. loaderHeaders[id] = result.headers;
  3328. }
  3329. } else {
  3330. loaderData[id] = result.data;
  3331. if (result.statusCode && result.statusCode !== 200 && !foundError) {
  3332. statusCode = result.statusCode;
  3333. }
  3334. if (result.headers) {
  3335. loaderHeaders[id] = result.headers;
  3336. }
  3337. }
  3338. }
  3339. });
  3340. if (pendingError !== void 0 && pendingActionResult) {
  3341. errors = {
  3342. [pendingActionResult[0]]: pendingError
  3343. };
  3344. loaderData[pendingActionResult[0]] = void 0;
  3345. }
  3346. return {
  3347. loaderData,
  3348. errors,
  3349. statusCode: statusCode || 200,
  3350. loaderHeaders
  3351. };
  3352. }
  3353. function processLoaderData(state, matches, results, pendingActionResult, revalidatingFetchers, fetcherResults, activeDeferreds) {
  3354. let {
  3355. loaderData,
  3356. errors
  3357. } = processRouteLoaderData(
  3358. matches,
  3359. results,
  3360. pendingActionResult,
  3361. activeDeferreds,
  3362. false
  3363. // This method is only called client side so we always want to bubble
  3364. );
  3365. revalidatingFetchers.forEach((rf) => {
  3366. let {
  3367. key,
  3368. match,
  3369. controller
  3370. } = rf;
  3371. let result = fetcherResults[key];
  3372. invariant(result, "Did not find corresponding fetcher result");
  3373. if (controller && controller.signal.aborted) {
  3374. return;
  3375. } else if (isErrorResult(result)) {
  3376. let boundaryMatch = findNearestBoundary(state.matches, match == null ? void 0 : match.route.id);
  3377. if (!(errors && errors[boundaryMatch.route.id])) {
  3378. errors = _extends({}, errors, {
  3379. [boundaryMatch.route.id]: result.error
  3380. });
  3381. }
  3382. state.fetchers.delete(key);
  3383. } else if (isRedirectResult(result)) {
  3384. invariant(false, "Unhandled fetcher revalidation redirect");
  3385. } else if (isDeferredResult(result)) {
  3386. invariant(false, "Unhandled fetcher deferred data");
  3387. } else {
  3388. let doneFetcher = getDoneFetcher(result.data);
  3389. state.fetchers.set(key, doneFetcher);
  3390. }
  3391. });
  3392. return {
  3393. loaderData,
  3394. errors
  3395. };
  3396. }
  3397. function mergeLoaderData(loaderData, newLoaderData, matches, errors) {
  3398. let mergedLoaderData = _extends({}, newLoaderData);
  3399. for (let match of matches) {
  3400. let id = match.route.id;
  3401. if (newLoaderData.hasOwnProperty(id)) {
  3402. if (newLoaderData[id] !== void 0) {
  3403. mergedLoaderData[id] = newLoaderData[id];
  3404. }
  3405. } else if (loaderData[id] !== void 0 && match.route.loader) {
  3406. mergedLoaderData[id] = loaderData[id];
  3407. }
  3408. if (errors && errors.hasOwnProperty(id)) {
  3409. break;
  3410. }
  3411. }
  3412. return mergedLoaderData;
  3413. }
  3414. function getActionDataForCommit(pendingActionResult) {
  3415. if (!pendingActionResult) {
  3416. return {};
  3417. }
  3418. return isErrorResult(pendingActionResult[1]) ? {
  3419. // Clear out prior actionData on errors
  3420. actionData: {}
  3421. } : {
  3422. actionData: {
  3423. [pendingActionResult[0]]: pendingActionResult[1].data
  3424. }
  3425. };
  3426. }
  3427. function findNearestBoundary(matches, routeId) {
  3428. let eligibleMatches = routeId ? matches.slice(0, matches.findIndex((m) => m.route.id === routeId) + 1) : [...matches];
  3429. return eligibleMatches.reverse().find((m) => m.route.hasErrorBoundary === true) || matches[0];
  3430. }
  3431. function getShortCircuitMatches(routes) {
  3432. let route = routes.length === 1 ? routes[0] : routes.find((r) => r.index || !r.path || r.path === "/") || {
  3433. id: "__shim-error-route__"
  3434. };
  3435. return {
  3436. matches: [{
  3437. params: {},
  3438. pathname: "",
  3439. pathnameBase: "",
  3440. route
  3441. }],
  3442. route
  3443. };
  3444. }
  3445. function getInternalRouterError(status, _temp5) {
  3446. let {
  3447. pathname,
  3448. routeId,
  3449. method,
  3450. type,
  3451. message
  3452. } = _temp5 === void 0 ? {} : _temp5;
  3453. let statusText = "Unknown Server Error";
  3454. let errorMessage = "Unknown @remix-run/router error";
  3455. if (status === 400) {
  3456. statusText = "Bad Request";
  3457. if (method && pathname && routeId) {
  3458. 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.";
  3459. } else if (type === "defer-action") {
  3460. errorMessage = "defer() is not supported in actions";
  3461. } else if (type === "invalid-body") {
  3462. errorMessage = "Unable to encode submission body";
  3463. }
  3464. } else if (status === 403) {
  3465. statusText = "Forbidden";
  3466. errorMessage = 'Route "' + routeId + '" does not match URL "' + pathname + '"';
  3467. } else if (status === 404) {
  3468. statusText = "Not Found";
  3469. errorMessage = 'No route matches URL "' + pathname + '"';
  3470. } else if (status === 405) {
  3471. statusText = "Method Not Allowed";
  3472. if (method && pathname && routeId) {
  3473. 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.";
  3474. } else if (method) {
  3475. errorMessage = 'Invalid request method "' + method.toUpperCase() + '"';
  3476. }
  3477. }
  3478. return new ErrorResponseImpl(status || 500, statusText, new Error(errorMessage), true);
  3479. }
  3480. function findRedirect(results) {
  3481. let entries = Object.entries(results);
  3482. for (let i = entries.length - 1; i >= 0; i--) {
  3483. let [key, result] = entries[i];
  3484. if (isRedirectResult(result)) {
  3485. return {
  3486. key,
  3487. result
  3488. };
  3489. }
  3490. }
  3491. }
  3492. function stripHashFromPath(path) {
  3493. let parsedPath = typeof path === "string" ? parsePath(path) : path;
  3494. return createPath(_extends({}, parsedPath, {
  3495. hash: ""
  3496. }));
  3497. }
  3498. function isHashChangeOnly(a, b) {
  3499. if (a.pathname !== b.pathname || a.search !== b.search) {
  3500. return false;
  3501. }
  3502. if (a.hash === "") {
  3503. return b.hash !== "";
  3504. } else if (a.hash === b.hash) {
  3505. return true;
  3506. } else if (b.hash !== "") {
  3507. return true;
  3508. }
  3509. return false;
  3510. }
  3511. function isRedirectDataStrategyResultResult(result) {
  3512. return isResponse(result.result) && redirectStatusCodes.has(result.result.status);
  3513. }
  3514. function isDeferredResult(result) {
  3515. return result.type === ResultType.deferred;
  3516. }
  3517. function isErrorResult(result) {
  3518. return result.type === ResultType.error;
  3519. }
  3520. function isRedirectResult(result) {
  3521. return (result && result.type) === ResultType.redirect;
  3522. }
  3523. function isDataWithResponseInit(value) {
  3524. return typeof value === "object" && value != null && "type" in value && "data" in value && "init" in value && value.type === "DataWithResponseInit";
  3525. }
  3526. function isDeferredData(value) {
  3527. let deferred = value;
  3528. return deferred && typeof deferred === "object" && typeof deferred.data === "object" && typeof deferred.subscribe === "function" && typeof deferred.cancel === "function" && typeof deferred.resolveData === "function";
  3529. }
  3530. function isResponse(value) {
  3531. return value != null && typeof value.status === "number" && typeof value.statusText === "string" && typeof value.headers === "object" && typeof value.body !== "undefined";
  3532. }
  3533. function isValidMethod(method) {
  3534. return validRequestMethods.has(method.toLowerCase());
  3535. }
  3536. function isMutationMethod(method) {
  3537. return validMutationMethods.has(method.toLowerCase());
  3538. }
  3539. async function resolveNavigationDeferredResults(matches, results, signal, currentMatches, currentLoaderData) {
  3540. let entries = Object.entries(results);
  3541. for (let index = 0; index < entries.length; index++) {
  3542. let [routeId, result] = entries[index];
  3543. let match = matches.find((m) => (m == null ? void 0 : m.route.id) === routeId);
  3544. if (!match) {
  3545. continue;
  3546. }
  3547. let currentMatch = currentMatches.find((m) => m.route.id === match.route.id);
  3548. let isRevalidatingLoader = currentMatch != null && !isNewRouteInstance(currentMatch, match) && (currentLoaderData && currentLoaderData[match.route.id]) !== void 0;
  3549. if (isDeferredResult(result) && isRevalidatingLoader) {
  3550. await resolveDeferredData(result, signal, false).then((result2) => {
  3551. if (result2) {
  3552. results[routeId] = result2;
  3553. }
  3554. });
  3555. }
  3556. }
  3557. }
  3558. async function resolveFetcherDeferredResults(matches, results, revalidatingFetchers) {
  3559. for (let index = 0; index < revalidatingFetchers.length; index++) {
  3560. let {
  3561. key,
  3562. routeId,
  3563. controller
  3564. } = revalidatingFetchers[index];
  3565. let result = results[key];
  3566. let match = matches.find((m) => (m == null ? void 0 : m.route.id) === routeId);
  3567. if (!match) {
  3568. continue;
  3569. }
  3570. if (isDeferredResult(result)) {
  3571. invariant(controller, "Expected an AbortController for revalidating fetcher deferred result");
  3572. await resolveDeferredData(result, controller.signal, true).then((result2) => {
  3573. if (result2) {
  3574. results[key] = result2;
  3575. }
  3576. });
  3577. }
  3578. }
  3579. }
  3580. async function resolveDeferredData(result, signal, unwrap) {
  3581. if (unwrap === void 0) {
  3582. unwrap = false;
  3583. }
  3584. let aborted = await result.deferredData.resolveData(signal);
  3585. if (aborted) {
  3586. return;
  3587. }
  3588. if (unwrap) {
  3589. try {
  3590. return {
  3591. type: ResultType.data,
  3592. data: result.deferredData.unwrappedData
  3593. };
  3594. } catch (e) {
  3595. return {
  3596. type: ResultType.error,
  3597. error: e
  3598. };
  3599. }
  3600. }
  3601. return {
  3602. type: ResultType.data,
  3603. data: result.deferredData.data
  3604. };
  3605. }
  3606. function hasNakedIndexQuery(search) {
  3607. return new URLSearchParams(search).getAll("index").some((v) => v === "");
  3608. }
  3609. function getTargetMatch(matches, location) {
  3610. let search = typeof location === "string" ? parsePath(location).search : location.search;
  3611. if (matches[matches.length - 1].route.index && hasNakedIndexQuery(search || "")) {
  3612. return matches[matches.length - 1];
  3613. }
  3614. let pathMatches = getPathContributingMatches(matches);
  3615. return pathMatches[pathMatches.length - 1];
  3616. }
  3617. function getSubmissionFromNavigation(navigation) {
  3618. let {
  3619. formMethod,
  3620. formAction,
  3621. formEncType,
  3622. text,
  3623. formData,
  3624. json: json3
  3625. } = navigation;
  3626. if (!formMethod || !formAction || !formEncType) {
  3627. return;
  3628. }
  3629. if (text != null) {
  3630. return {
  3631. formMethod,
  3632. formAction,
  3633. formEncType,
  3634. formData: void 0,
  3635. json: void 0,
  3636. text
  3637. };
  3638. } else if (formData != null) {
  3639. return {
  3640. formMethod,
  3641. formAction,
  3642. formEncType,
  3643. formData,
  3644. json: void 0,
  3645. text: void 0
  3646. };
  3647. } else if (json3 !== void 0) {
  3648. return {
  3649. formMethod,
  3650. formAction,
  3651. formEncType,
  3652. formData: void 0,
  3653. json: json3,
  3654. text: void 0
  3655. };
  3656. }
  3657. }
  3658. function getLoadingNavigation(location, submission) {
  3659. if (submission) {
  3660. let navigation = {
  3661. state: "loading",
  3662. location,
  3663. formMethod: submission.formMethod,
  3664. formAction: submission.formAction,
  3665. formEncType: submission.formEncType,
  3666. formData: submission.formData,
  3667. json: submission.json,
  3668. text: submission.text
  3669. };
  3670. return navigation;
  3671. } else {
  3672. let navigation = {
  3673. state: "loading",
  3674. location,
  3675. formMethod: void 0,
  3676. formAction: void 0,
  3677. formEncType: void 0,
  3678. formData: void 0,
  3679. json: void 0,
  3680. text: void 0
  3681. };
  3682. return navigation;
  3683. }
  3684. }
  3685. function getSubmittingNavigation(location, submission) {
  3686. let navigation = {
  3687. state: "submitting",
  3688. location,
  3689. formMethod: submission.formMethod,
  3690. formAction: submission.formAction,
  3691. formEncType: submission.formEncType,
  3692. formData: submission.formData,
  3693. json: submission.json,
  3694. text: submission.text
  3695. };
  3696. return navigation;
  3697. }
  3698. function getLoadingFetcher(submission, data) {
  3699. if (submission) {
  3700. let fetcher = {
  3701. state: "loading",
  3702. formMethod: submission.formMethod,
  3703. formAction: submission.formAction,
  3704. formEncType: submission.formEncType,
  3705. formData: submission.formData,
  3706. json: submission.json,
  3707. text: submission.text,
  3708. data
  3709. };
  3710. return fetcher;
  3711. } else {
  3712. let fetcher = {
  3713. state: "loading",
  3714. formMethod: void 0,
  3715. formAction: void 0,
  3716. formEncType: void 0,
  3717. formData: void 0,
  3718. json: void 0,
  3719. text: void 0,
  3720. data
  3721. };
  3722. return fetcher;
  3723. }
  3724. }
  3725. function getSubmittingFetcher(submission, existingFetcher) {
  3726. let fetcher = {
  3727. state: "submitting",
  3728. formMethod: submission.formMethod,
  3729. formAction: submission.formAction,
  3730. formEncType: submission.formEncType,
  3731. formData: submission.formData,
  3732. json: submission.json,
  3733. text: submission.text,
  3734. data: existingFetcher ? existingFetcher.data : void 0
  3735. };
  3736. return fetcher;
  3737. }
  3738. function getDoneFetcher(data) {
  3739. let fetcher = {
  3740. state: "idle",
  3741. formMethod: void 0,
  3742. formAction: void 0,
  3743. formEncType: void 0,
  3744. formData: void 0,
  3745. json: void 0,
  3746. text: void 0,
  3747. data
  3748. };
  3749. return fetcher;
  3750. }
  3751. function restoreAppliedTransitions(_window, transitions) {
  3752. try {
  3753. let sessionPositions = _window.sessionStorage.getItem(TRANSITIONS_STORAGE_KEY);
  3754. if (sessionPositions) {
  3755. let json3 = JSON.parse(sessionPositions);
  3756. for (let [k, v] of Object.entries(json3 || {})) {
  3757. if (v && Array.isArray(v)) {
  3758. transitions.set(k, new Set(v || []));
  3759. }
  3760. }
  3761. }
  3762. } catch (e) {
  3763. }
  3764. }
  3765. function persistAppliedTransitions(_window, transitions) {
  3766. if (transitions.size > 0) {
  3767. let json3 = {};
  3768. for (let [k, v] of transitions) {
  3769. json3[k] = [...v];
  3770. }
  3771. try {
  3772. _window.sessionStorage.setItem(TRANSITIONS_STORAGE_KEY, JSON.stringify(json3));
  3773. } catch (error) {
  3774. warning(false, "Failed to save applied view transitions in sessionStorage (" + error + ").");
  3775. }
  3776. }
  3777. }
  3778. // node_modules/react-router/dist/index.js
  3779. function _extends2() {
  3780. _extends2 = Object.assign ? Object.assign.bind() : function(target) {
  3781. for (var i = 1; i < arguments.length; i++) {
  3782. var source = arguments[i];
  3783. for (var key in source) {
  3784. if (Object.prototype.hasOwnProperty.call(source, key)) {
  3785. target[key] = source[key];
  3786. }
  3787. }
  3788. }
  3789. return target;
  3790. };
  3791. return _extends2.apply(this, arguments);
  3792. }
  3793. var DataRouterContext = React.createContext(null);
  3794. if (true) {
  3795. DataRouterContext.displayName = "DataRouter";
  3796. }
  3797. var DataRouterStateContext = React.createContext(null);
  3798. if (true) {
  3799. DataRouterStateContext.displayName = "DataRouterState";
  3800. }
  3801. var AwaitContext = React.createContext(null);
  3802. if (true) {
  3803. AwaitContext.displayName = "Await";
  3804. }
  3805. var NavigationContext = React.createContext(null);
  3806. if (true) {
  3807. NavigationContext.displayName = "Navigation";
  3808. }
  3809. var LocationContext = React.createContext(null);
  3810. if (true) {
  3811. LocationContext.displayName = "Location";
  3812. }
  3813. var RouteContext = React.createContext({
  3814. outlet: null,
  3815. matches: [],
  3816. isDataRoute: false
  3817. });
  3818. if (true) {
  3819. RouteContext.displayName = "Route";
  3820. }
  3821. var RouteErrorContext = React.createContext(null);
  3822. if (true) {
  3823. RouteErrorContext.displayName = "RouteError";
  3824. }
  3825. function useHref(to, _temp) {
  3826. let {
  3827. relative
  3828. } = _temp === void 0 ? {} : _temp;
  3829. !useInRouterContext() ? true ? invariant(
  3830. false,
  3831. // TODO: This error is probably because they somehow have 2 versions of the
  3832. // router loaded. We can help them understand how to avoid that.
  3833. "useHref() may be used only in the context of a <Router> component."
  3834. ) : invariant(false) : void 0;
  3835. let {
  3836. basename,
  3837. navigator
  3838. } = React.useContext(NavigationContext);
  3839. let {
  3840. hash,
  3841. pathname,
  3842. search
  3843. } = useResolvedPath(to, {
  3844. relative
  3845. });
  3846. let joinedPathname = pathname;
  3847. if (basename !== "/") {
  3848. joinedPathname = pathname === "/" ? basename : joinPaths([basename, pathname]);
  3849. }
  3850. return navigator.createHref({
  3851. pathname: joinedPathname,
  3852. search,
  3853. hash
  3854. });
  3855. }
  3856. function useInRouterContext() {
  3857. return React.useContext(LocationContext) != null;
  3858. }
  3859. function useLocation() {
  3860. !useInRouterContext() ? true ? invariant(
  3861. false,
  3862. // TODO: This error is probably because they somehow have 2 versions of the
  3863. // router loaded. We can help them understand how to avoid that.
  3864. "useLocation() may be used only in the context of a <Router> component."
  3865. ) : invariant(false) : void 0;
  3866. return React.useContext(LocationContext).location;
  3867. }
  3868. function useNavigationType() {
  3869. return React.useContext(LocationContext).navigationType;
  3870. }
  3871. function useMatch(pattern) {
  3872. !useInRouterContext() ? true ? invariant(
  3873. false,
  3874. // TODO: This error is probably because they somehow have 2 versions of the
  3875. // router loaded. We can help them understand how to avoid that.
  3876. "useMatch() may be used only in the context of a <Router> component."
  3877. ) : invariant(false) : void 0;
  3878. let {
  3879. pathname
  3880. } = useLocation();
  3881. return React.useMemo(() => matchPath(pattern, decodePath(pathname)), [pathname, pattern]);
  3882. }
  3883. var navigateEffectWarning = "You should call navigate() in a React.useEffect(), not when your component is first rendered.";
  3884. function useIsomorphicLayoutEffect(cb) {
  3885. let isStatic = React.useContext(NavigationContext).static;
  3886. if (!isStatic) {
  3887. React.useLayoutEffect(cb);
  3888. }
  3889. }
  3890. function useNavigate() {
  3891. let {
  3892. isDataRoute
  3893. } = React.useContext(RouteContext);
  3894. return isDataRoute ? useNavigateStable() : useNavigateUnstable();
  3895. }
  3896. function useNavigateUnstable() {
  3897. !useInRouterContext() ? true ? invariant(
  3898. false,
  3899. // TODO: This error is probably because they somehow have 2 versions of the
  3900. // router loaded. We can help them understand how to avoid that.
  3901. "useNavigate() may be used only in the context of a <Router> component."
  3902. ) : invariant(false) : void 0;
  3903. let dataRouterContext = React.useContext(DataRouterContext);
  3904. let {
  3905. basename,
  3906. future,
  3907. navigator
  3908. } = React.useContext(NavigationContext);
  3909. let {
  3910. matches
  3911. } = React.useContext(RouteContext);
  3912. let {
  3913. pathname: locationPathname
  3914. } = useLocation();
  3915. let routePathnamesJson = JSON.stringify(getResolveToMatches(matches, future.v7_relativeSplatPath));
  3916. let activeRef = React.useRef(false);
  3917. useIsomorphicLayoutEffect(() => {
  3918. activeRef.current = true;
  3919. });
  3920. let navigate = React.useCallback(function(to, options) {
  3921. if (options === void 0) {
  3922. options = {};
  3923. }
  3924. true ? warning(activeRef.current, navigateEffectWarning) : void 0;
  3925. if (!activeRef.current) return;
  3926. if (typeof to === "number") {
  3927. navigator.go(to);
  3928. return;
  3929. }
  3930. let path = resolveTo(to, JSON.parse(routePathnamesJson), locationPathname, options.relative === "path");
  3931. if (dataRouterContext == null && basename !== "/") {
  3932. path.pathname = path.pathname === "/" ? basename : joinPaths([basename, path.pathname]);
  3933. }
  3934. (!!options.replace ? navigator.replace : navigator.push)(path, options.state, options);
  3935. }, [basename, navigator, routePathnamesJson, locationPathname, dataRouterContext]);
  3936. return navigate;
  3937. }
  3938. var OutletContext = React.createContext(null);
  3939. function useOutletContext() {
  3940. return React.useContext(OutletContext);
  3941. }
  3942. function useOutlet(context) {
  3943. let outlet = React.useContext(RouteContext).outlet;
  3944. if (outlet) {
  3945. return React.createElement(OutletContext.Provider, {
  3946. value: context
  3947. }, outlet);
  3948. }
  3949. return outlet;
  3950. }
  3951. function useParams() {
  3952. let {
  3953. matches
  3954. } = React.useContext(RouteContext);
  3955. let routeMatch = matches[matches.length - 1];
  3956. return routeMatch ? routeMatch.params : {};
  3957. }
  3958. function useResolvedPath(to, _temp2) {
  3959. let {
  3960. relative
  3961. } = _temp2 === void 0 ? {} : _temp2;
  3962. let {
  3963. future
  3964. } = React.useContext(NavigationContext);
  3965. let {
  3966. matches
  3967. } = React.useContext(RouteContext);
  3968. let {
  3969. pathname: locationPathname
  3970. } = useLocation();
  3971. let routePathnamesJson = JSON.stringify(getResolveToMatches(matches, future.v7_relativeSplatPath));
  3972. return React.useMemo(() => resolveTo(to, JSON.parse(routePathnamesJson), locationPathname, relative === "path"), [to, routePathnamesJson, locationPathname, relative]);
  3973. }
  3974. function useRoutes(routes, locationArg) {
  3975. return useRoutesImpl(routes, locationArg);
  3976. }
  3977. function useRoutesImpl(routes, locationArg, dataRouterState, future) {
  3978. !useInRouterContext() ? true ? invariant(
  3979. false,
  3980. // TODO: This error is probably because they somehow have 2 versions of the
  3981. // router loaded. We can help them understand how to avoid that.
  3982. "useRoutes() may be used only in the context of a <Router> component."
  3983. ) : invariant(false) : void 0;
  3984. let {
  3985. navigator
  3986. } = React.useContext(NavigationContext);
  3987. let {
  3988. matches: parentMatches
  3989. } = React.useContext(RouteContext);
  3990. let routeMatch = parentMatches[parentMatches.length - 1];
  3991. let parentParams = routeMatch ? routeMatch.params : {};
  3992. let parentPathname = routeMatch ? routeMatch.pathname : "/";
  3993. let parentPathnameBase = routeMatch ? routeMatch.pathnameBase : "/";
  3994. let parentRoute = routeMatch && routeMatch.route;
  3995. if (true) {
  3996. let parentPath = parentRoute && parentRoute.path || "";
  3997. warningOnce(parentPathname, !parentRoute || parentPath.endsWith("*"), "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.
  3998. ` + ('Please change the parent <Route path="' + parentPath + '"> to <Route ') + ('path="' + (parentPath === "/" ? "*" : parentPath + "/*") + '">.'));
  3999. }
  4000. let locationFromContext = useLocation();
  4001. let location;
  4002. if (locationArg) {
  4003. var _parsedLocationArg$pa;
  4004. let parsedLocationArg = typeof locationArg === "string" ? parsePath(locationArg) : locationArg;
  4005. !(parentPathnameBase === "/" || ((_parsedLocationArg$pa = parsedLocationArg.pathname) == null ? void 0 : _parsedLocationArg$pa.startsWith(parentPathnameBase))) ? true ? invariant(false, "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.')) : invariant(false) : void 0;
  4006. location = parsedLocationArg;
  4007. } else {
  4008. location = locationFromContext;
  4009. }
  4010. let pathname = location.pathname || "/";
  4011. let remainingPathname = pathname;
  4012. if (parentPathnameBase !== "/") {
  4013. let parentSegments = parentPathnameBase.replace(/^\//, "").split("/");
  4014. let segments = pathname.replace(/^\//, "").split("/");
  4015. remainingPathname = "/" + segments.slice(parentSegments.length).join("/");
  4016. }
  4017. let matches = matchRoutes(routes, {
  4018. pathname: remainingPathname
  4019. });
  4020. if (true) {
  4021. true ? warning(parentRoute || matches != null, 'No routes matched location "' + location.pathname + location.search + location.hash + '" ') : void 0;
  4022. true ? warning(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, 'Matched leaf route at location "' + location.pathname + location.search + location.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.') : void 0;
  4023. }
  4024. let renderedMatches = _renderMatches(matches && matches.map((match) => Object.assign({}, match, {
  4025. params: Object.assign({}, parentParams, match.params),
  4026. pathname: joinPaths([
  4027. parentPathnameBase,
  4028. // Re-encode pathnames that were decoded inside matchRoutes
  4029. navigator.encodeLocation ? navigator.encodeLocation(match.pathname).pathname : match.pathname
  4030. ]),
  4031. pathnameBase: match.pathnameBase === "/" ? parentPathnameBase : joinPaths([
  4032. parentPathnameBase,
  4033. // Re-encode pathnames that were decoded inside matchRoutes
  4034. navigator.encodeLocation ? navigator.encodeLocation(match.pathnameBase).pathname : match.pathnameBase
  4035. ])
  4036. })), parentMatches, dataRouterState, future);
  4037. if (locationArg && renderedMatches) {
  4038. return React.createElement(LocationContext.Provider, {
  4039. value: {
  4040. location: _extends2({
  4041. pathname: "/",
  4042. search: "",
  4043. hash: "",
  4044. state: null,
  4045. key: "default"
  4046. }, location),
  4047. navigationType: Action.Pop
  4048. }
  4049. }, renderedMatches);
  4050. }
  4051. return renderedMatches;
  4052. }
  4053. function DefaultErrorComponent() {
  4054. let error = useRouteError();
  4055. let message = isRouteErrorResponse(error) ? error.status + " " + error.statusText : error instanceof Error ? error.message : JSON.stringify(error);
  4056. let stack = error instanceof Error ? error.stack : null;
  4057. let lightgrey = "rgba(200,200,200, 0.5)";
  4058. let preStyles = {
  4059. padding: "0.5rem",
  4060. backgroundColor: lightgrey
  4061. };
  4062. let codeStyles = {
  4063. padding: "2px 4px",
  4064. backgroundColor: lightgrey
  4065. };
  4066. let devInfo = null;
  4067. if (true) {
  4068. console.error("Error handled by React Router default ErrorBoundary:", error);
  4069. devInfo = React.createElement(React.Fragment, null, React.createElement("p", null, "💿 Hey developer 👋"), React.createElement("p", null, "You can provide a way better UX than this when your app throws errors by providing your own ", React.createElement("code", {
  4070. style: codeStyles
  4071. }, "ErrorBoundary"), " or", " ", React.createElement("code", {
  4072. style: codeStyles
  4073. }, "errorElement"), " prop on your route."));
  4074. }
  4075. return React.createElement(React.Fragment, null, React.createElement("h2", null, "Unexpected Application Error!"), React.createElement("h3", {
  4076. style: {
  4077. fontStyle: "italic"
  4078. }
  4079. }, message), stack ? React.createElement("pre", {
  4080. style: preStyles
  4081. }, stack) : null, devInfo);
  4082. }
  4083. var defaultErrorElement = React.createElement(DefaultErrorComponent, null);
  4084. var RenderErrorBoundary = class extends React.Component {
  4085. constructor(props) {
  4086. super(props);
  4087. this.state = {
  4088. location: props.location,
  4089. revalidation: props.revalidation,
  4090. error: props.error
  4091. };
  4092. }
  4093. static getDerivedStateFromError(error) {
  4094. return {
  4095. error
  4096. };
  4097. }
  4098. static getDerivedStateFromProps(props, state) {
  4099. if (state.location !== props.location || state.revalidation !== "idle" && props.revalidation === "idle") {
  4100. return {
  4101. error: props.error,
  4102. location: props.location,
  4103. revalidation: props.revalidation
  4104. };
  4105. }
  4106. return {
  4107. error: props.error !== void 0 ? props.error : state.error,
  4108. location: state.location,
  4109. revalidation: props.revalidation || state.revalidation
  4110. };
  4111. }
  4112. componentDidCatch(error, errorInfo) {
  4113. console.error("React Router caught the following error during render", error, errorInfo);
  4114. }
  4115. render() {
  4116. return this.state.error !== void 0 ? React.createElement(RouteContext.Provider, {
  4117. value: this.props.routeContext
  4118. }, React.createElement(RouteErrorContext.Provider, {
  4119. value: this.state.error,
  4120. children: this.props.component
  4121. })) : this.props.children;
  4122. }
  4123. };
  4124. function RenderedRoute(_ref) {
  4125. let {
  4126. routeContext,
  4127. match,
  4128. children
  4129. } = _ref;
  4130. let dataRouterContext = React.useContext(DataRouterContext);
  4131. if (dataRouterContext && dataRouterContext.static && dataRouterContext.staticContext && (match.route.errorElement || match.route.ErrorBoundary)) {
  4132. dataRouterContext.staticContext._deepestRenderedBoundaryId = match.route.id;
  4133. }
  4134. return React.createElement(RouteContext.Provider, {
  4135. value: routeContext
  4136. }, children);
  4137. }
  4138. function _renderMatches(matches, parentMatches, dataRouterState, future) {
  4139. var _dataRouterState;
  4140. if (parentMatches === void 0) {
  4141. parentMatches = [];
  4142. }
  4143. if (dataRouterState === void 0) {
  4144. dataRouterState = null;
  4145. }
  4146. if (future === void 0) {
  4147. future = null;
  4148. }
  4149. if (matches == null) {
  4150. var _future;
  4151. if (!dataRouterState) {
  4152. return null;
  4153. }
  4154. if (dataRouterState.errors) {
  4155. matches = dataRouterState.matches;
  4156. } else if ((_future = future) != null && _future.v7_partialHydration && parentMatches.length === 0 && !dataRouterState.initialized && dataRouterState.matches.length > 0) {
  4157. matches = dataRouterState.matches;
  4158. } else {
  4159. return null;
  4160. }
  4161. }
  4162. let renderedMatches = matches;
  4163. let errors = (_dataRouterState = dataRouterState) == null ? void 0 : _dataRouterState.errors;
  4164. if (errors != null) {
  4165. let errorIndex = renderedMatches.findIndex((m) => m.route.id && (errors == null ? void 0 : errors[m.route.id]) !== void 0);
  4166. !(errorIndex >= 0) ? true ? invariant(false, "Could not find a matching route for errors on route IDs: " + Object.keys(errors).join(",")) : invariant(false) : void 0;
  4167. renderedMatches = renderedMatches.slice(0, Math.min(renderedMatches.length, errorIndex + 1));
  4168. }
  4169. let renderFallback = false;
  4170. let fallbackIndex = -1;
  4171. if (dataRouterState && future && future.v7_partialHydration) {
  4172. for (let i = 0; i < renderedMatches.length; i++) {
  4173. let match = renderedMatches[i];
  4174. if (match.route.HydrateFallback || match.route.hydrateFallbackElement) {
  4175. fallbackIndex = i;
  4176. }
  4177. if (match.route.id) {
  4178. let {
  4179. loaderData,
  4180. errors: errors2
  4181. } = dataRouterState;
  4182. let needsToRunLoader = match.route.loader && loaderData[match.route.id] === void 0 && (!errors2 || errors2[match.route.id] === void 0);
  4183. if (match.route.lazy || needsToRunLoader) {
  4184. renderFallback = true;
  4185. if (fallbackIndex >= 0) {
  4186. renderedMatches = renderedMatches.slice(0, fallbackIndex + 1);
  4187. } else {
  4188. renderedMatches = [renderedMatches[0]];
  4189. }
  4190. break;
  4191. }
  4192. }
  4193. }
  4194. }
  4195. return renderedMatches.reduceRight((outlet, match, index) => {
  4196. let error;
  4197. let shouldRenderHydrateFallback = false;
  4198. let errorElement = null;
  4199. let hydrateFallbackElement = null;
  4200. if (dataRouterState) {
  4201. error = errors && match.route.id ? errors[match.route.id] : void 0;
  4202. errorElement = match.route.errorElement || defaultErrorElement;
  4203. if (renderFallback) {
  4204. if (fallbackIndex < 0 && index === 0) {
  4205. warningOnce("route-fallback", false, "No `HydrateFallback` element provided to render during initial hydration");
  4206. shouldRenderHydrateFallback = true;
  4207. hydrateFallbackElement = null;
  4208. } else if (fallbackIndex === index) {
  4209. shouldRenderHydrateFallback = true;
  4210. hydrateFallbackElement = match.route.hydrateFallbackElement || null;
  4211. }
  4212. }
  4213. }
  4214. let matches2 = parentMatches.concat(renderedMatches.slice(0, index + 1));
  4215. let getChildren = () => {
  4216. let children;
  4217. if (error) {
  4218. children = errorElement;
  4219. } else if (shouldRenderHydrateFallback) {
  4220. children = hydrateFallbackElement;
  4221. } else if (match.route.Component) {
  4222. children = React.createElement(match.route.Component, null);
  4223. } else if (match.route.element) {
  4224. children = match.route.element;
  4225. } else {
  4226. children = outlet;
  4227. }
  4228. return React.createElement(RenderedRoute, {
  4229. match,
  4230. routeContext: {
  4231. outlet,
  4232. matches: matches2,
  4233. isDataRoute: dataRouterState != null
  4234. },
  4235. children
  4236. });
  4237. };
  4238. return dataRouterState && (match.route.ErrorBoundary || match.route.errorElement || index === 0) ? React.createElement(RenderErrorBoundary, {
  4239. location: dataRouterState.location,
  4240. revalidation: dataRouterState.revalidation,
  4241. component: errorElement,
  4242. error,
  4243. children: getChildren(),
  4244. routeContext: {
  4245. outlet: null,
  4246. matches: matches2,
  4247. isDataRoute: true
  4248. }
  4249. }) : getChildren();
  4250. }, null);
  4251. }
  4252. var DataRouterHook = (function(DataRouterHook3) {
  4253. DataRouterHook3["UseBlocker"] = "useBlocker";
  4254. DataRouterHook3["UseRevalidator"] = "useRevalidator";
  4255. DataRouterHook3["UseNavigateStable"] = "useNavigate";
  4256. return DataRouterHook3;
  4257. })(DataRouterHook || {});
  4258. var DataRouterStateHook = (function(DataRouterStateHook3) {
  4259. DataRouterStateHook3["UseBlocker"] = "useBlocker";
  4260. DataRouterStateHook3["UseLoaderData"] = "useLoaderData";
  4261. DataRouterStateHook3["UseActionData"] = "useActionData";
  4262. DataRouterStateHook3["UseRouteError"] = "useRouteError";
  4263. DataRouterStateHook3["UseNavigation"] = "useNavigation";
  4264. DataRouterStateHook3["UseRouteLoaderData"] = "useRouteLoaderData";
  4265. DataRouterStateHook3["UseMatches"] = "useMatches";
  4266. DataRouterStateHook3["UseRevalidator"] = "useRevalidator";
  4267. DataRouterStateHook3["UseNavigateStable"] = "useNavigate";
  4268. DataRouterStateHook3["UseRouteId"] = "useRouteId";
  4269. return DataRouterStateHook3;
  4270. })(DataRouterStateHook || {});
  4271. function getDataRouterConsoleError(hookName) {
  4272. return hookName + " must be used within a data router. See https://reactrouter.com/v6/routers/picking-a-router.";
  4273. }
  4274. function useDataRouterContext(hookName) {
  4275. let ctx = React.useContext(DataRouterContext);
  4276. !ctx ? true ? invariant(false, getDataRouterConsoleError(hookName)) : invariant(false) : void 0;
  4277. return ctx;
  4278. }
  4279. function useDataRouterState(hookName) {
  4280. let state = React.useContext(DataRouterStateContext);
  4281. !state ? true ? invariant(false, getDataRouterConsoleError(hookName)) : invariant(false) : void 0;
  4282. return state;
  4283. }
  4284. function useRouteContext(hookName) {
  4285. let route = React.useContext(RouteContext);
  4286. !route ? true ? invariant(false, getDataRouterConsoleError(hookName)) : invariant(false) : void 0;
  4287. return route;
  4288. }
  4289. function useCurrentRouteId(hookName) {
  4290. let route = useRouteContext(hookName);
  4291. let thisRoute = route.matches[route.matches.length - 1];
  4292. !thisRoute.route.id ? true ? invariant(false, hookName + ' can only be used on routes that contain a unique "id"') : invariant(false) : void 0;
  4293. return thisRoute.route.id;
  4294. }
  4295. function useRouteId() {
  4296. return useCurrentRouteId(DataRouterStateHook.UseRouteId);
  4297. }
  4298. function useNavigation() {
  4299. let state = useDataRouterState(DataRouterStateHook.UseNavigation);
  4300. return state.navigation;
  4301. }
  4302. function useRevalidator() {
  4303. let dataRouterContext = useDataRouterContext(DataRouterHook.UseRevalidator);
  4304. let state = useDataRouterState(DataRouterStateHook.UseRevalidator);
  4305. return React.useMemo(() => ({
  4306. revalidate: dataRouterContext.router.revalidate,
  4307. state: state.revalidation
  4308. }), [dataRouterContext.router.revalidate, state.revalidation]);
  4309. }
  4310. function useMatches() {
  4311. let {
  4312. matches,
  4313. loaderData
  4314. } = useDataRouterState(DataRouterStateHook.UseMatches);
  4315. return React.useMemo(() => matches.map((m) => convertRouteMatchToUiMatch(m, loaderData)), [matches, loaderData]);
  4316. }
  4317. function useLoaderData() {
  4318. let state = useDataRouterState(DataRouterStateHook.UseLoaderData);
  4319. let routeId = useCurrentRouteId(DataRouterStateHook.UseLoaderData);
  4320. if (state.errors && state.errors[routeId] != null) {
  4321. console.error("You cannot `useLoaderData` in an errorElement (routeId: " + routeId + ")");
  4322. return void 0;
  4323. }
  4324. return state.loaderData[routeId];
  4325. }
  4326. function useRouteLoaderData(routeId) {
  4327. let state = useDataRouterState(DataRouterStateHook.UseRouteLoaderData);
  4328. return state.loaderData[routeId];
  4329. }
  4330. function useActionData() {
  4331. let state = useDataRouterState(DataRouterStateHook.UseActionData);
  4332. let routeId = useCurrentRouteId(DataRouterStateHook.UseLoaderData);
  4333. return state.actionData ? state.actionData[routeId] : void 0;
  4334. }
  4335. function useRouteError() {
  4336. var _state$errors;
  4337. let error = React.useContext(RouteErrorContext);
  4338. let state = useDataRouterState(DataRouterStateHook.UseRouteError);
  4339. let routeId = useCurrentRouteId(DataRouterStateHook.UseRouteError);
  4340. if (error !== void 0) {
  4341. return error;
  4342. }
  4343. return (_state$errors = state.errors) == null ? void 0 : _state$errors[routeId];
  4344. }
  4345. function useAsyncValue() {
  4346. let value = React.useContext(AwaitContext);
  4347. return value == null ? void 0 : value._data;
  4348. }
  4349. function useAsyncError() {
  4350. let value = React.useContext(AwaitContext);
  4351. return value == null ? void 0 : value._error;
  4352. }
  4353. var blockerId = 0;
  4354. function useBlocker(shouldBlock) {
  4355. let {
  4356. router,
  4357. basename
  4358. } = useDataRouterContext(DataRouterHook.UseBlocker);
  4359. let state = useDataRouterState(DataRouterStateHook.UseBlocker);
  4360. let [blockerKey, setBlockerKey] = React.useState("");
  4361. let blockerFunction = React.useCallback((arg) => {
  4362. if (typeof shouldBlock !== "function") {
  4363. return !!shouldBlock;
  4364. }
  4365. if (basename === "/") {
  4366. return shouldBlock(arg);
  4367. }
  4368. let {
  4369. currentLocation,
  4370. nextLocation,
  4371. historyAction
  4372. } = arg;
  4373. return shouldBlock({
  4374. currentLocation: _extends2({}, currentLocation, {
  4375. pathname: stripBasename(currentLocation.pathname, basename) || currentLocation.pathname
  4376. }),
  4377. nextLocation: _extends2({}, nextLocation, {
  4378. pathname: stripBasename(nextLocation.pathname, basename) || nextLocation.pathname
  4379. }),
  4380. historyAction
  4381. });
  4382. }, [basename, shouldBlock]);
  4383. React.useEffect(() => {
  4384. let key = String(++blockerId);
  4385. setBlockerKey(key);
  4386. return () => router.deleteBlocker(key);
  4387. }, [router]);
  4388. React.useEffect(() => {
  4389. if (blockerKey !== "") {
  4390. router.getBlocker(blockerKey, blockerFunction);
  4391. }
  4392. }, [router, blockerKey, blockerFunction]);
  4393. return blockerKey && state.blockers.has(blockerKey) ? state.blockers.get(blockerKey) : IDLE_BLOCKER;
  4394. }
  4395. function useNavigateStable() {
  4396. let {
  4397. router
  4398. } = useDataRouterContext(DataRouterHook.UseNavigateStable);
  4399. let id = useCurrentRouteId(DataRouterStateHook.UseNavigateStable);
  4400. let activeRef = React.useRef(false);
  4401. useIsomorphicLayoutEffect(() => {
  4402. activeRef.current = true;
  4403. });
  4404. let navigate = React.useCallback(function(to, options) {
  4405. if (options === void 0) {
  4406. options = {};
  4407. }
  4408. true ? warning(activeRef.current, navigateEffectWarning) : void 0;
  4409. if (!activeRef.current) return;
  4410. if (typeof to === "number") {
  4411. router.navigate(to);
  4412. } else {
  4413. router.navigate(to, _extends2({
  4414. fromRouteId: id
  4415. }, options));
  4416. }
  4417. }, [router, id]);
  4418. return navigate;
  4419. }
  4420. var alreadyWarned$1 = {};
  4421. function warningOnce(key, cond, message) {
  4422. if (!cond && !alreadyWarned$1[key]) {
  4423. alreadyWarned$1[key] = true;
  4424. true ? warning(false, message) : void 0;
  4425. }
  4426. }
  4427. var alreadyWarned = {};
  4428. function warnOnce(key, message) {
  4429. if (!alreadyWarned[message]) {
  4430. alreadyWarned[message] = true;
  4431. console.warn(message);
  4432. }
  4433. }
  4434. var logDeprecation = (flag, msg, link) => warnOnce(flag, "⚠️ React Router Future Flag Warning: " + msg + ". " + ("You can use the `" + flag + "` future flag to opt-in early. ") + ("For more information, see " + link + "."));
  4435. function logV6DeprecationWarnings(renderFuture, routerFuture) {
  4436. if ((renderFuture == null ? void 0 : renderFuture.v7_startTransition) === void 0) {
  4437. logDeprecation("v7_startTransition", "React Router will begin wrapping state updates in `React.startTransition` in v7", "https://reactrouter.com/v6/upgrading/future#v7_starttransition");
  4438. }
  4439. if ((renderFuture == null ? void 0 : renderFuture.v7_relativeSplatPath) === void 0 && (!routerFuture || routerFuture.v7_relativeSplatPath === void 0)) {
  4440. logDeprecation("v7_relativeSplatPath", "Relative route resolution within Splat routes is changing in v7", "https://reactrouter.com/v6/upgrading/future#v7_relativesplatpath");
  4441. }
  4442. if (routerFuture) {
  4443. if (routerFuture.v7_fetcherPersist === void 0) {
  4444. logDeprecation("v7_fetcherPersist", "The persistence behavior of fetchers is changing in v7", "https://reactrouter.com/v6/upgrading/future#v7_fetcherpersist");
  4445. }
  4446. if (routerFuture.v7_normalizeFormMethod === void 0) {
  4447. logDeprecation("v7_normalizeFormMethod", "Casing of `formMethod` fields is being normalized to uppercase in v7", "https://reactrouter.com/v6/upgrading/future#v7_normalizeformmethod");
  4448. }
  4449. if (routerFuture.v7_partialHydration === void 0) {
  4450. logDeprecation("v7_partialHydration", "`RouterProvider` hydration behavior is changing in v7", "https://reactrouter.com/v6/upgrading/future#v7_partialhydration");
  4451. }
  4452. if (routerFuture.v7_skipActionErrorRevalidation === void 0) {
  4453. logDeprecation("v7_skipActionErrorRevalidation", "The revalidation behavior after 4xx/5xx `action` responses is changing in v7", "https://reactrouter.com/v6/upgrading/future#v7_skipactionerrorrevalidation");
  4454. }
  4455. }
  4456. }
  4457. var START_TRANSITION = "startTransition";
  4458. var startTransitionImpl = React[START_TRANSITION];
  4459. function MemoryRouter(_ref3) {
  4460. let {
  4461. basename,
  4462. children,
  4463. initialEntries,
  4464. initialIndex,
  4465. future
  4466. } = _ref3;
  4467. let historyRef = React.useRef();
  4468. if (historyRef.current == null) {
  4469. historyRef.current = createMemoryHistory({
  4470. initialEntries,
  4471. initialIndex,
  4472. v5Compat: true
  4473. });
  4474. }
  4475. let history = historyRef.current;
  4476. let [state, setStateImpl] = React.useState({
  4477. action: history.action,
  4478. location: history.location
  4479. });
  4480. let {
  4481. v7_startTransition
  4482. } = future || {};
  4483. let setState = React.useCallback((newState) => {
  4484. v7_startTransition && startTransitionImpl ? startTransitionImpl(() => setStateImpl(newState)) : setStateImpl(newState);
  4485. }, [setStateImpl, v7_startTransition]);
  4486. React.useLayoutEffect(() => history.listen(setState), [history, setState]);
  4487. React.useEffect(() => logV6DeprecationWarnings(future), [future]);
  4488. return React.createElement(Router, {
  4489. basename,
  4490. children,
  4491. location: state.location,
  4492. navigationType: state.action,
  4493. navigator: history,
  4494. future
  4495. });
  4496. }
  4497. function Navigate(_ref4) {
  4498. let {
  4499. to,
  4500. replace: replace2,
  4501. state,
  4502. relative
  4503. } = _ref4;
  4504. !useInRouterContext() ? true ? invariant(
  4505. false,
  4506. // TODO: This error is probably because they somehow have 2 versions of
  4507. // the router loaded. We can help them understand how to avoid that.
  4508. "<Navigate> may be used only in the context of a <Router> component."
  4509. ) : invariant(false) : void 0;
  4510. let {
  4511. future,
  4512. static: isStatic
  4513. } = React.useContext(NavigationContext);
  4514. true ? warning(!isStatic, "<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.") : void 0;
  4515. let {
  4516. matches
  4517. } = React.useContext(RouteContext);
  4518. let {
  4519. pathname: locationPathname
  4520. } = useLocation();
  4521. let navigate = useNavigate();
  4522. let path = resolveTo(to, getResolveToMatches(matches, future.v7_relativeSplatPath), locationPathname, relative === "path");
  4523. let jsonPath = JSON.stringify(path);
  4524. React.useEffect(() => navigate(JSON.parse(jsonPath), {
  4525. replace: replace2,
  4526. state,
  4527. relative
  4528. }), [navigate, jsonPath, relative, replace2, state]);
  4529. return null;
  4530. }
  4531. function Outlet(props) {
  4532. return useOutlet(props.context);
  4533. }
  4534. function Route(_props) {
  4535. true ? invariant(false, "A <Route> is only ever to be used as the child of <Routes> element, never rendered directly. Please wrap your <Route> in a <Routes>.") : invariant(false);
  4536. }
  4537. function Router(_ref5) {
  4538. let {
  4539. basename: basenameProp = "/",
  4540. children = null,
  4541. location: locationProp,
  4542. navigationType = Action.Pop,
  4543. navigator,
  4544. static: staticProp = false,
  4545. future
  4546. } = _ref5;
  4547. !!useInRouterContext() ? true ? invariant(false, "You cannot render a <Router> inside another <Router>. You should never have more than one in your app.") : invariant(false) : void 0;
  4548. let basename = basenameProp.replace(/^\/*/, "/");
  4549. let navigationContext = React.useMemo(() => ({
  4550. basename,
  4551. navigator,
  4552. static: staticProp,
  4553. future: _extends2({
  4554. v7_relativeSplatPath: false
  4555. }, future)
  4556. }), [basename, future, navigator, staticProp]);
  4557. if (typeof locationProp === "string") {
  4558. locationProp = parsePath(locationProp);
  4559. }
  4560. let {
  4561. pathname = "/",
  4562. search = "",
  4563. hash = "",
  4564. state = null,
  4565. key = "default"
  4566. } = locationProp;
  4567. let locationContext = React.useMemo(() => {
  4568. let trailingPathname = stripBasename(pathname, basename);
  4569. if (trailingPathname == null) {
  4570. return null;
  4571. }
  4572. return {
  4573. location: {
  4574. pathname: trailingPathname,
  4575. search,
  4576. hash,
  4577. state,
  4578. key
  4579. },
  4580. navigationType
  4581. };
  4582. }, [basename, pathname, search, hash, state, key, navigationType]);
  4583. true ? warning(locationContext != null, '<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.") : void 0;
  4584. if (locationContext == null) {
  4585. return null;
  4586. }
  4587. return React.createElement(NavigationContext.Provider, {
  4588. value: navigationContext
  4589. }, React.createElement(LocationContext.Provider, {
  4590. children,
  4591. value: locationContext
  4592. }));
  4593. }
  4594. function Routes(_ref6) {
  4595. let {
  4596. children,
  4597. location
  4598. } = _ref6;
  4599. return useRoutes(createRoutesFromChildren(children), location);
  4600. }
  4601. function Await(_ref7) {
  4602. let {
  4603. children,
  4604. errorElement,
  4605. resolve
  4606. } = _ref7;
  4607. return React.createElement(AwaitErrorBoundary, {
  4608. resolve,
  4609. errorElement
  4610. }, React.createElement(ResolveAwait, null, children));
  4611. }
  4612. var AwaitRenderStatus = (function(AwaitRenderStatus2) {
  4613. AwaitRenderStatus2[AwaitRenderStatus2["pending"] = 0] = "pending";
  4614. AwaitRenderStatus2[AwaitRenderStatus2["success"] = 1] = "success";
  4615. AwaitRenderStatus2[AwaitRenderStatus2["error"] = 2] = "error";
  4616. return AwaitRenderStatus2;
  4617. })(AwaitRenderStatus || {});
  4618. var neverSettledPromise = new Promise(() => {
  4619. });
  4620. var AwaitErrorBoundary = class extends React.Component {
  4621. constructor(props) {
  4622. super(props);
  4623. this.state = {
  4624. error: null
  4625. };
  4626. }
  4627. static getDerivedStateFromError(error) {
  4628. return {
  4629. error
  4630. };
  4631. }
  4632. componentDidCatch(error, errorInfo) {
  4633. console.error("<Await> caught the following error during render", error, errorInfo);
  4634. }
  4635. render() {
  4636. let {
  4637. children,
  4638. errorElement,
  4639. resolve
  4640. } = this.props;
  4641. let promise = null;
  4642. let status = AwaitRenderStatus.pending;
  4643. if (!(resolve instanceof Promise)) {
  4644. status = AwaitRenderStatus.success;
  4645. promise = Promise.resolve();
  4646. Object.defineProperty(promise, "_tracked", {
  4647. get: () => true
  4648. });
  4649. Object.defineProperty(promise, "_data", {
  4650. get: () => resolve
  4651. });
  4652. } else if (this.state.error) {
  4653. status = AwaitRenderStatus.error;
  4654. let renderError = this.state.error;
  4655. promise = Promise.reject().catch(() => {
  4656. });
  4657. Object.defineProperty(promise, "_tracked", {
  4658. get: () => true
  4659. });
  4660. Object.defineProperty(promise, "_error", {
  4661. get: () => renderError
  4662. });
  4663. } else if (resolve._tracked) {
  4664. promise = resolve;
  4665. status = "_error" in promise ? AwaitRenderStatus.error : "_data" in promise ? AwaitRenderStatus.success : AwaitRenderStatus.pending;
  4666. } else {
  4667. status = AwaitRenderStatus.pending;
  4668. Object.defineProperty(resolve, "_tracked", {
  4669. get: () => true
  4670. });
  4671. promise = resolve.then((data) => Object.defineProperty(resolve, "_data", {
  4672. get: () => data
  4673. }), (error) => Object.defineProperty(resolve, "_error", {
  4674. get: () => error
  4675. }));
  4676. }
  4677. if (status === AwaitRenderStatus.error && promise._error instanceof AbortedDeferredError) {
  4678. throw neverSettledPromise;
  4679. }
  4680. if (status === AwaitRenderStatus.error && !errorElement) {
  4681. throw promise._error;
  4682. }
  4683. if (status === AwaitRenderStatus.error) {
  4684. return React.createElement(AwaitContext.Provider, {
  4685. value: promise,
  4686. children: errorElement
  4687. });
  4688. }
  4689. if (status === AwaitRenderStatus.success) {
  4690. return React.createElement(AwaitContext.Provider, {
  4691. value: promise,
  4692. children
  4693. });
  4694. }
  4695. throw promise;
  4696. }
  4697. };
  4698. function ResolveAwait(_ref8) {
  4699. let {
  4700. children
  4701. } = _ref8;
  4702. let data = useAsyncValue();
  4703. let toRender = typeof children === "function" ? children(data) : children;
  4704. return React.createElement(React.Fragment, null, toRender);
  4705. }
  4706. function createRoutesFromChildren(children, parentPath) {
  4707. if (parentPath === void 0) {
  4708. parentPath = [];
  4709. }
  4710. let routes = [];
  4711. React.Children.forEach(children, (element, index) => {
  4712. if (!React.isValidElement(element)) {
  4713. return;
  4714. }
  4715. let treePath = [...parentPath, index];
  4716. if (element.type === React.Fragment) {
  4717. routes.push.apply(routes, createRoutesFromChildren(element.props.children, treePath));
  4718. return;
  4719. }
  4720. !(element.type === Route) ? true ? invariant(false, "[" + (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>") : invariant(false) : void 0;
  4721. !(!element.props.index || !element.props.children) ? true ? invariant(false, "An index route cannot have child routes.") : invariant(false) : void 0;
  4722. let route = {
  4723. id: element.props.id || treePath.join("-"),
  4724. caseSensitive: element.props.caseSensitive,
  4725. element: element.props.element,
  4726. Component: element.props.Component,
  4727. index: element.props.index,
  4728. path: element.props.path,
  4729. loader: element.props.loader,
  4730. action: element.props.action,
  4731. errorElement: element.props.errorElement,
  4732. ErrorBoundary: element.props.ErrorBoundary,
  4733. hasErrorBoundary: element.props.ErrorBoundary != null || element.props.errorElement != null,
  4734. shouldRevalidate: element.props.shouldRevalidate,
  4735. handle: element.props.handle,
  4736. lazy: element.props.lazy
  4737. };
  4738. if (element.props.children) {
  4739. route.children = createRoutesFromChildren(element.props.children, treePath);
  4740. }
  4741. routes.push(route);
  4742. });
  4743. return routes;
  4744. }
  4745. function renderMatches(matches) {
  4746. return _renderMatches(matches);
  4747. }
  4748. function mapRouteProperties(route) {
  4749. let updates = {
  4750. // Note: this check also occurs in createRoutesFromChildren so update
  4751. // there if you change this -- please and thank you!
  4752. hasErrorBoundary: route.ErrorBoundary != null || route.errorElement != null
  4753. };
  4754. if (route.Component) {
  4755. if (true) {
  4756. if (route.element) {
  4757. true ? warning(false, "You should not include both `Component` and `element` on your route - `Component` will be used.") : void 0;
  4758. }
  4759. }
  4760. Object.assign(updates, {
  4761. element: React.createElement(route.Component),
  4762. Component: void 0
  4763. });
  4764. }
  4765. if (route.HydrateFallback) {
  4766. if (true) {
  4767. if (route.hydrateFallbackElement) {
  4768. true ? warning(false, "You should not include both `HydrateFallback` and `hydrateFallbackElement` on your route - `HydrateFallback` will be used.") : void 0;
  4769. }
  4770. }
  4771. Object.assign(updates, {
  4772. hydrateFallbackElement: React.createElement(route.HydrateFallback),
  4773. HydrateFallback: void 0
  4774. });
  4775. }
  4776. if (route.ErrorBoundary) {
  4777. if (true) {
  4778. if (route.errorElement) {
  4779. true ? warning(false, "You should not include both `ErrorBoundary` and `errorElement` on your route - `ErrorBoundary` will be used.") : void 0;
  4780. }
  4781. }
  4782. Object.assign(updates, {
  4783. errorElement: React.createElement(route.ErrorBoundary),
  4784. ErrorBoundary: void 0
  4785. });
  4786. }
  4787. return updates;
  4788. }
  4789. function createMemoryRouter(routes, opts) {
  4790. return createRouter({
  4791. basename: opts == null ? void 0 : opts.basename,
  4792. future: _extends2({}, opts == null ? void 0 : opts.future, {
  4793. v7_prependBasename: true
  4794. }),
  4795. history: createMemoryHistory({
  4796. initialEntries: opts == null ? void 0 : opts.initialEntries,
  4797. initialIndex: opts == null ? void 0 : opts.initialIndex
  4798. }),
  4799. hydrationData: opts == null ? void 0 : opts.hydrationData,
  4800. routes,
  4801. mapRouteProperties,
  4802. dataStrategy: opts == null ? void 0 : opts.dataStrategy,
  4803. patchRoutesOnNavigation: opts == null ? void 0 : opts.patchRoutesOnNavigation
  4804. }).initialize();
  4805. }
  4806. // node_modules/react-router-dom/dist/index.js
  4807. function _extends3() {
  4808. _extends3 = Object.assign ? Object.assign.bind() : function(target) {
  4809. for (var i = 1; i < arguments.length; i++) {
  4810. var source = arguments[i];
  4811. for (var key in source) {
  4812. if (Object.prototype.hasOwnProperty.call(source, key)) {
  4813. target[key] = source[key];
  4814. }
  4815. }
  4816. }
  4817. return target;
  4818. };
  4819. return _extends3.apply(this, arguments);
  4820. }
  4821. function _objectWithoutPropertiesLoose(source, excluded) {
  4822. if (source == null) return {};
  4823. var target = {};
  4824. var sourceKeys = Object.keys(source);
  4825. var key, i;
  4826. for (i = 0; i < sourceKeys.length; i++) {
  4827. key = sourceKeys[i];
  4828. if (excluded.indexOf(key) >= 0) continue;
  4829. target[key] = source[key];
  4830. }
  4831. return target;
  4832. }
  4833. var defaultMethod = "get";
  4834. var defaultEncType = "application/x-www-form-urlencoded";
  4835. function isHtmlElement(object) {
  4836. return object != null && typeof object.tagName === "string";
  4837. }
  4838. function isButtonElement(object) {
  4839. return isHtmlElement(object) && object.tagName.toLowerCase() === "button";
  4840. }
  4841. function isFormElement(object) {
  4842. return isHtmlElement(object) && object.tagName.toLowerCase() === "form";
  4843. }
  4844. function isInputElement(object) {
  4845. return isHtmlElement(object) && object.tagName.toLowerCase() === "input";
  4846. }
  4847. function isModifiedEvent(event) {
  4848. return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey);
  4849. }
  4850. function shouldProcessLinkClick(event, target) {
  4851. return event.button === 0 && // Ignore everything but left clicks
  4852. (!target || target === "_self") && // Let browser handle "target=_blank" etc.
  4853. !isModifiedEvent(event);
  4854. }
  4855. function createSearchParams(init) {
  4856. if (init === void 0) {
  4857. init = "";
  4858. }
  4859. return new URLSearchParams(typeof init === "string" || Array.isArray(init) || init instanceof URLSearchParams ? init : Object.keys(init).reduce((memo2, key) => {
  4860. let value = init[key];
  4861. return memo2.concat(Array.isArray(value) ? value.map((v) => [key, v]) : [[key, value]]);
  4862. }, []));
  4863. }
  4864. function getSearchParamsForLocation(locationSearch, defaultSearchParams) {
  4865. let searchParams = createSearchParams(locationSearch);
  4866. if (defaultSearchParams) {
  4867. defaultSearchParams.forEach((_, key) => {
  4868. if (!searchParams.has(key)) {
  4869. defaultSearchParams.getAll(key).forEach((value) => {
  4870. searchParams.append(key, value);
  4871. });
  4872. }
  4873. });
  4874. }
  4875. return searchParams;
  4876. }
  4877. var _formDataSupportsSubmitter = null;
  4878. function isFormDataSubmitterSupported() {
  4879. if (_formDataSupportsSubmitter === null) {
  4880. try {
  4881. new FormData(
  4882. document.createElement("form"),
  4883. // @ts-expect-error if FormData supports the submitter parameter, this will throw
  4884. 0
  4885. );
  4886. _formDataSupportsSubmitter = false;
  4887. } catch (e) {
  4888. _formDataSupportsSubmitter = true;
  4889. }
  4890. }
  4891. return _formDataSupportsSubmitter;
  4892. }
  4893. var supportedFormEncTypes = /* @__PURE__ */ new Set(["application/x-www-form-urlencoded", "multipart/form-data", "text/plain"]);
  4894. function getFormEncType(encType) {
  4895. if (encType != null && !supportedFormEncTypes.has(encType)) {
  4896. true ? warning(false, '"' + encType + '" is not a valid `encType` for `<Form>`/`<fetcher.Form>` ' + ('and will default to "' + defaultEncType + '"')) : void 0;
  4897. return null;
  4898. }
  4899. return encType;
  4900. }
  4901. function getFormSubmissionInfo(target, basename) {
  4902. let method;
  4903. let action;
  4904. let encType;
  4905. let formData;
  4906. let body;
  4907. if (isFormElement(target)) {
  4908. let attr = target.getAttribute("action");
  4909. action = attr ? stripBasename(attr, basename) : null;
  4910. method = target.getAttribute("method") || defaultMethod;
  4911. encType = getFormEncType(target.getAttribute("enctype")) || defaultEncType;
  4912. formData = new FormData(target);
  4913. } else if (isButtonElement(target) || isInputElement(target) && (target.type === "submit" || target.type === "image")) {
  4914. let form = target.form;
  4915. if (form == null) {
  4916. throw new Error('Cannot submit a <button> or <input type="submit"> without a <form>');
  4917. }
  4918. let attr = target.getAttribute("formaction") || form.getAttribute("action");
  4919. action = attr ? stripBasename(attr, basename) : null;
  4920. method = target.getAttribute("formmethod") || form.getAttribute("method") || defaultMethod;
  4921. encType = getFormEncType(target.getAttribute("formenctype")) || getFormEncType(form.getAttribute("enctype")) || defaultEncType;
  4922. formData = new FormData(form, target);
  4923. if (!isFormDataSubmitterSupported()) {
  4924. let {
  4925. name,
  4926. type,
  4927. value
  4928. } = target;
  4929. if (type === "image") {
  4930. let prefix = name ? name + "." : "";
  4931. formData.append(prefix + "x", "0");
  4932. formData.append(prefix + "y", "0");
  4933. } else if (name) {
  4934. formData.append(name, value);
  4935. }
  4936. }
  4937. } else if (isHtmlElement(target)) {
  4938. throw new Error('Cannot submit element that is not <form>, <button>, or <input type="submit|image">');
  4939. } else {
  4940. method = defaultMethod;
  4941. action = null;
  4942. encType = defaultEncType;
  4943. body = target;
  4944. }
  4945. if (formData && encType === "text/plain") {
  4946. body = formData;
  4947. formData = void 0;
  4948. }
  4949. return {
  4950. action,
  4951. method: method.toLowerCase(),
  4952. encType,
  4953. formData,
  4954. body
  4955. };
  4956. }
  4957. var _excluded = ["onClick", "relative", "reloadDocument", "replace", "state", "target", "to", "preventScrollReset", "viewTransition"];
  4958. var _excluded2 = ["aria-current", "caseSensitive", "className", "end", "style", "to", "viewTransition", "children"];
  4959. var _excluded3 = ["fetcherKey", "navigate", "reloadDocument", "replace", "state", "method", "action", "onSubmit", "relative", "preventScrollReset", "viewTransition"];
  4960. var REACT_ROUTER_VERSION = "6";
  4961. try {
  4962. window.__reactRouterVersion = REACT_ROUTER_VERSION;
  4963. } catch (e) {
  4964. }
  4965. function createBrowserRouter(routes, opts) {
  4966. return createRouter({
  4967. basename: opts == null ? void 0 : opts.basename,
  4968. future: _extends3({}, opts == null ? void 0 : opts.future, {
  4969. v7_prependBasename: true
  4970. }),
  4971. history: createBrowserHistory({
  4972. window: opts == null ? void 0 : opts.window
  4973. }),
  4974. hydrationData: (opts == null ? void 0 : opts.hydrationData) || parseHydrationData(),
  4975. routes,
  4976. mapRouteProperties,
  4977. dataStrategy: opts == null ? void 0 : opts.dataStrategy,
  4978. patchRoutesOnNavigation: opts == null ? void 0 : opts.patchRoutesOnNavigation,
  4979. window: opts == null ? void 0 : opts.window
  4980. }).initialize();
  4981. }
  4982. function createHashRouter(routes, opts) {
  4983. return createRouter({
  4984. basename: opts == null ? void 0 : opts.basename,
  4985. future: _extends3({}, opts == null ? void 0 : opts.future, {
  4986. v7_prependBasename: true
  4987. }),
  4988. history: createHashHistory({
  4989. window: opts == null ? void 0 : opts.window
  4990. }),
  4991. hydrationData: (opts == null ? void 0 : opts.hydrationData) || parseHydrationData(),
  4992. routes,
  4993. mapRouteProperties,
  4994. dataStrategy: opts == null ? void 0 : opts.dataStrategy,
  4995. patchRoutesOnNavigation: opts == null ? void 0 : opts.patchRoutesOnNavigation,
  4996. window: opts == null ? void 0 : opts.window
  4997. }).initialize();
  4998. }
  4999. function parseHydrationData() {
  5000. var _window;
  5001. let state = (_window = window) == null ? void 0 : _window.__staticRouterHydrationData;
  5002. if (state && state.errors) {
  5003. state = _extends3({}, state, {
  5004. errors: deserializeErrors(state.errors)
  5005. });
  5006. }
  5007. return state;
  5008. }
  5009. function deserializeErrors(errors) {
  5010. if (!errors) return null;
  5011. let entries = Object.entries(errors);
  5012. let serialized = {};
  5013. for (let [key, val] of entries) {
  5014. if (val && val.__type === "RouteErrorResponse") {
  5015. serialized[key] = new ErrorResponseImpl(val.status, val.statusText, val.data, val.internal === true);
  5016. } else if (val && val.__type === "Error") {
  5017. if (val.__subType) {
  5018. let ErrorConstructor = window[val.__subType];
  5019. if (typeof ErrorConstructor === "function") {
  5020. try {
  5021. let error = new ErrorConstructor(val.message);
  5022. error.stack = "";
  5023. serialized[key] = error;
  5024. } catch (e) {
  5025. }
  5026. }
  5027. }
  5028. if (serialized[key] == null) {
  5029. let error = new Error(val.message);
  5030. error.stack = "";
  5031. serialized[key] = error;
  5032. }
  5033. } else {
  5034. serialized[key] = val;
  5035. }
  5036. }
  5037. return serialized;
  5038. }
  5039. var ViewTransitionContext = React2.createContext({
  5040. isTransitioning: false
  5041. });
  5042. if (true) {
  5043. ViewTransitionContext.displayName = "ViewTransition";
  5044. }
  5045. var FetchersContext = React2.createContext(/* @__PURE__ */ new Map());
  5046. if (true) {
  5047. FetchersContext.displayName = "Fetchers";
  5048. }
  5049. var START_TRANSITION2 = "startTransition";
  5050. var startTransitionImpl2 = React2[START_TRANSITION2];
  5051. var FLUSH_SYNC = "flushSync";
  5052. var flushSyncImpl = ReactDOM[FLUSH_SYNC];
  5053. var USE_ID = "useId";
  5054. var useIdImpl = React2[USE_ID];
  5055. function startTransitionSafe(cb) {
  5056. if (startTransitionImpl2) {
  5057. startTransitionImpl2(cb);
  5058. } else {
  5059. cb();
  5060. }
  5061. }
  5062. function flushSyncSafe(cb) {
  5063. if (flushSyncImpl) {
  5064. flushSyncImpl(cb);
  5065. } else {
  5066. cb();
  5067. }
  5068. }
  5069. var Deferred = class {
  5070. constructor() {
  5071. this.status = "pending";
  5072. this.promise = new Promise((resolve, reject) => {
  5073. this.resolve = (value) => {
  5074. if (this.status === "pending") {
  5075. this.status = "resolved";
  5076. resolve(value);
  5077. }
  5078. };
  5079. this.reject = (reason) => {
  5080. if (this.status === "pending") {
  5081. this.status = "rejected";
  5082. reject(reason);
  5083. }
  5084. };
  5085. });
  5086. }
  5087. };
  5088. function RouterProvider(_ref) {
  5089. let {
  5090. fallbackElement,
  5091. router,
  5092. future
  5093. } = _ref;
  5094. let [state, setStateImpl] = React2.useState(router.state);
  5095. let [pendingState, setPendingState] = React2.useState();
  5096. let [vtContext, setVtContext] = React2.useState({
  5097. isTransitioning: false
  5098. });
  5099. let [renderDfd, setRenderDfd] = React2.useState();
  5100. let [transition, setTransition] = React2.useState();
  5101. let [interruption, setInterruption] = React2.useState();
  5102. let fetcherData = React2.useRef(/* @__PURE__ */ new Map());
  5103. let {
  5104. v7_startTransition
  5105. } = future || {};
  5106. let optInStartTransition = React2.useCallback((cb) => {
  5107. if (v7_startTransition) {
  5108. startTransitionSafe(cb);
  5109. } else {
  5110. cb();
  5111. }
  5112. }, [v7_startTransition]);
  5113. let setState = React2.useCallback((newState, _ref2) => {
  5114. let {
  5115. deletedFetchers,
  5116. flushSync,
  5117. viewTransitionOpts
  5118. } = _ref2;
  5119. newState.fetchers.forEach((fetcher, key) => {
  5120. if (fetcher.data !== void 0) {
  5121. fetcherData.current.set(key, fetcher.data);
  5122. }
  5123. });
  5124. deletedFetchers.forEach((key) => fetcherData.current.delete(key));
  5125. let isViewTransitionUnavailable = router.window == null || router.window.document == null || typeof router.window.document.startViewTransition !== "function";
  5126. if (!viewTransitionOpts || isViewTransitionUnavailable) {
  5127. if (flushSync) {
  5128. flushSyncSafe(() => setStateImpl(newState));
  5129. } else {
  5130. optInStartTransition(() => setStateImpl(newState));
  5131. }
  5132. return;
  5133. }
  5134. if (flushSync) {
  5135. flushSyncSafe(() => {
  5136. if (transition) {
  5137. renderDfd && renderDfd.resolve();
  5138. transition.skipTransition();
  5139. }
  5140. setVtContext({
  5141. isTransitioning: true,
  5142. flushSync: true,
  5143. currentLocation: viewTransitionOpts.currentLocation,
  5144. nextLocation: viewTransitionOpts.nextLocation
  5145. });
  5146. });
  5147. let t = router.window.document.startViewTransition(() => {
  5148. flushSyncSafe(() => setStateImpl(newState));
  5149. });
  5150. t.finished.finally(() => {
  5151. flushSyncSafe(() => {
  5152. setRenderDfd(void 0);
  5153. setTransition(void 0);
  5154. setPendingState(void 0);
  5155. setVtContext({
  5156. isTransitioning: false
  5157. });
  5158. });
  5159. });
  5160. flushSyncSafe(() => setTransition(t));
  5161. return;
  5162. }
  5163. if (transition) {
  5164. renderDfd && renderDfd.resolve();
  5165. transition.skipTransition();
  5166. setInterruption({
  5167. state: newState,
  5168. currentLocation: viewTransitionOpts.currentLocation,
  5169. nextLocation: viewTransitionOpts.nextLocation
  5170. });
  5171. } else {
  5172. setPendingState(newState);
  5173. setVtContext({
  5174. isTransitioning: true,
  5175. flushSync: false,
  5176. currentLocation: viewTransitionOpts.currentLocation,
  5177. nextLocation: viewTransitionOpts.nextLocation
  5178. });
  5179. }
  5180. }, [router.window, transition, renderDfd, fetcherData, optInStartTransition]);
  5181. React2.useLayoutEffect(() => router.subscribe(setState), [router, setState]);
  5182. React2.useEffect(() => {
  5183. if (vtContext.isTransitioning && !vtContext.flushSync) {
  5184. setRenderDfd(new Deferred());
  5185. }
  5186. }, [vtContext]);
  5187. React2.useEffect(() => {
  5188. if (renderDfd && pendingState && router.window) {
  5189. let newState = pendingState;
  5190. let renderPromise = renderDfd.promise;
  5191. let transition2 = router.window.document.startViewTransition(async () => {
  5192. optInStartTransition(() => setStateImpl(newState));
  5193. await renderPromise;
  5194. });
  5195. transition2.finished.finally(() => {
  5196. setRenderDfd(void 0);
  5197. setTransition(void 0);
  5198. setPendingState(void 0);
  5199. setVtContext({
  5200. isTransitioning: false
  5201. });
  5202. });
  5203. setTransition(transition2);
  5204. }
  5205. }, [optInStartTransition, pendingState, renderDfd, router.window]);
  5206. React2.useEffect(() => {
  5207. if (renderDfd && pendingState && state.location.key === pendingState.location.key) {
  5208. renderDfd.resolve();
  5209. }
  5210. }, [renderDfd, transition, state.location, pendingState]);
  5211. React2.useEffect(() => {
  5212. if (!vtContext.isTransitioning && interruption) {
  5213. setPendingState(interruption.state);
  5214. setVtContext({
  5215. isTransitioning: true,
  5216. flushSync: false,
  5217. currentLocation: interruption.currentLocation,
  5218. nextLocation: interruption.nextLocation
  5219. });
  5220. setInterruption(void 0);
  5221. }
  5222. }, [vtContext.isTransitioning, interruption]);
  5223. React2.useEffect(() => {
  5224. true ? warning(fallbackElement == null || !router.future.v7_partialHydration, "`<RouterProvider fallbackElement>` is deprecated when using `v7_partialHydration`, use a `HydrateFallback` component instead") : void 0;
  5225. }, []);
  5226. let navigator = React2.useMemo(() => {
  5227. return {
  5228. createHref: router.createHref,
  5229. encodeLocation: router.encodeLocation,
  5230. go: (n) => router.navigate(n),
  5231. push: (to, state2, opts) => router.navigate(to, {
  5232. state: state2,
  5233. preventScrollReset: opts == null ? void 0 : opts.preventScrollReset
  5234. }),
  5235. replace: (to, state2, opts) => router.navigate(to, {
  5236. replace: true,
  5237. state: state2,
  5238. preventScrollReset: opts == null ? void 0 : opts.preventScrollReset
  5239. })
  5240. };
  5241. }, [router]);
  5242. let basename = router.basename || "/";
  5243. let dataRouterContext = React2.useMemo(() => ({
  5244. router,
  5245. navigator,
  5246. static: false,
  5247. basename
  5248. }), [router, navigator, basename]);
  5249. let routerFuture = React2.useMemo(() => ({
  5250. v7_relativeSplatPath: router.future.v7_relativeSplatPath
  5251. }), [router.future.v7_relativeSplatPath]);
  5252. React2.useEffect(() => logV6DeprecationWarnings(future, router.future), [future, router.future]);
  5253. return React2.createElement(React2.Fragment, null, React2.createElement(DataRouterContext.Provider, {
  5254. value: dataRouterContext
  5255. }, React2.createElement(DataRouterStateContext.Provider, {
  5256. value: state
  5257. }, React2.createElement(FetchersContext.Provider, {
  5258. value: fetcherData.current
  5259. }, React2.createElement(ViewTransitionContext.Provider, {
  5260. value: vtContext
  5261. }, React2.createElement(Router, {
  5262. basename,
  5263. location: state.location,
  5264. navigationType: state.historyAction,
  5265. navigator,
  5266. future: routerFuture
  5267. }, state.initialized || router.future.v7_partialHydration ? React2.createElement(MemoizedDataRoutes, {
  5268. routes: router.routes,
  5269. future: router.future,
  5270. state
  5271. }) : fallbackElement))))), null);
  5272. }
  5273. var MemoizedDataRoutes = React2.memo(DataRoutes);
  5274. function DataRoutes(_ref3) {
  5275. let {
  5276. routes,
  5277. future,
  5278. state
  5279. } = _ref3;
  5280. return useRoutesImpl(routes, void 0, state, future);
  5281. }
  5282. function BrowserRouter(_ref4) {
  5283. let {
  5284. basename,
  5285. children,
  5286. future,
  5287. window: window2
  5288. } = _ref4;
  5289. let historyRef = React2.useRef();
  5290. if (historyRef.current == null) {
  5291. historyRef.current = createBrowserHistory({
  5292. window: window2,
  5293. v5Compat: true
  5294. });
  5295. }
  5296. let history = historyRef.current;
  5297. let [state, setStateImpl] = React2.useState({
  5298. action: history.action,
  5299. location: history.location
  5300. });
  5301. let {
  5302. v7_startTransition
  5303. } = future || {};
  5304. let setState = React2.useCallback((newState) => {
  5305. v7_startTransition && startTransitionImpl2 ? startTransitionImpl2(() => setStateImpl(newState)) : setStateImpl(newState);
  5306. }, [setStateImpl, v7_startTransition]);
  5307. React2.useLayoutEffect(() => history.listen(setState), [history, setState]);
  5308. React2.useEffect(() => logV6DeprecationWarnings(future), [future]);
  5309. return React2.createElement(Router, {
  5310. basename,
  5311. children,
  5312. location: state.location,
  5313. navigationType: state.action,
  5314. navigator: history,
  5315. future
  5316. });
  5317. }
  5318. function HashRouter(_ref5) {
  5319. let {
  5320. basename,
  5321. children,
  5322. future,
  5323. window: window2
  5324. } = _ref5;
  5325. let historyRef = React2.useRef();
  5326. if (historyRef.current == null) {
  5327. historyRef.current = createHashHistory({
  5328. window: window2,
  5329. v5Compat: true
  5330. });
  5331. }
  5332. let history = historyRef.current;
  5333. let [state, setStateImpl] = React2.useState({
  5334. action: history.action,
  5335. location: history.location
  5336. });
  5337. let {
  5338. v7_startTransition
  5339. } = future || {};
  5340. let setState = React2.useCallback((newState) => {
  5341. v7_startTransition && startTransitionImpl2 ? startTransitionImpl2(() => setStateImpl(newState)) : setStateImpl(newState);
  5342. }, [setStateImpl, v7_startTransition]);
  5343. React2.useLayoutEffect(() => history.listen(setState), [history, setState]);
  5344. React2.useEffect(() => logV6DeprecationWarnings(future), [future]);
  5345. return React2.createElement(Router, {
  5346. basename,
  5347. children,
  5348. location: state.location,
  5349. navigationType: state.action,
  5350. navigator: history,
  5351. future
  5352. });
  5353. }
  5354. function HistoryRouter(_ref6) {
  5355. let {
  5356. basename,
  5357. children,
  5358. future,
  5359. history
  5360. } = _ref6;
  5361. let [state, setStateImpl] = React2.useState({
  5362. action: history.action,
  5363. location: history.location
  5364. });
  5365. let {
  5366. v7_startTransition
  5367. } = future || {};
  5368. let setState = React2.useCallback((newState) => {
  5369. v7_startTransition && startTransitionImpl2 ? startTransitionImpl2(() => setStateImpl(newState)) : setStateImpl(newState);
  5370. }, [setStateImpl, v7_startTransition]);
  5371. React2.useLayoutEffect(() => history.listen(setState), [history, setState]);
  5372. React2.useEffect(() => logV6DeprecationWarnings(future), [future]);
  5373. return React2.createElement(Router, {
  5374. basename,
  5375. children,
  5376. location: state.location,
  5377. navigationType: state.action,
  5378. navigator: history,
  5379. future
  5380. });
  5381. }
  5382. if (true) {
  5383. HistoryRouter.displayName = "unstable_HistoryRouter";
  5384. }
  5385. var isBrowser = typeof window !== "undefined" && typeof window.document !== "undefined" && typeof window.document.createElement !== "undefined";
  5386. var ABSOLUTE_URL_REGEX2 = /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i;
  5387. var Link = React2.forwardRef(function LinkWithRef(_ref7, ref) {
  5388. let {
  5389. onClick,
  5390. relative,
  5391. reloadDocument,
  5392. replace: replace2,
  5393. state,
  5394. target,
  5395. to,
  5396. preventScrollReset,
  5397. viewTransition
  5398. } = _ref7, rest = _objectWithoutPropertiesLoose(_ref7, _excluded);
  5399. let {
  5400. basename
  5401. } = React2.useContext(NavigationContext);
  5402. let absoluteHref;
  5403. let isExternal = false;
  5404. if (typeof to === "string" && ABSOLUTE_URL_REGEX2.test(to)) {
  5405. absoluteHref = to;
  5406. if (isBrowser) {
  5407. try {
  5408. let currentUrl = new URL(window.location.href);
  5409. let targetUrl = to.startsWith("//") ? new URL(currentUrl.protocol + to) : new URL(to);
  5410. let path = stripBasename(targetUrl.pathname, basename);
  5411. if (targetUrl.origin === currentUrl.origin && path != null) {
  5412. to = path + targetUrl.search + targetUrl.hash;
  5413. } else {
  5414. isExternal = true;
  5415. }
  5416. } catch (e) {
  5417. true ? warning(false, '<Link to="' + to + '"> contains an invalid URL which will probably break when clicked - please update to a valid URL path.') : void 0;
  5418. }
  5419. }
  5420. }
  5421. let href = useHref(to, {
  5422. relative
  5423. });
  5424. let internalOnClick = useLinkClickHandler(to, {
  5425. replace: replace2,
  5426. state,
  5427. target,
  5428. preventScrollReset,
  5429. relative,
  5430. viewTransition
  5431. });
  5432. function handleClick(event) {
  5433. if (onClick) onClick(event);
  5434. if (!event.defaultPrevented) {
  5435. internalOnClick(event);
  5436. }
  5437. }
  5438. return (
  5439. // eslint-disable-next-line jsx-a11y/anchor-has-content
  5440. React2.createElement("a", _extends3({}, rest, {
  5441. href: absoluteHref || href,
  5442. onClick: isExternal || reloadDocument ? onClick : handleClick,
  5443. ref,
  5444. target
  5445. }))
  5446. );
  5447. });
  5448. if (true) {
  5449. Link.displayName = "Link";
  5450. }
  5451. var NavLink = React2.forwardRef(function NavLinkWithRef(_ref8, ref) {
  5452. let {
  5453. "aria-current": ariaCurrentProp = "page",
  5454. caseSensitive = false,
  5455. className: classNameProp = "",
  5456. end = false,
  5457. style: styleProp,
  5458. to,
  5459. viewTransition,
  5460. children
  5461. } = _ref8, rest = _objectWithoutPropertiesLoose(_ref8, _excluded2);
  5462. let path = useResolvedPath(to, {
  5463. relative: rest.relative
  5464. });
  5465. let location = useLocation();
  5466. let routerState = React2.useContext(DataRouterStateContext);
  5467. let {
  5468. navigator,
  5469. basename
  5470. } = React2.useContext(NavigationContext);
  5471. let isTransitioning = routerState != null && // Conditional usage is OK here because the usage of a data router is static
  5472. // eslint-disable-next-line react-hooks/rules-of-hooks
  5473. useViewTransitionState(path) && viewTransition === true;
  5474. let toPathname = navigator.encodeLocation ? navigator.encodeLocation(path).pathname : path.pathname;
  5475. let locationPathname = location.pathname;
  5476. let nextLocationPathname = routerState && routerState.navigation && routerState.navigation.location ? routerState.navigation.location.pathname : null;
  5477. if (!caseSensitive) {
  5478. locationPathname = locationPathname.toLowerCase();
  5479. nextLocationPathname = nextLocationPathname ? nextLocationPathname.toLowerCase() : null;
  5480. toPathname = toPathname.toLowerCase();
  5481. }
  5482. if (nextLocationPathname && basename) {
  5483. nextLocationPathname = stripBasename(nextLocationPathname, basename) || nextLocationPathname;
  5484. }
  5485. const endSlashPosition = toPathname !== "/" && toPathname.endsWith("/") ? toPathname.length - 1 : toPathname.length;
  5486. let isActive = locationPathname === toPathname || !end && locationPathname.startsWith(toPathname) && locationPathname.charAt(endSlashPosition) === "/";
  5487. let isPending = nextLocationPathname != null && (nextLocationPathname === toPathname || !end && nextLocationPathname.startsWith(toPathname) && nextLocationPathname.charAt(toPathname.length) === "/");
  5488. let renderProps = {
  5489. isActive,
  5490. isPending,
  5491. isTransitioning
  5492. };
  5493. let ariaCurrent = isActive ? ariaCurrentProp : void 0;
  5494. let className;
  5495. if (typeof classNameProp === "function") {
  5496. className = classNameProp(renderProps);
  5497. } else {
  5498. className = [classNameProp, isActive ? "active" : null, isPending ? "pending" : null, isTransitioning ? "transitioning" : null].filter(Boolean).join(" ");
  5499. }
  5500. let style = typeof styleProp === "function" ? styleProp(renderProps) : styleProp;
  5501. return React2.createElement(Link, _extends3({}, rest, {
  5502. "aria-current": ariaCurrent,
  5503. className,
  5504. ref,
  5505. style,
  5506. to,
  5507. viewTransition
  5508. }), typeof children === "function" ? children(renderProps) : children);
  5509. });
  5510. if (true) {
  5511. NavLink.displayName = "NavLink";
  5512. }
  5513. var Form = React2.forwardRef((_ref9, forwardedRef) => {
  5514. let {
  5515. fetcherKey,
  5516. navigate,
  5517. reloadDocument,
  5518. replace: replace2,
  5519. state,
  5520. method = defaultMethod,
  5521. action,
  5522. onSubmit,
  5523. relative,
  5524. preventScrollReset,
  5525. viewTransition
  5526. } = _ref9, props = _objectWithoutPropertiesLoose(_ref9, _excluded3);
  5527. let submit = useSubmit();
  5528. let formAction = useFormAction(action, {
  5529. relative
  5530. });
  5531. let formMethod = method.toLowerCase() === "get" ? "get" : "post";
  5532. let submitHandler = (event) => {
  5533. onSubmit && onSubmit(event);
  5534. if (event.defaultPrevented) return;
  5535. event.preventDefault();
  5536. let submitter = event.nativeEvent.submitter;
  5537. let submitMethod = (submitter == null ? void 0 : submitter.getAttribute("formmethod")) || method;
  5538. submit(submitter || event.currentTarget, {
  5539. fetcherKey,
  5540. method: submitMethod,
  5541. navigate,
  5542. replace: replace2,
  5543. state,
  5544. relative,
  5545. preventScrollReset,
  5546. viewTransition
  5547. });
  5548. };
  5549. return React2.createElement("form", _extends3({
  5550. ref: forwardedRef,
  5551. method: formMethod,
  5552. action: formAction,
  5553. onSubmit: reloadDocument ? onSubmit : submitHandler
  5554. }, props));
  5555. });
  5556. if (true) {
  5557. Form.displayName = "Form";
  5558. }
  5559. function ScrollRestoration(_ref10) {
  5560. let {
  5561. getKey,
  5562. storageKey
  5563. } = _ref10;
  5564. useScrollRestoration({
  5565. getKey,
  5566. storageKey
  5567. });
  5568. return null;
  5569. }
  5570. if (true) {
  5571. ScrollRestoration.displayName = "ScrollRestoration";
  5572. }
  5573. var DataRouterHook2;
  5574. (function(DataRouterHook3) {
  5575. DataRouterHook3["UseScrollRestoration"] = "useScrollRestoration";
  5576. DataRouterHook3["UseSubmit"] = "useSubmit";
  5577. DataRouterHook3["UseSubmitFetcher"] = "useSubmitFetcher";
  5578. DataRouterHook3["UseFetcher"] = "useFetcher";
  5579. DataRouterHook3["useViewTransitionState"] = "useViewTransitionState";
  5580. })(DataRouterHook2 || (DataRouterHook2 = {}));
  5581. var DataRouterStateHook2;
  5582. (function(DataRouterStateHook3) {
  5583. DataRouterStateHook3["UseFetcher"] = "useFetcher";
  5584. DataRouterStateHook3["UseFetchers"] = "useFetchers";
  5585. DataRouterStateHook3["UseScrollRestoration"] = "useScrollRestoration";
  5586. })(DataRouterStateHook2 || (DataRouterStateHook2 = {}));
  5587. function getDataRouterConsoleError2(hookName) {
  5588. return hookName + " must be used within a data router. See https://reactrouter.com/v6/routers/picking-a-router.";
  5589. }
  5590. function useDataRouterContext2(hookName) {
  5591. let ctx = React2.useContext(DataRouterContext);
  5592. !ctx ? true ? invariant(false, getDataRouterConsoleError2(hookName)) : invariant(false) : void 0;
  5593. return ctx;
  5594. }
  5595. function useDataRouterState2(hookName) {
  5596. let state = React2.useContext(DataRouterStateContext);
  5597. !state ? true ? invariant(false, getDataRouterConsoleError2(hookName)) : invariant(false) : void 0;
  5598. return state;
  5599. }
  5600. function useLinkClickHandler(to, _temp) {
  5601. let {
  5602. target,
  5603. replace: replaceProp,
  5604. state,
  5605. preventScrollReset,
  5606. relative,
  5607. viewTransition
  5608. } = _temp === void 0 ? {} : _temp;
  5609. let navigate = useNavigate();
  5610. let location = useLocation();
  5611. let path = useResolvedPath(to, {
  5612. relative
  5613. });
  5614. return React2.useCallback((event) => {
  5615. if (shouldProcessLinkClick(event, target)) {
  5616. event.preventDefault();
  5617. let replace2 = replaceProp !== void 0 ? replaceProp : createPath(location) === createPath(path);
  5618. navigate(to, {
  5619. replace: replace2,
  5620. state,
  5621. preventScrollReset,
  5622. relative,
  5623. viewTransition
  5624. });
  5625. }
  5626. }, [location, navigate, path, replaceProp, state, target, to, preventScrollReset, relative, viewTransition]);
  5627. }
  5628. function useSearchParams(defaultInit) {
  5629. true ? warning(typeof URLSearchParams !== "undefined", "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.") : void 0;
  5630. let defaultSearchParamsRef = React2.useRef(createSearchParams(defaultInit));
  5631. let hasSetSearchParamsRef = React2.useRef(false);
  5632. let location = useLocation();
  5633. let searchParams = React2.useMemo(() => (
  5634. // Only merge in the defaults if we haven't yet called setSearchParams.
  5635. // Once we call that we want those to take precedence, otherwise you can't
  5636. // remove a param with setSearchParams({}) if it has an initial value
  5637. getSearchParamsForLocation(location.search, hasSetSearchParamsRef.current ? null : defaultSearchParamsRef.current)
  5638. ), [location.search]);
  5639. let navigate = useNavigate();
  5640. let setSearchParams = React2.useCallback((nextInit, navigateOptions) => {
  5641. const newSearchParams = createSearchParams(typeof nextInit === "function" ? nextInit(searchParams) : nextInit);
  5642. hasSetSearchParamsRef.current = true;
  5643. navigate("?" + newSearchParams, navigateOptions);
  5644. }, [navigate, searchParams]);
  5645. return [searchParams, setSearchParams];
  5646. }
  5647. function validateClientSideSubmission() {
  5648. if (typeof document === "undefined") {
  5649. throw new Error("You are calling submit during the server render. Try calling submit within a `useEffect` or callback instead.");
  5650. }
  5651. }
  5652. var fetcherId = 0;
  5653. var getUniqueFetcherId = () => "__" + String(++fetcherId) + "__";
  5654. function useSubmit() {
  5655. let {
  5656. router
  5657. } = useDataRouterContext2(DataRouterHook2.UseSubmit);
  5658. let {
  5659. basename
  5660. } = React2.useContext(NavigationContext);
  5661. let currentRouteId = useRouteId();
  5662. return React2.useCallback(function(target, options) {
  5663. if (options === void 0) {
  5664. options = {};
  5665. }
  5666. validateClientSideSubmission();
  5667. let {
  5668. action,
  5669. method,
  5670. encType,
  5671. formData,
  5672. body
  5673. } = getFormSubmissionInfo(target, basename);
  5674. if (options.navigate === false) {
  5675. let key = options.fetcherKey || getUniqueFetcherId();
  5676. router.fetch(key, currentRouteId, options.action || action, {
  5677. preventScrollReset: options.preventScrollReset,
  5678. formData,
  5679. body,
  5680. formMethod: options.method || method,
  5681. formEncType: options.encType || encType,
  5682. flushSync: options.flushSync
  5683. });
  5684. } else {
  5685. router.navigate(options.action || action, {
  5686. preventScrollReset: options.preventScrollReset,
  5687. formData,
  5688. body,
  5689. formMethod: options.method || method,
  5690. formEncType: options.encType || encType,
  5691. replace: options.replace,
  5692. state: options.state,
  5693. fromRouteId: currentRouteId,
  5694. flushSync: options.flushSync,
  5695. viewTransition: options.viewTransition
  5696. });
  5697. }
  5698. }, [router, basename, currentRouteId]);
  5699. }
  5700. function useFormAction(action, _temp2) {
  5701. let {
  5702. relative
  5703. } = _temp2 === void 0 ? {} : _temp2;
  5704. let {
  5705. basename
  5706. } = React2.useContext(NavigationContext);
  5707. let routeContext = React2.useContext(RouteContext);
  5708. !routeContext ? true ? invariant(false, "useFormAction must be used inside a RouteContext") : invariant(false) : void 0;
  5709. let [match] = routeContext.matches.slice(-1);
  5710. let path = _extends3({}, useResolvedPath(action ? action : ".", {
  5711. relative
  5712. }));
  5713. let location = useLocation();
  5714. if (action == null) {
  5715. path.search = location.search;
  5716. let params = new URLSearchParams(path.search);
  5717. let indexValues = params.getAll("index");
  5718. let hasNakedIndexParam = indexValues.some((v) => v === "");
  5719. if (hasNakedIndexParam) {
  5720. params.delete("index");
  5721. indexValues.filter((v) => v).forEach((v) => params.append("index", v));
  5722. let qs = params.toString();
  5723. path.search = qs ? "?" + qs : "";
  5724. }
  5725. }
  5726. if ((!action || action === ".") && match.route.index) {
  5727. path.search = path.search ? path.search.replace(/^\?/, "?index&") : "?index";
  5728. }
  5729. if (basename !== "/") {
  5730. path.pathname = path.pathname === "/" ? basename : joinPaths([basename, path.pathname]);
  5731. }
  5732. return createPath(path);
  5733. }
  5734. function useFetcher(_temp3) {
  5735. var _route$matches;
  5736. let {
  5737. key
  5738. } = _temp3 === void 0 ? {} : _temp3;
  5739. let {
  5740. router
  5741. } = useDataRouterContext2(DataRouterHook2.UseFetcher);
  5742. let state = useDataRouterState2(DataRouterStateHook2.UseFetcher);
  5743. let fetcherData = React2.useContext(FetchersContext);
  5744. let route = React2.useContext(RouteContext);
  5745. let routeId = (_route$matches = route.matches[route.matches.length - 1]) == null ? void 0 : _route$matches.route.id;
  5746. !fetcherData ? true ? invariant(false, "useFetcher must be used inside a FetchersContext") : invariant(false) : void 0;
  5747. !route ? true ? invariant(false, "useFetcher must be used inside a RouteContext") : invariant(false) : void 0;
  5748. !(routeId != null) ? true ? invariant(false, 'useFetcher can only be used on routes that contain a unique "id"') : invariant(false) : void 0;
  5749. let defaultKey = useIdImpl ? useIdImpl() : "";
  5750. let [fetcherKey, setFetcherKey] = React2.useState(key || defaultKey);
  5751. if (key && key !== fetcherKey) {
  5752. setFetcherKey(key);
  5753. } else if (!fetcherKey) {
  5754. setFetcherKey(getUniqueFetcherId());
  5755. }
  5756. React2.useEffect(() => {
  5757. router.getFetcher(fetcherKey);
  5758. return () => {
  5759. router.deleteFetcher(fetcherKey);
  5760. };
  5761. }, [router, fetcherKey]);
  5762. let load = React2.useCallback((href, opts) => {
  5763. !routeId ? true ? invariant(false, "No routeId available for fetcher.load()") : invariant(false) : void 0;
  5764. router.fetch(fetcherKey, routeId, href, opts);
  5765. }, [fetcherKey, routeId, router]);
  5766. let submitImpl = useSubmit();
  5767. let submit = React2.useCallback((target, opts) => {
  5768. submitImpl(target, _extends3({}, opts, {
  5769. navigate: false,
  5770. fetcherKey
  5771. }));
  5772. }, [fetcherKey, submitImpl]);
  5773. let FetcherForm = React2.useMemo(() => {
  5774. let FetcherForm2 = React2.forwardRef((props, ref) => {
  5775. return React2.createElement(Form, _extends3({}, props, {
  5776. navigate: false,
  5777. fetcherKey,
  5778. ref
  5779. }));
  5780. });
  5781. if (true) {
  5782. FetcherForm2.displayName = "fetcher.Form";
  5783. }
  5784. return FetcherForm2;
  5785. }, [fetcherKey]);
  5786. let fetcher = state.fetchers.get(fetcherKey) || IDLE_FETCHER;
  5787. let data = fetcherData.get(fetcherKey);
  5788. let fetcherWithComponents = React2.useMemo(() => _extends3({
  5789. Form: FetcherForm,
  5790. submit,
  5791. load
  5792. }, fetcher, {
  5793. data
  5794. }), [FetcherForm, submit, load, fetcher, data]);
  5795. return fetcherWithComponents;
  5796. }
  5797. function useFetchers() {
  5798. let state = useDataRouterState2(DataRouterStateHook2.UseFetchers);
  5799. return Array.from(state.fetchers.entries()).map((_ref11) => {
  5800. let [key, fetcher] = _ref11;
  5801. return _extends3({}, fetcher, {
  5802. key
  5803. });
  5804. });
  5805. }
  5806. var SCROLL_RESTORATION_STORAGE_KEY = "react-router-scroll-positions";
  5807. var savedScrollPositions = {};
  5808. function useScrollRestoration(_temp4) {
  5809. let {
  5810. getKey,
  5811. storageKey
  5812. } = _temp4 === void 0 ? {} : _temp4;
  5813. let {
  5814. router
  5815. } = useDataRouterContext2(DataRouterHook2.UseScrollRestoration);
  5816. let {
  5817. restoreScrollPosition,
  5818. preventScrollReset
  5819. } = useDataRouterState2(DataRouterStateHook2.UseScrollRestoration);
  5820. let {
  5821. basename
  5822. } = React2.useContext(NavigationContext);
  5823. let location = useLocation();
  5824. let matches = useMatches();
  5825. let navigation = useNavigation();
  5826. React2.useEffect(() => {
  5827. window.history.scrollRestoration = "manual";
  5828. return () => {
  5829. window.history.scrollRestoration = "auto";
  5830. };
  5831. }, []);
  5832. usePageHide(React2.useCallback(() => {
  5833. if (navigation.state === "idle") {
  5834. let key = (getKey ? getKey(location, matches) : null) || location.key;
  5835. savedScrollPositions[key] = window.scrollY;
  5836. }
  5837. try {
  5838. sessionStorage.setItem(storageKey || SCROLL_RESTORATION_STORAGE_KEY, JSON.stringify(savedScrollPositions));
  5839. } catch (error) {
  5840. true ? warning(false, "Failed to save scroll positions in sessionStorage, <ScrollRestoration /> will not work properly (" + error + ").") : void 0;
  5841. }
  5842. window.history.scrollRestoration = "auto";
  5843. }, [storageKey, getKey, navigation.state, location, matches]));
  5844. if (typeof document !== "undefined") {
  5845. React2.useLayoutEffect(() => {
  5846. try {
  5847. let sessionPositions = sessionStorage.getItem(storageKey || SCROLL_RESTORATION_STORAGE_KEY);
  5848. if (sessionPositions) {
  5849. savedScrollPositions = JSON.parse(sessionPositions);
  5850. }
  5851. } catch (e) {
  5852. }
  5853. }, [storageKey]);
  5854. React2.useLayoutEffect(() => {
  5855. let getKeyWithoutBasename = getKey && basename !== "/" ? (location2, matches2) => getKey(
  5856. // Strip the basename to match useLocation()
  5857. _extends3({}, location2, {
  5858. pathname: stripBasename(location2.pathname, basename) || location2.pathname
  5859. }),
  5860. matches2
  5861. ) : getKey;
  5862. let disableScrollRestoration = router == null ? void 0 : router.enableScrollRestoration(savedScrollPositions, () => window.scrollY, getKeyWithoutBasename);
  5863. return () => disableScrollRestoration && disableScrollRestoration();
  5864. }, [router, basename, getKey]);
  5865. React2.useLayoutEffect(() => {
  5866. if (restoreScrollPosition === false) {
  5867. return;
  5868. }
  5869. if (typeof restoreScrollPosition === "number") {
  5870. window.scrollTo(0, restoreScrollPosition);
  5871. return;
  5872. }
  5873. if (location.hash) {
  5874. let el = document.getElementById(decodeURIComponent(location.hash.slice(1)));
  5875. if (el) {
  5876. el.scrollIntoView();
  5877. return;
  5878. }
  5879. }
  5880. if (preventScrollReset === true) {
  5881. return;
  5882. }
  5883. window.scrollTo(0, 0);
  5884. }, [location, restoreScrollPosition, preventScrollReset]);
  5885. }
  5886. }
  5887. function useBeforeUnload(callback, options) {
  5888. let {
  5889. capture
  5890. } = options || {};
  5891. React2.useEffect(() => {
  5892. let opts = capture != null ? {
  5893. capture
  5894. } : void 0;
  5895. window.addEventListener("beforeunload", callback, opts);
  5896. return () => {
  5897. window.removeEventListener("beforeunload", callback, opts);
  5898. };
  5899. }, [callback, capture]);
  5900. }
  5901. function usePageHide(callback, options) {
  5902. let {
  5903. capture
  5904. } = options || {};
  5905. React2.useEffect(() => {
  5906. let opts = capture != null ? {
  5907. capture
  5908. } : void 0;
  5909. window.addEventListener("pagehide", callback, opts);
  5910. return () => {
  5911. window.removeEventListener("pagehide", callback, opts);
  5912. };
  5913. }, [callback, capture]);
  5914. }
  5915. function usePrompt(_ref12) {
  5916. let {
  5917. when,
  5918. message
  5919. } = _ref12;
  5920. let blocker = useBlocker(when);
  5921. React2.useEffect(() => {
  5922. if (blocker.state === "blocked") {
  5923. let proceed = window.confirm(message);
  5924. if (proceed) {
  5925. setTimeout(blocker.proceed, 0);
  5926. } else {
  5927. blocker.reset();
  5928. }
  5929. }
  5930. }, [blocker, message]);
  5931. React2.useEffect(() => {
  5932. if (blocker.state === "blocked" && !when) {
  5933. blocker.reset();
  5934. }
  5935. }, [blocker, when]);
  5936. }
  5937. function useViewTransitionState(to, opts) {
  5938. if (opts === void 0) {
  5939. opts = {};
  5940. }
  5941. let vtContext = React2.useContext(ViewTransitionContext);
  5942. !(vtContext != null) ? true ? invariant(false, "`useViewTransitionState` must be used within `react-router-dom`'s `RouterProvider`. Did you accidentally import `RouterProvider` from `react-router`?") : invariant(false) : void 0;
  5943. let {
  5944. basename
  5945. } = useDataRouterContext2(DataRouterHook2.useViewTransitionState);
  5946. let path = useResolvedPath(to, {
  5947. relative: opts.relative
  5948. });
  5949. if (!vtContext.isTransitioning) {
  5950. return false;
  5951. }
  5952. let currentPath = stripBasename(vtContext.currentLocation.pathname, basename) || vtContext.currentLocation.pathname;
  5953. let nextPath = stripBasename(vtContext.nextLocation.pathname, basename) || vtContext.nextLocation.pathname;
  5954. return matchPath(path.pathname, nextPath) != null || matchPath(path.pathname, currentPath) != null;
  5955. }
  5956. export {
  5957. AbortedDeferredError,
  5958. Await,
  5959. BrowserRouter,
  5960. Form,
  5961. HashRouter,
  5962. Link,
  5963. MemoryRouter,
  5964. NavLink,
  5965. Navigate,
  5966. Action as NavigationType,
  5967. Outlet,
  5968. Route,
  5969. Router,
  5970. RouterProvider,
  5971. Routes,
  5972. ScrollRestoration,
  5973. DataRouterContext as UNSAFE_DataRouterContext,
  5974. DataRouterStateContext as UNSAFE_DataRouterStateContext,
  5975. ErrorResponseImpl as UNSAFE_ErrorResponseImpl,
  5976. FetchersContext as UNSAFE_FetchersContext,
  5977. LocationContext as UNSAFE_LocationContext,
  5978. NavigationContext as UNSAFE_NavigationContext,
  5979. RouteContext as UNSAFE_RouteContext,
  5980. ViewTransitionContext as UNSAFE_ViewTransitionContext,
  5981. useRouteId as UNSAFE_useRouteId,
  5982. useScrollRestoration as UNSAFE_useScrollRestoration,
  5983. createBrowserRouter,
  5984. createHashRouter,
  5985. createMemoryRouter,
  5986. createPath,
  5987. createRoutesFromChildren,
  5988. createRoutesFromChildren as createRoutesFromElements,
  5989. createSearchParams,
  5990. defer,
  5991. generatePath,
  5992. isRouteErrorResponse,
  5993. json,
  5994. matchPath,
  5995. matchRoutes,
  5996. parsePath,
  5997. redirect,
  5998. redirectDocument,
  5999. renderMatches,
  6000. replace,
  6001. resolvePath,
  6002. HistoryRouter as unstable_HistoryRouter,
  6003. usePrompt as unstable_usePrompt,
  6004. useActionData,
  6005. useAsyncError,
  6006. useAsyncValue,
  6007. useBeforeUnload,
  6008. useBlocker,
  6009. useFetcher,
  6010. useFetchers,
  6011. useFormAction,
  6012. useHref,
  6013. useInRouterContext,
  6014. useLinkClickHandler,
  6015. useLoaderData,
  6016. useLocation,
  6017. useMatch,
  6018. useMatches,
  6019. useNavigate,
  6020. useNavigation,
  6021. useNavigationType,
  6022. useOutlet,
  6023. useOutletContext,
  6024. useParams,
  6025. useResolvedPath,
  6026. useRevalidator,
  6027. useRouteError,
  6028. useRouteLoaderData,
  6029. useRoutes,
  6030. useSearchParams,
  6031. useSubmit,
  6032. useViewTransitionState
  6033. };
  6034. /*! Bundled license information:
  6035. @remix-run/router/dist/router.js:
  6036. (**
  6037. * @remix-run/router v1.23.2
  6038. *
  6039. * Copyright (c) Remix Software Inc.
  6040. *
  6041. * This source code is licensed under the MIT license found in the
  6042. * LICENSE.md file in the root directory of this source tree.
  6043. *
  6044. * @license MIT
  6045. *)
  6046. react-router/dist/index.js:
  6047. (**
  6048. * React Router v6.30.3
  6049. *
  6050. * Copyright (c) Remix Software Inc.
  6051. *
  6052. * This source code is licensed under the MIT license found in the
  6053. * LICENSE.md file in the root directory of this source tree.
  6054. *
  6055. * @license MIT
  6056. *)
  6057. react-router-dom/dist/index.js:
  6058. (**
  6059. * React Router DOM v6.30.3
  6060. *
  6061. * Copyright (c) Remix Software Inc.
  6062. *
  6063. * This source code is licensed under the MIT license found in the
  6064. * LICENSE.md file in the root directory of this source tree.
  6065. *
  6066. * @license MIT
  6067. *)
  6068. */
  6069. //# sourceMappingURL=react-router-dom.js.map