chunk-WWGJGFF6.mjs 340 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765
  1. /**
  2. * react-router v7.10.1
  3. *
  4. * Copyright (c) Remix Software Inc.
  5. *
  6. * This source code is licensed under the MIT license found in the
  7. * LICENSE.md file in the root directory of this source tree.
  8. *
  9. * @license MIT
  10. */
  11. var __typeError = (msg) => {
  12. throw TypeError(msg);
  13. };
  14. var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
  15. var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
  16. var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
  17. // lib/router/history.ts
  18. var Action = /* @__PURE__ */ ((Action2) => {
  19. Action2["Pop"] = "POP";
  20. Action2["Push"] = "PUSH";
  21. Action2["Replace"] = "REPLACE";
  22. return Action2;
  23. })(Action || {});
  24. var PopStateEventType = "popstate";
  25. function createMemoryHistory(options = {}) {
  26. let { initialEntries = ["/"], initialIndex, v5Compat = false } = options;
  27. let entries;
  28. entries = initialEntries.map(
  29. (entry, index2) => createMemoryLocation(
  30. entry,
  31. typeof entry === "string" ? null : entry.state,
  32. index2 === 0 ? "default" : void 0
  33. )
  34. );
  35. let index = clampIndex(
  36. initialIndex == null ? entries.length - 1 : initialIndex
  37. );
  38. let action = "POP" /* Pop */;
  39. let listener = null;
  40. function clampIndex(n) {
  41. return Math.min(Math.max(n, 0), entries.length - 1);
  42. }
  43. function getCurrentLocation() {
  44. return entries[index];
  45. }
  46. function createMemoryLocation(to, state = null, key) {
  47. let location = createLocation(
  48. entries ? getCurrentLocation().pathname : "/",
  49. to,
  50. state,
  51. key
  52. );
  53. warning(
  54. location.pathname.charAt(0) === "/",
  55. `relative pathnames are not supported in memory history: ${JSON.stringify(
  56. to
  57. )}`
  58. );
  59. return location;
  60. }
  61. function createHref2(to) {
  62. return typeof to === "string" ? to : createPath(to);
  63. }
  64. let history = {
  65. get index() {
  66. return index;
  67. },
  68. get action() {
  69. return action;
  70. },
  71. get location() {
  72. return getCurrentLocation();
  73. },
  74. createHref: createHref2,
  75. createURL(to) {
  76. return new URL(createHref2(to), "http://localhost");
  77. },
  78. encodeLocation(to) {
  79. let path = typeof to === "string" ? parsePath(to) : to;
  80. return {
  81. pathname: path.pathname || "",
  82. search: path.search || "",
  83. hash: path.hash || ""
  84. };
  85. },
  86. push(to, state) {
  87. action = "PUSH" /* Push */;
  88. let nextLocation = createMemoryLocation(to, state);
  89. index += 1;
  90. entries.splice(index, entries.length, nextLocation);
  91. if (v5Compat && listener) {
  92. listener({ action, location: nextLocation, delta: 1 });
  93. }
  94. },
  95. replace(to, state) {
  96. action = "REPLACE" /* Replace */;
  97. let nextLocation = createMemoryLocation(to, state);
  98. entries[index] = nextLocation;
  99. if (v5Compat && listener) {
  100. listener({ action, location: nextLocation, delta: 0 });
  101. }
  102. },
  103. go(delta) {
  104. action = "POP" /* Pop */;
  105. let nextIndex = clampIndex(index + delta);
  106. let nextLocation = entries[nextIndex];
  107. index = nextIndex;
  108. if (listener) {
  109. listener({ action, location: nextLocation, delta });
  110. }
  111. },
  112. listen(fn) {
  113. listener = fn;
  114. return () => {
  115. listener = null;
  116. };
  117. }
  118. };
  119. return history;
  120. }
  121. function createBrowserHistory(options = {}) {
  122. function createBrowserLocation(window2, globalHistory) {
  123. let { pathname, search, hash } = window2.location;
  124. return createLocation(
  125. "",
  126. { pathname, search, hash },
  127. // state defaults to `null` because `window.history.state` does
  128. globalHistory.state && globalHistory.state.usr || null,
  129. globalHistory.state && globalHistory.state.key || "default"
  130. );
  131. }
  132. function createBrowserHref(window2, to) {
  133. return typeof to === "string" ? to : createPath(to);
  134. }
  135. return getUrlBasedHistory(
  136. createBrowserLocation,
  137. createBrowserHref,
  138. null,
  139. options
  140. );
  141. }
  142. function createHashHistory(options = {}) {
  143. function createHashLocation(window2, globalHistory) {
  144. let {
  145. pathname = "/",
  146. search = "",
  147. hash = ""
  148. } = parsePath(window2.location.hash.substring(1));
  149. if (!pathname.startsWith("/") && !pathname.startsWith(".")) {
  150. pathname = "/" + pathname;
  151. }
  152. return createLocation(
  153. "",
  154. { pathname, search, hash },
  155. // state defaults to `null` because `window.history.state` does
  156. globalHistory.state && globalHistory.state.usr || null,
  157. globalHistory.state && globalHistory.state.key || "default"
  158. );
  159. }
  160. function createHashHref(window2, to) {
  161. let base = window2.document.querySelector("base");
  162. let href = "";
  163. if (base && base.getAttribute("href")) {
  164. let url = window2.location.href;
  165. let hashIndex = url.indexOf("#");
  166. href = hashIndex === -1 ? url : url.slice(0, hashIndex);
  167. }
  168. return href + "#" + (typeof to === "string" ? to : createPath(to));
  169. }
  170. function validateHashLocation(location, to) {
  171. warning(
  172. location.pathname.charAt(0) === "/",
  173. `relative pathnames are not supported in hash history.push(${JSON.stringify(
  174. to
  175. )})`
  176. );
  177. }
  178. return getUrlBasedHistory(
  179. createHashLocation,
  180. createHashHref,
  181. validateHashLocation,
  182. options
  183. );
  184. }
  185. function invariant(value, message) {
  186. if (value === false || value === null || typeof value === "undefined") {
  187. throw new Error(message);
  188. }
  189. }
  190. function warning(cond, message) {
  191. if (!cond) {
  192. if (typeof console !== "undefined") console.warn(message);
  193. try {
  194. throw new Error(message);
  195. } catch (e) {
  196. }
  197. }
  198. }
  199. function createKey() {
  200. return Math.random().toString(36).substring(2, 10);
  201. }
  202. function getHistoryState(location, index) {
  203. return {
  204. usr: location.state,
  205. key: location.key,
  206. idx: index
  207. };
  208. }
  209. function createLocation(current, to, state = null, key) {
  210. let location = {
  211. pathname: typeof current === "string" ? current : current.pathname,
  212. search: "",
  213. hash: "",
  214. ...typeof to === "string" ? parsePath(to) : to,
  215. state,
  216. // TODO: This could be cleaned up. push/replace should probably just take
  217. // full Locations now and avoid the need to run through this flow at all
  218. // But that's a pretty big refactor to the current test suite so going to
  219. // keep as is for the time being and just let any incoming keys take precedence
  220. key: to && to.key || key || createKey()
  221. };
  222. return location;
  223. }
  224. function createPath({
  225. pathname = "/",
  226. search = "",
  227. hash = ""
  228. }) {
  229. if (search && search !== "?")
  230. pathname += search.charAt(0) === "?" ? search : "?" + search;
  231. if (hash && hash !== "#")
  232. pathname += hash.charAt(0) === "#" ? hash : "#" + hash;
  233. return pathname;
  234. }
  235. function parsePath(path) {
  236. let parsedPath = {};
  237. if (path) {
  238. let hashIndex = path.indexOf("#");
  239. if (hashIndex >= 0) {
  240. parsedPath.hash = path.substring(hashIndex);
  241. path = path.substring(0, hashIndex);
  242. }
  243. let searchIndex = path.indexOf("?");
  244. if (searchIndex >= 0) {
  245. parsedPath.search = path.substring(searchIndex);
  246. path = path.substring(0, searchIndex);
  247. }
  248. if (path) {
  249. parsedPath.pathname = path;
  250. }
  251. }
  252. return parsedPath;
  253. }
  254. function getUrlBasedHistory(getLocation, createHref2, validateLocation, options = {}) {
  255. let { window: window2 = document.defaultView, v5Compat = false } = options;
  256. let globalHistory = window2.history;
  257. let action = "POP" /* Pop */;
  258. let listener = null;
  259. let index = getIndex();
  260. if (index == null) {
  261. index = 0;
  262. globalHistory.replaceState({ ...globalHistory.state, idx: index }, "");
  263. }
  264. function getIndex() {
  265. let state = globalHistory.state || { idx: null };
  266. return state.idx;
  267. }
  268. function handlePop() {
  269. action = "POP" /* Pop */;
  270. let nextIndex = getIndex();
  271. let delta = nextIndex == null ? null : nextIndex - index;
  272. index = nextIndex;
  273. if (listener) {
  274. listener({ action, location: history.location, delta });
  275. }
  276. }
  277. function push(to, state) {
  278. action = "PUSH" /* Push */;
  279. let location = createLocation(history.location, to, state);
  280. if (validateLocation) validateLocation(location, to);
  281. index = getIndex() + 1;
  282. let historyState = getHistoryState(location, index);
  283. let url = history.createHref(location);
  284. try {
  285. globalHistory.pushState(historyState, "", url);
  286. } catch (error) {
  287. if (error instanceof DOMException && error.name === "DataCloneError") {
  288. throw error;
  289. }
  290. window2.location.assign(url);
  291. }
  292. if (v5Compat && listener) {
  293. listener({ action, location: history.location, delta: 1 });
  294. }
  295. }
  296. function replace2(to, state) {
  297. action = "REPLACE" /* Replace */;
  298. let location = createLocation(history.location, to, state);
  299. if (validateLocation) validateLocation(location, to);
  300. index = getIndex();
  301. let historyState = getHistoryState(location, index);
  302. let url = history.createHref(location);
  303. globalHistory.replaceState(historyState, "", url);
  304. if (v5Compat && listener) {
  305. listener({ action, location: history.location, delta: 0 });
  306. }
  307. }
  308. function createURL(to) {
  309. return createBrowserURLImpl(to);
  310. }
  311. let history = {
  312. get action() {
  313. return action;
  314. },
  315. get location() {
  316. return getLocation(window2, globalHistory);
  317. },
  318. listen(fn) {
  319. if (listener) {
  320. throw new Error("A history only accepts one active listener");
  321. }
  322. window2.addEventListener(PopStateEventType, handlePop);
  323. listener = fn;
  324. return () => {
  325. window2.removeEventListener(PopStateEventType, handlePop);
  326. listener = null;
  327. };
  328. },
  329. createHref(to) {
  330. return createHref2(window2, to);
  331. },
  332. createURL,
  333. encodeLocation(to) {
  334. let url = createURL(to);
  335. return {
  336. pathname: url.pathname,
  337. search: url.search,
  338. hash: url.hash
  339. };
  340. },
  341. push,
  342. replace: replace2,
  343. go(n) {
  344. return globalHistory.go(n);
  345. }
  346. };
  347. return history;
  348. }
  349. function createBrowserURLImpl(to, isAbsolute = false) {
  350. let base = "http://localhost";
  351. if (typeof window !== "undefined") {
  352. base = window.location.origin !== "null" ? window.location.origin : window.location.href;
  353. }
  354. invariant(base, "No window.location.(origin|href) available to create URL");
  355. let href = typeof to === "string" ? to : createPath(to);
  356. href = href.replace(/ $/, "%20");
  357. if (!isAbsolute && href.startsWith("//")) {
  358. href = base + href;
  359. }
  360. return new URL(href, base);
  361. }
  362. // lib/router/utils.ts
  363. function createContext(defaultValue) {
  364. return { defaultValue };
  365. }
  366. var _map;
  367. var RouterContextProvider = class {
  368. /**
  369. * Create a new `RouterContextProvider` instance
  370. * @param init An optional initial context map to populate the provider with
  371. */
  372. constructor(init) {
  373. __privateAdd(this, _map, /* @__PURE__ */ new Map());
  374. if (init) {
  375. for (let [context, value] of init) {
  376. this.set(context, value);
  377. }
  378. }
  379. }
  380. /**
  381. * Access a value from the context. If no value has been set for the context,
  382. * it will return the context's `defaultValue` if provided, or throw an error
  383. * if no `defaultValue` was set.
  384. * @param context The context to get the value for
  385. * @returns The value for the context, or the context's `defaultValue` if no
  386. * value was set
  387. */
  388. get(context) {
  389. if (__privateGet(this, _map).has(context)) {
  390. return __privateGet(this, _map).get(context);
  391. }
  392. if (context.defaultValue !== void 0) {
  393. return context.defaultValue;
  394. }
  395. throw new Error("No value found for context");
  396. }
  397. /**
  398. * Set a value for the context. If the context already has a value set, this
  399. * will overwrite it.
  400. *
  401. * @param context The context to set the value for
  402. * @param value The value to set for the context
  403. * @returns {void}
  404. */
  405. set(context, value) {
  406. __privateGet(this, _map).set(context, value);
  407. }
  408. };
  409. _map = new WeakMap();
  410. var unsupportedLazyRouteObjectKeys = /* @__PURE__ */ new Set([
  411. "lazy",
  412. "caseSensitive",
  413. "path",
  414. "id",
  415. "index",
  416. "children"
  417. ]);
  418. function isUnsupportedLazyRouteObjectKey(key) {
  419. return unsupportedLazyRouteObjectKeys.has(
  420. key
  421. );
  422. }
  423. var unsupportedLazyRouteFunctionKeys = /* @__PURE__ */ new Set([
  424. "lazy",
  425. "caseSensitive",
  426. "path",
  427. "id",
  428. "index",
  429. "middleware",
  430. "children"
  431. ]);
  432. function isUnsupportedLazyRouteFunctionKey(key) {
  433. return unsupportedLazyRouteFunctionKeys.has(
  434. key
  435. );
  436. }
  437. function isIndexRoute(route) {
  438. return route.index === true;
  439. }
  440. function convertRoutesToDataRoutes(routes, mapRouteProperties2, parentPath = [], manifest = {}, allowInPlaceMutations = false) {
  441. return routes.map((route, index) => {
  442. let treePath = [...parentPath, String(index)];
  443. let id = typeof route.id === "string" ? route.id : treePath.join("-");
  444. invariant(
  445. route.index !== true || !route.children,
  446. `Cannot specify children on an index route`
  447. );
  448. invariant(
  449. allowInPlaceMutations || !manifest[id],
  450. `Found a route id collision on id "${id}". Route id's must be globally unique within Data Router usages`
  451. );
  452. if (isIndexRoute(route)) {
  453. let indexRoute = {
  454. ...route,
  455. id
  456. };
  457. manifest[id] = mergeRouteUpdates(
  458. indexRoute,
  459. mapRouteProperties2(indexRoute)
  460. );
  461. return indexRoute;
  462. } else {
  463. let pathOrLayoutRoute = {
  464. ...route,
  465. id,
  466. children: void 0
  467. };
  468. manifest[id] = mergeRouteUpdates(
  469. pathOrLayoutRoute,
  470. mapRouteProperties2(pathOrLayoutRoute)
  471. );
  472. if (route.children) {
  473. pathOrLayoutRoute.children = convertRoutesToDataRoutes(
  474. route.children,
  475. mapRouteProperties2,
  476. treePath,
  477. manifest,
  478. allowInPlaceMutations
  479. );
  480. }
  481. return pathOrLayoutRoute;
  482. }
  483. });
  484. }
  485. function mergeRouteUpdates(route, updates) {
  486. return Object.assign(route, {
  487. ...updates,
  488. ...typeof updates.lazy === "object" && updates.lazy != null ? {
  489. lazy: {
  490. ...route.lazy,
  491. ...updates.lazy
  492. }
  493. } : {}
  494. });
  495. }
  496. function matchRoutes(routes, locationArg, basename = "/") {
  497. return matchRoutesImpl(routes, locationArg, basename, false);
  498. }
  499. function matchRoutesImpl(routes, locationArg, basename, allowPartial) {
  500. let location = typeof locationArg === "string" ? parsePath(locationArg) : locationArg;
  501. let pathname = stripBasename(location.pathname || "/", basename);
  502. if (pathname == null) {
  503. return null;
  504. }
  505. let branches = flattenRoutes(routes);
  506. rankRouteBranches(branches);
  507. let matches = null;
  508. for (let i = 0; matches == null && i < branches.length; ++i) {
  509. let decoded = decodePath(pathname);
  510. matches = matchRouteBranch(
  511. branches[i],
  512. decoded,
  513. allowPartial
  514. );
  515. }
  516. return matches;
  517. }
  518. function convertRouteMatchToUiMatch(match, loaderData) {
  519. let { route, pathname, params } = match;
  520. return {
  521. id: route.id,
  522. pathname,
  523. params,
  524. data: loaderData[route.id],
  525. loaderData: loaderData[route.id],
  526. handle: route.handle
  527. };
  528. }
  529. function flattenRoutes(routes, branches = [], parentsMeta = [], parentPath = "", _hasParentOptionalSegments = false) {
  530. let flattenRoute = (route, index, hasParentOptionalSegments = _hasParentOptionalSegments, relativePath) => {
  531. let meta = {
  532. relativePath: relativePath === void 0 ? route.path || "" : relativePath,
  533. caseSensitive: route.caseSensitive === true,
  534. childrenIndex: index,
  535. route
  536. };
  537. if (meta.relativePath.startsWith("/")) {
  538. if (!meta.relativePath.startsWith(parentPath) && hasParentOptionalSegments) {
  539. return;
  540. }
  541. invariant(
  542. meta.relativePath.startsWith(parentPath),
  543. `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.`
  544. );
  545. meta.relativePath = meta.relativePath.slice(parentPath.length);
  546. }
  547. let path = joinPaths([parentPath, meta.relativePath]);
  548. let routesMeta = parentsMeta.concat(meta);
  549. if (route.children && route.children.length > 0) {
  550. invariant(
  551. // Our types know better, but runtime JS may not!
  552. // @ts-expect-error
  553. route.index !== true,
  554. `Index routes must not have child routes. Please remove all child routes from route path "${path}".`
  555. );
  556. flattenRoutes(
  557. route.children,
  558. branches,
  559. routesMeta,
  560. path,
  561. hasParentOptionalSegments
  562. );
  563. }
  564. if (route.path == null && !route.index) {
  565. return;
  566. }
  567. branches.push({
  568. path,
  569. score: computeScore(path, route.index),
  570. routesMeta
  571. });
  572. };
  573. routes.forEach((route, index) => {
  574. if (route.path === "" || !route.path?.includes("?")) {
  575. flattenRoute(route, index);
  576. } else {
  577. for (let exploded of explodeOptionalSegments(route.path)) {
  578. flattenRoute(route, index, true, exploded);
  579. }
  580. }
  581. });
  582. return branches;
  583. }
  584. function explodeOptionalSegments(path) {
  585. let segments = path.split("/");
  586. if (segments.length === 0) return [];
  587. let [first, ...rest] = segments;
  588. let isOptional = first.endsWith("?");
  589. let required = first.replace(/\?$/, "");
  590. if (rest.length === 0) {
  591. return isOptional ? [required, ""] : [required];
  592. }
  593. let restExploded = explodeOptionalSegments(rest.join("/"));
  594. let result = [];
  595. result.push(
  596. ...restExploded.map(
  597. (subpath) => subpath === "" ? required : [required, subpath].join("/")
  598. )
  599. );
  600. if (isOptional) {
  601. result.push(...restExploded);
  602. }
  603. return result.map(
  604. (exploded) => path.startsWith("/") && exploded === "" ? "/" : exploded
  605. );
  606. }
  607. function rankRouteBranches(branches) {
  608. branches.sort(
  609. (a, b) => a.score !== b.score ? b.score - a.score : compareIndexes(
  610. a.routesMeta.map((meta) => meta.childrenIndex),
  611. b.routesMeta.map((meta) => meta.childrenIndex)
  612. )
  613. );
  614. }
  615. var paramRe = /^:[\w-]+$/;
  616. var dynamicSegmentValue = 3;
  617. var indexRouteValue = 2;
  618. var emptySegmentValue = 1;
  619. var staticSegmentValue = 10;
  620. var splatPenalty = -2;
  621. var isSplat = (s) => s === "*";
  622. function computeScore(path, index) {
  623. let segments = path.split("/");
  624. let initialScore = segments.length;
  625. if (segments.some(isSplat)) {
  626. initialScore += splatPenalty;
  627. }
  628. if (index) {
  629. initialScore += indexRouteValue;
  630. }
  631. return segments.filter((s) => !isSplat(s)).reduce(
  632. (score, segment) => score + (paramRe.test(segment) ? dynamicSegmentValue : segment === "" ? emptySegmentValue : staticSegmentValue),
  633. initialScore
  634. );
  635. }
  636. function compareIndexes(a, b) {
  637. let siblings = a.length === b.length && a.slice(0, -1).every((n, i) => n === b[i]);
  638. return siblings ? (
  639. // If two routes are siblings, we should try to match the earlier sibling
  640. // first. This allows people to have fine-grained control over the matching
  641. // behavior by simply putting routes with identical paths in the order they
  642. // want them tried.
  643. a[a.length - 1] - b[b.length - 1]
  644. ) : (
  645. // Otherwise, it doesn't really make sense to rank non-siblings by index,
  646. // so they sort equally.
  647. 0
  648. );
  649. }
  650. function matchRouteBranch(branch, pathname, allowPartial = false) {
  651. let { routesMeta } = branch;
  652. let matchedParams = {};
  653. let matchedPathname = "/";
  654. let matches = [];
  655. for (let i = 0; i < routesMeta.length; ++i) {
  656. let meta = routesMeta[i];
  657. let end = i === routesMeta.length - 1;
  658. let remainingPathname = matchedPathname === "/" ? pathname : pathname.slice(matchedPathname.length) || "/";
  659. let match = matchPath(
  660. { path: meta.relativePath, caseSensitive: meta.caseSensitive, end },
  661. remainingPathname
  662. );
  663. let route = meta.route;
  664. if (!match && end && allowPartial && !routesMeta[routesMeta.length - 1].route.index) {
  665. match = matchPath(
  666. {
  667. path: meta.relativePath,
  668. caseSensitive: meta.caseSensitive,
  669. end: false
  670. },
  671. remainingPathname
  672. );
  673. }
  674. if (!match) {
  675. return null;
  676. }
  677. Object.assign(matchedParams, match.params);
  678. matches.push({
  679. // TODO: Can this as be avoided?
  680. params: matchedParams,
  681. pathname: joinPaths([matchedPathname, match.pathname]),
  682. pathnameBase: normalizePathname(
  683. joinPaths([matchedPathname, match.pathnameBase])
  684. ),
  685. route
  686. });
  687. if (match.pathnameBase !== "/") {
  688. matchedPathname = joinPaths([matchedPathname, match.pathnameBase]);
  689. }
  690. }
  691. return matches;
  692. }
  693. function generatePath(originalPath, params = {}) {
  694. let path = originalPath;
  695. if (path.endsWith("*") && path !== "*" && !path.endsWith("/*")) {
  696. warning(
  697. false,
  698. `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(/\*$/, "/*")}".`
  699. );
  700. path = path.replace(/\*$/, "/*");
  701. }
  702. const prefix = path.startsWith("/") ? "/" : "";
  703. const stringify2 = (p) => p == null ? "" : typeof p === "string" ? p : String(p);
  704. const segments = path.split(/\/+/).map((segment, index, array) => {
  705. const isLastSegment = index === array.length - 1;
  706. if (isLastSegment && segment === "*") {
  707. const star = "*";
  708. return stringify2(params[star]);
  709. }
  710. const keyMatch = segment.match(/^:([\w-]+)(\??)$/);
  711. if (keyMatch) {
  712. const [, key, optional] = keyMatch;
  713. let param = params[key];
  714. invariant(optional === "?" || param != null, `Missing ":${key}" param`);
  715. return encodeURIComponent(stringify2(param));
  716. }
  717. return segment.replace(/\?$/g, "");
  718. }).filter((segment) => !!segment);
  719. return prefix + segments.join("/");
  720. }
  721. function matchPath(pattern, pathname) {
  722. if (typeof pattern === "string") {
  723. pattern = { path: pattern, caseSensitive: false, end: true };
  724. }
  725. let [matcher, compiledParams] = compilePath(
  726. pattern.path,
  727. pattern.caseSensitive,
  728. pattern.end
  729. );
  730. let match = pathname.match(matcher);
  731. if (!match) return null;
  732. let matchedPathname = match[0];
  733. let pathnameBase = matchedPathname.replace(/(.)\/+$/, "$1");
  734. let captureGroups = match.slice(1);
  735. let params = compiledParams.reduce(
  736. (memo2, { paramName, isOptional }, index) => {
  737. if (paramName === "*") {
  738. let splatValue = captureGroups[index] || "";
  739. pathnameBase = matchedPathname.slice(0, matchedPathname.length - splatValue.length).replace(/(.)\/+$/, "$1");
  740. }
  741. const value = captureGroups[index];
  742. if (isOptional && !value) {
  743. memo2[paramName] = void 0;
  744. } else {
  745. memo2[paramName] = (value || "").replace(/%2F/g, "/");
  746. }
  747. return memo2;
  748. },
  749. {}
  750. );
  751. return {
  752. params,
  753. pathname: matchedPathname,
  754. pathnameBase,
  755. pattern
  756. };
  757. }
  758. function compilePath(path, caseSensitive = false, end = true) {
  759. warning(
  760. path === "*" || !path.endsWith("*") || path.endsWith("/*"),
  761. `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(/\*$/, "/*")}".`
  762. );
  763. let params = [];
  764. let regexpSource = "^" + path.replace(/\/*\*?$/, "").replace(/^\/*/, "/").replace(/[\\.*+^${}|()[\]]/g, "\\$&").replace(
  765. /\/:([\w-]+)(\?)?/g,
  766. (_, paramName, isOptional) => {
  767. params.push({ paramName, isOptional: isOptional != null });
  768. return isOptional ? "/?([^\\/]+)?" : "/([^\\/]+)";
  769. }
  770. ).replace(/\/([\w-]+)\?(\/|$)/g, "(/$1)?$2");
  771. if (path.endsWith("*")) {
  772. params.push({ paramName: "*" });
  773. regexpSource += path === "*" || path === "/*" ? "(.*)$" : "(?:\\/(.+)|\\/*)$";
  774. } else if (end) {
  775. regexpSource += "\\/*$";
  776. } else if (path !== "" && path !== "/") {
  777. regexpSource += "(?:(?=\\/|$))";
  778. } else {
  779. }
  780. let matcher = new RegExp(regexpSource, caseSensitive ? void 0 : "i");
  781. return [matcher, params];
  782. }
  783. function decodePath(value) {
  784. try {
  785. return value.split("/").map((v) => decodeURIComponent(v).replace(/\//g, "%2F")).join("/");
  786. } catch (error) {
  787. warning(
  788. false,
  789. `The URL path "${value}" could not be decoded because it is a malformed URL segment. This is probably due to a bad percent encoding (${error}).`
  790. );
  791. return value;
  792. }
  793. }
  794. function stripBasename(pathname, basename) {
  795. if (basename === "/") return pathname;
  796. if (!pathname.toLowerCase().startsWith(basename.toLowerCase())) {
  797. return null;
  798. }
  799. let startIndex = basename.endsWith("/") ? basename.length - 1 : basename.length;
  800. let nextChar = pathname.charAt(startIndex);
  801. if (nextChar && nextChar !== "/") {
  802. return null;
  803. }
  804. return pathname.slice(startIndex) || "/";
  805. }
  806. function prependBasename({
  807. basename,
  808. pathname
  809. }) {
  810. return pathname === "/" ? basename : joinPaths([basename, pathname]);
  811. }
  812. var ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i;
  813. var isAbsoluteUrl = (url) => ABSOLUTE_URL_REGEX.test(url);
  814. function resolvePath(to, fromPathname = "/") {
  815. let {
  816. pathname: toPathname,
  817. search = "",
  818. hash = ""
  819. } = typeof to === "string" ? parsePath(to) : to;
  820. let pathname;
  821. if (toPathname) {
  822. if (isAbsoluteUrl(toPathname)) {
  823. pathname = toPathname;
  824. } else {
  825. if (toPathname.includes("//")) {
  826. let oldPathname = toPathname;
  827. toPathname = toPathname.replace(/\/\/+/g, "/");
  828. warning(
  829. false,
  830. `Pathnames cannot have embedded double slashes - normalizing ${oldPathname} -> ${toPathname}`
  831. );
  832. }
  833. if (toPathname.startsWith("/")) {
  834. pathname = resolvePathname(toPathname.substring(1), "/");
  835. } else {
  836. pathname = resolvePathname(toPathname, fromPathname);
  837. }
  838. }
  839. } else {
  840. pathname = fromPathname;
  841. }
  842. return {
  843. pathname,
  844. search: normalizeSearch(search),
  845. hash: normalizeHash(hash)
  846. };
  847. }
  848. function resolvePathname(relativePath, fromPathname) {
  849. let segments = fromPathname.replace(/\/+$/, "").split("/");
  850. let relativeSegments = relativePath.split("/");
  851. relativeSegments.forEach((segment) => {
  852. if (segment === "..") {
  853. if (segments.length > 1) segments.pop();
  854. } else if (segment !== ".") {
  855. segments.push(segment);
  856. }
  857. });
  858. return segments.length > 1 ? segments.join("/") : "/";
  859. }
  860. function getInvalidPathError(char, field, dest, path) {
  861. return `Cannot include a '${char}' character in a manually specified \`to.${field}\` field [${JSON.stringify(
  862. path
  863. )}]. 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.`;
  864. }
  865. function getPathContributingMatches(matches) {
  866. return matches.filter(
  867. (match, index) => index === 0 || match.route.path && match.route.path.length > 0
  868. );
  869. }
  870. function getResolveToMatches(matches) {
  871. let pathMatches = getPathContributingMatches(matches);
  872. return pathMatches.map(
  873. (match, idx) => idx === pathMatches.length - 1 ? match.pathname : match.pathnameBase
  874. );
  875. }
  876. function resolveTo(toArg, routePathnames, locationPathname, isPathRelative = false) {
  877. let to;
  878. if (typeof toArg === "string") {
  879. to = parsePath(toArg);
  880. } else {
  881. to = { ...toArg };
  882. invariant(
  883. !to.pathname || !to.pathname.includes("?"),
  884. getInvalidPathError("?", "pathname", "search", to)
  885. );
  886. invariant(
  887. !to.pathname || !to.pathname.includes("#"),
  888. getInvalidPathError("#", "pathname", "hash", to)
  889. );
  890. invariant(
  891. !to.search || !to.search.includes("#"),
  892. getInvalidPathError("#", "search", "hash", to)
  893. );
  894. }
  895. let isEmptyPath = toArg === "" || to.pathname === "";
  896. let toPathname = isEmptyPath ? "/" : to.pathname;
  897. let from;
  898. if (toPathname == null) {
  899. from = locationPathname;
  900. } else {
  901. let routePathnameIndex = routePathnames.length - 1;
  902. if (!isPathRelative && toPathname.startsWith("..")) {
  903. let toSegments = toPathname.split("/");
  904. while (toSegments[0] === "..") {
  905. toSegments.shift();
  906. routePathnameIndex -= 1;
  907. }
  908. to.pathname = toSegments.join("/");
  909. }
  910. from = routePathnameIndex >= 0 ? routePathnames[routePathnameIndex] : "/";
  911. }
  912. let path = resolvePath(to, from);
  913. let hasExplicitTrailingSlash = toPathname && toPathname !== "/" && toPathname.endsWith("/");
  914. let hasCurrentTrailingSlash = (isEmptyPath || toPathname === ".") && locationPathname.endsWith("/");
  915. if (!path.pathname.endsWith("/") && (hasExplicitTrailingSlash || hasCurrentTrailingSlash)) {
  916. path.pathname += "/";
  917. }
  918. return path;
  919. }
  920. var joinPaths = (paths) => paths.join("/").replace(/\/\/+/g, "/");
  921. var normalizePathname = (pathname) => pathname.replace(/\/+$/, "").replace(/^\/*/, "/");
  922. var normalizeSearch = (search) => !search || search === "?" ? "" : search.startsWith("?") ? search : "?" + search;
  923. var normalizeHash = (hash) => !hash || hash === "#" ? "" : hash.startsWith("#") ? hash : "#" + hash;
  924. var DataWithResponseInit = class {
  925. constructor(data2, init) {
  926. this.type = "DataWithResponseInit";
  927. this.data = data2;
  928. this.init = init || null;
  929. }
  930. };
  931. function data(data2, init) {
  932. return new DataWithResponseInit(
  933. data2,
  934. typeof init === "number" ? { status: init } : init
  935. );
  936. }
  937. var redirect = (url, init = 302) => {
  938. let responseInit = init;
  939. if (typeof responseInit === "number") {
  940. responseInit = { status: responseInit };
  941. } else if (typeof responseInit.status === "undefined") {
  942. responseInit.status = 302;
  943. }
  944. let headers = new Headers(responseInit.headers);
  945. headers.set("Location", url);
  946. return new Response(null, { ...responseInit, headers });
  947. };
  948. var redirectDocument = (url, init) => {
  949. let response = redirect(url, init);
  950. response.headers.set("X-Remix-Reload-Document", "true");
  951. return response;
  952. };
  953. var replace = (url, init) => {
  954. let response = redirect(url, init);
  955. response.headers.set("X-Remix-Replace", "true");
  956. return response;
  957. };
  958. var ErrorResponseImpl = class {
  959. constructor(status, statusText, data2, internal = false) {
  960. this.status = status;
  961. this.statusText = statusText || "";
  962. this.internal = internal;
  963. if (data2 instanceof Error) {
  964. this.data = data2.toString();
  965. this.error = data2;
  966. } else {
  967. this.data = data2;
  968. }
  969. }
  970. };
  971. function isRouteErrorResponse(error) {
  972. return error != null && typeof error.status === "number" && typeof error.statusText === "string" && typeof error.internal === "boolean" && "data" in error;
  973. }
  974. function getRoutePattern(matches) {
  975. return matches.map((m) => m.route.path).filter(Boolean).join("/").replace(/\/\/*/g, "/") || "/";
  976. }
  977. // lib/router/instrumentation.ts
  978. var UninstrumentedSymbol = Symbol("Uninstrumented");
  979. function getRouteInstrumentationUpdates(fns, route) {
  980. let aggregated = {
  981. lazy: [],
  982. "lazy.loader": [],
  983. "lazy.action": [],
  984. "lazy.middleware": [],
  985. middleware: [],
  986. loader: [],
  987. action: []
  988. };
  989. fns.forEach(
  990. (fn) => fn({
  991. id: route.id,
  992. index: route.index,
  993. path: route.path,
  994. instrument(i) {
  995. let keys = Object.keys(aggregated);
  996. for (let key of keys) {
  997. if (i[key]) {
  998. aggregated[key].push(i[key]);
  999. }
  1000. }
  1001. }
  1002. })
  1003. );
  1004. let updates = {};
  1005. if (typeof route.lazy === "function" && aggregated.lazy.length > 0) {
  1006. let instrumented = wrapImpl(aggregated.lazy, route.lazy, () => void 0);
  1007. if (instrumented) {
  1008. updates.lazy = instrumented;
  1009. }
  1010. }
  1011. if (typeof route.lazy === "object") {
  1012. let lazyObject = route.lazy;
  1013. ["middleware", "loader", "action"].forEach((key) => {
  1014. let lazyFn = lazyObject[key];
  1015. let instrumentations = aggregated[`lazy.${key}`];
  1016. if (typeof lazyFn === "function" && instrumentations.length > 0) {
  1017. let instrumented = wrapImpl(instrumentations, lazyFn, () => void 0);
  1018. if (instrumented) {
  1019. updates.lazy = Object.assign(updates.lazy || {}, {
  1020. [key]: instrumented
  1021. });
  1022. }
  1023. }
  1024. });
  1025. }
  1026. ["loader", "action"].forEach((key) => {
  1027. let handler = route[key];
  1028. if (typeof handler === "function" && aggregated[key].length > 0) {
  1029. let original = handler[UninstrumentedSymbol] ?? handler;
  1030. let instrumented = wrapImpl(
  1031. aggregated[key],
  1032. original,
  1033. (...args) => getHandlerInfo(args[0])
  1034. );
  1035. if (instrumented) {
  1036. instrumented[UninstrumentedSymbol] = original;
  1037. updates[key] = instrumented;
  1038. }
  1039. }
  1040. });
  1041. if (route.middleware && route.middleware.length > 0 && aggregated.middleware.length > 0) {
  1042. updates.middleware = route.middleware.map((middleware) => {
  1043. let original = middleware[UninstrumentedSymbol] ?? middleware;
  1044. let instrumented = wrapImpl(
  1045. aggregated.middleware,
  1046. original,
  1047. (...args) => getHandlerInfo(args[0])
  1048. );
  1049. if (instrumented) {
  1050. instrumented[UninstrumentedSymbol] = original;
  1051. return instrumented;
  1052. }
  1053. return middleware;
  1054. });
  1055. }
  1056. return updates;
  1057. }
  1058. function instrumentClientSideRouter(router, fns) {
  1059. let aggregated = {
  1060. navigate: [],
  1061. fetch: []
  1062. };
  1063. fns.forEach(
  1064. (fn) => fn({
  1065. instrument(i) {
  1066. let keys = Object.keys(i);
  1067. for (let key of keys) {
  1068. if (i[key]) {
  1069. aggregated[key].push(i[key]);
  1070. }
  1071. }
  1072. }
  1073. })
  1074. );
  1075. if (aggregated.navigate.length > 0) {
  1076. let navigate = router.navigate[UninstrumentedSymbol] ?? router.navigate;
  1077. let instrumentedNavigate = wrapImpl(
  1078. aggregated.navigate,
  1079. navigate,
  1080. (...args) => {
  1081. let [to, opts] = args;
  1082. return {
  1083. to: typeof to === "number" || typeof to === "string" ? to : to ? createPath(to) : ".",
  1084. ...getRouterInfo(router, opts ?? {})
  1085. };
  1086. }
  1087. );
  1088. if (instrumentedNavigate) {
  1089. instrumentedNavigate[UninstrumentedSymbol] = navigate;
  1090. router.navigate = instrumentedNavigate;
  1091. }
  1092. }
  1093. if (aggregated.fetch.length > 0) {
  1094. let fetch2 = router.fetch[UninstrumentedSymbol] ?? router.fetch;
  1095. let instrumentedFetch = wrapImpl(aggregated.fetch, fetch2, (...args) => {
  1096. let [key, , href, opts] = args;
  1097. return {
  1098. href: href ?? ".",
  1099. fetcherKey: key,
  1100. ...getRouterInfo(router, opts ?? {})
  1101. };
  1102. });
  1103. if (instrumentedFetch) {
  1104. instrumentedFetch[UninstrumentedSymbol] = fetch2;
  1105. router.fetch = instrumentedFetch;
  1106. }
  1107. }
  1108. return router;
  1109. }
  1110. function instrumentHandler(handler, fns) {
  1111. let aggregated = {
  1112. request: []
  1113. };
  1114. fns.forEach(
  1115. (fn) => fn({
  1116. instrument(i) {
  1117. let keys = Object.keys(i);
  1118. for (let key of keys) {
  1119. if (i[key]) {
  1120. aggregated[key].push(i[key]);
  1121. }
  1122. }
  1123. }
  1124. })
  1125. );
  1126. let instrumentedHandler = handler;
  1127. if (aggregated.request.length > 0) {
  1128. instrumentedHandler = wrapImpl(aggregated.request, handler, (...args) => {
  1129. let [request, context] = args;
  1130. return {
  1131. request: getReadonlyRequest(request),
  1132. context: context != null ? getReadonlyContext(context) : context
  1133. };
  1134. });
  1135. }
  1136. return instrumentedHandler;
  1137. }
  1138. function wrapImpl(impls, handler, getInfo) {
  1139. if (impls.length === 0) {
  1140. return null;
  1141. }
  1142. return async (...args) => {
  1143. let result = await recurseRight(
  1144. impls,
  1145. getInfo(...args),
  1146. () => handler(...args),
  1147. impls.length - 1
  1148. );
  1149. if (result.type === "error") {
  1150. throw result.value;
  1151. }
  1152. return result.value;
  1153. };
  1154. }
  1155. async function recurseRight(impls, info, handler, index) {
  1156. let impl = impls[index];
  1157. let result;
  1158. if (!impl) {
  1159. try {
  1160. let value = await handler();
  1161. result = { type: "success", value };
  1162. } catch (e) {
  1163. result = { type: "error", value: e };
  1164. }
  1165. } else {
  1166. let handlerPromise = void 0;
  1167. let callHandler = async () => {
  1168. if (handlerPromise) {
  1169. console.error("You cannot call instrumented handlers more than once");
  1170. } else {
  1171. handlerPromise = recurseRight(impls, info, handler, index - 1);
  1172. }
  1173. result = await handlerPromise;
  1174. invariant(result, "Expected a result");
  1175. if (result.type === "error" && result.value instanceof Error) {
  1176. return { status: "error", error: result.value };
  1177. }
  1178. return { status: "success", error: void 0 };
  1179. };
  1180. try {
  1181. await impl(callHandler, info);
  1182. } catch (e) {
  1183. console.error("An instrumentation function threw an error:", e);
  1184. }
  1185. if (!handlerPromise) {
  1186. await callHandler();
  1187. }
  1188. await handlerPromise;
  1189. }
  1190. if (result) {
  1191. return result;
  1192. }
  1193. return {
  1194. type: "error",
  1195. value: new Error("No result assigned in instrumentation chain.")
  1196. };
  1197. }
  1198. function getHandlerInfo(args) {
  1199. let { request, context, params, unstable_pattern } = args;
  1200. return {
  1201. request: getReadonlyRequest(request),
  1202. params: { ...params },
  1203. unstable_pattern,
  1204. context: getReadonlyContext(context)
  1205. };
  1206. }
  1207. function getRouterInfo(router, opts) {
  1208. return {
  1209. currentUrl: createPath(router.state.location),
  1210. ..."formMethod" in opts ? { formMethod: opts.formMethod } : {},
  1211. ..."formEncType" in opts ? { formEncType: opts.formEncType } : {},
  1212. ..."formData" in opts ? { formData: opts.formData } : {},
  1213. ..."body" in opts ? { body: opts.body } : {}
  1214. };
  1215. }
  1216. function getReadonlyRequest(request) {
  1217. return {
  1218. method: request.method,
  1219. url: request.url,
  1220. headers: {
  1221. get: (...args) => request.headers.get(...args)
  1222. }
  1223. };
  1224. }
  1225. function getReadonlyContext(context) {
  1226. if (isPlainObject(context)) {
  1227. let frozen = { ...context };
  1228. Object.freeze(frozen);
  1229. return frozen;
  1230. } else {
  1231. return {
  1232. get: (ctx) => context.get(ctx)
  1233. };
  1234. }
  1235. }
  1236. var objectProtoNames = Object.getOwnPropertyNames(Object.prototype).sort().join("\0");
  1237. function isPlainObject(thing) {
  1238. if (thing === null || typeof thing !== "object") {
  1239. return false;
  1240. }
  1241. const proto = Object.getPrototypeOf(thing);
  1242. return proto === Object.prototype || proto === null || Object.getOwnPropertyNames(proto).sort().join("\0") === objectProtoNames;
  1243. }
  1244. // lib/router/router.ts
  1245. var validMutationMethodsArr = [
  1246. "POST",
  1247. "PUT",
  1248. "PATCH",
  1249. "DELETE"
  1250. ];
  1251. var validMutationMethods = new Set(
  1252. validMutationMethodsArr
  1253. );
  1254. var validRequestMethodsArr = [
  1255. "GET",
  1256. ...validMutationMethodsArr
  1257. ];
  1258. var validRequestMethods = new Set(validRequestMethodsArr);
  1259. var redirectStatusCodes = /* @__PURE__ */ new Set([301, 302, 303, 307, 308]);
  1260. var redirectPreserveMethodStatusCodes = /* @__PURE__ */ new Set([307, 308]);
  1261. var IDLE_NAVIGATION = {
  1262. state: "idle",
  1263. location: void 0,
  1264. formMethod: void 0,
  1265. formAction: void 0,
  1266. formEncType: void 0,
  1267. formData: void 0,
  1268. json: void 0,
  1269. text: void 0
  1270. };
  1271. var IDLE_FETCHER = {
  1272. state: "idle",
  1273. data: void 0,
  1274. formMethod: void 0,
  1275. formAction: void 0,
  1276. formEncType: void 0,
  1277. formData: void 0,
  1278. json: void 0,
  1279. text: void 0
  1280. };
  1281. var IDLE_BLOCKER = {
  1282. state: "unblocked",
  1283. proceed: void 0,
  1284. reset: void 0,
  1285. location: void 0
  1286. };
  1287. var defaultMapRouteProperties = (route) => ({
  1288. hasErrorBoundary: Boolean(route.hasErrorBoundary)
  1289. });
  1290. var TRANSITIONS_STORAGE_KEY = "remix-router-transitions";
  1291. var ResetLoaderDataSymbol = Symbol("ResetLoaderData");
  1292. function createRouter(init) {
  1293. const routerWindow = init.window ? init.window : typeof window !== "undefined" ? window : void 0;
  1294. const isBrowser2 = typeof routerWindow !== "undefined" && typeof routerWindow.document !== "undefined" && typeof routerWindow.document.createElement !== "undefined";
  1295. invariant(
  1296. init.routes.length > 0,
  1297. "You must provide a non-empty routes array to createRouter"
  1298. );
  1299. let hydrationRouteProperties2 = init.hydrationRouteProperties || [];
  1300. let _mapRouteProperties = init.mapRouteProperties || defaultMapRouteProperties;
  1301. let mapRouteProperties2 = _mapRouteProperties;
  1302. if (init.unstable_instrumentations) {
  1303. let instrumentations = init.unstable_instrumentations;
  1304. mapRouteProperties2 = (route) => {
  1305. return {
  1306. ..._mapRouteProperties(route),
  1307. ...getRouteInstrumentationUpdates(
  1308. instrumentations.map((i) => i.route).filter(Boolean),
  1309. route
  1310. )
  1311. };
  1312. };
  1313. }
  1314. let manifest = {};
  1315. let dataRoutes = convertRoutesToDataRoutes(
  1316. init.routes,
  1317. mapRouteProperties2,
  1318. void 0,
  1319. manifest
  1320. );
  1321. let inFlightDataRoutes;
  1322. let basename = init.basename || "/";
  1323. if (!basename.startsWith("/")) {
  1324. basename = `/${basename}`;
  1325. }
  1326. let dataStrategyImpl = init.dataStrategy || defaultDataStrategyWithMiddleware;
  1327. let future = {
  1328. ...init.future
  1329. };
  1330. let unlistenHistory = null;
  1331. let subscribers = /* @__PURE__ */ new Set();
  1332. let savedScrollPositions2 = null;
  1333. let getScrollRestorationKey2 = null;
  1334. let getScrollPosition = null;
  1335. let initialScrollRestored = init.hydrationData != null;
  1336. let initialMatches = matchRoutes(dataRoutes, init.history.location, basename);
  1337. let initialMatchesIsFOW = false;
  1338. let initialErrors = null;
  1339. let initialized;
  1340. if (initialMatches == null && !init.patchRoutesOnNavigation) {
  1341. let error = getInternalRouterError(404, {
  1342. pathname: init.history.location.pathname
  1343. });
  1344. let { matches, route } = getShortCircuitMatches(dataRoutes);
  1345. initialized = true;
  1346. initialMatches = matches;
  1347. initialErrors = { [route.id]: error };
  1348. } else {
  1349. if (initialMatches && !init.hydrationData) {
  1350. let fogOfWar = checkFogOfWar(
  1351. initialMatches,
  1352. dataRoutes,
  1353. init.history.location.pathname
  1354. );
  1355. if (fogOfWar.active) {
  1356. initialMatches = null;
  1357. }
  1358. }
  1359. if (!initialMatches) {
  1360. initialized = false;
  1361. initialMatches = [];
  1362. let fogOfWar = checkFogOfWar(
  1363. null,
  1364. dataRoutes,
  1365. init.history.location.pathname
  1366. );
  1367. if (fogOfWar.active && fogOfWar.matches) {
  1368. initialMatchesIsFOW = true;
  1369. initialMatches = fogOfWar.matches;
  1370. }
  1371. } else if (initialMatches.some((m) => m.route.lazy)) {
  1372. initialized = false;
  1373. } else if (!initialMatches.some((m) => routeHasLoaderOrMiddleware(m.route))) {
  1374. initialized = true;
  1375. } else {
  1376. let loaderData = init.hydrationData ? init.hydrationData.loaderData : null;
  1377. let errors = init.hydrationData ? init.hydrationData.errors : null;
  1378. if (errors) {
  1379. let idx = initialMatches.findIndex(
  1380. (m) => errors[m.route.id] !== void 0
  1381. );
  1382. initialized = initialMatches.slice(0, idx + 1).every(
  1383. (m) => !shouldLoadRouteOnHydration(m.route, loaderData, errors)
  1384. );
  1385. } else {
  1386. initialized = initialMatches.every(
  1387. (m) => !shouldLoadRouteOnHydration(m.route, loaderData, errors)
  1388. );
  1389. }
  1390. }
  1391. }
  1392. let router;
  1393. let state = {
  1394. historyAction: init.history.action,
  1395. location: init.history.location,
  1396. matches: initialMatches,
  1397. initialized,
  1398. navigation: IDLE_NAVIGATION,
  1399. // Don't restore on initial updateState() if we were SSR'd
  1400. restoreScrollPosition: init.hydrationData != null ? false : null,
  1401. preventScrollReset: false,
  1402. revalidation: "idle",
  1403. loaderData: init.hydrationData && init.hydrationData.loaderData || {},
  1404. actionData: init.hydrationData && init.hydrationData.actionData || null,
  1405. errors: init.hydrationData && init.hydrationData.errors || initialErrors,
  1406. fetchers: /* @__PURE__ */ new Map(),
  1407. blockers: /* @__PURE__ */ new Map()
  1408. };
  1409. let pendingAction = "POP" /* Pop */;
  1410. let pendingPopstateNavigationDfd = null;
  1411. let pendingPreventScrollReset = false;
  1412. let pendingNavigationController;
  1413. let pendingViewTransitionEnabled = false;
  1414. let appliedViewTransitions = /* @__PURE__ */ new Map();
  1415. let removePageHideEventListener = null;
  1416. let isUninterruptedRevalidation = false;
  1417. let isRevalidationRequired = false;
  1418. let cancelledFetcherLoads = /* @__PURE__ */ new Set();
  1419. let fetchControllers = /* @__PURE__ */ new Map();
  1420. let incrementingLoadId = 0;
  1421. let pendingNavigationLoadId = -1;
  1422. let fetchReloadIds = /* @__PURE__ */ new Map();
  1423. let fetchRedirectIds = /* @__PURE__ */ new Set();
  1424. let fetchLoadMatches = /* @__PURE__ */ new Map();
  1425. let activeFetchers = /* @__PURE__ */ new Map();
  1426. let fetchersQueuedForDeletion = /* @__PURE__ */ new Set();
  1427. let blockerFunctions = /* @__PURE__ */ new Map();
  1428. let unblockBlockerHistoryUpdate = void 0;
  1429. let pendingRevalidationDfd = null;
  1430. function initialize() {
  1431. unlistenHistory = init.history.listen(
  1432. ({ action: historyAction, location, delta }) => {
  1433. if (unblockBlockerHistoryUpdate) {
  1434. unblockBlockerHistoryUpdate();
  1435. unblockBlockerHistoryUpdate = void 0;
  1436. return;
  1437. }
  1438. warning(
  1439. blockerFunctions.size === 0 || delta != null,
  1440. "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."
  1441. );
  1442. let blockerKey = shouldBlockNavigation({
  1443. currentLocation: state.location,
  1444. nextLocation: location,
  1445. historyAction
  1446. });
  1447. if (blockerKey && delta != null) {
  1448. let nextHistoryUpdatePromise = new Promise((resolve) => {
  1449. unblockBlockerHistoryUpdate = resolve;
  1450. });
  1451. init.history.go(delta * -1);
  1452. updateBlocker(blockerKey, {
  1453. state: "blocked",
  1454. location,
  1455. proceed() {
  1456. updateBlocker(blockerKey, {
  1457. state: "proceeding",
  1458. proceed: void 0,
  1459. reset: void 0,
  1460. location
  1461. });
  1462. nextHistoryUpdatePromise.then(() => init.history.go(delta));
  1463. },
  1464. reset() {
  1465. let blockers = new Map(state.blockers);
  1466. blockers.set(blockerKey, IDLE_BLOCKER);
  1467. updateState({ blockers });
  1468. }
  1469. });
  1470. pendingPopstateNavigationDfd?.resolve();
  1471. pendingPopstateNavigationDfd = null;
  1472. return;
  1473. }
  1474. return startNavigation(historyAction, location);
  1475. }
  1476. );
  1477. if (isBrowser2) {
  1478. restoreAppliedTransitions(routerWindow, appliedViewTransitions);
  1479. let _saveAppliedTransitions = () => persistAppliedTransitions(routerWindow, appliedViewTransitions);
  1480. routerWindow.addEventListener("pagehide", _saveAppliedTransitions);
  1481. removePageHideEventListener = () => routerWindow.removeEventListener("pagehide", _saveAppliedTransitions);
  1482. }
  1483. if (!state.initialized) {
  1484. startNavigation("POP" /* Pop */, state.location, {
  1485. initialHydration: true
  1486. });
  1487. }
  1488. return router;
  1489. }
  1490. function dispose() {
  1491. if (unlistenHistory) {
  1492. unlistenHistory();
  1493. }
  1494. if (removePageHideEventListener) {
  1495. removePageHideEventListener();
  1496. }
  1497. subscribers.clear();
  1498. pendingNavigationController && pendingNavigationController.abort();
  1499. state.fetchers.forEach((_, key) => deleteFetcher(key));
  1500. state.blockers.forEach((_, key) => deleteBlocker(key));
  1501. }
  1502. function subscribe(fn) {
  1503. subscribers.add(fn);
  1504. return () => subscribers.delete(fn);
  1505. }
  1506. function updateState(newState, opts = {}) {
  1507. if (newState.matches) {
  1508. newState.matches = newState.matches.map((m) => {
  1509. let route = manifest[m.route.id];
  1510. let matchRoute = m.route;
  1511. if (matchRoute.element !== route.element || matchRoute.errorElement !== route.errorElement || matchRoute.hydrateFallbackElement !== route.hydrateFallbackElement) {
  1512. return {
  1513. ...m,
  1514. route
  1515. };
  1516. }
  1517. return m;
  1518. });
  1519. }
  1520. state = {
  1521. ...state,
  1522. ...newState
  1523. };
  1524. let unmountedFetchers = [];
  1525. let mountedFetchers = [];
  1526. state.fetchers.forEach((fetcher, key) => {
  1527. if (fetcher.state === "idle") {
  1528. if (fetchersQueuedForDeletion.has(key)) {
  1529. unmountedFetchers.push(key);
  1530. } else {
  1531. mountedFetchers.push(key);
  1532. }
  1533. }
  1534. });
  1535. fetchersQueuedForDeletion.forEach((key) => {
  1536. if (!state.fetchers.has(key) && !fetchControllers.has(key)) {
  1537. unmountedFetchers.push(key);
  1538. }
  1539. });
  1540. [...subscribers].forEach(
  1541. (subscriber) => subscriber(state, {
  1542. deletedFetchers: unmountedFetchers,
  1543. newErrors: newState.errors ?? null,
  1544. viewTransitionOpts: opts.viewTransitionOpts,
  1545. flushSync: opts.flushSync === true
  1546. })
  1547. );
  1548. unmountedFetchers.forEach((key) => deleteFetcher(key));
  1549. mountedFetchers.forEach((key) => state.fetchers.delete(key));
  1550. }
  1551. function completeNavigation(location, newState, { flushSync } = {}) {
  1552. let isActionReload = state.actionData != null && state.navigation.formMethod != null && isMutationMethod(state.navigation.formMethod) && state.navigation.state === "loading" && location.state?._isRedirect !== true;
  1553. let actionData;
  1554. if (newState.actionData) {
  1555. if (Object.keys(newState.actionData).length > 0) {
  1556. actionData = newState.actionData;
  1557. } else {
  1558. actionData = null;
  1559. }
  1560. } else if (isActionReload) {
  1561. actionData = state.actionData;
  1562. } else {
  1563. actionData = null;
  1564. }
  1565. let loaderData = newState.loaderData ? mergeLoaderData(
  1566. state.loaderData,
  1567. newState.loaderData,
  1568. newState.matches || [],
  1569. newState.errors
  1570. ) : state.loaderData;
  1571. let blockers = state.blockers;
  1572. if (blockers.size > 0) {
  1573. blockers = new Map(blockers);
  1574. blockers.forEach((_, k) => blockers.set(k, IDLE_BLOCKER));
  1575. }
  1576. let restoreScrollPosition = isUninterruptedRevalidation ? false : getSavedScrollPosition(location, newState.matches || state.matches);
  1577. let preventScrollReset = pendingPreventScrollReset === true || state.navigation.formMethod != null && isMutationMethod(state.navigation.formMethod) && location.state?._isRedirect !== true;
  1578. if (inFlightDataRoutes) {
  1579. dataRoutes = inFlightDataRoutes;
  1580. inFlightDataRoutes = void 0;
  1581. }
  1582. if (isUninterruptedRevalidation) {
  1583. } else if (pendingAction === "POP" /* Pop */) {
  1584. } else if (pendingAction === "PUSH" /* Push */) {
  1585. init.history.push(location, location.state);
  1586. } else if (pendingAction === "REPLACE" /* Replace */) {
  1587. init.history.replace(location, location.state);
  1588. }
  1589. let viewTransitionOpts;
  1590. if (pendingAction === "POP" /* Pop */) {
  1591. let priorPaths = appliedViewTransitions.get(state.location.pathname);
  1592. if (priorPaths && priorPaths.has(location.pathname)) {
  1593. viewTransitionOpts = {
  1594. currentLocation: state.location,
  1595. nextLocation: location
  1596. };
  1597. } else if (appliedViewTransitions.has(location.pathname)) {
  1598. viewTransitionOpts = {
  1599. currentLocation: location,
  1600. nextLocation: state.location
  1601. };
  1602. }
  1603. } else if (pendingViewTransitionEnabled) {
  1604. let toPaths = appliedViewTransitions.get(state.location.pathname);
  1605. if (toPaths) {
  1606. toPaths.add(location.pathname);
  1607. } else {
  1608. toPaths = /* @__PURE__ */ new Set([location.pathname]);
  1609. appliedViewTransitions.set(state.location.pathname, toPaths);
  1610. }
  1611. viewTransitionOpts = {
  1612. currentLocation: state.location,
  1613. nextLocation: location
  1614. };
  1615. }
  1616. updateState(
  1617. {
  1618. ...newState,
  1619. // matches, errors, fetchers go through as-is
  1620. actionData,
  1621. loaderData,
  1622. historyAction: pendingAction,
  1623. location,
  1624. initialized: true,
  1625. navigation: IDLE_NAVIGATION,
  1626. revalidation: "idle",
  1627. restoreScrollPosition,
  1628. preventScrollReset,
  1629. blockers
  1630. },
  1631. {
  1632. viewTransitionOpts,
  1633. flushSync: flushSync === true
  1634. }
  1635. );
  1636. pendingAction = "POP" /* Pop */;
  1637. pendingPreventScrollReset = false;
  1638. pendingViewTransitionEnabled = false;
  1639. isUninterruptedRevalidation = false;
  1640. isRevalidationRequired = false;
  1641. pendingPopstateNavigationDfd?.resolve();
  1642. pendingPopstateNavigationDfd = null;
  1643. pendingRevalidationDfd?.resolve();
  1644. pendingRevalidationDfd = null;
  1645. }
  1646. async function navigate(to, opts) {
  1647. pendingPopstateNavigationDfd?.resolve();
  1648. pendingPopstateNavigationDfd = null;
  1649. if (typeof to === "number") {
  1650. if (!pendingPopstateNavigationDfd) {
  1651. pendingPopstateNavigationDfd = createDeferred();
  1652. }
  1653. let promise = pendingPopstateNavigationDfd.promise;
  1654. init.history.go(to);
  1655. return promise;
  1656. }
  1657. let normalizedPath = normalizeTo(
  1658. state.location,
  1659. state.matches,
  1660. basename,
  1661. to,
  1662. opts?.fromRouteId,
  1663. opts?.relative
  1664. );
  1665. let { path, submission, error } = normalizeNavigateOptions(
  1666. false,
  1667. normalizedPath,
  1668. opts
  1669. );
  1670. let currentLocation = state.location;
  1671. let nextLocation = createLocation(state.location, path, opts && opts.state);
  1672. nextLocation = {
  1673. ...nextLocation,
  1674. ...init.history.encodeLocation(nextLocation)
  1675. };
  1676. let userReplace = opts && opts.replace != null ? opts.replace : void 0;
  1677. let historyAction = "PUSH" /* Push */;
  1678. if (userReplace === true) {
  1679. historyAction = "REPLACE" /* Replace */;
  1680. } else if (userReplace === false) {
  1681. } else if (submission != null && isMutationMethod(submission.formMethod) && submission.formAction === state.location.pathname + state.location.search) {
  1682. historyAction = "REPLACE" /* Replace */;
  1683. }
  1684. let preventScrollReset = opts && "preventScrollReset" in opts ? opts.preventScrollReset === true : void 0;
  1685. let flushSync = (opts && opts.flushSync) === true;
  1686. let blockerKey = shouldBlockNavigation({
  1687. currentLocation,
  1688. nextLocation,
  1689. historyAction
  1690. });
  1691. if (blockerKey) {
  1692. updateBlocker(blockerKey, {
  1693. state: "blocked",
  1694. location: nextLocation,
  1695. proceed() {
  1696. updateBlocker(blockerKey, {
  1697. state: "proceeding",
  1698. proceed: void 0,
  1699. reset: void 0,
  1700. location: nextLocation
  1701. });
  1702. navigate(to, opts);
  1703. },
  1704. reset() {
  1705. let blockers = new Map(state.blockers);
  1706. blockers.set(blockerKey, IDLE_BLOCKER);
  1707. updateState({ blockers });
  1708. }
  1709. });
  1710. return;
  1711. }
  1712. await startNavigation(historyAction, nextLocation, {
  1713. submission,
  1714. // Send through the formData serialization error if we have one so we can
  1715. // render at the right error boundary after we match routes
  1716. pendingError: error,
  1717. preventScrollReset,
  1718. replace: opts && opts.replace,
  1719. enableViewTransition: opts && opts.viewTransition,
  1720. flushSync
  1721. });
  1722. }
  1723. function revalidate() {
  1724. if (!pendingRevalidationDfd) {
  1725. pendingRevalidationDfd = createDeferred();
  1726. }
  1727. interruptActiveLoads();
  1728. updateState({ revalidation: "loading" });
  1729. let promise = pendingRevalidationDfd.promise;
  1730. if (state.navigation.state === "submitting") {
  1731. return promise;
  1732. }
  1733. if (state.navigation.state === "idle") {
  1734. startNavigation(state.historyAction, state.location, {
  1735. startUninterruptedRevalidation: true
  1736. });
  1737. return promise;
  1738. }
  1739. startNavigation(
  1740. pendingAction || state.historyAction,
  1741. state.navigation.location,
  1742. {
  1743. overrideNavigation: state.navigation,
  1744. // Proxy through any rending view transition
  1745. enableViewTransition: pendingViewTransitionEnabled === true
  1746. }
  1747. );
  1748. return promise;
  1749. }
  1750. async function startNavigation(historyAction, location, opts) {
  1751. pendingNavigationController && pendingNavigationController.abort();
  1752. pendingNavigationController = null;
  1753. pendingAction = historyAction;
  1754. isUninterruptedRevalidation = (opts && opts.startUninterruptedRevalidation) === true;
  1755. saveScrollPosition(state.location, state.matches);
  1756. pendingPreventScrollReset = (opts && opts.preventScrollReset) === true;
  1757. pendingViewTransitionEnabled = (opts && opts.enableViewTransition) === true;
  1758. let routesToUse = inFlightDataRoutes || dataRoutes;
  1759. let loadingNavigation = opts && opts.overrideNavigation;
  1760. let matches = opts?.initialHydration && state.matches && state.matches.length > 0 && !initialMatchesIsFOW ? (
  1761. // `matchRoutes()` has already been called if we're in here via `router.initialize()`
  1762. state.matches
  1763. ) : matchRoutes(routesToUse, location, basename);
  1764. let flushSync = (opts && opts.flushSync) === true;
  1765. if (matches && state.initialized && !isRevalidationRequired && isHashChangeOnly(state.location, location) && !(opts && opts.submission && isMutationMethod(opts.submission.formMethod))) {
  1766. completeNavigation(location, { matches }, { flushSync });
  1767. return;
  1768. }
  1769. let fogOfWar = checkFogOfWar(matches, routesToUse, location.pathname);
  1770. if (fogOfWar.active && fogOfWar.matches) {
  1771. matches = fogOfWar.matches;
  1772. }
  1773. if (!matches) {
  1774. let { error, notFoundMatches, route } = handleNavigational404(
  1775. location.pathname
  1776. );
  1777. completeNavigation(
  1778. location,
  1779. {
  1780. matches: notFoundMatches,
  1781. loaderData: {},
  1782. errors: {
  1783. [route.id]: error
  1784. }
  1785. },
  1786. { flushSync }
  1787. );
  1788. return;
  1789. }
  1790. pendingNavigationController = new AbortController();
  1791. let request = createClientSideRequest(
  1792. init.history,
  1793. location,
  1794. pendingNavigationController.signal,
  1795. opts && opts.submission
  1796. );
  1797. let scopedContext = init.getContext ? await init.getContext() : new RouterContextProvider();
  1798. let pendingActionResult;
  1799. if (opts && opts.pendingError) {
  1800. pendingActionResult = [
  1801. findNearestBoundary(matches).route.id,
  1802. { type: "error" /* error */, error: opts.pendingError }
  1803. ];
  1804. } else if (opts && opts.submission && isMutationMethod(opts.submission.formMethod)) {
  1805. let actionResult = await handleAction(
  1806. request,
  1807. location,
  1808. opts.submission,
  1809. matches,
  1810. scopedContext,
  1811. fogOfWar.active,
  1812. opts && opts.initialHydration === true,
  1813. { replace: opts.replace, flushSync }
  1814. );
  1815. if (actionResult.shortCircuited) {
  1816. return;
  1817. }
  1818. if (actionResult.pendingActionResult) {
  1819. let [routeId, result] = actionResult.pendingActionResult;
  1820. if (isErrorResult(result) && isRouteErrorResponse(result.error) && result.error.status === 404) {
  1821. pendingNavigationController = null;
  1822. completeNavigation(location, {
  1823. matches: actionResult.matches,
  1824. loaderData: {},
  1825. errors: {
  1826. [routeId]: result.error
  1827. }
  1828. });
  1829. return;
  1830. }
  1831. }
  1832. matches = actionResult.matches || matches;
  1833. pendingActionResult = actionResult.pendingActionResult;
  1834. loadingNavigation = getLoadingNavigation(location, opts.submission);
  1835. flushSync = false;
  1836. fogOfWar.active = false;
  1837. request = createClientSideRequest(
  1838. init.history,
  1839. request.url,
  1840. request.signal
  1841. );
  1842. }
  1843. let {
  1844. shortCircuited,
  1845. matches: updatedMatches,
  1846. loaderData,
  1847. errors
  1848. } = await handleLoaders(
  1849. request,
  1850. location,
  1851. matches,
  1852. scopedContext,
  1853. fogOfWar.active,
  1854. loadingNavigation,
  1855. opts && opts.submission,
  1856. opts && opts.fetcherSubmission,
  1857. opts && opts.replace,
  1858. opts && opts.initialHydration === true,
  1859. flushSync,
  1860. pendingActionResult
  1861. );
  1862. if (shortCircuited) {
  1863. return;
  1864. }
  1865. pendingNavigationController = null;
  1866. completeNavigation(location, {
  1867. matches: updatedMatches || matches,
  1868. ...getActionDataForCommit(pendingActionResult),
  1869. loaderData,
  1870. errors
  1871. });
  1872. }
  1873. async function handleAction(request, location, submission, matches, scopedContext, isFogOfWar, initialHydration, opts = {}) {
  1874. interruptActiveLoads();
  1875. let navigation = getSubmittingNavigation(location, submission);
  1876. updateState({ navigation }, { flushSync: opts.flushSync === true });
  1877. if (isFogOfWar) {
  1878. let discoverResult = await discoverRoutes(
  1879. matches,
  1880. location.pathname,
  1881. request.signal
  1882. );
  1883. if (discoverResult.type === "aborted") {
  1884. return { shortCircuited: true };
  1885. } else if (discoverResult.type === "error") {
  1886. if (discoverResult.partialMatches.length === 0) {
  1887. let { matches: matches2, route } = getShortCircuitMatches(dataRoutes);
  1888. return {
  1889. matches: matches2,
  1890. pendingActionResult: [
  1891. route.id,
  1892. {
  1893. type: "error" /* error */,
  1894. error: discoverResult.error
  1895. }
  1896. ]
  1897. };
  1898. }
  1899. let boundaryId = findNearestBoundary(discoverResult.partialMatches).route.id;
  1900. return {
  1901. matches: discoverResult.partialMatches,
  1902. pendingActionResult: [
  1903. boundaryId,
  1904. {
  1905. type: "error" /* error */,
  1906. error: discoverResult.error
  1907. }
  1908. ]
  1909. };
  1910. } else if (!discoverResult.matches) {
  1911. let { notFoundMatches, error, route } = handleNavigational404(
  1912. location.pathname
  1913. );
  1914. return {
  1915. matches: notFoundMatches,
  1916. pendingActionResult: [
  1917. route.id,
  1918. {
  1919. type: "error" /* error */,
  1920. error
  1921. }
  1922. ]
  1923. };
  1924. } else {
  1925. matches = discoverResult.matches;
  1926. }
  1927. }
  1928. let result;
  1929. let actionMatch = getTargetMatch(matches, location);
  1930. if (!actionMatch.route.action && !actionMatch.route.lazy) {
  1931. result = {
  1932. type: "error" /* error */,
  1933. error: getInternalRouterError(405, {
  1934. method: request.method,
  1935. pathname: location.pathname,
  1936. routeId: actionMatch.route.id
  1937. })
  1938. };
  1939. } else {
  1940. let dsMatches = getTargetedDataStrategyMatches(
  1941. mapRouteProperties2,
  1942. manifest,
  1943. request,
  1944. matches,
  1945. actionMatch,
  1946. initialHydration ? [] : hydrationRouteProperties2,
  1947. scopedContext
  1948. );
  1949. let results = await callDataStrategy(
  1950. request,
  1951. dsMatches,
  1952. scopedContext,
  1953. null
  1954. );
  1955. result = results[actionMatch.route.id];
  1956. if (!result) {
  1957. for (let match of matches) {
  1958. if (results[match.route.id]) {
  1959. result = results[match.route.id];
  1960. break;
  1961. }
  1962. }
  1963. }
  1964. if (request.signal.aborted) {
  1965. return { shortCircuited: true };
  1966. }
  1967. }
  1968. if (isRedirectResult(result)) {
  1969. let replace2;
  1970. if (opts && opts.replace != null) {
  1971. replace2 = opts.replace;
  1972. } else {
  1973. let location2 = normalizeRedirectLocation(
  1974. result.response.headers.get("Location"),
  1975. new URL(request.url),
  1976. basename
  1977. );
  1978. replace2 = location2 === state.location.pathname + state.location.search;
  1979. }
  1980. await startRedirectNavigation(request, result, true, {
  1981. submission,
  1982. replace: replace2
  1983. });
  1984. return { shortCircuited: true };
  1985. }
  1986. if (isErrorResult(result)) {
  1987. let boundaryMatch = findNearestBoundary(matches, actionMatch.route.id);
  1988. if ((opts && opts.replace) !== true) {
  1989. pendingAction = "PUSH" /* Push */;
  1990. }
  1991. return {
  1992. matches,
  1993. pendingActionResult: [
  1994. boundaryMatch.route.id,
  1995. result,
  1996. actionMatch.route.id
  1997. ]
  1998. };
  1999. }
  2000. return {
  2001. matches,
  2002. pendingActionResult: [actionMatch.route.id, result]
  2003. };
  2004. }
  2005. async function handleLoaders(request, location, matches, scopedContext, isFogOfWar, overrideNavigation, submission, fetcherSubmission, replace2, initialHydration, flushSync, pendingActionResult) {
  2006. let loadingNavigation = overrideNavigation || getLoadingNavigation(location, submission);
  2007. let activeSubmission = submission || fetcherSubmission || getSubmissionFromNavigation(loadingNavigation);
  2008. let shouldUpdateNavigationState = !isUninterruptedRevalidation && !initialHydration;
  2009. if (isFogOfWar) {
  2010. if (shouldUpdateNavigationState) {
  2011. let actionData = getUpdatedActionData(pendingActionResult);
  2012. updateState(
  2013. {
  2014. navigation: loadingNavigation,
  2015. ...actionData !== void 0 ? { actionData } : {}
  2016. },
  2017. {
  2018. flushSync
  2019. }
  2020. );
  2021. }
  2022. let discoverResult = await discoverRoutes(
  2023. matches,
  2024. location.pathname,
  2025. request.signal
  2026. );
  2027. if (discoverResult.type === "aborted") {
  2028. return { shortCircuited: true };
  2029. } else if (discoverResult.type === "error") {
  2030. if (discoverResult.partialMatches.length === 0) {
  2031. let { matches: matches2, route } = getShortCircuitMatches(dataRoutes);
  2032. return {
  2033. matches: matches2,
  2034. loaderData: {},
  2035. errors: {
  2036. [route.id]: discoverResult.error
  2037. }
  2038. };
  2039. }
  2040. let boundaryId = findNearestBoundary(discoverResult.partialMatches).route.id;
  2041. return {
  2042. matches: discoverResult.partialMatches,
  2043. loaderData: {},
  2044. errors: {
  2045. [boundaryId]: discoverResult.error
  2046. }
  2047. };
  2048. } else if (!discoverResult.matches) {
  2049. let { error, notFoundMatches, route } = handleNavigational404(
  2050. location.pathname
  2051. );
  2052. return {
  2053. matches: notFoundMatches,
  2054. loaderData: {},
  2055. errors: {
  2056. [route.id]: error
  2057. }
  2058. };
  2059. } else {
  2060. matches = discoverResult.matches;
  2061. }
  2062. }
  2063. let routesToUse = inFlightDataRoutes || dataRoutes;
  2064. let { dsMatches, revalidatingFetchers } = getMatchesToLoad(
  2065. request,
  2066. scopedContext,
  2067. mapRouteProperties2,
  2068. manifest,
  2069. init.history,
  2070. state,
  2071. matches,
  2072. activeSubmission,
  2073. location,
  2074. initialHydration ? [] : hydrationRouteProperties2,
  2075. initialHydration === true,
  2076. isRevalidationRequired,
  2077. cancelledFetcherLoads,
  2078. fetchersQueuedForDeletion,
  2079. fetchLoadMatches,
  2080. fetchRedirectIds,
  2081. routesToUse,
  2082. basename,
  2083. init.patchRoutesOnNavigation != null,
  2084. pendingActionResult
  2085. );
  2086. pendingNavigationLoadId = ++incrementingLoadId;
  2087. if (!init.dataStrategy && !dsMatches.some((m) => m.shouldLoad) && !dsMatches.some(
  2088. (m) => m.route.middleware && m.route.middleware.length > 0
  2089. ) && revalidatingFetchers.length === 0) {
  2090. let updatedFetchers2 = markFetchRedirectsDone();
  2091. completeNavigation(
  2092. location,
  2093. {
  2094. matches,
  2095. loaderData: {},
  2096. // Commit pending error if we're short circuiting
  2097. errors: pendingActionResult && isErrorResult(pendingActionResult[1]) ? { [pendingActionResult[0]]: pendingActionResult[1].error } : null,
  2098. ...getActionDataForCommit(pendingActionResult),
  2099. ...updatedFetchers2 ? { fetchers: new Map(state.fetchers) } : {}
  2100. },
  2101. { flushSync }
  2102. );
  2103. return { shortCircuited: true };
  2104. }
  2105. if (shouldUpdateNavigationState) {
  2106. let updates = {};
  2107. if (!isFogOfWar) {
  2108. updates.navigation = loadingNavigation;
  2109. let actionData = getUpdatedActionData(pendingActionResult);
  2110. if (actionData !== void 0) {
  2111. updates.actionData = actionData;
  2112. }
  2113. }
  2114. if (revalidatingFetchers.length > 0) {
  2115. updates.fetchers = getUpdatedRevalidatingFetchers(revalidatingFetchers);
  2116. }
  2117. updateState(updates, { flushSync });
  2118. }
  2119. revalidatingFetchers.forEach((rf) => {
  2120. abortFetcher(rf.key);
  2121. if (rf.controller) {
  2122. fetchControllers.set(rf.key, rf.controller);
  2123. }
  2124. });
  2125. let abortPendingFetchRevalidations = () => revalidatingFetchers.forEach((f) => abortFetcher(f.key));
  2126. if (pendingNavigationController) {
  2127. pendingNavigationController.signal.addEventListener(
  2128. "abort",
  2129. abortPendingFetchRevalidations
  2130. );
  2131. }
  2132. let { loaderResults, fetcherResults } = await callLoadersAndMaybeResolveData(
  2133. dsMatches,
  2134. revalidatingFetchers,
  2135. request,
  2136. scopedContext
  2137. );
  2138. if (request.signal.aborted) {
  2139. return { shortCircuited: true };
  2140. }
  2141. if (pendingNavigationController) {
  2142. pendingNavigationController.signal.removeEventListener(
  2143. "abort",
  2144. abortPendingFetchRevalidations
  2145. );
  2146. }
  2147. revalidatingFetchers.forEach((rf) => fetchControllers.delete(rf.key));
  2148. let redirect2 = findRedirect(loaderResults);
  2149. if (redirect2) {
  2150. await startRedirectNavigation(request, redirect2.result, true, {
  2151. replace: replace2
  2152. });
  2153. return { shortCircuited: true };
  2154. }
  2155. redirect2 = findRedirect(fetcherResults);
  2156. if (redirect2) {
  2157. fetchRedirectIds.add(redirect2.key);
  2158. await startRedirectNavigation(request, redirect2.result, true, {
  2159. replace: replace2
  2160. });
  2161. return { shortCircuited: true };
  2162. }
  2163. let { loaderData, errors } = processLoaderData(
  2164. state,
  2165. matches,
  2166. loaderResults,
  2167. pendingActionResult,
  2168. revalidatingFetchers,
  2169. fetcherResults
  2170. );
  2171. if (initialHydration && state.errors) {
  2172. errors = { ...state.errors, ...errors };
  2173. }
  2174. let updatedFetchers = markFetchRedirectsDone();
  2175. let didAbortFetchLoads = abortStaleFetchLoads(pendingNavigationLoadId);
  2176. let shouldUpdateFetchers = updatedFetchers || didAbortFetchLoads || revalidatingFetchers.length > 0;
  2177. return {
  2178. matches,
  2179. loaderData,
  2180. errors,
  2181. ...shouldUpdateFetchers ? { fetchers: new Map(state.fetchers) } : {}
  2182. };
  2183. }
  2184. function getUpdatedActionData(pendingActionResult) {
  2185. if (pendingActionResult && !isErrorResult(pendingActionResult[1])) {
  2186. return {
  2187. [pendingActionResult[0]]: pendingActionResult[1].data
  2188. };
  2189. } else if (state.actionData) {
  2190. if (Object.keys(state.actionData).length === 0) {
  2191. return null;
  2192. } else {
  2193. return state.actionData;
  2194. }
  2195. }
  2196. }
  2197. function getUpdatedRevalidatingFetchers(revalidatingFetchers) {
  2198. revalidatingFetchers.forEach((rf) => {
  2199. let fetcher = state.fetchers.get(rf.key);
  2200. let revalidatingFetcher = getLoadingFetcher(
  2201. void 0,
  2202. fetcher ? fetcher.data : void 0
  2203. );
  2204. state.fetchers.set(rf.key, revalidatingFetcher);
  2205. });
  2206. return new Map(state.fetchers);
  2207. }
  2208. async function fetch2(key, routeId, href, opts) {
  2209. abortFetcher(key);
  2210. let flushSync = (opts && opts.flushSync) === true;
  2211. let routesToUse = inFlightDataRoutes || dataRoutes;
  2212. let normalizedPath = normalizeTo(
  2213. state.location,
  2214. state.matches,
  2215. basename,
  2216. href,
  2217. routeId,
  2218. opts?.relative
  2219. );
  2220. let matches = matchRoutes(routesToUse, normalizedPath, basename);
  2221. let fogOfWar = checkFogOfWar(matches, routesToUse, normalizedPath);
  2222. if (fogOfWar.active && fogOfWar.matches) {
  2223. matches = fogOfWar.matches;
  2224. }
  2225. if (!matches) {
  2226. setFetcherError(
  2227. key,
  2228. routeId,
  2229. getInternalRouterError(404, { pathname: normalizedPath }),
  2230. { flushSync }
  2231. );
  2232. return;
  2233. }
  2234. let { path, submission, error } = normalizeNavigateOptions(
  2235. true,
  2236. normalizedPath,
  2237. opts
  2238. );
  2239. if (error) {
  2240. setFetcherError(key, routeId, error, { flushSync });
  2241. return;
  2242. }
  2243. let scopedContext = init.getContext ? await init.getContext() : new RouterContextProvider();
  2244. let preventScrollReset = (opts && opts.preventScrollReset) === true;
  2245. if (submission && isMutationMethod(submission.formMethod)) {
  2246. await handleFetcherAction(
  2247. key,
  2248. routeId,
  2249. path,
  2250. matches,
  2251. scopedContext,
  2252. fogOfWar.active,
  2253. flushSync,
  2254. preventScrollReset,
  2255. submission
  2256. );
  2257. return;
  2258. }
  2259. fetchLoadMatches.set(key, { routeId, path });
  2260. await handleFetcherLoader(
  2261. key,
  2262. routeId,
  2263. path,
  2264. matches,
  2265. scopedContext,
  2266. fogOfWar.active,
  2267. flushSync,
  2268. preventScrollReset,
  2269. submission
  2270. );
  2271. }
  2272. async function handleFetcherAction(key, routeId, path, requestMatches, scopedContext, isFogOfWar, flushSync, preventScrollReset, submission) {
  2273. interruptActiveLoads();
  2274. fetchLoadMatches.delete(key);
  2275. let existingFetcher = state.fetchers.get(key);
  2276. updateFetcherState(key, getSubmittingFetcher(submission, existingFetcher), {
  2277. flushSync
  2278. });
  2279. let abortController = new AbortController();
  2280. let fetchRequest = createClientSideRequest(
  2281. init.history,
  2282. path,
  2283. abortController.signal,
  2284. submission
  2285. );
  2286. if (isFogOfWar) {
  2287. let discoverResult = await discoverRoutes(
  2288. requestMatches,
  2289. new URL(fetchRequest.url).pathname,
  2290. fetchRequest.signal,
  2291. key
  2292. );
  2293. if (discoverResult.type === "aborted") {
  2294. return;
  2295. } else if (discoverResult.type === "error") {
  2296. setFetcherError(key, routeId, discoverResult.error, { flushSync });
  2297. return;
  2298. } else if (!discoverResult.matches) {
  2299. setFetcherError(
  2300. key,
  2301. routeId,
  2302. getInternalRouterError(404, { pathname: path }),
  2303. { flushSync }
  2304. );
  2305. return;
  2306. } else {
  2307. requestMatches = discoverResult.matches;
  2308. }
  2309. }
  2310. let match = getTargetMatch(requestMatches, path);
  2311. if (!match.route.action && !match.route.lazy) {
  2312. let error = getInternalRouterError(405, {
  2313. method: submission.formMethod,
  2314. pathname: path,
  2315. routeId
  2316. });
  2317. setFetcherError(key, routeId, error, { flushSync });
  2318. return;
  2319. }
  2320. fetchControllers.set(key, abortController);
  2321. let originatingLoadId = incrementingLoadId;
  2322. let fetchMatches = getTargetedDataStrategyMatches(
  2323. mapRouteProperties2,
  2324. manifest,
  2325. fetchRequest,
  2326. requestMatches,
  2327. match,
  2328. hydrationRouteProperties2,
  2329. scopedContext
  2330. );
  2331. let actionResults = await callDataStrategy(
  2332. fetchRequest,
  2333. fetchMatches,
  2334. scopedContext,
  2335. key
  2336. );
  2337. let actionResult = actionResults[match.route.id];
  2338. if (!actionResult) {
  2339. for (let match2 of fetchMatches) {
  2340. if (actionResults[match2.route.id]) {
  2341. actionResult = actionResults[match2.route.id];
  2342. break;
  2343. }
  2344. }
  2345. }
  2346. if (fetchRequest.signal.aborted) {
  2347. if (fetchControllers.get(key) === abortController) {
  2348. fetchControllers.delete(key);
  2349. }
  2350. return;
  2351. }
  2352. if (fetchersQueuedForDeletion.has(key)) {
  2353. if (isRedirectResult(actionResult) || isErrorResult(actionResult)) {
  2354. updateFetcherState(key, getDoneFetcher(void 0));
  2355. return;
  2356. }
  2357. } else {
  2358. if (isRedirectResult(actionResult)) {
  2359. fetchControllers.delete(key);
  2360. if (pendingNavigationLoadId > originatingLoadId) {
  2361. updateFetcherState(key, getDoneFetcher(void 0));
  2362. return;
  2363. } else {
  2364. fetchRedirectIds.add(key);
  2365. updateFetcherState(key, getLoadingFetcher(submission));
  2366. return startRedirectNavigation(fetchRequest, actionResult, false, {
  2367. fetcherSubmission: submission,
  2368. preventScrollReset
  2369. });
  2370. }
  2371. }
  2372. if (isErrorResult(actionResult)) {
  2373. setFetcherError(key, routeId, actionResult.error);
  2374. return;
  2375. }
  2376. }
  2377. let nextLocation = state.navigation.location || state.location;
  2378. let revalidationRequest = createClientSideRequest(
  2379. init.history,
  2380. nextLocation,
  2381. abortController.signal
  2382. );
  2383. let routesToUse = inFlightDataRoutes || dataRoutes;
  2384. let matches = state.navigation.state !== "idle" ? matchRoutes(routesToUse, state.navigation.location, basename) : state.matches;
  2385. invariant(matches, "Didn't find any matches after fetcher action");
  2386. let loadId = ++incrementingLoadId;
  2387. fetchReloadIds.set(key, loadId);
  2388. let loadFetcher = getLoadingFetcher(submission, actionResult.data);
  2389. state.fetchers.set(key, loadFetcher);
  2390. let { dsMatches, revalidatingFetchers } = getMatchesToLoad(
  2391. revalidationRequest,
  2392. scopedContext,
  2393. mapRouteProperties2,
  2394. manifest,
  2395. init.history,
  2396. state,
  2397. matches,
  2398. submission,
  2399. nextLocation,
  2400. hydrationRouteProperties2,
  2401. false,
  2402. isRevalidationRequired,
  2403. cancelledFetcherLoads,
  2404. fetchersQueuedForDeletion,
  2405. fetchLoadMatches,
  2406. fetchRedirectIds,
  2407. routesToUse,
  2408. basename,
  2409. init.patchRoutesOnNavigation != null,
  2410. [match.route.id, actionResult]
  2411. );
  2412. revalidatingFetchers.filter((rf) => rf.key !== key).forEach((rf) => {
  2413. let staleKey = rf.key;
  2414. let existingFetcher2 = state.fetchers.get(staleKey);
  2415. let revalidatingFetcher = getLoadingFetcher(
  2416. void 0,
  2417. existingFetcher2 ? existingFetcher2.data : void 0
  2418. );
  2419. state.fetchers.set(staleKey, revalidatingFetcher);
  2420. abortFetcher(staleKey);
  2421. if (rf.controller) {
  2422. fetchControllers.set(staleKey, rf.controller);
  2423. }
  2424. });
  2425. updateState({ fetchers: new Map(state.fetchers) });
  2426. let abortPendingFetchRevalidations = () => revalidatingFetchers.forEach((rf) => abortFetcher(rf.key));
  2427. abortController.signal.addEventListener(
  2428. "abort",
  2429. abortPendingFetchRevalidations
  2430. );
  2431. let { loaderResults, fetcherResults } = await callLoadersAndMaybeResolveData(
  2432. dsMatches,
  2433. revalidatingFetchers,
  2434. revalidationRequest,
  2435. scopedContext
  2436. );
  2437. if (abortController.signal.aborted) {
  2438. return;
  2439. }
  2440. abortController.signal.removeEventListener(
  2441. "abort",
  2442. abortPendingFetchRevalidations
  2443. );
  2444. fetchReloadIds.delete(key);
  2445. fetchControllers.delete(key);
  2446. revalidatingFetchers.forEach((r) => fetchControllers.delete(r.key));
  2447. if (state.fetchers.has(key)) {
  2448. let doneFetcher = getDoneFetcher(actionResult.data);
  2449. state.fetchers.set(key, doneFetcher);
  2450. }
  2451. let redirect2 = findRedirect(loaderResults);
  2452. if (redirect2) {
  2453. return startRedirectNavigation(
  2454. revalidationRequest,
  2455. redirect2.result,
  2456. false,
  2457. { preventScrollReset }
  2458. );
  2459. }
  2460. redirect2 = findRedirect(fetcherResults);
  2461. if (redirect2) {
  2462. fetchRedirectIds.add(redirect2.key);
  2463. return startRedirectNavigation(
  2464. revalidationRequest,
  2465. redirect2.result,
  2466. false,
  2467. { preventScrollReset }
  2468. );
  2469. }
  2470. let { loaderData, errors } = processLoaderData(
  2471. state,
  2472. matches,
  2473. loaderResults,
  2474. void 0,
  2475. revalidatingFetchers,
  2476. fetcherResults
  2477. );
  2478. abortStaleFetchLoads(loadId);
  2479. if (state.navigation.state === "loading" && loadId > pendingNavigationLoadId) {
  2480. invariant(pendingAction, "Expected pending action");
  2481. pendingNavigationController && pendingNavigationController.abort();
  2482. completeNavigation(state.navigation.location, {
  2483. matches,
  2484. loaderData,
  2485. errors,
  2486. fetchers: new Map(state.fetchers)
  2487. });
  2488. } else {
  2489. updateState({
  2490. errors,
  2491. loaderData: mergeLoaderData(
  2492. state.loaderData,
  2493. loaderData,
  2494. matches,
  2495. errors
  2496. ),
  2497. fetchers: new Map(state.fetchers)
  2498. });
  2499. isRevalidationRequired = false;
  2500. }
  2501. }
  2502. async function handleFetcherLoader(key, routeId, path, matches, scopedContext, isFogOfWar, flushSync, preventScrollReset, submission) {
  2503. let existingFetcher = state.fetchers.get(key);
  2504. updateFetcherState(
  2505. key,
  2506. getLoadingFetcher(
  2507. submission,
  2508. existingFetcher ? existingFetcher.data : void 0
  2509. ),
  2510. { flushSync }
  2511. );
  2512. let abortController = new AbortController();
  2513. let fetchRequest = createClientSideRequest(
  2514. init.history,
  2515. path,
  2516. abortController.signal
  2517. );
  2518. if (isFogOfWar) {
  2519. let discoverResult = await discoverRoutes(
  2520. matches,
  2521. new URL(fetchRequest.url).pathname,
  2522. fetchRequest.signal,
  2523. key
  2524. );
  2525. if (discoverResult.type === "aborted") {
  2526. return;
  2527. } else if (discoverResult.type === "error") {
  2528. setFetcherError(key, routeId, discoverResult.error, { flushSync });
  2529. return;
  2530. } else if (!discoverResult.matches) {
  2531. setFetcherError(
  2532. key,
  2533. routeId,
  2534. getInternalRouterError(404, { pathname: path }),
  2535. { flushSync }
  2536. );
  2537. return;
  2538. } else {
  2539. matches = discoverResult.matches;
  2540. }
  2541. }
  2542. let match = getTargetMatch(matches, path);
  2543. fetchControllers.set(key, abortController);
  2544. let originatingLoadId = incrementingLoadId;
  2545. let dsMatches = getTargetedDataStrategyMatches(
  2546. mapRouteProperties2,
  2547. manifest,
  2548. fetchRequest,
  2549. matches,
  2550. match,
  2551. hydrationRouteProperties2,
  2552. scopedContext
  2553. );
  2554. let results = await callDataStrategy(
  2555. fetchRequest,
  2556. dsMatches,
  2557. scopedContext,
  2558. key
  2559. );
  2560. let result = results[match.route.id];
  2561. if (fetchControllers.get(key) === abortController) {
  2562. fetchControllers.delete(key);
  2563. }
  2564. if (fetchRequest.signal.aborted) {
  2565. return;
  2566. }
  2567. if (fetchersQueuedForDeletion.has(key)) {
  2568. updateFetcherState(key, getDoneFetcher(void 0));
  2569. return;
  2570. }
  2571. if (isRedirectResult(result)) {
  2572. if (pendingNavigationLoadId > originatingLoadId) {
  2573. updateFetcherState(key, getDoneFetcher(void 0));
  2574. return;
  2575. } else {
  2576. fetchRedirectIds.add(key);
  2577. await startRedirectNavigation(fetchRequest, result, false, {
  2578. preventScrollReset
  2579. });
  2580. return;
  2581. }
  2582. }
  2583. if (isErrorResult(result)) {
  2584. setFetcherError(key, routeId, result.error);
  2585. return;
  2586. }
  2587. updateFetcherState(key, getDoneFetcher(result.data));
  2588. }
  2589. async function startRedirectNavigation(request, redirect2, isNavigation, {
  2590. submission,
  2591. fetcherSubmission,
  2592. preventScrollReset,
  2593. replace: replace2
  2594. } = {}) {
  2595. if (!isNavigation) {
  2596. pendingPopstateNavigationDfd?.resolve();
  2597. pendingPopstateNavigationDfd = null;
  2598. }
  2599. if (redirect2.response.headers.has("X-Remix-Revalidate")) {
  2600. isRevalidationRequired = true;
  2601. }
  2602. let location = redirect2.response.headers.get("Location");
  2603. invariant(location, "Expected a Location header on the redirect Response");
  2604. location = normalizeRedirectLocation(
  2605. location,
  2606. new URL(request.url),
  2607. basename
  2608. );
  2609. let redirectLocation = createLocation(state.location, location, {
  2610. _isRedirect: true
  2611. });
  2612. if (isBrowser2) {
  2613. let isDocumentReload = false;
  2614. if (redirect2.response.headers.has("X-Remix-Reload-Document")) {
  2615. isDocumentReload = true;
  2616. } else if (isAbsoluteUrl(location)) {
  2617. const url = createBrowserURLImpl(location, true);
  2618. isDocumentReload = // Hard reload if it's an absolute URL to a new origin
  2619. url.origin !== routerWindow.location.origin || // Hard reload if it's an absolute URL that does not match our basename
  2620. stripBasename(url.pathname, basename) == null;
  2621. }
  2622. if (isDocumentReload) {
  2623. if (replace2) {
  2624. routerWindow.location.replace(location);
  2625. } else {
  2626. routerWindow.location.assign(location);
  2627. }
  2628. return;
  2629. }
  2630. }
  2631. pendingNavigationController = null;
  2632. let redirectNavigationType = replace2 === true || redirect2.response.headers.has("X-Remix-Replace") ? "REPLACE" /* Replace */ : "PUSH" /* Push */;
  2633. let { formMethod, formAction, formEncType } = state.navigation;
  2634. if (!submission && !fetcherSubmission && formMethod && formAction && formEncType) {
  2635. submission = getSubmissionFromNavigation(state.navigation);
  2636. }
  2637. let activeSubmission = submission || fetcherSubmission;
  2638. if (redirectPreserveMethodStatusCodes.has(redirect2.response.status) && activeSubmission && isMutationMethod(activeSubmission.formMethod)) {
  2639. await startNavigation(redirectNavigationType, redirectLocation, {
  2640. submission: {
  2641. ...activeSubmission,
  2642. formAction: location
  2643. },
  2644. // Preserve these flags across redirects
  2645. preventScrollReset: preventScrollReset || pendingPreventScrollReset,
  2646. enableViewTransition: isNavigation ? pendingViewTransitionEnabled : void 0
  2647. });
  2648. } else {
  2649. let overrideNavigation = getLoadingNavigation(
  2650. redirectLocation,
  2651. submission
  2652. );
  2653. await startNavigation(redirectNavigationType, redirectLocation, {
  2654. overrideNavigation,
  2655. // Send fetcher submissions through for shouldRevalidate
  2656. fetcherSubmission,
  2657. // Preserve these flags across redirects
  2658. preventScrollReset: preventScrollReset || pendingPreventScrollReset,
  2659. enableViewTransition: isNavigation ? pendingViewTransitionEnabled : void 0
  2660. });
  2661. }
  2662. }
  2663. async function callDataStrategy(request, matches, scopedContext, fetcherKey) {
  2664. let results;
  2665. let dataResults = {};
  2666. try {
  2667. results = await callDataStrategyImpl(
  2668. dataStrategyImpl,
  2669. request,
  2670. matches,
  2671. fetcherKey,
  2672. scopedContext,
  2673. false
  2674. );
  2675. } catch (e) {
  2676. matches.filter((m) => m.shouldLoad).forEach((m) => {
  2677. dataResults[m.route.id] = {
  2678. type: "error" /* error */,
  2679. error: e
  2680. };
  2681. });
  2682. return dataResults;
  2683. }
  2684. if (request.signal.aborted) {
  2685. return dataResults;
  2686. }
  2687. for (let [routeId, result] of Object.entries(results)) {
  2688. if (isRedirectDataStrategyResult(result)) {
  2689. let response = result.result;
  2690. dataResults[routeId] = {
  2691. type: "redirect" /* redirect */,
  2692. response: normalizeRelativeRoutingRedirectResponse(
  2693. response,
  2694. request,
  2695. routeId,
  2696. matches,
  2697. basename
  2698. )
  2699. };
  2700. } else {
  2701. dataResults[routeId] = await convertDataStrategyResultToDataResult(result);
  2702. }
  2703. }
  2704. return dataResults;
  2705. }
  2706. async function callLoadersAndMaybeResolveData(matches, fetchersToLoad, request, scopedContext) {
  2707. let loaderResultsPromise = callDataStrategy(
  2708. request,
  2709. matches,
  2710. scopedContext,
  2711. null
  2712. );
  2713. let fetcherResultsPromise = Promise.all(
  2714. fetchersToLoad.map(async (f) => {
  2715. if (f.matches && f.match && f.request && f.controller) {
  2716. let results = await callDataStrategy(
  2717. f.request,
  2718. f.matches,
  2719. scopedContext,
  2720. f.key
  2721. );
  2722. let result = results[f.match.route.id];
  2723. return { [f.key]: result };
  2724. } else {
  2725. return Promise.resolve({
  2726. [f.key]: {
  2727. type: "error" /* error */,
  2728. error: getInternalRouterError(404, {
  2729. pathname: f.path
  2730. })
  2731. }
  2732. });
  2733. }
  2734. })
  2735. );
  2736. let loaderResults = await loaderResultsPromise;
  2737. let fetcherResults = (await fetcherResultsPromise).reduce(
  2738. (acc, r) => Object.assign(acc, r),
  2739. {}
  2740. );
  2741. return {
  2742. loaderResults,
  2743. fetcherResults
  2744. };
  2745. }
  2746. function interruptActiveLoads() {
  2747. isRevalidationRequired = true;
  2748. fetchLoadMatches.forEach((_, key) => {
  2749. if (fetchControllers.has(key)) {
  2750. cancelledFetcherLoads.add(key);
  2751. }
  2752. abortFetcher(key);
  2753. });
  2754. }
  2755. function updateFetcherState(key, fetcher, opts = {}) {
  2756. state.fetchers.set(key, fetcher);
  2757. updateState(
  2758. { fetchers: new Map(state.fetchers) },
  2759. { flushSync: (opts && opts.flushSync) === true }
  2760. );
  2761. }
  2762. function setFetcherError(key, routeId, error, opts = {}) {
  2763. let boundaryMatch = findNearestBoundary(state.matches, routeId);
  2764. deleteFetcher(key);
  2765. updateState(
  2766. {
  2767. errors: {
  2768. [boundaryMatch.route.id]: error
  2769. },
  2770. fetchers: new Map(state.fetchers)
  2771. },
  2772. { flushSync: (opts && opts.flushSync) === true }
  2773. );
  2774. }
  2775. function getFetcher(key) {
  2776. activeFetchers.set(key, (activeFetchers.get(key) || 0) + 1);
  2777. if (fetchersQueuedForDeletion.has(key)) {
  2778. fetchersQueuedForDeletion.delete(key);
  2779. }
  2780. return state.fetchers.get(key) || IDLE_FETCHER;
  2781. }
  2782. function resetFetcher(key, opts) {
  2783. abortFetcher(key, opts?.reason);
  2784. updateFetcherState(key, getDoneFetcher(null));
  2785. }
  2786. function deleteFetcher(key) {
  2787. let fetcher = state.fetchers.get(key);
  2788. if (fetchControllers.has(key) && !(fetcher && fetcher.state === "loading" && fetchReloadIds.has(key))) {
  2789. abortFetcher(key);
  2790. }
  2791. fetchLoadMatches.delete(key);
  2792. fetchReloadIds.delete(key);
  2793. fetchRedirectIds.delete(key);
  2794. fetchersQueuedForDeletion.delete(key);
  2795. cancelledFetcherLoads.delete(key);
  2796. state.fetchers.delete(key);
  2797. }
  2798. function queueFetcherForDeletion(key) {
  2799. let count = (activeFetchers.get(key) || 0) - 1;
  2800. if (count <= 0) {
  2801. activeFetchers.delete(key);
  2802. fetchersQueuedForDeletion.add(key);
  2803. } else {
  2804. activeFetchers.set(key, count);
  2805. }
  2806. updateState({ fetchers: new Map(state.fetchers) });
  2807. }
  2808. function abortFetcher(key, reason) {
  2809. let controller = fetchControllers.get(key);
  2810. if (controller) {
  2811. controller.abort(reason);
  2812. fetchControllers.delete(key);
  2813. }
  2814. }
  2815. function markFetchersDone(keys) {
  2816. for (let key of keys) {
  2817. let fetcher = getFetcher(key);
  2818. let doneFetcher = getDoneFetcher(fetcher.data);
  2819. state.fetchers.set(key, doneFetcher);
  2820. }
  2821. }
  2822. function markFetchRedirectsDone() {
  2823. let doneKeys = [];
  2824. let updatedFetchers = false;
  2825. for (let key of fetchRedirectIds) {
  2826. let fetcher = state.fetchers.get(key);
  2827. invariant(fetcher, `Expected fetcher: ${key}`);
  2828. if (fetcher.state === "loading") {
  2829. fetchRedirectIds.delete(key);
  2830. doneKeys.push(key);
  2831. updatedFetchers = true;
  2832. }
  2833. }
  2834. markFetchersDone(doneKeys);
  2835. return updatedFetchers;
  2836. }
  2837. function abortStaleFetchLoads(landedId) {
  2838. let yeetedKeys = [];
  2839. for (let [key, id] of fetchReloadIds) {
  2840. if (id < landedId) {
  2841. let fetcher = state.fetchers.get(key);
  2842. invariant(fetcher, `Expected fetcher: ${key}`);
  2843. if (fetcher.state === "loading") {
  2844. abortFetcher(key);
  2845. fetchReloadIds.delete(key);
  2846. yeetedKeys.push(key);
  2847. }
  2848. }
  2849. }
  2850. markFetchersDone(yeetedKeys);
  2851. return yeetedKeys.length > 0;
  2852. }
  2853. function getBlocker(key, fn) {
  2854. let blocker = state.blockers.get(key) || IDLE_BLOCKER;
  2855. if (blockerFunctions.get(key) !== fn) {
  2856. blockerFunctions.set(key, fn);
  2857. }
  2858. return blocker;
  2859. }
  2860. function deleteBlocker(key) {
  2861. state.blockers.delete(key);
  2862. blockerFunctions.delete(key);
  2863. }
  2864. function updateBlocker(key, newBlocker) {
  2865. let blocker = state.blockers.get(key) || IDLE_BLOCKER;
  2866. invariant(
  2867. 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",
  2868. `Invalid blocker state transition: ${blocker.state} -> ${newBlocker.state}`
  2869. );
  2870. let blockers = new Map(state.blockers);
  2871. blockers.set(key, newBlocker);
  2872. updateState({ blockers });
  2873. }
  2874. function shouldBlockNavigation({
  2875. currentLocation,
  2876. nextLocation,
  2877. historyAction
  2878. }) {
  2879. if (blockerFunctions.size === 0) {
  2880. return;
  2881. }
  2882. if (blockerFunctions.size > 1) {
  2883. warning(false, "A router only supports one blocker at a time");
  2884. }
  2885. let entries = Array.from(blockerFunctions.entries());
  2886. let [blockerKey, blockerFunction] = entries[entries.length - 1];
  2887. let blocker = state.blockers.get(blockerKey);
  2888. if (blocker && blocker.state === "proceeding") {
  2889. return;
  2890. }
  2891. if (blockerFunction({ currentLocation, nextLocation, historyAction })) {
  2892. return blockerKey;
  2893. }
  2894. }
  2895. function handleNavigational404(pathname) {
  2896. let error = getInternalRouterError(404, { pathname });
  2897. let routesToUse = inFlightDataRoutes || dataRoutes;
  2898. let { matches, route } = getShortCircuitMatches(routesToUse);
  2899. return { notFoundMatches: matches, route, error };
  2900. }
  2901. function enableScrollRestoration(positions, getPosition, getKey) {
  2902. savedScrollPositions2 = positions;
  2903. getScrollPosition = getPosition;
  2904. getScrollRestorationKey2 = getKey || null;
  2905. if (!initialScrollRestored && state.navigation === IDLE_NAVIGATION) {
  2906. initialScrollRestored = true;
  2907. let y = getSavedScrollPosition(state.location, state.matches);
  2908. if (y != null) {
  2909. updateState({ restoreScrollPosition: y });
  2910. }
  2911. }
  2912. return () => {
  2913. savedScrollPositions2 = null;
  2914. getScrollPosition = null;
  2915. getScrollRestorationKey2 = null;
  2916. };
  2917. }
  2918. function getScrollKey(location, matches) {
  2919. if (getScrollRestorationKey2) {
  2920. let key = getScrollRestorationKey2(
  2921. location,
  2922. matches.map((m) => convertRouteMatchToUiMatch(m, state.loaderData))
  2923. );
  2924. return key || location.key;
  2925. }
  2926. return location.key;
  2927. }
  2928. function saveScrollPosition(location, matches) {
  2929. if (savedScrollPositions2 && getScrollPosition) {
  2930. let key = getScrollKey(location, matches);
  2931. savedScrollPositions2[key] = getScrollPosition();
  2932. }
  2933. }
  2934. function getSavedScrollPosition(location, matches) {
  2935. if (savedScrollPositions2) {
  2936. let key = getScrollKey(location, matches);
  2937. let y = savedScrollPositions2[key];
  2938. if (typeof y === "number") {
  2939. return y;
  2940. }
  2941. }
  2942. return null;
  2943. }
  2944. function checkFogOfWar(matches, routesToUse, pathname) {
  2945. if (init.patchRoutesOnNavigation) {
  2946. if (!matches) {
  2947. let fogMatches = matchRoutesImpl(
  2948. routesToUse,
  2949. pathname,
  2950. basename,
  2951. true
  2952. );
  2953. return { active: true, matches: fogMatches || [] };
  2954. } else {
  2955. if (Object.keys(matches[0].params).length > 0) {
  2956. let partialMatches = matchRoutesImpl(
  2957. routesToUse,
  2958. pathname,
  2959. basename,
  2960. true
  2961. );
  2962. return { active: true, matches: partialMatches };
  2963. }
  2964. }
  2965. }
  2966. return { active: false, matches: null };
  2967. }
  2968. async function discoverRoutes(matches, pathname, signal, fetcherKey) {
  2969. if (!init.patchRoutesOnNavigation) {
  2970. return { type: "success", matches };
  2971. }
  2972. let partialMatches = matches;
  2973. while (true) {
  2974. let isNonHMR = inFlightDataRoutes == null;
  2975. let routesToUse = inFlightDataRoutes || dataRoutes;
  2976. let localManifest = manifest;
  2977. try {
  2978. await init.patchRoutesOnNavigation({
  2979. signal,
  2980. path: pathname,
  2981. matches: partialMatches,
  2982. fetcherKey,
  2983. patch: (routeId, children) => {
  2984. if (signal.aborted) return;
  2985. patchRoutesImpl(
  2986. routeId,
  2987. children,
  2988. routesToUse,
  2989. localManifest,
  2990. mapRouteProperties2,
  2991. false
  2992. );
  2993. }
  2994. });
  2995. } catch (e) {
  2996. return { type: "error", error: e, partialMatches };
  2997. } finally {
  2998. if (isNonHMR && !signal.aborted) {
  2999. dataRoutes = [...dataRoutes];
  3000. }
  3001. }
  3002. if (signal.aborted) {
  3003. return { type: "aborted" };
  3004. }
  3005. let newMatches = matchRoutes(routesToUse, pathname, basename);
  3006. let newPartialMatches = null;
  3007. if (newMatches) {
  3008. if (Object.keys(newMatches[0].params).length === 0) {
  3009. return { type: "success", matches: newMatches };
  3010. } else {
  3011. newPartialMatches = matchRoutesImpl(
  3012. routesToUse,
  3013. pathname,
  3014. basename,
  3015. true
  3016. );
  3017. let matchedDeeper = newPartialMatches && partialMatches.length < newPartialMatches.length && compareMatches(
  3018. partialMatches,
  3019. newPartialMatches.slice(0, partialMatches.length)
  3020. );
  3021. if (!matchedDeeper) {
  3022. return { type: "success", matches: newMatches };
  3023. }
  3024. }
  3025. }
  3026. if (!newPartialMatches) {
  3027. newPartialMatches = matchRoutesImpl(
  3028. routesToUse,
  3029. pathname,
  3030. basename,
  3031. true
  3032. );
  3033. }
  3034. if (!newPartialMatches || compareMatches(partialMatches, newPartialMatches)) {
  3035. return { type: "success", matches: null };
  3036. }
  3037. partialMatches = newPartialMatches;
  3038. }
  3039. }
  3040. function compareMatches(a, b) {
  3041. return a.length === b.length && a.every((m, i) => m.route.id === b[i].route.id);
  3042. }
  3043. function _internalSetRoutes(newRoutes) {
  3044. manifest = {};
  3045. inFlightDataRoutes = convertRoutesToDataRoutes(
  3046. newRoutes,
  3047. mapRouteProperties2,
  3048. void 0,
  3049. manifest
  3050. );
  3051. }
  3052. function patchRoutes(routeId, children, unstable_allowElementMutations = false) {
  3053. let isNonHMR = inFlightDataRoutes == null;
  3054. let routesToUse = inFlightDataRoutes || dataRoutes;
  3055. patchRoutesImpl(
  3056. routeId,
  3057. children,
  3058. routesToUse,
  3059. manifest,
  3060. mapRouteProperties2,
  3061. unstable_allowElementMutations
  3062. );
  3063. if (isNonHMR) {
  3064. dataRoutes = [...dataRoutes];
  3065. updateState({});
  3066. }
  3067. }
  3068. router = {
  3069. get basename() {
  3070. return basename;
  3071. },
  3072. get future() {
  3073. return future;
  3074. },
  3075. get state() {
  3076. return state;
  3077. },
  3078. get routes() {
  3079. return dataRoutes;
  3080. },
  3081. get window() {
  3082. return routerWindow;
  3083. },
  3084. initialize,
  3085. subscribe,
  3086. enableScrollRestoration,
  3087. navigate,
  3088. fetch: fetch2,
  3089. revalidate,
  3090. // Passthrough to history-aware createHref used by useHref so we get proper
  3091. // hash-aware URLs in DOM paths
  3092. createHref: (to) => init.history.createHref(to),
  3093. encodeLocation: (to) => init.history.encodeLocation(to),
  3094. getFetcher,
  3095. resetFetcher,
  3096. deleteFetcher: queueFetcherForDeletion,
  3097. dispose,
  3098. getBlocker,
  3099. deleteBlocker,
  3100. patchRoutes,
  3101. _internalFetchControllers: fetchControllers,
  3102. // TODO: Remove setRoutes, it's temporary to avoid dealing with
  3103. // updating the tree while validating the update algorithm.
  3104. _internalSetRoutes,
  3105. _internalSetStateDoNotUseOrYouWillBreakYourApp(newState) {
  3106. updateState(newState);
  3107. }
  3108. };
  3109. if (init.unstable_instrumentations) {
  3110. router = instrumentClientSideRouter(
  3111. router,
  3112. init.unstable_instrumentations.map((i) => i.router).filter(Boolean)
  3113. );
  3114. }
  3115. return router;
  3116. }
  3117. function createStaticHandler(routes, opts) {
  3118. invariant(
  3119. routes.length > 0,
  3120. "You must provide a non-empty routes array to createStaticHandler"
  3121. );
  3122. let manifest = {};
  3123. let basename = (opts ? opts.basename : null) || "/";
  3124. let _mapRouteProperties = opts?.mapRouteProperties || defaultMapRouteProperties;
  3125. let mapRouteProperties2 = _mapRouteProperties;
  3126. if (opts?.unstable_instrumentations) {
  3127. let instrumentations = opts.unstable_instrumentations;
  3128. mapRouteProperties2 = (route) => {
  3129. return {
  3130. ..._mapRouteProperties(route),
  3131. ...getRouteInstrumentationUpdates(
  3132. instrumentations.map((i) => i.route).filter(Boolean),
  3133. route
  3134. )
  3135. };
  3136. };
  3137. }
  3138. let dataRoutes = convertRoutesToDataRoutes(
  3139. routes,
  3140. mapRouteProperties2,
  3141. void 0,
  3142. manifest
  3143. );
  3144. async function query(request, {
  3145. requestContext,
  3146. filterMatchesToLoad,
  3147. skipLoaderErrorBubbling,
  3148. skipRevalidation,
  3149. dataStrategy,
  3150. generateMiddlewareResponse
  3151. } = {}) {
  3152. let url = new URL(request.url);
  3153. let method = request.method;
  3154. let location = createLocation("", createPath(url), null, "default");
  3155. let matches = matchRoutes(dataRoutes, location, basename);
  3156. requestContext = requestContext != null ? requestContext : new RouterContextProvider();
  3157. if (!isValidMethod(method) && method !== "HEAD") {
  3158. let error = getInternalRouterError(405, { method });
  3159. let { matches: methodNotAllowedMatches, route } = getShortCircuitMatches(dataRoutes);
  3160. let staticContext = {
  3161. basename,
  3162. location,
  3163. matches: methodNotAllowedMatches,
  3164. loaderData: {},
  3165. actionData: null,
  3166. errors: {
  3167. [route.id]: error
  3168. },
  3169. statusCode: error.status,
  3170. loaderHeaders: {},
  3171. actionHeaders: {}
  3172. };
  3173. return generateMiddlewareResponse ? generateMiddlewareResponse(() => Promise.resolve(staticContext)) : staticContext;
  3174. } else if (!matches) {
  3175. let error = getInternalRouterError(404, { pathname: location.pathname });
  3176. let { matches: notFoundMatches, route } = getShortCircuitMatches(dataRoutes);
  3177. let staticContext = {
  3178. basename,
  3179. location,
  3180. matches: notFoundMatches,
  3181. loaderData: {},
  3182. actionData: null,
  3183. errors: {
  3184. [route.id]: error
  3185. },
  3186. statusCode: error.status,
  3187. loaderHeaders: {},
  3188. actionHeaders: {}
  3189. };
  3190. return generateMiddlewareResponse ? generateMiddlewareResponse(() => Promise.resolve(staticContext)) : staticContext;
  3191. }
  3192. if (generateMiddlewareResponse) {
  3193. invariant(
  3194. requestContext instanceof RouterContextProvider,
  3195. "When using middleware in `staticHandler.query()`, any provided `requestContext` must be an instance of `RouterContextProvider`"
  3196. );
  3197. try {
  3198. await loadLazyMiddlewareForMatches(
  3199. matches,
  3200. manifest,
  3201. mapRouteProperties2
  3202. );
  3203. let renderedStaticContext;
  3204. let response = await runServerMiddlewarePipeline(
  3205. {
  3206. request,
  3207. unstable_pattern: getRoutePattern(matches),
  3208. matches,
  3209. params: matches[0].params,
  3210. // If we're calling middleware then it must be enabled so we can cast
  3211. // this to the proper type knowing it's not an `AppLoadContext`
  3212. context: requestContext
  3213. },
  3214. async () => {
  3215. let res = await generateMiddlewareResponse(
  3216. async (revalidationRequest, opts2 = {}) => {
  3217. let result2 = await queryImpl(
  3218. revalidationRequest,
  3219. location,
  3220. matches,
  3221. requestContext,
  3222. dataStrategy || null,
  3223. skipLoaderErrorBubbling === true,
  3224. null,
  3225. "filterMatchesToLoad" in opts2 ? opts2.filterMatchesToLoad ?? null : filterMatchesToLoad ?? null,
  3226. skipRevalidation === true
  3227. );
  3228. if (isResponse(result2)) {
  3229. return result2;
  3230. }
  3231. renderedStaticContext = { location, basename, ...result2 };
  3232. return renderedStaticContext;
  3233. }
  3234. );
  3235. return res;
  3236. },
  3237. async (error, routeId) => {
  3238. if (isRedirectResponse(error)) {
  3239. return error;
  3240. }
  3241. if (isResponse(error)) {
  3242. try {
  3243. error = new ErrorResponseImpl(
  3244. error.status,
  3245. error.statusText,
  3246. await parseResponseBody(error)
  3247. );
  3248. } catch (e) {
  3249. error = e;
  3250. }
  3251. }
  3252. if (isDataWithResponseInit(error)) {
  3253. error = dataWithResponseInitToErrorResponse(error);
  3254. }
  3255. if (renderedStaticContext) {
  3256. if (routeId in renderedStaticContext.loaderData) {
  3257. renderedStaticContext.loaderData[routeId] = void 0;
  3258. }
  3259. let staticContext = getStaticContextFromError(
  3260. dataRoutes,
  3261. renderedStaticContext,
  3262. error,
  3263. skipLoaderErrorBubbling ? routeId : findNearestBoundary(matches, routeId).route.id
  3264. );
  3265. return generateMiddlewareResponse(
  3266. () => Promise.resolve(staticContext)
  3267. );
  3268. } else {
  3269. let boundaryRouteId = skipLoaderErrorBubbling ? routeId : findNearestBoundary(
  3270. matches,
  3271. matches.find(
  3272. (m) => m.route.id === routeId || m.route.loader
  3273. )?.route.id || routeId
  3274. ).route.id;
  3275. let staticContext = {
  3276. matches,
  3277. location,
  3278. basename,
  3279. loaderData: {},
  3280. actionData: null,
  3281. errors: {
  3282. [boundaryRouteId]: error
  3283. },
  3284. statusCode: isRouteErrorResponse(error) ? error.status : 500,
  3285. actionHeaders: {},
  3286. loaderHeaders: {}
  3287. };
  3288. return generateMiddlewareResponse(
  3289. () => Promise.resolve(staticContext)
  3290. );
  3291. }
  3292. }
  3293. );
  3294. invariant(isResponse(response), "Expected a response in query()");
  3295. return response;
  3296. } catch (e) {
  3297. if (isResponse(e)) {
  3298. return e;
  3299. }
  3300. throw e;
  3301. }
  3302. }
  3303. let result = await queryImpl(
  3304. request,
  3305. location,
  3306. matches,
  3307. requestContext,
  3308. dataStrategy || null,
  3309. skipLoaderErrorBubbling === true,
  3310. null,
  3311. filterMatchesToLoad || null,
  3312. skipRevalidation === true
  3313. );
  3314. if (isResponse(result)) {
  3315. return result;
  3316. }
  3317. return { location, basename, ...result };
  3318. }
  3319. async function queryRoute(request, {
  3320. routeId,
  3321. requestContext,
  3322. dataStrategy,
  3323. generateMiddlewareResponse
  3324. } = {}) {
  3325. let url = new URL(request.url);
  3326. let method = request.method;
  3327. let location = createLocation("", createPath(url), null, "default");
  3328. let matches = matchRoutes(dataRoutes, location, basename);
  3329. requestContext = requestContext != null ? requestContext : new RouterContextProvider();
  3330. if (!isValidMethod(method) && method !== "HEAD" && method !== "OPTIONS") {
  3331. throw getInternalRouterError(405, { method });
  3332. } else if (!matches) {
  3333. throw getInternalRouterError(404, { pathname: location.pathname });
  3334. }
  3335. let match = routeId ? matches.find((m) => m.route.id === routeId) : getTargetMatch(matches, location);
  3336. if (routeId && !match) {
  3337. throw getInternalRouterError(403, {
  3338. pathname: location.pathname,
  3339. routeId
  3340. });
  3341. } else if (!match) {
  3342. throw getInternalRouterError(404, { pathname: location.pathname });
  3343. }
  3344. if (generateMiddlewareResponse) {
  3345. invariant(
  3346. requestContext instanceof RouterContextProvider,
  3347. "When using middleware in `staticHandler.queryRoute()`, any provided `requestContext` must be an instance of `RouterContextProvider`"
  3348. );
  3349. await loadLazyMiddlewareForMatches(matches, manifest, mapRouteProperties2);
  3350. let response = await runServerMiddlewarePipeline(
  3351. {
  3352. request,
  3353. unstable_pattern: getRoutePattern(matches),
  3354. matches,
  3355. params: matches[0].params,
  3356. // If we're calling middleware then it must be enabled so we can cast
  3357. // this to the proper type knowing it's not an `AppLoadContext`
  3358. context: requestContext
  3359. },
  3360. async () => {
  3361. let res = await generateMiddlewareResponse(
  3362. async (innerRequest) => {
  3363. let result2 = await queryImpl(
  3364. innerRequest,
  3365. location,
  3366. matches,
  3367. requestContext,
  3368. dataStrategy || null,
  3369. false,
  3370. match,
  3371. null,
  3372. false
  3373. );
  3374. let processed = handleQueryResult(result2);
  3375. return isResponse(processed) ? processed : typeof processed === "string" ? new Response(processed) : Response.json(processed);
  3376. }
  3377. );
  3378. return res;
  3379. },
  3380. (error) => {
  3381. if (isDataWithResponseInit(error)) {
  3382. return Promise.resolve(dataWithResponseInitToResponse(error));
  3383. }
  3384. if (isResponse(error)) {
  3385. return Promise.resolve(error);
  3386. }
  3387. throw error;
  3388. }
  3389. );
  3390. return response;
  3391. }
  3392. let result = await queryImpl(
  3393. request,
  3394. location,
  3395. matches,
  3396. requestContext,
  3397. dataStrategy || null,
  3398. false,
  3399. match,
  3400. null,
  3401. false
  3402. );
  3403. return handleQueryResult(result);
  3404. function handleQueryResult(result2) {
  3405. if (isResponse(result2)) {
  3406. return result2;
  3407. }
  3408. let error = result2.errors ? Object.values(result2.errors)[0] : void 0;
  3409. if (error !== void 0) {
  3410. throw error;
  3411. }
  3412. if (result2.actionData) {
  3413. return Object.values(result2.actionData)[0];
  3414. }
  3415. if (result2.loaderData) {
  3416. return Object.values(result2.loaderData)[0];
  3417. }
  3418. return void 0;
  3419. }
  3420. }
  3421. async function queryImpl(request, location, matches, requestContext, dataStrategy, skipLoaderErrorBubbling, routeMatch, filterMatchesToLoad, skipRevalidation) {
  3422. invariant(
  3423. request.signal,
  3424. "query()/queryRoute() requests must contain an AbortController signal"
  3425. );
  3426. try {
  3427. if (isMutationMethod(request.method)) {
  3428. let result2 = await submit(
  3429. request,
  3430. matches,
  3431. routeMatch || getTargetMatch(matches, location),
  3432. requestContext,
  3433. dataStrategy,
  3434. skipLoaderErrorBubbling,
  3435. routeMatch != null,
  3436. filterMatchesToLoad,
  3437. skipRevalidation
  3438. );
  3439. return result2;
  3440. }
  3441. let result = await loadRouteData(
  3442. request,
  3443. matches,
  3444. requestContext,
  3445. dataStrategy,
  3446. skipLoaderErrorBubbling,
  3447. routeMatch,
  3448. filterMatchesToLoad
  3449. );
  3450. return isResponse(result) ? result : {
  3451. ...result,
  3452. actionData: null,
  3453. actionHeaders: {}
  3454. };
  3455. } catch (e) {
  3456. if (isDataStrategyResult(e) && isResponse(e.result)) {
  3457. if (e.type === "error" /* error */) {
  3458. throw e.result;
  3459. }
  3460. return e.result;
  3461. }
  3462. if (isRedirectResponse(e)) {
  3463. return e;
  3464. }
  3465. throw e;
  3466. }
  3467. }
  3468. async function submit(request, matches, actionMatch, requestContext, dataStrategy, skipLoaderErrorBubbling, isRouteRequest, filterMatchesToLoad, skipRevalidation) {
  3469. let result;
  3470. if (!actionMatch.route.action && !actionMatch.route.lazy) {
  3471. let error = getInternalRouterError(405, {
  3472. method: request.method,
  3473. pathname: new URL(request.url).pathname,
  3474. routeId: actionMatch.route.id
  3475. });
  3476. if (isRouteRequest) {
  3477. throw error;
  3478. }
  3479. result = {
  3480. type: "error" /* error */,
  3481. error
  3482. };
  3483. } else {
  3484. let dsMatches = getTargetedDataStrategyMatches(
  3485. mapRouteProperties2,
  3486. manifest,
  3487. request,
  3488. matches,
  3489. actionMatch,
  3490. [],
  3491. requestContext
  3492. );
  3493. let results = await callDataStrategy(
  3494. request,
  3495. dsMatches,
  3496. isRouteRequest,
  3497. requestContext,
  3498. dataStrategy
  3499. );
  3500. result = results[actionMatch.route.id];
  3501. if (request.signal.aborted) {
  3502. throwStaticHandlerAbortedError(request, isRouteRequest);
  3503. }
  3504. }
  3505. if (isRedirectResult(result)) {
  3506. throw new Response(null, {
  3507. status: result.response.status,
  3508. headers: {
  3509. Location: result.response.headers.get("Location")
  3510. }
  3511. });
  3512. }
  3513. if (isRouteRequest) {
  3514. if (isErrorResult(result)) {
  3515. throw result.error;
  3516. }
  3517. return {
  3518. matches: [actionMatch],
  3519. loaderData: {},
  3520. actionData: { [actionMatch.route.id]: result.data },
  3521. errors: null,
  3522. // Note: statusCode + headers are unused here since queryRoute will
  3523. // return the raw Response or value
  3524. statusCode: 200,
  3525. loaderHeaders: {},
  3526. actionHeaders: {}
  3527. };
  3528. }
  3529. if (skipRevalidation) {
  3530. if (isErrorResult(result)) {
  3531. let boundaryMatch = skipLoaderErrorBubbling ? actionMatch : findNearestBoundary(matches, actionMatch.route.id);
  3532. return {
  3533. statusCode: isRouteErrorResponse(result.error) ? result.error.status : result.statusCode != null ? result.statusCode : 500,
  3534. actionData: null,
  3535. actionHeaders: {
  3536. ...result.headers ? { [actionMatch.route.id]: result.headers } : {}
  3537. },
  3538. matches,
  3539. loaderData: {},
  3540. errors: {
  3541. [boundaryMatch.route.id]: result.error
  3542. },
  3543. loaderHeaders: {}
  3544. };
  3545. } else {
  3546. return {
  3547. actionData: {
  3548. [actionMatch.route.id]: result.data
  3549. },
  3550. actionHeaders: result.headers ? { [actionMatch.route.id]: result.headers } : {},
  3551. matches,
  3552. loaderData: {},
  3553. errors: null,
  3554. statusCode: result.statusCode || 200,
  3555. loaderHeaders: {}
  3556. };
  3557. }
  3558. }
  3559. let loaderRequest = new Request(request.url, {
  3560. headers: request.headers,
  3561. redirect: request.redirect,
  3562. signal: request.signal
  3563. });
  3564. if (isErrorResult(result)) {
  3565. let boundaryMatch = skipLoaderErrorBubbling ? actionMatch : findNearestBoundary(matches, actionMatch.route.id);
  3566. let handlerContext2 = await loadRouteData(
  3567. loaderRequest,
  3568. matches,
  3569. requestContext,
  3570. dataStrategy,
  3571. skipLoaderErrorBubbling,
  3572. null,
  3573. filterMatchesToLoad,
  3574. [boundaryMatch.route.id, result]
  3575. );
  3576. return {
  3577. ...handlerContext2,
  3578. statusCode: isRouteErrorResponse(result.error) ? result.error.status : result.statusCode != null ? result.statusCode : 500,
  3579. actionData: null,
  3580. actionHeaders: {
  3581. ...result.headers ? { [actionMatch.route.id]: result.headers } : {}
  3582. }
  3583. };
  3584. }
  3585. let handlerContext = await loadRouteData(
  3586. loaderRequest,
  3587. matches,
  3588. requestContext,
  3589. dataStrategy,
  3590. skipLoaderErrorBubbling,
  3591. null,
  3592. filterMatchesToLoad
  3593. );
  3594. return {
  3595. ...handlerContext,
  3596. actionData: {
  3597. [actionMatch.route.id]: result.data
  3598. },
  3599. // action status codes take precedence over loader status codes
  3600. ...result.statusCode ? { statusCode: result.statusCode } : {},
  3601. actionHeaders: result.headers ? { [actionMatch.route.id]: result.headers } : {}
  3602. };
  3603. }
  3604. async function loadRouteData(request, matches, requestContext, dataStrategy, skipLoaderErrorBubbling, routeMatch, filterMatchesToLoad, pendingActionResult) {
  3605. let isRouteRequest = routeMatch != null;
  3606. if (isRouteRequest && !routeMatch?.route.loader && !routeMatch?.route.lazy) {
  3607. throw getInternalRouterError(400, {
  3608. method: request.method,
  3609. pathname: new URL(request.url).pathname,
  3610. routeId: routeMatch?.route.id
  3611. });
  3612. }
  3613. let dsMatches;
  3614. if (routeMatch) {
  3615. dsMatches = getTargetedDataStrategyMatches(
  3616. mapRouteProperties2,
  3617. manifest,
  3618. request,
  3619. matches,
  3620. routeMatch,
  3621. [],
  3622. requestContext
  3623. );
  3624. } else {
  3625. let maxIdx = pendingActionResult && isErrorResult(pendingActionResult[1]) ? (
  3626. // Up to but not including the boundary
  3627. matches.findIndex((m) => m.route.id === pendingActionResult[0]) - 1
  3628. ) : void 0;
  3629. let pattern = getRoutePattern(matches);
  3630. dsMatches = matches.map((match, index) => {
  3631. if (maxIdx != null && index > maxIdx) {
  3632. return getDataStrategyMatch(
  3633. mapRouteProperties2,
  3634. manifest,
  3635. request,
  3636. pattern,
  3637. match,
  3638. [],
  3639. requestContext,
  3640. false
  3641. );
  3642. }
  3643. return getDataStrategyMatch(
  3644. mapRouteProperties2,
  3645. manifest,
  3646. request,
  3647. pattern,
  3648. match,
  3649. [],
  3650. requestContext,
  3651. (match.route.loader || match.route.lazy) != null && (!filterMatchesToLoad || filterMatchesToLoad(match))
  3652. );
  3653. });
  3654. }
  3655. if (!dataStrategy && !dsMatches.some((m) => m.shouldLoad)) {
  3656. return {
  3657. matches,
  3658. loaderData: {},
  3659. errors: pendingActionResult && isErrorResult(pendingActionResult[1]) ? {
  3660. [pendingActionResult[0]]: pendingActionResult[1].error
  3661. } : null,
  3662. statusCode: 200,
  3663. loaderHeaders: {}
  3664. };
  3665. }
  3666. let results = await callDataStrategy(
  3667. request,
  3668. dsMatches,
  3669. isRouteRequest,
  3670. requestContext,
  3671. dataStrategy
  3672. );
  3673. if (request.signal.aborted) {
  3674. throwStaticHandlerAbortedError(request, isRouteRequest);
  3675. }
  3676. let handlerContext = processRouteLoaderData(
  3677. matches,
  3678. results,
  3679. pendingActionResult,
  3680. true,
  3681. skipLoaderErrorBubbling
  3682. );
  3683. return {
  3684. ...handlerContext,
  3685. matches
  3686. };
  3687. }
  3688. async function callDataStrategy(request, matches, isRouteRequest, requestContext, dataStrategy) {
  3689. let results = await callDataStrategyImpl(
  3690. dataStrategy || defaultDataStrategy,
  3691. request,
  3692. matches,
  3693. null,
  3694. requestContext,
  3695. true
  3696. );
  3697. let dataResults = {};
  3698. await Promise.all(
  3699. matches.map(async (match) => {
  3700. if (!(match.route.id in results)) {
  3701. return;
  3702. }
  3703. let result = results[match.route.id];
  3704. if (isRedirectDataStrategyResult(result)) {
  3705. let response = result.result;
  3706. throw normalizeRelativeRoutingRedirectResponse(
  3707. response,
  3708. request,
  3709. match.route.id,
  3710. matches,
  3711. basename
  3712. );
  3713. }
  3714. if (isRouteRequest) {
  3715. if (isResponse(result.result)) {
  3716. throw result;
  3717. } else if (isDataWithResponseInit(result.result)) {
  3718. throw dataWithResponseInitToResponse(result.result);
  3719. }
  3720. }
  3721. dataResults[match.route.id] = await convertDataStrategyResultToDataResult(result);
  3722. })
  3723. );
  3724. return dataResults;
  3725. }
  3726. return {
  3727. dataRoutes,
  3728. query,
  3729. queryRoute
  3730. };
  3731. }
  3732. function getStaticContextFromError(routes, handlerContext, error, boundaryId) {
  3733. let errorBoundaryId = boundaryId || handlerContext._deepestRenderedBoundaryId || routes[0].id;
  3734. return {
  3735. ...handlerContext,
  3736. statusCode: isRouteErrorResponse(error) ? error.status : 500,
  3737. errors: {
  3738. [errorBoundaryId]: error
  3739. }
  3740. };
  3741. }
  3742. function throwStaticHandlerAbortedError(request, isRouteRequest) {
  3743. if (request.signal.reason !== void 0) {
  3744. throw request.signal.reason;
  3745. }
  3746. let method = isRouteRequest ? "queryRoute" : "query";
  3747. throw new Error(
  3748. `${method}() call aborted without an \`AbortSignal.reason\`: ${request.method} ${request.url}`
  3749. );
  3750. }
  3751. function isSubmissionNavigation(opts) {
  3752. return opts != null && ("formData" in opts && opts.formData != null || "body" in opts && opts.body !== void 0);
  3753. }
  3754. function normalizeTo(location, matches, basename, to, fromRouteId, relative) {
  3755. let contextualMatches;
  3756. let activeRouteMatch;
  3757. if (fromRouteId) {
  3758. contextualMatches = [];
  3759. for (let match of matches) {
  3760. contextualMatches.push(match);
  3761. if (match.route.id === fromRouteId) {
  3762. activeRouteMatch = match;
  3763. break;
  3764. }
  3765. }
  3766. } else {
  3767. contextualMatches = matches;
  3768. activeRouteMatch = matches[matches.length - 1];
  3769. }
  3770. let path = resolveTo(
  3771. to ? to : ".",
  3772. getResolveToMatches(contextualMatches),
  3773. stripBasename(location.pathname, basename) || location.pathname,
  3774. relative === "path"
  3775. );
  3776. if (to == null) {
  3777. path.search = location.search;
  3778. path.hash = location.hash;
  3779. }
  3780. if ((to == null || to === "" || to === ".") && activeRouteMatch) {
  3781. let nakedIndex = hasNakedIndexQuery(path.search);
  3782. if (activeRouteMatch.route.index && !nakedIndex) {
  3783. path.search = path.search ? path.search.replace(/^\?/, "?index&") : "?index";
  3784. } else if (!activeRouteMatch.route.index && nakedIndex) {
  3785. let params = new URLSearchParams(path.search);
  3786. let indexValues = params.getAll("index");
  3787. params.delete("index");
  3788. indexValues.filter((v) => v).forEach((v) => params.append("index", v));
  3789. let qs = params.toString();
  3790. path.search = qs ? `?${qs}` : "";
  3791. }
  3792. }
  3793. if (basename !== "/") {
  3794. path.pathname = prependBasename({ basename, pathname: path.pathname });
  3795. }
  3796. return createPath(path);
  3797. }
  3798. function normalizeNavigateOptions(isFetcher, path, opts) {
  3799. if (!opts || !isSubmissionNavigation(opts)) {
  3800. return { path };
  3801. }
  3802. if (opts.formMethod && !isValidMethod(opts.formMethod)) {
  3803. return {
  3804. path,
  3805. error: getInternalRouterError(405, { method: opts.formMethod })
  3806. };
  3807. }
  3808. let getInvalidBodyError = () => ({
  3809. path,
  3810. error: getInternalRouterError(400, { type: "invalid-body" })
  3811. });
  3812. let rawFormMethod = opts.formMethod || "get";
  3813. let formMethod = rawFormMethod.toUpperCase();
  3814. let formAction = stripHashFromPath(path);
  3815. if (opts.body !== void 0) {
  3816. if (opts.formEncType === "text/plain") {
  3817. if (!isMutationMethod(formMethod)) {
  3818. return getInvalidBodyError();
  3819. }
  3820. let text = typeof opts.body === "string" ? opts.body : opts.body instanceof FormData || opts.body instanceof URLSearchParams ? (
  3821. // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#plain-text-form-data
  3822. Array.from(opts.body.entries()).reduce(
  3823. (acc, [name, value]) => `${acc}${name}=${value}
  3824. `,
  3825. ""
  3826. )
  3827. ) : String(opts.body);
  3828. return {
  3829. path,
  3830. submission: {
  3831. formMethod,
  3832. formAction,
  3833. formEncType: opts.formEncType,
  3834. formData: void 0,
  3835. json: void 0,
  3836. text
  3837. }
  3838. };
  3839. } else if (opts.formEncType === "application/json") {
  3840. if (!isMutationMethod(formMethod)) {
  3841. return getInvalidBodyError();
  3842. }
  3843. try {
  3844. let json = typeof opts.body === "string" ? JSON.parse(opts.body) : opts.body;
  3845. return {
  3846. path,
  3847. submission: {
  3848. formMethod,
  3849. formAction,
  3850. formEncType: opts.formEncType,
  3851. formData: void 0,
  3852. json,
  3853. text: void 0
  3854. }
  3855. };
  3856. } catch (e) {
  3857. return getInvalidBodyError();
  3858. }
  3859. }
  3860. }
  3861. invariant(
  3862. typeof FormData === "function",
  3863. "FormData is not available in this environment"
  3864. );
  3865. let searchParams;
  3866. let formData;
  3867. if (opts.formData) {
  3868. searchParams = convertFormDataToSearchParams(opts.formData);
  3869. formData = opts.formData;
  3870. } else if (opts.body instanceof FormData) {
  3871. searchParams = convertFormDataToSearchParams(opts.body);
  3872. formData = opts.body;
  3873. } else if (opts.body instanceof URLSearchParams) {
  3874. searchParams = opts.body;
  3875. formData = convertSearchParamsToFormData(searchParams);
  3876. } else if (opts.body == null) {
  3877. searchParams = new URLSearchParams();
  3878. formData = new FormData();
  3879. } else {
  3880. try {
  3881. searchParams = new URLSearchParams(opts.body);
  3882. formData = convertSearchParamsToFormData(searchParams);
  3883. } catch (e) {
  3884. return getInvalidBodyError();
  3885. }
  3886. }
  3887. let submission = {
  3888. formMethod,
  3889. formAction,
  3890. formEncType: opts && opts.formEncType || "application/x-www-form-urlencoded",
  3891. formData,
  3892. json: void 0,
  3893. text: void 0
  3894. };
  3895. if (isMutationMethod(submission.formMethod)) {
  3896. return { path, submission };
  3897. }
  3898. let parsedPath = parsePath(path);
  3899. if (isFetcher && parsedPath.search && hasNakedIndexQuery(parsedPath.search)) {
  3900. searchParams.append("index", "");
  3901. }
  3902. parsedPath.search = `?${searchParams}`;
  3903. return { path: createPath(parsedPath), submission };
  3904. }
  3905. function getMatchesToLoad(request, scopedContext, mapRouteProperties2, manifest, history, state, matches, submission, location, lazyRoutePropertiesToSkip, initialHydration, isRevalidationRequired, cancelledFetcherLoads, fetchersQueuedForDeletion, fetchLoadMatches, fetchRedirectIds, routesToUse, basename, hasPatchRoutesOnNavigation, pendingActionResult) {
  3906. let actionResult = pendingActionResult ? isErrorResult(pendingActionResult[1]) ? pendingActionResult[1].error : pendingActionResult[1].data : void 0;
  3907. let currentUrl = history.createURL(state.location);
  3908. let nextUrl = history.createURL(location);
  3909. let maxIdx;
  3910. if (initialHydration && state.errors) {
  3911. let boundaryId = Object.keys(state.errors)[0];
  3912. maxIdx = matches.findIndex((m) => m.route.id === boundaryId);
  3913. } else if (pendingActionResult && isErrorResult(pendingActionResult[1])) {
  3914. let boundaryId = pendingActionResult[0];
  3915. maxIdx = matches.findIndex((m) => m.route.id === boundaryId) - 1;
  3916. }
  3917. let actionStatus = pendingActionResult ? pendingActionResult[1].statusCode : void 0;
  3918. let shouldSkipRevalidation = actionStatus && actionStatus >= 400;
  3919. let baseShouldRevalidateArgs = {
  3920. currentUrl,
  3921. currentParams: state.matches[0]?.params || {},
  3922. nextUrl,
  3923. nextParams: matches[0].params,
  3924. ...submission,
  3925. actionResult,
  3926. actionStatus
  3927. };
  3928. let pattern = getRoutePattern(matches);
  3929. let dsMatches = matches.map((match, index) => {
  3930. let { route } = match;
  3931. let forceShouldLoad = null;
  3932. if (maxIdx != null && index > maxIdx) {
  3933. forceShouldLoad = false;
  3934. } else if (route.lazy) {
  3935. forceShouldLoad = true;
  3936. } else if (!routeHasLoaderOrMiddleware(route)) {
  3937. forceShouldLoad = false;
  3938. } else if (initialHydration) {
  3939. forceShouldLoad = shouldLoadRouteOnHydration(
  3940. route,
  3941. state.loaderData,
  3942. state.errors
  3943. );
  3944. } else if (isNewLoader(state.loaderData, state.matches[index], match)) {
  3945. forceShouldLoad = true;
  3946. }
  3947. if (forceShouldLoad !== null) {
  3948. return getDataStrategyMatch(
  3949. mapRouteProperties2,
  3950. manifest,
  3951. request,
  3952. pattern,
  3953. match,
  3954. lazyRoutePropertiesToSkip,
  3955. scopedContext,
  3956. forceShouldLoad
  3957. );
  3958. }
  3959. let defaultShouldRevalidate = shouldSkipRevalidation ? false : (
  3960. // Forced revalidation due to submission, useRevalidator, or X-Remix-Revalidate
  3961. isRevalidationRequired || currentUrl.pathname + currentUrl.search === nextUrl.pathname + nextUrl.search || // Search params affect all loaders
  3962. currentUrl.search !== nextUrl.search || isNewRouteInstance(state.matches[index], match)
  3963. );
  3964. let shouldRevalidateArgs = {
  3965. ...baseShouldRevalidateArgs,
  3966. defaultShouldRevalidate
  3967. };
  3968. let shouldLoad = shouldRevalidateLoader(match, shouldRevalidateArgs);
  3969. return getDataStrategyMatch(
  3970. mapRouteProperties2,
  3971. manifest,
  3972. request,
  3973. pattern,
  3974. match,
  3975. lazyRoutePropertiesToSkip,
  3976. scopedContext,
  3977. shouldLoad,
  3978. shouldRevalidateArgs
  3979. );
  3980. });
  3981. let revalidatingFetchers = [];
  3982. fetchLoadMatches.forEach((f, key) => {
  3983. if (initialHydration || !matches.some((m) => m.route.id === f.routeId) || fetchersQueuedForDeletion.has(key)) {
  3984. return;
  3985. }
  3986. let fetcher = state.fetchers.get(key);
  3987. let isMidInitialLoad = fetcher && fetcher.state !== "idle" && fetcher.data === void 0;
  3988. let fetcherMatches = matchRoutes(routesToUse, f.path, basename);
  3989. if (!fetcherMatches) {
  3990. if (hasPatchRoutesOnNavigation && isMidInitialLoad) {
  3991. return;
  3992. }
  3993. revalidatingFetchers.push({
  3994. key,
  3995. routeId: f.routeId,
  3996. path: f.path,
  3997. matches: null,
  3998. match: null,
  3999. request: null,
  4000. controller: null
  4001. });
  4002. return;
  4003. }
  4004. if (fetchRedirectIds.has(key)) {
  4005. return;
  4006. }
  4007. let fetcherMatch = getTargetMatch(fetcherMatches, f.path);
  4008. let fetchController = new AbortController();
  4009. let fetchRequest = createClientSideRequest(
  4010. history,
  4011. f.path,
  4012. fetchController.signal
  4013. );
  4014. let fetcherDsMatches = null;
  4015. if (cancelledFetcherLoads.has(key)) {
  4016. cancelledFetcherLoads.delete(key);
  4017. fetcherDsMatches = getTargetedDataStrategyMatches(
  4018. mapRouteProperties2,
  4019. manifest,
  4020. fetchRequest,
  4021. fetcherMatches,
  4022. fetcherMatch,
  4023. lazyRoutePropertiesToSkip,
  4024. scopedContext
  4025. );
  4026. } else if (isMidInitialLoad) {
  4027. if (isRevalidationRequired) {
  4028. fetcherDsMatches = getTargetedDataStrategyMatches(
  4029. mapRouteProperties2,
  4030. manifest,
  4031. fetchRequest,
  4032. fetcherMatches,
  4033. fetcherMatch,
  4034. lazyRoutePropertiesToSkip,
  4035. scopedContext
  4036. );
  4037. }
  4038. } else {
  4039. let shouldRevalidateArgs = {
  4040. ...baseShouldRevalidateArgs,
  4041. defaultShouldRevalidate: shouldSkipRevalidation ? false : isRevalidationRequired
  4042. };
  4043. if (shouldRevalidateLoader(fetcherMatch, shouldRevalidateArgs)) {
  4044. fetcherDsMatches = getTargetedDataStrategyMatches(
  4045. mapRouteProperties2,
  4046. manifest,
  4047. fetchRequest,
  4048. fetcherMatches,
  4049. fetcherMatch,
  4050. lazyRoutePropertiesToSkip,
  4051. scopedContext,
  4052. shouldRevalidateArgs
  4053. );
  4054. }
  4055. }
  4056. if (fetcherDsMatches) {
  4057. revalidatingFetchers.push({
  4058. key,
  4059. routeId: f.routeId,
  4060. path: f.path,
  4061. matches: fetcherDsMatches,
  4062. match: fetcherMatch,
  4063. request: fetchRequest,
  4064. controller: fetchController
  4065. });
  4066. }
  4067. });
  4068. return { dsMatches, revalidatingFetchers };
  4069. }
  4070. function routeHasLoaderOrMiddleware(route) {
  4071. return route.loader != null || route.middleware != null && route.middleware.length > 0;
  4072. }
  4073. function shouldLoadRouteOnHydration(route, loaderData, errors) {
  4074. if (route.lazy) {
  4075. return true;
  4076. }
  4077. if (!routeHasLoaderOrMiddleware(route)) {
  4078. return false;
  4079. }
  4080. let hasData = loaderData != null && route.id in loaderData;
  4081. let hasError = errors != null && errors[route.id] !== void 0;
  4082. if (!hasData && hasError) {
  4083. return false;
  4084. }
  4085. if (typeof route.loader === "function" && route.loader.hydrate === true) {
  4086. return true;
  4087. }
  4088. return !hasData && !hasError;
  4089. }
  4090. function isNewLoader(currentLoaderData, currentMatch, match) {
  4091. let isNew = (
  4092. // [a] -> [a, b]
  4093. !currentMatch || // [a, b] -> [a, c]
  4094. match.route.id !== currentMatch.route.id
  4095. );
  4096. let isMissingData = !currentLoaderData.hasOwnProperty(match.route.id);
  4097. return isNew || isMissingData;
  4098. }
  4099. function isNewRouteInstance(currentMatch, match) {
  4100. let currentPath = currentMatch.route.path;
  4101. return (
  4102. // param change for this match, /users/123 -> /users/456
  4103. currentMatch.pathname !== match.pathname || // splat param changed, which is not present in match.path
  4104. // e.g. /files/images/avatar.jpg -> files/finances.xls
  4105. currentPath != null && currentPath.endsWith("*") && currentMatch.params["*"] !== match.params["*"]
  4106. );
  4107. }
  4108. function shouldRevalidateLoader(loaderMatch, arg) {
  4109. if (loaderMatch.route.shouldRevalidate) {
  4110. let routeChoice = loaderMatch.route.shouldRevalidate(arg);
  4111. if (typeof routeChoice === "boolean") {
  4112. return routeChoice;
  4113. }
  4114. }
  4115. return arg.defaultShouldRevalidate;
  4116. }
  4117. function patchRoutesImpl(routeId, children, routesToUse, manifest, mapRouteProperties2, allowElementMutations) {
  4118. let childrenToPatch;
  4119. if (routeId) {
  4120. let route = manifest[routeId];
  4121. invariant(
  4122. route,
  4123. `No route found to patch children into: routeId = ${routeId}`
  4124. );
  4125. if (!route.children) {
  4126. route.children = [];
  4127. }
  4128. childrenToPatch = route.children;
  4129. } else {
  4130. childrenToPatch = routesToUse;
  4131. }
  4132. let uniqueChildren = [];
  4133. let existingChildren = [];
  4134. children.forEach((newRoute) => {
  4135. let existingRoute = childrenToPatch.find(
  4136. (existingRoute2) => isSameRoute(newRoute, existingRoute2)
  4137. );
  4138. if (existingRoute) {
  4139. existingChildren.push({ existingRoute, newRoute });
  4140. } else {
  4141. uniqueChildren.push(newRoute);
  4142. }
  4143. });
  4144. if (uniqueChildren.length > 0) {
  4145. let newRoutes = convertRoutesToDataRoutes(
  4146. uniqueChildren,
  4147. mapRouteProperties2,
  4148. [routeId || "_", "patch", String(childrenToPatch?.length || "0")],
  4149. manifest
  4150. );
  4151. childrenToPatch.push(...newRoutes);
  4152. }
  4153. if (allowElementMutations && existingChildren.length > 0) {
  4154. for (let i = 0; i < existingChildren.length; i++) {
  4155. let { existingRoute, newRoute } = existingChildren[i];
  4156. let existingRouteTyped = existingRoute;
  4157. let [newRouteTyped] = convertRoutesToDataRoutes(
  4158. [newRoute],
  4159. mapRouteProperties2,
  4160. [],
  4161. // Doesn't matter for mutated routes since they already have an id
  4162. {},
  4163. // Don't touch the manifest here since we're updating in place
  4164. true
  4165. );
  4166. Object.assign(existingRouteTyped, {
  4167. element: newRouteTyped.element ? newRouteTyped.element : existingRouteTyped.element,
  4168. errorElement: newRouteTyped.errorElement ? newRouteTyped.errorElement : existingRouteTyped.errorElement,
  4169. hydrateFallbackElement: newRouteTyped.hydrateFallbackElement ? newRouteTyped.hydrateFallbackElement : existingRouteTyped.hydrateFallbackElement
  4170. });
  4171. }
  4172. }
  4173. }
  4174. function isSameRoute(newRoute, existingRoute) {
  4175. if ("id" in newRoute && "id" in existingRoute && newRoute.id === existingRoute.id) {
  4176. return true;
  4177. }
  4178. if (!(newRoute.index === existingRoute.index && newRoute.path === existingRoute.path && newRoute.caseSensitive === existingRoute.caseSensitive)) {
  4179. return false;
  4180. }
  4181. if ((!newRoute.children || newRoute.children.length === 0) && (!existingRoute.children || existingRoute.children.length === 0)) {
  4182. return true;
  4183. }
  4184. return newRoute.children.every(
  4185. (aChild, i) => existingRoute.children?.some((bChild) => isSameRoute(aChild, bChild))
  4186. );
  4187. }
  4188. var lazyRoutePropertyCache = /* @__PURE__ */ new WeakMap();
  4189. var loadLazyRouteProperty = ({
  4190. key,
  4191. route,
  4192. manifest,
  4193. mapRouteProperties: mapRouteProperties2
  4194. }) => {
  4195. let routeToUpdate = manifest[route.id];
  4196. invariant(routeToUpdate, "No route found in manifest");
  4197. if (!routeToUpdate.lazy || typeof routeToUpdate.lazy !== "object") {
  4198. return;
  4199. }
  4200. let lazyFn = routeToUpdate.lazy[key];
  4201. if (!lazyFn) {
  4202. return;
  4203. }
  4204. let cache = lazyRoutePropertyCache.get(routeToUpdate);
  4205. if (!cache) {
  4206. cache = {};
  4207. lazyRoutePropertyCache.set(routeToUpdate, cache);
  4208. }
  4209. let cachedPromise = cache[key];
  4210. if (cachedPromise) {
  4211. return cachedPromise;
  4212. }
  4213. let propertyPromise = (async () => {
  4214. let isUnsupported = isUnsupportedLazyRouteObjectKey(key);
  4215. let staticRouteValue = routeToUpdate[key];
  4216. let isStaticallyDefined = staticRouteValue !== void 0 && key !== "hasErrorBoundary";
  4217. if (isUnsupported) {
  4218. warning(
  4219. !isUnsupported,
  4220. "Route property " + key + " is not a supported lazy route property. This property will be ignored."
  4221. );
  4222. cache[key] = Promise.resolve();
  4223. } else if (isStaticallyDefined) {
  4224. warning(
  4225. false,
  4226. `Route "${routeToUpdate.id}" has a static property "${key}" defined. The lazy property will be ignored.`
  4227. );
  4228. } else {
  4229. let value = await lazyFn();
  4230. if (value != null) {
  4231. Object.assign(routeToUpdate, { [key]: value });
  4232. Object.assign(routeToUpdate, mapRouteProperties2(routeToUpdate));
  4233. }
  4234. }
  4235. if (typeof routeToUpdate.lazy === "object") {
  4236. routeToUpdate.lazy[key] = void 0;
  4237. if (Object.values(routeToUpdate.lazy).every((value) => value === void 0)) {
  4238. routeToUpdate.lazy = void 0;
  4239. }
  4240. }
  4241. })();
  4242. cache[key] = propertyPromise;
  4243. return propertyPromise;
  4244. };
  4245. var lazyRouteFunctionCache = /* @__PURE__ */ new WeakMap();
  4246. function loadLazyRoute(route, type, manifest, mapRouteProperties2, lazyRoutePropertiesToSkip) {
  4247. let routeToUpdate = manifest[route.id];
  4248. invariant(routeToUpdate, "No route found in manifest");
  4249. if (!route.lazy) {
  4250. return {
  4251. lazyRoutePromise: void 0,
  4252. lazyHandlerPromise: void 0
  4253. };
  4254. }
  4255. if (typeof route.lazy === "function") {
  4256. let cachedPromise = lazyRouteFunctionCache.get(routeToUpdate);
  4257. if (cachedPromise) {
  4258. return {
  4259. lazyRoutePromise: cachedPromise,
  4260. lazyHandlerPromise: cachedPromise
  4261. };
  4262. }
  4263. let lazyRoutePromise2 = (async () => {
  4264. invariant(
  4265. typeof route.lazy === "function",
  4266. "No lazy route function found"
  4267. );
  4268. let lazyRoute = await route.lazy();
  4269. let routeUpdates = {};
  4270. for (let lazyRouteProperty in lazyRoute) {
  4271. let lazyValue = lazyRoute[lazyRouteProperty];
  4272. if (lazyValue === void 0) {
  4273. continue;
  4274. }
  4275. let isUnsupported = isUnsupportedLazyRouteFunctionKey(lazyRouteProperty);
  4276. let staticRouteValue = routeToUpdate[lazyRouteProperty];
  4277. let isStaticallyDefined = staticRouteValue !== void 0 && // This property isn't static since it should always be updated based
  4278. // on the route updates
  4279. lazyRouteProperty !== "hasErrorBoundary";
  4280. if (isUnsupported) {
  4281. warning(
  4282. !isUnsupported,
  4283. "Route property " + lazyRouteProperty + " is not a supported property to be returned from a lazy route function. This property will be ignored."
  4284. );
  4285. } else if (isStaticallyDefined) {
  4286. warning(
  4287. !isStaticallyDefined,
  4288. `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.`
  4289. );
  4290. } else {
  4291. routeUpdates[lazyRouteProperty] = lazyValue;
  4292. }
  4293. }
  4294. Object.assign(routeToUpdate, routeUpdates);
  4295. Object.assign(routeToUpdate, {
  4296. // To keep things framework agnostic, we use the provided `mapRouteProperties`
  4297. // function to set the framework-aware properties (`element`/`hasErrorBoundary`)
  4298. // since the logic will differ between frameworks.
  4299. ...mapRouteProperties2(routeToUpdate),
  4300. lazy: void 0
  4301. });
  4302. })();
  4303. lazyRouteFunctionCache.set(routeToUpdate, lazyRoutePromise2);
  4304. lazyRoutePromise2.catch(() => {
  4305. });
  4306. return {
  4307. lazyRoutePromise: lazyRoutePromise2,
  4308. lazyHandlerPromise: lazyRoutePromise2
  4309. };
  4310. }
  4311. let lazyKeys = Object.keys(route.lazy);
  4312. let lazyPropertyPromises = [];
  4313. let lazyHandlerPromise = void 0;
  4314. for (let key of lazyKeys) {
  4315. if (lazyRoutePropertiesToSkip && lazyRoutePropertiesToSkip.includes(key)) {
  4316. continue;
  4317. }
  4318. let promise = loadLazyRouteProperty({
  4319. key,
  4320. route,
  4321. manifest,
  4322. mapRouteProperties: mapRouteProperties2
  4323. });
  4324. if (promise) {
  4325. lazyPropertyPromises.push(promise);
  4326. if (key === type) {
  4327. lazyHandlerPromise = promise;
  4328. }
  4329. }
  4330. }
  4331. let lazyRoutePromise = lazyPropertyPromises.length > 0 ? Promise.all(lazyPropertyPromises).then(() => {
  4332. }) : void 0;
  4333. lazyRoutePromise?.catch(() => {
  4334. });
  4335. lazyHandlerPromise?.catch(() => {
  4336. });
  4337. return {
  4338. lazyRoutePromise,
  4339. lazyHandlerPromise
  4340. };
  4341. }
  4342. function isNonNullable(value) {
  4343. return value !== void 0;
  4344. }
  4345. function loadLazyMiddlewareForMatches(matches, manifest, mapRouteProperties2) {
  4346. let promises = matches.map(({ route }) => {
  4347. if (typeof route.lazy !== "object" || !route.lazy.middleware) {
  4348. return void 0;
  4349. }
  4350. return loadLazyRouteProperty({
  4351. key: "middleware",
  4352. route,
  4353. manifest,
  4354. mapRouteProperties: mapRouteProperties2
  4355. });
  4356. }).filter(isNonNullable);
  4357. return promises.length > 0 ? Promise.all(promises) : void 0;
  4358. }
  4359. async function defaultDataStrategy(args) {
  4360. let matchesToLoad = args.matches.filter((m) => m.shouldLoad);
  4361. let keyedResults = {};
  4362. let results = await Promise.all(matchesToLoad.map((m) => m.resolve()));
  4363. results.forEach((result, i) => {
  4364. keyedResults[matchesToLoad[i].route.id] = result;
  4365. });
  4366. return keyedResults;
  4367. }
  4368. async function defaultDataStrategyWithMiddleware(args) {
  4369. if (!args.matches.some((m) => m.route.middleware)) {
  4370. return defaultDataStrategy(args);
  4371. }
  4372. return runClientMiddlewarePipeline(args, () => defaultDataStrategy(args));
  4373. }
  4374. function runServerMiddlewarePipeline(args, handler, errorHandler) {
  4375. return runMiddlewarePipeline(
  4376. args,
  4377. handler,
  4378. processResult,
  4379. isResponse,
  4380. errorHandler
  4381. );
  4382. function processResult(result) {
  4383. return isDataWithResponseInit(result) ? dataWithResponseInitToResponse(result) : result;
  4384. }
  4385. }
  4386. function runClientMiddlewarePipeline(args, handler) {
  4387. return runMiddlewarePipeline(
  4388. args,
  4389. handler,
  4390. (r) => r,
  4391. // No post-processing needed on the client
  4392. isDataStrategyResults,
  4393. errorHandler
  4394. );
  4395. function errorHandler(error, routeId, nextResult) {
  4396. if (nextResult) {
  4397. return Promise.resolve(
  4398. Object.assign(nextResult.value, {
  4399. [routeId]: { type: "error", result: error }
  4400. })
  4401. );
  4402. } else {
  4403. let { matches } = args;
  4404. let maxBoundaryIdx = Math.min(
  4405. // Throwing route
  4406. Math.max(
  4407. matches.findIndex((m) => m.route.id === routeId),
  4408. 0
  4409. ),
  4410. // or the shallowest route that needs to load data
  4411. Math.max(
  4412. matches.findIndex((m) => m.shouldCallHandler()),
  4413. 0
  4414. )
  4415. );
  4416. let boundaryRouteId = findNearestBoundary(
  4417. matches,
  4418. matches[maxBoundaryIdx].route.id
  4419. ).route.id;
  4420. return Promise.resolve({
  4421. [boundaryRouteId]: { type: "error", result: error }
  4422. });
  4423. }
  4424. }
  4425. }
  4426. async function runMiddlewarePipeline(args, handler, processResult, isResult, errorHandler) {
  4427. let { matches, request, params, context, unstable_pattern } = args;
  4428. let tuples = matches.flatMap(
  4429. (m) => m.route.middleware ? m.route.middleware.map((fn) => [m.route.id, fn]) : []
  4430. );
  4431. let result = await callRouteMiddleware(
  4432. {
  4433. request,
  4434. params,
  4435. context,
  4436. unstable_pattern
  4437. },
  4438. tuples,
  4439. handler,
  4440. processResult,
  4441. isResult,
  4442. errorHandler
  4443. );
  4444. return result;
  4445. }
  4446. async function callRouteMiddleware(args, middlewares, handler, processResult, isResult, errorHandler, idx = 0) {
  4447. let { request } = args;
  4448. if (request.signal.aborted) {
  4449. throw request.signal.reason ?? new Error(`Request aborted: ${request.method} ${request.url}`);
  4450. }
  4451. let tuple = middlewares[idx];
  4452. if (!tuple) {
  4453. let result = await handler();
  4454. return result;
  4455. }
  4456. let [routeId, middleware] = tuple;
  4457. let nextResult;
  4458. let next = async () => {
  4459. if (nextResult) {
  4460. throw new Error("You may only call `next()` once per middleware");
  4461. }
  4462. try {
  4463. let result = await callRouteMiddleware(
  4464. args,
  4465. middlewares,
  4466. handler,
  4467. processResult,
  4468. isResult,
  4469. errorHandler,
  4470. idx + 1
  4471. );
  4472. nextResult = { value: result };
  4473. return nextResult.value;
  4474. } catch (error) {
  4475. nextResult = { value: await errorHandler(error, routeId, nextResult) };
  4476. return nextResult.value;
  4477. }
  4478. };
  4479. try {
  4480. let value = await middleware(args, next);
  4481. let result = value != null ? processResult(value) : void 0;
  4482. if (isResult(result)) {
  4483. return result;
  4484. } else if (nextResult) {
  4485. return result ?? nextResult.value;
  4486. } else {
  4487. nextResult = { value: await next() };
  4488. return nextResult.value;
  4489. }
  4490. } catch (error) {
  4491. let response = await errorHandler(error, routeId, nextResult);
  4492. return response;
  4493. }
  4494. }
  4495. function getDataStrategyMatchLazyPromises(mapRouteProperties2, manifest, request, match, lazyRoutePropertiesToSkip) {
  4496. let lazyMiddlewarePromise = loadLazyRouteProperty({
  4497. key: "middleware",
  4498. route: match.route,
  4499. manifest,
  4500. mapRouteProperties: mapRouteProperties2
  4501. });
  4502. let lazyRoutePromises = loadLazyRoute(
  4503. match.route,
  4504. isMutationMethod(request.method) ? "action" : "loader",
  4505. manifest,
  4506. mapRouteProperties2,
  4507. lazyRoutePropertiesToSkip
  4508. );
  4509. return {
  4510. middleware: lazyMiddlewarePromise,
  4511. route: lazyRoutePromises.lazyRoutePromise,
  4512. handler: lazyRoutePromises.lazyHandlerPromise
  4513. };
  4514. }
  4515. function getDataStrategyMatch(mapRouteProperties2, manifest, request, unstable_pattern, match, lazyRoutePropertiesToSkip, scopedContext, shouldLoad, shouldRevalidateArgs = null) {
  4516. let isUsingNewApi = false;
  4517. let _lazyPromises = getDataStrategyMatchLazyPromises(
  4518. mapRouteProperties2,
  4519. manifest,
  4520. request,
  4521. match,
  4522. lazyRoutePropertiesToSkip
  4523. );
  4524. return {
  4525. ...match,
  4526. _lazyPromises,
  4527. shouldLoad,
  4528. shouldRevalidateArgs,
  4529. shouldCallHandler(defaultShouldRevalidate) {
  4530. isUsingNewApi = true;
  4531. if (!shouldRevalidateArgs) {
  4532. return shouldLoad;
  4533. }
  4534. if (typeof defaultShouldRevalidate === "boolean") {
  4535. return shouldRevalidateLoader(match, {
  4536. ...shouldRevalidateArgs,
  4537. defaultShouldRevalidate
  4538. });
  4539. }
  4540. return shouldRevalidateLoader(match, shouldRevalidateArgs);
  4541. },
  4542. resolve(handlerOverride) {
  4543. let { lazy, loader, middleware } = match.route;
  4544. let callHandler = isUsingNewApi || shouldLoad || handlerOverride && !isMutationMethod(request.method) && (lazy || loader);
  4545. let isMiddlewareOnlyRoute = middleware && middleware.length > 0 && !loader && !lazy;
  4546. if (callHandler && (isMutationMethod(request.method) || !isMiddlewareOnlyRoute)) {
  4547. return callLoaderOrAction({
  4548. request,
  4549. unstable_pattern,
  4550. match,
  4551. lazyHandlerPromise: _lazyPromises?.handler,
  4552. lazyRoutePromise: _lazyPromises?.route,
  4553. handlerOverride,
  4554. scopedContext
  4555. });
  4556. }
  4557. return Promise.resolve({ type: "data" /* data */, result: void 0 });
  4558. }
  4559. };
  4560. }
  4561. function getTargetedDataStrategyMatches(mapRouteProperties2, manifest, request, matches, targetMatch, lazyRoutePropertiesToSkip, scopedContext, shouldRevalidateArgs = null) {
  4562. return matches.map((match) => {
  4563. if (match.route.id !== targetMatch.route.id) {
  4564. return {
  4565. ...match,
  4566. shouldLoad: false,
  4567. shouldRevalidateArgs,
  4568. shouldCallHandler: () => false,
  4569. _lazyPromises: getDataStrategyMatchLazyPromises(
  4570. mapRouteProperties2,
  4571. manifest,
  4572. request,
  4573. match,
  4574. lazyRoutePropertiesToSkip
  4575. ),
  4576. resolve: () => Promise.resolve({ type: "data", result: void 0 })
  4577. };
  4578. }
  4579. return getDataStrategyMatch(
  4580. mapRouteProperties2,
  4581. manifest,
  4582. request,
  4583. getRoutePattern(matches),
  4584. match,
  4585. lazyRoutePropertiesToSkip,
  4586. scopedContext,
  4587. true,
  4588. shouldRevalidateArgs
  4589. );
  4590. });
  4591. }
  4592. async function callDataStrategyImpl(dataStrategyImpl, request, matches, fetcherKey, scopedContext, isStaticHandler) {
  4593. if (matches.some((m) => m._lazyPromises?.middleware)) {
  4594. await Promise.all(matches.map((m) => m._lazyPromises?.middleware));
  4595. }
  4596. let dataStrategyArgs = {
  4597. request,
  4598. unstable_pattern: getRoutePattern(matches),
  4599. params: matches[0].params,
  4600. context: scopedContext,
  4601. matches
  4602. };
  4603. let runClientMiddleware = isStaticHandler ? () => {
  4604. throw new Error(
  4605. "You cannot call `runClientMiddleware()` from a static handler `dataStrategy`. Middleware is run outside of `dataStrategy` during SSR in order to bubble up the Response. You can enable middleware via the `respond` API in `query`/`queryRoute`"
  4606. );
  4607. } : (cb) => {
  4608. let typedDataStrategyArgs = dataStrategyArgs;
  4609. return runClientMiddlewarePipeline(typedDataStrategyArgs, () => {
  4610. return cb({
  4611. ...typedDataStrategyArgs,
  4612. fetcherKey,
  4613. runClientMiddleware: () => {
  4614. throw new Error(
  4615. "Cannot call `runClientMiddleware()` from within an `runClientMiddleware` handler"
  4616. );
  4617. }
  4618. });
  4619. });
  4620. };
  4621. let results = await dataStrategyImpl({
  4622. ...dataStrategyArgs,
  4623. fetcherKey,
  4624. runClientMiddleware
  4625. });
  4626. try {
  4627. await Promise.all(
  4628. matches.flatMap((m) => [
  4629. m._lazyPromises?.handler,
  4630. m._lazyPromises?.route
  4631. ])
  4632. );
  4633. } catch (e) {
  4634. }
  4635. return results;
  4636. }
  4637. async function callLoaderOrAction({
  4638. request,
  4639. unstable_pattern,
  4640. match,
  4641. lazyHandlerPromise,
  4642. lazyRoutePromise,
  4643. handlerOverride,
  4644. scopedContext
  4645. }) {
  4646. let result;
  4647. let onReject;
  4648. let isAction = isMutationMethod(request.method);
  4649. let type = isAction ? "action" : "loader";
  4650. let runHandler = (handler) => {
  4651. let reject;
  4652. let abortPromise = new Promise((_, r) => reject = r);
  4653. onReject = () => reject();
  4654. request.signal.addEventListener("abort", onReject);
  4655. let actualHandler = (ctx) => {
  4656. if (typeof handler !== "function") {
  4657. return Promise.reject(
  4658. new Error(
  4659. `You cannot call the handler for a route which defines a boolean "${type}" [routeId: ${match.route.id}]`
  4660. )
  4661. );
  4662. }
  4663. return handler(
  4664. {
  4665. request,
  4666. unstable_pattern,
  4667. params: match.params,
  4668. context: scopedContext
  4669. },
  4670. ...ctx !== void 0 ? [ctx] : []
  4671. );
  4672. };
  4673. let handlerPromise = (async () => {
  4674. try {
  4675. let val = await (handlerOverride ? handlerOverride((ctx) => actualHandler(ctx)) : actualHandler());
  4676. return { type: "data", result: val };
  4677. } catch (e) {
  4678. return { type: "error", result: e };
  4679. }
  4680. })();
  4681. return Promise.race([handlerPromise, abortPromise]);
  4682. };
  4683. try {
  4684. let handler = isAction ? match.route.action : match.route.loader;
  4685. if (lazyHandlerPromise || lazyRoutePromise) {
  4686. if (handler) {
  4687. let handlerError;
  4688. let [value] = await Promise.all([
  4689. // If the handler throws, don't let it immediately bubble out,
  4690. // since we need to let the lazy() execution finish so we know if this
  4691. // route has a boundary that can handle the error
  4692. runHandler(handler).catch((e) => {
  4693. handlerError = e;
  4694. }),
  4695. // Ensure all lazy route promises are resolved before continuing
  4696. lazyHandlerPromise,
  4697. lazyRoutePromise
  4698. ]);
  4699. if (handlerError !== void 0) {
  4700. throw handlerError;
  4701. }
  4702. result = value;
  4703. } else {
  4704. await lazyHandlerPromise;
  4705. let handler2 = isAction ? match.route.action : match.route.loader;
  4706. if (handler2) {
  4707. [result] = await Promise.all([runHandler(handler2), lazyRoutePromise]);
  4708. } else if (type === "action") {
  4709. let url = new URL(request.url);
  4710. let pathname = url.pathname + url.search;
  4711. throw getInternalRouterError(405, {
  4712. method: request.method,
  4713. pathname,
  4714. routeId: match.route.id
  4715. });
  4716. } else {
  4717. return { type: "data" /* data */, result: void 0 };
  4718. }
  4719. }
  4720. } else if (!handler) {
  4721. let url = new URL(request.url);
  4722. let pathname = url.pathname + url.search;
  4723. throw getInternalRouterError(404, {
  4724. pathname
  4725. });
  4726. } else {
  4727. result = await runHandler(handler);
  4728. }
  4729. } catch (e) {
  4730. return { type: "error" /* error */, result: e };
  4731. } finally {
  4732. if (onReject) {
  4733. request.signal.removeEventListener("abort", onReject);
  4734. }
  4735. }
  4736. return result;
  4737. }
  4738. async function parseResponseBody(response) {
  4739. let contentType = response.headers.get("Content-Type");
  4740. if (contentType && /\bapplication\/json\b/.test(contentType)) {
  4741. return response.body == null ? null : response.json();
  4742. }
  4743. return response.text();
  4744. }
  4745. async function convertDataStrategyResultToDataResult(dataStrategyResult) {
  4746. let { result, type } = dataStrategyResult;
  4747. if (isResponse(result)) {
  4748. let data2;
  4749. try {
  4750. data2 = await parseResponseBody(result);
  4751. } catch (e) {
  4752. return { type: "error" /* error */, error: e };
  4753. }
  4754. if (type === "error" /* error */) {
  4755. return {
  4756. type: "error" /* error */,
  4757. error: new ErrorResponseImpl(result.status, result.statusText, data2),
  4758. statusCode: result.status,
  4759. headers: result.headers
  4760. };
  4761. }
  4762. return {
  4763. type: "data" /* data */,
  4764. data: data2,
  4765. statusCode: result.status,
  4766. headers: result.headers
  4767. };
  4768. }
  4769. if (type === "error" /* error */) {
  4770. if (isDataWithResponseInit(result)) {
  4771. if (result.data instanceof Error) {
  4772. return {
  4773. type: "error" /* error */,
  4774. error: result.data,
  4775. statusCode: result.init?.status,
  4776. headers: result.init?.headers ? new Headers(result.init.headers) : void 0
  4777. };
  4778. }
  4779. return {
  4780. type: "error" /* error */,
  4781. error: dataWithResponseInitToErrorResponse(result),
  4782. statusCode: isRouteErrorResponse(result) ? result.status : void 0,
  4783. headers: result.init?.headers ? new Headers(result.init.headers) : void 0
  4784. };
  4785. }
  4786. return {
  4787. type: "error" /* error */,
  4788. error: result,
  4789. statusCode: isRouteErrorResponse(result) ? result.status : void 0
  4790. };
  4791. }
  4792. if (isDataWithResponseInit(result)) {
  4793. return {
  4794. type: "data" /* data */,
  4795. data: result.data,
  4796. statusCode: result.init?.status,
  4797. headers: result.init?.headers ? new Headers(result.init.headers) : void 0
  4798. };
  4799. }
  4800. return { type: "data" /* data */, data: result };
  4801. }
  4802. function normalizeRelativeRoutingRedirectResponse(response, request, routeId, matches, basename) {
  4803. let location = response.headers.get("Location");
  4804. invariant(
  4805. location,
  4806. "Redirects returned/thrown from loaders/actions must have a Location header"
  4807. );
  4808. if (!isAbsoluteUrl(location)) {
  4809. let trimmedMatches = matches.slice(
  4810. 0,
  4811. matches.findIndex((m) => m.route.id === routeId) + 1
  4812. );
  4813. location = normalizeTo(
  4814. new URL(request.url),
  4815. trimmedMatches,
  4816. basename,
  4817. location
  4818. );
  4819. response.headers.set("Location", location);
  4820. }
  4821. return response;
  4822. }
  4823. function normalizeRedirectLocation(location, currentUrl, basename) {
  4824. if (isAbsoluteUrl(location)) {
  4825. let normalizedLocation = location;
  4826. let url = normalizedLocation.startsWith("//") ? new URL(currentUrl.protocol + normalizedLocation) : new URL(normalizedLocation);
  4827. let isSameBasename = stripBasename(url.pathname, basename) != null;
  4828. if (url.origin === currentUrl.origin && isSameBasename) {
  4829. return url.pathname + url.search + url.hash;
  4830. }
  4831. }
  4832. return location;
  4833. }
  4834. function createClientSideRequest(history, location, signal, submission) {
  4835. let url = history.createURL(stripHashFromPath(location)).toString();
  4836. let init = { signal };
  4837. if (submission && isMutationMethod(submission.formMethod)) {
  4838. let { formMethod, formEncType } = submission;
  4839. init.method = formMethod.toUpperCase();
  4840. if (formEncType === "application/json") {
  4841. init.headers = new Headers({ "Content-Type": formEncType });
  4842. init.body = JSON.stringify(submission.json);
  4843. } else if (formEncType === "text/plain") {
  4844. init.body = submission.text;
  4845. } else if (formEncType === "application/x-www-form-urlencoded" && submission.formData) {
  4846. init.body = convertFormDataToSearchParams(submission.formData);
  4847. } else {
  4848. init.body = submission.formData;
  4849. }
  4850. }
  4851. return new Request(url, init);
  4852. }
  4853. function convertFormDataToSearchParams(formData) {
  4854. let searchParams = new URLSearchParams();
  4855. for (let [key, value] of formData.entries()) {
  4856. searchParams.append(key, typeof value === "string" ? value : value.name);
  4857. }
  4858. return searchParams;
  4859. }
  4860. function convertSearchParamsToFormData(searchParams) {
  4861. let formData = new FormData();
  4862. for (let [key, value] of searchParams.entries()) {
  4863. formData.append(key, value);
  4864. }
  4865. return formData;
  4866. }
  4867. function processRouteLoaderData(matches, results, pendingActionResult, isStaticHandler = false, skipLoaderErrorBubbling = false) {
  4868. let loaderData = {};
  4869. let errors = null;
  4870. let statusCode;
  4871. let foundError = false;
  4872. let loaderHeaders = {};
  4873. let pendingError = pendingActionResult && isErrorResult(pendingActionResult[1]) ? pendingActionResult[1].error : void 0;
  4874. matches.forEach((match) => {
  4875. if (!(match.route.id in results)) {
  4876. return;
  4877. }
  4878. let id = match.route.id;
  4879. let result = results[id];
  4880. invariant(
  4881. !isRedirectResult(result),
  4882. "Cannot handle redirect results in processLoaderData"
  4883. );
  4884. if (isErrorResult(result)) {
  4885. let error = result.error;
  4886. if (pendingError !== void 0) {
  4887. error = pendingError;
  4888. pendingError = void 0;
  4889. }
  4890. errors = errors || {};
  4891. if (skipLoaderErrorBubbling) {
  4892. errors[id] = error;
  4893. } else {
  4894. let boundaryMatch = findNearestBoundary(matches, id);
  4895. if (errors[boundaryMatch.route.id] == null) {
  4896. errors[boundaryMatch.route.id] = error;
  4897. }
  4898. }
  4899. if (!isStaticHandler) {
  4900. loaderData[id] = ResetLoaderDataSymbol;
  4901. }
  4902. if (!foundError) {
  4903. foundError = true;
  4904. statusCode = isRouteErrorResponse(result.error) ? result.error.status : 500;
  4905. }
  4906. if (result.headers) {
  4907. loaderHeaders[id] = result.headers;
  4908. }
  4909. } else {
  4910. loaderData[id] = result.data;
  4911. if (result.statusCode && result.statusCode !== 200 && !foundError) {
  4912. statusCode = result.statusCode;
  4913. }
  4914. if (result.headers) {
  4915. loaderHeaders[id] = result.headers;
  4916. }
  4917. }
  4918. });
  4919. if (pendingError !== void 0 && pendingActionResult) {
  4920. errors = { [pendingActionResult[0]]: pendingError };
  4921. if (pendingActionResult[2]) {
  4922. loaderData[pendingActionResult[2]] = void 0;
  4923. }
  4924. }
  4925. return {
  4926. loaderData,
  4927. errors,
  4928. statusCode: statusCode || 200,
  4929. loaderHeaders
  4930. };
  4931. }
  4932. function processLoaderData(state, matches, results, pendingActionResult, revalidatingFetchers, fetcherResults) {
  4933. let { loaderData, errors } = processRouteLoaderData(
  4934. matches,
  4935. results,
  4936. pendingActionResult
  4937. );
  4938. revalidatingFetchers.filter((f) => !f.matches || f.matches.some((m) => m.shouldLoad)).forEach((rf) => {
  4939. let { key, match, controller } = rf;
  4940. if (controller && controller.signal.aborted) {
  4941. return;
  4942. }
  4943. let result = fetcherResults[key];
  4944. invariant(result, "Did not find corresponding fetcher result");
  4945. if (isErrorResult(result)) {
  4946. let boundaryMatch = findNearestBoundary(state.matches, match?.route.id);
  4947. if (!(errors && errors[boundaryMatch.route.id])) {
  4948. errors = {
  4949. ...errors,
  4950. [boundaryMatch.route.id]: result.error
  4951. };
  4952. }
  4953. state.fetchers.delete(key);
  4954. } else if (isRedirectResult(result)) {
  4955. invariant(false, "Unhandled fetcher revalidation redirect");
  4956. } else {
  4957. let doneFetcher = getDoneFetcher(result.data);
  4958. state.fetchers.set(key, doneFetcher);
  4959. }
  4960. });
  4961. return { loaderData, errors };
  4962. }
  4963. function mergeLoaderData(loaderData, newLoaderData, matches, errors) {
  4964. let mergedLoaderData = Object.entries(newLoaderData).filter(([, v]) => v !== ResetLoaderDataSymbol).reduce((merged, [k, v]) => {
  4965. merged[k] = v;
  4966. return merged;
  4967. }, {});
  4968. for (let match of matches) {
  4969. let id = match.route.id;
  4970. if (!newLoaderData.hasOwnProperty(id) && loaderData.hasOwnProperty(id) && match.route.loader) {
  4971. mergedLoaderData[id] = loaderData[id];
  4972. }
  4973. if (errors && errors.hasOwnProperty(id)) {
  4974. break;
  4975. }
  4976. }
  4977. return mergedLoaderData;
  4978. }
  4979. function getActionDataForCommit(pendingActionResult) {
  4980. if (!pendingActionResult) {
  4981. return {};
  4982. }
  4983. return isErrorResult(pendingActionResult[1]) ? {
  4984. // Clear out prior actionData on errors
  4985. actionData: {}
  4986. } : {
  4987. actionData: {
  4988. [pendingActionResult[0]]: pendingActionResult[1].data
  4989. }
  4990. };
  4991. }
  4992. function findNearestBoundary(matches, routeId) {
  4993. let eligibleMatches = routeId ? matches.slice(0, matches.findIndex((m) => m.route.id === routeId) + 1) : [...matches];
  4994. return eligibleMatches.reverse().find((m) => m.route.hasErrorBoundary === true) || matches[0];
  4995. }
  4996. function getShortCircuitMatches(routes) {
  4997. let route = routes.length === 1 ? routes[0] : routes.find((r) => r.index || !r.path || r.path === "/") || {
  4998. id: `__shim-error-route__`
  4999. };
  5000. return {
  5001. matches: [
  5002. {
  5003. params: {},
  5004. pathname: "",
  5005. pathnameBase: "",
  5006. route
  5007. }
  5008. ],
  5009. route
  5010. };
  5011. }
  5012. function getInternalRouterError(status, {
  5013. pathname,
  5014. routeId,
  5015. method,
  5016. type,
  5017. message
  5018. } = {}) {
  5019. let statusText = "Unknown Server Error";
  5020. let errorMessage = "Unknown @remix-run/router error";
  5021. if (status === 400) {
  5022. statusText = "Bad Request";
  5023. if (method && pathname && routeId) {
  5024. 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.`;
  5025. } else if (type === "invalid-body") {
  5026. errorMessage = "Unable to encode submission body";
  5027. }
  5028. } else if (status === 403) {
  5029. statusText = "Forbidden";
  5030. errorMessage = `Route "${routeId}" does not match URL "${pathname}"`;
  5031. } else if (status === 404) {
  5032. statusText = "Not Found";
  5033. errorMessage = `No route matches URL "${pathname}"`;
  5034. } else if (status === 405) {
  5035. statusText = "Method Not Allowed";
  5036. if (method && pathname && routeId) {
  5037. 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.`;
  5038. } else if (method) {
  5039. errorMessage = `Invalid request method "${method.toUpperCase()}"`;
  5040. }
  5041. }
  5042. return new ErrorResponseImpl(
  5043. status || 500,
  5044. statusText,
  5045. new Error(errorMessage),
  5046. true
  5047. );
  5048. }
  5049. function findRedirect(results) {
  5050. let entries = Object.entries(results);
  5051. for (let i = entries.length - 1; i >= 0; i--) {
  5052. let [key, result] = entries[i];
  5053. if (isRedirectResult(result)) {
  5054. return { key, result };
  5055. }
  5056. }
  5057. }
  5058. function stripHashFromPath(path) {
  5059. let parsedPath = typeof path === "string" ? parsePath(path) : path;
  5060. return createPath({ ...parsedPath, hash: "" });
  5061. }
  5062. function isHashChangeOnly(a, b) {
  5063. if (a.pathname !== b.pathname || a.search !== b.search) {
  5064. return false;
  5065. }
  5066. if (a.hash === "") {
  5067. return b.hash !== "";
  5068. } else if (a.hash === b.hash) {
  5069. return true;
  5070. } else if (b.hash !== "") {
  5071. return true;
  5072. }
  5073. return false;
  5074. }
  5075. function dataWithResponseInitToResponse(data2) {
  5076. return Response.json(data2.data, data2.init ?? void 0);
  5077. }
  5078. function dataWithResponseInitToErrorResponse(data2) {
  5079. return new ErrorResponseImpl(
  5080. data2.init?.status ?? 500,
  5081. data2.init?.statusText ?? "Internal Server Error",
  5082. data2.data
  5083. );
  5084. }
  5085. function isDataStrategyResults(result) {
  5086. return result != null && typeof result === "object" && Object.entries(result).every(
  5087. ([key, value]) => typeof key === "string" && isDataStrategyResult(value)
  5088. );
  5089. }
  5090. function isDataStrategyResult(result) {
  5091. return result != null && typeof result === "object" && "type" in result && "result" in result && (result.type === "data" /* data */ || result.type === "error" /* error */);
  5092. }
  5093. function isRedirectDataStrategyResult(result) {
  5094. return isResponse(result.result) && redirectStatusCodes.has(result.result.status);
  5095. }
  5096. function isErrorResult(result) {
  5097. return result.type === "error" /* error */;
  5098. }
  5099. function isRedirectResult(result) {
  5100. return (result && result.type) === "redirect" /* redirect */;
  5101. }
  5102. function isDataWithResponseInit(value) {
  5103. return typeof value === "object" && value != null && "type" in value && "data" in value && "init" in value && value.type === "DataWithResponseInit";
  5104. }
  5105. function isResponse(value) {
  5106. return value != null && typeof value.status === "number" && typeof value.statusText === "string" && typeof value.headers === "object" && typeof value.body !== "undefined";
  5107. }
  5108. function isRedirectStatusCode(statusCode) {
  5109. return redirectStatusCodes.has(statusCode);
  5110. }
  5111. function isRedirectResponse(result) {
  5112. return isResponse(result) && isRedirectStatusCode(result.status) && result.headers.has("Location");
  5113. }
  5114. function isValidMethod(method) {
  5115. return validRequestMethods.has(method.toUpperCase());
  5116. }
  5117. function isMutationMethod(method) {
  5118. return validMutationMethods.has(method.toUpperCase());
  5119. }
  5120. function hasNakedIndexQuery(search) {
  5121. return new URLSearchParams(search).getAll("index").some((v) => v === "");
  5122. }
  5123. function getTargetMatch(matches, location) {
  5124. let search = typeof location === "string" ? parsePath(location).search : location.search;
  5125. if (matches[matches.length - 1].route.index && hasNakedIndexQuery(search || "")) {
  5126. return matches[matches.length - 1];
  5127. }
  5128. let pathMatches = getPathContributingMatches(matches);
  5129. return pathMatches[pathMatches.length - 1];
  5130. }
  5131. function getSubmissionFromNavigation(navigation) {
  5132. let { formMethod, formAction, formEncType, text, formData, json } = navigation;
  5133. if (!formMethod || !formAction || !formEncType) {
  5134. return;
  5135. }
  5136. if (text != null) {
  5137. return {
  5138. formMethod,
  5139. formAction,
  5140. formEncType,
  5141. formData: void 0,
  5142. json: void 0,
  5143. text
  5144. };
  5145. } else if (formData != null) {
  5146. return {
  5147. formMethod,
  5148. formAction,
  5149. formEncType,
  5150. formData,
  5151. json: void 0,
  5152. text: void 0
  5153. };
  5154. } else if (json !== void 0) {
  5155. return {
  5156. formMethod,
  5157. formAction,
  5158. formEncType,
  5159. formData: void 0,
  5160. json,
  5161. text: void 0
  5162. };
  5163. }
  5164. }
  5165. function getLoadingNavigation(location, submission) {
  5166. if (submission) {
  5167. let navigation = {
  5168. state: "loading",
  5169. location,
  5170. formMethod: submission.formMethod,
  5171. formAction: submission.formAction,
  5172. formEncType: submission.formEncType,
  5173. formData: submission.formData,
  5174. json: submission.json,
  5175. text: submission.text
  5176. };
  5177. return navigation;
  5178. } else {
  5179. let navigation = {
  5180. state: "loading",
  5181. location,
  5182. formMethod: void 0,
  5183. formAction: void 0,
  5184. formEncType: void 0,
  5185. formData: void 0,
  5186. json: void 0,
  5187. text: void 0
  5188. };
  5189. return navigation;
  5190. }
  5191. }
  5192. function getSubmittingNavigation(location, submission) {
  5193. let navigation = {
  5194. state: "submitting",
  5195. location,
  5196. formMethod: submission.formMethod,
  5197. formAction: submission.formAction,
  5198. formEncType: submission.formEncType,
  5199. formData: submission.formData,
  5200. json: submission.json,
  5201. text: submission.text
  5202. };
  5203. return navigation;
  5204. }
  5205. function getLoadingFetcher(submission, data2) {
  5206. if (submission) {
  5207. let fetcher = {
  5208. state: "loading",
  5209. formMethod: submission.formMethod,
  5210. formAction: submission.formAction,
  5211. formEncType: submission.formEncType,
  5212. formData: submission.formData,
  5213. json: submission.json,
  5214. text: submission.text,
  5215. data: data2
  5216. };
  5217. return fetcher;
  5218. } else {
  5219. let fetcher = {
  5220. state: "loading",
  5221. formMethod: void 0,
  5222. formAction: void 0,
  5223. formEncType: void 0,
  5224. formData: void 0,
  5225. json: void 0,
  5226. text: void 0,
  5227. data: data2
  5228. };
  5229. return fetcher;
  5230. }
  5231. }
  5232. function getSubmittingFetcher(submission, existingFetcher) {
  5233. let fetcher = {
  5234. state: "submitting",
  5235. formMethod: submission.formMethod,
  5236. formAction: submission.formAction,
  5237. formEncType: submission.formEncType,
  5238. formData: submission.formData,
  5239. json: submission.json,
  5240. text: submission.text,
  5241. data: existingFetcher ? existingFetcher.data : void 0
  5242. };
  5243. return fetcher;
  5244. }
  5245. function getDoneFetcher(data2) {
  5246. let fetcher = {
  5247. state: "idle",
  5248. formMethod: void 0,
  5249. formAction: void 0,
  5250. formEncType: void 0,
  5251. formData: void 0,
  5252. json: void 0,
  5253. text: void 0,
  5254. data: data2
  5255. };
  5256. return fetcher;
  5257. }
  5258. function restoreAppliedTransitions(_window, transitions) {
  5259. try {
  5260. let sessionPositions = _window.sessionStorage.getItem(
  5261. TRANSITIONS_STORAGE_KEY
  5262. );
  5263. if (sessionPositions) {
  5264. let json = JSON.parse(sessionPositions);
  5265. for (let [k, v] of Object.entries(json || {})) {
  5266. if (v && Array.isArray(v)) {
  5267. transitions.set(k, new Set(v || []));
  5268. }
  5269. }
  5270. }
  5271. } catch (e) {
  5272. }
  5273. }
  5274. function persistAppliedTransitions(_window, transitions) {
  5275. if (transitions.size > 0) {
  5276. let json = {};
  5277. for (let [k, v] of transitions) {
  5278. json[k] = [...v];
  5279. }
  5280. try {
  5281. _window.sessionStorage.setItem(
  5282. TRANSITIONS_STORAGE_KEY,
  5283. JSON.stringify(json)
  5284. );
  5285. } catch (error) {
  5286. warning(
  5287. false,
  5288. `Failed to save applied view transitions in sessionStorage (${error}).`
  5289. );
  5290. }
  5291. }
  5292. }
  5293. function createDeferred() {
  5294. let resolve;
  5295. let reject;
  5296. let promise = new Promise((res, rej) => {
  5297. resolve = async (val) => {
  5298. res(val);
  5299. try {
  5300. await promise;
  5301. } catch (e) {
  5302. }
  5303. };
  5304. reject = async (error) => {
  5305. rej(error);
  5306. try {
  5307. await promise;
  5308. } catch (e) {
  5309. }
  5310. };
  5311. });
  5312. return {
  5313. promise,
  5314. //@ts-ignore
  5315. resolve,
  5316. //@ts-ignore
  5317. reject
  5318. };
  5319. }
  5320. // lib/context.ts
  5321. import * as React from "react";
  5322. var DataRouterContext = React.createContext(null);
  5323. DataRouterContext.displayName = "DataRouter";
  5324. var DataRouterStateContext = React.createContext(null);
  5325. DataRouterStateContext.displayName = "DataRouterState";
  5326. var RSCRouterContext = React.createContext(false);
  5327. function useIsRSCRouterContext() {
  5328. return React.useContext(RSCRouterContext);
  5329. }
  5330. var ViewTransitionContext = React.createContext({
  5331. isTransitioning: false
  5332. });
  5333. ViewTransitionContext.displayName = "ViewTransition";
  5334. var FetchersContext = React.createContext(
  5335. /* @__PURE__ */ new Map()
  5336. );
  5337. FetchersContext.displayName = "Fetchers";
  5338. var AwaitContext = React.createContext(null);
  5339. AwaitContext.displayName = "Await";
  5340. var AwaitContextProvider = (props) => React.createElement(AwaitContext.Provider, props);
  5341. var NavigationContext = React.createContext(
  5342. null
  5343. );
  5344. NavigationContext.displayName = "Navigation";
  5345. var LocationContext = React.createContext(
  5346. null
  5347. );
  5348. LocationContext.displayName = "Location";
  5349. var RouteContext = React.createContext({
  5350. outlet: null,
  5351. matches: [],
  5352. isDataRoute: false
  5353. });
  5354. RouteContext.displayName = "Route";
  5355. var RouteErrorContext = React.createContext(null);
  5356. RouteErrorContext.displayName = "RouteError";
  5357. var ENABLE_DEV_WARNINGS = true;
  5358. // lib/hooks.tsx
  5359. import * as React2 from "react";
  5360. function useHref(to, { relative } = {}) {
  5361. invariant(
  5362. useInRouterContext(),
  5363. // TODO: This error is probably because they somehow have 2 versions of the
  5364. // router loaded. We can help them understand how to avoid that.
  5365. `useHref() may be used only in the context of a <Router> component.`
  5366. );
  5367. let { basename, navigator } = React2.useContext(NavigationContext);
  5368. let { hash, pathname, search } = useResolvedPath(to, { relative });
  5369. let joinedPathname = pathname;
  5370. if (basename !== "/") {
  5371. joinedPathname = pathname === "/" ? basename : joinPaths([basename, pathname]);
  5372. }
  5373. return navigator.createHref({ pathname: joinedPathname, search, hash });
  5374. }
  5375. function useInRouterContext() {
  5376. return React2.useContext(LocationContext) != null;
  5377. }
  5378. function useLocation() {
  5379. invariant(
  5380. useInRouterContext(),
  5381. // TODO: This error is probably because they somehow have 2 versions of the
  5382. // router loaded. We can help them understand how to avoid that.
  5383. `useLocation() may be used only in the context of a <Router> component.`
  5384. );
  5385. return React2.useContext(LocationContext).location;
  5386. }
  5387. function useNavigationType() {
  5388. return React2.useContext(LocationContext).navigationType;
  5389. }
  5390. function useMatch(pattern) {
  5391. invariant(
  5392. useInRouterContext(),
  5393. // TODO: This error is probably because they somehow have 2 versions of the
  5394. // router loaded. We can help them understand how to avoid that.
  5395. `useMatch() may be used only in the context of a <Router> component.`
  5396. );
  5397. let { pathname } = useLocation();
  5398. return React2.useMemo(
  5399. () => matchPath(pattern, decodePath(pathname)),
  5400. [pathname, pattern]
  5401. );
  5402. }
  5403. var navigateEffectWarning = `You should call navigate() in a React.useEffect(), not when your component is first rendered.`;
  5404. function useIsomorphicLayoutEffect(cb) {
  5405. let isStatic = React2.useContext(NavigationContext).static;
  5406. if (!isStatic) {
  5407. React2.useLayoutEffect(cb);
  5408. }
  5409. }
  5410. function useNavigate() {
  5411. let { isDataRoute } = React2.useContext(RouteContext);
  5412. return isDataRoute ? useNavigateStable() : useNavigateUnstable();
  5413. }
  5414. function useNavigateUnstable() {
  5415. invariant(
  5416. useInRouterContext(),
  5417. // TODO: This error is probably because they somehow have 2 versions of the
  5418. // router loaded. We can help them understand how to avoid that.
  5419. `useNavigate() may be used only in the context of a <Router> component.`
  5420. );
  5421. let dataRouterContext = React2.useContext(DataRouterContext);
  5422. let { basename, navigator } = React2.useContext(NavigationContext);
  5423. let { matches } = React2.useContext(RouteContext);
  5424. let { pathname: locationPathname } = useLocation();
  5425. let routePathnamesJson = JSON.stringify(getResolveToMatches(matches));
  5426. let activeRef = React2.useRef(false);
  5427. useIsomorphicLayoutEffect(() => {
  5428. activeRef.current = true;
  5429. });
  5430. let navigate = React2.useCallback(
  5431. (to, options = {}) => {
  5432. warning(activeRef.current, navigateEffectWarning);
  5433. if (!activeRef.current) return;
  5434. if (typeof to === "number") {
  5435. navigator.go(to);
  5436. return;
  5437. }
  5438. let path = resolveTo(
  5439. to,
  5440. JSON.parse(routePathnamesJson),
  5441. locationPathname,
  5442. options.relative === "path"
  5443. );
  5444. if (dataRouterContext == null && basename !== "/") {
  5445. path.pathname = path.pathname === "/" ? basename : joinPaths([basename, path.pathname]);
  5446. }
  5447. (!!options.replace ? navigator.replace : navigator.push)(
  5448. path,
  5449. options.state,
  5450. options
  5451. );
  5452. },
  5453. [
  5454. basename,
  5455. navigator,
  5456. routePathnamesJson,
  5457. locationPathname,
  5458. dataRouterContext
  5459. ]
  5460. );
  5461. return navigate;
  5462. }
  5463. var OutletContext = React2.createContext(null);
  5464. function useOutletContext() {
  5465. return React2.useContext(OutletContext);
  5466. }
  5467. function useOutlet(context) {
  5468. let outlet = React2.useContext(RouteContext).outlet;
  5469. return React2.useMemo(
  5470. () => outlet && /* @__PURE__ */ React2.createElement(OutletContext.Provider, { value: context }, outlet),
  5471. [outlet, context]
  5472. );
  5473. }
  5474. function useParams() {
  5475. let { matches } = React2.useContext(RouteContext);
  5476. let routeMatch = matches[matches.length - 1];
  5477. return routeMatch ? routeMatch.params : {};
  5478. }
  5479. function useResolvedPath(to, { relative } = {}) {
  5480. let { matches } = React2.useContext(RouteContext);
  5481. let { pathname: locationPathname } = useLocation();
  5482. let routePathnamesJson = JSON.stringify(getResolveToMatches(matches));
  5483. return React2.useMemo(
  5484. () => resolveTo(
  5485. to,
  5486. JSON.parse(routePathnamesJson),
  5487. locationPathname,
  5488. relative === "path"
  5489. ),
  5490. [to, routePathnamesJson, locationPathname, relative]
  5491. );
  5492. }
  5493. function useRoutes(routes, locationArg) {
  5494. return useRoutesImpl(routes, locationArg);
  5495. }
  5496. function useRoutesImpl(routes, locationArg, dataRouterState, unstable_onError, future) {
  5497. invariant(
  5498. useInRouterContext(),
  5499. // TODO: This error is probably because they somehow have 2 versions of the
  5500. // router loaded. We can help them understand how to avoid that.
  5501. `useRoutes() may be used only in the context of a <Router> component.`
  5502. );
  5503. let { navigator } = React2.useContext(NavigationContext);
  5504. let { matches: parentMatches } = React2.useContext(RouteContext);
  5505. let routeMatch = parentMatches[parentMatches.length - 1];
  5506. let parentParams = routeMatch ? routeMatch.params : {};
  5507. let parentPathname = routeMatch ? routeMatch.pathname : "/";
  5508. let parentPathnameBase = routeMatch ? routeMatch.pathnameBase : "/";
  5509. let parentRoute = routeMatch && routeMatch.route;
  5510. if (ENABLE_DEV_WARNINGS) {
  5511. let parentPath = parentRoute && parentRoute.path || "";
  5512. warningOnce(
  5513. parentPathname,
  5514. !parentRoute || parentPath.endsWith("*") || parentPath.endsWith("*?"),
  5515. `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.
  5516. Please change the parent <Route path="${parentPath}"> to <Route path="${parentPath === "/" ? "*" : `${parentPath}/*`}">.`
  5517. );
  5518. }
  5519. let locationFromContext = useLocation();
  5520. let location;
  5521. if (locationArg) {
  5522. let parsedLocationArg = typeof locationArg === "string" ? parsePath(locationArg) : locationArg;
  5523. invariant(
  5524. parentPathnameBase === "/" || parsedLocationArg.pathname?.startsWith(parentPathnameBase),
  5525. `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.`
  5526. );
  5527. location = parsedLocationArg;
  5528. } else {
  5529. location = locationFromContext;
  5530. }
  5531. let pathname = location.pathname || "/";
  5532. let remainingPathname = pathname;
  5533. if (parentPathnameBase !== "/") {
  5534. let parentSegments = parentPathnameBase.replace(/^\//, "").split("/");
  5535. let segments = pathname.replace(/^\//, "").split("/");
  5536. remainingPathname = "/" + segments.slice(parentSegments.length).join("/");
  5537. }
  5538. let matches = matchRoutes(routes, { pathname: remainingPathname });
  5539. if (ENABLE_DEV_WARNINGS) {
  5540. warning(
  5541. parentRoute || matches != null,
  5542. `No routes matched location "${location.pathname}${location.search}${location.hash}" `
  5543. );
  5544. warning(
  5545. 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,
  5546. `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.`
  5547. );
  5548. }
  5549. let renderedMatches = _renderMatches(
  5550. matches && matches.map(
  5551. (match) => Object.assign({}, match, {
  5552. params: Object.assign({}, parentParams, match.params),
  5553. pathname: joinPaths([
  5554. parentPathnameBase,
  5555. // Re-encode pathnames that were decoded inside matchRoutes.
  5556. // Pre-encode `?` and `#` ahead of `encodeLocation` because it uses
  5557. // `new URL()` internally and we need to prevent it from treating
  5558. // them as separators
  5559. navigator.encodeLocation ? navigator.encodeLocation(
  5560. match.pathname.replace(/\?/g, "%3F").replace(/#/g, "%23")
  5561. ).pathname : match.pathname
  5562. ]),
  5563. pathnameBase: match.pathnameBase === "/" ? parentPathnameBase : joinPaths([
  5564. parentPathnameBase,
  5565. // Re-encode pathnames that were decoded inside matchRoutes
  5566. // Pre-encode `?` and `#` ahead of `encodeLocation` because it uses
  5567. // `new URL()` internally and we need to prevent it from treating
  5568. // them as separators
  5569. navigator.encodeLocation ? navigator.encodeLocation(
  5570. match.pathnameBase.replace(/\?/g, "%3F").replace(/#/g, "%23")
  5571. ).pathname : match.pathnameBase
  5572. ])
  5573. })
  5574. ),
  5575. parentMatches,
  5576. dataRouterState,
  5577. unstable_onError,
  5578. future
  5579. );
  5580. if (locationArg && renderedMatches) {
  5581. return /* @__PURE__ */ React2.createElement(
  5582. LocationContext.Provider,
  5583. {
  5584. value: {
  5585. location: {
  5586. pathname: "/",
  5587. search: "",
  5588. hash: "",
  5589. state: null,
  5590. key: "default",
  5591. ...location
  5592. },
  5593. navigationType: "POP" /* Pop */
  5594. }
  5595. },
  5596. renderedMatches
  5597. );
  5598. }
  5599. return renderedMatches;
  5600. }
  5601. function DefaultErrorComponent() {
  5602. let error = useRouteError();
  5603. let message = isRouteErrorResponse(error) ? `${error.status} ${error.statusText}` : error instanceof Error ? error.message : JSON.stringify(error);
  5604. let stack = error instanceof Error ? error.stack : null;
  5605. let lightgrey = "rgba(200,200,200, 0.5)";
  5606. let preStyles = { padding: "0.5rem", backgroundColor: lightgrey };
  5607. let codeStyles = { padding: "2px 4px", backgroundColor: lightgrey };
  5608. let devInfo = null;
  5609. if (ENABLE_DEV_WARNINGS) {
  5610. console.error(
  5611. "Error handled by React Router default ErrorBoundary:",
  5612. error
  5613. );
  5614. devInfo = /* @__PURE__ */ React2.createElement(React2.Fragment, null, /* @__PURE__ */ React2.createElement("p", null, "\u{1F4BF} Hey developer \u{1F44B}"), /* @__PURE__ */ React2.createElement("p", null, "You can provide a way better UX than this when your app throws errors by providing your own ", /* @__PURE__ */ React2.createElement("code", { style: codeStyles }, "ErrorBoundary"), " or", " ", /* @__PURE__ */ React2.createElement("code", { style: codeStyles }, "errorElement"), " prop on your route."));
  5615. }
  5616. return /* @__PURE__ */ React2.createElement(React2.Fragment, null, /* @__PURE__ */ React2.createElement("h2", null, "Unexpected Application Error!"), /* @__PURE__ */ React2.createElement("h3", { style: { fontStyle: "italic" } }, message), stack ? /* @__PURE__ */ React2.createElement("pre", { style: preStyles }, stack) : null, devInfo);
  5617. }
  5618. var defaultErrorElement = /* @__PURE__ */ React2.createElement(DefaultErrorComponent, null);
  5619. var RenderErrorBoundary = class extends React2.Component {
  5620. constructor(props) {
  5621. super(props);
  5622. this.state = {
  5623. location: props.location,
  5624. revalidation: props.revalidation,
  5625. error: props.error
  5626. };
  5627. }
  5628. static getDerivedStateFromError(error) {
  5629. return { error };
  5630. }
  5631. static getDerivedStateFromProps(props, state) {
  5632. if (state.location !== props.location || state.revalidation !== "idle" && props.revalidation === "idle") {
  5633. return {
  5634. error: props.error,
  5635. location: props.location,
  5636. revalidation: props.revalidation
  5637. };
  5638. }
  5639. return {
  5640. error: props.error !== void 0 ? props.error : state.error,
  5641. location: state.location,
  5642. revalidation: props.revalidation || state.revalidation
  5643. };
  5644. }
  5645. componentDidCatch(error, errorInfo) {
  5646. if (this.props.onError) {
  5647. this.props.onError(error, errorInfo);
  5648. } else {
  5649. console.error(
  5650. "React Router caught the following error during render",
  5651. error
  5652. );
  5653. }
  5654. }
  5655. render() {
  5656. return this.state.error !== void 0 ? /* @__PURE__ */ React2.createElement(RouteContext.Provider, { value: this.props.routeContext }, /* @__PURE__ */ React2.createElement(
  5657. RouteErrorContext.Provider,
  5658. {
  5659. value: this.state.error,
  5660. children: this.props.component
  5661. }
  5662. )) : this.props.children;
  5663. }
  5664. };
  5665. function RenderedRoute({ routeContext, match, children }) {
  5666. let dataRouterContext = React2.useContext(DataRouterContext);
  5667. if (dataRouterContext && dataRouterContext.static && dataRouterContext.staticContext && (match.route.errorElement || match.route.ErrorBoundary)) {
  5668. dataRouterContext.staticContext._deepestRenderedBoundaryId = match.route.id;
  5669. }
  5670. return /* @__PURE__ */ React2.createElement(RouteContext.Provider, { value: routeContext }, children);
  5671. }
  5672. function _renderMatches(matches, parentMatches = [], dataRouterState = null, unstable_onError = null, future = null) {
  5673. if (matches == null) {
  5674. if (!dataRouterState) {
  5675. return null;
  5676. }
  5677. if (dataRouterState.errors) {
  5678. matches = dataRouterState.matches;
  5679. } else if (parentMatches.length === 0 && !dataRouterState.initialized && dataRouterState.matches.length > 0) {
  5680. matches = dataRouterState.matches;
  5681. } else {
  5682. return null;
  5683. }
  5684. }
  5685. let renderedMatches = matches;
  5686. let errors = dataRouterState?.errors;
  5687. if (errors != null) {
  5688. let errorIndex = renderedMatches.findIndex(
  5689. (m) => m.route.id && errors?.[m.route.id] !== void 0
  5690. );
  5691. invariant(
  5692. errorIndex >= 0,
  5693. `Could not find a matching route for errors on route IDs: ${Object.keys(
  5694. errors
  5695. ).join(",")}`
  5696. );
  5697. renderedMatches = renderedMatches.slice(
  5698. 0,
  5699. Math.min(renderedMatches.length, errorIndex + 1)
  5700. );
  5701. }
  5702. let renderFallback = false;
  5703. let fallbackIndex = -1;
  5704. if (dataRouterState) {
  5705. for (let i = 0; i < renderedMatches.length; i++) {
  5706. let match = renderedMatches[i];
  5707. if (match.route.HydrateFallback || match.route.hydrateFallbackElement) {
  5708. fallbackIndex = i;
  5709. }
  5710. if (match.route.id) {
  5711. let { loaderData, errors: errors2 } = dataRouterState;
  5712. let needsToRunLoader = match.route.loader && !loaderData.hasOwnProperty(match.route.id) && (!errors2 || errors2[match.route.id] === void 0);
  5713. if (match.route.lazy || needsToRunLoader) {
  5714. renderFallback = true;
  5715. if (fallbackIndex >= 0) {
  5716. renderedMatches = renderedMatches.slice(0, fallbackIndex + 1);
  5717. } else {
  5718. renderedMatches = [renderedMatches[0]];
  5719. }
  5720. break;
  5721. }
  5722. }
  5723. }
  5724. }
  5725. let onError = dataRouterState && unstable_onError ? (error, errorInfo) => {
  5726. unstable_onError(error, {
  5727. location: dataRouterState.location,
  5728. params: dataRouterState.matches?.[0]?.params ?? {},
  5729. unstable_pattern: getRoutePattern(dataRouterState.matches),
  5730. errorInfo
  5731. });
  5732. } : void 0;
  5733. return renderedMatches.reduceRight(
  5734. (outlet, match, index) => {
  5735. let error;
  5736. let shouldRenderHydrateFallback = false;
  5737. let errorElement = null;
  5738. let hydrateFallbackElement = null;
  5739. if (dataRouterState) {
  5740. error = errors && match.route.id ? errors[match.route.id] : void 0;
  5741. errorElement = match.route.errorElement || defaultErrorElement;
  5742. if (renderFallback) {
  5743. if (fallbackIndex < 0 && index === 0) {
  5744. warningOnce(
  5745. "route-fallback",
  5746. false,
  5747. "No `HydrateFallback` element provided to render during initial hydration"
  5748. );
  5749. shouldRenderHydrateFallback = true;
  5750. hydrateFallbackElement = null;
  5751. } else if (fallbackIndex === index) {
  5752. shouldRenderHydrateFallback = true;
  5753. hydrateFallbackElement = match.route.hydrateFallbackElement || null;
  5754. }
  5755. }
  5756. }
  5757. let matches2 = parentMatches.concat(renderedMatches.slice(0, index + 1));
  5758. let getChildren = () => {
  5759. let children;
  5760. if (error) {
  5761. children = errorElement;
  5762. } else if (shouldRenderHydrateFallback) {
  5763. children = hydrateFallbackElement;
  5764. } else if (match.route.Component) {
  5765. children = /* @__PURE__ */ React2.createElement(match.route.Component, null);
  5766. } else if (match.route.element) {
  5767. children = match.route.element;
  5768. } else {
  5769. children = outlet;
  5770. }
  5771. return /* @__PURE__ */ React2.createElement(
  5772. RenderedRoute,
  5773. {
  5774. match,
  5775. routeContext: {
  5776. outlet,
  5777. matches: matches2,
  5778. isDataRoute: dataRouterState != null
  5779. },
  5780. children
  5781. }
  5782. );
  5783. };
  5784. return dataRouterState && (match.route.ErrorBoundary || match.route.errorElement || index === 0) ? /* @__PURE__ */ React2.createElement(
  5785. RenderErrorBoundary,
  5786. {
  5787. location: dataRouterState.location,
  5788. revalidation: dataRouterState.revalidation,
  5789. component: errorElement,
  5790. error,
  5791. children: getChildren(),
  5792. routeContext: { outlet: null, matches: matches2, isDataRoute: true },
  5793. onError
  5794. }
  5795. ) : getChildren();
  5796. },
  5797. null
  5798. );
  5799. }
  5800. function getDataRouterConsoleError(hookName) {
  5801. return `${hookName} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`;
  5802. }
  5803. function useDataRouterContext(hookName) {
  5804. let ctx = React2.useContext(DataRouterContext);
  5805. invariant(ctx, getDataRouterConsoleError(hookName));
  5806. return ctx;
  5807. }
  5808. function useDataRouterState(hookName) {
  5809. let state = React2.useContext(DataRouterStateContext);
  5810. invariant(state, getDataRouterConsoleError(hookName));
  5811. return state;
  5812. }
  5813. function useRouteContext(hookName) {
  5814. let route = React2.useContext(RouteContext);
  5815. invariant(route, getDataRouterConsoleError(hookName));
  5816. return route;
  5817. }
  5818. function useCurrentRouteId(hookName) {
  5819. let route = useRouteContext(hookName);
  5820. let thisRoute = route.matches[route.matches.length - 1];
  5821. invariant(
  5822. thisRoute.route.id,
  5823. `${hookName} can only be used on routes that contain a unique "id"`
  5824. );
  5825. return thisRoute.route.id;
  5826. }
  5827. function useRouteId() {
  5828. return useCurrentRouteId("useRouteId" /* UseRouteId */);
  5829. }
  5830. function useNavigation() {
  5831. let state = useDataRouterState("useNavigation" /* UseNavigation */);
  5832. return state.navigation;
  5833. }
  5834. function useRevalidator() {
  5835. let dataRouterContext = useDataRouterContext("useRevalidator" /* UseRevalidator */);
  5836. let state = useDataRouterState("useRevalidator" /* UseRevalidator */);
  5837. let revalidate = React2.useCallback(async () => {
  5838. await dataRouterContext.router.revalidate();
  5839. }, [dataRouterContext.router]);
  5840. return React2.useMemo(
  5841. () => ({ revalidate, state: state.revalidation }),
  5842. [revalidate, state.revalidation]
  5843. );
  5844. }
  5845. function useMatches() {
  5846. let { matches, loaderData } = useDataRouterState(
  5847. "useMatches" /* UseMatches */
  5848. );
  5849. return React2.useMemo(
  5850. () => matches.map((m) => convertRouteMatchToUiMatch(m, loaderData)),
  5851. [matches, loaderData]
  5852. );
  5853. }
  5854. function useLoaderData() {
  5855. let state = useDataRouterState("useLoaderData" /* UseLoaderData */);
  5856. let routeId = useCurrentRouteId("useLoaderData" /* UseLoaderData */);
  5857. return state.loaderData[routeId];
  5858. }
  5859. function useRouteLoaderData(routeId) {
  5860. let state = useDataRouterState("useRouteLoaderData" /* UseRouteLoaderData */);
  5861. return state.loaderData[routeId];
  5862. }
  5863. function useActionData() {
  5864. let state = useDataRouterState("useActionData" /* UseActionData */);
  5865. let routeId = useCurrentRouteId("useLoaderData" /* UseLoaderData */);
  5866. return state.actionData ? state.actionData[routeId] : void 0;
  5867. }
  5868. function useRouteError() {
  5869. let error = React2.useContext(RouteErrorContext);
  5870. let state = useDataRouterState("useRouteError" /* UseRouteError */);
  5871. let routeId = useCurrentRouteId("useRouteError" /* UseRouteError */);
  5872. if (error !== void 0) {
  5873. return error;
  5874. }
  5875. return state.errors?.[routeId];
  5876. }
  5877. function useAsyncValue() {
  5878. let value = React2.useContext(AwaitContext);
  5879. return value?._data;
  5880. }
  5881. function useAsyncError() {
  5882. let value = React2.useContext(AwaitContext);
  5883. return value?._error;
  5884. }
  5885. var blockerId = 0;
  5886. function useBlocker(shouldBlock) {
  5887. let { router, basename } = useDataRouterContext("useBlocker" /* UseBlocker */);
  5888. let state = useDataRouterState("useBlocker" /* UseBlocker */);
  5889. let [blockerKey, setBlockerKey] = React2.useState("");
  5890. let blockerFunction = React2.useCallback(
  5891. (arg) => {
  5892. if (typeof shouldBlock !== "function") {
  5893. return !!shouldBlock;
  5894. }
  5895. if (basename === "/") {
  5896. return shouldBlock(arg);
  5897. }
  5898. let { currentLocation, nextLocation, historyAction } = arg;
  5899. return shouldBlock({
  5900. currentLocation: {
  5901. ...currentLocation,
  5902. pathname: stripBasename(currentLocation.pathname, basename) || currentLocation.pathname
  5903. },
  5904. nextLocation: {
  5905. ...nextLocation,
  5906. pathname: stripBasename(nextLocation.pathname, basename) || nextLocation.pathname
  5907. },
  5908. historyAction
  5909. });
  5910. },
  5911. [basename, shouldBlock]
  5912. );
  5913. React2.useEffect(() => {
  5914. let key = String(++blockerId);
  5915. setBlockerKey(key);
  5916. return () => router.deleteBlocker(key);
  5917. }, [router]);
  5918. React2.useEffect(() => {
  5919. if (blockerKey !== "") {
  5920. router.getBlocker(blockerKey, blockerFunction);
  5921. }
  5922. }, [router, blockerKey, blockerFunction]);
  5923. return blockerKey && state.blockers.has(blockerKey) ? state.blockers.get(blockerKey) : IDLE_BLOCKER;
  5924. }
  5925. function useNavigateStable() {
  5926. let { router } = useDataRouterContext("useNavigate" /* UseNavigateStable */);
  5927. let id = useCurrentRouteId("useNavigate" /* UseNavigateStable */);
  5928. let activeRef = React2.useRef(false);
  5929. useIsomorphicLayoutEffect(() => {
  5930. activeRef.current = true;
  5931. });
  5932. let navigate = React2.useCallback(
  5933. async (to, options = {}) => {
  5934. warning(activeRef.current, navigateEffectWarning);
  5935. if (!activeRef.current) return;
  5936. if (typeof to === "number") {
  5937. await router.navigate(to);
  5938. } else {
  5939. await router.navigate(to, { fromRouteId: id, ...options });
  5940. }
  5941. },
  5942. [router, id]
  5943. );
  5944. return navigate;
  5945. }
  5946. var alreadyWarned = {};
  5947. function warningOnce(key, cond, message) {
  5948. if (!cond && !alreadyWarned[key]) {
  5949. alreadyWarned[key] = true;
  5950. warning(false, message);
  5951. }
  5952. }
  5953. function useRoute(...args) {
  5954. const currentRouteId = useCurrentRouteId(
  5955. "useRoute" /* UseRoute */
  5956. );
  5957. const id = args[0] ?? currentRouteId;
  5958. const state = useDataRouterState("useRoute" /* UseRoute */);
  5959. const route = state.matches.find(({ route: route2 }) => route2.id === id);
  5960. if (route === void 0) return void 0;
  5961. return {
  5962. handle: route.route.handle,
  5963. loaderData: state.loaderData[id],
  5964. actionData: state.actionData?.[id]
  5965. };
  5966. }
  5967. // lib/components.tsx
  5968. import * as React3 from "react";
  5969. // lib/server-runtime/warnings.ts
  5970. var alreadyWarned2 = {};
  5971. function warnOnce(condition, message) {
  5972. if (!condition && !alreadyWarned2[message]) {
  5973. alreadyWarned2[message] = true;
  5974. console.warn(message);
  5975. }
  5976. }
  5977. // lib/components.tsx
  5978. var USE_OPTIMISTIC = "useOptimistic";
  5979. var useOptimisticImpl = React3[USE_OPTIMISTIC];
  5980. var stableUseOptimisticSetter = () => void 0;
  5981. function useOptimisticSafe(val) {
  5982. if (useOptimisticImpl) {
  5983. return useOptimisticImpl(val);
  5984. } else {
  5985. return [val, stableUseOptimisticSetter];
  5986. }
  5987. }
  5988. function mapRouteProperties(route) {
  5989. let updates = {
  5990. // Note: this check also occurs in createRoutesFromChildren so update
  5991. // there if you change this -- please and thank you!
  5992. hasErrorBoundary: route.hasErrorBoundary || route.ErrorBoundary != null || route.errorElement != null
  5993. };
  5994. if (route.Component) {
  5995. if (ENABLE_DEV_WARNINGS) {
  5996. if (route.element) {
  5997. warning(
  5998. false,
  5999. "You should not include both `Component` and `element` on your route - `Component` will be used."
  6000. );
  6001. }
  6002. }
  6003. Object.assign(updates, {
  6004. element: React3.createElement(route.Component),
  6005. Component: void 0
  6006. });
  6007. }
  6008. if (route.HydrateFallback) {
  6009. if (ENABLE_DEV_WARNINGS) {
  6010. if (route.hydrateFallbackElement) {
  6011. warning(
  6012. false,
  6013. "You should not include both `HydrateFallback` and `hydrateFallbackElement` on your route - `HydrateFallback` will be used."
  6014. );
  6015. }
  6016. }
  6017. Object.assign(updates, {
  6018. hydrateFallbackElement: React3.createElement(route.HydrateFallback),
  6019. HydrateFallback: void 0
  6020. });
  6021. }
  6022. if (route.ErrorBoundary) {
  6023. if (ENABLE_DEV_WARNINGS) {
  6024. if (route.errorElement) {
  6025. warning(
  6026. false,
  6027. "You should not include both `ErrorBoundary` and `errorElement` on your route - `ErrorBoundary` will be used."
  6028. );
  6029. }
  6030. }
  6031. Object.assign(updates, {
  6032. errorElement: React3.createElement(route.ErrorBoundary),
  6033. ErrorBoundary: void 0
  6034. });
  6035. }
  6036. return updates;
  6037. }
  6038. var hydrationRouteProperties = [
  6039. "HydrateFallback",
  6040. "hydrateFallbackElement"
  6041. ];
  6042. function createMemoryRouter(routes, opts) {
  6043. return createRouter({
  6044. basename: opts?.basename,
  6045. getContext: opts?.getContext,
  6046. future: opts?.future,
  6047. history: createMemoryHistory({
  6048. initialEntries: opts?.initialEntries,
  6049. initialIndex: opts?.initialIndex
  6050. }),
  6051. hydrationData: opts?.hydrationData,
  6052. routes,
  6053. hydrationRouteProperties,
  6054. mapRouteProperties,
  6055. dataStrategy: opts?.dataStrategy,
  6056. patchRoutesOnNavigation: opts?.patchRoutesOnNavigation,
  6057. unstable_instrumentations: opts?.unstable_instrumentations
  6058. }).initialize();
  6059. }
  6060. var Deferred = class {
  6061. constructor() {
  6062. this.status = "pending";
  6063. this.promise = new Promise((resolve, reject) => {
  6064. this.resolve = (value) => {
  6065. if (this.status === "pending") {
  6066. this.status = "resolved";
  6067. resolve(value);
  6068. }
  6069. };
  6070. this.reject = (reason) => {
  6071. if (this.status === "pending") {
  6072. this.status = "rejected";
  6073. reject(reason);
  6074. }
  6075. };
  6076. });
  6077. }
  6078. };
  6079. function RouterProvider({
  6080. router,
  6081. flushSync: reactDomFlushSyncImpl,
  6082. unstable_onError,
  6083. unstable_useTransitions
  6084. }) {
  6085. let [_state, setStateImpl] = React3.useState(router.state);
  6086. let [state, setOptimisticState] = useOptimisticSafe(_state);
  6087. let [pendingState, setPendingState] = React3.useState();
  6088. let [vtContext, setVtContext] = React3.useState({
  6089. isTransitioning: false
  6090. });
  6091. let [renderDfd, setRenderDfd] = React3.useState();
  6092. let [transition, setTransition] = React3.useState();
  6093. let [interruption, setInterruption] = React3.useState();
  6094. let fetcherData = React3.useRef(/* @__PURE__ */ new Map());
  6095. let setState = React3.useCallback(
  6096. (newState, { deletedFetchers, newErrors, flushSync, viewTransitionOpts }) => {
  6097. if (newErrors && unstable_onError) {
  6098. Object.values(newErrors).forEach(
  6099. (error) => unstable_onError(error, {
  6100. location: newState.location,
  6101. params: newState.matches[0]?.params ?? {},
  6102. unstable_pattern: getRoutePattern(newState.matches)
  6103. })
  6104. );
  6105. }
  6106. newState.fetchers.forEach((fetcher, key) => {
  6107. if (fetcher.data !== void 0) {
  6108. fetcherData.current.set(key, fetcher.data);
  6109. }
  6110. });
  6111. deletedFetchers.forEach((key) => fetcherData.current.delete(key));
  6112. warnOnce(
  6113. flushSync === false || reactDomFlushSyncImpl != null,
  6114. 'You provided the `flushSync` option to a router update, but you are not using the `<RouterProvider>` from `react-router/dom` so `ReactDOM.flushSync()` is unavailable. Please update your app to `import { RouterProvider } from "react-router/dom"` and ensure you have `react-dom` installed as a dependency to use the `flushSync` option.'
  6115. );
  6116. let isViewTransitionAvailable = router.window != null && router.window.document != null && typeof router.window.document.startViewTransition === "function";
  6117. warnOnce(
  6118. viewTransitionOpts == null || isViewTransitionAvailable,
  6119. "You provided the `viewTransition` option to a router update, but you do not appear to be running in a DOM environment as `window.startViewTransition` is not available."
  6120. );
  6121. if (!viewTransitionOpts || !isViewTransitionAvailable) {
  6122. if (reactDomFlushSyncImpl && flushSync) {
  6123. reactDomFlushSyncImpl(() => setStateImpl(newState));
  6124. } else if (unstable_useTransitions === false) {
  6125. setStateImpl(newState);
  6126. } else {
  6127. React3.startTransition(() => {
  6128. if (unstable_useTransitions === true) {
  6129. setOptimisticState((s) => getOptimisticRouterState(s, newState));
  6130. }
  6131. setStateImpl(newState);
  6132. });
  6133. }
  6134. return;
  6135. }
  6136. if (reactDomFlushSyncImpl && flushSync) {
  6137. reactDomFlushSyncImpl(() => {
  6138. if (transition) {
  6139. renderDfd?.resolve();
  6140. transition.skipTransition();
  6141. }
  6142. setVtContext({
  6143. isTransitioning: true,
  6144. flushSync: true,
  6145. currentLocation: viewTransitionOpts.currentLocation,
  6146. nextLocation: viewTransitionOpts.nextLocation
  6147. });
  6148. });
  6149. let t = router.window.document.startViewTransition(() => {
  6150. reactDomFlushSyncImpl(() => setStateImpl(newState));
  6151. });
  6152. t.finished.finally(() => {
  6153. reactDomFlushSyncImpl(() => {
  6154. setRenderDfd(void 0);
  6155. setTransition(void 0);
  6156. setPendingState(void 0);
  6157. setVtContext({ isTransitioning: false });
  6158. });
  6159. });
  6160. reactDomFlushSyncImpl(() => setTransition(t));
  6161. return;
  6162. }
  6163. if (transition) {
  6164. renderDfd?.resolve();
  6165. transition.skipTransition();
  6166. setInterruption({
  6167. state: newState,
  6168. currentLocation: viewTransitionOpts.currentLocation,
  6169. nextLocation: viewTransitionOpts.nextLocation
  6170. });
  6171. } else {
  6172. setPendingState(newState);
  6173. setVtContext({
  6174. isTransitioning: true,
  6175. flushSync: false,
  6176. currentLocation: viewTransitionOpts.currentLocation,
  6177. nextLocation: viewTransitionOpts.nextLocation
  6178. });
  6179. }
  6180. },
  6181. [
  6182. router.window,
  6183. reactDomFlushSyncImpl,
  6184. transition,
  6185. renderDfd,
  6186. unstable_useTransitions,
  6187. setOptimisticState,
  6188. unstable_onError
  6189. ]
  6190. );
  6191. React3.useLayoutEffect(() => router.subscribe(setState), [router, setState]);
  6192. React3.useEffect(() => {
  6193. if (vtContext.isTransitioning && !vtContext.flushSync) {
  6194. setRenderDfd(new Deferred());
  6195. }
  6196. }, [vtContext]);
  6197. React3.useEffect(() => {
  6198. if (renderDfd && pendingState && router.window) {
  6199. let newState = pendingState;
  6200. let renderPromise = renderDfd.promise;
  6201. let transition2 = router.window.document.startViewTransition(async () => {
  6202. if (unstable_useTransitions === false) {
  6203. setStateImpl(newState);
  6204. } else {
  6205. React3.startTransition(() => {
  6206. if (unstable_useTransitions === true) {
  6207. setOptimisticState((s) => getOptimisticRouterState(s, newState));
  6208. }
  6209. setStateImpl(newState);
  6210. });
  6211. }
  6212. await renderPromise;
  6213. });
  6214. transition2.finished.finally(() => {
  6215. setRenderDfd(void 0);
  6216. setTransition(void 0);
  6217. setPendingState(void 0);
  6218. setVtContext({ isTransitioning: false });
  6219. });
  6220. setTransition(transition2);
  6221. }
  6222. }, [
  6223. pendingState,
  6224. renderDfd,
  6225. router.window,
  6226. unstable_useTransitions,
  6227. setOptimisticState
  6228. ]);
  6229. React3.useEffect(() => {
  6230. if (renderDfd && pendingState && state.location.key === pendingState.location.key) {
  6231. renderDfd.resolve();
  6232. }
  6233. }, [renderDfd, transition, state.location, pendingState]);
  6234. React3.useEffect(() => {
  6235. if (!vtContext.isTransitioning && interruption) {
  6236. setPendingState(interruption.state);
  6237. setVtContext({
  6238. isTransitioning: true,
  6239. flushSync: false,
  6240. currentLocation: interruption.currentLocation,
  6241. nextLocation: interruption.nextLocation
  6242. });
  6243. setInterruption(void 0);
  6244. }
  6245. }, [vtContext.isTransitioning, interruption]);
  6246. let navigator = React3.useMemo(() => {
  6247. return {
  6248. createHref: router.createHref,
  6249. encodeLocation: router.encodeLocation,
  6250. go: (n) => router.navigate(n),
  6251. push: (to, state2, opts) => router.navigate(to, {
  6252. state: state2,
  6253. preventScrollReset: opts?.preventScrollReset
  6254. }),
  6255. replace: (to, state2, opts) => router.navigate(to, {
  6256. replace: true,
  6257. state: state2,
  6258. preventScrollReset: opts?.preventScrollReset
  6259. })
  6260. };
  6261. }, [router]);
  6262. let basename = router.basename || "/";
  6263. let dataRouterContext = React3.useMemo(
  6264. () => ({
  6265. router,
  6266. navigator,
  6267. static: false,
  6268. basename,
  6269. unstable_onError
  6270. }),
  6271. [router, navigator, basename, unstable_onError]
  6272. );
  6273. return /* @__PURE__ */ React3.createElement(React3.Fragment, null, /* @__PURE__ */ React3.createElement(DataRouterContext.Provider, { value: dataRouterContext }, /* @__PURE__ */ React3.createElement(DataRouterStateContext.Provider, { value: state }, /* @__PURE__ */ React3.createElement(FetchersContext.Provider, { value: fetcherData.current }, /* @__PURE__ */ React3.createElement(ViewTransitionContext.Provider, { value: vtContext }, /* @__PURE__ */ React3.createElement(
  6274. Router,
  6275. {
  6276. basename,
  6277. location: state.location,
  6278. navigationType: state.historyAction,
  6279. navigator,
  6280. unstable_useTransitions: unstable_useTransitions === true
  6281. },
  6282. /* @__PURE__ */ React3.createElement(
  6283. MemoizedDataRoutes,
  6284. {
  6285. routes: router.routes,
  6286. future: router.future,
  6287. state,
  6288. unstable_onError
  6289. }
  6290. )
  6291. ))))), null);
  6292. }
  6293. function getOptimisticRouterState(currentState, newState) {
  6294. return {
  6295. // Don't surface "current location specific" stuff mid-navigation
  6296. // (historyAction, location, matches, loaderData, errors, initialized,
  6297. // restoreScroll, preventScrollReset, blockers, etc.)
  6298. ...currentState,
  6299. // Only surface "pending/in-flight stuff"
  6300. // (navigation, revalidation, actionData, fetchers, )
  6301. navigation: newState.navigation.state !== "idle" ? newState.navigation : currentState.navigation,
  6302. revalidation: newState.revalidation !== "idle" ? newState.revalidation : currentState.revalidation,
  6303. actionData: newState.navigation.state !== "submitting" ? newState.actionData : currentState.actionData,
  6304. fetchers: newState.fetchers
  6305. };
  6306. }
  6307. var MemoizedDataRoutes = React3.memo(DataRoutes);
  6308. function DataRoutes({
  6309. routes,
  6310. future,
  6311. state,
  6312. unstable_onError
  6313. }) {
  6314. return useRoutesImpl(routes, void 0, state, unstable_onError, future);
  6315. }
  6316. function MemoryRouter({
  6317. basename,
  6318. children,
  6319. initialEntries,
  6320. initialIndex,
  6321. unstable_useTransitions
  6322. }) {
  6323. let historyRef = React3.useRef();
  6324. if (historyRef.current == null) {
  6325. historyRef.current = createMemoryHistory({
  6326. initialEntries,
  6327. initialIndex,
  6328. v5Compat: true
  6329. });
  6330. }
  6331. let history = historyRef.current;
  6332. let [state, setStateImpl] = React3.useState({
  6333. action: history.action,
  6334. location: history.location
  6335. });
  6336. let setState = React3.useCallback(
  6337. (newState) => {
  6338. if (unstable_useTransitions === false) {
  6339. setStateImpl(newState);
  6340. } else {
  6341. React3.startTransition(() => setStateImpl(newState));
  6342. }
  6343. },
  6344. [unstable_useTransitions]
  6345. );
  6346. React3.useLayoutEffect(() => history.listen(setState), [history, setState]);
  6347. return /* @__PURE__ */ React3.createElement(
  6348. Router,
  6349. {
  6350. basename,
  6351. children,
  6352. location: state.location,
  6353. navigationType: state.action,
  6354. navigator: history,
  6355. unstable_useTransitions: unstable_useTransitions === true
  6356. }
  6357. );
  6358. }
  6359. function Navigate({
  6360. to,
  6361. replace: replace2,
  6362. state,
  6363. relative
  6364. }) {
  6365. invariant(
  6366. useInRouterContext(),
  6367. // TODO: This error is probably because they somehow have 2 versions of
  6368. // the router loaded. We can help them understand how to avoid that.
  6369. `<Navigate> may be used only in the context of a <Router> component.`
  6370. );
  6371. let { static: isStatic } = React3.useContext(NavigationContext);
  6372. warning(
  6373. !isStatic,
  6374. `<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.`
  6375. );
  6376. let { matches } = React3.useContext(RouteContext);
  6377. let { pathname: locationPathname } = useLocation();
  6378. let navigate = useNavigate();
  6379. let path = resolveTo(
  6380. to,
  6381. getResolveToMatches(matches),
  6382. locationPathname,
  6383. relative === "path"
  6384. );
  6385. let jsonPath = JSON.stringify(path);
  6386. React3.useEffect(() => {
  6387. navigate(JSON.parse(jsonPath), { replace: replace2, state, relative });
  6388. }, [navigate, jsonPath, relative, replace2, state]);
  6389. return null;
  6390. }
  6391. function Outlet(props) {
  6392. return useOutlet(props.context);
  6393. }
  6394. function Route(props) {
  6395. invariant(
  6396. false,
  6397. `A <Route> is only ever to be used as the child of <Routes> element, never rendered directly. Please wrap your <Route> in a <Routes>.`
  6398. );
  6399. }
  6400. function Router({
  6401. basename: basenameProp = "/",
  6402. children = null,
  6403. location: locationProp,
  6404. navigationType = "POP" /* Pop */,
  6405. navigator,
  6406. static: staticProp = false,
  6407. unstable_useTransitions
  6408. }) {
  6409. invariant(
  6410. !useInRouterContext(),
  6411. `You cannot render a <Router> inside another <Router>. You should never have more than one in your app.`
  6412. );
  6413. let basename = basenameProp.replace(/^\/*/, "/");
  6414. let navigationContext = React3.useMemo(
  6415. () => ({
  6416. basename,
  6417. navigator,
  6418. static: staticProp,
  6419. unstable_useTransitions,
  6420. future: {}
  6421. }),
  6422. [basename, navigator, staticProp, unstable_useTransitions]
  6423. );
  6424. if (typeof locationProp === "string") {
  6425. locationProp = parsePath(locationProp);
  6426. }
  6427. let {
  6428. pathname = "/",
  6429. search = "",
  6430. hash = "",
  6431. state = null,
  6432. key = "default"
  6433. } = locationProp;
  6434. let locationContext = React3.useMemo(() => {
  6435. let trailingPathname = stripBasename(pathname, basename);
  6436. if (trailingPathname == null) {
  6437. return null;
  6438. }
  6439. return {
  6440. location: {
  6441. pathname: trailingPathname,
  6442. search,
  6443. hash,
  6444. state,
  6445. key
  6446. },
  6447. navigationType
  6448. };
  6449. }, [basename, pathname, search, hash, state, key, navigationType]);
  6450. warning(
  6451. locationContext != null,
  6452. `<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.`
  6453. );
  6454. if (locationContext == null) {
  6455. return null;
  6456. }
  6457. return /* @__PURE__ */ React3.createElement(NavigationContext.Provider, { value: navigationContext }, /* @__PURE__ */ React3.createElement(LocationContext.Provider, { children, value: locationContext }));
  6458. }
  6459. function Routes({
  6460. children,
  6461. location
  6462. }) {
  6463. return useRoutes(createRoutesFromChildren(children), location);
  6464. }
  6465. function Await({
  6466. children,
  6467. errorElement,
  6468. resolve
  6469. }) {
  6470. let dataRouterContext = React3.useContext(DataRouterContext);
  6471. let dataRouterStateContext = React3.useContext(DataRouterStateContext);
  6472. let onError = React3.useCallback(
  6473. (error, errorInfo) => {
  6474. if (dataRouterContext && dataRouterContext.unstable_onError && dataRouterStateContext) {
  6475. dataRouterContext.unstable_onError(error, {
  6476. location: dataRouterStateContext.location,
  6477. params: dataRouterStateContext.matches[0]?.params || {},
  6478. unstable_pattern: getRoutePattern(dataRouterStateContext.matches),
  6479. errorInfo
  6480. });
  6481. }
  6482. },
  6483. [dataRouterContext, dataRouterStateContext]
  6484. );
  6485. return /* @__PURE__ */ React3.createElement(
  6486. AwaitErrorBoundary,
  6487. {
  6488. resolve,
  6489. errorElement,
  6490. onError
  6491. },
  6492. /* @__PURE__ */ React3.createElement(ResolveAwait, null, children)
  6493. );
  6494. }
  6495. var AwaitErrorBoundary = class extends React3.Component {
  6496. constructor(props) {
  6497. super(props);
  6498. this.state = { error: null };
  6499. }
  6500. static getDerivedStateFromError(error) {
  6501. return { error };
  6502. }
  6503. componentDidCatch(error, errorInfo) {
  6504. if (this.props.onError) {
  6505. this.props.onError(error, errorInfo);
  6506. } else {
  6507. console.error(
  6508. "<Await> caught the following error during render",
  6509. error,
  6510. errorInfo
  6511. );
  6512. }
  6513. }
  6514. render() {
  6515. let { children, errorElement, resolve } = this.props;
  6516. let promise = null;
  6517. let status = 0 /* pending */;
  6518. if (!(resolve instanceof Promise)) {
  6519. status = 1 /* success */;
  6520. promise = Promise.resolve();
  6521. Object.defineProperty(promise, "_tracked", { get: () => true });
  6522. Object.defineProperty(promise, "_data", { get: () => resolve });
  6523. } else if (this.state.error) {
  6524. status = 2 /* error */;
  6525. let renderError = this.state.error;
  6526. promise = Promise.reject().catch(() => {
  6527. });
  6528. Object.defineProperty(promise, "_tracked", { get: () => true });
  6529. Object.defineProperty(promise, "_error", { get: () => renderError });
  6530. } else if (resolve._tracked) {
  6531. promise = resolve;
  6532. status = "_error" in promise ? 2 /* error */ : "_data" in promise ? 1 /* success */ : 0 /* pending */;
  6533. } else {
  6534. status = 0 /* pending */;
  6535. Object.defineProperty(resolve, "_tracked", { get: () => true });
  6536. promise = resolve.then(
  6537. (data2) => Object.defineProperty(resolve, "_data", { get: () => data2 }),
  6538. (error) => {
  6539. this.props.onError?.(error);
  6540. Object.defineProperty(resolve, "_error", { get: () => error });
  6541. }
  6542. );
  6543. }
  6544. if (status === 2 /* error */ && !errorElement) {
  6545. throw promise._error;
  6546. }
  6547. if (status === 2 /* error */) {
  6548. return /* @__PURE__ */ React3.createElement(AwaitContext.Provider, { value: promise, children: errorElement });
  6549. }
  6550. if (status === 1 /* success */) {
  6551. return /* @__PURE__ */ React3.createElement(AwaitContext.Provider, { value: promise, children });
  6552. }
  6553. throw promise;
  6554. }
  6555. };
  6556. function ResolveAwait({
  6557. children
  6558. }) {
  6559. let data2 = useAsyncValue();
  6560. let toRender = typeof children === "function" ? children(data2) : children;
  6561. return /* @__PURE__ */ React3.createElement(React3.Fragment, null, toRender);
  6562. }
  6563. function createRoutesFromChildren(children, parentPath = []) {
  6564. let routes = [];
  6565. React3.Children.forEach(children, (element, index) => {
  6566. if (!React3.isValidElement(element)) {
  6567. return;
  6568. }
  6569. let treePath = [...parentPath, index];
  6570. if (element.type === React3.Fragment) {
  6571. routes.push.apply(
  6572. routes,
  6573. createRoutesFromChildren(element.props.children, treePath)
  6574. );
  6575. return;
  6576. }
  6577. invariant(
  6578. element.type === Route,
  6579. `[${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>`
  6580. );
  6581. invariant(
  6582. !element.props.index || !element.props.children,
  6583. "An index route cannot have child routes."
  6584. );
  6585. let route = {
  6586. id: element.props.id || treePath.join("-"),
  6587. caseSensitive: element.props.caseSensitive,
  6588. element: element.props.element,
  6589. Component: element.props.Component,
  6590. index: element.props.index,
  6591. path: element.props.path,
  6592. middleware: element.props.middleware,
  6593. loader: element.props.loader,
  6594. action: element.props.action,
  6595. hydrateFallbackElement: element.props.hydrateFallbackElement,
  6596. HydrateFallback: element.props.HydrateFallback,
  6597. errorElement: element.props.errorElement,
  6598. ErrorBoundary: element.props.ErrorBoundary,
  6599. hasErrorBoundary: element.props.hasErrorBoundary === true || element.props.ErrorBoundary != null || element.props.errorElement != null,
  6600. shouldRevalidate: element.props.shouldRevalidate,
  6601. handle: element.props.handle,
  6602. lazy: element.props.lazy
  6603. };
  6604. if (element.props.children) {
  6605. route.children = createRoutesFromChildren(
  6606. element.props.children,
  6607. treePath
  6608. );
  6609. }
  6610. routes.push(route);
  6611. });
  6612. return routes;
  6613. }
  6614. var createRoutesFromElements = createRoutesFromChildren;
  6615. function renderMatches(matches) {
  6616. return _renderMatches(matches);
  6617. }
  6618. function useRouteComponentProps() {
  6619. return {
  6620. params: useParams(),
  6621. loaderData: useLoaderData(),
  6622. actionData: useActionData(),
  6623. matches: useMatches()
  6624. };
  6625. }
  6626. function WithComponentProps({
  6627. children
  6628. }) {
  6629. const props = useRouteComponentProps();
  6630. return React3.cloneElement(children, props);
  6631. }
  6632. function withComponentProps(Component4) {
  6633. return function WithComponentProps2() {
  6634. const props = useRouteComponentProps();
  6635. return React3.createElement(Component4, props);
  6636. };
  6637. }
  6638. function useHydrateFallbackProps() {
  6639. return {
  6640. params: useParams(),
  6641. loaderData: useLoaderData(),
  6642. actionData: useActionData()
  6643. };
  6644. }
  6645. function WithHydrateFallbackProps({
  6646. children
  6647. }) {
  6648. const props = useHydrateFallbackProps();
  6649. return React3.cloneElement(children, props);
  6650. }
  6651. function withHydrateFallbackProps(HydrateFallback) {
  6652. return function WithHydrateFallbackProps2() {
  6653. const props = useHydrateFallbackProps();
  6654. return React3.createElement(HydrateFallback, props);
  6655. };
  6656. }
  6657. function useErrorBoundaryProps() {
  6658. return {
  6659. params: useParams(),
  6660. loaderData: useLoaderData(),
  6661. actionData: useActionData(),
  6662. error: useRouteError()
  6663. };
  6664. }
  6665. function WithErrorBoundaryProps({
  6666. children
  6667. }) {
  6668. const props = useErrorBoundaryProps();
  6669. return React3.cloneElement(children, props);
  6670. }
  6671. function withErrorBoundaryProps(ErrorBoundary) {
  6672. return function WithErrorBoundaryProps2() {
  6673. const props = useErrorBoundaryProps();
  6674. return React3.createElement(ErrorBoundary, props);
  6675. };
  6676. }
  6677. // lib/dom/dom.ts
  6678. var defaultMethod = "get";
  6679. var defaultEncType = "application/x-www-form-urlencoded";
  6680. function isHtmlElement(object) {
  6681. return typeof HTMLElement !== "undefined" && object instanceof HTMLElement;
  6682. }
  6683. function isButtonElement(object) {
  6684. return isHtmlElement(object) && object.tagName.toLowerCase() === "button";
  6685. }
  6686. function isFormElement(object) {
  6687. return isHtmlElement(object) && object.tagName.toLowerCase() === "form";
  6688. }
  6689. function isInputElement(object) {
  6690. return isHtmlElement(object) && object.tagName.toLowerCase() === "input";
  6691. }
  6692. function isModifiedEvent(event) {
  6693. return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey);
  6694. }
  6695. function shouldProcessLinkClick(event, target) {
  6696. return event.button === 0 && // Ignore everything but left clicks
  6697. (!target || target === "_self") && // Let browser handle "target=_blank" etc.
  6698. !isModifiedEvent(event);
  6699. }
  6700. function createSearchParams(init = "") {
  6701. return new URLSearchParams(
  6702. typeof init === "string" || Array.isArray(init) || init instanceof URLSearchParams ? init : Object.keys(init).reduce((memo2, key) => {
  6703. let value = init[key];
  6704. return memo2.concat(
  6705. Array.isArray(value) ? value.map((v) => [key, v]) : [[key, value]]
  6706. );
  6707. }, [])
  6708. );
  6709. }
  6710. function getSearchParamsForLocation(locationSearch, defaultSearchParams) {
  6711. let searchParams = createSearchParams(locationSearch);
  6712. if (defaultSearchParams) {
  6713. defaultSearchParams.forEach((_, key) => {
  6714. if (!searchParams.has(key)) {
  6715. defaultSearchParams.getAll(key).forEach((value) => {
  6716. searchParams.append(key, value);
  6717. });
  6718. }
  6719. });
  6720. }
  6721. return searchParams;
  6722. }
  6723. var _formDataSupportsSubmitter = null;
  6724. function isFormDataSubmitterSupported() {
  6725. if (_formDataSupportsSubmitter === null) {
  6726. try {
  6727. new FormData(
  6728. document.createElement("form"),
  6729. // @ts-expect-error if FormData supports the submitter parameter, this will throw
  6730. 0
  6731. );
  6732. _formDataSupportsSubmitter = false;
  6733. } catch (e) {
  6734. _formDataSupportsSubmitter = true;
  6735. }
  6736. }
  6737. return _formDataSupportsSubmitter;
  6738. }
  6739. var supportedFormEncTypes = /* @__PURE__ */ new Set([
  6740. "application/x-www-form-urlencoded",
  6741. "multipart/form-data",
  6742. "text/plain"
  6743. ]);
  6744. function getFormEncType(encType) {
  6745. if (encType != null && !supportedFormEncTypes.has(encType)) {
  6746. warning(
  6747. false,
  6748. `"${encType}" is not a valid \`encType\` for \`<Form>\`/\`<fetcher.Form>\` and will default to "${defaultEncType}"`
  6749. );
  6750. return null;
  6751. }
  6752. return encType;
  6753. }
  6754. function getFormSubmissionInfo(target, basename) {
  6755. let method;
  6756. let action;
  6757. let encType;
  6758. let formData;
  6759. let body;
  6760. if (isFormElement(target)) {
  6761. let attr = target.getAttribute("action");
  6762. action = attr ? stripBasename(attr, basename) : null;
  6763. method = target.getAttribute("method") || defaultMethod;
  6764. encType = getFormEncType(target.getAttribute("enctype")) || defaultEncType;
  6765. formData = new FormData(target);
  6766. } else if (isButtonElement(target) || isInputElement(target) && (target.type === "submit" || target.type === "image")) {
  6767. let form = target.form;
  6768. if (form == null) {
  6769. throw new Error(
  6770. `Cannot submit a <button> or <input type="submit"> without a <form>`
  6771. );
  6772. }
  6773. let attr = target.getAttribute("formaction") || form.getAttribute("action");
  6774. action = attr ? stripBasename(attr, basename) : null;
  6775. method = target.getAttribute("formmethod") || form.getAttribute("method") || defaultMethod;
  6776. encType = getFormEncType(target.getAttribute("formenctype")) || getFormEncType(form.getAttribute("enctype")) || defaultEncType;
  6777. formData = new FormData(form, target);
  6778. if (!isFormDataSubmitterSupported()) {
  6779. let { name, type, value } = target;
  6780. if (type === "image") {
  6781. let prefix = name ? `${name}.` : "";
  6782. formData.append(`${prefix}x`, "0");
  6783. formData.append(`${prefix}y`, "0");
  6784. } else if (name) {
  6785. formData.append(name, value);
  6786. }
  6787. }
  6788. } else if (isHtmlElement(target)) {
  6789. throw new Error(
  6790. `Cannot submit element that is not <form>, <button>, or <input type="submit|image">`
  6791. );
  6792. } else {
  6793. method = defaultMethod;
  6794. action = null;
  6795. encType = defaultEncType;
  6796. body = target;
  6797. }
  6798. if (formData && encType === "text/plain") {
  6799. body = formData;
  6800. formData = void 0;
  6801. }
  6802. return { action, method: method.toLowerCase(), encType, formData, body };
  6803. }
  6804. // lib/dom/ssr/single-fetch.tsx
  6805. import * as React4 from "react";
  6806. // vendor/turbo-stream-v2/utils.ts
  6807. var HOLE = -1;
  6808. var NAN = -2;
  6809. var NEGATIVE_INFINITY = -3;
  6810. var NEGATIVE_ZERO = -4;
  6811. var NULL = -5;
  6812. var POSITIVE_INFINITY = -6;
  6813. var UNDEFINED = -7;
  6814. var TYPE_BIGINT = "B";
  6815. var TYPE_DATE = "D";
  6816. var TYPE_ERROR = "E";
  6817. var TYPE_MAP = "M";
  6818. var TYPE_NULL_OBJECT = "N";
  6819. var TYPE_PROMISE = "P";
  6820. var TYPE_REGEXP = "R";
  6821. var TYPE_SET = "S";
  6822. var TYPE_SYMBOL = "Y";
  6823. var TYPE_URL = "U";
  6824. var TYPE_PREVIOUS_RESOLVED = "Z";
  6825. var Deferred2 = class {
  6826. constructor() {
  6827. this.promise = new Promise((resolve, reject) => {
  6828. this.resolve = resolve;
  6829. this.reject = reject;
  6830. });
  6831. }
  6832. };
  6833. function createLineSplittingTransform() {
  6834. const decoder = new TextDecoder();
  6835. let leftover = "";
  6836. return new TransformStream({
  6837. transform(chunk, controller) {
  6838. const str = decoder.decode(chunk, { stream: true });
  6839. const parts = (leftover + str).split("\n");
  6840. leftover = parts.pop() || "";
  6841. for (const part of parts) {
  6842. controller.enqueue(part);
  6843. }
  6844. },
  6845. flush(controller) {
  6846. if (leftover) {
  6847. controller.enqueue(leftover);
  6848. }
  6849. }
  6850. });
  6851. }
  6852. // vendor/turbo-stream-v2/flatten.ts
  6853. function flatten(input) {
  6854. const { indices } = this;
  6855. const existing = indices.get(input);
  6856. if (existing) return [existing];
  6857. if (input === void 0) return UNDEFINED;
  6858. if (input === null) return NULL;
  6859. if (Number.isNaN(input)) return NAN;
  6860. if (input === Number.POSITIVE_INFINITY) return POSITIVE_INFINITY;
  6861. if (input === Number.NEGATIVE_INFINITY) return NEGATIVE_INFINITY;
  6862. if (input === 0 && 1 / input < 0) return NEGATIVE_ZERO;
  6863. const index = this.index++;
  6864. indices.set(input, index);
  6865. stringify.call(this, input, index);
  6866. return index;
  6867. }
  6868. function stringify(input, index) {
  6869. const { deferred, plugins, postPlugins } = this;
  6870. const str = this.stringified;
  6871. const stack = [[input, index]];
  6872. while (stack.length > 0) {
  6873. const [input2, index2] = stack.pop();
  6874. const partsForObj = (obj) => Object.keys(obj).map((k) => `"_${flatten.call(this, k)}":${flatten.call(this, obj[k])}`).join(",");
  6875. let error = null;
  6876. switch (typeof input2) {
  6877. case "boolean":
  6878. case "number":
  6879. case "string":
  6880. str[index2] = JSON.stringify(input2);
  6881. break;
  6882. case "bigint":
  6883. str[index2] = `["${TYPE_BIGINT}","${input2}"]`;
  6884. break;
  6885. case "symbol": {
  6886. const keyFor = Symbol.keyFor(input2);
  6887. if (!keyFor) {
  6888. error = new Error(
  6889. "Cannot encode symbol unless created with Symbol.for()"
  6890. );
  6891. } else {
  6892. str[index2] = `["${TYPE_SYMBOL}",${JSON.stringify(keyFor)}]`;
  6893. }
  6894. break;
  6895. }
  6896. case "object": {
  6897. if (!input2) {
  6898. str[index2] = `${NULL}`;
  6899. break;
  6900. }
  6901. const isArray = Array.isArray(input2);
  6902. let pluginHandled = false;
  6903. if (!isArray && plugins) {
  6904. for (const plugin of plugins) {
  6905. const pluginResult = plugin(input2);
  6906. if (Array.isArray(pluginResult)) {
  6907. pluginHandled = true;
  6908. const [pluginIdentifier, ...rest] = pluginResult;
  6909. str[index2] = `[${JSON.stringify(pluginIdentifier)}`;
  6910. if (rest.length > 0) {
  6911. str[index2] += `,${rest.map((v) => flatten.call(this, v)).join(",")}`;
  6912. }
  6913. str[index2] += "]";
  6914. break;
  6915. }
  6916. }
  6917. }
  6918. if (!pluginHandled) {
  6919. let result = isArray ? "[" : "{";
  6920. if (isArray) {
  6921. for (let i = 0; i < input2.length; i++)
  6922. result += (i ? "," : "") + (i in input2 ? flatten.call(this, input2[i]) : HOLE);
  6923. str[index2] = `${result}]`;
  6924. } else if (input2 instanceof Date) {
  6925. const dateTime = input2.getTime();
  6926. str[index2] = `["${TYPE_DATE}",${Number.isNaN(dateTime) ? JSON.stringify("invalid") : dateTime}]`;
  6927. } else if (input2 instanceof URL) {
  6928. str[index2] = `["${TYPE_URL}",${JSON.stringify(input2.href)}]`;
  6929. } else if (input2 instanceof RegExp) {
  6930. str[index2] = `["${TYPE_REGEXP}",${JSON.stringify(
  6931. input2.source
  6932. )},${JSON.stringify(input2.flags)}]`;
  6933. } else if (input2 instanceof Set) {
  6934. if (input2.size > 0) {
  6935. str[index2] = `["${TYPE_SET}",${[...input2].map((val) => flatten.call(this, val)).join(",")}]`;
  6936. } else {
  6937. str[index2] = `["${TYPE_SET}"]`;
  6938. }
  6939. } else if (input2 instanceof Map) {
  6940. if (input2.size > 0) {
  6941. str[index2] = `["${TYPE_MAP}",${[...input2].flatMap(([k, v]) => [
  6942. flatten.call(this, k),
  6943. flatten.call(this, v)
  6944. ]).join(",")}]`;
  6945. } else {
  6946. str[index2] = `["${TYPE_MAP}"]`;
  6947. }
  6948. } else if (input2 instanceof Promise) {
  6949. str[index2] = `["${TYPE_PROMISE}",${index2}]`;
  6950. deferred[index2] = input2;
  6951. } else if (input2 instanceof Error) {
  6952. str[index2] = `["${TYPE_ERROR}",${JSON.stringify(input2.message)}`;
  6953. if (input2.name !== "Error") {
  6954. str[index2] += `,${JSON.stringify(input2.name)}`;
  6955. }
  6956. str[index2] += "]";
  6957. } else if (Object.getPrototypeOf(input2) === null) {
  6958. str[index2] = `["${TYPE_NULL_OBJECT}",{${partsForObj(input2)}}]`;
  6959. } else if (isPlainObject2(input2)) {
  6960. str[index2] = `{${partsForObj(input2)}}`;
  6961. } else {
  6962. error = new Error("Cannot encode object with prototype");
  6963. }
  6964. }
  6965. break;
  6966. }
  6967. default: {
  6968. const isArray = Array.isArray(input2);
  6969. let pluginHandled = false;
  6970. if (!isArray && plugins) {
  6971. for (const plugin of plugins) {
  6972. const pluginResult = plugin(input2);
  6973. if (Array.isArray(pluginResult)) {
  6974. pluginHandled = true;
  6975. const [pluginIdentifier, ...rest] = pluginResult;
  6976. str[index2] = `[${JSON.stringify(pluginIdentifier)}`;
  6977. if (rest.length > 0) {
  6978. str[index2] += `,${rest.map((v) => flatten.call(this, v)).join(",")}`;
  6979. }
  6980. str[index2] += "]";
  6981. break;
  6982. }
  6983. }
  6984. }
  6985. if (!pluginHandled) {
  6986. error = new Error("Cannot encode function or unexpected type");
  6987. }
  6988. }
  6989. }
  6990. if (error) {
  6991. let pluginHandled = false;
  6992. if (postPlugins) {
  6993. for (const plugin of postPlugins) {
  6994. const pluginResult = plugin(input2);
  6995. if (Array.isArray(pluginResult)) {
  6996. pluginHandled = true;
  6997. const [pluginIdentifier, ...rest] = pluginResult;
  6998. str[index2] = `[${JSON.stringify(pluginIdentifier)}`;
  6999. if (rest.length > 0) {
  7000. str[index2] += `,${rest.map((v) => flatten.call(this, v)).join(",")}`;
  7001. }
  7002. str[index2] += "]";
  7003. break;
  7004. }
  7005. }
  7006. }
  7007. if (!pluginHandled) {
  7008. throw error;
  7009. }
  7010. }
  7011. }
  7012. }
  7013. var objectProtoNames2 = Object.getOwnPropertyNames(Object.prototype).sort().join("\0");
  7014. function isPlainObject2(thing) {
  7015. const proto = Object.getPrototypeOf(thing);
  7016. return proto === Object.prototype || proto === null || Object.getOwnPropertyNames(proto).sort().join("\0") === objectProtoNames2;
  7017. }
  7018. // vendor/turbo-stream-v2/unflatten.ts
  7019. var globalObj = typeof window !== "undefined" ? window : typeof globalThis !== "undefined" ? globalThis : void 0;
  7020. function unflatten(parsed) {
  7021. const { hydrated, values } = this;
  7022. if (typeof parsed === "number") return hydrate.call(this, parsed);
  7023. if (!Array.isArray(parsed) || !parsed.length) throw new SyntaxError();
  7024. const startIndex = values.length;
  7025. for (const value of parsed) {
  7026. values.push(value);
  7027. }
  7028. hydrated.length = values.length;
  7029. return hydrate.call(this, startIndex);
  7030. }
  7031. function hydrate(index) {
  7032. const { hydrated, values, deferred, plugins } = this;
  7033. let result;
  7034. const stack = [
  7035. [
  7036. index,
  7037. (v) => {
  7038. result = v;
  7039. }
  7040. ]
  7041. ];
  7042. let postRun = [];
  7043. while (stack.length > 0) {
  7044. const [index2, set] = stack.pop();
  7045. switch (index2) {
  7046. case UNDEFINED:
  7047. set(void 0);
  7048. continue;
  7049. case NULL:
  7050. set(null);
  7051. continue;
  7052. case NAN:
  7053. set(NaN);
  7054. continue;
  7055. case POSITIVE_INFINITY:
  7056. set(Infinity);
  7057. continue;
  7058. case NEGATIVE_INFINITY:
  7059. set(-Infinity);
  7060. continue;
  7061. case NEGATIVE_ZERO:
  7062. set(-0);
  7063. continue;
  7064. }
  7065. if (hydrated[index2]) {
  7066. set(hydrated[index2]);
  7067. continue;
  7068. }
  7069. const value = values[index2];
  7070. if (!value || typeof value !== "object") {
  7071. hydrated[index2] = value;
  7072. set(value);
  7073. continue;
  7074. }
  7075. if (Array.isArray(value)) {
  7076. if (typeof value[0] === "string") {
  7077. const [type, b, c] = value;
  7078. switch (type) {
  7079. case TYPE_DATE:
  7080. set(hydrated[index2] = new Date(b));
  7081. continue;
  7082. case TYPE_URL:
  7083. set(hydrated[index2] = new URL(b));
  7084. continue;
  7085. case TYPE_BIGINT:
  7086. set(hydrated[index2] = BigInt(b));
  7087. continue;
  7088. case TYPE_REGEXP:
  7089. set(hydrated[index2] = new RegExp(b, c));
  7090. continue;
  7091. case TYPE_SYMBOL:
  7092. set(hydrated[index2] = Symbol.for(b));
  7093. continue;
  7094. case TYPE_SET:
  7095. const newSet = /* @__PURE__ */ new Set();
  7096. hydrated[index2] = newSet;
  7097. for (let i = value.length - 1; i > 0; i--)
  7098. stack.push([
  7099. value[i],
  7100. (v) => {
  7101. newSet.add(v);
  7102. }
  7103. ]);
  7104. set(newSet);
  7105. continue;
  7106. case TYPE_MAP:
  7107. const map = /* @__PURE__ */ new Map();
  7108. hydrated[index2] = map;
  7109. for (let i = value.length - 2; i > 0; i -= 2) {
  7110. const r = [];
  7111. stack.push([
  7112. value[i + 1],
  7113. (v) => {
  7114. r[1] = v;
  7115. }
  7116. ]);
  7117. stack.push([
  7118. value[i],
  7119. (k) => {
  7120. r[0] = k;
  7121. }
  7122. ]);
  7123. postRun.push(() => {
  7124. map.set(r[0], r[1]);
  7125. });
  7126. }
  7127. set(map);
  7128. continue;
  7129. case TYPE_NULL_OBJECT:
  7130. const obj = /* @__PURE__ */ Object.create(null);
  7131. hydrated[index2] = obj;
  7132. for (const key of Object.keys(b).reverse()) {
  7133. const r = [];
  7134. stack.push([
  7135. b[key],
  7136. (v) => {
  7137. r[1] = v;
  7138. }
  7139. ]);
  7140. stack.push([
  7141. Number(key.slice(1)),
  7142. (k) => {
  7143. r[0] = k;
  7144. }
  7145. ]);
  7146. postRun.push(() => {
  7147. obj[r[0]] = r[1];
  7148. });
  7149. }
  7150. set(obj);
  7151. continue;
  7152. case TYPE_PROMISE:
  7153. if (hydrated[b]) {
  7154. set(hydrated[index2] = hydrated[b]);
  7155. } else {
  7156. const d = new Deferred2();
  7157. deferred[b] = d;
  7158. set(hydrated[index2] = d.promise);
  7159. }
  7160. continue;
  7161. case TYPE_ERROR:
  7162. const [, message, errorType] = value;
  7163. let error = errorType && globalObj && globalObj[errorType] ? new globalObj[errorType](message) : new Error(message);
  7164. hydrated[index2] = error;
  7165. set(error);
  7166. continue;
  7167. case TYPE_PREVIOUS_RESOLVED:
  7168. set(hydrated[index2] = hydrated[b]);
  7169. continue;
  7170. default:
  7171. if (Array.isArray(plugins)) {
  7172. const r = [];
  7173. const vals = value.slice(1);
  7174. for (let i = 0; i < vals.length; i++) {
  7175. const v = vals[i];
  7176. stack.push([
  7177. v,
  7178. (v2) => {
  7179. r[i] = v2;
  7180. }
  7181. ]);
  7182. }
  7183. postRun.push(() => {
  7184. for (const plugin of plugins) {
  7185. const result2 = plugin(value[0], ...r);
  7186. if (result2) {
  7187. set(hydrated[index2] = result2.value);
  7188. return;
  7189. }
  7190. }
  7191. throw new SyntaxError();
  7192. });
  7193. continue;
  7194. }
  7195. throw new SyntaxError();
  7196. }
  7197. } else {
  7198. const array = [];
  7199. hydrated[index2] = array;
  7200. for (let i = 0; i < value.length; i++) {
  7201. const n = value[i];
  7202. if (n !== HOLE) {
  7203. stack.push([
  7204. n,
  7205. (v) => {
  7206. array[i] = v;
  7207. }
  7208. ]);
  7209. }
  7210. }
  7211. set(array);
  7212. continue;
  7213. }
  7214. } else {
  7215. const object = {};
  7216. hydrated[index2] = object;
  7217. for (const key of Object.keys(value).reverse()) {
  7218. const r = [];
  7219. stack.push([
  7220. value[key],
  7221. (v) => {
  7222. r[1] = v;
  7223. }
  7224. ]);
  7225. stack.push([
  7226. Number(key.slice(1)),
  7227. (k) => {
  7228. r[0] = k;
  7229. }
  7230. ]);
  7231. postRun.push(() => {
  7232. object[r[0]] = r[1];
  7233. });
  7234. }
  7235. set(object);
  7236. continue;
  7237. }
  7238. }
  7239. while (postRun.length > 0) {
  7240. postRun.pop()();
  7241. }
  7242. return result;
  7243. }
  7244. // vendor/turbo-stream-v2/turbo-stream.ts
  7245. async function decode(readable, options) {
  7246. const { plugins } = options ?? {};
  7247. const done = new Deferred2();
  7248. const reader = readable.pipeThrough(createLineSplittingTransform()).getReader();
  7249. const decoder = {
  7250. values: [],
  7251. hydrated: [],
  7252. deferred: {},
  7253. plugins
  7254. };
  7255. const decoded = await decodeInitial.call(decoder, reader);
  7256. let donePromise = done.promise;
  7257. if (decoded.done) {
  7258. done.resolve();
  7259. } else {
  7260. donePromise = decodeDeferred.call(decoder, reader).then(done.resolve).catch((reason) => {
  7261. for (const deferred of Object.values(decoder.deferred)) {
  7262. deferred.reject(reason);
  7263. }
  7264. done.reject(reason);
  7265. });
  7266. }
  7267. return {
  7268. done: donePromise.then(() => reader.closed),
  7269. value: decoded.value
  7270. };
  7271. }
  7272. async function decodeInitial(reader) {
  7273. const read = await reader.read();
  7274. if (!read.value) {
  7275. throw new SyntaxError();
  7276. }
  7277. let line;
  7278. try {
  7279. line = JSON.parse(read.value);
  7280. } catch (reason) {
  7281. throw new SyntaxError();
  7282. }
  7283. return {
  7284. done: read.done,
  7285. value: unflatten.call(this, line)
  7286. };
  7287. }
  7288. async function decodeDeferred(reader) {
  7289. let read = await reader.read();
  7290. while (!read.done) {
  7291. if (!read.value) continue;
  7292. const line = read.value;
  7293. switch (line[0]) {
  7294. case TYPE_PROMISE: {
  7295. const colonIndex = line.indexOf(":");
  7296. const deferredId = Number(line.slice(1, colonIndex));
  7297. const deferred = this.deferred[deferredId];
  7298. if (!deferred) {
  7299. throw new Error(`Deferred ID ${deferredId} not found in stream`);
  7300. }
  7301. const lineData = line.slice(colonIndex + 1);
  7302. let jsonLine;
  7303. try {
  7304. jsonLine = JSON.parse(lineData);
  7305. } catch (reason) {
  7306. throw new SyntaxError();
  7307. }
  7308. const value = unflatten.call(this, jsonLine);
  7309. deferred.resolve(value);
  7310. break;
  7311. }
  7312. case TYPE_ERROR: {
  7313. const colonIndex = line.indexOf(":");
  7314. const deferredId = Number(line.slice(1, colonIndex));
  7315. const deferred = this.deferred[deferredId];
  7316. if (!deferred) {
  7317. throw new Error(`Deferred ID ${deferredId} not found in stream`);
  7318. }
  7319. const lineData = line.slice(colonIndex + 1);
  7320. let jsonLine;
  7321. try {
  7322. jsonLine = JSON.parse(lineData);
  7323. } catch (reason) {
  7324. throw new SyntaxError();
  7325. }
  7326. const value = unflatten.call(this, jsonLine);
  7327. deferred.reject(value);
  7328. break;
  7329. }
  7330. default:
  7331. throw new SyntaxError();
  7332. }
  7333. read = await reader.read();
  7334. }
  7335. }
  7336. function encode(input, options) {
  7337. const { plugins, postPlugins, signal } = options ?? {};
  7338. const encoder = {
  7339. deferred: {},
  7340. index: 0,
  7341. indices: /* @__PURE__ */ new Map(),
  7342. stringified: [],
  7343. plugins,
  7344. postPlugins,
  7345. signal
  7346. };
  7347. const textEncoder = new TextEncoder();
  7348. let lastSentIndex = 0;
  7349. const readable = new ReadableStream({
  7350. async start(controller) {
  7351. const id = flatten.call(encoder, input);
  7352. if (Array.isArray(id)) {
  7353. throw new Error("This should never happen");
  7354. }
  7355. if (id < 0) {
  7356. controller.enqueue(textEncoder.encode(`${id}
  7357. `));
  7358. } else {
  7359. controller.enqueue(
  7360. textEncoder.encode(`[${encoder.stringified.join(",")}]
  7361. `)
  7362. );
  7363. lastSentIndex = encoder.stringified.length - 1;
  7364. }
  7365. const seenPromises = /* @__PURE__ */ new WeakSet();
  7366. if (Object.keys(encoder.deferred).length) {
  7367. let raceDone;
  7368. const racePromise = new Promise((resolve, reject) => {
  7369. raceDone = resolve;
  7370. if (signal) {
  7371. const rejectPromise = () => reject(signal.reason || new Error("Signal was aborted."));
  7372. if (signal.aborted) {
  7373. rejectPromise();
  7374. } else {
  7375. signal.addEventListener("abort", (event) => {
  7376. rejectPromise();
  7377. });
  7378. }
  7379. }
  7380. });
  7381. while (Object.keys(encoder.deferred).length > 0) {
  7382. for (const [deferredId, deferred] of Object.entries(
  7383. encoder.deferred
  7384. )) {
  7385. if (seenPromises.has(deferred)) continue;
  7386. seenPromises.add(
  7387. // biome-ignore lint/suspicious/noAssignInExpressions: <explanation>
  7388. encoder.deferred[Number(deferredId)] = Promise.race([
  7389. racePromise,
  7390. deferred
  7391. ]).then(
  7392. (resolved) => {
  7393. const id2 = flatten.call(encoder, resolved);
  7394. if (Array.isArray(id2)) {
  7395. controller.enqueue(
  7396. textEncoder.encode(
  7397. `${TYPE_PROMISE}${deferredId}:[["${TYPE_PREVIOUS_RESOLVED}",${id2[0]}]]
  7398. `
  7399. )
  7400. );
  7401. encoder.index++;
  7402. lastSentIndex++;
  7403. } else if (id2 < 0) {
  7404. controller.enqueue(
  7405. textEncoder.encode(
  7406. `${TYPE_PROMISE}${deferredId}:${id2}
  7407. `
  7408. )
  7409. );
  7410. } else {
  7411. const values = encoder.stringified.slice(lastSentIndex + 1).join(",");
  7412. controller.enqueue(
  7413. textEncoder.encode(
  7414. `${TYPE_PROMISE}${deferredId}:[${values}]
  7415. `
  7416. )
  7417. );
  7418. lastSentIndex = encoder.stringified.length - 1;
  7419. }
  7420. },
  7421. (reason) => {
  7422. if (!reason || typeof reason !== "object" || !(reason instanceof Error)) {
  7423. reason = new Error("An unknown error occurred");
  7424. }
  7425. const id2 = flatten.call(encoder, reason);
  7426. if (Array.isArray(id2)) {
  7427. controller.enqueue(
  7428. textEncoder.encode(
  7429. `${TYPE_ERROR}${deferredId}:[["${TYPE_PREVIOUS_RESOLVED}",${id2[0]}]]
  7430. `
  7431. )
  7432. );
  7433. encoder.index++;
  7434. lastSentIndex++;
  7435. } else if (id2 < 0) {
  7436. controller.enqueue(
  7437. textEncoder.encode(
  7438. `${TYPE_ERROR}${deferredId}:${id2}
  7439. `
  7440. )
  7441. );
  7442. } else {
  7443. const values = encoder.stringified.slice(lastSentIndex + 1).join(",");
  7444. controller.enqueue(
  7445. textEncoder.encode(
  7446. `${TYPE_ERROR}${deferredId}:[${values}]
  7447. `
  7448. )
  7449. );
  7450. lastSentIndex = encoder.stringified.length - 1;
  7451. }
  7452. }
  7453. ).finally(() => {
  7454. delete encoder.deferred[Number(deferredId)];
  7455. })
  7456. );
  7457. }
  7458. await Promise.race(Object.values(encoder.deferred));
  7459. }
  7460. raceDone();
  7461. }
  7462. await Promise.all(Object.values(encoder.deferred));
  7463. controller.close();
  7464. }
  7465. });
  7466. return readable;
  7467. }
  7468. // lib/dom/ssr/data.ts
  7469. async function createRequestInit(request) {
  7470. let init = { signal: request.signal };
  7471. if (request.method !== "GET") {
  7472. init.method = request.method;
  7473. let contentType = request.headers.get("Content-Type");
  7474. if (contentType && /\bapplication\/json\b/.test(contentType)) {
  7475. init.headers = { "Content-Type": contentType };
  7476. init.body = JSON.stringify(await request.json());
  7477. } else if (contentType && /\btext\/plain\b/.test(contentType)) {
  7478. init.headers = { "Content-Type": contentType };
  7479. init.body = await request.text();
  7480. } else if (contentType && /\bapplication\/x-www-form-urlencoded\b/.test(contentType)) {
  7481. init.body = new URLSearchParams(await request.text());
  7482. } else {
  7483. init.body = await request.formData();
  7484. }
  7485. }
  7486. return init;
  7487. }
  7488. // lib/dom/ssr/markup.ts
  7489. var ESCAPE_LOOKUP = {
  7490. "&": "\\u0026",
  7491. ">": "\\u003e",
  7492. "<": "\\u003c",
  7493. "\u2028": "\\u2028",
  7494. "\u2029": "\\u2029"
  7495. };
  7496. var ESCAPE_REGEX = /[&><\u2028\u2029]/g;
  7497. function escapeHtml(html) {
  7498. return html.replace(ESCAPE_REGEX, (match) => ESCAPE_LOOKUP[match]);
  7499. }
  7500. // lib/dom/ssr/invariant.ts
  7501. function invariant2(value, message) {
  7502. if (value === false || value === null || typeof value === "undefined") {
  7503. throw new Error(message);
  7504. }
  7505. }
  7506. // lib/dom/ssr/single-fetch.tsx
  7507. var SingleFetchRedirectSymbol = Symbol("SingleFetchRedirect");
  7508. var SingleFetchNoResultError = class extends Error {
  7509. };
  7510. var SINGLE_FETCH_REDIRECT_STATUS = 202;
  7511. var NO_BODY_STATUS_CODES = /* @__PURE__ */ new Set([100, 101, 204, 205]);
  7512. function StreamTransfer({
  7513. context,
  7514. identifier,
  7515. reader,
  7516. textDecoder,
  7517. nonce
  7518. }) {
  7519. if (!context.renderMeta || !context.renderMeta.didRenderScripts) {
  7520. return null;
  7521. }
  7522. if (!context.renderMeta.streamCache) {
  7523. context.renderMeta.streamCache = {};
  7524. }
  7525. let { streamCache } = context.renderMeta;
  7526. let promise = streamCache[identifier];
  7527. if (!promise) {
  7528. promise = streamCache[identifier] = reader.read().then((result) => {
  7529. streamCache[identifier].result = {
  7530. done: result.done,
  7531. value: textDecoder.decode(result.value, { stream: true })
  7532. };
  7533. }).catch((e) => {
  7534. streamCache[identifier].error = e;
  7535. });
  7536. }
  7537. if (promise.error) {
  7538. throw promise.error;
  7539. }
  7540. if (promise.result === void 0) {
  7541. throw promise;
  7542. }
  7543. let { done, value } = promise.result;
  7544. let scriptTag = value ? /* @__PURE__ */ React4.createElement(
  7545. "script",
  7546. {
  7547. nonce,
  7548. dangerouslySetInnerHTML: {
  7549. __html: `window.__reactRouterContext.streamController.enqueue(${escapeHtml(
  7550. JSON.stringify(value)
  7551. )});`
  7552. }
  7553. }
  7554. ) : null;
  7555. if (done) {
  7556. return /* @__PURE__ */ React4.createElement(React4.Fragment, null, scriptTag, /* @__PURE__ */ React4.createElement(
  7557. "script",
  7558. {
  7559. nonce,
  7560. dangerouslySetInnerHTML: {
  7561. __html: `window.__reactRouterContext.streamController.close();`
  7562. }
  7563. }
  7564. ));
  7565. } else {
  7566. return /* @__PURE__ */ React4.createElement(React4.Fragment, null, scriptTag, /* @__PURE__ */ React4.createElement(React4.Suspense, null, /* @__PURE__ */ React4.createElement(
  7567. StreamTransfer,
  7568. {
  7569. context,
  7570. identifier: identifier + 1,
  7571. reader,
  7572. textDecoder,
  7573. nonce
  7574. }
  7575. )));
  7576. }
  7577. }
  7578. function getTurboStreamSingleFetchDataStrategy(getRouter, manifest, routeModules, ssr, basename) {
  7579. let dataStrategy = getSingleFetchDataStrategyImpl(
  7580. getRouter,
  7581. (match) => {
  7582. let manifestRoute = manifest.routes[match.route.id];
  7583. invariant2(manifestRoute, "Route not found in manifest");
  7584. let routeModule = routeModules[match.route.id];
  7585. return {
  7586. hasLoader: manifestRoute.hasLoader,
  7587. hasClientLoader: manifestRoute.hasClientLoader,
  7588. hasShouldRevalidate: Boolean(routeModule?.shouldRevalidate)
  7589. };
  7590. },
  7591. fetchAndDecodeViaTurboStream,
  7592. ssr,
  7593. basename
  7594. );
  7595. return async (args) => args.runClientMiddleware(dataStrategy);
  7596. }
  7597. function getSingleFetchDataStrategyImpl(getRouter, getRouteInfo, fetchAndDecode, ssr, basename, shouldAllowOptOut = () => true) {
  7598. return async (args) => {
  7599. let { request, matches, fetcherKey } = args;
  7600. let router = getRouter();
  7601. if (request.method !== "GET") {
  7602. return singleFetchActionStrategy(args, fetchAndDecode, basename);
  7603. }
  7604. let foundRevalidatingServerLoader = matches.some((m) => {
  7605. let { hasLoader, hasClientLoader } = getRouteInfo(m);
  7606. return m.shouldCallHandler() && hasLoader && !hasClientLoader;
  7607. });
  7608. if (!ssr && !foundRevalidatingServerLoader) {
  7609. return nonSsrStrategy(args, getRouteInfo, fetchAndDecode, basename);
  7610. }
  7611. if (fetcherKey) {
  7612. return singleFetchLoaderFetcherStrategy(args, fetchAndDecode, basename);
  7613. }
  7614. return singleFetchLoaderNavigationStrategy(
  7615. args,
  7616. router,
  7617. getRouteInfo,
  7618. fetchAndDecode,
  7619. ssr,
  7620. basename,
  7621. shouldAllowOptOut
  7622. );
  7623. };
  7624. }
  7625. async function singleFetchActionStrategy(args, fetchAndDecode, basename) {
  7626. let actionMatch = args.matches.find((m) => m.shouldCallHandler());
  7627. invariant2(actionMatch, "No action match found");
  7628. let actionStatus = void 0;
  7629. let result = await actionMatch.resolve(async (handler) => {
  7630. let result2 = await handler(async () => {
  7631. let { data: data2, status } = await fetchAndDecode(args, basename, [
  7632. actionMatch.route.id
  7633. ]);
  7634. actionStatus = status;
  7635. return unwrapSingleFetchResult(data2, actionMatch.route.id);
  7636. });
  7637. return result2;
  7638. });
  7639. if (isResponse(result.result) || isRouteErrorResponse(result.result) || isDataWithResponseInit(result.result)) {
  7640. return { [actionMatch.route.id]: result };
  7641. }
  7642. return {
  7643. [actionMatch.route.id]: {
  7644. type: result.type,
  7645. result: data(result.result, actionStatus)
  7646. }
  7647. };
  7648. }
  7649. async function nonSsrStrategy(args, getRouteInfo, fetchAndDecode, basename) {
  7650. let matchesToLoad = args.matches.filter((m) => m.shouldCallHandler());
  7651. let results = {};
  7652. await Promise.all(
  7653. matchesToLoad.map(
  7654. (m) => m.resolve(async (handler) => {
  7655. try {
  7656. let { hasClientLoader } = getRouteInfo(m);
  7657. let routeId = m.route.id;
  7658. let result = hasClientLoader ? await handler(async () => {
  7659. let { data: data2 } = await fetchAndDecode(args, basename, [routeId]);
  7660. return unwrapSingleFetchResult(data2, routeId);
  7661. }) : await handler();
  7662. results[m.route.id] = { type: "data", result };
  7663. } catch (e) {
  7664. results[m.route.id] = { type: "error", result: e };
  7665. }
  7666. })
  7667. )
  7668. );
  7669. return results;
  7670. }
  7671. async function singleFetchLoaderNavigationStrategy(args, router, getRouteInfo, fetchAndDecode, ssr, basename, shouldAllowOptOut = () => true) {
  7672. let routesParams = /* @__PURE__ */ new Set();
  7673. let foundOptOutRoute = false;
  7674. let routeDfds = args.matches.map(() => createDeferred2());
  7675. let singleFetchDfd = createDeferred2();
  7676. let results = {};
  7677. let resolvePromise = Promise.all(
  7678. args.matches.map(
  7679. async (m, i) => m.resolve(async (handler) => {
  7680. routeDfds[i].resolve();
  7681. let routeId = m.route.id;
  7682. let { hasLoader, hasClientLoader, hasShouldRevalidate } = getRouteInfo(m);
  7683. let defaultShouldRevalidate = !m.shouldRevalidateArgs || m.shouldRevalidateArgs.actionStatus == null || m.shouldRevalidateArgs.actionStatus < 400;
  7684. let shouldCall = m.shouldCallHandler(defaultShouldRevalidate);
  7685. if (!shouldCall) {
  7686. foundOptOutRoute || (foundOptOutRoute = m.shouldRevalidateArgs != null && // This is a revalidation,
  7687. hasLoader && // for a route with a server loader,
  7688. hasShouldRevalidate === true);
  7689. return;
  7690. }
  7691. if (shouldAllowOptOut(m) && hasClientLoader) {
  7692. if (hasLoader) {
  7693. foundOptOutRoute = true;
  7694. }
  7695. try {
  7696. let result = await handler(async () => {
  7697. let { data: data2 } = await fetchAndDecode(args, basename, [routeId]);
  7698. return unwrapSingleFetchResult(data2, routeId);
  7699. });
  7700. results[routeId] = { type: "data", result };
  7701. } catch (e) {
  7702. results[routeId] = { type: "error", result: e };
  7703. }
  7704. return;
  7705. }
  7706. if (hasLoader) {
  7707. routesParams.add(routeId);
  7708. }
  7709. try {
  7710. let result = await handler(async () => {
  7711. let data2 = await singleFetchDfd.promise;
  7712. return unwrapSingleFetchResult(data2, routeId);
  7713. });
  7714. results[routeId] = { type: "data", result };
  7715. } catch (e) {
  7716. results[routeId] = { type: "error", result: e };
  7717. }
  7718. })
  7719. )
  7720. );
  7721. await Promise.all(routeDfds.map((d) => d.promise));
  7722. let isInitialLoad = !router.state.initialized && router.state.navigation.state === "idle";
  7723. if ((isInitialLoad || routesParams.size === 0) && !window.__reactRouterHdrActive) {
  7724. singleFetchDfd.resolve({ routes: {} });
  7725. } else {
  7726. let targetRoutes = ssr && foundOptOutRoute && routesParams.size > 0 ? [...routesParams.keys()] : void 0;
  7727. try {
  7728. let data2 = await fetchAndDecode(args, basename, targetRoutes);
  7729. singleFetchDfd.resolve(data2.data);
  7730. } catch (e) {
  7731. singleFetchDfd.reject(e);
  7732. }
  7733. }
  7734. await resolvePromise;
  7735. await bubbleMiddlewareErrors(
  7736. singleFetchDfd.promise,
  7737. args.matches,
  7738. routesParams,
  7739. results
  7740. );
  7741. return results;
  7742. }
  7743. async function bubbleMiddlewareErrors(singleFetchPromise, matches, routesParams, results) {
  7744. try {
  7745. let middlewareError;
  7746. let fetchedData = await singleFetchPromise;
  7747. if ("routes" in fetchedData) {
  7748. for (let match of matches) {
  7749. if (match.route.id in fetchedData.routes) {
  7750. let routeResult = fetchedData.routes[match.route.id];
  7751. if ("error" in routeResult) {
  7752. middlewareError = routeResult.error;
  7753. if (results[match.route.id]?.result == null) {
  7754. results[match.route.id] = {
  7755. type: "error",
  7756. result: middlewareError
  7757. };
  7758. }
  7759. break;
  7760. }
  7761. }
  7762. }
  7763. }
  7764. if (middlewareError !== void 0) {
  7765. Array.from(routesParams.values()).forEach((routeId) => {
  7766. if (results[routeId].result instanceof SingleFetchNoResultError) {
  7767. results[routeId].result = middlewareError;
  7768. }
  7769. });
  7770. }
  7771. } catch (e) {
  7772. }
  7773. }
  7774. async function singleFetchLoaderFetcherStrategy(args, fetchAndDecode, basename) {
  7775. let fetcherMatch = args.matches.find((m) => m.shouldCallHandler());
  7776. invariant2(fetcherMatch, "No fetcher match found");
  7777. let routeId = fetcherMatch.route.id;
  7778. let result = await fetcherMatch.resolve(
  7779. async (handler) => handler(async () => {
  7780. let { data: data2 } = await fetchAndDecode(args, basename, [routeId]);
  7781. return unwrapSingleFetchResult(data2, routeId);
  7782. })
  7783. );
  7784. return { [fetcherMatch.route.id]: result };
  7785. }
  7786. function stripIndexParam(url) {
  7787. let indexValues = url.searchParams.getAll("index");
  7788. url.searchParams.delete("index");
  7789. let indexValuesToKeep = [];
  7790. for (let indexValue of indexValues) {
  7791. if (indexValue) {
  7792. indexValuesToKeep.push(indexValue);
  7793. }
  7794. }
  7795. for (let toKeep of indexValuesToKeep) {
  7796. url.searchParams.append("index", toKeep);
  7797. }
  7798. return url;
  7799. }
  7800. function singleFetchUrl(reqUrl, basename, extension) {
  7801. let url = typeof reqUrl === "string" ? new URL(
  7802. reqUrl,
  7803. // This can be called during the SSR flow via PrefetchPageLinksImpl so
  7804. // don't assume window is available
  7805. typeof window === "undefined" ? "server://singlefetch/" : window.location.origin
  7806. ) : reqUrl;
  7807. if (url.pathname === "/") {
  7808. url.pathname = `_root.${extension}`;
  7809. } else if (basename && stripBasename(url.pathname, basename) === "/") {
  7810. url.pathname = `${basename.replace(/\/$/, "")}/_root.${extension}`;
  7811. } else {
  7812. url.pathname = `${url.pathname.replace(/\/$/, "")}.${extension}`;
  7813. }
  7814. return url;
  7815. }
  7816. async function fetchAndDecodeViaTurboStream(args, basename, targetRoutes) {
  7817. let { request } = args;
  7818. let url = singleFetchUrl(request.url, basename, "data");
  7819. if (request.method === "GET") {
  7820. url = stripIndexParam(url);
  7821. if (targetRoutes) {
  7822. url.searchParams.set("_routes", targetRoutes.join(","));
  7823. }
  7824. }
  7825. let res = await fetch(url, await createRequestInit(request));
  7826. if (res.status >= 400 && !res.headers.has("X-Remix-Response")) {
  7827. throw new ErrorResponseImpl(res.status, res.statusText, await res.text());
  7828. }
  7829. if (res.status === 204 && res.headers.has("X-Remix-Redirect")) {
  7830. return {
  7831. status: SINGLE_FETCH_REDIRECT_STATUS,
  7832. data: {
  7833. redirect: {
  7834. redirect: res.headers.get("X-Remix-Redirect"),
  7835. status: Number(res.headers.get("X-Remix-Status") || "302"),
  7836. revalidate: res.headers.get("X-Remix-Revalidate") === "true",
  7837. reload: res.headers.get("X-Remix-Reload-Document") === "true",
  7838. replace: res.headers.get("X-Remix-Replace") === "true"
  7839. }
  7840. }
  7841. };
  7842. }
  7843. if (NO_BODY_STATUS_CODES.has(res.status)) {
  7844. let routes = {};
  7845. if (targetRoutes && request.method !== "GET") {
  7846. routes[targetRoutes[0]] = { data: void 0 };
  7847. }
  7848. return {
  7849. status: res.status,
  7850. data: { routes }
  7851. };
  7852. }
  7853. invariant2(res.body, "No response body to decode");
  7854. try {
  7855. let decoded = await decodeViaTurboStream(res.body, window);
  7856. let data2;
  7857. if (request.method === "GET") {
  7858. let typed = decoded.value;
  7859. if (SingleFetchRedirectSymbol in typed) {
  7860. data2 = { redirect: typed[SingleFetchRedirectSymbol] };
  7861. } else {
  7862. data2 = { routes: typed };
  7863. }
  7864. } else {
  7865. let typed = decoded.value;
  7866. let routeId = targetRoutes?.[0];
  7867. invariant2(routeId, "No routeId found for single fetch call decoding");
  7868. if ("redirect" in typed) {
  7869. data2 = { redirect: typed };
  7870. } else {
  7871. data2 = { routes: { [routeId]: typed } };
  7872. }
  7873. }
  7874. return { status: res.status, data: data2 };
  7875. } catch (e) {
  7876. throw new Error("Unable to decode turbo-stream response");
  7877. }
  7878. }
  7879. function decodeViaTurboStream(body, global) {
  7880. return decode(body, {
  7881. plugins: [
  7882. (type, ...rest) => {
  7883. if (type === "SanitizedError") {
  7884. let [name, message, stack] = rest;
  7885. let Constructor = Error;
  7886. if (name && name in global && typeof global[name] === "function") {
  7887. Constructor = global[name];
  7888. }
  7889. let error = new Constructor(message);
  7890. error.stack = stack;
  7891. return { value: error };
  7892. }
  7893. if (type === "ErrorResponse") {
  7894. let [data2, status, statusText] = rest;
  7895. return {
  7896. value: new ErrorResponseImpl(status, statusText, data2)
  7897. };
  7898. }
  7899. if (type === "SingleFetchRedirect") {
  7900. return { value: { [SingleFetchRedirectSymbol]: rest[0] } };
  7901. }
  7902. if (type === "SingleFetchClassInstance") {
  7903. return { value: rest[0] };
  7904. }
  7905. if (type === "SingleFetchFallback") {
  7906. return { value: void 0 };
  7907. }
  7908. }
  7909. ]
  7910. });
  7911. }
  7912. function unwrapSingleFetchResult(result, routeId) {
  7913. if ("redirect" in result) {
  7914. let {
  7915. redirect: location,
  7916. revalidate,
  7917. reload,
  7918. replace: replace2,
  7919. status
  7920. } = result.redirect;
  7921. throw redirect(location, {
  7922. status,
  7923. headers: {
  7924. // Three R's of redirecting (lol Veep)
  7925. ...revalidate ? { "X-Remix-Revalidate": "yes" } : null,
  7926. ...reload ? { "X-Remix-Reload-Document": "yes" } : null,
  7927. ...replace2 ? { "X-Remix-Replace": "yes" } : null
  7928. }
  7929. });
  7930. }
  7931. let routeResult = result.routes[routeId];
  7932. if (routeResult == null) {
  7933. throw new SingleFetchNoResultError(
  7934. `No result found for routeId "${routeId}"`
  7935. );
  7936. } else if ("error" in routeResult) {
  7937. throw routeResult.error;
  7938. } else if ("data" in routeResult) {
  7939. return routeResult.data;
  7940. } else {
  7941. throw new Error(`Invalid response found for routeId "${routeId}"`);
  7942. }
  7943. }
  7944. function createDeferred2() {
  7945. let resolve;
  7946. let reject;
  7947. let promise = new Promise((res, rej) => {
  7948. resolve = async (val) => {
  7949. res(val);
  7950. try {
  7951. await promise;
  7952. } catch (e) {
  7953. }
  7954. };
  7955. reject = async (error) => {
  7956. rej(error);
  7957. try {
  7958. await promise;
  7959. } catch (e) {
  7960. }
  7961. };
  7962. });
  7963. return {
  7964. promise,
  7965. //@ts-ignore
  7966. resolve,
  7967. //@ts-ignore
  7968. reject
  7969. };
  7970. }
  7971. // lib/dom/ssr/errorBoundaries.tsx
  7972. import * as React9 from "react";
  7973. // lib/dom/ssr/components.tsx
  7974. import * as React8 from "react";
  7975. // lib/dom/ssr/routeModules.ts
  7976. async function loadRouteModule(route, routeModulesCache) {
  7977. if (route.id in routeModulesCache) {
  7978. return routeModulesCache[route.id];
  7979. }
  7980. try {
  7981. let routeModule = await import(
  7982. /* @vite-ignore */
  7983. /* webpackIgnore: true */
  7984. route.module
  7985. );
  7986. routeModulesCache[route.id] = routeModule;
  7987. return routeModule;
  7988. } catch (error) {
  7989. console.error(
  7990. `Error loading route module \`${route.module}\`, reloading page...`
  7991. );
  7992. console.error(error);
  7993. if (window.__reactRouterContext && window.__reactRouterContext.isSpaMode && // @ts-expect-error
  7994. import.meta.hot) {
  7995. throw error;
  7996. }
  7997. window.location.reload();
  7998. return new Promise(() => {
  7999. });
  8000. }
  8001. }
  8002. // lib/dom/ssr/links.ts
  8003. function getKeyedLinksForMatches(matches, routeModules, manifest) {
  8004. let descriptors = matches.map((match) => {
  8005. let module = routeModules[match.route.id];
  8006. let route = manifest.routes[match.route.id];
  8007. return [
  8008. route && route.css ? route.css.map((href) => ({ rel: "stylesheet", href })) : [],
  8009. module?.links?.() || []
  8010. ];
  8011. }).flat(2);
  8012. let preloads = getModuleLinkHrefs(matches, manifest);
  8013. return dedupeLinkDescriptors(descriptors, preloads);
  8014. }
  8015. function getRouteCssDescriptors(route) {
  8016. if (!route.css) return [];
  8017. return route.css.map((href) => ({ rel: "stylesheet", href }));
  8018. }
  8019. async function prefetchRouteCss(route) {
  8020. if (!route.css) return;
  8021. let descriptors = getRouteCssDescriptors(route);
  8022. await Promise.all(descriptors.map(prefetchStyleLink));
  8023. }
  8024. async function prefetchStyleLinks(route, routeModule) {
  8025. if (!route.css && !routeModule.links || !isPreloadSupported()) return;
  8026. let descriptors = [];
  8027. if (route.css) {
  8028. descriptors.push(...getRouteCssDescriptors(route));
  8029. }
  8030. if (routeModule.links) {
  8031. descriptors.push(...routeModule.links());
  8032. }
  8033. if (descriptors.length === 0) return;
  8034. let styleLinks = [];
  8035. for (let descriptor of descriptors) {
  8036. if (!isPageLinkDescriptor(descriptor) && descriptor.rel === "stylesheet") {
  8037. styleLinks.push({
  8038. ...descriptor,
  8039. rel: "preload",
  8040. as: "style"
  8041. });
  8042. }
  8043. }
  8044. await Promise.all(styleLinks.map(prefetchStyleLink));
  8045. }
  8046. async function prefetchStyleLink(descriptor) {
  8047. return new Promise((resolve) => {
  8048. if (descriptor.media && !window.matchMedia(descriptor.media).matches || document.querySelector(
  8049. `link[rel="stylesheet"][href="${descriptor.href}"]`
  8050. )) {
  8051. return resolve();
  8052. }
  8053. let link = document.createElement("link");
  8054. Object.assign(link, descriptor);
  8055. function removeLink() {
  8056. if (document.head.contains(link)) {
  8057. document.head.removeChild(link);
  8058. }
  8059. }
  8060. link.onload = () => {
  8061. removeLink();
  8062. resolve();
  8063. };
  8064. link.onerror = () => {
  8065. removeLink();
  8066. resolve();
  8067. };
  8068. document.head.appendChild(link);
  8069. });
  8070. }
  8071. function isPageLinkDescriptor(object) {
  8072. return object != null && typeof object.page === "string";
  8073. }
  8074. function isHtmlLinkDescriptor(object) {
  8075. if (object == null) {
  8076. return false;
  8077. }
  8078. if (object.href == null) {
  8079. return object.rel === "preload" && typeof object.imageSrcSet === "string" && typeof object.imageSizes === "string";
  8080. }
  8081. return typeof object.rel === "string" && typeof object.href === "string";
  8082. }
  8083. async function getKeyedPrefetchLinks(matches, manifest, routeModules) {
  8084. let links = await Promise.all(
  8085. matches.map(async (match) => {
  8086. let route = manifest.routes[match.route.id];
  8087. if (route) {
  8088. let mod = await loadRouteModule(route, routeModules);
  8089. return mod.links ? mod.links() : [];
  8090. }
  8091. return [];
  8092. })
  8093. );
  8094. return dedupeLinkDescriptors(
  8095. links.flat(1).filter(isHtmlLinkDescriptor).filter((link) => link.rel === "stylesheet" || link.rel === "preload").map(
  8096. (link) => link.rel === "stylesheet" ? { ...link, rel: "prefetch", as: "style" } : { ...link, rel: "prefetch" }
  8097. )
  8098. );
  8099. }
  8100. function getNewMatchesForLinks(page, nextMatches, currentMatches, manifest, location, mode) {
  8101. let isNew = (match, index) => {
  8102. if (!currentMatches[index]) return true;
  8103. return match.route.id !== currentMatches[index].route.id;
  8104. };
  8105. let matchPathChanged = (match, index) => {
  8106. return (
  8107. // param change, /users/123 -> /users/456
  8108. currentMatches[index].pathname !== match.pathname || // splat param changed, which is not present in match.path
  8109. // e.g. /files/images/avatar.jpg -> files/finances.xls
  8110. currentMatches[index].route.path?.endsWith("*") && currentMatches[index].params["*"] !== match.params["*"]
  8111. );
  8112. };
  8113. if (mode === "assets") {
  8114. return nextMatches.filter(
  8115. (match, index) => isNew(match, index) || matchPathChanged(match, index)
  8116. );
  8117. }
  8118. if (mode === "data") {
  8119. return nextMatches.filter((match, index) => {
  8120. let manifestRoute = manifest.routes[match.route.id];
  8121. if (!manifestRoute || !manifestRoute.hasLoader) {
  8122. return false;
  8123. }
  8124. if (isNew(match, index) || matchPathChanged(match, index)) {
  8125. return true;
  8126. }
  8127. if (match.route.shouldRevalidate) {
  8128. let routeChoice = match.route.shouldRevalidate({
  8129. currentUrl: new URL(
  8130. location.pathname + location.search + location.hash,
  8131. window.origin
  8132. ),
  8133. currentParams: currentMatches[0]?.params || {},
  8134. nextUrl: new URL(page, window.origin),
  8135. nextParams: match.params,
  8136. defaultShouldRevalidate: true
  8137. });
  8138. if (typeof routeChoice === "boolean") {
  8139. return routeChoice;
  8140. }
  8141. }
  8142. return true;
  8143. });
  8144. }
  8145. return [];
  8146. }
  8147. function getModuleLinkHrefs(matches, manifest, { includeHydrateFallback } = {}) {
  8148. return dedupeHrefs(
  8149. matches.map((match) => {
  8150. let route = manifest.routes[match.route.id];
  8151. if (!route) return [];
  8152. let hrefs = [route.module];
  8153. if (route.clientActionModule) {
  8154. hrefs = hrefs.concat(route.clientActionModule);
  8155. }
  8156. if (route.clientLoaderModule) {
  8157. hrefs = hrefs.concat(route.clientLoaderModule);
  8158. }
  8159. if (includeHydrateFallback && route.hydrateFallbackModule) {
  8160. hrefs = hrefs.concat(route.hydrateFallbackModule);
  8161. }
  8162. if (route.imports) {
  8163. hrefs = hrefs.concat(route.imports);
  8164. }
  8165. return hrefs;
  8166. }).flat(1)
  8167. );
  8168. }
  8169. function dedupeHrefs(hrefs) {
  8170. return [...new Set(hrefs)];
  8171. }
  8172. function sortKeys(obj) {
  8173. let sorted = {};
  8174. let keys = Object.keys(obj).sort();
  8175. for (let key of keys) {
  8176. sorted[key] = obj[key];
  8177. }
  8178. return sorted;
  8179. }
  8180. function dedupeLinkDescriptors(descriptors, preloads) {
  8181. let set = /* @__PURE__ */ new Set();
  8182. let preloadsSet = new Set(preloads);
  8183. return descriptors.reduce((deduped, descriptor) => {
  8184. let alreadyModulePreload = preloads && !isPageLinkDescriptor(descriptor) && descriptor.as === "script" && descriptor.href && preloadsSet.has(descriptor.href);
  8185. if (alreadyModulePreload) {
  8186. return deduped;
  8187. }
  8188. let key = JSON.stringify(sortKeys(descriptor));
  8189. if (!set.has(key)) {
  8190. set.add(key);
  8191. deduped.push({ key, link: descriptor });
  8192. }
  8193. return deduped;
  8194. }, []);
  8195. }
  8196. var _isPreloadSupported;
  8197. function isPreloadSupported() {
  8198. if (_isPreloadSupported !== void 0) {
  8199. return _isPreloadSupported;
  8200. }
  8201. let el = document.createElement("link");
  8202. _isPreloadSupported = el.relList.supports("preload");
  8203. el = null;
  8204. return _isPreloadSupported;
  8205. }
  8206. // lib/dom/ssr/fog-of-war.ts
  8207. import * as React7 from "react";
  8208. // lib/dom/ssr/routes.tsx
  8209. import * as React6 from "react";
  8210. // lib/dom/ssr/fallback.tsx
  8211. import * as React5 from "react";
  8212. function RemixRootDefaultHydrateFallback() {
  8213. return /* @__PURE__ */ React5.createElement(BoundaryShell, { title: "Loading...", renderScripts: true }, ENABLE_DEV_WARNINGS ? /* @__PURE__ */ React5.createElement(
  8214. "script",
  8215. {
  8216. dangerouslySetInnerHTML: {
  8217. __html: `
  8218. console.log(
  8219. "\u{1F4BF} Hey developer \u{1F44B}. You can provide a way better UX than this " +
  8220. "when your app is loading JS modules and/or running \`clientLoader\` " +
  8221. "functions. Check out https://reactrouter.com/start/framework/route-module#hydratefallback " +
  8222. "for more information."
  8223. );
  8224. `
  8225. }
  8226. }
  8227. ) : null);
  8228. }
  8229. // lib/dom/ssr/routes.tsx
  8230. function groupRoutesByParentId(manifest) {
  8231. let routes = {};
  8232. Object.values(manifest).forEach((route) => {
  8233. if (route) {
  8234. let parentId = route.parentId || "";
  8235. if (!routes[parentId]) {
  8236. routes[parentId] = [];
  8237. }
  8238. routes[parentId].push(route);
  8239. }
  8240. });
  8241. return routes;
  8242. }
  8243. function getRouteComponents(route, routeModule, isSpaMode) {
  8244. let Component4 = getRouteModuleComponent(routeModule);
  8245. let HydrateFallback = routeModule.HydrateFallback && (!isSpaMode || route.id === "root") ? routeModule.HydrateFallback : route.id === "root" ? RemixRootDefaultHydrateFallback : void 0;
  8246. let ErrorBoundary = routeModule.ErrorBoundary ? routeModule.ErrorBoundary : route.id === "root" ? () => /* @__PURE__ */ React6.createElement(RemixRootDefaultErrorBoundary, { error: useRouteError() }) : void 0;
  8247. if (route.id === "root" && routeModule.Layout) {
  8248. return {
  8249. ...Component4 ? {
  8250. element: /* @__PURE__ */ React6.createElement(routeModule.Layout, null, /* @__PURE__ */ React6.createElement(Component4, null))
  8251. } : { Component: Component4 },
  8252. ...ErrorBoundary ? {
  8253. errorElement: /* @__PURE__ */ React6.createElement(routeModule.Layout, null, /* @__PURE__ */ React6.createElement(ErrorBoundary, null))
  8254. } : { ErrorBoundary },
  8255. ...HydrateFallback ? {
  8256. hydrateFallbackElement: /* @__PURE__ */ React6.createElement(routeModule.Layout, null, /* @__PURE__ */ React6.createElement(HydrateFallback, null))
  8257. } : { HydrateFallback }
  8258. };
  8259. }
  8260. return { Component: Component4, ErrorBoundary, HydrateFallback };
  8261. }
  8262. function createServerRoutes(manifest, routeModules, future, isSpaMode, parentId = "", routesByParentId = groupRoutesByParentId(manifest), spaModeLazyPromise = Promise.resolve({ Component: () => null })) {
  8263. return (routesByParentId[parentId] || []).map((route) => {
  8264. let routeModule = routeModules[route.id];
  8265. invariant2(
  8266. routeModule,
  8267. "No `routeModule` available to create server routes"
  8268. );
  8269. let dataRoute = {
  8270. ...getRouteComponents(route, routeModule, isSpaMode),
  8271. caseSensitive: route.caseSensitive,
  8272. id: route.id,
  8273. index: route.index,
  8274. path: route.path,
  8275. handle: routeModule.handle,
  8276. // For SPA Mode, all routes are lazy except root. However we tell the
  8277. // router root is also lazy here too since we don't need a full
  8278. // implementation - we just need a `lazy` prop to tell the RR rendering
  8279. // where to stop which is always at the root route in SPA mode
  8280. lazy: isSpaMode ? () => spaModeLazyPromise : void 0,
  8281. // For partial hydration rendering, we need to indicate when the route
  8282. // has a loader/clientLoader, but it won't ever be called during the static
  8283. // render, so just give it a no-op function so we can render down to the
  8284. // proper fallback
  8285. loader: route.hasLoader || route.hasClientLoader ? () => null : void 0
  8286. // We don't need middleware/action/shouldRevalidate on these routes since
  8287. // they're for a static render
  8288. };
  8289. let children = createServerRoutes(
  8290. manifest,
  8291. routeModules,
  8292. future,
  8293. isSpaMode,
  8294. route.id,
  8295. routesByParentId,
  8296. spaModeLazyPromise
  8297. );
  8298. if (children.length > 0) dataRoute.children = children;
  8299. return dataRoute;
  8300. });
  8301. }
  8302. function createClientRoutesWithHMRRevalidationOptOut(needsRevalidation, manifest, routeModulesCache, initialState, ssr, isSpaMode) {
  8303. return createClientRoutes(
  8304. manifest,
  8305. routeModulesCache,
  8306. initialState,
  8307. ssr,
  8308. isSpaMode,
  8309. "",
  8310. groupRoutesByParentId(manifest),
  8311. needsRevalidation
  8312. );
  8313. }
  8314. function preventInvalidServerHandlerCall(type, route) {
  8315. if (type === "loader" && !route.hasLoader || type === "action" && !route.hasAction) {
  8316. let fn = type === "action" ? "serverAction()" : "serverLoader()";
  8317. let msg = `You are trying to call ${fn} on a route that does not have a server ${type} (routeId: "${route.id}")`;
  8318. console.error(msg);
  8319. throw new ErrorResponseImpl(400, "Bad Request", new Error(msg), true);
  8320. }
  8321. }
  8322. function noActionDefinedError(type, routeId) {
  8323. let article = type === "clientAction" ? "a" : "an";
  8324. let msg = `Route "${routeId}" does not have ${article} ${type}, but you are trying to submit to it. To fix this, please add ${article} \`${type}\` function to the route`;
  8325. console.error(msg);
  8326. throw new ErrorResponseImpl(405, "Method Not Allowed", new Error(msg), true);
  8327. }
  8328. function createClientRoutes(manifest, routeModulesCache, initialState, ssr, isSpaMode, parentId = "", routesByParentId = groupRoutesByParentId(manifest), needsRevalidation) {
  8329. return (routesByParentId[parentId] || []).map((route) => {
  8330. let routeModule = routeModulesCache[route.id];
  8331. function fetchServerHandler(singleFetch) {
  8332. invariant2(
  8333. typeof singleFetch === "function",
  8334. "No single fetch function available for route handler"
  8335. );
  8336. return singleFetch();
  8337. }
  8338. function fetchServerLoader(singleFetch) {
  8339. if (!route.hasLoader) return Promise.resolve(null);
  8340. return fetchServerHandler(singleFetch);
  8341. }
  8342. function fetchServerAction(singleFetch) {
  8343. if (!route.hasAction) {
  8344. throw noActionDefinedError("action", route.id);
  8345. }
  8346. return fetchServerHandler(singleFetch);
  8347. }
  8348. function prefetchModule(modulePath) {
  8349. import(
  8350. /* @vite-ignore */
  8351. /* webpackIgnore: true */
  8352. modulePath
  8353. );
  8354. }
  8355. function prefetchRouteModuleChunks(route2) {
  8356. if (route2.clientActionModule) {
  8357. prefetchModule(route2.clientActionModule);
  8358. }
  8359. if (route2.clientLoaderModule) {
  8360. prefetchModule(route2.clientLoaderModule);
  8361. }
  8362. }
  8363. async function prefetchStylesAndCallHandler(handler) {
  8364. let cachedModule = routeModulesCache[route.id];
  8365. let linkPrefetchPromise = cachedModule ? prefetchStyleLinks(route, cachedModule) : Promise.resolve();
  8366. try {
  8367. return handler();
  8368. } finally {
  8369. await linkPrefetchPromise;
  8370. }
  8371. }
  8372. let dataRoute = {
  8373. id: route.id,
  8374. index: route.index,
  8375. path: route.path
  8376. };
  8377. if (routeModule) {
  8378. Object.assign(dataRoute, {
  8379. ...dataRoute,
  8380. ...getRouteComponents(route, routeModule, isSpaMode),
  8381. middleware: routeModule.clientMiddleware,
  8382. handle: routeModule.handle,
  8383. shouldRevalidate: getShouldRevalidateFunction(
  8384. dataRoute.path,
  8385. routeModule,
  8386. route,
  8387. ssr,
  8388. needsRevalidation
  8389. )
  8390. });
  8391. let hasInitialData = initialState && initialState.loaderData && route.id in initialState.loaderData;
  8392. let initialData = hasInitialData ? initialState?.loaderData?.[route.id] : void 0;
  8393. let hasInitialError = initialState && initialState.errors && route.id in initialState.errors;
  8394. let initialError = hasInitialError ? initialState?.errors?.[route.id] : void 0;
  8395. let isHydrationRequest = needsRevalidation == null && (routeModule.clientLoader?.hydrate === true || !route.hasLoader);
  8396. dataRoute.loader = async ({ request, params, context, unstable_pattern }, singleFetch) => {
  8397. try {
  8398. let result = await prefetchStylesAndCallHandler(async () => {
  8399. invariant2(
  8400. routeModule,
  8401. "No `routeModule` available for critical-route loader"
  8402. );
  8403. if (!routeModule.clientLoader) {
  8404. return fetchServerLoader(singleFetch);
  8405. }
  8406. return routeModule.clientLoader({
  8407. request,
  8408. params,
  8409. context,
  8410. unstable_pattern,
  8411. async serverLoader() {
  8412. preventInvalidServerHandlerCall("loader", route);
  8413. if (isHydrationRequest) {
  8414. if (hasInitialData) {
  8415. return initialData;
  8416. }
  8417. if (hasInitialError) {
  8418. throw initialError;
  8419. }
  8420. }
  8421. return fetchServerLoader(singleFetch);
  8422. }
  8423. });
  8424. });
  8425. return result;
  8426. } finally {
  8427. isHydrationRequest = false;
  8428. }
  8429. };
  8430. dataRoute.loader.hydrate = shouldHydrateRouteLoader(
  8431. route.id,
  8432. routeModule.clientLoader,
  8433. route.hasLoader,
  8434. isSpaMode
  8435. );
  8436. dataRoute.action = ({ request, params, context, unstable_pattern }, singleFetch) => {
  8437. return prefetchStylesAndCallHandler(async () => {
  8438. invariant2(
  8439. routeModule,
  8440. "No `routeModule` available for critical-route action"
  8441. );
  8442. if (!routeModule.clientAction) {
  8443. if (isSpaMode) {
  8444. throw noActionDefinedError("clientAction", route.id);
  8445. }
  8446. return fetchServerAction(singleFetch);
  8447. }
  8448. return routeModule.clientAction({
  8449. request,
  8450. params,
  8451. context,
  8452. unstable_pattern,
  8453. async serverAction() {
  8454. preventInvalidServerHandlerCall("action", route);
  8455. return fetchServerAction(singleFetch);
  8456. }
  8457. });
  8458. });
  8459. };
  8460. } else {
  8461. if (!route.hasClientLoader) {
  8462. dataRoute.loader = (_, singleFetch) => prefetchStylesAndCallHandler(() => {
  8463. return fetchServerLoader(singleFetch);
  8464. });
  8465. }
  8466. if (!route.hasClientAction) {
  8467. dataRoute.action = (_, singleFetch) => prefetchStylesAndCallHandler(() => {
  8468. if (isSpaMode) {
  8469. throw noActionDefinedError("clientAction", route.id);
  8470. }
  8471. return fetchServerAction(singleFetch);
  8472. });
  8473. }
  8474. let lazyRoutePromise;
  8475. async function getLazyRoute() {
  8476. if (lazyRoutePromise) {
  8477. return await lazyRoutePromise;
  8478. }
  8479. lazyRoutePromise = (async () => {
  8480. if (route.clientLoaderModule || route.clientActionModule) {
  8481. await new Promise((resolve) => setTimeout(resolve, 0));
  8482. }
  8483. let routeModulePromise = loadRouteModuleWithBlockingLinks(
  8484. route,
  8485. routeModulesCache
  8486. );
  8487. prefetchRouteModuleChunks(route);
  8488. return await routeModulePromise;
  8489. })();
  8490. return await lazyRoutePromise;
  8491. }
  8492. dataRoute.lazy = {
  8493. loader: route.hasClientLoader ? async () => {
  8494. let { clientLoader } = route.clientLoaderModule ? await import(
  8495. /* @vite-ignore */
  8496. /* webpackIgnore: true */
  8497. route.clientLoaderModule
  8498. ) : await getLazyRoute();
  8499. invariant2(clientLoader, "No `clientLoader` export found");
  8500. return (args, singleFetch) => clientLoader({
  8501. ...args,
  8502. async serverLoader() {
  8503. preventInvalidServerHandlerCall("loader", route);
  8504. return fetchServerLoader(singleFetch);
  8505. }
  8506. });
  8507. } : void 0,
  8508. action: route.hasClientAction ? async () => {
  8509. let clientActionPromise = route.clientActionModule ? import(
  8510. /* @vite-ignore */
  8511. /* webpackIgnore: true */
  8512. route.clientActionModule
  8513. ) : getLazyRoute();
  8514. prefetchRouteModuleChunks(route);
  8515. let { clientAction } = await clientActionPromise;
  8516. invariant2(clientAction, "No `clientAction` export found");
  8517. return (args, singleFetch) => clientAction({
  8518. ...args,
  8519. async serverAction() {
  8520. preventInvalidServerHandlerCall("action", route);
  8521. return fetchServerAction(singleFetch);
  8522. }
  8523. });
  8524. } : void 0,
  8525. middleware: route.hasClientMiddleware ? async () => {
  8526. let { clientMiddleware } = route.clientMiddlewareModule ? await import(
  8527. /* @vite-ignore */
  8528. /* webpackIgnore: true */
  8529. route.clientMiddlewareModule
  8530. ) : await getLazyRoute();
  8531. invariant2(clientMiddleware, "No `clientMiddleware` export found");
  8532. return clientMiddleware;
  8533. } : void 0,
  8534. shouldRevalidate: async () => {
  8535. let lazyRoute = await getLazyRoute();
  8536. return getShouldRevalidateFunction(
  8537. dataRoute.path,
  8538. lazyRoute,
  8539. route,
  8540. ssr,
  8541. needsRevalidation
  8542. );
  8543. },
  8544. handle: async () => (await getLazyRoute()).handle,
  8545. // No need to wrap these in layout since the root route is never
  8546. // loaded via route.lazy()
  8547. Component: async () => (await getLazyRoute()).Component,
  8548. ErrorBoundary: route.hasErrorBoundary ? async () => (await getLazyRoute()).ErrorBoundary : void 0
  8549. };
  8550. }
  8551. let children = createClientRoutes(
  8552. manifest,
  8553. routeModulesCache,
  8554. initialState,
  8555. ssr,
  8556. isSpaMode,
  8557. route.id,
  8558. routesByParentId,
  8559. needsRevalidation
  8560. );
  8561. if (children.length > 0) dataRoute.children = children;
  8562. return dataRoute;
  8563. });
  8564. }
  8565. function getShouldRevalidateFunction(path, route, manifestRoute, ssr, needsRevalidation) {
  8566. if (needsRevalidation) {
  8567. return wrapShouldRevalidateForHdr(
  8568. manifestRoute.id,
  8569. route.shouldRevalidate,
  8570. needsRevalidation
  8571. );
  8572. }
  8573. if (!ssr && manifestRoute.hasLoader && !manifestRoute.hasClientLoader) {
  8574. let myParams = path ? compilePath(path)[1].map((p) => p.paramName) : [];
  8575. const didParamsChange = (opts) => myParams.some((p) => opts.currentParams[p] !== opts.nextParams[p]);
  8576. if (route.shouldRevalidate) {
  8577. let fn = route.shouldRevalidate;
  8578. return (opts) => fn({
  8579. ...opts,
  8580. defaultShouldRevalidate: didParamsChange(opts)
  8581. });
  8582. } else {
  8583. return (opts) => didParamsChange(opts);
  8584. }
  8585. }
  8586. return route.shouldRevalidate;
  8587. }
  8588. function wrapShouldRevalidateForHdr(routeId, routeShouldRevalidate, needsRevalidation) {
  8589. let handledRevalidation = false;
  8590. return (arg) => {
  8591. if (!handledRevalidation) {
  8592. handledRevalidation = true;
  8593. return needsRevalidation.has(routeId);
  8594. }
  8595. return routeShouldRevalidate ? routeShouldRevalidate(arg) : arg.defaultShouldRevalidate;
  8596. };
  8597. }
  8598. async function loadRouteModuleWithBlockingLinks(route, routeModules) {
  8599. let routeModulePromise = loadRouteModule(route, routeModules);
  8600. let prefetchRouteCssPromise = prefetchRouteCss(route);
  8601. let routeModule = await routeModulePromise;
  8602. await Promise.all([
  8603. prefetchRouteCssPromise,
  8604. prefetchStyleLinks(route, routeModule)
  8605. ]);
  8606. return {
  8607. Component: getRouteModuleComponent(routeModule),
  8608. ErrorBoundary: routeModule.ErrorBoundary,
  8609. clientMiddleware: routeModule.clientMiddleware,
  8610. clientAction: routeModule.clientAction,
  8611. clientLoader: routeModule.clientLoader,
  8612. handle: routeModule.handle,
  8613. links: routeModule.links,
  8614. meta: routeModule.meta,
  8615. shouldRevalidate: routeModule.shouldRevalidate
  8616. };
  8617. }
  8618. function getRouteModuleComponent(routeModule) {
  8619. if (routeModule.default == null) return void 0;
  8620. let isEmptyObject = typeof routeModule.default === "object" && Object.keys(routeModule.default).length === 0;
  8621. if (!isEmptyObject) {
  8622. return routeModule.default;
  8623. }
  8624. }
  8625. function shouldHydrateRouteLoader(routeId, clientLoader, hasLoader, isSpaMode) {
  8626. return isSpaMode && routeId !== "root" || clientLoader != null && (clientLoader.hydrate === true || hasLoader !== true);
  8627. }
  8628. // lib/dom/ssr/fog-of-war.ts
  8629. var nextPaths = /* @__PURE__ */ new Set();
  8630. var discoveredPathsMaxSize = 1e3;
  8631. var discoveredPaths = /* @__PURE__ */ new Set();
  8632. var URL_LIMIT = 7680;
  8633. function isFogOfWarEnabled(routeDiscovery, ssr) {
  8634. return routeDiscovery.mode === "lazy" && ssr === true;
  8635. }
  8636. function getPartialManifest({ sri, ...manifest }, router) {
  8637. let routeIds = new Set(router.state.matches.map((m) => m.route.id));
  8638. let segments = router.state.location.pathname.split("/").filter(Boolean);
  8639. let paths = ["/"];
  8640. segments.pop();
  8641. while (segments.length > 0) {
  8642. paths.push(`/${segments.join("/")}`);
  8643. segments.pop();
  8644. }
  8645. paths.forEach((path) => {
  8646. let matches = matchRoutes(router.routes, path, router.basename);
  8647. if (matches) {
  8648. matches.forEach((m) => routeIds.add(m.route.id));
  8649. }
  8650. });
  8651. let initialRoutes = [...routeIds].reduce(
  8652. (acc, id) => Object.assign(acc, { [id]: manifest.routes[id] }),
  8653. {}
  8654. );
  8655. return {
  8656. ...manifest,
  8657. routes: initialRoutes,
  8658. sri: sri ? true : void 0
  8659. };
  8660. }
  8661. function getPatchRoutesOnNavigationFunction(manifest, routeModules, ssr, routeDiscovery, isSpaMode, basename) {
  8662. if (!isFogOfWarEnabled(routeDiscovery, ssr)) {
  8663. return void 0;
  8664. }
  8665. return async ({ path, patch, signal, fetcherKey }) => {
  8666. if (discoveredPaths.has(path)) {
  8667. return;
  8668. }
  8669. await fetchAndApplyManifestPatches(
  8670. [path],
  8671. fetcherKey ? window.location.href : path,
  8672. manifest,
  8673. routeModules,
  8674. ssr,
  8675. isSpaMode,
  8676. basename,
  8677. routeDiscovery.manifestPath,
  8678. patch,
  8679. signal
  8680. );
  8681. };
  8682. }
  8683. function useFogOFWarDiscovery(router, manifest, routeModules, ssr, routeDiscovery, isSpaMode) {
  8684. React7.useEffect(() => {
  8685. if (!isFogOfWarEnabled(routeDiscovery, ssr) || // @ts-expect-error - TS doesn't know about this yet
  8686. window.navigator?.connection?.saveData === true) {
  8687. return;
  8688. }
  8689. function registerElement(el) {
  8690. let path = el.tagName === "FORM" ? el.getAttribute("action") : el.getAttribute("href");
  8691. if (!path) {
  8692. return;
  8693. }
  8694. let pathname = el.tagName === "A" ? el.pathname : new URL(path, window.location.origin).pathname;
  8695. if (!discoveredPaths.has(pathname)) {
  8696. nextPaths.add(pathname);
  8697. }
  8698. }
  8699. async function fetchPatches() {
  8700. document.querySelectorAll("a[data-discover], form[data-discover]").forEach(registerElement);
  8701. let lazyPaths = Array.from(nextPaths.keys()).filter((path) => {
  8702. if (discoveredPaths.has(path)) {
  8703. nextPaths.delete(path);
  8704. return false;
  8705. }
  8706. return true;
  8707. });
  8708. if (lazyPaths.length === 0) {
  8709. return;
  8710. }
  8711. try {
  8712. await fetchAndApplyManifestPatches(
  8713. lazyPaths,
  8714. null,
  8715. manifest,
  8716. routeModules,
  8717. ssr,
  8718. isSpaMode,
  8719. router.basename,
  8720. routeDiscovery.manifestPath,
  8721. router.patchRoutes
  8722. );
  8723. } catch (e) {
  8724. console.error("Failed to fetch manifest patches", e);
  8725. }
  8726. }
  8727. let debouncedFetchPatches = debounce(fetchPatches, 100);
  8728. fetchPatches();
  8729. let observer = new MutationObserver(() => debouncedFetchPatches());
  8730. observer.observe(document.documentElement, {
  8731. subtree: true,
  8732. childList: true,
  8733. attributes: true,
  8734. attributeFilter: ["data-discover", "href", "action"]
  8735. });
  8736. return () => observer.disconnect();
  8737. }, [ssr, isSpaMode, manifest, routeModules, router, routeDiscovery]);
  8738. }
  8739. function getManifestPath(_manifestPath, basename) {
  8740. let manifestPath = _manifestPath || "/__manifest";
  8741. if (basename == null) {
  8742. return manifestPath;
  8743. }
  8744. return `${basename}${manifestPath}`.replace(/\/+/g, "/");
  8745. }
  8746. var MANIFEST_VERSION_STORAGE_KEY = "react-router-manifest-version";
  8747. async function fetchAndApplyManifestPatches(paths, errorReloadPath, manifest, routeModules, ssr, isSpaMode, basename, manifestPath, patchRoutes, signal) {
  8748. const searchParams = new URLSearchParams();
  8749. searchParams.set("paths", paths.sort().join(","));
  8750. searchParams.set("version", manifest.version);
  8751. let url = new URL(
  8752. getManifestPath(manifestPath, basename),
  8753. window.location.origin
  8754. );
  8755. url.search = searchParams.toString();
  8756. if (url.toString().length > URL_LIMIT) {
  8757. nextPaths.clear();
  8758. return;
  8759. }
  8760. let serverPatches;
  8761. try {
  8762. let res = await fetch(url, { signal });
  8763. if (!res.ok) {
  8764. throw new Error(`${res.status} ${res.statusText}`);
  8765. } else if (res.status === 204 && res.headers.has("X-Remix-Reload-Document")) {
  8766. if (!errorReloadPath) {
  8767. console.warn(
  8768. "Detected a manifest version mismatch during eager route discovery. The next navigation/fetch to an undiscovered route will result in a new document navigation to sync up with the latest manifest."
  8769. );
  8770. return;
  8771. }
  8772. try {
  8773. if (sessionStorage.getItem(MANIFEST_VERSION_STORAGE_KEY) === manifest.version) {
  8774. console.error(
  8775. "Unable to discover routes due to manifest version mismatch."
  8776. );
  8777. return;
  8778. }
  8779. sessionStorage.setItem(MANIFEST_VERSION_STORAGE_KEY, manifest.version);
  8780. } catch {
  8781. }
  8782. window.location.href = errorReloadPath;
  8783. console.warn("Detected manifest version mismatch, reloading...");
  8784. await new Promise(() => {
  8785. });
  8786. } else if (res.status >= 400) {
  8787. throw new Error(await res.text());
  8788. }
  8789. try {
  8790. sessionStorage.removeItem(MANIFEST_VERSION_STORAGE_KEY);
  8791. } catch {
  8792. }
  8793. serverPatches = await res.json();
  8794. } catch (e) {
  8795. if (signal?.aborted) return;
  8796. throw e;
  8797. }
  8798. let knownRoutes = new Set(Object.keys(manifest.routes));
  8799. let patches = Object.values(serverPatches).reduce((acc, route) => {
  8800. if (route && !knownRoutes.has(route.id)) {
  8801. acc[route.id] = route;
  8802. }
  8803. return acc;
  8804. }, {});
  8805. Object.assign(manifest.routes, patches);
  8806. paths.forEach((p) => addToFifoQueue(p, discoveredPaths));
  8807. let parentIds = /* @__PURE__ */ new Set();
  8808. Object.values(patches).forEach((patch) => {
  8809. if (patch && (!patch.parentId || !patches[patch.parentId])) {
  8810. parentIds.add(patch.parentId);
  8811. }
  8812. });
  8813. parentIds.forEach(
  8814. (parentId) => patchRoutes(
  8815. parentId || null,
  8816. createClientRoutes(patches, routeModules, null, ssr, isSpaMode, parentId)
  8817. )
  8818. );
  8819. }
  8820. function addToFifoQueue(path, queue) {
  8821. if (queue.size >= discoveredPathsMaxSize) {
  8822. let first = queue.values().next().value;
  8823. queue.delete(first);
  8824. }
  8825. queue.add(path);
  8826. }
  8827. function debounce(callback, wait) {
  8828. let timeoutId;
  8829. return (...args) => {
  8830. window.clearTimeout(timeoutId);
  8831. timeoutId = window.setTimeout(() => callback(...args), wait);
  8832. };
  8833. }
  8834. // lib/dom/ssr/components.tsx
  8835. function useDataRouterContext2() {
  8836. let context = React8.useContext(DataRouterContext);
  8837. invariant2(
  8838. context,
  8839. "You must render this element inside a <DataRouterContext.Provider> element"
  8840. );
  8841. return context;
  8842. }
  8843. function useDataRouterStateContext() {
  8844. let context = React8.useContext(DataRouterStateContext);
  8845. invariant2(
  8846. context,
  8847. "You must render this element inside a <DataRouterStateContext.Provider> element"
  8848. );
  8849. return context;
  8850. }
  8851. var FrameworkContext = React8.createContext(void 0);
  8852. FrameworkContext.displayName = "FrameworkContext";
  8853. function useFrameworkContext() {
  8854. let context = React8.useContext(FrameworkContext);
  8855. invariant2(
  8856. context,
  8857. "You must render this element inside a <HydratedRouter> element"
  8858. );
  8859. return context;
  8860. }
  8861. function usePrefetchBehavior(prefetch, theirElementProps) {
  8862. let frameworkContext = React8.useContext(FrameworkContext);
  8863. let [maybePrefetch, setMaybePrefetch] = React8.useState(false);
  8864. let [shouldPrefetch, setShouldPrefetch] = React8.useState(false);
  8865. let { onFocus, onBlur, onMouseEnter, onMouseLeave, onTouchStart } = theirElementProps;
  8866. let ref = React8.useRef(null);
  8867. React8.useEffect(() => {
  8868. if (prefetch === "render") {
  8869. setShouldPrefetch(true);
  8870. }
  8871. if (prefetch === "viewport") {
  8872. let callback = (entries) => {
  8873. entries.forEach((entry) => {
  8874. setShouldPrefetch(entry.isIntersecting);
  8875. });
  8876. };
  8877. let observer = new IntersectionObserver(callback, { threshold: 0.5 });
  8878. if (ref.current) observer.observe(ref.current);
  8879. return () => {
  8880. observer.disconnect();
  8881. };
  8882. }
  8883. }, [prefetch]);
  8884. React8.useEffect(() => {
  8885. if (maybePrefetch) {
  8886. let id = setTimeout(() => {
  8887. setShouldPrefetch(true);
  8888. }, 100);
  8889. return () => {
  8890. clearTimeout(id);
  8891. };
  8892. }
  8893. }, [maybePrefetch]);
  8894. let setIntent = () => {
  8895. setMaybePrefetch(true);
  8896. };
  8897. let cancelIntent = () => {
  8898. setMaybePrefetch(false);
  8899. setShouldPrefetch(false);
  8900. };
  8901. if (!frameworkContext) {
  8902. return [false, ref, {}];
  8903. }
  8904. if (prefetch !== "intent") {
  8905. return [shouldPrefetch, ref, {}];
  8906. }
  8907. return [
  8908. shouldPrefetch,
  8909. ref,
  8910. {
  8911. onFocus: composeEventHandlers(onFocus, setIntent),
  8912. onBlur: composeEventHandlers(onBlur, cancelIntent),
  8913. onMouseEnter: composeEventHandlers(onMouseEnter, setIntent),
  8914. onMouseLeave: composeEventHandlers(onMouseLeave, cancelIntent),
  8915. onTouchStart: composeEventHandlers(onTouchStart, setIntent)
  8916. }
  8917. ];
  8918. }
  8919. function composeEventHandlers(theirHandler, ourHandler) {
  8920. return (event) => {
  8921. theirHandler && theirHandler(event);
  8922. if (!event.defaultPrevented) {
  8923. ourHandler(event);
  8924. }
  8925. };
  8926. }
  8927. function getActiveMatches(matches, errors, isSpaMode) {
  8928. if (isSpaMode && !isHydrated) {
  8929. return [matches[0]];
  8930. }
  8931. if (errors) {
  8932. let errorIdx = matches.findIndex((m) => errors[m.route.id] !== void 0);
  8933. return matches.slice(0, errorIdx + 1);
  8934. }
  8935. return matches;
  8936. }
  8937. var CRITICAL_CSS_DATA_ATTRIBUTE = "data-react-router-critical-css";
  8938. function Links({ nonce }) {
  8939. let { isSpaMode, manifest, routeModules, criticalCss } = useFrameworkContext();
  8940. let { errors, matches: routerMatches } = useDataRouterStateContext();
  8941. let matches = getActiveMatches(routerMatches, errors, isSpaMode);
  8942. let keyedLinks = React8.useMemo(
  8943. () => getKeyedLinksForMatches(matches, routeModules, manifest),
  8944. [matches, routeModules, manifest]
  8945. );
  8946. return /* @__PURE__ */ React8.createElement(React8.Fragment, null, typeof criticalCss === "string" ? /* @__PURE__ */ React8.createElement(
  8947. "style",
  8948. {
  8949. ...{ [CRITICAL_CSS_DATA_ATTRIBUTE]: "" },
  8950. dangerouslySetInnerHTML: { __html: criticalCss }
  8951. }
  8952. ) : null, typeof criticalCss === "object" ? /* @__PURE__ */ React8.createElement(
  8953. "link",
  8954. {
  8955. ...{ [CRITICAL_CSS_DATA_ATTRIBUTE]: "" },
  8956. rel: "stylesheet",
  8957. href: criticalCss.href,
  8958. nonce
  8959. }
  8960. ) : null, keyedLinks.map(
  8961. ({ key, link }) => isPageLinkDescriptor(link) ? /* @__PURE__ */ React8.createElement(PrefetchPageLinks, { key, nonce, ...link }) : /* @__PURE__ */ React8.createElement("link", { key, nonce, ...link })
  8962. ));
  8963. }
  8964. function PrefetchPageLinks({ page, ...linkProps }) {
  8965. let { router } = useDataRouterContext2();
  8966. let matches = React8.useMemo(
  8967. () => matchRoutes(router.routes, page, router.basename),
  8968. [router.routes, page, router.basename]
  8969. );
  8970. if (!matches) {
  8971. return null;
  8972. }
  8973. return /* @__PURE__ */ React8.createElement(PrefetchPageLinksImpl, { page, matches, ...linkProps });
  8974. }
  8975. function useKeyedPrefetchLinks(matches) {
  8976. let { manifest, routeModules } = useFrameworkContext();
  8977. let [keyedPrefetchLinks, setKeyedPrefetchLinks] = React8.useState([]);
  8978. React8.useEffect(() => {
  8979. let interrupted = false;
  8980. void getKeyedPrefetchLinks(matches, manifest, routeModules).then(
  8981. (links) => {
  8982. if (!interrupted) {
  8983. setKeyedPrefetchLinks(links);
  8984. }
  8985. }
  8986. );
  8987. return () => {
  8988. interrupted = true;
  8989. };
  8990. }, [matches, manifest, routeModules]);
  8991. return keyedPrefetchLinks;
  8992. }
  8993. function PrefetchPageLinksImpl({
  8994. page,
  8995. matches: nextMatches,
  8996. ...linkProps
  8997. }) {
  8998. let location = useLocation();
  8999. let { manifest, routeModules } = useFrameworkContext();
  9000. let { basename } = useDataRouterContext2();
  9001. let { loaderData, matches } = useDataRouterStateContext();
  9002. let newMatchesForData = React8.useMemo(
  9003. () => getNewMatchesForLinks(
  9004. page,
  9005. nextMatches,
  9006. matches,
  9007. manifest,
  9008. location,
  9009. "data"
  9010. ),
  9011. [page, nextMatches, matches, manifest, location]
  9012. );
  9013. let newMatchesForAssets = React8.useMemo(
  9014. () => getNewMatchesForLinks(
  9015. page,
  9016. nextMatches,
  9017. matches,
  9018. manifest,
  9019. location,
  9020. "assets"
  9021. ),
  9022. [page, nextMatches, matches, manifest, location]
  9023. );
  9024. let dataHrefs = React8.useMemo(() => {
  9025. if (page === location.pathname + location.search + location.hash) {
  9026. return [];
  9027. }
  9028. let routesParams = /* @__PURE__ */ new Set();
  9029. let foundOptOutRoute = false;
  9030. nextMatches.forEach((m) => {
  9031. let manifestRoute = manifest.routes[m.route.id];
  9032. if (!manifestRoute || !manifestRoute.hasLoader) {
  9033. return;
  9034. }
  9035. if (!newMatchesForData.some((m2) => m2.route.id === m.route.id) && m.route.id in loaderData && routeModules[m.route.id]?.shouldRevalidate) {
  9036. foundOptOutRoute = true;
  9037. } else if (manifestRoute.hasClientLoader) {
  9038. foundOptOutRoute = true;
  9039. } else {
  9040. routesParams.add(m.route.id);
  9041. }
  9042. });
  9043. if (routesParams.size === 0) {
  9044. return [];
  9045. }
  9046. let url = singleFetchUrl(page, basename, "data");
  9047. if (foundOptOutRoute && routesParams.size > 0) {
  9048. url.searchParams.set(
  9049. "_routes",
  9050. nextMatches.filter((m) => routesParams.has(m.route.id)).map((m) => m.route.id).join(",")
  9051. );
  9052. }
  9053. return [url.pathname + url.search];
  9054. }, [
  9055. basename,
  9056. loaderData,
  9057. location,
  9058. manifest,
  9059. newMatchesForData,
  9060. nextMatches,
  9061. page,
  9062. routeModules
  9063. ]);
  9064. let moduleHrefs = React8.useMemo(
  9065. () => getModuleLinkHrefs(newMatchesForAssets, manifest),
  9066. [newMatchesForAssets, manifest]
  9067. );
  9068. let keyedPrefetchLinks = useKeyedPrefetchLinks(newMatchesForAssets);
  9069. return /* @__PURE__ */ React8.createElement(React8.Fragment, null, dataHrefs.map((href) => /* @__PURE__ */ React8.createElement("link", { key: href, rel: "prefetch", as: "fetch", href, ...linkProps })), moduleHrefs.map((href) => /* @__PURE__ */ React8.createElement("link", { key: href, rel: "modulepreload", href, ...linkProps })), keyedPrefetchLinks.map(({ key, link }) => (
  9070. // these don't spread `linkProps` because they are full link descriptors
  9071. // already with their own props
  9072. /* @__PURE__ */ React8.createElement("link", { key, nonce: linkProps.nonce, ...link })
  9073. )));
  9074. }
  9075. function Meta() {
  9076. let { isSpaMode, routeModules } = useFrameworkContext();
  9077. let {
  9078. errors,
  9079. matches: routerMatches,
  9080. loaderData
  9081. } = useDataRouterStateContext();
  9082. let location = useLocation();
  9083. let _matches = getActiveMatches(routerMatches, errors, isSpaMode);
  9084. let error = null;
  9085. if (errors) {
  9086. error = errors[_matches[_matches.length - 1].route.id];
  9087. }
  9088. let meta = [];
  9089. let leafMeta = null;
  9090. let matches = [];
  9091. for (let i = 0; i < _matches.length; i++) {
  9092. let _match = _matches[i];
  9093. let routeId = _match.route.id;
  9094. let data2 = loaderData[routeId];
  9095. let params = _match.params;
  9096. let routeModule = routeModules[routeId];
  9097. let routeMeta = [];
  9098. let match = {
  9099. id: routeId,
  9100. data: data2,
  9101. loaderData: data2,
  9102. meta: [],
  9103. params: _match.params,
  9104. pathname: _match.pathname,
  9105. handle: _match.route.handle,
  9106. error
  9107. };
  9108. matches[i] = match;
  9109. if (routeModule?.meta) {
  9110. routeMeta = typeof routeModule.meta === "function" ? routeModule.meta({
  9111. data: data2,
  9112. loaderData: data2,
  9113. params,
  9114. location,
  9115. matches,
  9116. error
  9117. }) : Array.isArray(routeModule.meta) ? [...routeModule.meta] : routeModule.meta;
  9118. } else if (leafMeta) {
  9119. routeMeta = [...leafMeta];
  9120. }
  9121. routeMeta = routeMeta || [];
  9122. if (!Array.isArray(routeMeta)) {
  9123. throw new Error(
  9124. "The route at " + _match.route.path + " returns an invalid value. All route meta functions must return an array of meta objects.\n\nTo reference the meta function API, see https://remix.run/route/meta"
  9125. );
  9126. }
  9127. match.meta = routeMeta;
  9128. matches[i] = match;
  9129. meta = [...routeMeta];
  9130. leafMeta = meta;
  9131. }
  9132. return /* @__PURE__ */ React8.createElement(React8.Fragment, null, meta.flat().map((metaProps) => {
  9133. if (!metaProps) {
  9134. return null;
  9135. }
  9136. if ("tagName" in metaProps) {
  9137. let { tagName, ...rest } = metaProps;
  9138. if (!isValidMetaTag(tagName)) {
  9139. console.warn(
  9140. `A meta object uses an invalid tagName: ${tagName}. Expected either 'link' or 'meta'`
  9141. );
  9142. return null;
  9143. }
  9144. let Comp = tagName;
  9145. return /* @__PURE__ */ React8.createElement(Comp, { key: JSON.stringify(rest), ...rest });
  9146. }
  9147. if ("title" in metaProps) {
  9148. return /* @__PURE__ */ React8.createElement("title", { key: "title" }, String(metaProps.title));
  9149. }
  9150. if ("charset" in metaProps) {
  9151. metaProps.charSet ?? (metaProps.charSet = metaProps.charset);
  9152. delete metaProps.charset;
  9153. }
  9154. if ("charSet" in metaProps && metaProps.charSet != null) {
  9155. return typeof metaProps.charSet === "string" ? /* @__PURE__ */ React8.createElement("meta", { key: "charSet", charSet: metaProps.charSet }) : null;
  9156. }
  9157. if ("script:ld+json" in metaProps) {
  9158. try {
  9159. let json = JSON.stringify(metaProps["script:ld+json"]);
  9160. return /* @__PURE__ */ React8.createElement(
  9161. "script",
  9162. {
  9163. key: `script:ld+json:${json}`,
  9164. type: "application/ld+json",
  9165. dangerouslySetInnerHTML: { __html: escapeHtml(json) }
  9166. }
  9167. );
  9168. } catch (err) {
  9169. return null;
  9170. }
  9171. }
  9172. return /* @__PURE__ */ React8.createElement("meta", { key: JSON.stringify(metaProps), ...metaProps });
  9173. }));
  9174. }
  9175. function isValidMetaTag(tagName) {
  9176. return typeof tagName === "string" && /^(meta|link)$/.test(tagName);
  9177. }
  9178. var isHydrated = false;
  9179. function setIsHydrated() {
  9180. isHydrated = true;
  9181. }
  9182. function Scripts(scriptProps) {
  9183. let {
  9184. manifest,
  9185. serverHandoffString,
  9186. isSpaMode,
  9187. renderMeta,
  9188. routeDiscovery,
  9189. ssr
  9190. } = useFrameworkContext();
  9191. let { router, static: isStatic, staticContext } = useDataRouterContext2();
  9192. let { matches: routerMatches } = useDataRouterStateContext();
  9193. let isRSCRouterContext = useIsRSCRouterContext();
  9194. let enableFogOfWar = isFogOfWarEnabled(routeDiscovery, ssr);
  9195. if (renderMeta) {
  9196. renderMeta.didRenderScripts = true;
  9197. }
  9198. let matches = getActiveMatches(routerMatches, null, isSpaMode);
  9199. React8.useEffect(() => {
  9200. setIsHydrated();
  9201. }, []);
  9202. let initialScripts = React8.useMemo(() => {
  9203. if (isRSCRouterContext) {
  9204. return null;
  9205. }
  9206. let streamScript = "window.__reactRouterContext.stream = new ReadableStream({start(controller){window.__reactRouterContext.streamController = controller;}}).pipeThrough(new TextEncoderStream());";
  9207. let contextScript = staticContext ? `window.__reactRouterContext = ${serverHandoffString};${streamScript}` : " ";
  9208. let routeModulesScript = !isStatic ? " " : `${manifest.hmr?.runtime ? `import ${JSON.stringify(manifest.hmr.runtime)};` : ""}${!enableFogOfWar ? `import ${JSON.stringify(manifest.url)}` : ""};
  9209. ${matches.map((match, routeIndex) => {
  9210. let routeVarName = `route${routeIndex}`;
  9211. let manifestEntry = manifest.routes[match.route.id];
  9212. invariant2(manifestEntry, `Route ${match.route.id} not found in manifest`);
  9213. let {
  9214. clientActionModule,
  9215. clientLoaderModule,
  9216. clientMiddlewareModule,
  9217. hydrateFallbackModule,
  9218. module
  9219. } = manifestEntry;
  9220. let chunks = [
  9221. ...clientActionModule ? [
  9222. {
  9223. module: clientActionModule,
  9224. varName: `${routeVarName}_clientAction`
  9225. }
  9226. ] : [],
  9227. ...clientLoaderModule ? [
  9228. {
  9229. module: clientLoaderModule,
  9230. varName: `${routeVarName}_clientLoader`
  9231. }
  9232. ] : [],
  9233. ...clientMiddlewareModule ? [
  9234. {
  9235. module: clientMiddlewareModule,
  9236. varName: `${routeVarName}_clientMiddleware`
  9237. }
  9238. ] : [],
  9239. ...hydrateFallbackModule ? [
  9240. {
  9241. module: hydrateFallbackModule,
  9242. varName: `${routeVarName}_HydrateFallback`
  9243. }
  9244. ] : [],
  9245. { module, varName: `${routeVarName}_main` }
  9246. ];
  9247. if (chunks.length === 1) {
  9248. return `import * as ${routeVarName} from ${JSON.stringify(module)};`;
  9249. }
  9250. let chunkImportsSnippet = chunks.map((chunk) => `import * as ${chunk.varName} from "${chunk.module}";`).join("\n");
  9251. let mergedChunksSnippet = `const ${routeVarName} = {${chunks.map((chunk) => `...${chunk.varName}`).join(",")}};`;
  9252. return [chunkImportsSnippet, mergedChunksSnippet].join("\n");
  9253. }).join("\n")}
  9254. ${enableFogOfWar ? (
  9255. // Inline a minimal manifest with the SSR matches
  9256. `window.__reactRouterManifest = ${JSON.stringify(
  9257. getPartialManifest(manifest, router),
  9258. null,
  9259. 2
  9260. )};`
  9261. ) : ""}
  9262. window.__reactRouterRouteModules = {${matches.map((match, index) => `${JSON.stringify(match.route.id)}:route${index}`).join(",")}};
  9263. import(${JSON.stringify(manifest.entry.module)});`;
  9264. return /* @__PURE__ */ React8.createElement(React8.Fragment, null, /* @__PURE__ */ React8.createElement(
  9265. "script",
  9266. {
  9267. ...scriptProps,
  9268. suppressHydrationWarning: true,
  9269. dangerouslySetInnerHTML: { __html: contextScript },
  9270. type: void 0
  9271. }
  9272. ), /* @__PURE__ */ React8.createElement(
  9273. "script",
  9274. {
  9275. ...scriptProps,
  9276. suppressHydrationWarning: true,
  9277. dangerouslySetInnerHTML: { __html: routeModulesScript },
  9278. type: "module",
  9279. async: true
  9280. }
  9281. ));
  9282. }, []);
  9283. let preloads = isHydrated || isRSCRouterContext ? [] : dedupe(
  9284. manifest.entry.imports.concat(
  9285. getModuleLinkHrefs(matches, manifest, {
  9286. includeHydrateFallback: true
  9287. })
  9288. )
  9289. );
  9290. let sri = typeof manifest.sri === "object" ? manifest.sri : {};
  9291. warnOnce(
  9292. !isRSCRouterContext,
  9293. "The <Scripts /> element is a no-op when using RSC and can be safely removed."
  9294. );
  9295. return isHydrated || isRSCRouterContext ? null : /* @__PURE__ */ React8.createElement(React8.Fragment, null, typeof manifest.sri === "object" ? /* @__PURE__ */ React8.createElement(
  9296. "script",
  9297. {
  9298. "rr-importmap": "",
  9299. type: "importmap",
  9300. suppressHydrationWarning: true,
  9301. dangerouslySetInnerHTML: {
  9302. __html: JSON.stringify({
  9303. integrity: sri
  9304. })
  9305. }
  9306. }
  9307. ) : null, !enableFogOfWar ? /* @__PURE__ */ React8.createElement(
  9308. "link",
  9309. {
  9310. rel: "modulepreload",
  9311. href: manifest.url,
  9312. crossOrigin: scriptProps.crossOrigin,
  9313. integrity: sri[manifest.url],
  9314. suppressHydrationWarning: true
  9315. }
  9316. ) : null, /* @__PURE__ */ React8.createElement(
  9317. "link",
  9318. {
  9319. rel: "modulepreload",
  9320. href: manifest.entry.module,
  9321. crossOrigin: scriptProps.crossOrigin,
  9322. integrity: sri[manifest.entry.module],
  9323. suppressHydrationWarning: true
  9324. }
  9325. ), preloads.map((path) => /* @__PURE__ */ React8.createElement(
  9326. "link",
  9327. {
  9328. key: path,
  9329. rel: "modulepreload",
  9330. href: path,
  9331. crossOrigin: scriptProps.crossOrigin,
  9332. integrity: sri[path],
  9333. suppressHydrationWarning: true
  9334. }
  9335. )), initialScripts);
  9336. }
  9337. function dedupe(array) {
  9338. return [...new Set(array)];
  9339. }
  9340. function mergeRefs(...refs) {
  9341. return (value) => {
  9342. refs.forEach((ref) => {
  9343. if (typeof ref === "function") {
  9344. ref(value);
  9345. } else if (ref != null) {
  9346. ref.current = value;
  9347. }
  9348. });
  9349. };
  9350. }
  9351. // lib/dom/ssr/errorBoundaries.tsx
  9352. var RemixErrorBoundary = class extends React9.Component {
  9353. constructor(props) {
  9354. super(props);
  9355. this.state = { error: props.error || null, location: props.location };
  9356. }
  9357. static getDerivedStateFromError(error) {
  9358. return { error };
  9359. }
  9360. static getDerivedStateFromProps(props, state) {
  9361. if (state.location !== props.location) {
  9362. return { error: props.error || null, location: props.location };
  9363. }
  9364. return { error: props.error || state.error, location: state.location };
  9365. }
  9366. render() {
  9367. if (this.state.error) {
  9368. return /* @__PURE__ */ React9.createElement(
  9369. RemixRootDefaultErrorBoundary,
  9370. {
  9371. error: this.state.error,
  9372. isOutsideRemixApp: true
  9373. }
  9374. );
  9375. } else {
  9376. return this.props.children;
  9377. }
  9378. }
  9379. };
  9380. function RemixRootDefaultErrorBoundary({
  9381. error,
  9382. isOutsideRemixApp
  9383. }) {
  9384. console.error(error);
  9385. let heyDeveloper = /* @__PURE__ */ React9.createElement(
  9386. "script",
  9387. {
  9388. dangerouslySetInnerHTML: {
  9389. __html: `
  9390. console.log(
  9391. "\u{1F4BF} Hey developer \u{1F44B}. You can provide a way better UX than this when your app throws errors. Check out https://reactrouter.com/how-to/error-boundary for more information."
  9392. );
  9393. `
  9394. }
  9395. }
  9396. );
  9397. if (isRouteErrorResponse(error)) {
  9398. return /* @__PURE__ */ React9.createElement(BoundaryShell, { title: "Unhandled Thrown Response!" }, /* @__PURE__ */ React9.createElement("h1", { style: { fontSize: "24px" } }, error.status, " ", error.statusText), ENABLE_DEV_WARNINGS ? heyDeveloper : null);
  9399. }
  9400. let errorInstance;
  9401. if (error instanceof Error) {
  9402. errorInstance = error;
  9403. } else {
  9404. let errorString = error == null ? "Unknown Error" : typeof error === "object" && "toString" in error ? error.toString() : JSON.stringify(error);
  9405. errorInstance = new Error(errorString);
  9406. }
  9407. return /* @__PURE__ */ React9.createElement(
  9408. BoundaryShell,
  9409. {
  9410. title: "Application Error!",
  9411. isOutsideRemixApp
  9412. },
  9413. /* @__PURE__ */ React9.createElement("h1", { style: { fontSize: "24px" } }, "Application Error"),
  9414. /* @__PURE__ */ React9.createElement(
  9415. "pre",
  9416. {
  9417. style: {
  9418. padding: "2rem",
  9419. background: "hsla(10, 50%, 50%, 0.1)",
  9420. color: "red",
  9421. overflow: "auto"
  9422. }
  9423. },
  9424. errorInstance.stack
  9425. ),
  9426. heyDeveloper
  9427. );
  9428. }
  9429. function BoundaryShell({
  9430. title,
  9431. renderScripts,
  9432. isOutsideRemixApp,
  9433. children
  9434. }) {
  9435. let { routeModules } = useFrameworkContext();
  9436. if (routeModules.root?.Layout && !isOutsideRemixApp) {
  9437. return children;
  9438. }
  9439. return /* @__PURE__ */ React9.createElement("html", { lang: "en" }, /* @__PURE__ */ React9.createElement("head", null, /* @__PURE__ */ React9.createElement("meta", { charSet: "utf-8" }), /* @__PURE__ */ React9.createElement(
  9440. "meta",
  9441. {
  9442. name: "viewport",
  9443. content: "width=device-width,initial-scale=1,viewport-fit=cover"
  9444. }
  9445. ), /* @__PURE__ */ React9.createElement("title", null, title)), /* @__PURE__ */ React9.createElement("body", null, /* @__PURE__ */ React9.createElement("main", { style: { fontFamily: "system-ui, sans-serif", padding: "2rem" } }, children, renderScripts ? /* @__PURE__ */ React9.createElement(Scripts, null) : null)));
  9446. }
  9447. // lib/dom/lib.tsx
  9448. import * as React10 from "react";
  9449. var isBrowser = typeof window !== "undefined" && typeof window.document !== "undefined" && typeof window.document.createElement !== "undefined";
  9450. try {
  9451. if (isBrowser) {
  9452. window.__reactRouterVersion = // @ts-expect-error
  9453. "7.10.1";
  9454. }
  9455. } catch (e) {
  9456. }
  9457. function createBrowserRouter(routes, opts) {
  9458. return createRouter({
  9459. basename: opts?.basename,
  9460. getContext: opts?.getContext,
  9461. future: opts?.future,
  9462. history: createBrowserHistory({ window: opts?.window }),
  9463. hydrationData: opts?.hydrationData || parseHydrationData(),
  9464. routes,
  9465. mapRouteProperties,
  9466. hydrationRouteProperties,
  9467. dataStrategy: opts?.dataStrategy,
  9468. patchRoutesOnNavigation: opts?.patchRoutesOnNavigation,
  9469. window: opts?.window,
  9470. unstable_instrumentations: opts?.unstable_instrumentations
  9471. }).initialize();
  9472. }
  9473. function createHashRouter(routes, opts) {
  9474. return createRouter({
  9475. basename: opts?.basename,
  9476. getContext: opts?.getContext,
  9477. future: opts?.future,
  9478. history: createHashHistory({ window: opts?.window }),
  9479. hydrationData: opts?.hydrationData || parseHydrationData(),
  9480. routes,
  9481. mapRouteProperties,
  9482. hydrationRouteProperties,
  9483. dataStrategy: opts?.dataStrategy,
  9484. patchRoutesOnNavigation: opts?.patchRoutesOnNavigation,
  9485. window: opts?.window,
  9486. unstable_instrumentations: opts?.unstable_instrumentations
  9487. }).initialize();
  9488. }
  9489. function parseHydrationData() {
  9490. let state = window?.__staticRouterHydrationData;
  9491. if (state && state.errors) {
  9492. state = {
  9493. ...state,
  9494. errors: deserializeErrors(state.errors)
  9495. };
  9496. }
  9497. return state;
  9498. }
  9499. function deserializeErrors(errors) {
  9500. if (!errors) return null;
  9501. let entries = Object.entries(errors);
  9502. let serialized = {};
  9503. for (let [key, val] of entries) {
  9504. if (val && val.__type === "RouteErrorResponse") {
  9505. serialized[key] = new ErrorResponseImpl(
  9506. val.status,
  9507. val.statusText,
  9508. val.data,
  9509. val.internal === true
  9510. );
  9511. } else if (val && val.__type === "Error") {
  9512. if (val.__subType) {
  9513. let ErrorConstructor = window[val.__subType];
  9514. if (typeof ErrorConstructor === "function") {
  9515. try {
  9516. let error = new ErrorConstructor(val.message);
  9517. error.stack = "";
  9518. serialized[key] = error;
  9519. } catch (e) {
  9520. }
  9521. }
  9522. }
  9523. if (serialized[key] == null) {
  9524. let error = new Error(val.message);
  9525. error.stack = "";
  9526. serialized[key] = error;
  9527. }
  9528. } else {
  9529. serialized[key] = val;
  9530. }
  9531. }
  9532. return serialized;
  9533. }
  9534. function BrowserRouter({
  9535. basename,
  9536. children,
  9537. unstable_useTransitions,
  9538. window: window2
  9539. }) {
  9540. let historyRef = React10.useRef();
  9541. if (historyRef.current == null) {
  9542. historyRef.current = createBrowserHistory({ window: window2, v5Compat: true });
  9543. }
  9544. let history = historyRef.current;
  9545. let [state, setStateImpl] = React10.useState({
  9546. action: history.action,
  9547. location: history.location
  9548. });
  9549. let setState = React10.useCallback(
  9550. (newState) => {
  9551. if (unstable_useTransitions === false) {
  9552. setStateImpl(newState);
  9553. } else {
  9554. React10.startTransition(() => setStateImpl(newState));
  9555. }
  9556. },
  9557. [unstable_useTransitions]
  9558. );
  9559. React10.useLayoutEffect(() => history.listen(setState), [history, setState]);
  9560. return /* @__PURE__ */ React10.createElement(
  9561. Router,
  9562. {
  9563. basename,
  9564. children,
  9565. location: state.location,
  9566. navigationType: state.action,
  9567. navigator: history,
  9568. unstable_useTransitions: unstable_useTransitions === true
  9569. }
  9570. );
  9571. }
  9572. function HashRouter({
  9573. basename,
  9574. children,
  9575. unstable_useTransitions,
  9576. window: window2
  9577. }) {
  9578. let historyRef = React10.useRef();
  9579. if (historyRef.current == null) {
  9580. historyRef.current = createHashHistory({ window: window2, v5Compat: true });
  9581. }
  9582. let history = historyRef.current;
  9583. let [state, setStateImpl] = React10.useState({
  9584. action: history.action,
  9585. location: history.location
  9586. });
  9587. let setState = React10.useCallback(
  9588. (newState) => {
  9589. if (unstable_useTransitions === false) {
  9590. setStateImpl(newState);
  9591. } else {
  9592. React10.startTransition(() => setStateImpl(newState));
  9593. }
  9594. },
  9595. [unstable_useTransitions]
  9596. );
  9597. React10.useLayoutEffect(() => history.listen(setState), [history, setState]);
  9598. return /* @__PURE__ */ React10.createElement(
  9599. Router,
  9600. {
  9601. basename,
  9602. children,
  9603. location: state.location,
  9604. navigationType: state.action,
  9605. navigator: history,
  9606. unstable_useTransitions: unstable_useTransitions === true
  9607. }
  9608. );
  9609. }
  9610. function HistoryRouter({
  9611. basename,
  9612. children,
  9613. history,
  9614. unstable_useTransitions
  9615. }) {
  9616. let [state, setStateImpl] = React10.useState({
  9617. action: history.action,
  9618. location: history.location
  9619. });
  9620. let setState = React10.useCallback(
  9621. (newState) => {
  9622. if (unstable_useTransitions === false) {
  9623. setStateImpl(newState);
  9624. } else {
  9625. React10.startTransition(() => setStateImpl(newState));
  9626. }
  9627. },
  9628. [unstable_useTransitions]
  9629. );
  9630. React10.useLayoutEffect(() => history.listen(setState), [history, setState]);
  9631. return /* @__PURE__ */ React10.createElement(
  9632. Router,
  9633. {
  9634. basename,
  9635. children,
  9636. location: state.location,
  9637. navigationType: state.action,
  9638. navigator: history,
  9639. unstable_useTransitions: unstable_useTransitions === true
  9640. }
  9641. );
  9642. }
  9643. HistoryRouter.displayName = "unstable_HistoryRouter";
  9644. var ABSOLUTE_URL_REGEX2 = /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i;
  9645. var Link = React10.forwardRef(
  9646. function LinkWithRef({
  9647. onClick,
  9648. discover = "render",
  9649. prefetch = "none",
  9650. relative,
  9651. reloadDocument,
  9652. replace: replace2,
  9653. state,
  9654. target,
  9655. to,
  9656. preventScrollReset,
  9657. viewTransition,
  9658. ...rest
  9659. }, forwardedRef) {
  9660. let { basename, unstable_useTransitions } = React10.useContext(NavigationContext);
  9661. let isAbsolute = typeof to === "string" && ABSOLUTE_URL_REGEX2.test(to);
  9662. let absoluteHref;
  9663. let isExternal = false;
  9664. if (typeof to === "string" && isAbsolute) {
  9665. absoluteHref = to;
  9666. if (isBrowser) {
  9667. try {
  9668. let currentUrl = new URL(window.location.href);
  9669. let targetUrl = to.startsWith("//") ? new URL(currentUrl.protocol + to) : new URL(to);
  9670. let path = stripBasename(targetUrl.pathname, basename);
  9671. if (targetUrl.origin === currentUrl.origin && path != null) {
  9672. to = path + targetUrl.search + targetUrl.hash;
  9673. } else {
  9674. isExternal = true;
  9675. }
  9676. } catch (e) {
  9677. warning(
  9678. false,
  9679. `<Link to="${to}"> contains an invalid URL which will probably break when clicked - please update to a valid URL path.`
  9680. );
  9681. }
  9682. }
  9683. }
  9684. let href = useHref(to, { relative });
  9685. let [shouldPrefetch, prefetchRef, prefetchHandlers] = usePrefetchBehavior(
  9686. prefetch,
  9687. rest
  9688. );
  9689. let internalOnClick = useLinkClickHandler(to, {
  9690. replace: replace2,
  9691. state,
  9692. target,
  9693. preventScrollReset,
  9694. relative,
  9695. viewTransition,
  9696. unstable_useTransitions
  9697. });
  9698. function handleClick(event) {
  9699. if (onClick) onClick(event);
  9700. if (!event.defaultPrevented) {
  9701. internalOnClick(event);
  9702. }
  9703. }
  9704. let link = (
  9705. // eslint-disable-next-line jsx-a11y/anchor-has-content
  9706. /* @__PURE__ */ React10.createElement(
  9707. "a",
  9708. {
  9709. ...rest,
  9710. ...prefetchHandlers,
  9711. href: absoluteHref || href,
  9712. onClick: isExternal || reloadDocument ? onClick : handleClick,
  9713. ref: mergeRefs(forwardedRef, prefetchRef),
  9714. target,
  9715. "data-discover": !isAbsolute && discover === "render" ? "true" : void 0
  9716. }
  9717. )
  9718. );
  9719. return shouldPrefetch && !isAbsolute ? /* @__PURE__ */ React10.createElement(React10.Fragment, null, link, /* @__PURE__ */ React10.createElement(PrefetchPageLinks, { page: href })) : link;
  9720. }
  9721. );
  9722. Link.displayName = "Link";
  9723. var NavLink = React10.forwardRef(
  9724. function NavLinkWithRef({
  9725. "aria-current": ariaCurrentProp = "page",
  9726. caseSensitive = false,
  9727. className: classNameProp = "",
  9728. end = false,
  9729. style: styleProp,
  9730. to,
  9731. viewTransition,
  9732. children,
  9733. ...rest
  9734. }, ref) {
  9735. let path = useResolvedPath(to, { relative: rest.relative });
  9736. let location = useLocation();
  9737. let routerState = React10.useContext(DataRouterStateContext);
  9738. let { navigator, basename } = React10.useContext(NavigationContext);
  9739. let isTransitioning = routerState != null && // Conditional usage is OK here because the usage of a data router is static
  9740. // eslint-disable-next-line react-hooks/rules-of-hooks
  9741. useViewTransitionState(path) && viewTransition === true;
  9742. let toPathname = navigator.encodeLocation ? navigator.encodeLocation(path).pathname : path.pathname;
  9743. let locationPathname = location.pathname;
  9744. let nextLocationPathname = routerState && routerState.navigation && routerState.navigation.location ? routerState.navigation.location.pathname : null;
  9745. if (!caseSensitive) {
  9746. locationPathname = locationPathname.toLowerCase();
  9747. nextLocationPathname = nextLocationPathname ? nextLocationPathname.toLowerCase() : null;
  9748. toPathname = toPathname.toLowerCase();
  9749. }
  9750. if (nextLocationPathname && basename) {
  9751. nextLocationPathname = stripBasename(nextLocationPathname, basename) || nextLocationPathname;
  9752. }
  9753. const endSlashPosition = toPathname !== "/" && toPathname.endsWith("/") ? toPathname.length - 1 : toPathname.length;
  9754. let isActive = locationPathname === toPathname || !end && locationPathname.startsWith(toPathname) && locationPathname.charAt(endSlashPosition) === "/";
  9755. let isPending = nextLocationPathname != null && (nextLocationPathname === toPathname || !end && nextLocationPathname.startsWith(toPathname) && nextLocationPathname.charAt(toPathname.length) === "/");
  9756. let renderProps = {
  9757. isActive,
  9758. isPending,
  9759. isTransitioning
  9760. };
  9761. let ariaCurrent = isActive ? ariaCurrentProp : void 0;
  9762. let className;
  9763. if (typeof classNameProp === "function") {
  9764. className = classNameProp(renderProps);
  9765. } else {
  9766. className = [
  9767. classNameProp,
  9768. isActive ? "active" : null,
  9769. isPending ? "pending" : null,
  9770. isTransitioning ? "transitioning" : null
  9771. ].filter(Boolean).join(" ");
  9772. }
  9773. let style = typeof styleProp === "function" ? styleProp(renderProps) : styleProp;
  9774. return /* @__PURE__ */ React10.createElement(
  9775. Link,
  9776. {
  9777. ...rest,
  9778. "aria-current": ariaCurrent,
  9779. className,
  9780. ref,
  9781. style,
  9782. to,
  9783. viewTransition
  9784. },
  9785. typeof children === "function" ? children(renderProps) : children
  9786. );
  9787. }
  9788. );
  9789. NavLink.displayName = "NavLink";
  9790. var Form = React10.forwardRef(
  9791. ({
  9792. discover = "render",
  9793. fetcherKey,
  9794. navigate,
  9795. reloadDocument,
  9796. replace: replace2,
  9797. state,
  9798. method = defaultMethod,
  9799. action,
  9800. onSubmit,
  9801. relative,
  9802. preventScrollReset,
  9803. viewTransition,
  9804. ...props
  9805. }, forwardedRef) => {
  9806. let { unstable_useTransitions } = React10.useContext(NavigationContext);
  9807. let submit = useSubmit();
  9808. let formAction = useFormAction(action, { relative });
  9809. let formMethod = method.toLowerCase() === "get" ? "get" : "post";
  9810. let isAbsolute = typeof action === "string" && ABSOLUTE_URL_REGEX2.test(action);
  9811. let submitHandler = (event) => {
  9812. onSubmit && onSubmit(event);
  9813. if (event.defaultPrevented) return;
  9814. event.preventDefault();
  9815. let submitter = event.nativeEvent.submitter;
  9816. let submitMethod = submitter?.getAttribute("formmethod") || method;
  9817. let doSubmit = () => submit(submitter || event.currentTarget, {
  9818. fetcherKey,
  9819. method: submitMethod,
  9820. navigate,
  9821. replace: replace2,
  9822. state,
  9823. relative,
  9824. preventScrollReset,
  9825. viewTransition
  9826. });
  9827. if (unstable_useTransitions && navigate !== false) {
  9828. React10.startTransition(() => doSubmit());
  9829. } else {
  9830. doSubmit();
  9831. }
  9832. };
  9833. return /* @__PURE__ */ React10.createElement(
  9834. "form",
  9835. {
  9836. ref: forwardedRef,
  9837. method: formMethod,
  9838. action: formAction,
  9839. onSubmit: reloadDocument ? onSubmit : submitHandler,
  9840. ...props,
  9841. "data-discover": !isAbsolute && discover === "render" ? "true" : void 0
  9842. }
  9843. );
  9844. }
  9845. );
  9846. Form.displayName = "Form";
  9847. function ScrollRestoration({
  9848. getKey,
  9849. storageKey,
  9850. ...props
  9851. }) {
  9852. let remixContext = React10.useContext(FrameworkContext);
  9853. let { basename } = React10.useContext(NavigationContext);
  9854. let location = useLocation();
  9855. let matches = useMatches();
  9856. useScrollRestoration({ getKey, storageKey });
  9857. let ssrKey = React10.useMemo(
  9858. () => {
  9859. if (!remixContext || !getKey) return null;
  9860. let userKey = getScrollRestorationKey(
  9861. location,
  9862. matches,
  9863. basename,
  9864. getKey
  9865. );
  9866. return userKey !== location.key ? userKey : null;
  9867. },
  9868. // Nah, we only need this the first time for the SSR render
  9869. // eslint-disable-next-line react-hooks/exhaustive-deps
  9870. []
  9871. );
  9872. if (!remixContext || remixContext.isSpaMode) {
  9873. return null;
  9874. }
  9875. let restoreScroll = ((storageKey2, restoreKey) => {
  9876. if (!window.history.state || !window.history.state.key) {
  9877. let key = Math.random().toString(32).slice(2);
  9878. window.history.replaceState({ key }, "");
  9879. }
  9880. try {
  9881. let positions = JSON.parse(sessionStorage.getItem(storageKey2) || "{}");
  9882. let storedY = positions[restoreKey || window.history.state.key];
  9883. if (typeof storedY === "number") {
  9884. window.scrollTo(0, storedY);
  9885. }
  9886. } catch (error) {
  9887. console.error(error);
  9888. sessionStorage.removeItem(storageKey2);
  9889. }
  9890. }).toString();
  9891. return /* @__PURE__ */ React10.createElement(
  9892. "script",
  9893. {
  9894. ...props,
  9895. suppressHydrationWarning: true,
  9896. dangerouslySetInnerHTML: {
  9897. __html: `(${restoreScroll})(${JSON.stringify(
  9898. storageKey || SCROLL_RESTORATION_STORAGE_KEY
  9899. )}, ${JSON.stringify(ssrKey)})`
  9900. }
  9901. }
  9902. );
  9903. }
  9904. ScrollRestoration.displayName = "ScrollRestoration";
  9905. function getDataRouterConsoleError2(hookName) {
  9906. return `${hookName} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`;
  9907. }
  9908. function useDataRouterContext3(hookName) {
  9909. let ctx = React10.useContext(DataRouterContext);
  9910. invariant(ctx, getDataRouterConsoleError2(hookName));
  9911. return ctx;
  9912. }
  9913. function useDataRouterState2(hookName) {
  9914. let state = React10.useContext(DataRouterStateContext);
  9915. invariant(state, getDataRouterConsoleError2(hookName));
  9916. return state;
  9917. }
  9918. function useLinkClickHandler(to, {
  9919. target,
  9920. replace: replaceProp,
  9921. state,
  9922. preventScrollReset,
  9923. relative,
  9924. viewTransition,
  9925. unstable_useTransitions
  9926. } = {}) {
  9927. let navigate = useNavigate();
  9928. let location = useLocation();
  9929. let path = useResolvedPath(to, { relative });
  9930. return React10.useCallback(
  9931. (event) => {
  9932. if (shouldProcessLinkClick(event, target)) {
  9933. event.preventDefault();
  9934. let replace2 = replaceProp !== void 0 ? replaceProp : createPath(location) === createPath(path);
  9935. let doNavigate = () => navigate(to, {
  9936. replace: replace2,
  9937. state,
  9938. preventScrollReset,
  9939. relative,
  9940. viewTransition
  9941. });
  9942. if (unstable_useTransitions) {
  9943. React10.startTransition(() => doNavigate());
  9944. } else {
  9945. doNavigate();
  9946. }
  9947. }
  9948. },
  9949. [
  9950. location,
  9951. navigate,
  9952. path,
  9953. replaceProp,
  9954. state,
  9955. target,
  9956. to,
  9957. preventScrollReset,
  9958. relative,
  9959. viewTransition,
  9960. unstable_useTransitions
  9961. ]
  9962. );
  9963. }
  9964. function useSearchParams(defaultInit) {
  9965. warning(
  9966. typeof URLSearchParams !== "undefined",
  9967. `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.`
  9968. );
  9969. let defaultSearchParamsRef = React10.useRef(createSearchParams(defaultInit));
  9970. let hasSetSearchParamsRef = React10.useRef(false);
  9971. let location = useLocation();
  9972. let searchParams = React10.useMemo(
  9973. () => (
  9974. // Only merge in the defaults if we haven't yet called setSearchParams.
  9975. // Once we call that we want those to take precedence, otherwise you can't
  9976. // remove a param with setSearchParams({}) if it has an initial value
  9977. getSearchParamsForLocation(
  9978. location.search,
  9979. hasSetSearchParamsRef.current ? null : defaultSearchParamsRef.current
  9980. )
  9981. ),
  9982. [location.search]
  9983. );
  9984. let navigate = useNavigate();
  9985. let setSearchParams = React10.useCallback(
  9986. (nextInit, navigateOptions) => {
  9987. const newSearchParams = createSearchParams(
  9988. typeof nextInit === "function" ? nextInit(new URLSearchParams(searchParams)) : nextInit
  9989. );
  9990. hasSetSearchParamsRef.current = true;
  9991. navigate("?" + newSearchParams, navigateOptions);
  9992. },
  9993. [navigate, searchParams]
  9994. );
  9995. return [searchParams, setSearchParams];
  9996. }
  9997. var fetcherId = 0;
  9998. var getUniqueFetcherId = () => `__${String(++fetcherId)}__`;
  9999. function useSubmit() {
  10000. let { router } = useDataRouterContext3("useSubmit" /* UseSubmit */);
  10001. let { basename } = React10.useContext(NavigationContext);
  10002. let currentRouteId = useRouteId();
  10003. let routerFetch = router.fetch;
  10004. let routerNavigate = router.navigate;
  10005. return React10.useCallback(
  10006. async (target, options = {}) => {
  10007. let { action, method, encType, formData, body } = getFormSubmissionInfo(
  10008. target,
  10009. basename
  10010. );
  10011. if (options.navigate === false) {
  10012. let key = options.fetcherKey || getUniqueFetcherId();
  10013. await routerFetch(key, currentRouteId, options.action || action, {
  10014. preventScrollReset: options.preventScrollReset,
  10015. formData,
  10016. body,
  10017. formMethod: options.method || method,
  10018. formEncType: options.encType || encType,
  10019. flushSync: options.flushSync
  10020. });
  10021. } else {
  10022. await routerNavigate(options.action || action, {
  10023. preventScrollReset: options.preventScrollReset,
  10024. formData,
  10025. body,
  10026. formMethod: options.method || method,
  10027. formEncType: options.encType || encType,
  10028. replace: options.replace,
  10029. state: options.state,
  10030. fromRouteId: currentRouteId,
  10031. flushSync: options.flushSync,
  10032. viewTransition: options.viewTransition
  10033. });
  10034. }
  10035. },
  10036. [routerFetch, routerNavigate, basename, currentRouteId]
  10037. );
  10038. }
  10039. function useFormAction(action, { relative } = {}) {
  10040. let { basename } = React10.useContext(NavigationContext);
  10041. let routeContext = React10.useContext(RouteContext);
  10042. invariant(routeContext, "useFormAction must be used inside a RouteContext");
  10043. let [match] = routeContext.matches.slice(-1);
  10044. let path = { ...useResolvedPath(action ? action : ".", { relative }) };
  10045. let location = useLocation();
  10046. if (action == null) {
  10047. path.search = location.search;
  10048. let params = new URLSearchParams(path.search);
  10049. let indexValues = params.getAll("index");
  10050. let hasNakedIndexParam = indexValues.some((v) => v === "");
  10051. if (hasNakedIndexParam) {
  10052. params.delete("index");
  10053. indexValues.filter((v) => v).forEach((v) => params.append("index", v));
  10054. let qs = params.toString();
  10055. path.search = qs ? `?${qs}` : "";
  10056. }
  10057. }
  10058. if ((!action || action === ".") && match.route.index) {
  10059. path.search = path.search ? path.search.replace(/^\?/, "?index&") : "?index";
  10060. }
  10061. if (basename !== "/") {
  10062. path.pathname = path.pathname === "/" ? basename : joinPaths([basename, path.pathname]);
  10063. }
  10064. return createPath(path);
  10065. }
  10066. function useFetcher({
  10067. key
  10068. } = {}) {
  10069. let { router } = useDataRouterContext3("useFetcher" /* UseFetcher */);
  10070. let state = useDataRouterState2("useFetcher" /* UseFetcher */);
  10071. let fetcherData = React10.useContext(FetchersContext);
  10072. let route = React10.useContext(RouteContext);
  10073. let routeId = route.matches[route.matches.length - 1]?.route.id;
  10074. invariant(fetcherData, `useFetcher must be used inside a FetchersContext`);
  10075. invariant(route, `useFetcher must be used inside a RouteContext`);
  10076. invariant(
  10077. routeId != null,
  10078. `useFetcher can only be used on routes that contain a unique "id"`
  10079. );
  10080. let defaultKey = React10.useId();
  10081. let [fetcherKey, setFetcherKey] = React10.useState(key || defaultKey);
  10082. if (key && key !== fetcherKey) {
  10083. setFetcherKey(key);
  10084. }
  10085. let { deleteFetcher, getFetcher, resetFetcher, fetch: routerFetch } = router;
  10086. React10.useEffect(() => {
  10087. getFetcher(fetcherKey);
  10088. return () => deleteFetcher(fetcherKey);
  10089. }, [deleteFetcher, getFetcher, fetcherKey]);
  10090. let load = React10.useCallback(
  10091. async (href, opts) => {
  10092. invariant(routeId, "No routeId available for fetcher.load()");
  10093. await routerFetch(fetcherKey, routeId, href, opts);
  10094. },
  10095. [fetcherKey, routeId, routerFetch]
  10096. );
  10097. let submitImpl = useSubmit();
  10098. let submit = React10.useCallback(
  10099. async (target, opts) => {
  10100. await submitImpl(target, {
  10101. ...opts,
  10102. navigate: false,
  10103. fetcherKey
  10104. });
  10105. },
  10106. [fetcherKey, submitImpl]
  10107. );
  10108. let reset = React10.useCallback(
  10109. (opts) => resetFetcher(fetcherKey, opts),
  10110. [resetFetcher, fetcherKey]
  10111. );
  10112. let FetcherForm = React10.useMemo(() => {
  10113. let FetcherForm2 = React10.forwardRef(
  10114. (props, ref) => {
  10115. return /* @__PURE__ */ React10.createElement(Form, { ...props, navigate: false, fetcherKey, ref });
  10116. }
  10117. );
  10118. FetcherForm2.displayName = "fetcher.Form";
  10119. return FetcherForm2;
  10120. }, [fetcherKey]);
  10121. let fetcher = state.fetchers.get(fetcherKey) || IDLE_FETCHER;
  10122. let data2 = fetcherData.get(fetcherKey);
  10123. let fetcherWithComponents = React10.useMemo(
  10124. () => ({
  10125. Form: FetcherForm,
  10126. submit,
  10127. load,
  10128. reset,
  10129. ...fetcher,
  10130. data: data2
  10131. }),
  10132. [FetcherForm, submit, load, reset, fetcher, data2]
  10133. );
  10134. return fetcherWithComponents;
  10135. }
  10136. function useFetchers() {
  10137. let state = useDataRouterState2("useFetchers" /* UseFetchers */);
  10138. return Array.from(state.fetchers.entries()).map(([key, fetcher]) => ({
  10139. ...fetcher,
  10140. key
  10141. }));
  10142. }
  10143. var SCROLL_RESTORATION_STORAGE_KEY = "react-router-scroll-positions";
  10144. var savedScrollPositions = {};
  10145. function getScrollRestorationKey(location, matches, basename, getKey) {
  10146. let key = null;
  10147. if (getKey) {
  10148. if (basename !== "/") {
  10149. key = getKey(
  10150. {
  10151. ...location,
  10152. pathname: stripBasename(location.pathname, basename) || location.pathname
  10153. },
  10154. matches
  10155. );
  10156. } else {
  10157. key = getKey(location, matches);
  10158. }
  10159. }
  10160. if (key == null) {
  10161. key = location.key;
  10162. }
  10163. return key;
  10164. }
  10165. function useScrollRestoration({
  10166. getKey,
  10167. storageKey
  10168. } = {}) {
  10169. let { router } = useDataRouterContext3("useScrollRestoration" /* UseScrollRestoration */);
  10170. let { restoreScrollPosition, preventScrollReset } = useDataRouterState2(
  10171. "useScrollRestoration" /* UseScrollRestoration */
  10172. );
  10173. let { basename } = React10.useContext(NavigationContext);
  10174. let location = useLocation();
  10175. let matches = useMatches();
  10176. let navigation = useNavigation();
  10177. React10.useEffect(() => {
  10178. window.history.scrollRestoration = "manual";
  10179. return () => {
  10180. window.history.scrollRestoration = "auto";
  10181. };
  10182. }, []);
  10183. usePageHide(
  10184. React10.useCallback(() => {
  10185. if (navigation.state === "idle") {
  10186. let key = getScrollRestorationKey(location, matches, basename, getKey);
  10187. savedScrollPositions[key] = window.scrollY;
  10188. }
  10189. try {
  10190. sessionStorage.setItem(
  10191. storageKey || SCROLL_RESTORATION_STORAGE_KEY,
  10192. JSON.stringify(savedScrollPositions)
  10193. );
  10194. } catch (error) {
  10195. warning(
  10196. false,
  10197. `Failed to save scroll positions in sessionStorage, <ScrollRestoration /> will not work properly (${error}).`
  10198. );
  10199. }
  10200. window.history.scrollRestoration = "auto";
  10201. }, [navigation.state, getKey, basename, location, matches, storageKey])
  10202. );
  10203. if (typeof document !== "undefined") {
  10204. React10.useLayoutEffect(() => {
  10205. try {
  10206. let sessionPositions = sessionStorage.getItem(
  10207. storageKey || SCROLL_RESTORATION_STORAGE_KEY
  10208. );
  10209. if (sessionPositions) {
  10210. savedScrollPositions = JSON.parse(sessionPositions);
  10211. }
  10212. } catch (e) {
  10213. }
  10214. }, [storageKey]);
  10215. React10.useLayoutEffect(() => {
  10216. let disableScrollRestoration = router?.enableScrollRestoration(
  10217. savedScrollPositions,
  10218. () => window.scrollY,
  10219. getKey ? (location2, matches2) => getScrollRestorationKey(location2, matches2, basename, getKey) : void 0
  10220. );
  10221. return () => disableScrollRestoration && disableScrollRestoration();
  10222. }, [router, basename, getKey]);
  10223. React10.useLayoutEffect(() => {
  10224. if (restoreScrollPosition === false) {
  10225. return;
  10226. }
  10227. if (typeof restoreScrollPosition === "number") {
  10228. window.scrollTo(0, restoreScrollPosition);
  10229. return;
  10230. }
  10231. try {
  10232. if (location.hash) {
  10233. let el = document.getElementById(
  10234. decodeURIComponent(location.hash.slice(1))
  10235. );
  10236. if (el) {
  10237. el.scrollIntoView();
  10238. return;
  10239. }
  10240. }
  10241. } catch {
  10242. warning(
  10243. false,
  10244. `"${location.hash.slice(
  10245. 1
  10246. )}" is not a decodable element ID. The view will not scroll to it.`
  10247. );
  10248. }
  10249. if (preventScrollReset === true) {
  10250. return;
  10251. }
  10252. window.scrollTo(0, 0);
  10253. }, [location, restoreScrollPosition, preventScrollReset]);
  10254. }
  10255. }
  10256. function useBeforeUnload(callback, options) {
  10257. let { capture } = options || {};
  10258. React10.useEffect(() => {
  10259. let opts = capture != null ? { capture } : void 0;
  10260. window.addEventListener("beforeunload", callback, opts);
  10261. return () => {
  10262. window.removeEventListener("beforeunload", callback, opts);
  10263. };
  10264. }, [callback, capture]);
  10265. }
  10266. function usePageHide(callback, options) {
  10267. let { capture } = options || {};
  10268. React10.useEffect(() => {
  10269. let opts = capture != null ? { capture } : void 0;
  10270. window.addEventListener("pagehide", callback, opts);
  10271. return () => {
  10272. window.removeEventListener("pagehide", callback, opts);
  10273. };
  10274. }, [callback, capture]);
  10275. }
  10276. function usePrompt({
  10277. when,
  10278. message
  10279. }) {
  10280. let blocker = useBlocker(when);
  10281. React10.useEffect(() => {
  10282. if (blocker.state === "blocked") {
  10283. let proceed = window.confirm(message);
  10284. if (proceed) {
  10285. setTimeout(blocker.proceed, 0);
  10286. } else {
  10287. blocker.reset();
  10288. }
  10289. }
  10290. }, [blocker, message]);
  10291. React10.useEffect(() => {
  10292. if (blocker.state === "blocked" && !when) {
  10293. blocker.reset();
  10294. }
  10295. }, [blocker, when]);
  10296. }
  10297. function useViewTransitionState(to, { relative } = {}) {
  10298. let vtContext = React10.useContext(ViewTransitionContext);
  10299. invariant(
  10300. vtContext != null,
  10301. "`useViewTransitionState` must be used within `react-router-dom`'s `RouterProvider`. Did you accidentally import `RouterProvider` from `react-router`?"
  10302. );
  10303. let { basename } = useDataRouterContext3(
  10304. "useViewTransitionState" /* useViewTransitionState */
  10305. );
  10306. let path = useResolvedPath(to, { relative });
  10307. if (!vtContext.isTransitioning) {
  10308. return false;
  10309. }
  10310. let currentPath = stripBasename(vtContext.currentLocation.pathname, basename) || vtContext.currentLocation.pathname;
  10311. let nextPath = stripBasename(vtContext.nextLocation.pathname, basename) || vtContext.nextLocation.pathname;
  10312. return matchPath(path.pathname, nextPath) != null || matchPath(path.pathname, currentPath) != null;
  10313. }
  10314. // lib/dom/server.tsx
  10315. import * as React11 from "react";
  10316. function StaticRouter({
  10317. basename,
  10318. children,
  10319. location: locationProp = "/"
  10320. }) {
  10321. if (typeof locationProp === "string") {
  10322. locationProp = parsePath(locationProp);
  10323. }
  10324. let action = "POP" /* Pop */;
  10325. let location = {
  10326. pathname: locationProp.pathname || "/",
  10327. search: locationProp.search || "",
  10328. hash: locationProp.hash || "",
  10329. state: locationProp.state != null ? locationProp.state : null,
  10330. key: locationProp.key || "default"
  10331. };
  10332. let staticNavigator = getStatelessNavigator();
  10333. return /* @__PURE__ */ React11.createElement(
  10334. Router,
  10335. {
  10336. basename,
  10337. children,
  10338. location,
  10339. navigationType: action,
  10340. navigator: staticNavigator,
  10341. static: true,
  10342. unstable_useTransitions: false
  10343. }
  10344. );
  10345. }
  10346. function StaticRouterProvider({
  10347. context,
  10348. router,
  10349. hydrate: hydrate2 = true,
  10350. nonce
  10351. }) {
  10352. invariant(
  10353. router && context,
  10354. "You must provide `router` and `context` to <StaticRouterProvider>"
  10355. );
  10356. let dataRouterContext = {
  10357. router,
  10358. navigator: getStatelessNavigator(),
  10359. static: true,
  10360. staticContext: context,
  10361. basename: context.basename || "/"
  10362. };
  10363. let fetchersContext = /* @__PURE__ */ new Map();
  10364. let hydrateScript = "";
  10365. if (hydrate2 !== false) {
  10366. let data2 = {
  10367. loaderData: context.loaderData,
  10368. actionData: context.actionData,
  10369. errors: serializeErrors(context.errors)
  10370. };
  10371. let json = htmlEscape(JSON.stringify(JSON.stringify(data2)));
  10372. hydrateScript = `window.__staticRouterHydrationData = JSON.parse(${json});`;
  10373. }
  10374. let { state } = dataRouterContext.router;
  10375. return /* @__PURE__ */ React11.createElement(React11.Fragment, null, /* @__PURE__ */ React11.createElement(DataRouterContext.Provider, { value: dataRouterContext }, /* @__PURE__ */ React11.createElement(DataRouterStateContext.Provider, { value: state }, /* @__PURE__ */ React11.createElement(FetchersContext.Provider, { value: fetchersContext }, /* @__PURE__ */ React11.createElement(ViewTransitionContext.Provider, { value: { isTransitioning: false } }, /* @__PURE__ */ React11.createElement(
  10376. Router,
  10377. {
  10378. basename: dataRouterContext.basename,
  10379. location: state.location,
  10380. navigationType: state.historyAction,
  10381. navigator: dataRouterContext.navigator,
  10382. static: dataRouterContext.static,
  10383. unstable_useTransitions: false
  10384. },
  10385. /* @__PURE__ */ React11.createElement(
  10386. DataRoutes2,
  10387. {
  10388. routes: router.routes,
  10389. future: router.future,
  10390. state
  10391. }
  10392. )
  10393. ))))), hydrateScript ? /* @__PURE__ */ React11.createElement(
  10394. "script",
  10395. {
  10396. suppressHydrationWarning: true,
  10397. nonce,
  10398. dangerouslySetInnerHTML: { __html: hydrateScript }
  10399. }
  10400. ) : null);
  10401. }
  10402. function DataRoutes2({
  10403. routes,
  10404. future,
  10405. state
  10406. }) {
  10407. return useRoutesImpl(routes, void 0, state, void 0, future);
  10408. }
  10409. function serializeErrors(errors) {
  10410. if (!errors) return null;
  10411. let entries = Object.entries(errors);
  10412. let serialized = {};
  10413. for (let [key, val] of entries) {
  10414. if (isRouteErrorResponse(val)) {
  10415. serialized[key] = { ...val, __type: "RouteErrorResponse" };
  10416. } else if (val instanceof Error) {
  10417. serialized[key] = {
  10418. message: val.message,
  10419. __type: "Error",
  10420. // If this is a subclass (i.e., ReferenceError), send up the type so we
  10421. // can re-create the same type during hydration.
  10422. ...val.name !== "Error" ? {
  10423. __subType: val.name
  10424. } : {}
  10425. };
  10426. } else {
  10427. serialized[key] = val;
  10428. }
  10429. }
  10430. return serialized;
  10431. }
  10432. function getStatelessNavigator() {
  10433. return {
  10434. createHref,
  10435. encodeLocation,
  10436. push(to) {
  10437. throw new Error(
  10438. `You cannot use navigator.push() on the server because it is a stateless environment. This error was probably triggered when you did a \`navigate(${JSON.stringify(to)})\` somewhere in your app.`
  10439. );
  10440. },
  10441. replace(to) {
  10442. throw new Error(
  10443. `You cannot use navigator.replace() on the server because it is a stateless environment. This error was probably triggered when you did a \`navigate(${JSON.stringify(to)}, { replace: true })\` somewhere in your app.`
  10444. );
  10445. },
  10446. go(delta) {
  10447. throw new Error(
  10448. `You cannot use navigator.go() on the server because it is a stateless environment. This error was probably triggered when you did a \`navigate(${delta})\` somewhere in your app.`
  10449. );
  10450. },
  10451. back() {
  10452. throw new Error(
  10453. `You cannot use navigator.back() on the server because it is a stateless environment.`
  10454. );
  10455. },
  10456. forward() {
  10457. throw new Error(
  10458. `You cannot use navigator.forward() on the server because it is a stateless environment.`
  10459. );
  10460. }
  10461. };
  10462. }
  10463. function createStaticHandler2(routes, opts) {
  10464. return createStaticHandler(routes, {
  10465. ...opts,
  10466. mapRouteProperties
  10467. });
  10468. }
  10469. function createStaticRouter(routes, context, opts = {}) {
  10470. let manifest = {};
  10471. let dataRoutes = convertRoutesToDataRoutes(
  10472. routes,
  10473. mapRouteProperties,
  10474. void 0,
  10475. manifest
  10476. );
  10477. let matches = context.matches.map((match) => {
  10478. let route = manifest[match.route.id] || match.route;
  10479. return {
  10480. ...match,
  10481. route
  10482. };
  10483. });
  10484. let msg = (method) => `You cannot use router.${method}() on the server because it is a stateless environment`;
  10485. return {
  10486. get basename() {
  10487. return context.basename;
  10488. },
  10489. get future() {
  10490. return {
  10491. v8_middleware: false,
  10492. ...opts?.future
  10493. };
  10494. },
  10495. get state() {
  10496. return {
  10497. historyAction: "POP" /* Pop */,
  10498. location: context.location,
  10499. matches,
  10500. loaderData: context.loaderData,
  10501. actionData: context.actionData,
  10502. errors: context.errors,
  10503. initialized: true,
  10504. navigation: IDLE_NAVIGATION,
  10505. restoreScrollPosition: null,
  10506. preventScrollReset: false,
  10507. revalidation: "idle",
  10508. fetchers: /* @__PURE__ */ new Map(),
  10509. blockers: /* @__PURE__ */ new Map()
  10510. };
  10511. },
  10512. get routes() {
  10513. return dataRoutes;
  10514. },
  10515. get window() {
  10516. return void 0;
  10517. },
  10518. initialize() {
  10519. throw msg("initialize");
  10520. },
  10521. subscribe() {
  10522. throw msg("subscribe");
  10523. },
  10524. enableScrollRestoration() {
  10525. throw msg("enableScrollRestoration");
  10526. },
  10527. navigate() {
  10528. throw msg("navigate");
  10529. },
  10530. fetch() {
  10531. throw msg("fetch");
  10532. },
  10533. revalidate() {
  10534. throw msg("revalidate");
  10535. },
  10536. createHref,
  10537. encodeLocation,
  10538. getFetcher() {
  10539. return IDLE_FETCHER;
  10540. },
  10541. deleteFetcher() {
  10542. throw msg("deleteFetcher");
  10543. },
  10544. resetFetcher() {
  10545. throw msg("resetFetcher");
  10546. },
  10547. dispose() {
  10548. throw msg("dispose");
  10549. },
  10550. getBlocker() {
  10551. return IDLE_BLOCKER;
  10552. },
  10553. deleteBlocker() {
  10554. throw msg("deleteBlocker");
  10555. },
  10556. patchRoutes() {
  10557. throw msg("patchRoutes");
  10558. },
  10559. _internalFetchControllers: /* @__PURE__ */ new Map(),
  10560. _internalSetRoutes() {
  10561. throw msg("_internalSetRoutes");
  10562. },
  10563. _internalSetStateDoNotUseOrYouWillBreakYourApp() {
  10564. throw msg("_internalSetStateDoNotUseOrYouWillBreakYourApp");
  10565. }
  10566. };
  10567. }
  10568. function createHref(to) {
  10569. return typeof to === "string" ? to : createPath(to);
  10570. }
  10571. function encodeLocation(to) {
  10572. let href = typeof to === "string" ? to : createPath(to);
  10573. href = href.replace(/ $/, "%20");
  10574. let encoded = ABSOLUTE_URL_REGEX3.test(href) ? new URL(href) : new URL(href, "http://localhost");
  10575. return {
  10576. pathname: encoded.pathname,
  10577. search: encoded.search,
  10578. hash: encoded.hash
  10579. };
  10580. }
  10581. var ABSOLUTE_URL_REGEX3 = /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i;
  10582. var ESCAPE_LOOKUP2 = {
  10583. "&": "\\u0026",
  10584. ">": "\\u003e",
  10585. "<": "\\u003c",
  10586. "\u2028": "\\u2028",
  10587. "\u2029": "\\u2029"
  10588. };
  10589. var ESCAPE_REGEX2 = /[&><\u2028\u2029]/g;
  10590. function htmlEscape(str) {
  10591. return str.replace(ESCAPE_REGEX2, (match) => ESCAPE_LOOKUP2[match]);
  10592. }
  10593. export {
  10594. Action,
  10595. createBrowserHistory,
  10596. invariant,
  10597. createPath,
  10598. parsePath,
  10599. createContext,
  10600. RouterContextProvider,
  10601. convertRoutesToDataRoutes,
  10602. matchRoutes,
  10603. generatePath,
  10604. matchPath,
  10605. stripBasename,
  10606. resolvePath,
  10607. data,
  10608. redirect,
  10609. redirectDocument,
  10610. replace,
  10611. ErrorResponseImpl,
  10612. isRouteErrorResponse,
  10613. instrumentHandler,
  10614. IDLE_NAVIGATION,
  10615. IDLE_FETCHER,
  10616. IDLE_BLOCKER,
  10617. createRouter,
  10618. createStaticHandler,
  10619. getStaticContextFromError,
  10620. isDataWithResponseInit,
  10621. isResponse,
  10622. isRedirectStatusCode,
  10623. isRedirectResponse,
  10624. isMutationMethod,
  10625. DataRouterContext,
  10626. DataRouterStateContext,
  10627. RSCRouterContext,
  10628. ViewTransitionContext,
  10629. FetchersContext,
  10630. AwaitContextProvider,
  10631. NavigationContext,
  10632. LocationContext,
  10633. RouteContext,
  10634. ENABLE_DEV_WARNINGS,
  10635. useHref,
  10636. useInRouterContext,
  10637. useLocation,
  10638. useNavigationType,
  10639. useMatch,
  10640. useNavigate,
  10641. useOutletContext,
  10642. useOutlet,
  10643. useParams,
  10644. useResolvedPath,
  10645. useRoutes,
  10646. useNavigation,
  10647. useRevalidator,
  10648. useMatches,
  10649. useLoaderData,
  10650. useRouteLoaderData,
  10651. useActionData,
  10652. useRouteError,
  10653. useAsyncValue,
  10654. useAsyncError,
  10655. useBlocker,
  10656. useRoute,
  10657. warnOnce,
  10658. mapRouteProperties,
  10659. hydrationRouteProperties,
  10660. createMemoryRouter,
  10661. RouterProvider,
  10662. MemoryRouter,
  10663. Navigate,
  10664. Outlet,
  10665. Route,
  10666. Router,
  10667. Routes,
  10668. Await,
  10669. createRoutesFromChildren,
  10670. createRoutesFromElements,
  10671. renderMatches,
  10672. WithComponentProps,
  10673. withComponentProps,
  10674. WithHydrateFallbackProps,
  10675. withHydrateFallbackProps,
  10676. WithErrorBoundaryProps,
  10677. withErrorBoundaryProps,
  10678. createSearchParams,
  10679. escapeHtml,
  10680. encode,
  10681. createRequestInit,
  10682. SingleFetchRedirectSymbol,
  10683. SINGLE_FETCH_REDIRECT_STATUS,
  10684. NO_BODY_STATUS_CODES,
  10685. StreamTransfer,
  10686. getTurboStreamSingleFetchDataStrategy,
  10687. getSingleFetchDataStrategyImpl,
  10688. stripIndexParam,
  10689. singleFetchUrl,
  10690. decodeViaTurboStream,
  10691. RemixErrorBoundary,
  10692. createServerRoutes,
  10693. createClientRoutesWithHMRRevalidationOptOut,
  10694. noActionDefinedError,
  10695. createClientRoutes,
  10696. shouldHydrateRouteLoader,
  10697. getPatchRoutesOnNavigationFunction,
  10698. useFogOFWarDiscovery,
  10699. getManifestPath,
  10700. FrameworkContext,
  10701. CRITICAL_CSS_DATA_ATTRIBUTE,
  10702. Links,
  10703. PrefetchPageLinks,
  10704. Meta,
  10705. setIsHydrated,
  10706. Scripts,
  10707. createBrowserRouter,
  10708. createHashRouter,
  10709. BrowserRouter,
  10710. HashRouter,
  10711. HistoryRouter,
  10712. Link,
  10713. NavLink,
  10714. Form,
  10715. ScrollRestoration,
  10716. useLinkClickHandler,
  10717. useSearchParams,
  10718. useSubmit,
  10719. useFormAction,
  10720. useFetcher,
  10721. useFetchers,
  10722. useScrollRestoration,
  10723. useBeforeUnload,
  10724. usePrompt,
  10725. useViewTransitionState,
  10726. StaticRouter,
  10727. StaticRouterProvider,
  10728. createStaticHandler2,
  10729. createStaticRouter
  10730. };