router.umd.js 140 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067
  1. /**
  2. * @remix-run/router v1.3.2
  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. (function (global, factory) {
  12. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  13. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  14. (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.RemixRouter = {}));
  15. })(this, (function (exports) { 'use strict';
  16. function _extends() {
  17. _extends = Object.assign ? Object.assign.bind() : function (target) {
  18. for (var i = 1; i < arguments.length; i++) {
  19. var source = arguments[i];
  20. for (var key in source) {
  21. if (Object.prototype.hasOwnProperty.call(source, key)) {
  22. target[key] = source[key];
  23. }
  24. }
  25. }
  26. return target;
  27. };
  28. return _extends.apply(this, arguments);
  29. }
  30. ////////////////////////////////////////////////////////////////////////////////
  31. //#region Types and Constants
  32. ////////////////////////////////////////////////////////////////////////////////
  33. /**
  34. * Actions represent the type of change to a location value.
  35. */
  36. exports.Action = void 0;
  37. /**
  38. * The pathname, search, and hash values of a URL.
  39. */
  40. (function (Action) {
  41. Action["Pop"] = "POP";
  42. Action["Push"] = "PUSH";
  43. Action["Replace"] = "REPLACE";
  44. })(exports.Action || (exports.Action = {}));
  45. const PopStateEventType = "popstate"; //#endregion
  46. ////////////////////////////////////////////////////////////////////////////////
  47. //#region Memory History
  48. ////////////////////////////////////////////////////////////////////////////////
  49. /**
  50. * A user-supplied object that describes a location. Used when providing
  51. * entries to `createMemoryHistory` via its `initialEntries` option.
  52. */
  53. /**
  54. * Memory history stores the current location in memory. It is designed for use
  55. * in stateful non-browser environments like tests and React Native.
  56. */
  57. function createMemoryHistory(options) {
  58. if (options === void 0) {
  59. options = {};
  60. }
  61. let {
  62. initialEntries = ["/"],
  63. initialIndex,
  64. v5Compat = false
  65. } = options;
  66. let entries; // Declare so we can access from createMemoryLocation
  67. entries = initialEntries.map((entry, index) => createMemoryLocation(entry, typeof entry === "string" ? null : entry.state, index === 0 ? "default" : undefined));
  68. let index = clampIndex(initialIndex == null ? entries.length - 1 : initialIndex);
  69. let action = exports.Action.Pop;
  70. let listener = null;
  71. function clampIndex(n) {
  72. return Math.min(Math.max(n, 0), entries.length - 1);
  73. }
  74. function getCurrentLocation() {
  75. return entries[index];
  76. }
  77. function createMemoryLocation(to, state, key) {
  78. if (state === void 0) {
  79. state = null;
  80. }
  81. let location = createLocation(entries ? getCurrentLocation().pathname : "/", to, state, key);
  82. warning$1(location.pathname.charAt(0) === "/", "relative pathnames are not supported in memory history: " + JSON.stringify(to));
  83. return location;
  84. }
  85. function createHref(to) {
  86. return typeof to === "string" ? to : createPath(to);
  87. }
  88. let history = {
  89. get index() {
  90. return index;
  91. },
  92. get action() {
  93. return action;
  94. },
  95. get location() {
  96. return getCurrentLocation();
  97. },
  98. createHref,
  99. createURL(to) {
  100. return new URL(createHref(to), "http://localhost");
  101. },
  102. encodeLocation(to) {
  103. let path = typeof to === "string" ? parsePath(to) : to;
  104. return {
  105. pathname: path.pathname || "",
  106. search: path.search || "",
  107. hash: path.hash || ""
  108. };
  109. },
  110. push(to, state) {
  111. action = exports.Action.Push;
  112. let nextLocation = createMemoryLocation(to, state);
  113. index += 1;
  114. entries.splice(index, entries.length, nextLocation);
  115. if (v5Compat && listener) {
  116. listener({
  117. action,
  118. location: nextLocation,
  119. delta: 1
  120. });
  121. }
  122. },
  123. replace(to, state) {
  124. action = exports.Action.Replace;
  125. let nextLocation = createMemoryLocation(to, state);
  126. entries[index] = nextLocation;
  127. if (v5Compat && listener) {
  128. listener({
  129. action,
  130. location: nextLocation,
  131. delta: 0
  132. });
  133. }
  134. },
  135. go(delta) {
  136. action = exports.Action.Pop;
  137. let nextIndex = clampIndex(index + delta);
  138. let nextLocation = entries[nextIndex];
  139. index = nextIndex;
  140. if (listener) {
  141. listener({
  142. action,
  143. location: nextLocation,
  144. delta
  145. });
  146. }
  147. },
  148. listen(fn) {
  149. listener = fn;
  150. return () => {
  151. listener = null;
  152. };
  153. }
  154. };
  155. return history;
  156. } //#endregion
  157. ////////////////////////////////////////////////////////////////////////////////
  158. //#region Browser History
  159. ////////////////////////////////////////////////////////////////////////////////
  160. /**
  161. * A browser history stores the current location in regular URLs in a web
  162. * browser environment. This is the standard for most web apps and provides the
  163. * cleanest URLs the browser's address bar.
  164. *
  165. * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#browserhistory
  166. */
  167. /**
  168. * Browser history stores the location in regular URLs. This is the standard for
  169. * most web apps, but it requires some configuration on the server to ensure you
  170. * serve the same app at multiple URLs.
  171. *
  172. * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createbrowserhistory
  173. */
  174. function createBrowserHistory(options) {
  175. if (options === void 0) {
  176. options = {};
  177. }
  178. function createBrowserLocation(window, globalHistory) {
  179. let {
  180. pathname,
  181. search,
  182. hash
  183. } = window.location;
  184. return createLocation("", {
  185. pathname,
  186. search,
  187. hash
  188. }, // state defaults to `null` because `window.history.state` does
  189. globalHistory.state && globalHistory.state.usr || null, globalHistory.state && globalHistory.state.key || "default");
  190. }
  191. function createBrowserHref(window, to) {
  192. return typeof to === "string" ? to : createPath(to);
  193. }
  194. return getUrlBasedHistory(createBrowserLocation, createBrowserHref, null, options);
  195. } //#endregion
  196. ////////////////////////////////////////////////////////////////////////////////
  197. //#region Hash History
  198. ////////////////////////////////////////////////////////////////////////////////
  199. /**
  200. * A hash history stores the current location in the fragment identifier portion
  201. * of the URL in a web browser environment.
  202. *
  203. * This is ideal for apps that do not control the server for some reason
  204. * (because the fragment identifier is never sent to the server), including some
  205. * shared hosting environments that do not provide fine-grained controls over
  206. * which pages are served at which URLs.
  207. *
  208. * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#hashhistory
  209. */
  210. /**
  211. * Hash history stores the location in window.location.hash. This makes it ideal
  212. * for situations where you don't want to send the location to the server for
  213. * some reason, either because you do cannot configure it or the URL space is
  214. * reserved for something else.
  215. *
  216. * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createhashhistory
  217. */
  218. function createHashHistory(options) {
  219. if (options === void 0) {
  220. options = {};
  221. }
  222. function createHashLocation(window, globalHistory) {
  223. let {
  224. pathname = "/",
  225. search = "",
  226. hash = ""
  227. } = parsePath(window.location.hash.substr(1));
  228. return createLocation("", {
  229. pathname,
  230. search,
  231. hash
  232. }, // state defaults to `null` because `window.history.state` does
  233. globalHistory.state && globalHistory.state.usr || null, globalHistory.state && globalHistory.state.key || "default");
  234. }
  235. function createHashHref(window, to) {
  236. let base = window.document.querySelector("base");
  237. let href = "";
  238. if (base && base.getAttribute("href")) {
  239. let url = window.location.href;
  240. let hashIndex = url.indexOf("#");
  241. href = hashIndex === -1 ? url : url.slice(0, hashIndex);
  242. }
  243. return href + "#" + (typeof to === "string" ? to : createPath(to));
  244. }
  245. function validateHashLocation(location, to) {
  246. warning$1(location.pathname.charAt(0) === "/", "relative pathnames are not supported in hash history.push(" + JSON.stringify(to) + ")");
  247. }
  248. return getUrlBasedHistory(createHashLocation, createHashHref, validateHashLocation, options);
  249. } //#endregion
  250. ////////////////////////////////////////////////////////////////////////////////
  251. //#region UTILS
  252. ////////////////////////////////////////////////////////////////////////////////
  253. /**
  254. * @private
  255. */
  256. function invariant(value, message) {
  257. if (value === false || value === null || typeof value === "undefined") {
  258. throw new Error(message);
  259. }
  260. }
  261. function warning$1(cond, message) {
  262. if (!cond) {
  263. // eslint-disable-next-line no-console
  264. if (typeof console !== "undefined") console.warn(message);
  265. try {
  266. // Welcome to debugging history!
  267. //
  268. // This error is thrown as a convenience so you can more easily
  269. // find the source for a warning that appears in the console by
  270. // enabling "pause on exceptions" in your JavaScript debugger.
  271. throw new Error(message); // eslint-disable-next-line no-empty
  272. } catch (e) {}
  273. }
  274. }
  275. function createKey() {
  276. return Math.random().toString(36).substr(2, 8);
  277. }
  278. /**
  279. * For browser-based histories, we combine the state and key into an object
  280. */
  281. function getHistoryState(location, index) {
  282. return {
  283. usr: location.state,
  284. key: location.key,
  285. idx: index
  286. };
  287. }
  288. /**
  289. * Creates a Location object with a unique key from the given Path
  290. */
  291. function createLocation(current, to, state, key) {
  292. if (state === void 0) {
  293. state = null;
  294. }
  295. let location = _extends({
  296. pathname: typeof current === "string" ? current : current.pathname,
  297. search: "",
  298. hash: ""
  299. }, typeof to === "string" ? parsePath(to) : to, {
  300. state,
  301. // TODO: This could be cleaned up. push/replace should probably just take
  302. // full Locations now and avoid the need to run through this flow at all
  303. // But that's a pretty big refactor to the current test suite so going to
  304. // keep as is for the time being and just let any incoming keys take precedence
  305. key: to && to.key || key || createKey()
  306. });
  307. return location;
  308. }
  309. /**
  310. * Creates a string URL path from the given pathname, search, and hash components.
  311. */
  312. function createPath(_ref) {
  313. let {
  314. pathname = "/",
  315. search = "",
  316. hash = ""
  317. } = _ref;
  318. if (search && search !== "?") pathname += search.charAt(0) === "?" ? search : "?" + search;
  319. if (hash && hash !== "#") pathname += hash.charAt(0) === "#" ? hash : "#" + hash;
  320. return pathname;
  321. }
  322. /**
  323. * Parses a string URL path into its separate pathname, search, and hash components.
  324. */
  325. function parsePath(path) {
  326. let parsedPath = {};
  327. if (path) {
  328. let hashIndex = path.indexOf("#");
  329. if (hashIndex >= 0) {
  330. parsedPath.hash = path.substr(hashIndex);
  331. path = path.substr(0, hashIndex);
  332. }
  333. let searchIndex = path.indexOf("?");
  334. if (searchIndex >= 0) {
  335. parsedPath.search = path.substr(searchIndex);
  336. path = path.substr(0, searchIndex);
  337. }
  338. if (path) {
  339. parsedPath.pathname = path;
  340. }
  341. }
  342. return parsedPath;
  343. }
  344. function getUrlBasedHistory(getLocation, createHref, validateLocation, options) {
  345. if (options === void 0) {
  346. options = {};
  347. }
  348. let {
  349. window = document.defaultView,
  350. v5Compat = false
  351. } = options;
  352. let globalHistory = window.history;
  353. let action = exports.Action.Pop;
  354. let listener = null;
  355. let index = getIndex(); // Index should only be null when we initialize. If not, it's because the
  356. // user called history.pushState or history.replaceState directly, in which
  357. // case we should log a warning as it will result in bugs.
  358. if (index == null) {
  359. index = 0;
  360. globalHistory.replaceState(_extends({}, globalHistory.state, {
  361. idx: index
  362. }), "");
  363. }
  364. function getIndex() {
  365. let state = globalHistory.state || {
  366. idx: null
  367. };
  368. return state.idx;
  369. }
  370. function handlePop() {
  371. action = exports.Action.Pop;
  372. let nextIndex = getIndex();
  373. let delta = nextIndex == null ? null : nextIndex - index;
  374. index = nextIndex;
  375. if (listener) {
  376. listener({
  377. action,
  378. location: history.location,
  379. delta
  380. });
  381. }
  382. }
  383. function push(to, state) {
  384. action = exports.Action.Push;
  385. let location = createLocation(history.location, to, state);
  386. if (validateLocation) validateLocation(location, to);
  387. index = getIndex() + 1;
  388. let historyState = getHistoryState(location, index);
  389. let url = history.createHref(location); // try...catch because iOS limits us to 100 pushState calls :/
  390. try {
  391. globalHistory.pushState(historyState, "", url);
  392. } catch (error) {
  393. // They are going to lose state here, but there is no real
  394. // way to warn them about it since the page will refresh...
  395. window.location.assign(url);
  396. }
  397. if (v5Compat && listener) {
  398. listener({
  399. action,
  400. location: history.location,
  401. delta: 1
  402. });
  403. }
  404. }
  405. function replace(to, state) {
  406. action = exports.Action.Replace;
  407. let location = createLocation(history.location, to, state);
  408. if (validateLocation) validateLocation(location, to);
  409. index = getIndex();
  410. let historyState = getHistoryState(location, index);
  411. let url = history.createHref(location);
  412. globalHistory.replaceState(historyState, "", url);
  413. if (v5Compat && listener) {
  414. listener({
  415. action,
  416. location: history.location,
  417. delta: 0
  418. });
  419. }
  420. }
  421. function createURL(to) {
  422. // window.location.origin is "null" (the literal string value) in Firefox
  423. // under certain conditions, notably when serving from a local HTML file
  424. // See https://bugzilla.mozilla.org/show_bug.cgi?id=878297
  425. let base = window.location.origin !== "null" ? window.location.origin : window.location.href;
  426. let href = typeof to === "string" ? to : createPath(to);
  427. invariant(base, "No window.location.(origin|href) available to create URL for href: " + href);
  428. return new URL(href, base);
  429. }
  430. let history = {
  431. get action() {
  432. return action;
  433. },
  434. get location() {
  435. return getLocation(window, globalHistory);
  436. },
  437. listen(fn) {
  438. if (listener) {
  439. throw new Error("A history only accepts one active listener");
  440. }
  441. window.addEventListener(PopStateEventType, handlePop);
  442. listener = fn;
  443. return () => {
  444. window.removeEventListener(PopStateEventType, handlePop);
  445. listener = null;
  446. };
  447. },
  448. createHref(to) {
  449. return createHref(window, to);
  450. },
  451. createURL,
  452. encodeLocation(to) {
  453. // Encode a Location the same way window.location would
  454. let url = createURL(to);
  455. return {
  456. pathname: url.pathname,
  457. search: url.search,
  458. hash: url.hash
  459. };
  460. },
  461. push,
  462. replace,
  463. go(n) {
  464. return globalHistory.go(n);
  465. }
  466. };
  467. return history;
  468. } //#endregion
  469. /**
  470. * Map of routeId -> data returned from a loader/action/error
  471. */
  472. let ResultType;
  473. /**
  474. * Successful result from a loader or action
  475. */
  476. (function (ResultType) {
  477. ResultType["data"] = "data";
  478. ResultType["deferred"] = "deferred";
  479. ResultType["redirect"] = "redirect";
  480. ResultType["error"] = "error";
  481. })(ResultType || (ResultType = {}));
  482. function isIndexRoute(route) {
  483. return route.index === true;
  484. } // Walk the route tree generating unique IDs where necessary so we are working
  485. // solely with AgnosticDataRouteObject's within the Router
  486. function convertRoutesToDataRoutes(routes, parentPath, allIds) {
  487. if (parentPath === void 0) {
  488. parentPath = [];
  489. }
  490. if (allIds === void 0) {
  491. allIds = new Set();
  492. }
  493. return routes.map((route, index) => {
  494. let treePath = [...parentPath, index];
  495. let id = typeof route.id === "string" ? route.id : treePath.join("-");
  496. invariant(route.index !== true || !route.children, "Cannot specify children on an index route");
  497. invariant(!allIds.has(id), "Found a route id collision on id \"" + id + "\". Route " + "id's must be globally unique within Data Router usages");
  498. allIds.add(id);
  499. if (isIndexRoute(route)) {
  500. let indexRoute = _extends({}, route, {
  501. id
  502. });
  503. return indexRoute;
  504. } else {
  505. let pathOrLayoutRoute = _extends({}, route, {
  506. id,
  507. children: route.children ? convertRoutesToDataRoutes(route.children, treePath, allIds) : undefined
  508. });
  509. return pathOrLayoutRoute;
  510. }
  511. });
  512. }
  513. /**
  514. * Matches the given routes to a location and returns the match data.
  515. *
  516. * @see https://reactrouter.com/utils/match-routes
  517. */
  518. function matchRoutes(routes, locationArg, basename) {
  519. if (basename === void 0) {
  520. basename = "/";
  521. }
  522. let location = typeof locationArg === "string" ? parsePath(locationArg) : locationArg;
  523. let pathname = stripBasename(location.pathname || "/", basename);
  524. if (pathname == null) {
  525. return null;
  526. }
  527. let branches = flattenRoutes(routes);
  528. rankRouteBranches(branches);
  529. let matches = null;
  530. for (let i = 0; matches == null && i < branches.length; ++i) {
  531. matches = matchRouteBranch(branches[i], // Incoming pathnames are generally encoded from either window.location
  532. // or from router.navigate, but we want to match against the unencoded
  533. // paths in the route definitions. Memory router locations won't be
  534. // encoded here but there also shouldn't be anything to decode so this
  535. // should be a safe operation. This avoids needing matchRoutes to be
  536. // history-aware.
  537. safelyDecodeURI(pathname));
  538. }
  539. return matches;
  540. }
  541. function flattenRoutes(routes, branches, parentsMeta, parentPath) {
  542. if (branches === void 0) {
  543. branches = [];
  544. }
  545. if (parentsMeta === void 0) {
  546. parentsMeta = [];
  547. }
  548. if (parentPath === void 0) {
  549. parentPath = "";
  550. }
  551. let flattenRoute = (route, index, relativePath) => {
  552. let meta = {
  553. relativePath: relativePath === undefined ? route.path || "" : relativePath,
  554. caseSensitive: route.caseSensitive === true,
  555. childrenIndex: index,
  556. route
  557. };
  558. if (meta.relativePath.startsWith("/")) {
  559. invariant(meta.relativePath.startsWith(parentPath), "Absolute route path \"" + meta.relativePath + "\" nested under path " + ("\"" + parentPath + "\" is not valid. An absolute child route path ") + "must start with the combined path of all its parent routes.");
  560. meta.relativePath = meta.relativePath.slice(parentPath.length);
  561. }
  562. let path = joinPaths([parentPath, meta.relativePath]);
  563. let routesMeta = parentsMeta.concat(meta); // Add the children before adding this route to the array so we traverse the
  564. // route tree depth-first and child routes appear before their parents in
  565. // the "flattened" version.
  566. if (route.children && route.children.length > 0) {
  567. invariant( // Our types know better, but runtime JS may not!
  568. // @ts-expect-error
  569. route.index !== true, "Index routes must not have child routes. Please remove " + ("all child routes from route path \"" + path + "\"."));
  570. flattenRoutes(route.children, branches, routesMeta, path);
  571. } // Routes without a path shouldn't ever match by themselves unless they are
  572. // index routes, so don't add them to the list of possible branches.
  573. if (route.path == null && !route.index) {
  574. return;
  575. }
  576. branches.push({
  577. path,
  578. score: computeScore(path, route.index),
  579. routesMeta
  580. });
  581. };
  582. routes.forEach((route, index) => {
  583. var _route$path;
  584. // coarse-grain check for optional params
  585. if (route.path === "" || !((_route$path = route.path) != null && _route$path.includes("?"))) {
  586. flattenRoute(route, index);
  587. } else {
  588. for (let exploded of explodeOptionalSegments(route.path)) {
  589. flattenRoute(route, index, exploded);
  590. }
  591. }
  592. });
  593. return branches;
  594. }
  595. /**
  596. * Computes all combinations of optional path segments for a given path,
  597. * excluding combinations that are ambiguous and of lower priority.
  598. *
  599. * For example, `/one/:two?/three/:four?/:five?` explodes to:
  600. * - `/one/three`
  601. * - `/one/:two/three`
  602. * - `/one/three/:four`
  603. * - `/one/three/:five`
  604. * - `/one/:two/three/:four`
  605. * - `/one/:two/three/:five`
  606. * - `/one/three/:four/:five`
  607. * - `/one/:two/three/:four/:five`
  608. */
  609. function explodeOptionalSegments(path) {
  610. let segments = path.split("/");
  611. if (segments.length === 0) return [];
  612. let [first, ...rest] = segments; // Optional path segments are denoted by a trailing `?`
  613. let isOptional = first.endsWith("?"); // Compute the corresponding required segment: `foo?` -> `foo`
  614. let required = first.replace(/\?$/, "");
  615. if (rest.length === 0) {
  616. // Intepret empty string as omitting an optional segment
  617. // `["one", "", "three"]` corresponds to omitting `:two` from `/one/:two?/three` -> `/one/three`
  618. return isOptional ? [required, ""] : [required];
  619. }
  620. let restExploded = explodeOptionalSegments(rest.join("/"));
  621. let result = []; // All child paths with the prefix. Do this for all children before the
  622. // optional version for all children so we get consistent ordering where the
  623. // parent optional aspect is preferred as required. Otherwise, we can get
  624. // child sections interspersed where deeper optional segments are higher than
  625. // parent optional segments, where for example, /:two would explodes _earlier_
  626. // then /:one. By always including the parent as required _for all children_
  627. // first, we avoid this issue
  628. result.push(...restExploded.map(subpath => subpath === "" ? required : [required, subpath].join("/"))); // Then if this is an optional value, add all child versions without
  629. if (isOptional) {
  630. result.push(...restExploded);
  631. } // for absolute paths, ensure `/` instead of empty segment
  632. return result.map(exploded => path.startsWith("/") && exploded === "" ? "/" : exploded);
  633. }
  634. function rankRouteBranches(branches) {
  635. branches.sort((a, b) => a.score !== b.score ? b.score - a.score // Higher score first
  636. : compareIndexes(a.routesMeta.map(meta => meta.childrenIndex), b.routesMeta.map(meta => meta.childrenIndex)));
  637. }
  638. const paramRe = /^:\w+$/;
  639. const dynamicSegmentValue = 3;
  640. const indexRouteValue = 2;
  641. const emptySegmentValue = 1;
  642. const staticSegmentValue = 10;
  643. const splatPenalty = -2;
  644. const isSplat = s => s === "*";
  645. function computeScore(path, index) {
  646. let segments = path.split("/");
  647. let initialScore = segments.length;
  648. if (segments.some(isSplat)) {
  649. initialScore += splatPenalty;
  650. }
  651. if (index) {
  652. initialScore += indexRouteValue;
  653. }
  654. return segments.filter(s => !isSplat(s)).reduce((score, segment) => score + (paramRe.test(segment) ? dynamicSegmentValue : segment === "" ? emptySegmentValue : staticSegmentValue), initialScore);
  655. }
  656. function compareIndexes(a, b) {
  657. let siblings = a.length === b.length && a.slice(0, -1).every((n, i) => n === b[i]);
  658. return siblings ? // If two routes are siblings, we should try to match the earlier sibling
  659. // first. This allows people to have fine-grained control over the matching
  660. // behavior by simply putting routes with identical paths in the order they
  661. // want them tried.
  662. a[a.length - 1] - b[b.length - 1] : // Otherwise, it doesn't really make sense to rank non-siblings by index,
  663. // so they sort equally.
  664. 0;
  665. }
  666. function matchRouteBranch(branch, pathname) {
  667. let {
  668. routesMeta
  669. } = branch;
  670. let matchedParams = {};
  671. let matchedPathname = "/";
  672. let matches = [];
  673. for (let i = 0; i < routesMeta.length; ++i) {
  674. let meta = routesMeta[i];
  675. let end = i === routesMeta.length - 1;
  676. let remainingPathname = matchedPathname === "/" ? pathname : pathname.slice(matchedPathname.length) || "/";
  677. let match = matchPath({
  678. path: meta.relativePath,
  679. caseSensitive: meta.caseSensitive,
  680. end
  681. }, remainingPathname);
  682. if (!match) return null;
  683. Object.assign(matchedParams, match.params);
  684. let route = meta.route;
  685. matches.push({
  686. // TODO: Can this as be avoided?
  687. params: matchedParams,
  688. pathname: joinPaths([matchedPathname, match.pathname]),
  689. pathnameBase: normalizePathname(joinPaths([matchedPathname, match.pathnameBase])),
  690. route
  691. });
  692. if (match.pathnameBase !== "/") {
  693. matchedPathname = joinPaths([matchedPathname, match.pathnameBase]);
  694. }
  695. }
  696. return matches;
  697. }
  698. /**
  699. * Returns a path with params interpolated.
  700. *
  701. * @see https://reactrouter.com/utils/generate-path
  702. */
  703. function generatePath(originalPath, params) {
  704. if (params === void 0) {
  705. params = {};
  706. }
  707. let path = originalPath;
  708. if (path.endsWith("*") && path !== "*" && !path.endsWith("/*")) {
  709. warning(false, "Route path \"" + path + "\" will be treated as if it were " + ("\"" + path.replace(/\*$/, "/*") + "\" because the `*` character must ") + "always follow a `/` in the pattern. To get rid of this warning, " + ("please change the route path to \"" + path.replace(/\*$/, "/*") + "\"."));
  710. path = path.replace(/\*$/, "/*");
  711. }
  712. return path.replace(/^:(\w+)(\??)/g, (_, key, optional) => {
  713. let param = params[key];
  714. if (optional === "?") {
  715. return param == null ? "" : param;
  716. }
  717. if (param == null) {
  718. invariant(false, "Missing \":" + key + "\" param");
  719. }
  720. return param;
  721. }).replace(/\/:(\w+)(\??)/g, (_, key, optional) => {
  722. let param = params[key];
  723. if (optional === "?") {
  724. return param == null ? "" : "/" + param;
  725. }
  726. if (param == null) {
  727. invariant(false, "Missing \":" + key + "\" param");
  728. }
  729. return "/" + param;
  730. }) // Remove any optional markers from optional static segments
  731. .replace(/\?/g, "").replace(/(\/?)\*/, (_, prefix, __, str) => {
  732. const star = "*";
  733. if (params[star] == null) {
  734. // If no splat was provided, trim the trailing slash _unless_ it's
  735. // the entire path
  736. return str === "/*" ? "/" : "";
  737. } // Apply the splat
  738. return "" + prefix + params[star];
  739. });
  740. }
  741. /**
  742. * A PathPattern is used to match on some portion of a URL pathname.
  743. */
  744. /**
  745. * Performs pattern matching on a URL pathname and returns information about
  746. * the match.
  747. *
  748. * @see https://reactrouter.com/utils/match-path
  749. */
  750. function matchPath(pattern, pathname) {
  751. if (typeof pattern === "string") {
  752. pattern = {
  753. path: pattern,
  754. caseSensitive: false,
  755. end: true
  756. };
  757. }
  758. let [matcher, paramNames] = compilePath(pattern.path, pattern.caseSensitive, pattern.end);
  759. let match = pathname.match(matcher);
  760. if (!match) return null;
  761. let matchedPathname = match[0];
  762. let pathnameBase = matchedPathname.replace(/(.)\/+$/, "$1");
  763. let captureGroups = match.slice(1);
  764. let params = paramNames.reduce((memo, paramName, index) => {
  765. // We need to compute the pathnameBase here using the raw splat value
  766. // instead of using params["*"] later because it will be decoded then
  767. if (paramName === "*") {
  768. let splatValue = captureGroups[index] || "";
  769. pathnameBase = matchedPathname.slice(0, matchedPathname.length - splatValue.length).replace(/(.)\/+$/, "$1");
  770. }
  771. memo[paramName] = safelyDecodeURIComponent(captureGroups[index] || "", paramName);
  772. return memo;
  773. }, {});
  774. return {
  775. params,
  776. pathname: matchedPathname,
  777. pathnameBase,
  778. pattern
  779. };
  780. }
  781. function compilePath(path, caseSensitive, end) {
  782. if (caseSensitive === void 0) {
  783. caseSensitive = false;
  784. }
  785. if (end === void 0) {
  786. end = true;
  787. }
  788. warning(path === "*" || !path.endsWith("*") || path.endsWith("/*"), "Route path \"" + path + "\" will be treated as if it were " + ("\"" + path.replace(/\*$/, "/*") + "\" because the `*` character must ") + "always follow a `/` in the pattern. To get rid of this warning, " + ("please change the route path to \"" + path.replace(/\*$/, "/*") + "\"."));
  789. let paramNames = [];
  790. let regexpSource = "^" + path.replace(/\/*\*?$/, "") // Ignore trailing / and /*, we'll handle it below
  791. .replace(/^\/*/, "/") // Make sure it has a leading /
  792. .replace(/[\\.*+^$?{}|()[\]]/g, "\\$&") // Escape special regex chars
  793. .replace(/\/:(\w+)/g, (_, paramName) => {
  794. paramNames.push(paramName);
  795. return "/([^\\/]+)";
  796. });
  797. if (path.endsWith("*")) {
  798. paramNames.push("*");
  799. regexpSource += path === "*" || path === "/*" ? "(.*)$" // Already matched the initial /, just match the rest
  800. : "(?:\\/(.+)|\\/*)$"; // Don't include the / in params["*"]
  801. } else if (end) {
  802. // When matching to the end, ignore trailing slashes
  803. regexpSource += "\\/*$";
  804. } else if (path !== "" && path !== "/") {
  805. // If our path is non-empty and contains anything beyond an initial slash,
  806. // then we have _some_ form of path in our regex so we should expect to
  807. // match only if we find the end of this path segment. Look for an optional
  808. // non-captured trailing slash (to match a portion of the URL) or the end
  809. // of the path (if we've matched to the end). We used to do this with a
  810. // word boundary but that gives false positives on routes like
  811. // /user-preferences since `-` counts as a word boundary.
  812. regexpSource += "(?:(?=\\/|$))";
  813. } else ;
  814. let matcher = new RegExp(regexpSource, caseSensitive ? undefined : "i");
  815. return [matcher, paramNames];
  816. }
  817. function safelyDecodeURI(value) {
  818. try {
  819. return decodeURI(value);
  820. } catch (error) {
  821. warning(false, "The URL path \"" + value + "\" could not be decoded because it is is a " + "malformed URL segment. This is probably due to a bad percent " + ("encoding (" + error + ")."));
  822. return value;
  823. }
  824. }
  825. function safelyDecodeURIComponent(value, paramName) {
  826. try {
  827. return decodeURIComponent(value);
  828. } catch (error) {
  829. warning(false, "The value for the URL param \"" + paramName + "\" will not be decoded because" + (" the string \"" + value + "\" is a malformed URL segment. This is probably") + (" due to a bad percent encoding (" + error + ")."));
  830. return value;
  831. }
  832. }
  833. /**
  834. * @private
  835. */
  836. function stripBasename(pathname, basename) {
  837. if (basename === "/") return pathname;
  838. if (!pathname.toLowerCase().startsWith(basename.toLowerCase())) {
  839. return null;
  840. } // We want to leave trailing slash behavior in the user's control, so if they
  841. // specify a basename with a trailing slash, we should support it
  842. let startIndex = basename.endsWith("/") ? basename.length - 1 : basename.length;
  843. let nextChar = pathname.charAt(startIndex);
  844. if (nextChar && nextChar !== "/") {
  845. // pathname does not start with basename/
  846. return null;
  847. }
  848. return pathname.slice(startIndex) || "/";
  849. }
  850. /**
  851. * @private
  852. */
  853. function warning(cond, message) {
  854. if (!cond) {
  855. // eslint-disable-next-line no-console
  856. if (typeof console !== "undefined") console.warn(message);
  857. try {
  858. // Welcome to debugging @remix-run/router!
  859. //
  860. // This error is thrown as a convenience so you can more easily
  861. // find the source for a warning that appears in the console by
  862. // enabling "pause on exceptions" in your JavaScript debugger.
  863. throw new Error(message); // eslint-disable-next-line no-empty
  864. } catch (e) {}
  865. }
  866. }
  867. /**
  868. * Returns a resolved path object relative to the given pathname.
  869. *
  870. * @see https://reactrouter.com/utils/resolve-path
  871. */
  872. function resolvePath(to, fromPathname) {
  873. if (fromPathname === void 0) {
  874. fromPathname = "/";
  875. }
  876. let {
  877. pathname: toPathname,
  878. search = "",
  879. hash = ""
  880. } = typeof to === "string" ? parsePath(to) : to;
  881. let pathname = toPathname ? toPathname.startsWith("/") ? toPathname : resolvePathname(toPathname, fromPathname) : fromPathname;
  882. return {
  883. pathname,
  884. search: normalizeSearch(search),
  885. hash: normalizeHash(hash)
  886. };
  887. }
  888. function resolvePathname(relativePath, fromPathname) {
  889. let segments = fromPathname.replace(/\/+$/, "").split("/");
  890. let relativeSegments = relativePath.split("/");
  891. relativeSegments.forEach(segment => {
  892. if (segment === "..") {
  893. // Keep the root "" segment so the pathname starts at /
  894. if (segments.length > 1) segments.pop();
  895. } else if (segment !== ".") {
  896. segments.push(segment);
  897. }
  898. });
  899. return segments.length > 1 ? segments.join("/") : "/";
  900. }
  901. function getInvalidPathError(char, field, dest, path) {
  902. return "Cannot include a '" + char + "' character in a manually specified " + ("`to." + field + "` field [" + JSON.stringify(path) + "]. Please separate it out to the ") + ("`to." + dest + "` field. Alternatively you may provide the full path as ") + "a string in <Link to=\"...\"> and the router will parse it for you.";
  903. }
  904. /**
  905. * @private
  906. *
  907. * When processing relative navigation we want to ignore ancestor routes that
  908. * do not contribute to the path, such that index/pathless layout routes don't
  909. * interfere.
  910. *
  911. * For example, when moving a route element into an index route and/or a
  912. * pathless layout route, relative link behavior contained within should stay
  913. * the same. Both of the following examples should link back to the root:
  914. *
  915. * <Route path="/">
  916. * <Route path="accounts" element={<Link to=".."}>
  917. * </Route>
  918. *
  919. * <Route path="/">
  920. * <Route path="accounts">
  921. * <Route element={<AccountsLayout />}> // <-- Does not contribute
  922. * <Route index element={<Link to=".."} /> // <-- Does not contribute
  923. * </Route
  924. * </Route>
  925. * </Route>
  926. */
  927. function getPathContributingMatches(matches) {
  928. return matches.filter((match, index) => index === 0 || match.route.path && match.route.path.length > 0);
  929. }
  930. /**
  931. * @private
  932. */
  933. function resolveTo(toArg, routePathnames, locationPathname, isPathRelative) {
  934. if (isPathRelative === void 0) {
  935. isPathRelative = false;
  936. }
  937. let to;
  938. if (typeof toArg === "string") {
  939. to = parsePath(toArg);
  940. } else {
  941. to = _extends({}, toArg);
  942. invariant(!to.pathname || !to.pathname.includes("?"), getInvalidPathError("?", "pathname", "search", to));
  943. invariant(!to.pathname || !to.pathname.includes("#"), getInvalidPathError("#", "pathname", "hash", to));
  944. invariant(!to.search || !to.search.includes("#"), getInvalidPathError("#", "search", "hash", to));
  945. }
  946. let isEmptyPath = toArg === "" || to.pathname === "";
  947. let toPathname = isEmptyPath ? "/" : to.pathname;
  948. let from; // Routing is relative to the current pathname if explicitly requested.
  949. //
  950. // If a pathname is explicitly provided in `to`, it should be relative to the
  951. // route context. This is explained in `Note on `<Link to>` values` in our
  952. // migration guide from v5 as a means of disambiguation between `to` values
  953. // that begin with `/` and those that do not. However, this is problematic for
  954. // `to` values that do not provide a pathname. `to` can simply be a search or
  955. // hash string, in which case we should assume that the navigation is relative
  956. // to the current location's pathname and *not* the route pathname.
  957. if (isPathRelative || toPathname == null) {
  958. from = locationPathname;
  959. } else {
  960. let routePathnameIndex = routePathnames.length - 1;
  961. if (toPathname.startsWith("..")) {
  962. let toSegments = toPathname.split("/"); // Each leading .. segment means "go up one route" instead of "go up one
  963. // URL segment". This is a key difference from how <a href> works and a
  964. // major reason we call this a "to" value instead of a "href".
  965. while (toSegments[0] === "..") {
  966. toSegments.shift();
  967. routePathnameIndex -= 1;
  968. }
  969. to.pathname = toSegments.join("/");
  970. } // If there are more ".." segments than parent routes, resolve relative to
  971. // the root / URL.
  972. from = routePathnameIndex >= 0 ? routePathnames[routePathnameIndex] : "/";
  973. }
  974. let path = resolvePath(to, from); // Ensure the pathname has a trailing slash if the original "to" had one
  975. let hasExplicitTrailingSlash = toPathname && toPathname !== "/" && toPathname.endsWith("/"); // Or if this was a link to the current path which has a trailing slash
  976. let hasCurrentTrailingSlash = (isEmptyPath || toPathname === ".") && locationPathname.endsWith("/");
  977. if (!path.pathname.endsWith("/") && (hasExplicitTrailingSlash || hasCurrentTrailingSlash)) {
  978. path.pathname += "/";
  979. }
  980. return path;
  981. }
  982. /**
  983. * @private
  984. */
  985. function getToPathname(to) {
  986. // Empty strings should be treated the same as / paths
  987. return to === "" || to.pathname === "" ? "/" : typeof to === "string" ? parsePath(to).pathname : to.pathname;
  988. }
  989. /**
  990. * @private
  991. */
  992. const joinPaths = paths => paths.join("/").replace(/\/\/+/g, "/");
  993. /**
  994. * @private
  995. */
  996. const normalizePathname = pathname => pathname.replace(/\/+$/, "").replace(/^\/*/, "/");
  997. /**
  998. * @private
  999. */
  1000. const normalizeSearch = search => !search || search === "?" ? "" : search.startsWith("?") ? search : "?" + search;
  1001. /**
  1002. * @private
  1003. */
  1004. const normalizeHash = hash => !hash || hash === "#" ? "" : hash.startsWith("#") ? hash : "#" + hash;
  1005. /**
  1006. * This is a shortcut for creating `application/json` responses. Converts `data`
  1007. * to JSON and sets the `Content-Type` header.
  1008. */
  1009. const json = function json(data, init) {
  1010. if (init === void 0) {
  1011. init = {};
  1012. }
  1013. let responseInit = typeof init === "number" ? {
  1014. status: init
  1015. } : init;
  1016. let headers = new Headers(responseInit.headers);
  1017. if (!headers.has("Content-Type")) {
  1018. headers.set("Content-Type", "application/json; charset=utf-8");
  1019. }
  1020. return new Response(JSON.stringify(data), _extends({}, responseInit, {
  1021. headers
  1022. }));
  1023. };
  1024. class AbortedDeferredError extends Error {}
  1025. class DeferredData {
  1026. constructor(data, responseInit) {
  1027. this.pendingKeysSet = new Set();
  1028. this.subscribers = new Set();
  1029. this.deferredKeys = [];
  1030. invariant(data && typeof data === "object" && !Array.isArray(data), "defer() only accepts plain objects"); // Set up an AbortController + Promise we can race against to exit early
  1031. // cancellation
  1032. let reject;
  1033. this.abortPromise = new Promise((_, r) => reject = r);
  1034. this.controller = new AbortController();
  1035. let onAbort = () => reject(new AbortedDeferredError("Deferred data aborted"));
  1036. this.unlistenAbortSignal = () => this.controller.signal.removeEventListener("abort", onAbort);
  1037. this.controller.signal.addEventListener("abort", onAbort);
  1038. this.data = Object.entries(data).reduce((acc, _ref) => {
  1039. let [key, value] = _ref;
  1040. return Object.assign(acc, {
  1041. [key]: this.trackPromise(key, value)
  1042. });
  1043. }, {});
  1044. if (this.done) {
  1045. // All incoming values were resolved
  1046. this.unlistenAbortSignal();
  1047. }
  1048. this.init = responseInit;
  1049. }
  1050. trackPromise(key, value) {
  1051. if (!(value instanceof Promise)) {
  1052. return value;
  1053. }
  1054. this.deferredKeys.push(key);
  1055. this.pendingKeysSet.add(key); // We store a little wrapper promise that will be extended with
  1056. // _data/_error props upon resolve/reject
  1057. let promise = Promise.race([value, this.abortPromise]).then(data => this.onSettle(promise, key, null, data), error => this.onSettle(promise, key, error)); // Register rejection listeners to avoid uncaught promise rejections on
  1058. // errors or aborted deferred values
  1059. promise.catch(() => {});
  1060. Object.defineProperty(promise, "_tracked", {
  1061. get: () => true
  1062. });
  1063. return promise;
  1064. }
  1065. onSettle(promise, key, error, data) {
  1066. if (this.controller.signal.aborted && error instanceof AbortedDeferredError) {
  1067. this.unlistenAbortSignal();
  1068. Object.defineProperty(promise, "_error", {
  1069. get: () => error
  1070. });
  1071. return Promise.reject(error);
  1072. }
  1073. this.pendingKeysSet.delete(key);
  1074. if (this.done) {
  1075. // Nothing left to abort!
  1076. this.unlistenAbortSignal();
  1077. }
  1078. if (error) {
  1079. Object.defineProperty(promise, "_error", {
  1080. get: () => error
  1081. });
  1082. this.emit(false, key);
  1083. return Promise.reject(error);
  1084. }
  1085. Object.defineProperty(promise, "_data", {
  1086. get: () => data
  1087. });
  1088. this.emit(false, key);
  1089. return data;
  1090. }
  1091. emit(aborted, settledKey) {
  1092. this.subscribers.forEach(subscriber => subscriber(aborted, settledKey));
  1093. }
  1094. subscribe(fn) {
  1095. this.subscribers.add(fn);
  1096. return () => this.subscribers.delete(fn);
  1097. }
  1098. cancel() {
  1099. this.controller.abort();
  1100. this.pendingKeysSet.forEach((v, k) => this.pendingKeysSet.delete(k));
  1101. this.emit(true);
  1102. }
  1103. async resolveData(signal) {
  1104. let aborted = false;
  1105. if (!this.done) {
  1106. let onAbort = () => this.cancel();
  1107. signal.addEventListener("abort", onAbort);
  1108. aborted = await new Promise(resolve => {
  1109. this.subscribe(aborted => {
  1110. signal.removeEventListener("abort", onAbort);
  1111. if (aborted || this.done) {
  1112. resolve(aborted);
  1113. }
  1114. });
  1115. });
  1116. }
  1117. return aborted;
  1118. }
  1119. get done() {
  1120. return this.pendingKeysSet.size === 0;
  1121. }
  1122. get unwrappedData() {
  1123. invariant(this.data !== null && this.done, "Can only unwrap data on initialized and settled deferreds");
  1124. return Object.entries(this.data).reduce((acc, _ref2) => {
  1125. let [key, value] = _ref2;
  1126. return Object.assign(acc, {
  1127. [key]: unwrapTrackedPromise(value)
  1128. });
  1129. }, {});
  1130. }
  1131. get pendingKeys() {
  1132. return Array.from(this.pendingKeysSet);
  1133. }
  1134. }
  1135. function isTrackedPromise(value) {
  1136. return value instanceof Promise && value._tracked === true;
  1137. }
  1138. function unwrapTrackedPromise(value) {
  1139. if (!isTrackedPromise(value)) {
  1140. return value;
  1141. }
  1142. if (value._error) {
  1143. throw value._error;
  1144. }
  1145. return value._data;
  1146. }
  1147. const defer = function defer(data, init) {
  1148. if (init === void 0) {
  1149. init = {};
  1150. }
  1151. let responseInit = typeof init === "number" ? {
  1152. status: init
  1153. } : init;
  1154. return new DeferredData(data, responseInit);
  1155. };
  1156. /**
  1157. * A redirect response. Sets the status code and the `Location` header.
  1158. * Defaults to "302 Found".
  1159. */
  1160. const redirect = function redirect(url, init) {
  1161. if (init === void 0) {
  1162. init = 302;
  1163. }
  1164. let responseInit = init;
  1165. if (typeof responseInit === "number") {
  1166. responseInit = {
  1167. status: responseInit
  1168. };
  1169. } else if (typeof responseInit.status === "undefined") {
  1170. responseInit.status = 302;
  1171. }
  1172. let headers = new Headers(responseInit.headers);
  1173. headers.set("Location", url);
  1174. return new Response(null, _extends({}, responseInit, {
  1175. headers
  1176. }));
  1177. };
  1178. /**
  1179. * @private
  1180. * Utility class we use to hold auto-unwrapped 4xx/5xx Response bodies
  1181. */
  1182. class ErrorResponse {
  1183. constructor(status, statusText, data, internal) {
  1184. if (internal === void 0) {
  1185. internal = false;
  1186. }
  1187. this.status = status;
  1188. this.statusText = statusText || "";
  1189. this.internal = internal;
  1190. if (data instanceof Error) {
  1191. this.data = data.toString();
  1192. this.error = data;
  1193. } else {
  1194. this.data = data;
  1195. }
  1196. }
  1197. }
  1198. /**
  1199. * Check if the given error is an ErrorResponse generated from a 4xx/5xx
  1200. * Response thrown from an action/loader
  1201. */
  1202. function isRouteErrorResponse(error) {
  1203. return error != null && typeof error.status === "number" && typeof error.statusText === "string" && typeof error.internal === "boolean" && "data" in error;
  1204. }
  1205. //#region Types and Constants
  1206. ////////////////////////////////////////////////////////////////////////////////
  1207. /**
  1208. * A Router instance manages all navigation and data loading/mutations
  1209. */
  1210. const validMutationMethodsArr = ["post", "put", "patch", "delete"];
  1211. const validMutationMethods = new Set(validMutationMethodsArr);
  1212. const validRequestMethodsArr = ["get", ...validMutationMethodsArr];
  1213. const validRequestMethods = new Set(validRequestMethodsArr);
  1214. const redirectStatusCodes = new Set([301, 302, 303, 307, 308]);
  1215. const redirectPreserveMethodStatusCodes = new Set([307, 308]);
  1216. const IDLE_NAVIGATION = {
  1217. state: "idle",
  1218. location: undefined,
  1219. formMethod: undefined,
  1220. formAction: undefined,
  1221. formEncType: undefined,
  1222. formData: undefined
  1223. };
  1224. const IDLE_FETCHER = {
  1225. state: "idle",
  1226. data: undefined,
  1227. formMethod: undefined,
  1228. formAction: undefined,
  1229. formEncType: undefined,
  1230. formData: undefined
  1231. };
  1232. const IDLE_BLOCKER = {
  1233. state: "unblocked",
  1234. proceed: undefined,
  1235. reset: undefined,
  1236. location: undefined
  1237. };
  1238. const ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i;
  1239. const isBrowser = typeof window !== "undefined" && typeof window.document !== "undefined" && typeof window.document.createElement !== "undefined";
  1240. const isServer = !isBrowser; //#endregion
  1241. ////////////////////////////////////////////////////////////////////////////////
  1242. //#region createRouter
  1243. ////////////////////////////////////////////////////////////////////////////////
  1244. /**
  1245. * Create a router and listen to history POP navigations
  1246. */
  1247. function createRouter(init) {
  1248. invariant(init.routes.length > 0, "You must provide a non-empty routes array to createRouter");
  1249. let dataRoutes = convertRoutesToDataRoutes(init.routes); // Cleanup function for history
  1250. let unlistenHistory = null; // Externally-provided functions to call on all state changes
  1251. let subscribers = new Set(); // Externally-provided object to hold scroll restoration locations during routing
  1252. let savedScrollPositions = null; // Externally-provided function to get scroll restoration keys
  1253. let getScrollRestorationKey = null; // Externally-provided function to get current scroll position
  1254. let getScrollPosition = null; // One-time flag to control the initial hydration scroll restoration. Because
  1255. // we don't get the saved positions from <ScrollRestoration /> until _after_
  1256. // the initial render, we need to manually trigger a separate updateState to
  1257. // send along the restoreScrollPosition
  1258. // Set to true if we have `hydrationData` since we assume we were SSR'd and that
  1259. // SSR did the initial scroll restoration.
  1260. let initialScrollRestored = init.hydrationData != null;
  1261. let initialMatches = matchRoutes(dataRoutes, init.history.location, init.basename);
  1262. let initialErrors = null;
  1263. if (initialMatches == null) {
  1264. // If we do not match a user-provided-route, fall back to the root
  1265. // to allow the error boundary to take over
  1266. let error = getInternalRouterError(404, {
  1267. pathname: init.history.location.pathname
  1268. });
  1269. let {
  1270. matches,
  1271. route
  1272. } = getShortCircuitMatches(dataRoutes);
  1273. initialMatches = matches;
  1274. initialErrors = {
  1275. [route.id]: error
  1276. };
  1277. }
  1278. let initialized = !initialMatches.some(m => m.route.loader) || init.hydrationData != null;
  1279. let router;
  1280. let state = {
  1281. historyAction: init.history.action,
  1282. location: init.history.location,
  1283. matches: initialMatches,
  1284. initialized,
  1285. navigation: IDLE_NAVIGATION,
  1286. // Don't restore on initial updateState() if we were SSR'd
  1287. restoreScrollPosition: init.hydrationData != null ? false : null,
  1288. preventScrollReset: false,
  1289. revalidation: "idle",
  1290. loaderData: init.hydrationData && init.hydrationData.loaderData || {},
  1291. actionData: init.hydrationData && init.hydrationData.actionData || null,
  1292. errors: init.hydrationData && init.hydrationData.errors || initialErrors,
  1293. fetchers: new Map(),
  1294. blockers: new Map()
  1295. }; // -- Stateful internal variables to manage navigations --
  1296. // Current navigation in progress (to be committed in completeNavigation)
  1297. let pendingAction = exports.Action.Pop; // Should the current navigation prevent the scroll reset if scroll cannot
  1298. // be restored?
  1299. let pendingPreventScrollReset = false; // AbortController for the active navigation
  1300. let pendingNavigationController; // We use this to avoid touching history in completeNavigation if a
  1301. // revalidation is entirely uninterrupted
  1302. let isUninterruptedRevalidation = false; // Use this internal flag to force revalidation of all loaders:
  1303. // - submissions (completed or interrupted)
  1304. // - useRevalidate()
  1305. // - X-Remix-Revalidate (from redirect)
  1306. let isRevalidationRequired = false; // Use this internal array to capture routes that require revalidation due
  1307. // to a cancelled deferred on action submission
  1308. let cancelledDeferredRoutes = []; // Use this internal array to capture fetcher loads that were cancelled by an
  1309. // action navigation and require revalidation
  1310. let cancelledFetcherLoads = []; // AbortControllers for any in-flight fetchers
  1311. let fetchControllers = new Map(); // Track loads based on the order in which they started
  1312. let incrementingLoadId = 0; // Track the outstanding pending navigation data load to be compared against
  1313. // the globally incrementing load when a fetcher load lands after a completed
  1314. // navigation
  1315. let pendingNavigationLoadId = -1; // Fetchers that triggered data reloads as a result of their actions
  1316. let fetchReloadIds = new Map(); // Fetchers that triggered redirect navigations from their actions
  1317. let fetchRedirectIds = new Set(); // Most recent href/match for fetcher.load calls for fetchers
  1318. let fetchLoadMatches = new Map(); // Store DeferredData instances for active route matches. When a
  1319. // route loader returns defer() we stick one in here. Then, when a nested
  1320. // promise resolves we update loaderData. If a new navigation starts we
  1321. // cancel active deferreds for eliminated routes.
  1322. let activeDeferreds = new Map(); // Store blocker functions in a separate Map outside of router state since
  1323. // we don't need to update UI state if they change
  1324. let blockerFunctions = new Map(); // Flag to ignore the next history update, so we can revert the URL change on
  1325. // a POP navigation that was blocked by the user without touching router state
  1326. let ignoreNextHistoryUpdate = false; // Initialize the router, all side effects should be kicked off from here.
  1327. // Implemented as a Fluent API for ease of:
  1328. // let router = createRouter(init).initialize();
  1329. function initialize() {
  1330. // If history informs us of a POP navigation, start the navigation but do not update
  1331. // state. We'll update our own state once the navigation completes
  1332. unlistenHistory = init.history.listen(_ref => {
  1333. let {
  1334. action: historyAction,
  1335. location,
  1336. delta
  1337. } = _ref;
  1338. // Ignore this event if it was just us resetting the URL from a
  1339. // blocked POP navigation
  1340. if (ignoreNextHistoryUpdate) {
  1341. ignoreNextHistoryUpdate = false;
  1342. return;
  1343. }
  1344. warning(blockerFunctions.size === 0 || delta != null, "You are trying to use a blocker on a POP navigation to a location " + "that was not created by @remix-run/router. This will fail silently in " + "production. This can happen if you are navigating outside the router " + "via `window.history.pushState`/`window.location.hash` instead of using " + "router navigation APIs. This can also happen if you are using " + "createHashRouter and the user manually changes the URL.");
  1345. let blockerKey = shouldBlockNavigation({
  1346. currentLocation: state.location,
  1347. nextLocation: location,
  1348. historyAction
  1349. });
  1350. if (blockerKey && delta != null) {
  1351. // Restore the URL to match the current UI, but don't update router state
  1352. ignoreNextHistoryUpdate = true;
  1353. init.history.go(delta * -1); // Put the blocker into a blocked state
  1354. updateBlocker(blockerKey, {
  1355. state: "blocked",
  1356. location,
  1357. proceed() {
  1358. updateBlocker(blockerKey, {
  1359. state: "proceeding",
  1360. proceed: undefined,
  1361. reset: undefined,
  1362. location
  1363. }); // Re-do the same POP navigation we just blocked
  1364. init.history.go(delta);
  1365. },
  1366. reset() {
  1367. deleteBlocker(blockerKey);
  1368. updateState({
  1369. blockers: new Map(router.state.blockers)
  1370. });
  1371. }
  1372. });
  1373. return;
  1374. }
  1375. return startNavigation(historyAction, location);
  1376. }); // Kick off initial data load if needed. Use Pop to avoid modifying history
  1377. if (!state.initialized) {
  1378. startNavigation(exports.Action.Pop, state.location);
  1379. }
  1380. return router;
  1381. } // Clean up a router and it's side effects
  1382. function dispose() {
  1383. if (unlistenHistory) {
  1384. unlistenHistory();
  1385. }
  1386. subscribers.clear();
  1387. pendingNavigationController && pendingNavigationController.abort();
  1388. state.fetchers.forEach((_, key) => deleteFetcher(key));
  1389. state.blockers.forEach((_, key) => deleteBlocker(key));
  1390. } // Subscribe to state updates for the router
  1391. function subscribe(fn) {
  1392. subscribers.add(fn);
  1393. return () => subscribers.delete(fn);
  1394. } // Update our state and notify the calling context of the change
  1395. function updateState(newState) {
  1396. state = _extends({}, state, newState);
  1397. subscribers.forEach(subscriber => subscriber(state));
  1398. } // Complete a navigation returning the state.navigation back to the IDLE_NAVIGATION
  1399. // and setting state.[historyAction/location/matches] to the new route.
  1400. // - Location is a required param
  1401. // - Navigation will always be set to IDLE_NAVIGATION
  1402. // - Can pass any other state in newState
  1403. function completeNavigation(location, newState) {
  1404. var _location$state, _location$state2;
  1405. // Deduce if we're in a loading/actionReload state:
  1406. // - We have committed actionData in the store
  1407. // - The current navigation was a mutation submission
  1408. // - We're past the submitting state and into the loading state
  1409. // - The location being loaded is not the result of a redirect
  1410. let isActionReload = state.actionData != null && state.navigation.formMethod != null && isMutationMethod(state.navigation.formMethod) && state.navigation.state === "loading" && ((_location$state = location.state) == null ? void 0 : _location$state._isRedirect) !== true;
  1411. let actionData;
  1412. if (newState.actionData) {
  1413. if (Object.keys(newState.actionData).length > 0) {
  1414. actionData = newState.actionData;
  1415. } else {
  1416. // Empty actionData -> clear prior actionData due to an action error
  1417. actionData = null;
  1418. }
  1419. } else if (isActionReload) {
  1420. // Keep the current data if we're wrapping up the action reload
  1421. actionData = state.actionData;
  1422. } else {
  1423. // Clear actionData on any other completed navigations
  1424. actionData = null;
  1425. } // Always preserve any existing loaderData from re-used routes
  1426. let loaderData = newState.loaderData ? mergeLoaderData(state.loaderData, newState.loaderData, newState.matches || [], newState.errors) : state.loaderData; // On a successful navigation we can assume we got through all blockers
  1427. // so we can start fresh
  1428. for (let [key] of blockerFunctions) {
  1429. deleteBlocker(key);
  1430. } // Always respect the user flag. Otherwise don't reset on mutation
  1431. // submission navigations unless they redirect
  1432. let preventScrollReset = pendingPreventScrollReset === true || state.navigation.formMethod != null && isMutationMethod(state.navigation.formMethod) && ((_location$state2 = location.state) == null ? void 0 : _location$state2._isRedirect) !== true;
  1433. updateState(_extends({}, newState, {
  1434. // matches, errors, fetchers go through as-is
  1435. actionData,
  1436. loaderData,
  1437. historyAction: pendingAction,
  1438. location,
  1439. initialized: true,
  1440. navigation: IDLE_NAVIGATION,
  1441. revalidation: "idle",
  1442. restoreScrollPosition: getSavedScrollPosition(location, newState.matches || state.matches),
  1443. preventScrollReset,
  1444. blockers: new Map(state.blockers)
  1445. }));
  1446. if (isUninterruptedRevalidation) ; else if (pendingAction === exports.Action.Pop) ; else if (pendingAction === exports.Action.Push) {
  1447. init.history.push(location, location.state);
  1448. } else if (pendingAction === exports.Action.Replace) {
  1449. init.history.replace(location, location.state);
  1450. } // Reset stateful navigation vars
  1451. pendingAction = exports.Action.Pop;
  1452. pendingPreventScrollReset = false;
  1453. isUninterruptedRevalidation = false;
  1454. isRevalidationRequired = false;
  1455. cancelledDeferredRoutes = [];
  1456. cancelledFetcherLoads = [];
  1457. } // Trigger a navigation event, which can either be a numerical POP or a PUSH
  1458. // replace with an optional submission
  1459. async function navigate(to, opts) {
  1460. if (typeof to === "number") {
  1461. init.history.go(to);
  1462. return;
  1463. }
  1464. let {
  1465. path,
  1466. submission,
  1467. error
  1468. } = normalizeNavigateOptions(to, opts);
  1469. let currentLocation = state.location;
  1470. let nextLocation = createLocation(state.location, path, opts && opts.state); // When using navigate as a PUSH/REPLACE we aren't reading an already-encoded
  1471. // URL from window.location, so we need to encode it here so the behavior
  1472. // remains the same as POP and non-data-router usages. new URL() does all
  1473. // the same encoding we'd get from a history.pushState/window.location read
  1474. // without having to touch history
  1475. nextLocation = _extends({}, nextLocation, init.history.encodeLocation(nextLocation));
  1476. let userReplace = opts && opts.replace != null ? opts.replace : undefined;
  1477. let historyAction = exports.Action.Push;
  1478. if (userReplace === true) {
  1479. historyAction = exports.Action.Replace;
  1480. } else if (userReplace === false) ; else if (submission != null && isMutationMethod(submission.formMethod) && submission.formAction === state.location.pathname + state.location.search) {
  1481. // By default on submissions to the current location we REPLACE so that
  1482. // users don't have to double-click the back button to get to the prior
  1483. // location. If the user redirects to a different location from the
  1484. // action/loader this will be ignored and the redirect will be a PUSH
  1485. historyAction = exports.Action.Replace;
  1486. }
  1487. let preventScrollReset = opts && "preventScrollReset" in opts ? opts.preventScrollReset === true : undefined;
  1488. let blockerKey = shouldBlockNavigation({
  1489. currentLocation,
  1490. nextLocation,
  1491. historyAction
  1492. });
  1493. if (blockerKey) {
  1494. // Put the blocker into a blocked state
  1495. updateBlocker(blockerKey, {
  1496. state: "blocked",
  1497. location: nextLocation,
  1498. proceed() {
  1499. updateBlocker(blockerKey, {
  1500. state: "proceeding",
  1501. proceed: undefined,
  1502. reset: undefined,
  1503. location: nextLocation
  1504. }); // Send the same navigation through
  1505. navigate(to, opts);
  1506. },
  1507. reset() {
  1508. deleteBlocker(blockerKey);
  1509. updateState({
  1510. blockers: new Map(state.blockers)
  1511. });
  1512. }
  1513. });
  1514. return;
  1515. }
  1516. return await startNavigation(historyAction, nextLocation, {
  1517. submission,
  1518. // Send through the formData serialization error if we have one so we can
  1519. // render at the right error boundary after we match routes
  1520. pendingError: error,
  1521. preventScrollReset,
  1522. replace: opts && opts.replace
  1523. });
  1524. } // Revalidate all current loaders. If a navigation is in progress or if this
  1525. // is interrupted by a navigation, allow this to "succeed" by calling all
  1526. // loaders during the next loader round
  1527. function revalidate() {
  1528. interruptActiveLoads();
  1529. updateState({
  1530. revalidation: "loading"
  1531. }); // If we're currently submitting an action, we don't need to start a new
  1532. // navigation, we'll just let the follow up loader execution call all loaders
  1533. if (state.navigation.state === "submitting") {
  1534. return;
  1535. } // If we're currently in an idle state, start a new navigation for the current
  1536. // action/location and mark it as uninterrupted, which will skip the history
  1537. // update in completeNavigation
  1538. if (state.navigation.state === "idle") {
  1539. startNavigation(state.historyAction, state.location, {
  1540. startUninterruptedRevalidation: true
  1541. });
  1542. return;
  1543. } // Otherwise, if we're currently in a loading state, just start a new
  1544. // navigation to the navigation.location but do not trigger an uninterrupted
  1545. // revalidation so that history correctly updates once the navigation completes
  1546. startNavigation(pendingAction || state.historyAction, state.navigation.location, {
  1547. overrideNavigation: state.navigation
  1548. });
  1549. } // Start a navigation to the given action/location. Can optionally provide a
  1550. // overrideNavigation which will override the normalLoad in the case of a redirect
  1551. // navigation
  1552. async function startNavigation(historyAction, location, opts) {
  1553. // Abort any in-progress navigations and start a new one. Unset any ongoing
  1554. // uninterrupted revalidations unless told otherwise, since we want this
  1555. // new navigation to update history normally
  1556. pendingNavigationController && pendingNavigationController.abort();
  1557. pendingNavigationController = null;
  1558. pendingAction = historyAction;
  1559. isUninterruptedRevalidation = (opts && opts.startUninterruptedRevalidation) === true; // Save the current scroll position every time we start a new navigation,
  1560. // and track whether we should reset scroll on completion
  1561. saveScrollPosition(state.location, state.matches);
  1562. pendingPreventScrollReset = (opts && opts.preventScrollReset) === true;
  1563. let loadingNavigation = opts && opts.overrideNavigation;
  1564. let matches = matchRoutes(dataRoutes, location, init.basename); // Short circuit with a 404 on the root error boundary if we match nothing
  1565. if (!matches) {
  1566. let error = getInternalRouterError(404, {
  1567. pathname: location.pathname
  1568. });
  1569. let {
  1570. matches: notFoundMatches,
  1571. route
  1572. } = getShortCircuitMatches(dataRoutes); // Cancel all pending deferred on 404s since we don't keep any routes
  1573. cancelActiveDeferreds();
  1574. completeNavigation(location, {
  1575. matches: notFoundMatches,
  1576. loaderData: {},
  1577. errors: {
  1578. [route.id]: error
  1579. }
  1580. });
  1581. return;
  1582. } // Short circuit if it's only a hash change and not a mutation submission
  1583. // For example, on /page#hash and submit a <Form method="post"> which will
  1584. // default to a navigation to /page
  1585. if (isHashChangeOnly(state.location, location) && !(opts && opts.submission && isMutationMethod(opts.submission.formMethod))) {
  1586. completeNavigation(location, {
  1587. matches
  1588. });
  1589. return;
  1590. } // Create a controller/Request for this navigation
  1591. pendingNavigationController = new AbortController();
  1592. let request = createClientSideRequest(init.history, location, pendingNavigationController.signal, opts && opts.submission);
  1593. let pendingActionData;
  1594. let pendingError;
  1595. if (opts && opts.pendingError) {
  1596. // If we have a pendingError, it means the user attempted a GET submission
  1597. // with binary FormData so assign here and skip to handleLoaders. That
  1598. // way we handle calling loaders above the boundary etc. It's not really
  1599. // different from an actionError in that sense.
  1600. pendingError = {
  1601. [findNearestBoundary(matches).route.id]: opts.pendingError
  1602. };
  1603. } else if (opts && opts.submission && isMutationMethod(opts.submission.formMethod)) {
  1604. // Call action if we received an action submission
  1605. let actionOutput = await handleAction(request, location, opts.submission, matches, {
  1606. replace: opts.replace
  1607. });
  1608. if (actionOutput.shortCircuited) {
  1609. return;
  1610. }
  1611. pendingActionData = actionOutput.pendingActionData;
  1612. pendingError = actionOutput.pendingActionError;
  1613. let navigation = _extends({
  1614. state: "loading",
  1615. location
  1616. }, opts.submission);
  1617. loadingNavigation = navigation; // Create a GET request for the loaders
  1618. request = new Request(request.url, {
  1619. signal: request.signal
  1620. });
  1621. } // Call loaders
  1622. let {
  1623. shortCircuited,
  1624. loaderData,
  1625. errors
  1626. } = await handleLoaders(request, location, matches, loadingNavigation, opts && opts.submission, opts && opts.replace, pendingActionData, pendingError);
  1627. if (shortCircuited) {
  1628. return;
  1629. } // Clean up now that the action/loaders have completed. Don't clean up if
  1630. // we short circuited because pendingNavigationController will have already
  1631. // been assigned to a new controller for the next navigation
  1632. pendingNavigationController = null;
  1633. completeNavigation(location, _extends({
  1634. matches
  1635. }, pendingActionData ? {
  1636. actionData: pendingActionData
  1637. } : {}, {
  1638. loaderData,
  1639. errors
  1640. }));
  1641. } // Call the action matched by the leaf route for this navigation and handle
  1642. // redirects/errors
  1643. async function handleAction(request, location, submission, matches, opts) {
  1644. interruptActiveLoads(); // Put us in a submitting state
  1645. let navigation = _extends({
  1646. state: "submitting",
  1647. location
  1648. }, submission);
  1649. updateState({
  1650. navigation
  1651. }); // Call our action and get the result
  1652. let result;
  1653. let actionMatch = getTargetMatch(matches, location);
  1654. if (!actionMatch.route.action) {
  1655. result = {
  1656. type: ResultType.error,
  1657. error: getInternalRouterError(405, {
  1658. method: request.method,
  1659. pathname: location.pathname,
  1660. routeId: actionMatch.route.id
  1661. })
  1662. };
  1663. } else {
  1664. result = await callLoaderOrAction("action", request, actionMatch, matches, router.basename);
  1665. if (request.signal.aborted) {
  1666. return {
  1667. shortCircuited: true
  1668. };
  1669. }
  1670. }
  1671. if (isRedirectResult(result)) {
  1672. let replace;
  1673. if (opts && opts.replace != null) {
  1674. replace = opts.replace;
  1675. } else {
  1676. // If the user didn't explicity indicate replace behavior, replace if
  1677. // we redirected to the exact same location we're currently at to avoid
  1678. // double back-buttons
  1679. replace = result.location === state.location.pathname + state.location.search;
  1680. }
  1681. await startRedirectNavigation(state, result, {
  1682. submission,
  1683. replace
  1684. });
  1685. return {
  1686. shortCircuited: true
  1687. };
  1688. }
  1689. if (isErrorResult(result)) {
  1690. // Store off the pending error - we use it to determine which loaders
  1691. // to call and will commit it when we complete the navigation
  1692. let boundaryMatch = findNearestBoundary(matches, actionMatch.route.id); // By default, all submissions are REPLACE navigations, but if the
  1693. // action threw an error that'll be rendered in an errorElement, we fall
  1694. // back to PUSH so that the user can use the back button to get back to
  1695. // the pre-submission form location to try again
  1696. if ((opts && opts.replace) !== true) {
  1697. pendingAction = exports.Action.Push;
  1698. }
  1699. return {
  1700. // Send back an empty object we can use to clear out any prior actionData
  1701. pendingActionData: {},
  1702. pendingActionError: {
  1703. [boundaryMatch.route.id]: result.error
  1704. }
  1705. };
  1706. }
  1707. if (isDeferredResult(result)) {
  1708. throw getInternalRouterError(400, {
  1709. type: "defer-action"
  1710. });
  1711. }
  1712. return {
  1713. pendingActionData: {
  1714. [actionMatch.route.id]: result.data
  1715. }
  1716. };
  1717. } // Call all applicable loaders for the given matches, handling redirects,
  1718. // errors, etc.
  1719. async function handleLoaders(request, location, matches, overrideNavigation, submission, replace, pendingActionData, pendingError) {
  1720. // Figure out the right navigation we want to use for data loading
  1721. let loadingNavigation = overrideNavigation;
  1722. if (!loadingNavigation) {
  1723. let navigation = _extends({
  1724. state: "loading",
  1725. location,
  1726. formMethod: undefined,
  1727. formAction: undefined,
  1728. formEncType: undefined,
  1729. formData: undefined
  1730. }, submission);
  1731. loadingNavigation = navigation;
  1732. } // If this was a redirect from an action we don't have a "submission" but
  1733. // we have it on the loading navigation so use that if available
  1734. let activeSubmission = submission ? submission : loadingNavigation.formMethod && loadingNavigation.formAction && loadingNavigation.formData && loadingNavigation.formEncType ? {
  1735. formMethod: loadingNavigation.formMethod,
  1736. formAction: loadingNavigation.formAction,
  1737. formData: loadingNavigation.formData,
  1738. formEncType: loadingNavigation.formEncType
  1739. } : undefined;
  1740. let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(init.history, state, matches, activeSubmission, location, isRevalidationRequired, cancelledDeferredRoutes, cancelledFetcherLoads, pendingActionData, pendingError, fetchLoadMatches); // Cancel pending deferreds for no-longer-matched routes or routes we're
  1741. // about to reload. Note that if this is an action reload we would have
  1742. // already cancelled all pending deferreds so this would be a no-op
  1743. cancelActiveDeferreds(routeId => !(matches && matches.some(m => m.route.id === routeId)) || matchesToLoad && matchesToLoad.some(m => m.route.id === routeId)); // Short circuit if we have no loaders to run
  1744. if (matchesToLoad.length === 0 && revalidatingFetchers.length === 0) {
  1745. completeNavigation(location, _extends({
  1746. matches,
  1747. loaderData: {},
  1748. // Commit pending error if we're short circuiting
  1749. errors: pendingError || null
  1750. }, pendingActionData ? {
  1751. actionData: pendingActionData
  1752. } : {}));
  1753. return {
  1754. shortCircuited: true
  1755. };
  1756. } // If this is an uninterrupted revalidation, we remain in our current idle
  1757. // state. If not, we need to switch to our loading state and load data,
  1758. // preserving any new action data or existing action data (in the case of
  1759. // a revalidation interrupting an actionReload)
  1760. if (!isUninterruptedRevalidation) {
  1761. revalidatingFetchers.forEach(rf => {
  1762. let fetcher = state.fetchers.get(rf.key);
  1763. let revalidatingFetcher = {
  1764. state: "loading",
  1765. data: fetcher && fetcher.data,
  1766. formMethod: undefined,
  1767. formAction: undefined,
  1768. formEncType: undefined,
  1769. formData: undefined,
  1770. " _hasFetcherDoneAnything ": true
  1771. };
  1772. state.fetchers.set(rf.key, revalidatingFetcher);
  1773. });
  1774. let actionData = pendingActionData || state.actionData;
  1775. updateState(_extends({
  1776. navigation: loadingNavigation
  1777. }, actionData ? Object.keys(actionData).length === 0 ? {
  1778. actionData: null
  1779. } : {
  1780. actionData
  1781. } : {}, revalidatingFetchers.length > 0 ? {
  1782. fetchers: new Map(state.fetchers)
  1783. } : {}));
  1784. }
  1785. pendingNavigationLoadId = ++incrementingLoadId;
  1786. revalidatingFetchers.forEach(rf => fetchControllers.set(rf.key, pendingNavigationController));
  1787. let {
  1788. results,
  1789. loaderResults,
  1790. fetcherResults
  1791. } = await callLoadersAndMaybeResolveData(state.matches, matches, matchesToLoad, revalidatingFetchers, request);
  1792. if (request.signal.aborted) {
  1793. return {
  1794. shortCircuited: true
  1795. };
  1796. } // Clean up _after_ loaders have completed. Don't clean up if we short
  1797. // circuited because fetchControllers would have been aborted and
  1798. // reassigned to new controllers for the next navigation
  1799. revalidatingFetchers.forEach(rf => fetchControllers.delete(rf.key)); // If any loaders returned a redirect Response, start a new REPLACE navigation
  1800. let redirect = findRedirect(results);
  1801. if (redirect) {
  1802. await startRedirectNavigation(state, redirect, {
  1803. replace
  1804. });
  1805. return {
  1806. shortCircuited: true
  1807. };
  1808. } // Process and commit output from loaders
  1809. let {
  1810. loaderData,
  1811. errors
  1812. } = processLoaderData(state, matches, matchesToLoad, loaderResults, pendingError, revalidatingFetchers, fetcherResults, activeDeferreds); // Wire up subscribers to update loaderData as promises settle
  1813. activeDeferreds.forEach((deferredData, routeId) => {
  1814. deferredData.subscribe(aborted => {
  1815. // Note: No need to updateState here since the TrackedPromise on
  1816. // loaderData is stable across resolve/reject
  1817. // Remove this instance if we were aborted or if promises have settled
  1818. if (aborted || deferredData.done) {
  1819. activeDeferreds.delete(routeId);
  1820. }
  1821. });
  1822. });
  1823. markFetchRedirectsDone();
  1824. let didAbortFetchLoads = abortStaleFetchLoads(pendingNavigationLoadId);
  1825. return _extends({
  1826. loaderData,
  1827. errors
  1828. }, didAbortFetchLoads || revalidatingFetchers.length > 0 ? {
  1829. fetchers: new Map(state.fetchers)
  1830. } : {});
  1831. }
  1832. function getFetcher(key) {
  1833. return state.fetchers.get(key) || IDLE_FETCHER;
  1834. } // Trigger a fetcher load/submit for the given fetcher key
  1835. function fetch(key, routeId, href, opts) {
  1836. if (isServer) {
  1837. throw new Error("router.fetch() was called during the server render, but it shouldn't be. " + "You are likely calling a useFetcher() method in the body of your component. " + "Try moving it to a useEffect or a callback.");
  1838. }
  1839. if (fetchControllers.has(key)) abortFetcher(key);
  1840. let matches = matchRoutes(dataRoutes, href, init.basename);
  1841. if (!matches) {
  1842. setFetcherError(key, routeId, getInternalRouterError(404, {
  1843. pathname: href
  1844. }));
  1845. return;
  1846. }
  1847. let {
  1848. path,
  1849. submission
  1850. } = normalizeNavigateOptions(href, opts, true);
  1851. let match = getTargetMatch(matches, path);
  1852. pendingPreventScrollReset = (opts && opts.preventScrollReset) === true;
  1853. if (submission && isMutationMethod(submission.formMethod)) {
  1854. handleFetcherAction(key, routeId, path, match, matches, submission);
  1855. return;
  1856. } // Store off the match so we can call it's shouldRevalidate on subsequent
  1857. // revalidations
  1858. fetchLoadMatches.set(key, {
  1859. routeId,
  1860. path,
  1861. match,
  1862. matches
  1863. });
  1864. handleFetcherLoader(key, routeId, path, match, matches, submission);
  1865. } // Call the action for the matched fetcher.submit(), and then handle redirects,
  1866. // errors, and revalidation
  1867. async function handleFetcherAction(key, routeId, path, match, requestMatches, submission) {
  1868. interruptActiveLoads();
  1869. fetchLoadMatches.delete(key);
  1870. if (!match.route.action) {
  1871. let error = getInternalRouterError(405, {
  1872. method: submission.formMethod,
  1873. pathname: path,
  1874. routeId: routeId
  1875. });
  1876. setFetcherError(key, routeId, error);
  1877. return;
  1878. } // Put this fetcher into it's submitting state
  1879. let existingFetcher = state.fetchers.get(key);
  1880. let fetcher = _extends({
  1881. state: "submitting"
  1882. }, submission, {
  1883. data: existingFetcher && existingFetcher.data,
  1884. " _hasFetcherDoneAnything ": true
  1885. });
  1886. state.fetchers.set(key, fetcher);
  1887. updateState({
  1888. fetchers: new Map(state.fetchers)
  1889. }); // Call the action for the fetcher
  1890. let abortController = new AbortController();
  1891. let fetchRequest = createClientSideRequest(init.history, path, abortController.signal, submission);
  1892. fetchControllers.set(key, abortController);
  1893. let actionResult = await callLoaderOrAction("action", fetchRequest, match, requestMatches, router.basename);
  1894. if (fetchRequest.signal.aborted) {
  1895. // We can delete this so long as we weren't aborted by ou our own fetcher
  1896. // re-submit which would have put _new_ controller is in fetchControllers
  1897. if (fetchControllers.get(key) === abortController) {
  1898. fetchControllers.delete(key);
  1899. }
  1900. return;
  1901. }
  1902. if (isRedirectResult(actionResult)) {
  1903. fetchControllers.delete(key);
  1904. fetchRedirectIds.add(key);
  1905. let loadingFetcher = _extends({
  1906. state: "loading"
  1907. }, submission, {
  1908. data: undefined,
  1909. " _hasFetcherDoneAnything ": true
  1910. });
  1911. state.fetchers.set(key, loadingFetcher);
  1912. updateState({
  1913. fetchers: new Map(state.fetchers)
  1914. });
  1915. return startRedirectNavigation(state, actionResult, {
  1916. isFetchActionRedirect: true
  1917. });
  1918. } // Process any non-redirect errors thrown
  1919. if (isErrorResult(actionResult)) {
  1920. setFetcherError(key, routeId, actionResult.error);
  1921. return;
  1922. }
  1923. if (isDeferredResult(actionResult)) {
  1924. throw getInternalRouterError(400, {
  1925. type: "defer-action"
  1926. });
  1927. } // Start the data load for current matches, or the next location if we're
  1928. // in the middle of a navigation
  1929. let nextLocation = state.navigation.location || state.location;
  1930. let revalidationRequest = createClientSideRequest(init.history, nextLocation, abortController.signal);
  1931. let matches = state.navigation.state !== "idle" ? matchRoutes(dataRoutes, state.navigation.location, init.basename) : state.matches;
  1932. invariant(matches, "Didn't find any matches after fetcher action");
  1933. let loadId = ++incrementingLoadId;
  1934. fetchReloadIds.set(key, loadId);
  1935. let loadFetcher = _extends({
  1936. state: "loading",
  1937. data: actionResult.data
  1938. }, submission, {
  1939. " _hasFetcherDoneAnything ": true
  1940. });
  1941. state.fetchers.set(key, loadFetcher);
  1942. let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(init.history, state, matches, submission, nextLocation, isRevalidationRequired, cancelledDeferredRoutes, cancelledFetcherLoads, {
  1943. [match.route.id]: actionResult.data
  1944. }, undefined, // No need to send through errors since we short circuit above
  1945. fetchLoadMatches); // Put all revalidating fetchers into the loading state, except for the
  1946. // current fetcher which we want to keep in it's current loading state which
  1947. // contains it's action submission info + action data
  1948. revalidatingFetchers.filter(rf => rf.key !== key).forEach(rf => {
  1949. let staleKey = rf.key;
  1950. let existingFetcher = state.fetchers.get(staleKey);
  1951. let revalidatingFetcher = {
  1952. state: "loading",
  1953. data: existingFetcher && existingFetcher.data,
  1954. formMethod: undefined,
  1955. formAction: undefined,
  1956. formEncType: undefined,
  1957. formData: undefined,
  1958. " _hasFetcherDoneAnything ": true
  1959. };
  1960. state.fetchers.set(staleKey, revalidatingFetcher);
  1961. fetchControllers.set(staleKey, abortController);
  1962. });
  1963. updateState({
  1964. fetchers: new Map(state.fetchers)
  1965. });
  1966. let {
  1967. results,
  1968. loaderResults,
  1969. fetcherResults
  1970. } = await callLoadersAndMaybeResolveData(state.matches, matches, matchesToLoad, revalidatingFetchers, revalidationRequest);
  1971. if (abortController.signal.aborted) {
  1972. return;
  1973. }
  1974. fetchReloadIds.delete(key);
  1975. fetchControllers.delete(key);
  1976. revalidatingFetchers.forEach(r => fetchControllers.delete(r.key));
  1977. let redirect = findRedirect(results);
  1978. if (redirect) {
  1979. return startRedirectNavigation(state, redirect);
  1980. } // Process and commit output from loaders
  1981. let {
  1982. loaderData,
  1983. errors
  1984. } = processLoaderData(state, state.matches, matchesToLoad, loaderResults, undefined, revalidatingFetchers, fetcherResults, activeDeferreds);
  1985. let doneFetcher = {
  1986. state: "idle",
  1987. data: actionResult.data,
  1988. formMethod: undefined,
  1989. formAction: undefined,
  1990. formEncType: undefined,
  1991. formData: undefined,
  1992. " _hasFetcherDoneAnything ": true
  1993. };
  1994. state.fetchers.set(key, doneFetcher);
  1995. let didAbortFetchLoads = abortStaleFetchLoads(loadId); // If we are currently in a navigation loading state and this fetcher is
  1996. // more recent than the navigation, we want the newer data so abort the
  1997. // navigation and complete it with the fetcher data
  1998. if (state.navigation.state === "loading" && loadId > pendingNavigationLoadId) {
  1999. invariant(pendingAction, "Expected pending action");
  2000. pendingNavigationController && pendingNavigationController.abort();
  2001. completeNavigation(state.navigation.location, {
  2002. matches,
  2003. loaderData,
  2004. errors,
  2005. fetchers: new Map(state.fetchers)
  2006. });
  2007. } else {
  2008. // otherwise just update with the fetcher data, preserving any existing
  2009. // loaderData for loaders that did not need to reload. We have to
  2010. // manually merge here since we aren't going through completeNavigation
  2011. updateState(_extends({
  2012. errors,
  2013. loaderData: mergeLoaderData(state.loaderData, loaderData, matches, errors)
  2014. }, didAbortFetchLoads ? {
  2015. fetchers: new Map(state.fetchers)
  2016. } : {}));
  2017. isRevalidationRequired = false;
  2018. }
  2019. } // Call the matched loader for fetcher.load(), handling redirects, errors, etc.
  2020. async function handleFetcherLoader(key, routeId, path, match, matches, submission) {
  2021. let existingFetcher = state.fetchers.get(key); // Put this fetcher into it's loading state
  2022. let loadingFetcher = _extends({
  2023. state: "loading",
  2024. formMethod: undefined,
  2025. formAction: undefined,
  2026. formEncType: undefined,
  2027. formData: undefined
  2028. }, submission, {
  2029. data: existingFetcher && existingFetcher.data,
  2030. " _hasFetcherDoneAnything ": true
  2031. });
  2032. state.fetchers.set(key, loadingFetcher);
  2033. updateState({
  2034. fetchers: new Map(state.fetchers)
  2035. }); // Call the loader for this fetcher route match
  2036. let abortController = new AbortController();
  2037. let fetchRequest = createClientSideRequest(init.history, path, abortController.signal);
  2038. fetchControllers.set(key, abortController);
  2039. let result = await callLoaderOrAction("loader", fetchRequest, match, matches, router.basename); // Deferred isn't supported for fetcher loads, await everything and treat it
  2040. // as a normal load. resolveDeferredData will return undefined if this
  2041. // fetcher gets aborted, so we just leave result untouched and short circuit
  2042. // below if that happens
  2043. if (isDeferredResult(result)) {
  2044. result = (await resolveDeferredData(result, fetchRequest.signal, true)) || result;
  2045. } // We can delete this so long as we weren't aborted by ou our own fetcher
  2046. // re-load which would have put _new_ controller is in fetchControllers
  2047. if (fetchControllers.get(key) === abortController) {
  2048. fetchControllers.delete(key);
  2049. }
  2050. if (fetchRequest.signal.aborted) {
  2051. return;
  2052. } // If the loader threw a redirect Response, start a new REPLACE navigation
  2053. if (isRedirectResult(result)) {
  2054. await startRedirectNavigation(state, result);
  2055. return;
  2056. } // Process any non-redirect errors thrown
  2057. if (isErrorResult(result)) {
  2058. let boundaryMatch = findNearestBoundary(state.matches, routeId);
  2059. state.fetchers.delete(key); // TODO: In remix, this would reset to IDLE_NAVIGATION if it was a catch -
  2060. // do we need to behave any differently with our non-redirect errors?
  2061. // What if it was a non-redirect Response?
  2062. updateState({
  2063. fetchers: new Map(state.fetchers),
  2064. errors: {
  2065. [boundaryMatch.route.id]: result.error
  2066. }
  2067. });
  2068. return;
  2069. }
  2070. invariant(!isDeferredResult(result), "Unhandled fetcher deferred data"); // Put the fetcher back into an idle state
  2071. let doneFetcher = {
  2072. state: "idle",
  2073. data: result.data,
  2074. formMethod: undefined,
  2075. formAction: undefined,
  2076. formEncType: undefined,
  2077. formData: undefined,
  2078. " _hasFetcherDoneAnything ": true
  2079. };
  2080. state.fetchers.set(key, doneFetcher);
  2081. updateState({
  2082. fetchers: new Map(state.fetchers)
  2083. });
  2084. }
  2085. /**
  2086. * Utility function to handle redirects returned from an action or loader.
  2087. * Normally, a redirect "replaces" the navigation that triggered it. So, for
  2088. * example:
  2089. *
  2090. * - user is on /a
  2091. * - user clicks a link to /b
  2092. * - loader for /b redirects to /c
  2093. *
  2094. * In a non-JS app the browser would track the in-flight navigation to /b and
  2095. * then replace it with /c when it encountered the redirect response. In
  2096. * the end it would only ever update the URL bar with /c.
  2097. *
  2098. * In client-side routing using pushState/replaceState, we aim to emulate
  2099. * this behavior and we also do not update history until the end of the
  2100. * navigation (including processed redirects). This means that we never
  2101. * actually touch history until we've processed redirects, so we just use
  2102. * the history action from the original navigation (PUSH or REPLACE).
  2103. */
  2104. async function startRedirectNavigation(state, redirect, _temp) {
  2105. var _window;
  2106. let {
  2107. submission,
  2108. replace,
  2109. isFetchActionRedirect
  2110. } = _temp === void 0 ? {} : _temp;
  2111. if (redirect.revalidate) {
  2112. isRevalidationRequired = true;
  2113. }
  2114. let redirectLocation = createLocation(state.location, redirect.location, // TODO: This can be removed once we get rid of useTransition in Remix v2
  2115. _extends({
  2116. _isRedirect: true
  2117. }, isFetchActionRedirect ? {
  2118. _isFetchActionRedirect: true
  2119. } : {}));
  2120. invariant(redirectLocation, "Expected a location on the redirect navigation"); // Check if this an absolute external redirect that goes to a new origin
  2121. if (ABSOLUTE_URL_REGEX.test(redirect.location) && isBrowser && typeof ((_window = window) == null ? void 0 : _window.location) !== "undefined") {
  2122. let newOrigin = init.history.createURL(redirect.location).origin;
  2123. if (window.location.origin !== newOrigin) {
  2124. if (replace) {
  2125. window.location.replace(redirect.location);
  2126. } else {
  2127. window.location.assign(redirect.location);
  2128. }
  2129. return;
  2130. }
  2131. } // There's no need to abort on redirects, since we don't detect the
  2132. // redirect until the action/loaders have settled
  2133. pendingNavigationController = null;
  2134. let redirectHistoryAction = replace === true ? exports.Action.Replace : exports.Action.Push; // Use the incoming submission if provided, fallback on the active one in
  2135. // state.navigation
  2136. let {
  2137. formMethod,
  2138. formAction,
  2139. formEncType,
  2140. formData
  2141. } = state.navigation;
  2142. if (!submission && formMethod && formAction && formData && formEncType) {
  2143. submission = {
  2144. formMethod,
  2145. formAction,
  2146. formEncType,
  2147. formData
  2148. };
  2149. } // If this was a 307/308 submission we want to preserve the HTTP method and
  2150. // re-submit the GET/POST/PUT/PATCH/DELETE as a submission navigation to the
  2151. // redirected location
  2152. if (redirectPreserveMethodStatusCodes.has(redirect.status) && submission && isMutationMethod(submission.formMethod)) {
  2153. await startNavigation(redirectHistoryAction, redirectLocation, {
  2154. submission: _extends({}, submission, {
  2155. formAction: redirect.location
  2156. }),
  2157. // Preserve this flag across redirects
  2158. preventScrollReset: pendingPreventScrollReset
  2159. });
  2160. } else {
  2161. // Otherwise, we kick off a new loading navigation, preserving the
  2162. // submission info for the duration of this navigation
  2163. await startNavigation(redirectHistoryAction, redirectLocation, {
  2164. overrideNavigation: {
  2165. state: "loading",
  2166. location: redirectLocation,
  2167. formMethod: submission ? submission.formMethod : undefined,
  2168. formAction: submission ? submission.formAction : undefined,
  2169. formEncType: submission ? submission.formEncType : undefined,
  2170. formData: submission ? submission.formData : undefined
  2171. },
  2172. // Preserve this flag across redirects
  2173. preventScrollReset: pendingPreventScrollReset
  2174. });
  2175. }
  2176. }
  2177. async function callLoadersAndMaybeResolveData(currentMatches, matches, matchesToLoad, fetchersToLoad, request) {
  2178. // Call all navigation loaders and revalidating fetcher loaders in parallel,
  2179. // then slice off the results into separate arrays so we can handle them
  2180. // accordingly
  2181. let results = await Promise.all([...matchesToLoad.map(match => callLoaderOrAction("loader", request, match, matches, router.basename)), ...fetchersToLoad.map(f => callLoaderOrAction("loader", createClientSideRequest(init.history, f.path, request.signal), f.match, f.matches, router.basename))]);
  2182. let loaderResults = results.slice(0, matchesToLoad.length);
  2183. let fetcherResults = results.slice(matchesToLoad.length);
  2184. await Promise.all([resolveDeferredResults(currentMatches, matchesToLoad, loaderResults, request.signal, false, state.loaderData), resolveDeferredResults(currentMatches, fetchersToLoad.map(f => f.match), fetcherResults, request.signal, true)]);
  2185. return {
  2186. results,
  2187. loaderResults,
  2188. fetcherResults
  2189. };
  2190. }
  2191. function interruptActiveLoads() {
  2192. // Every interruption triggers a revalidation
  2193. isRevalidationRequired = true; // Cancel pending route-level deferreds and mark cancelled routes for
  2194. // revalidation
  2195. cancelledDeferredRoutes.push(...cancelActiveDeferreds()); // Abort in-flight fetcher loads
  2196. fetchLoadMatches.forEach((_, key) => {
  2197. if (fetchControllers.has(key)) {
  2198. cancelledFetcherLoads.push(key);
  2199. abortFetcher(key);
  2200. }
  2201. });
  2202. }
  2203. function setFetcherError(key, routeId, error) {
  2204. let boundaryMatch = findNearestBoundary(state.matches, routeId);
  2205. deleteFetcher(key);
  2206. updateState({
  2207. errors: {
  2208. [boundaryMatch.route.id]: error
  2209. },
  2210. fetchers: new Map(state.fetchers)
  2211. });
  2212. }
  2213. function deleteFetcher(key) {
  2214. if (fetchControllers.has(key)) abortFetcher(key);
  2215. fetchLoadMatches.delete(key);
  2216. fetchReloadIds.delete(key);
  2217. fetchRedirectIds.delete(key);
  2218. state.fetchers.delete(key);
  2219. }
  2220. function abortFetcher(key) {
  2221. let controller = fetchControllers.get(key);
  2222. invariant(controller, "Expected fetch controller: " + key);
  2223. controller.abort();
  2224. fetchControllers.delete(key);
  2225. }
  2226. function markFetchersDone(keys) {
  2227. for (let key of keys) {
  2228. let fetcher = getFetcher(key);
  2229. let doneFetcher = {
  2230. state: "idle",
  2231. data: fetcher.data,
  2232. formMethod: undefined,
  2233. formAction: undefined,
  2234. formEncType: undefined,
  2235. formData: undefined,
  2236. " _hasFetcherDoneAnything ": true
  2237. };
  2238. state.fetchers.set(key, doneFetcher);
  2239. }
  2240. }
  2241. function markFetchRedirectsDone() {
  2242. let doneKeys = [];
  2243. for (let key of fetchRedirectIds) {
  2244. let fetcher = state.fetchers.get(key);
  2245. invariant(fetcher, "Expected fetcher: " + key);
  2246. if (fetcher.state === "loading") {
  2247. fetchRedirectIds.delete(key);
  2248. doneKeys.push(key);
  2249. }
  2250. }
  2251. markFetchersDone(doneKeys);
  2252. }
  2253. function abortStaleFetchLoads(landedId) {
  2254. let yeetedKeys = [];
  2255. for (let [key, id] of fetchReloadIds) {
  2256. if (id < landedId) {
  2257. let fetcher = state.fetchers.get(key);
  2258. invariant(fetcher, "Expected fetcher: " + key);
  2259. if (fetcher.state === "loading") {
  2260. abortFetcher(key);
  2261. fetchReloadIds.delete(key);
  2262. yeetedKeys.push(key);
  2263. }
  2264. }
  2265. }
  2266. markFetchersDone(yeetedKeys);
  2267. return yeetedKeys.length > 0;
  2268. }
  2269. function getBlocker(key, fn) {
  2270. let blocker = state.blockers.get(key) || IDLE_BLOCKER;
  2271. if (blockerFunctions.get(key) !== fn) {
  2272. blockerFunctions.set(key, fn);
  2273. }
  2274. return blocker;
  2275. }
  2276. function deleteBlocker(key) {
  2277. state.blockers.delete(key);
  2278. blockerFunctions.delete(key);
  2279. } // Utility function to update blockers, ensuring valid state transitions
  2280. function updateBlocker(key, newBlocker) {
  2281. let blocker = state.blockers.get(key) || IDLE_BLOCKER; // Poor mans state machine :)
  2282. // https://mermaid.live/edit#pako:eNqVkc9OwzAMxl8l8nnjAYrEtDIOHEBIgwvKJTReGy3_lDpIqO27k6awMG0XcrLlnz87nwdonESogKXXBuE79rq75XZO3-yHds0RJVuv70YrPlUrCEe2HfrORS3rubqZfuhtpg5C9wk5tZ4VKcRUq88q9Z8RS0-48cE1iHJkL0ugbHuFLus9L6spZy8nX9MP2CNdomVaposqu3fGayT8T8-jJQwhepo_UtpgBQaDEUom04dZhAN1aJBDlUKJBxE1ceB2Smj0Mln-IBW5AFU2dwUiktt_2Qaq2dBfaKdEup85UV7Yd-dKjlnkabl2Pvr0DTkTreM
  2283. invariant(blocker.state === "unblocked" && newBlocker.state === "blocked" || blocker.state === "blocked" && newBlocker.state === "blocked" || blocker.state === "blocked" && newBlocker.state === "proceeding" || blocker.state === "blocked" && newBlocker.state === "unblocked" || blocker.state === "proceeding" && newBlocker.state === "unblocked", "Invalid blocker state transition: " + blocker.state + " -> " + newBlocker.state);
  2284. state.blockers.set(key, newBlocker);
  2285. updateState({
  2286. blockers: new Map(state.blockers)
  2287. });
  2288. }
  2289. function shouldBlockNavigation(_ref2) {
  2290. let {
  2291. currentLocation,
  2292. nextLocation,
  2293. historyAction
  2294. } = _ref2;
  2295. if (blockerFunctions.size === 0) {
  2296. return;
  2297. } // We ony support a single active blocker at the moment since we don't have
  2298. // any compelling use cases for multi-blocker yet
  2299. if (blockerFunctions.size > 1) {
  2300. warning(false, "A router only supports one blocker at a time");
  2301. }
  2302. let entries = Array.from(blockerFunctions.entries());
  2303. let [blockerKey, blockerFunction] = entries[entries.length - 1];
  2304. let blocker = state.blockers.get(blockerKey);
  2305. if (blocker && blocker.state === "proceeding") {
  2306. // If the blocker is currently proceeding, we don't need to re-check
  2307. // it and can let this navigation continue
  2308. return;
  2309. } // At this point, we know we're unblocked/blocked so we need to check the
  2310. // user-provided blocker function
  2311. if (blockerFunction({
  2312. currentLocation,
  2313. nextLocation,
  2314. historyAction
  2315. })) {
  2316. return blockerKey;
  2317. }
  2318. }
  2319. function cancelActiveDeferreds(predicate) {
  2320. let cancelledRouteIds = [];
  2321. activeDeferreds.forEach((dfd, routeId) => {
  2322. if (!predicate || predicate(routeId)) {
  2323. // Cancel the deferred - but do not remove from activeDeferreds here -
  2324. // we rely on the subscribers to do that so our tests can assert proper
  2325. // cleanup via _internalActiveDeferreds
  2326. dfd.cancel();
  2327. cancelledRouteIds.push(routeId);
  2328. activeDeferreds.delete(routeId);
  2329. }
  2330. });
  2331. return cancelledRouteIds;
  2332. } // Opt in to capturing and reporting scroll positions during navigations,
  2333. // used by the <ScrollRestoration> component
  2334. function enableScrollRestoration(positions, getPosition, getKey) {
  2335. savedScrollPositions = positions;
  2336. getScrollPosition = getPosition;
  2337. getScrollRestorationKey = getKey || (location => location.key); // Perform initial hydration scroll restoration, since we miss the boat on
  2338. // the initial updateState() because we've not yet rendered <ScrollRestoration/>
  2339. // and therefore have no savedScrollPositions available
  2340. if (!initialScrollRestored && state.navigation === IDLE_NAVIGATION) {
  2341. initialScrollRestored = true;
  2342. let y = getSavedScrollPosition(state.location, state.matches);
  2343. if (y != null) {
  2344. updateState({
  2345. restoreScrollPosition: y
  2346. });
  2347. }
  2348. }
  2349. return () => {
  2350. savedScrollPositions = null;
  2351. getScrollPosition = null;
  2352. getScrollRestorationKey = null;
  2353. };
  2354. }
  2355. function saveScrollPosition(location, matches) {
  2356. if (savedScrollPositions && getScrollRestorationKey && getScrollPosition) {
  2357. let userMatches = matches.map(m => createUseMatchesMatch(m, state.loaderData));
  2358. let key = getScrollRestorationKey(location, userMatches) || location.key;
  2359. savedScrollPositions[key] = getScrollPosition();
  2360. }
  2361. }
  2362. function getSavedScrollPosition(location, matches) {
  2363. if (savedScrollPositions && getScrollRestorationKey && getScrollPosition) {
  2364. let userMatches = matches.map(m => createUseMatchesMatch(m, state.loaderData));
  2365. let key = getScrollRestorationKey(location, userMatches) || location.key;
  2366. let y = savedScrollPositions[key];
  2367. if (typeof y === "number") {
  2368. return y;
  2369. }
  2370. }
  2371. return null;
  2372. }
  2373. router = {
  2374. get basename() {
  2375. return init.basename;
  2376. },
  2377. get state() {
  2378. return state;
  2379. },
  2380. get routes() {
  2381. return dataRoutes;
  2382. },
  2383. initialize,
  2384. subscribe,
  2385. enableScrollRestoration,
  2386. navigate,
  2387. fetch,
  2388. revalidate,
  2389. // Passthrough to history-aware createHref used by useHref so we get proper
  2390. // hash-aware URLs in DOM paths
  2391. createHref: to => init.history.createHref(to),
  2392. encodeLocation: to => init.history.encodeLocation(to),
  2393. getFetcher,
  2394. deleteFetcher,
  2395. dispose,
  2396. getBlocker,
  2397. deleteBlocker,
  2398. _internalFetchControllers: fetchControllers,
  2399. _internalActiveDeferreds: activeDeferreds
  2400. };
  2401. return router;
  2402. } //#endregion
  2403. ////////////////////////////////////////////////////////////////////////////////
  2404. //#region createStaticHandler
  2405. ////////////////////////////////////////////////////////////////////////////////
  2406. const UNSAFE_DEFERRED_SYMBOL = Symbol("deferred");
  2407. function createStaticHandler(routes, opts) {
  2408. invariant(routes.length > 0, "You must provide a non-empty routes array to createStaticHandler");
  2409. let dataRoutes = convertRoutesToDataRoutes(routes);
  2410. let basename = (opts ? opts.basename : null) || "/";
  2411. /**
  2412. * The query() method is intended for document requests, in which we want to
  2413. * call an optional action and potentially multiple loaders for all nested
  2414. * routes. It returns a StaticHandlerContext object, which is very similar
  2415. * to the router state (location, loaderData, actionData, errors, etc.) and
  2416. * also adds SSR-specific information such as the statusCode and headers
  2417. * from action/loaders Responses.
  2418. *
  2419. * It _should_ never throw and should report all errors through the
  2420. * returned context.errors object, properly associating errors to their error
  2421. * boundary. Additionally, it tracks _deepestRenderedBoundaryId which can be
  2422. * used to emulate React error boundaries during SSr by performing a second
  2423. * pass only down to the boundaryId.
  2424. *
  2425. * The one exception where we do not return a StaticHandlerContext is when a
  2426. * redirect response is returned or thrown from any action/loader. We
  2427. * propagate that out and return the raw Response so the HTTP server can
  2428. * return it directly.
  2429. */
  2430. async function query(request, _temp2) {
  2431. let {
  2432. requestContext
  2433. } = _temp2 === void 0 ? {} : _temp2;
  2434. let url = new URL(request.url);
  2435. let method = request.method.toLowerCase();
  2436. let location = createLocation("", createPath(url), null, "default");
  2437. let matches = matchRoutes(dataRoutes, location, basename); // SSR supports HEAD requests while SPA doesn't
  2438. if (!isValidMethod(method) && method !== "head") {
  2439. let error = getInternalRouterError(405, {
  2440. method
  2441. });
  2442. let {
  2443. matches: methodNotAllowedMatches,
  2444. route
  2445. } = getShortCircuitMatches(dataRoutes);
  2446. return {
  2447. basename,
  2448. location,
  2449. matches: methodNotAllowedMatches,
  2450. loaderData: {},
  2451. actionData: null,
  2452. errors: {
  2453. [route.id]: error
  2454. },
  2455. statusCode: error.status,
  2456. loaderHeaders: {},
  2457. actionHeaders: {},
  2458. activeDeferreds: null
  2459. };
  2460. } else if (!matches) {
  2461. let error = getInternalRouterError(404, {
  2462. pathname: location.pathname
  2463. });
  2464. let {
  2465. matches: notFoundMatches,
  2466. route
  2467. } = getShortCircuitMatches(dataRoutes);
  2468. return {
  2469. basename,
  2470. location,
  2471. matches: notFoundMatches,
  2472. loaderData: {},
  2473. actionData: null,
  2474. errors: {
  2475. [route.id]: error
  2476. },
  2477. statusCode: error.status,
  2478. loaderHeaders: {},
  2479. actionHeaders: {},
  2480. activeDeferreds: null
  2481. };
  2482. }
  2483. let result = await queryImpl(request, location, matches, requestContext);
  2484. if (isResponse(result)) {
  2485. return result;
  2486. } // When returning StaticHandlerContext, we patch back in the location here
  2487. // since we need it for React Context. But this helps keep our submit and
  2488. // loadRouteData operating on a Request instead of a Location
  2489. return _extends({
  2490. location,
  2491. basename
  2492. }, result);
  2493. }
  2494. /**
  2495. * The queryRoute() method is intended for targeted route requests, either
  2496. * for fetch ?_data requests or resource route requests. In this case, we
  2497. * are only ever calling a single action or loader, and we are returning the
  2498. * returned value directly. In most cases, this will be a Response returned
  2499. * from the action/loader, but it may be a primitive or other value as well -
  2500. * and in such cases the calling context should handle that accordingly.
  2501. *
  2502. * We do respect the throw/return differentiation, so if an action/loader
  2503. * throws, then this method will throw the value. This is important so we
  2504. * can do proper boundary identification in Remix where a thrown Response
  2505. * must go to the Catch Boundary but a returned Response is happy-path.
  2506. *
  2507. * One thing to note is that any Router-initiated Errors that make sense
  2508. * to associate with a status code will be thrown as an ErrorResponse
  2509. * instance which include the raw Error, such that the calling context can
  2510. * serialize the error as they see fit while including the proper response
  2511. * code. Examples here are 404 and 405 errors that occur prior to reaching
  2512. * any user-defined loaders.
  2513. */
  2514. async function queryRoute(request, _temp3) {
  2515. let {
  2516. routeId,
  2517. requestContext
  2518. } = _temp3 === void 0 ? {} : _temp3;
  2519. let url = new URL(request.url);
  2520. let method = request.method.toLowerCase();
  2521. let location = createLocation("", createPath(url), null, "default");
  2522. let matches = matchRoutes(dataRoutes, location, basename); // SSR supports HEAD requests while SPA doesn't
  2523. if (!isValidMethod(method) && method !== "head" && method !== "options") {
  2524. throw getInternalRouterError(405, {
  2525. method
  2526. });
  2527. } else if (!matches) {
  2528. throw getInternalRouterError(404, {
  2529. pathname: location.pathname
  2530. });
  2531. }
  2532. let match = routeId ? matches.find(m => m.route.id === routeId) : getTargetMatch(matches, location);
  2533. if (routeId && !match) {
  2534. throw getInternalRouterError(403, {
  2535. pathname: location.pathname,
  2536. routeId
  2537. });
  2538. } else if (!match) {
  2539. // This should never hit I don't think?
  2540. throw getInternalRouterError(404, {
  2541. pathname: location.pathname
  2542. });
  2543. }
  2544. let result = await queryImpl(request, location, matches, requestContext, match);
  2545. if (isResponse(result)) {
  2546. return result;
  2547. }
  2548. let error = result.errors ? Object.values(result.errors)[0] : undefined;
  2549. if (error !== undefined) {
  2550. // If we got back result.errors, that means the loader/action threw
  2551. // _something_ that wasn't a Response, but it's not guaranteed/required
  2552. // to be an `instanceof Error` either, so we have to use throw here to
  2553. // preserve the "error" state outside of queryImpl.
  2554. throw error;
  2555. } // Pick off the right state value to return
  2556. if (result.actionData) {
  2557. return Object.values(result.actionData)[0];
  2558. }
  2559. if (result.loaderData) {
  2560. var _result$activeDeferre;
  2561. let data = Object.values(result.loaderData)[0];
  2562. if ((_result$activeDeferre = result.activeDeferreds) != null && _result$activeDeferre[match.route.id]) {
  2563. data[UNSAFE_DEFERRED_SYMBOL] = result.activeDeferreds[match.route.id];
  2564. }
  2565. return data;
  2566. }
  2567. return undefined;
  2568. }
  2569. async function queryImpl(request, location, matches, requestContext, routeMatch) {
  2570. invariant(request.signal, "query()/queryRoute() requests must contain an AbortController signal");
  2571. try {
  2572. if (isMutationMethod(request.method.toLowerCase())) {
  2573. let result = await submit(request, matches, routeMatch || getTargetMatch(matches, location), requestContext, routeMatch != null);
  2574. return result;
  2575. }
  2576. let result = await loadRouteData(request, matches, requestContext, routeMatch);
  2577. return isResponse(result) ? result : _extends({}, result, {
  2578. actionData: null,
  2579. actionHeaders: {}
  2580. });
  2581. } catch (e) {
  2582. // If the user threw/returned a Response in callLoaderOrAction, we throw
  2583. // it to bail out and then return or throw here based on whether the user
  2584. // returned or threw
  2585. if (isQueryRouteResponse(e)) {
  2586. if (e.type === ResultType.error && !isRedirectResponse(e.response)) {
  2587. throw e.response;
  2588. }
  2589. return e.response;
  2590. } // Redirects are always returned since they don't propagate to catch
  2591. // boundaries
  2592. if (isRedirectResponse(e)) {
  2593. return e;
  2594. }
  2595. throw e;
  2596. }
  2597. }
  2598. async function submit(request, matches, actionMatch, requestContext, isRouteRequest) {
  2599. let result;
  2600. if (!actionMatch.route.action) {
  2601. let error = getInternalRouterError(405, {
  2602. method: request.method,
  2603. pathname: new URL(request.url).pathname,
  2604. routeId: actionMatch.route.id
  2605. });
  2606. if (isRouteRequest) {
  2607. throw error;
  2608. }
  2609. result = {
  2610. type: ResultType.error,
  2611. error
  2612. };
  2613. } else {
  2614. result = await callLoaderOrAction("action", request, actionMatch, matches, basename, true, isRouteRequest, requestContext);
  2615. if (request.signal.aborted) {
  2616. let method = isRouteRequest ? "queryRoute" : "query";
  2617. throw new Error(method + "() call aborted");
  2618. }
  2619. }
  2620. if (isRedirectResult(result)) {
  2621. // Uhhhh - this should never happen, we should always throw these from
  2622. // callLoaderOrAction, but the type narrowing here keeps TS happy and we
  2623. // can get back on the "throw all redirect responses" train here should
  2624. // this ever happen :/
  2625. throw new Response(null, {
  2626. status: result.status,
  2627. headers: {
  2628. Location: result.location
  2629. }
  2630. });
  2631. }
  2632. if (isDeferredResult(result)) {
  2633. let error = getInternalRouterError(400, {
  2634. type: "defer-action"
  2635. });
  2636. if (isRouteRequest) {
  2637. throw error;
  2638. }
  2639. result = {
  2640. type: ResultType.error,
  2641. error
  2642. };
  2643. }
  2644. if (isRouteRequest) {
  2645. // Note: This should only be non-Response values if we get here, since
  2646. // isRouteRequest should throw any Response received in callLoaderOrAction
  2647. if (isErrorResult(result)) {
  2648. throw result.error;
  2649. }
  2650. return {
  2651. matches: [actionMatch],
  2652. loaderData: {},
  2653. actionData: {
  2654. [actionMatch.route.id]: result.data
  2655. },
  2656. errors: null,
  2657. // Note: statusCode + headers are unused here since queryRoute will
  2658. // return the raw Response or value
  2659. statusCode: 200,
  2660. loaderHeaders: {},
  2661. actionHeaders: {},
  2662. activeDeferreds: null
  2663. };
  2664. }
  2665. if (isErrorResult(result)) {
  2666. // Store off the pending error - we use it to determine which loaders
  2667. // to call and will commit it when we complete the navigation
  2668. let boundaryMatch = findNearestBoundary(matches, actionMatch.route.id);
  2669. let context = await loadRouteData(request, matches, requestContext, undefined, {
  2670. [boundaryMatch.route.id]: result.error
  2671. }); // action status codes take precedence over loader status codes
  2672. return _extends({}, context, {
  2673. statusCode: isRouteErrorResponse(result.error) ? result.error.status : 500,
  2674. actionData: null,
  2675. actionHeaders: _extends({}, result.headers ? {
  2676. [actionMatch.route.id]: result.headers
  2677. } : {})
  2678. });
  2679. } // Create a GET request for the loaders
  2680. let loaderRequest = new Request(request.url, {
  2681. headers: request.headers,
  2682. redirect: request.redirect,
  2683. signal: request.signal
  2684. });
  2685. let context = await loadRouteData(loaderRequest, matches, requestContext);
  2686. return _extends({}, context, result.statusCode ? {
  2687. statusCode: result.statusCode
  2688. } : {}, {
  2689. actionData: {
  2690. [actionMatch.route.id]: result.data
  2691. },
  2692. actionHeaders: _extends({}, result.headers ? {
  2693. [actionMatch.route.id]: result.headers
  2694. } : {})
  2695. });
  2696. }
  2697. async function loadRouteData(request, matches, requestContext, routeMatch, pendingActionError) {
  2698. let isRouteRequest = routeMatch != null; // Short circuit if we have no loaders to run (queryRoute())
  2699. if (isRouteRequest && !(routeMatch != null && routeMatch.route.loader)) {
  2700. throw getInternalRouterError(400, {
  2701. method: request.method,
  2702. pathname: new URL(request.url).pathname,
  2703. routeId: routeMatch == null ? void 0 : routeMatch.route.id
  2704. });
  2705. }
  2706. let requestMatches = routeMatch ? [routeMatch] : getLoaderMatchesUntilBoundary(matches, Object.keys(pendingActionError || {})[0]);
  2707. let matchesToLoad = requestMatches.filter(m => m.route.loader); // Short circuit if we have no loaders to run (query())
  2708. if (matchesToLoad.length === 0) {
  2709. return {
  2710. matches,
  2711. // Add a null for all matched routes for proper revalidation on the client
  2712. loaderData: matches.reduce((acc, m) => Object.assign(acc, {
  2713. [m.route.id]: null
  2714. }), {}),
  2715. errors: pendingActionError || null,
  2716. statusCode: 200,
  2717. loaderHeaders: {},
  2718. activeDeferreds: null
  2719. };
  2720. }
  2721. let results = await Promise.all([...matchesToLoad.map(match => callLoaderOrAction("loader", request, match, matches, basename, true, isRouteRequest, requestContext))]);
  2722. if (request.signal.aborted) {
  2723. let method = isRouteRequest ? "queryRoute" : "query";
  2724. throw new Error(method + "() call aborted");
  2725. } // Process and commit output from loaders
  2726. let activeDeferreds = new Map();
  2727. let context = processRouteLoaderData(matches, matchesToLoad, results, pendingActionError, activeDeferreds); // Add a null for any non-loader matches for proper revalidation on the client
  2728. let executedLoaders = new Set(matchesToLoad.map(match => match.route.id));
  2729. matches.forEach(match => {
  2730. if (!executedLoaders.has(match.route.id)) {
  2731. context.loaderData[match.route.id] = null;
  2732. }
  2733. });
  2734. return _extends({}, context, {
  2735. matches,
  2736. activeDeferreds: activeDeferreds.size > 0 ? Object.fromEntries(activeDeferreds.entries()) : null
  2737. });
  2738. }
  2739. return {
  2740. dataRoutes,
  2741. query,
  2742. queryRoute
  2743. };
  2744. } //#endregion
  2745. ////////////////////////////////////////////////////////////////////////////////
  2746. //#region Helpers
  2747. ////////////////////////////////////////////////////////////////////////////////
  2748. /**
  2749. * Given an existing StaticHandlerContext and an error thrown at render time,
  2750. * provide an updated StaticHandlerContext suitable for a second SSR render
  2751. */
  2752. function getStaticContextFromError(routes, context, error) {
  2753. let newContext = _extends({}, context, {
  2754. statusCode: 500,
  2755. errors: {
  2756. [context._deepestRenderedBoundaryId || routes[0].id]: error
  2757. }
  2758. });
  2759. return newContext;
  2760. }
  2761. function isSubmissionNavigation(opts) {
  2762. return opts != null && "formData" in opts;
  2763. } // Normalize navigation options by converting formMethod=GET formData objects to
  2764. // URLSearchParams so they behave identically to links with query params
  2765. function normalizeNavigateOptions(to, opts, isFetcher) {
  2766. if (isFetcher === void 0) {
  2767. isFetcher = false;
  2768. }
  2769. let path = typeof to === "string" ? to : createPath(to); // Return location verbatim on non-submission navigations
  2770. if (!opts || !isSubmissionNavigation(opts)) {
  2771. return {
  2772. path
  2773. };
  2774. }
  2775. if (opts.formMethod && !isValidMethod(opts.formMethod)) {
  2776. return {
  2777. path,
  2778. error: getInternalRouterError(405, {
  2779. method: opts.formMethod
  2780. })
  2781. };
  2782. } // Create a Submission on non-GET navigations
  2783. let submission;
  2784. if (opts.formData) {
  2785. submission = {
  2786. formMethod: opts.formMethod || "get",
  2787. formAction: stripHashFromPath(path),
  2788. formEncType: opts && opts.formEncType || "application/x-www-form-urlencoded",
  2789. formData: opts.formData
  2790. };
  2791. if (isMutationMethod(submission.formMethod)) {
  2792. return {
  2793. path,
  2794. submission
  2795. };
  2796. }
  2797. } // Flatten submission onto URLSearchParams for GET submissions
  2798. let parsedPath = parsePath(path);
  2799. let searchParams = convertFormDataToSearchParams(opts.formData); // Since fetcher GET submissions only run a single loader (as opposed to
  2800. // navigation GET submissions which run all loaders), we need to preserve
  2801. // any incoming ?index params
  2802. if (isFetcher && parsedPath.search && hasNakedIndexQuery(parsedPath.search)) {
  2803. searchParams.append("index", "");
  2804. }
  2805. parsedPath.search = "?" + searchParams;
  2806. return {
  2807. path: createPath(parsedPath),
  2808. submission
  2809. };
  2810. } // Filter out all routes below any caught error as they aren't going to
  2811. // render so we don't need to load them
  2812. function getLoaderMatchesUntilBoundary(matches, boundaryId) {
  2813. let boundaryMatches = matches;
  2814. if (boundaryId) {
  2815. let index = matches.findIndex(m => m.route.id === boundaryId);
  2816. if (index >= 0) {
  2817. boundaryMatches = matches.slice(0, index);
  2818. }
  2819. }
  2820. return boundaryMatches;
  2821. }
  2822. function getMatchesToLoad(history, state, matches, submission, location, isRevalidationRequired, cancelledDeferredRoutes, cancelledFetcherLoads, pendingActionData, pendingError, fetchLoadMatches) {
  2823. let actionResult = pendingError ? Object.values(pendingError)[0] : pendingActionData ? Object.values(pendingActionData)[0] : undefined;
  2824. let currentUrl = history.createURL(state.location);
  2825. let nextUrl = history.createURL(location);
  2826. let defaultShouldRevalidate = // Forced revalidation due to submission, useRevalidate, or X-Remix-Revalidate
  2827. isRevalidationRequired || // Clicked the same link, resubmitted a GET form
  2828. currentUrl.toString() === nextUrl.toString() || // Search params affect all loaders
  2829. currentUrl.search !== nextUrl.search; // Pick navigation matches that are net-new or qualify for revalidation
  2830. let boundaryId = pendingError ? Object.keys(pendingError)[0] : undefined;
  2831. let boundaryMatches = getLoaderMatchesUntilBoundary(matches, boundaryId);
  2832. let navigationMatches = boundaryMatches.filter((match, index) => {
  2833. if (match.route.loader == null) {
  2834. return false;
  2835. } // Always call the loader on new route instances and pending defer cancellations
  2836. if (isNewLoader(state.loaderData, state.matches[index], match) || cancelledDeferredRoutes.some(id => id === match.route.id)) {
  2837. return true;
  2838. } // This is the default implementation for when we revalidate. If the route
  2839. // provides it's own implementation, then we give them full control but
  2840. // provide this value so they can leverage it if needed after they check
  2841. // their own specific use cases
  2842. let currentRouteMatch = state.matches[index];
  2843. let nextRouteMatch = match;
  2844. return shouldRevalidateLoader(match, _extends({
  2845. currentUrl,
  2846. currentParams: currentRouteMatch.params,
  2847. nextUrl,
  2848. nextParams: nextRouteMatch.params
  2849. }, submission, {
  2850. actionResult,
  2851. defaultShouldRevalidate: defaultShouldRevalidate || isNewRouteInstance(currentRouteMatch, nextRouteMatch)
  2852. }));
  2853. }); // Pick fetcher.loads that need to be revalidated
  2854. let revalidatingFetchers = [];
  2855. fetchLoadMatches && fetchLoadMatches.forEach((f, key) => {
  2856. if (!matches.some(m => m.route.id === f.routeId)) {
  2857. // This fetcher is not going to be present in the subsequent render so
  2858. // there's no need to revalidate it
  2859. return;
  2860. } else if (cancelledFetcherLoads.includes(key)) {
  2861. // This fetcher was cancelled from a prior action submission - force reload
  2862. revalidatingFetchers.push(_extends({
  2863. key
  2864. }, f));
  2865. } else {
  2866. // Revalidating fetchers are decoupled from the route matches since they
  2867. // hit a static href, so they _always_ check shouldRevalidate and the
  2868. // default is strictly if a revalidation is explicitly required (action
  2869. // submissions, useRevalidator, X-Remix-Revalidate).
  2870. let shouldRevalidate = shouldRevalidateLoader(f.match, _extends({
  2871. currentUrl,
  2872. currentParams: state.matches[state.matches.length - 1].params,
  2873. nextUrl,
  2874. nextParams: matches[matches.length - 1].params
  2875. }, submission, {
  2876. actionResult,
  2877. defaultShouldRevalidate
  2878. }));
  2879. if (shouldRevalidate) {
  2880. revalidatingFetchers.push(_extends({
  2881. key
  2882. }, f));
  2883. }
  2884. }
  2885. });
  2886. return [navigationMatches, revalidatingFetchers];
  2887. }
  2888. function isNewLoader(currentLoaderData, currentMatch, match) {
  2889. let isNew = // [a] -> [a, b]
  2890. !currentMatch || // [a, b] -> [a, c]
  2891. match.route.id !== currentMatch.route.id; // Handle the case that we don't have data for a re-used route, potentially
  2892. // from a prior error or from a cancelled pending deferred
  2893. let isMissingData = currentLoaderData[match.route.id] === undefined; // Always load if this is a net-new route or we don't yet have data
  2894. return isNew || isMissingData;
  2895. }
  2896. function isNewRouteInstance(currentMatch, match) {
  2897. let currentPath = currentMatch.route.path;
  2898. return (// param change for this match, /users/123 -> /users/456
  2899. currentMatch.pathname !== match.pathname || // splat param changed, which is not present in match.path
  2900. // e.g. /files/images/avatar.jpg -> files/finances.xls
  2901. currentPath != null && currentPath.endsWith("*") && currentMatch.params["*"] !== match.params["*"]
  2902. );
  2903. }
  2904. function shouldRevalidateLoader(loaderMatch, arg) {
  2905. if (loaderMatch.route.shouldRevalidate) {
  2906. let routeChoice = loaderMatch.route.shouldRevalidate(arg);
  2907. if (typeof routeChoice === "boolean") {
  2908. return routeChoice;
  2909. }
  2910. }
  2911. return arg.defaultShouldRevalidate;
  2912. }
  2913. async function callLoaderOrAction(type, request, match, matches, basename, isStaticRequest, isRouteRequest, requestContext) {
  2914. if (basename === void 0) {
  2915. basename = "/";
  2916. }
  2917. if (isStaticRequest === void 0) {
  2918. isStaticRequest = false;
  2919. }
  2920. if (isRouteRequest === void 0) {
  2921. isRouteRequest = false;
  2922. }
  2923. let resultType;
  2924. let result; // Setup a promise we can race against so that abort signals short circuit
  2925. let reject;
  2926. let abortPromise = new Promise((_, r) => reject = r);
  2927. let onReject = () => reject();
  2928. request.signal.addEventListener("abort", onReject);
  2929. try {
  2930. let handler = match.route[type];
  2931. invariant(handler, "Could not find the " + type + " to run on the \"" + match.route.id + "\" route");
  2932. result = await Promise.race([handler({
  2933. request,
  2934. params: match.params,
  2935. context: requestContext
  2936. }), abortPromise]);
  2937. invariant(result !== undefined, "You defined " + (type === "action" ? "an action" : "a loader") + " for route " + ("\"" + match.route.id + "\" but didn't return anything from your `" + type + "` ") + "function. Please return a value or `null`.");
  2938. } catch (e) {
  2939. resultType = ResultType.error;
  2940. result = e;
  2941. } finally {
  2942. request.signal.removeEventListener("abort", onReject);
  2943. }
  2944. if (isResponse(result)) {
  2945. let status = result.status; // Process redirects
  2946. if (redirectStatusCodes.has(status)) {
  2947. let location = result.headers.get("Location");
  2948. invariant(location, "Redirects returned/thrown from loaders/actions must have a Location header"); // Support relative routing in internal redirects
  2949. if (!ABSOLUTE_URL_REGEX.test(location)) {
  2950. let activeMatches = matches.slice(0, matches.indexOf(match) + 1);
  2951. let routePathnames = getPathContributingMatches(activeMatches).map(match => match.pathnameBase);
  2952. let resolvedLocation = resolveTo(location, routePathnames, new URL(request.url).pathname);
  2953. invariant(createPath(resolvedLocation), "Unable to resolve redirect location: " + location); // Prepend the basename to the redirect location if we have one
  2954. if (basename) {
  2955. let path = resolvedLocation.pathname;
  2956. resolvedLocation.pathname = path === "/" ? basename : joinPaths([basename, path]);
  2957. }
  2958. location = createPath(resolvedLocation);
  2959. } else if (!isStaticRequest) {
  2960. // Strip off the protocol+origin for same-origin absolute redirects.
  2961. // If this is a static reques, we can let it go back to the browser
  2962. // as-is
  2963. let currentUrl = new URL(request.url);
  2964. let url = location.startsWith("//") ? new URL(currentUrl.protocol + location) : new URL(location);
  2965. if (url.origin === currentUrl.origin) {
  2966. location = url.pathname + url.search + url.hash;
  2967. }
  2968. } // Don't process redirects in the router during static requests requests.
  2969. // Instead, throw the Response and let the server handle it with an HTTP
  2970. // redirect. We also update the Location header in place in this flow so
  2971. // basename and relative routing is taken into account
  2972. if (isStaticRequest) {
  2973. result.headers.set("Location", location);
  2974. throw result;
  2975. }
  2976. return {
  2977. type: ResultType.redirect,
  2978. status,
  2979. location,
  2980. revalidate: result.headers.get("X-Remix-Revalidate") !== null
  2981. };
  2982. } // For SSR single-route requests, we want to hand Responses back directly
  2983. // without unwrapping. We do this with the QueryRouteResponse wrapper
  2984. // interface so we can know whether it was returned or thrown
  2985. if (isRouteRequest) {
  2986. // eslint-disable-next-line no-throw-literal
  2987. throw {
  2988. type: resultType || ResultType.data,
  2989. response: result
  2990. };
  2991. }
  2992. let data;
  2993. let contentType = result.headers.get("Content-Type"); // Check between word boundaries instead of startsWith() due to the last
  2994. // paragraph of https://httpwg.org/specs/rfc9110.html#field.content-type
  2995. if (contentType && /\bapplication\/json\b/.test(contentType)) {
  2996. data = await result.json();
  2997. } else {
  2998. data = await result.text();
  2999. }
  3000. if (resultType === ResultType.error) {
  3001. return {
  3002. type: resultType,
  3003. error: new ErrorResponse(status, result.statusText, data),
  3004. headers: result.headers
  3005. };
  3006. }
  3007. return {
  3008. type: ResultType.data,
  3009. data,
  3010. statusCode: result.status,
  3011. headers: result.headers
  3012. };
  3013. }
  3014. if (resultType === ResultType.error) {
  3015. return {
  3016. type: resultType,
  3017. error: result
  3018. };
  3019. }
  3020. if (result instanceof DeferredData) {
  3021. return {
  3022. type: ResultType.deferred,
  3023. deferredData: result
  3024. };
  3025. }
  3026. return {
  3027. type: ResultType.data,
  3028. data: result
  3029. };
  3030. } // Utility method for creating the Request instances for loaders/actions during
  3031. // client-side navigations and fetches. During SSR we will always have a
  3032. // Request instance from the static handler (query/queryRoute)
  3033. function createClientSideRequest(history, location, signal, submission) {
  3034. let url = history.createURL(stripHashFromPath(location)).toString();
  3035. let init = {
  3036. signal
  3037. };
  3038. if (submission && isMutationMethod(submission.formMethod)) {
  3039. let {
  3040. formMethod,
  3041. formEncType,
  3042. formData
  3043. } = submission;
  3044. init.method = formMethod.toUpperCase();
  3045. init.body = formEncType === "application/x-www-form-urlencoded" ? convertFormDataToSearchParams(formData) : formData;
  3046. } // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)
  3047. return new Request(url, init);
  3048. }
  3049. function convertFormDataToSearchParams(formData) {
  3050. let searchParams = new URLSearchParams();
  3051. for (let [key, value] of formData.entries()) {
  3052. // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#converting-an-entry-list-to-a-list-of-name-value-pairs
  3053. searchParams.append(key, value instanceof File ? value.name : value);
  3054. }
  3055. return searchParams;
  3056. }
  3057. function processRouteLoaderData(matches, matchesToLoad, results, pendingError, activeDeferreds) {
  3058. // Fill in loaderData/errors from our loaders
  3059. let loaderData = {};
  3060. let errors = null;
  3061. let statusCode;
  3062. let foundError = false;
  3063. let loaderHeaders = {}; // Process loader results into state.loaderData/state.errors
  3064. results.forEach((result, index) => {
  3065. let id = matchesToLoad[index].route.id;
  3066. invariant(!isRedirectResult(result), "Cannot handle redirect results in processLoaderData");
  3067. if (isErrorResult(result)) {
  3068. // Look upwards from the matched route for the closest ancestor
  3069. // error boundary, defaulting to the root match
  3070. let boundaryMatch = findNearestBoundary(matches, id);
  3071. let error = result.error; // If we have a pending action error, we report it at the highest-route
  3072. // that throws a loader error, and then clear it out to indicate that
  3073. // it was consumed
  3074. if (pendingError) {
  3075. error = Object.values(pendingError)[0];
  3076. pendingError = undefined;
  3077. }
  3078. errors = errors || {}; // Prefer higher error values if lower errors bubble to the same boundary
  3079. if (errors[boundaryMatch.route.id] == null) {
  3080. errors[boundaryMatch.route.id] = error;
  3081. } // Clear our any prior loaderData for the throwing route
  3082. loaderData[id] = undefined; // Once we find our first (highest) error, we set the status code and
  3083. // prevent deeper status codes from overriding
  3084. if (!foundError) {
  3085. foundError = true;
  3086. statusCode = isRouteErrorResponse(result.error) ? result.error.status : 500;
  3087. }
  3088. if (result.headers) {
  3089. loaderHeaders[id] = result.headers;
  3090. }
  3091. } else {
  3092. if (isDeferredResult(result)) {
  3093. activeDeferreds.set(id, result.deferredData);
  3094. loaderData[id] = result.deferredData.data;
  3095. } else {
  3096. loaderData[id] = result.data;
  3097. } // Error status codes always override success status codes, but if all
  3098. // loaders are successful we take the deepest status code.
  3099. if (result.statusCode != null && result.statusCode !== 200 && !foundError) {
  3100. statusCode = result.statusCode;
  3101. }
  3102. if (result.headers) {
  3103. loaderHeaders[id] = result.headers;
  3104. }
  3105. }
  3106. }); // If we didn't consume the pending action error (i.e., all loaders
  3107. // resolved), then consume it here. Also clear out any loaderData for the
  3108. // throwing route
  3109. if (pendingError) {
  3110. errors = pendingError;
  3111. loaderData[Object.keys(pendingError)[0]] = undefined;
  3112. }
  3113. return {
  3114. loaderData,
  3115. errors,
  3116. statusCode: statusCode || 200,
  3117. loaderHeaders
  3118. };
  3119. }
  3120. function processLoaderData(state, matches, matchesToLoad, results, pendingError, revalidatingFetchers, fetcherResults, activeDeferreds) {
  3121. let {
  3122. loaderData,
  3123. errors
  3124. } = processRouteLoaderData(matches, matchesToLoad, results, pendingError, activeDeferreds); // Process results from our revalidating fetchers
  3125. for (let index = 0; index < revalidatingFetchers.length; index++) {
  3126. let {
  3127. key,
  3128. match
  3129. } = revalidatingFetchers[index];
  3130. invariant(fetcherResults !== undefined && fetcherResults[index] !== undefined, "Did not find corresponding fetcher result");
  3131. let result = fetcherResults[index]; // Process fetcher non-redirect errors
  3132. if (isErrorResult(result)) {
  3133. let boundaryMatch = findNearestBoundary(state.matches, match.route.id);
  3134. if (!(errors && errors[boundaryMatch.route.id])) {
  3135. errors = _extends({}, errors, {
  3136. [boundaryMatch.route.id]: result.error
  3137. });
  3138. }
  3139. state.fetchers.delete(key);
  3140. } else if (isRedirectResult(result)) {
  3141. // Should never get here, redirects should get processed above, but we
  3142. // keep this to type narrow to a success result in the else
  3143. invariant(false, "Unhandled fetcher revalidation redirect");
  3144. } else if (isDeferredResult(result)) {
  3145. // Should never get here, deferred data should be awaited for fetchers
  3146. // in resolveDeferredResults
  3147. invariant(false, "Unhandled fetcher deferred data");
  3148. } else {
  3149. let doneFetcher = {
  3150. state: "idle",
  3151. data: result.data,
  3152. formMethod: undefined,
  3153. formAction: undefined,
  3154. formEncType: undefined,
  3155. formData: undefined,
  3156. " _hasFetcherDoneAnything ": true
  3157. };
  3158. state.fetchers.set(key, doneFetcher);
  3159. }
  3160. }
  3161. return {
  3162. loaderData,
  3163. errors
  3164. };
  3165. }
  3166. function mergeLoaderData(loaderData, newLoaderData, matches, errors) {
  3167. let mergedLoaderData = _extends({}, newLoaderData);
  3168. for (let match of matches) {
  3169. let id = match.route.id;
  3170. if (newLoaderData.hasOwnProperty(id)) {
  3171. if (newLoaderData[id] !== undefined) {
  3172. mergedLoaderData[id] = newLoaderData[id];
  3173. }
  3174. } else if (loaderData[id] !== undefined) {
  3175. mergedLoaderData[id] = loaderData[id];
  3176. }
  3177. if (errors && errors.hasOwnProperty(id)) {
  3178. // Don't keep any loader data below the boundary
  3179. break;
  3180. }
  3181. }
  3182. return mergedLoaderData;
  3183. } // Find the nearest error boundary, looking upwards from the leaf route (or the
  3184. // route specified by routeId) for the closest ancestor error boundary,
  3185. // defaulting to the root match
  3186. function findNearestBoundary(matches, routeId) {
  3187. let eligibleMatches = routeId ? matches.slice(0, matches.findIndex(m => m.route.id === routeId) + 1) : [...matches];
  3188. return eligibleMatches.reverse().find(m => m.route.hasErrorBoundary === true) || matches[0];
  3189. }
  3190. function getShortCircuitMatches(routes) {
  3191. // Prefer a root layout route if present, otherwise shim in a route object
  3192. let route = routes.find(r => r.index || !r.path || r.path === "/") || {
  3193. id: "__shim-error-route__"
  3194. };
  3195. return {
  3196. matches: [{
  3197. params: {},
  3198. pathname: "",
  3199. pathnameBase: "",
  3200. route
  3201. }],
  3202. route
  3203. };
  3204. }
  3205. function getInternalRouterError(status, _temp4) {
  3206. let {
  3207. pathname,
  3208. routeId,
  3209. method,
  3210. type
  3211. } = _temp4 === void 0 ? {} : _temp4;
  3212. let statusText = "Unknown Server Error";
  3213. let errorMessage = "Unknown @remix-run/router error";
  3214. if (status === 400) {
  3215. statusText = "Bad Request";
  3216. if (method && pathname && routeId) {
  3217. 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.";
  3218. } else if (type === "defer-action") {
  3219. errorMessage = "defer() is not supported in actions";
  3220. }
  3221. } else if (status === 403) {
  3222. statusText = "Forbidden";
  3223. errorMessage = "Route \"" + routeId + "\" does not match URL \"" + pathname + "\"";
  3224. } else if (status === 404) {
  3225. statusText = "Not Found";
  3226. errorMessage = "No route matches URL \"" + pathname + "\"";
  3227. } else if (status === 405) {
  3228. statusText = "Method Not Allowed";
  3229. if (method && pathname && routeId) {
  3230. 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.";
  3231. } else if (method) {
  3232. errorMessage = "Invalid request method \"" + method.toUpperCase() + "\"";
  3233. }
  3234. }
  3235. return new ErrorResponse(status || 500, statusText, new Error(errorMessage), true);
  3236. } // Find any returned redirect errors, starting from the lowest match
  3237. function findRedirect(results) {
  3238. for (let i = results.length - 1; i >= 0; i--) {
  3239. let result = results[i];
  3240. if (isRedirectResult(result)) {
  3241. return result;
  3242. }
  3243. }
  3244. }
  3245. function stripHashFromPath(path) {
  3246. let parsedPath = typeof path === "string" ? parsePath(path) : path;
  3247. return createPath(_extends({}, parsedPath, {
  3248. hash: ""
  3249. }));
  3250. }
  3251. function isHashChangeOnly(a, b) {
  3252. return a.pathname === b.pathname && a.search === b.search && a.hash !== b.hash;
  3253. }
  3254. function isDeferredResult(result) {
  3255. return result.type === ResultType.deferred;
  3256. }
  3257. function isErrorResult(result) {
  3258. return result.type === ResultType.error;
  3259. }
  3260. function isRedirectResult(result) {
  3261. return (result && result.type) === ResultType.redirect;
  3262. }
  3263. function isResponse(value) {
  3264. return value != null && typeof value.status === "number" && typeof value.statusText === "string" && typeof value.headers === "object" && typeof value.body !== "undefined";
  3265. }
  3266. function isRedirectResponse(result) {
  3267. if (!isResponse(result)) {
  3268. return false;
  3269. }
  3270. let status = result.status;
  3271. let location = result.headers.get("Location");
  3272. return status >= 300 && status <= 399 && location != null;
  3273. }
  3274. function isQueryRouteResponse(obj) {
  3275. return obj && isResponse(obj.response) && (obj.type === ResultType.data || ResultType.error);
  3276. }
  3277. function isValidMethod(method) {
  3278. return validRequestMethods.has(method);
  3279. }
  3280. function isMutationMethod(method) {
  3281. return validMutationMethods.has(method);
  3282. }
  3283. async function resolveDeferredResults(currentMatches, matchesToLoad, results, signal, isFetcher, currentLoaderData) {
  3284. for (let index = 0; index < results.length; index++) {
  3285. let result = results[index];
  3286. let match = matchesToLoad[index];
  3287. let currentMatch = currentMatches.find(m => m.route.id === match.route.id);
  3288. let isRevalidatingLoader = currentMatch != null && !isNewRouteInstance(currentMatch, match) && (currentLoaderData && currentLoaderData[match.route.id]) !== undefined;
  3289. if (isDeferredResult(result) && (isFetcher || isRevalidatingLoader)) {
  3290. // Note: we do not have to touch activeDeferreds here since we race them
  3291. // against the signal in resolveDeferredData and they'll get aborted
  3292. // there if needed
  3293. await resolveDeferredData(result, signal, isFetcher).then(result => {
  3294. if (result) {
  3295. results[index] = result || results[index];
  3296. }
  3297. });
  3298. }
  3299. }
  3300. }
  3301. async function resolveDeferredData(result, signal, unwrap) {
  3302. if (unwrap === void 0) {
  3303. unwrap = false;
  3304. }
  3305. let aborted = await result.deferredData.resolveData(signal);
  3306. if (aborted) {
  3307. return;
  3308. }
  3309. if (unwrap) {
  3310. try {
  3311. return {
  3312. type: ResultType.data,
  3313. data: result.deferredData.unwrappedData
  3314. };
  3315. } catch (e) {
  3316. // Handle any TrackedPromise._error values encountered while unwrapping
  3317. return {
  3318. type: ResultType.error,
  3319. error: e
  3320. };
  3321. }
  3322. }
  3323. return {
  3324. type: ResultType.data,
  3325. data: result.deferredData.data
  3326. };
  3327. }
  3328. function hasNakedIndexQuery(search) {
  3329. return new URLSearchParams(search).getAll("index").some(v => v === "");
  3330. } // Note: This should match the format exported by useMatches, so if you change
  3331. // this please also change that :) Eventually we'll DRY this up
  3332. function createUseMatchesMatch(match, loaderData) {
  3333. let {
  3334. route,
  3335. pathname,
  3336. params
  3337. } = match;
  3338. return {
  3339. id: route.id,
  3340. pathname,
  3341. params,
  3342. data: loaderData[route.id],
  3343. handle: route.handle
  3344. };
  3345. }
  3346. function getTargetMatch(matches, location) {
  3347. let search = typeof location === "string" ? parsePath(location).search : location.search;
  3348. if (matches[matches.length - 1].route.index && hasNakedIndexQuery(search || "")) {
  3349. // Return the leaf index route when index is present
  3350. return matches[matches.length - 1];
  3351. } // Otherwise grab the deepest "path contributing" match (ignoring index and
  3352. // pathless layout routes)
  3353. let pathMatches = getPathContributingMatches(matches);
  3354. return pathMatches[pathMatches.length - 1];
  3355. } //#endregion
  3356. exports.AbortedDeferredError = AbortedDeferredError;
  3357. exports.ErrorResponse = ErrorResponse;
  3358. exports.IDLE_BLOCKER = IDLE_BLOCKER;
  3359. exports.IDLE_FETCHER = IDLE_FETCHER;
  3360. exports.IDLE_NAVIGATION = IDLE_NAVIGATION;
  3361. exports.UNSAFE_DEFERRED_SYMBOL = UNSAFE_DEFERRED_SYMBOL;
  3362. exports.UNSAFE_DeferredData = DeferredData;
  3363. exports.UNSAFE_convertRoutesToDataRoutes = convertRoutesToDataRoutes;
  3364. exports.UNSAFE_getPathContributingMatches = getPathContributingMatches;
  3365. exports.createBrowserHistory = createBrowserHistory;
  3366. exports.createHashHistory = createHashHistory;
  3367. exports.createMemoryHistory = createMemoryHistory;
  3368. exports.createPath = createPath;
  3369. exports.createRouter = createRouter;
  3370. exports.createStaticHandler = createStaticHandler;
  3371. exports.defer = defer;
  3372. exports.generatePath = generatePath;
  3373. exports.getStaticContextFromError = getStaticContextFromError;
  3374. exports.getToPathname = getToPathname;
  3375. exports.invariant = invariant;
  3376. exports.isRouteErrorResponse = isRouteErrorResponse;
  3377. exports.joinPaths = joinPaths;
  3378. exports.json = json;
  3379. exports.matchPath = matchPath;
  3380. exports.matchRoutes = matchRoutes;
  3381. exports.normalizePathname = normalizePathname;
  3382. exports.parsePath = parsePath;
  3383. exports.redirect = redirect;
  3384. exports.resolvePath = resolvePath;
  3385. exports.resolveTo = resolveTo;
  3386. exports.stripBasename = stripBasename;
  3387. exports.warning = warning;
  3388. Object.defineProperty(exports, '__esModule', { value: true });
  3389. }));
  3390. //# sourceMappingURL=router.umd.js.map